Search in sources :

Example 26 with ExternalId

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

the class InitAdminUser method postRun.

@Override
public void postRun() throws Exception {
    AuthType authType = flags.cfg.getEnum(AuthType.values(), "auth", null, "type", null);
    if (authType != AuthType.DEVELOPMENT_BECOME_ANY_ACCOUNT) {
        return;
    }
    try (ReviewDb db = dbFactory.open()) {
        if (db.accounts().anyAccounts().toList().isEmpty()) {
            ui.header("Gerrit Administrator");
            if (ui.yesno(true, "Create administrator user")) {
                Account.Id id = new Account.Id(db.nextAccountId());
                String username = ui.readString("admin", "username");
                String name = ui.readString("Administrator", "name");
                String httpPassword = ui.readString("secret", "HTTP password");
                AccountSshKey sshKey = readSshKey(id);
                String email = readEmail(sshKey);
                List<ExternalId> extIds = new ArrayList<>(2);
                extIds.add(ExternalId.createUsername(username, id, httpPassword));
                if (email != null) {
                    extIds.add(ExternalId.createEmail(id, email));
                }
                externalIds.insert("Add external IDs for initial admin user", extIds);
                Account a = new Account(id, TimeUtil.nowTs());
                a.setFullName(name);
                a.setPreferredEmail(email);
                accounts.insert(db, a);
                AccountGroupName adminGroupName = db.accountGroupNames().get(new AccountGroup.NameKey("Administrators"));
                AccountGroupMember m = new AccountGroupMember(new AccountGroupMember.Key(id, adminGroupName.getId()));
                db.accountGroupMembers().insert(Collections.singleton(m));
                if (sshKey != null) {
                    VersionedAuthorizedKeysOnInit authorizedKeys = authorizedKeysFactory.create(id).load();
                    authorizedKeys.addKey(sshKey.getSshPublicKey());
                    authorizedKeys.save("Add SSH key for initial admin user\n");
                }
                AccountGroup adminGroup = db.accountGroups().get(adminGroupName.getId());
                AccountState as = new AccountState(a, Collections.singleton(adminGroup.getGroupUUID()), extIds, new HashMap<>());
                for (AccountIndex accountIndex : indexCollection.getWriteIndexes()) {
                    accountIndex.replace(as);
                }
            }
        }
    }
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) AccountGroupName(com.google.gerrit.reviewdb.client.AccountGroupName) AccountGroupMember(com.google.gerrit.reviewdb.client.AccountGroupMember) AccountIndex(com.google.gerrit.server.index.account.AccountIndex) AccountSshKey(com.google.gerrit.reviewdb.client.AccountSshKey) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ArrayList(java.util.ArrayList) AccountState(com.google.gerrit.server.account.AccountState) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) AuthType(com.google.gerrit.extensions.client.AuthType) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb)

Example 27 with ExternalId

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

the class CreateAccount method apply.

@Override
public Response<AccountInfo> apply(TopLevelResource rsrc, AccountInput input) throws BadRequestException, ResourceConflictException, UnprocessableEntityException, OrmException, IOException, ConfigInvalidException {
    if (input == null) {
        input = new AccountInput();
    }
    if (input.username != null && !username.equals(input.username)) {
        throw new BadRequestException("username must match URL");
    }
    if (!username.matches(Account.USER_NAME_PATTERN)) {
        throw new BadRequestException("Username '" + username + "' must contain only letters, numbers, _, - or .");
    }
    Set<AccountGroup.Id> groups = parseGroups(input.groups);
    Account.Id id = new Account.Id(db.nextAccountId());
    ExternalId extUser = ExternalId.createUsername(username, id, input.httpPassword);
    if (externalIds.get(extUser.key()) != null) {
        throw new ResourceConflictException("username '" + username + "' already exists");
    }
    if (input.email != null) {
        if (externalIds.get(ExternalId.Key.create(SCHEME_MAILTO, input.email)) != null) {
            throw new UnprocessableEntityException("email '" + input.email + "' already exists");
        }
        if (!validator.isValid(input.email)) {
            throw new BadRequestException("invalid email address");
        }
    }
    List<ExternalId> extIds = new ArrayList<>();
    extIds.add(extUser);
    for (AccountExternalIdCreator c : externalIdCreators) {
        extIds.addAll(c.create(id, username, input.email));
    }
    ExternalIdsUpdate externalIdsUpdate = externalIdsUpdateFactory.create();
    try {
        externalIdsUpdate.insert(extIds);
    } catch (OrmDuplicateKeyException duplicateKey) {
        throw new ResourceConflictException("username '" + username + "' already exists");
    }
    if (input.email != null) {
        try {
            externalIdsUpdate.insert(ExternalId.createEmail(id, input.email));
        } catch (OrmDuplicateKeyException duplicateKey) {
            try {
                externalIdsUpdate.delete(extUser);
            } catch (IOException | ConfigInvalidException cleanupError) {
            // Ignored
            }
            throw new UnprocessableEntityException("email '" + input.email + "' already exists");
        }
    }
    Account a = new Account(id, TimeUtil.nowTs());
    a.setFullName(input.name);
    a.setPreferredEmail(input.email);
    accountsUpdate.create().insert(db, a);
    for (AccountGroup.Id groupId : groups) {
        AccountGroupMember m = new AccountGroupMember(new AccountGroupMember.Key(id, groupId));
        auditService.dispatchAddAccountsToGroup(currentUser.get().getAccountId(), Collections.singleton(m));
        db.accountGroupMembers().insert(Collections.singleton(m));
    }
    if (input.sshKey != null) {
        try {
            authorizedKeys.addKey(id, input.sshKey);
            sshKeyCache.evict(username);
        } catch (InvalidSshKeyException e) {
            throw new BadRequestException(e.getMessage());
        }
    }
    accountCache.evictByUsername(username);
    byEmailCache.evict(input.email);
    indexer.index(id);
    AccountLoader loader = infoLoader.create(true);
    AccountInfo info = loader.get(id);
    loader.fill();
    return Response.created(info);
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) AccountGroupMember(com.google.gerrit.reviewdb.client.AccountGroupMember) OrmDuplicateKeyException(com.google.gwtorm.server.OrmDuplicateKeyException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ExternalIdsUpdate(com.google.gerrit.server.account.externalids.ExternalIdsUpdate) ArrayList(java.util.ArrayList) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) AccountExternalIdCreator(com.google.gerrit.server.api.accounts.AccountExternalIdCreator) InvalidSshKeyException(com.google.gerrit.common.errors.InvalidSshKeyException) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) AccountInput(com.google.gerrit.extensions.api.accounts.AccountInput) AccountInfo(com.google.gerrit.extensions.common.AccountInfo)

Example 28 with ExternalId

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

the class DeleteEmail method apply.

public Response<?> apply(IdentifiedUser user, String email) throws ResourceNotFoundException, ResourceConflictException, MethodNotAllowedException, OrmException, IOException, ConfigInvalidException {
    if (!realm.allowsEdit(AccountFieldName.REGISTER_NEW_EMAIL)) {
        throw new MethodNotAllowedException("realm does not allow deleting emails");
    }
    Set<ExternalId> extIds = externalIds.byAccount(user.getAccountId()).stream().filter(e -> email.equals(e.email())).collect(toSet());
    if (extIds.isEmpty()) {
        throw new ResourceNotFoundException(email);
    }
    try {
        for (ExternalId extId : extIds) {
            AuthRequest authRequest = new AuthRequest(extId.key());
            authRequest.setEmailAddress(email);
            accountManager.unlink(user.getAccountId(), authRequest);
        }
    } catch (AccountException e) {
        throw new ResourceConflictException(e.getMessage());
    }
    return Response.none();
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) GlobalPermission(com.google.gerrit.server.permissions.GlobalPermission) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) CurrentUser(com.google.gerrit.server.CurrentUser) OrmException(com.google.gwtorm.server.OrmException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) Input(com.google.gerrit.server.account.DeleteEmail.Input) Inject(com.google.inject.Inject) Set(java.util.Set) AccountFieldName(com.google.gerrit.extensions.client.AccountFieldName) IOException(java.io.IOException) Response(com.google.gerrit.extensions.restapi.Response) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) ExternalIds(com.google.gerrit.server.account.externalids.ExternalIds) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) Provider(com.google.inject.Provider) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) AuthException(com.google.gerrit.extensions.restapi.AuthException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) Collectors.toSet(java.util.stream.Collectors.toSet) Singleton(com.google.inject.Singleton) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException)

Example 29 with ExternalId

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

the class GetExternalIds method apply.

@Override
public List<AccountExternalIdInfo> apply(AccountResource resource) throws RestApiException, IOException, OrmException {
    if (self.get() != resource.getUser() && !self.get().getCapabilities().canAccessDatabase()) {
        throw new AuthException("not allowed to get external IDs");
    }
    Collection<ExternalId> ids = externalIds.byAccount(resource.getUser().getAccountId());
    if (ids.isEmpty()) {
        return ImmutableList.of();
    }
    List<AccountExternalIdInfo> result = Lists.newArrayListWithCapacity(ids.size());
    for (ExternalId id : ids) {
        AccountExternalIdInfo info = new AccountExternalIdInfo();
        info.identity = id.key().get();
        info.emailAddress = id.email();
        info.trusted = toBoolean(authConfig.isIdentityTrustable(Collections.singleton(id)));
        // actually used to establish this web session.
        if (!id.isScheme(SCHEME_USERNAME)) {
            ExternalId.Key last = resource.getUser().getLastLoginExternalIdKey();
            info.canDelete = toBoolean(last == null || !last.get().equals(info.identity));
        }
        result.add(info);
    }
    return result;
}
Also used : ExternalId(com.google.gerrit.server.account.externalids.ExternalId) AuthException(com.google.gerrit.extensions.restapi.AuthException) AccountExternalIdInfo(com.google.gerrit.extensions.common.AccountExternalIdInfo)

Example 30 with ExternalId

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

the class LocalUsernamesToLowerCase method run.

@Override
public int run() throws Exception {
    Injector dbInjector = createDbInjector(MULTI_USER);
    manager.add(dbInjector, dbInjector.createChildInjector(SchemaVersionCheck.module()));
    manager.start();
    dbInjector.createChildInjector(new AbstractModule() {

        @Override
        protected void configure() {
            // The LocalUsernamesToLowerCase program needs to access all external IDs only
            // once to update them. After the update they are not accessed again. Hence the
            // LocalUsernamesToLowerCase program doesn't benefit from caching external IDs and
            // the external ID cache can be disabled.
            install(DisabledExternalIdCache.module());
        }
    }).injectMembers(this);
    Collection<ExternalId> todo = externalIds.all();
    monitor.beginTask("Converting local usernames", todo.size());
    for (ExternalId extId : todo) {
        convertLocalUserToLowerCase(extId);
        monitor.update(1);
    }
    externalIdsBatchUpdate.commit("Convert local usernames to lower case");
    monitor.endTask();
    manager.stop();
    return 0;
}
Also used : Injector(com.google.inject.Injector) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) AbstractModule(com.google.inject.AbstractModule)

Aggregations

ExternalId (com.google.gerrit.server.account.externalids.ExternalId)34 Account (com.google.gerrit.reviewdb.client.Account)12 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)8 Test (org.junit.Test)8 OrmException (com.google.gwtorm.server.OrmException)7 ArrayList (java.util.ArrayList)7 ObjectId (org.eclipse.jgit.lib.ObjectId)7 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)6 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)6 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)6 NoteMap (org.eclipse.jgit.notes.NoteMap)6 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)5 ReviewDb (com.google.gerrit.reviewdb.server.ReviewDb)5 ExternalIdsUpdate (com.google.gerrit.server.account.externalids.ExternalIdsUpdate)5 HashSet (java.util.HashSet)5 AccountExternalIdInfo (com.google.gerrit.extensions.common.AccountExternalIdInfo)4 AuthException (com.google.gerrit.extensions.restapi.AuthException)4 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)4 AccountGroup (com.google.gerrit.reviewdb.client.AccountGroup)4 AccountGroupMember (com.google.gerrit.reviewdb.client.AccountGroupMember)4