Skip to content

Commit 635ec36

Browse files
committed
examples: honor allowed credential types when prompting user
Credential callback are being passed a bitset that indicates which credential types are allowed in the current context. In our examples code, we completely ignore that field and always return username/password credentials, which doesn't necessarily make sense e.g. when only SSH keys are allowed. Refactor the code and only return username/password credentials in the case where `USERPASS_PLAINTEXT` credentials are allowed. Otherwise, return a positive error code to indicate that no credentials could be acquired.
1 parent b106620 commit 635ec36

File tree

1 file changed

+20
-16
lines changed

1 file changed

+20
-16
lines changed

examples/common.c

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -330,38 +330,42 @@ static int readline(char **out)
330330
return error;
331331
}
332332

333+
static int ask(char **out, const char *prompt)
334+
{
335+
printf("%s ", prompt);
336+
fflush(stdout);
337+
338+
if (!readline(out)) {
339+
fprintf(stderr, "Could not read response: %s", strerror(errno));
340+
return -1;
341+
}
342+
343+
return 0;
344+
}
345+
333346
int cred_acquire_cb(git_cred **out,
334347
const char *url,
335348
const char *username_from_url,
336349
unsigned int allowed_types,
337350
void *payload)
338351
{
339352
char *username = NULL, *password = NULL;
340-
int error;
353+
int error = 1;
341354

342355
UNUSED(url);
343356
UNUSED(username_from_url);
344-
UNUSED(allowed_types);
345357
UNUSED(payload);
346358

347-
printf("Username: ");
348-
if (readline(&username) < 0) {
349-
fprintf(stderr, "Unable to read username: %s", strerror(errno));
350-
return -1;
351-
}
359+
if (allowed_types & GIT_CREDTYPE_USERPASS_PLAINTEXT) {
360+
if ((error = ask(&username, "Username:")) < 0 ||
361+
(error = ask(&password, "Password:")) < 0)
362+
goto out;
352363

353-
/* Yup. Right there on your terminal. Careful where you copy/paste output. */
354-
printf("Password: ");
355-
if (readline(&password) < 0) {
356-
fprintf(stderr, "Unable to read password: %s", strerror(errno));
357-
free(username);
358-
return -1;
364+
error = git_cred_userpass_plaintext_new(out, username, password);
359365
}
360366

361-
error = git_cred_userpass_plaintext_new(out, username, password);
362-
367+
out:
363368
free(username);
364369
free(password);
365-
366370
return error;
367371
}

0 commit comments

Comments
 (0)