use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.
the class HttpLoginServlet method doGet.
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
final String token = LoginUrlToken.getToken(req);
CacheHeaders.setNotCacheable(rsp);
final String user = authFilter.getRemoteUser(req);
if (user == null || "".equals(user)) {
logger.atSevere().log("Unable to authenticate user by %s request header." + " Check container or server configuration.", authFilter.getLoginHeader());
final Document doc = //
HtmlDomUtil.parseFile(HttpLoginServlet.class, "ConfigurationError.html");
replace(doc, "loginHeader", authFilter.getLoginHeader());
replace(doc, "ServerName", req.getServerName());
replace(doc, "ServerPort", ":" + req.getServerPort());
replace(doc, "ContextPath", req.getContextPath());
final byte[] bin = HtmlDomUtil.toUTF8(doc);
rsp.setStatus(HttpServletResponse.SC_FORBIDDEN);
rsp.setContentType("text/html");
rsp.setCharacterEncoding(UTF_8.name());
rsp.setContentLength(bin.length);
try (ServletOutputStream out = rsp.getOutputStream()) {
out.write(bin);
}
return;
}
final AuthRequest areq = authRequestFactory.createForUser(user);
areq.setDisplayName(authFilter.getRemoteDisplayname(req));
areq.setEmailAddress(authFilter.getRemoteEmail(req));
final AuthResult arsp;
try {
arsp = accountManager.authenticate(areq);
} catch (AccountException e) {
logger.atSevere().withCause(e).log("Unable to authenticate user \"%s\"", user);
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
String remoteExternalId = authFilter.getRemoteExternalIdToken(req);
if (remoteExternalId != null) {
try {
logger.atFine().log("Associating external identity \"%s\" to user \"%s\"", remoteExternalId, user);
updateRemoteExternalId(arsp, remoteExternalId);
} catch (AccountException | ConfigInvalidException e) {
logger.atSevere().withCause(e).log("Unable to associate external identity \"%s\" to user \"%s\"", remoteExternalId, user);
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
}
final StringBuilder rdr = new StringBuilder();
if (arsp.isNew() && authConfig.getRegisterPageUrl() != null) {
rdr.append(authConfig.getRegisterPageUrl());
} else {
rdr.append(urlProvider.get(req));
if (arsp.isNew() && !token.startsWith(PageLinks.REGISTER + "/")) {
rdr.append('#' + PageLinks.REGISTER);
}
rdr.append(token);
}
webSession.get().login(arsp, true);
rsp.sendRedirect(rdr.toString());
}
use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.
the class ProjectOAuthFilter method verify.
private boolean verify(HttpServletRequest req, Response rsp) throws IOException {
AuthInfo authInfo;
// first check if there is a BASIC authentication header
String hdr = req.getHeader(AUTHORIZATION);
if (hdr != null && hdr.startsWith(BASIC)) {
authInfo = extractAuthInfo(hdr, encoding(req));
if (authInfo == null) {
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
} else {
// if there is no BASIC authentication header, check if there is
// a cookie starting with the prefix "git-"
Cookie cookie = findGitCookie(req);
if (cookie != null) {
authInfo = extractAuthInfo(cookie);
if (authInfo == null) {
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
} else {
// an anonymous connection, or there might be a session cookie
return true;
}
}
// if there is authentication information but no secret => 401
if (Strings.isNullOrEmpty(authInfo.tokenOrSecret)) {
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
Optional<AccountState> who = accountCache.getByUsername(authInfo.username).filter(a -> a.account().isActive());
if (!who.isPresent()) {
logger.atWarning().log("%s: account inactive or not provisioned in Gerrit", authenticationFailedMsg(authInfo.username, req));
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
Account account = who.get().account();
AuthRequest authRequest = authRequestFactory.createForExternalUser(authInfo.username);
authRequest.setEmailAddress(account.preferredEmail());
authRequest.setDisplayName(account.fullName());
authRequest.setPassword(authInfo.tokenOrSecret);
authRequest.setAuthPlugin(authInfo.pluginName);
authRequest.setAuthProvider(authInfo.exportName);
try {
AuthResult authResult = accountManager.authenticate(authRequest);
WebSession ws = session.get();
ws.setUserAccountId(authResult.getAccountId());
ws.setAccessPathOk(AccessPath.GIT, true);
ws.setAccessPathOk(AccessPath.REST_API, true);
return true;
} catch (AccountException e) {
logger.atWarning().withCause(e).log("%s", authenticationFailedMsg(authInfo.username, req));
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
}
use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.
the class ConfirmEmail method apply.
@Override
public Response<?> apply(ConfigResource rsrc, Input input) throws AuthException, UnprocessableEntityException, IOException, ConfigInvalidException {
CurrentUser user = self.get();
if (!user.isIdentifiedUser()) {
throw new AuthException("Authentication required");
}
if (input == null) {
input = new Input();
}
if (input.token == null) {
throw new UnprocessableEntityException("missing token");
}
try {
EmailTokenVerifier.ParsedToken token = emailTokenVerifier.decode(input.token);
Account.Id accId = user.getAccountId();
if (accId.equals(token.getAccountId())) {
accountManager.link(accId, token.toAuthRequest());
return Response.none();
}
throw new UnprocessableEntityException("invalid token");
} catch (EmailTokenVerifier.InvalidTokenException e) {
throw new UnprocessableEntityException("invalid token", e);
} catch (AccountException e) {
throw new UnprocessableEntityException(e.getMessage());
}
}
use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.
the class OAuthSession method authenticateAndRedirect.
private void authenticateAndRedirect(HttpServletRequest req, HttpServletResponse rsp, OAuthToken token) throws IOException {
AuthRequest areq = authRequestFactory.create(externalIdKeyFactory.parse(user.getExternalId()));
AuthResult arsp;
try {
String claimedIdentifier = user.getClaimedIdentity();
if (!Strings.isNullOrEmpty(claimedIdentifier)) {
if (!authenticateWithIdentityClaimedDuringHandshake(areq, rsp, claimedIdentifier)) {
return;
}
} else if (linkMode) {
if (!authenticateWithLinkedIdentity(areq, rsp)) {
return;
}
}
areq.setUserName(user.getUserName());
areq.setEmailAddress(user.getEmailAddress());
areq.setDisplayName(user.getDisplayName());
arsp = accountManager.authenticate(areq);
accountId = arsp.getAccountId();
tokenCache.put(accountId, token);
} 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);
String suffix = redirectToken.substring(OAuthWebFilter.GERRIT_LOGIN.length() + 1);
suffix = CharMatcher.anyOf("/").trimLeadingFrom(Url.decode(suffix));
StringBuilder rdr = new StringBuilder(urlProvider.get(req));
rdr.append(suffix);
rsp.sendRedirect(rdr.toString());
}
use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.
the class CreateEmail method apply.
/**
* To be used from plugins that want to create emails without permission checks.
*/
@UsedAt(UsedAt.Project.PLUGIN_SERVICEUSER)
public EmailInfo apply(IdentifiedUser user, IdString id, EmailInput input) throws RestApiException, EmailException, MethodNotAllowedException, IOException, ConfigInvalidException, PermissionBackendException {
String email = id.get().trim();
if (input == null) {
input = new EmailInput();
}
if (input.email != null && !email.equals(input.email)) {
throw new BadRequestException("email address must match URL");
}
if (!validator.isValid(email)) {
throw new BadRequestException("invalid email address");
}
EmailInfo info = new EmailInfo();
info.email = email;
if (input.noConfirmation || isDevMode) {
if (isDevMode) {
logger.atWarning().log("skipping email validation in developer mode");
}
try {
accountManager.link(user.getAccountId(), authRequestFactory.createForEmail(email));
} catch (AccountException e) {
throw new ResourceConflictException(e.getMessage());
}
if (input.preferred) {
putPreferred.apply(new AccountResource.Email(user, email), null);
info.preferred = true;
}
} else {
try {
RegisterNewEmailSender emailSender = registerNewEmailFactory.create(email);
if (!emailSender.isAllowed()) {
throw new MethodNotAllowedException("Not allowed to add email address " + email);
}
emailSender.setMessageId(messageIdGenerator.fromAccountUpdate(user.getAccountId()));
emailSender.send();
info.pendingConfirmation = true;
} catch (EmailException | RuntimeException e) {
logger.atSevere().withCause(e).log("Cannot send email verification message to %s", email);
throw e;
}
}
return info;
}
Aggregations