use of com.google.gwtorm.server.OrmException in project gerrit by GerritCodeReview.
the class RunAsFilter method doFilter.
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String runas = req.getHeader(RUN_AS);
if (runas != null) {
if (!enabled) {
replyError(req, res, SC_FORBIDDEN, RUN_AS + " disabled by auth.enableRunAs = false", null);
return;
}
CurrentUser self = session.get().getUser();
try {
if (!self.isIdentifiedUser()) {
// because that would be crazy.
throw new AuthException("denied");
}
permissionBackend.user(self).check(GlobalPermission.RUN_AS);
} catch (AuthException e) {
replyError(req, res, SC_FORBIDDEN, "not permitted to use " + RUN_AS, null);
return;
} catch (PermissionBackendException e) {
log.warn("cannot check runAs", e);
replyError(req, res, SC_INTERNAL_SERVER_ERROR, RUN_AS + " unavailable", null);
return;
}
Account target;
try {
target = accountResolver.find(db.get(), runas);
} catch (OrmException e) {
log.warn("cannot resolve account for " + RUN_AS, e);
replyError(req, res, SC_INTERNAL_SERVER_ERROR, "cannot resolve " + RUN_AS, e);
return;
}
if (target == null) {
replyError(req, res, SC_FORBIDDEN, "no account matches " + RUN_AS, null);
return;
}
session.get().setUserAccountId(target.getId());
}
chain.doFilter(req, res);
}
use of com.google.gwtorm.server.OrmException in project gerrit by GerritCodeReview.
the class BecomeAnyAccountLoginServlet method doPost.
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException, ServletException {
CacheHeaders.setNotCacheable(rsp);
final AuthResult res;
if ("create_account".equals(req.getParameter("action"))) {
res = create();
} else if (req.getParameter("user_name") != null) {
res = byUserName(req.getParameter("user_name"));
} else if (req.getParameter("preferred_email") != null) {
res = byPreferredEmail(req.getParameter("preferred_email"));
} else if (req.getParameter("account_id") != null) {
res = byAccountId(req.getParameter("account_id"));
} else {
byte[] raw;
try {
raw = prepareHtmlOutput();
} catch (OrmException e) {
throw new ServletException(e);
}
rsp.setContentType("text/html");
rsp.setCharacterEncoding(HtmlDomUtil.ENC.name());
rsp.setContentLength(raw.length);
try (OutputStream out = rsp.getOutputStream()) {
out.write(raw);
}
return;
}
if (res != null) {
webSession.get().login(res, false);
final StringBuilder rdr = new StringBuilder();
rdr.append(req.getContextPath());
rdr.append("/");
if (res.isNew()) {
rdr.append('#' + PageLinks.REGISTER);
} else {
rdr.append(LoginUrlToken.getToken(req));
}
rsp.sendRedirect(rdr.toString());
} else {
rsp.setContentType("text/html");
rsp.setCharacterEncoding(HtmlDomUtil.ENC.name());
try (Writer out = rsp.getWriter()) {
out.write("<html>");
out.write("<body>");
out.write("<h1>Account Not Found</h1>");
out.write("</body>");
out.write("</html>");
}
}
}
use of com.google.gwtorm.server.OrmException in project gerrit by GerritCodeReview.
the class HttpLoginServlet method doGet.
@Override
protected void doGet(final HttpServletRequest req, final 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)) {
log.error("Unable to authenticate user by " + authFilter.getLoginHeader() + " request header. Check container or server configuration.");
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 = AuthRequest.forUser(user);
areq.setDisplayName(authFilter.getRemoteDisplayname(req));
areq.setEmailAddress(authFilter.getRemoteEmail(req));
final AuthResult arsp;
try {
arsp = accountManager.authenticate(areq);
} catch (AccountException e) {
log.error("Unable to authenticate user \"" + user + "\"", e);
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
String remoteExternalId = authFilter.getRemoteExternalIdToken(req);
if (remoteExternalId != null) {
try {
log.debug("Associating external identity \"{}\" to user \"{}\"", remoteExternalId, user);
updateRemoteExternalId(arsp, remoteExternalId);
} catch (AccountException | OrmException | ConfigInvalidException e) {
log.error("Unable to associate external identity \"" + remoteExternalId + "\" to user \"" + user + "\"", e);
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.gwtorm.server.OrmException in project gerrit by GerritCodeReview.
the class AccountManager method create.
private AuthResult create(ReviewDb db, AuthRequest who) throws OrmException, AccountException, IOException, ConfigInvalidException {
Account.Id newId = new Account.Id(db.nextAccountId());
Account account = new Account(newId, TimeUtil.nowTs());
ExternalId extId = ExternalId.createWithEmail(who.getExternalIdKey(), newId, who.getEmailAddress());
account.setFullName(who.getDisplayName());
account.setPreferredEmail(extId.email());
boolean isFirstAccount = awaitsFirstAccountCheck.getAndSet(false) && db.accounts().anyAccounts().toList().isEmpty();
try {
AccountsUpdate accountsUpdate = accountsUpdateFactory.create();
accountsUpdate.upsert(db, account);
ExternalId existingExtId = externalIds.get(extId.key());
if (existingExtId != null && !existingExtId.accountId().equals(extId.accountId())) {
// external ID is assigned to another account, do not overwrite
accountsUpdate.delete(db, account);
throw new AccountException("Cannot assign external ID \"" + extId.key().get() + "\" to account " + newId + "; external ID already in use.");
}
externalIdsUpdateFactory.create().upsert(extId);
} finally {
// If adding the account failed, it may be that it actually was the
// first account. So we reset the 'check for first account'-guard, as
// otherwise the first account would not get administration permissions.
awaitsFirstAccountCheck.set(isFirstAccount);
}
if (isFirstAccount) {
// This is the first user account on our site. Assume this user
// is going to be the site's administrator and just make them that
// to bootstrap the authentication database.
//
Permission admin = projectCache.getAllProjects().getConfig().getAccessSection(AccessSection.GLOBAL_CAPABILITIES).getPermission(GlobalCapability.ADMINISTRATE_SERVER);
AccountGroup.UUID uuid = admin.getRules().get(0).getGroup().getUUID();
AccountGroup g = db.accountGroups().byUUID(uuid).iterator().next();
AccountGroup.Id adminId = g.getId();
AccountGroupMember m = new AccountGroupMember(new AccountGroupMember.Key(newId, adminId));
auditService.dispatchAddAccountsToGroup(newId, Collections.singleton(m));
db.accountGroupMembers().insert(Collections.singleton(m));
}
if (who.getUserName() != null) {
// Only set if the name hasn't been used yet, but was given to us.
//
IdentifiedUser user = userFactory.create(newId);
try {
changeUserNameFactory.create(user, who.getUserName()).call();
} catch (NameAlreadyUsedException e) {
String message = "Cannot assign user name \"" + who.getUserName() + "\" to account " + newId + "; name already in use.";
handleSettingUserNameFailure(db, account, extId, message, e, false);
} catch (InvalidUserNameException e) {
String message = "Cannot assign user name \"" + who.getUserName() + "\" to account " + newId + "; name does not conform.";
handleSettingUserNameFailure(db, account, extId, message, e, false);
} catch (OrmException e) {
String message = "Cannot assign user name";
handleSettingUserNameFailure(db, account, extId, message, e, true);
}
}
byEmailCache.evict(account.getPreferredEmail());
byIdCache.evict(account.getId());
realm.onCreateAccount(who, account);
return new AuthResult(newId, extId.key(), true);
}
use of com.google.gwtorm.server.OrmException in project gerrit by GerritCodeReview.
the class AccountResolver method findAllByNameOrEmail.
/**
* Locate exactly one account matching the name or name/email string.
*
* @param db open database handle.
* @param nameOrEmail a string of the format "Full Name <email@example>", just the email
* address ("email@example"), a full name ("Full Name").
* @return the accounts that match, empty collection if none. Never null.
*/
public Set<Account.Id> findAllByNameOrEmail(ReviewDb db, String nameOrEmail) throws OrmException {
int lt = nameOrEmail.indexOf('<');
int gt = nameOrEmail.indexOf('>');
if (lt >= 0 && gt > lt && nameOrEmail.contains("@")) {
Set<Account.Id> ids = byEmail.get(nameOrEmail.substring(lt + 1, gt));
if (ids.isEmpty() || ids.size() == 1) {
return ids;
}
// more than one match, try to return the best one
String name = nameOrEmail.substring(0, lt - 1);
Set<Account.Id> nameMatches = new HashSet<>();
for (Account.Id id : ids) {
Account a = byId.get(id).getAccount();
if (name.equals(a.getFullName())) {
nameMatches.add(id);
}
}
return nameMatches.isEmpty() ? ids : nameMatches;
}
if (nameOrEmail.contains("@")) {
return byEmail.get(nameOrEmail);
}
Account.Id id = realm.lookup(nameOrEmail);
if (id != null) {
return Collections.singleton(id);
}
List<AccountState> m = accountQueryProvider.get().byFullName(nameOrEmail);
if (m.size() == 1) {
return Collections.singleton(m.get(0).getAccount().getId());
}
// and pray we come up with a reasonable result list.
return accountQueryProvider.get().byDefault(nameOrEmail).stream().map(a -> a.getAccount().getId()).collect(toSet());
}
Aggregations