use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.
the class LdapLoginServlet method doPost.
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
req.setCharacterEncoding(UTF_8.name());
String username = Strings.nullToEmpty(req.getParameter("username")).trim();
String password = Strings.nullToEmpty(req.getParameter("password"));
String remember = Strings.nullToEmpty(req.getParameter("rememberme"));
if (username.isEmpty() || password.isEmpty()) {
sendForm(req, res, "Invalid username or password.");
return;
}
AuthRequest areq = authRequestFactory.createForUser(username);
areq.setPassword(password);
AuthResult ares;
try {
ares = accountManager.authenticate(areq);
} catch (AccountUserNameException e) {
sendForm(req, res, e.getMessage());
return;
} catch (AuthenticationUnavailableException e) {
sendForm(req, res, "Authentication unavailable at this time.");
return;
} catch (AuthenticationFailedException e) {
// This exception is thrown if the user provided wrong credentials, we don't need to log a
// stacktrace for it.
logger.atWarning().log("'%s' failed to sign in: %s", username, e.getMessage());
sendForm(req, res, "Invalid username or password.");
return;
} catch (AccountException e) {
logger.atWarning().withCause(e).log("'%s' failed to sign in", username);
sendForm(req, res, "Authentication failed.");
return;
} catch (RuntimeException e) {
logger.atSevere().withCause(e).log("LDAP authentication failed");
sendForm(req, res, "Authentication unavailable at this time.");
return;
}
StringBuilder dest = new StringBuilder();
dest.append(urlProvider.get(req));
dest.append(LoginUrlToken.getToken(req));
CacheHeaders.setNotCacheable(res);
webSession.get().login(ares, "1".equals(remember));
res.sendRedirect(dest.toString());
}
use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.
the class OAuthSessionOverOpenID method authenticateAndRedirect.
private void authenticateAndRedirect(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
com.google.gerrit.server.account.AuthRequest areq = authRequestFactory.create(externalIdKeyFactory.parse(user.getExternalId()));
AuthResult arsp;
try {
String claimedIdentifier = user.getClaimedIdentity();
Optional<Account.Id> actualId = accountManager.lookup(user.getExternalId());
Optional<Account.Id> claimedId = Optional.empty();
// That why we query it here, not to lose linking mode.
if (!Strings.isNullOrEmpty(claimedIdentifier)) {
claimedId = accountManager.lookup(claimedIdentifier);
if (!claimedId.isPresent()) {
logger.atFine().log("Claimed identity is unknown");
}
}
// and user account exists for this identity
if (claimedId.isPresent()) {
logger.atFine().log("Claimed identity is set and is known");
if (actualId.isPresent()) {
if (claimedId.get().equals(actualId.get())) {
// Both link to the same account, that's what we expected.
logger.atFine().log("Both link to the same account. All is fine.");
} else {
// This is (for now) a fatal error. There are two records
// for what might be the same user. The admin would have to
// link the accounts manually.
logger.atFine().log("OAuth accounts disagree over user identity:\n" + " Claimed ID: %s is %s\n" + " Delgate ID: %s is %s", claimedId.get(), claimedIdentifier, actualId.get(), user.getExternalId());
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
} else {
// Claimed account already exists: link to it.
logger.atFine().log("Claimed account already exists: link to it.");
try {
accountManager.link(claimedId.get(), areq);
} catch (ConfigInvalidException e) {
logger.atSevere().log("Cannot link: %s to user identity:\n Claimed ID: %s is %s", user.getExternalId(), claimedId.get(), claimedIdentifier);
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
}
} else if (linkMode) {
// Use case 2: link mode activated from the UI
Account.Id accountId = identifiedUser.get().getAccountId();
try {
logger.atFine().log("Linking \"%s\" to \"%s\"", user.getExternalId(), accountId);
accountManager.link(accountId, areq);
} catch (ConfigInvalidException e) {
logger.atSevere().log("Cannot link: %s to user identity: %s", user.getExternalId(), accountId);
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
} finally {
linkMode = false;
}
}
areq.setUserName(user.getUserName());
areq.setEmailAddress(user.getEmailAddress());
areq.setDisplayName(user.getDisplayName());
arsp = accountManager.authenticate(areq);
} catch (AccountException e) {
logger.atSevere().withCause(e).log("Unable to authenticate user \"%s\"", user);
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
webSession.get().login(arsp, true);
StringBuilder rdr = new StringBuilder(urlProvider.get(req));
rdr.append(Url.decode(redirectToken));
rsp.sendRedirect(rdr.toString());
}
use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.
the class ProjectBasicAuthFilter method verify.
private boolean verify(HttpServletRequest req, Response rsp) throws IOException {
final String hdr = req.getHeader(AUTHORIZATION);
if (hdr == null || !hdr.startsWith(LIT_BASIC)) {
// session cookie instead of basic authentication.
return true;
}
final byte[] decoded = BaseEncoding.base64().decode(hdr.substring(LIT_BASIC.length()));
String usernamePassword = new String(decoded, encoding(req));
int splitPos = usernamePassword.indexOf(':');
if (splitPos < 1) {
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
String username = usernamePassword.substring(0, splitPos);
String password = usernamePassword.substring(splitPos + 1);
if (Strings.isNullOrEmpty(password)) {
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
if (authConfig.isUserNameToLowerCase()) {
username = username.toLowerCase(Locale.US);
}
Optional<AccountState> accountState = accountCache.getByUsername(username).filter(a -> a.account().isActive());
if (!accountState.isPresent()) {
logger.atWarning().log("Authentication failed for %s: account inactive or not provisioned in Gerrit", username);
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
AccountState who = accountState.get();
GitBasicAuthPolicy gitBasicAuthPolicy = authConfig.getGitBasicAuthPolicy();
if (gitBasicAuthPolicy == GitBasicAuthPolicy.HTTP || gitBasicAuthPolicy == GitBasicAuthPolicy.HTTP_LDAP) {
if (passwordVerifier.checkPassword(who.externalIds(), username, password)) {
logger.atFine().log("HTTP:%s %s username/password authentication succeeded", req.getMethod(), req.getRequestURI());
return succeedAuthentication(who, null);
}
}
if (gitBasicAuthPolicy == GitBasicAuthPolicy.HTTP) {
return failAuthentication(rsp, username, req);
}
AuthRequest whoAuth = authRequestFactory.createForUser(username);
whoAuth.setPassword(password);
try {
AuthResult whoAuthResult = accountManager.authenticate(whoAuth);
setUserIdentified(whoAuthResult.getAccountId(), whoAuthResult);
logger.atFine().log("HTTP:%s %s Realm authentication succeeded", req.getMethod(), req.getRequestURI());
return true;
} catch (NoSuchUserException e) {
if (passwordVerifier.checkPassword(who.externalIds(), username, password)) {
return succeedAuthentication(who, null);
}
logger.atWarning().withCause(e).log("%s", authenticationFailedMsg(username, req));
rsp.sendError(SC_UNAUTHORIZED);
return false;
} catch (AuthenticationFailedException e) {
// This exception is thrown if the user provided wrong credentials, we don't need to log a
// stacktrace for it.
logger.atWarning().log(authenticationFailedMsg(username, req) + ": %s", e.getMessage());
rsp.sendError(SC_UNAUTHORIZED);
return false;
} catch (AuthenticationUnavailableException e) {
logger.atSevere().withCause(e).log("could not reach authentication backend");
rsp.sendError(SC_SERVICE_UNAVAILABLE);
return false;
} catch (AccountException e) {
logger.atWarning().withCause(e).log("%s", authenticationFailedMsg(username, req));
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
}
use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.
the class AddMembers method createAccountByLdap.
private Optional<Account> createAccountByLdap(String user) throws IOException {
if (!ExternalId.isValidUsername(user)) {
return Optional.empty();
}
try {
AuthRequest req = authRequestFactory.createForUser(user);
req.setSkipAuthentication(true);
return accountCache.get(accountManager.authenticate(req).getAccountId()).map(AccountState::account);
} catch (AccountException e) {
return Optional.empty();
}
}
use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.
the class DeleteEmail method apply.
public Response<?> apply(IdentifiedUser user, String email) throws ResourceNotFoundException, ResourceConflictException, MethodNotAllowedException, IOException, ConfigInvalidException {
Account.Id accountId = user.getAccountId();
if (realm.accountBelongsToRealm(externalIds.byAccount(accountId)) && !realm.allowsEdit(AccountFieldName.REGISTER_NEW_EMAIL)) {
throw new MethodNotAllowedException("realm does not allow deleting emails");
}
Set<ExternalId> extIds = externalIds.byAccount(accountId).stream().filter(e -> email.equals(e.email())).collect(toSet());
if (extIds.isEmpty()) {
throw new ResourceNotFoundException(email);
}
if (realm.accountBelongsToRealm(extIds)) {
String errorMsg = String.format("Cannot remove e-mail '%s' which is directly associated with %s authentication", email, authType);
throw new ResourceConflictException(errorMsg);
}
try {
accountManager.unlink(user.getAccountId(), extIds.stream().map(ExternalId::key).collect(toSet()));
} catch (AccountException e) {
throw new ResourceConflictException(e.getMessage());
}
return Response.none();
}
Aggregations