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);
}
}
}
}
}
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);
}
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();
}
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;
}
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;
}
Aggregations