Search in sources :

Example 31 with AccountState

use of com.google.gerrit.server.account.AccountState in project gerrit by GerritCodeReview.

the class FromAddressGeneratorProviderTest method makeUser.

private AccountState makeUser(final String name, final String email) {
    final Account.Id userId = new Account.Id(42);
    final Account account = new Account(userId, TimeUtil.nowTs());
    account.setFullName(name);
    account.setPreferredEmail(email);
    return new AccountState(account, Collections.emptySet(), Collections.emptySet(), new HashMap<>());
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) AccountState(com.google.gerrit.server.account.AccountState)

Example 32 with AccountState

use of com.google.gerrit.server.account.AccountState in project gerrit by GerritCodeReview.

the class GerritGSSAuthenticator method validateIdentity.

@Override
public boolean validateIdentity(final ServerSession session, final String identity) {
    final SshSession sd = session.getAttribute(SshSession.KEY);
    int at = identity.indexOf('@');
    String username;
    if (at == -1) {
        username = identity;
    } else {
        username = identity.substring(0, at);
    }
    if (config.getBoolean("auth", "userNameToLowerCase", false)) {
        username = username.toLowerCase(Locale.US);
    }
    AccountState state = accounts.getByUsername(username);
    Account account = state == null ? null : state.getAccount();
    boolean active = account != null && account.isActive();
    if (active) {
        return SshUtil.success(username, session, sshScope, sshLog, sd, SshUtil.createUser(sd, userFactory, account.getId()));
    }
    return false;
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) AccountState(com.google.gerrit.server.account.AccountState)

Example 33 with AccountState

use of com.google.gerrit.server.account.AccountState in project gerrit by GerritCodeReview.

the class ProjectWatch method getWatchers.

/** Returns all watchers that are relevant */
public final Watchers getWatchers(NotifyType type, boolean includeWatchersFromNotifyConfig) throws OrmException {
    Watchers matching = new Watchers();
    Set<Account.Id> projectWatchers = new HashSet<>();
    for (AccountState a : args.accountQueryProvider.get().byWatchedProject(project)) {
        Account.Id accountId = a.getAccount().getId();
        for (Map.Entry<ProjectWatchKey, Set<NotifyType>> e : a.getProjectWatches().entrySet()) {
            if (project.equals(e.getKey().project()) && add(matching, accountId, e.getKey(), e.getValue(), type)) {
                // We only want to prevent matching All-Projects if this filter hits
                projectWatchers.add(accountId);
            }
        }
    }
    for (AccountState a : args.accountQueryProvider.get().byWatchedProject(args.allProjectsName)) {
        for (Map.Entry<ProjectWatchKey, Set<NotifyType>> e : a.getProjectWatches().entrySet()) {
            if (args.allProjectsName.equals(e.getKey().project())) {
                Account.Id accountId = a.getAccount().getId();
                if (!projectWatchers.contains(accountId)) {
                    add(matching, accountId, e.getKey(), e.getValue(), type);
                }
            }
        }
    }
    if (!includeWatchersFromNotifyConfig) {
        return matching;
    }
    for (ProjectState state : projectState.tree()) {
        for (NotifyConfig nc : state.getConfig().getNotifyConfigs()) {
            if (nc.isNotify(type)) {
                try {
                    add(matching, nc);
                } catch (QueryParseException e) {
                    log.warn("Project {} has invalid notify {} filter \"{}\": {}", state.getProject().getName(), nc.getName(), nc.getFilter(), e.getMessage());
                }
            }
        }
    }
    return matching;
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) HashSet(java.util.HashSet) Set(java.util.Set) ProjectWatchKey(com.google.gerrit.server.account.WatchConfig.ProjectWatchKey) AccountState(com.google.gerrit.server.account.AccountState) QueryParseException(com.google.gerrit.server.query.QueryParseException) ProjectState(com.google.gerrit.server.project.ProjectState) NotifyConfig(com.google.gerrit.server.git.NotifyConfig) Map(java.util.Map) HashSet(java.util.HashSet)

Example 34 with AccountState

use of com.google.gerrit.server.account.AccountState 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 35 with AccountState

use of com.google.gerrit.server.account.AccountState in project gerrit by GerritCodeReview.

the class AllAccountsIndexer method reindexAccounts.

private SiteIndexer.Result reindexAccounts(AccountIndex index, List<Account.Id> ids, ProgressMonitor progress) {
    progress.beginTask("Reindexing accounts", ids.size());
    List<ListenableFuture<?>> futures = new ArrayList<>(ids.size());
    AtomicBoolean ok = new AtomicBoolean(true);
    AtomicInteger done = new AtomicInteger();
    AtomicInteger failed = new AtomicInteger();
    Stopwatch sw = Stopwatch.createStarted();
    for (Account.Id id : ids) {
        String desc = "account " + id;
        ListenableFuture<?> future = executor.submit(() -> {
            try {
                Optional<AccountState> a = accountCache.get(id);
                if (a.isPresent()) {
                    if (isFirstInsertForEntry.equals(IsFirstInsertForEntry.YES)) {
                        index.insert(a.get());
                    } else {
                        index.replace(a.get());
                    }
                } else {
                    index.delete(id);
                }
                verboseWriter.println("Reindexed " + desc);
                done.incrementAndGet();
            } catch (Exception e) {
                failed.incrementAndGet();
                throw e;
            }
            return null;
        });
        addErrorListener(future, desc, progress, ok);
        futures.add(future);
    }
    try {
        Futures.successfulAsList(futures).get();
    } catch (ExecutionException | InterruptedException e) {
        logger.atSevere().withCause(e).log("Error waiting on account futures");
        return SiteIndexer.Result.create(sw, false, 0, 0);
    }
    progress.endTask();
    return SiteIndexer.Result.create(sw, ok.get(), done.get(), failed.get());
}
Also used : Account(com.google.gerrit.entities.Account) ArrayList(java.util.ArrayList) Stopwatch(com.google.common.base.Stopwatch) AccountState(com.google.gerrit.server.account.AccountState) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

AccountState (com.google.gerrit.server.account.AccountState)63 Account (com.google.gerrit.entities.Account)37 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)18 IOException (java.io.IOException)17 Test (org.junit.Test)16 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)15 Inject (com.google.inject.Inject)15 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)14 AuthException (com.google.gerrit.extensions.restapi.AuthException)12 ArrayList (java.util.ArrayList)12 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)11 HashSet (java.util.HashSet)11 List (java.util.List)11 ImmutableSet (com.google.common.collect.ImmutableSet)10 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)10 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)10 AccountsUpdate (com.google.gerrit.server.account.AccountsUpdate)10 TestAccount (com.google.gerrit.acceptance.TestAccount)9 Nullable (com.google.gerrit.common.Nullable)9 StorageException (com.google.gerrit.exceptions.StorageException)9