Search in sources :

Example 61 with Account

use of com.google.gerrit.entities.Account 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;
    }
}
Also used : Cookie(javax.servlet.http.Cookie) Account(com.google.gerrit.entities.Account) AuthRequest(com.google.gerrit.server.account.AuthRequest) AccountException(com.google.gerrit.server.account.AccountException) AuthResult(com.google.gerrit.server.account.AuthResult) AccountState(com.google.gerrit.server.account.AccountState)

Example 62 with Account

use of com.google.gerrit.entities.Account in project gerrit by GerritCodeReview.

the class IdentifiedUser method newRefLogIdent.

public PersonIdent newRefLogIdent(Instant when, TimeZone tz) {
    final Account ua = getAccount();
    String name = ua.fullName();
    if (name == null || name.isEmpty()) {
        name = ua.preferredEmail();
    }
    if (name == null || name.isEmpty()) {
        name = anonymousCowardName;
    }
    String user;
    if (enablePeerIPInReflogRecord) {
        user = constructMailAddress(ua, guessHost());
    } else {
        user = Strings.isNullOrEmpty(ua.preferredEmail()) ? constructMailAddress(ua, "unknown") : ua.preferredEmail();
    }
    return newPersonIdent(name, user, when, tz);
}
Also used : Account(com.google.gerrit.entities.Account)

Example 63 with Account

use of com.google.gerrit.entities.Account in project gerrit by GerritCodeReview.

the class AccountCacheImpl method get.

@Override
public Map<Account.Id, AccountState> get(Set<Account.Id> accountIds) {
    try {
        try (Repository allUsers = repoManager.openRepository(allUsersName)) {
            // Get the default preferences for this Gerrit host
            Ref ref = allUsers.exactRef(RefNames.REFS_USERS_DEFAULT);
            CachedPreferences defaultPreferences = ref != null ? defaultPreferenceCache.get(ref.getObjectId()) : DefaultPreferencesCache.EMPTY;
            Set<CachedAccountDetails.Key> keys = Sets.newLinkedHashSetWithExpectedSize(accountIds.size());
            for (Account.Id id : accountIds) {
                Ref userRef = allUsers.exactRef(RefNames.refsUsers(id));
                if (userRef == null) {
                    continue;
                }
                keys.add(CachedAccountDetails.Key.create(id, userRef.getObjectId()));
            }
            ImmutableMap.Builder<Account.Id, AccountState> result = ImmutableMap.builder();
            for (Map.Entry<CachedAccountDetails.Key, CachedAccountDetails> account : accountDetailsCache.getAll(keys).entrySet()) {
                result.put(account.getKey().accountId(), AccountState.forCachedAccount(account.getValue(), defaultPreferences, externalIds));
            }
            return result.build();
        }
    } catch (IOException | ExecutionException e) {
        throw new StorageException(e);
    }
}
Also used : Account(com.google.gerrit.entities.Account) IOException(java.io.IOException) ImmutableMap(com.google.common.collect.ImmutableMap) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) ExecutionException(java.util.concurrent.ExecutionException) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) StorageException(com.google.gerrit.exceptions.StorageException) CachedPreferences(com.google.gerrit.server.config.CachedPreferences)

Example 64 with Account

use of com.google.gerrit.entities.Account in project gerrit by GerritCodeReview.

the class Accounts method all.

/**
 * Returns all accounts.
 *
 * @return all accounts
 */
public List<AccountState> all() throws IOException {
    Set<Account.Id> accountIds = allIds();
    List<AccountState> accounts = new ArrayList<>(accountIds.size());
    try (Repository repo = repoManager.openRepository(allUsersName)) {
        for (Account.Id accountId : accountIds) {
            try {
                read(repo, accountId).ifPresent(accounts::add);
            } catch (Exception e) {
                logger.atSevere().withCause(e).log("Ignoring invalid account %s", accountId);
            }
        }
    }
    return accounts;
}
Also used : Account(com.google.gerrit.entities.Account) Repository(org.eclipse.jgit.lib.Repository) ArrayList(java.util.ArrayList) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) IOException(java.io.IOException)

Example 65 with Account

use of com.google.gerrit.entities.Account in project gerrit by GerritCodeReview.

the class AccountManager method authenticate.

/**
 * Authenticate the user, potentially creating a new account if they are new.
 *
 * @param who identity of the user, with any details we received about them.
 * @return the result of authenticating the user.
 * @throws AccountException the account does not exist, and cannot be created, or exists, but
 *     cannot be located, is unable to be activated or deactivated, or is inactive, or cannot be
 *     added to the admin group (only for the first account).
 */
public AuthResult authenticate(AuthRequest who) throws AccountException, IOException {
    try {
        who = realm.authenticate(who);
    } catch (NoSuchUserException e) {
        deactivateAccountIfItExists(who);
        throw e;
    }
    try {
        Optional<ExternalId> optionalExtId = externalIds.get(who.getExternalIdKey());
        if (!optionalExtId.isPresent()) {
            logger.atFine().log("External ID for account %s not found. A new account will be automatically created.", who.getUserName());
            return create(who);
        }
        ExternalId extId = optionalExtId.get();
        Optional<AccountState> accountState = byIdCache.get(extId.accountId());
        if (!accountState.isPresent()) {
            logger.atSevere().log("Authentication with external ID %s failed. Account %s doesn't exist.", extId.key().get(), extId.accountId().get());
            throw new AccountException("Authentication error, account not found");
        }
        // Account exists
        Optional<Account> act = updateAccountActiveStatus(who, accountState.get().account());
        if (!act.isPresent()) {
            // since we don't support deletion of accounts.
            throw new AccountException("Authentication error, account not found");
        }
        if (!act.get().isActive()) {
            throw new AccountException("Authentication error, account inactive");
        }
        // return the identity to the caller.
        update(who, extId);
        return new AuthResult(extId.accountId(), who.getExternalIdKey(), false);
    } catch (StorageException | ConfigInvalidException e) {
        throw new AccountException("Authentication error", e);
    }
}
Also used : Account(com.google.gerrit.entities.Account) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) NoSuchUserException(com.google.gerrit.server.auth.NoSuchUserException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) StorageException(com.google.gerrit.exceptions.StorageException)

Aggregations

Account (com.google.gerrit.entities.Account)124 Test (org.junit.Test)59 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)37 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)35 AccountState (com.google.gerrit.server.account.AccountState)35 IOException (java.io.IOException)31 Repository (org.eclipse.jgit.lib.Repository)31 Change (com.google.gerrit.entities.Change)28 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)26 Inject (com.google.inject.Inject)25 PersonIdent (org.eclipse.jgit.lib.PersonIdent)25 List (java.util.List)24 ArrayList (java.util.ArrayList)23 HashSet (java.util.HashSet)23 Set (java.util.Set)22 RefNames (com.google.gerrit.entities.RefNames)21 AuthRequest (com.google.gerrit.server.account.AuthRequest)21 Map (java.util.Map)21 ObjectId (org.eclipse.jgit.lib.ObjectId)21 ImmutableList (com.google.common.collect.ImmutableList)20