use of com.google.gerrit.reviewdb.client.AccountGroupMember 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.gerrit.reviewdb.client.AccountGroupMember 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.reviewdb.client.AccountGroupMember 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.reviewdb.client.AccountGroupMember in project gerrit by GerritCodeReview.
the class ProjectWatch method deliverToMembers.
private void deliverToMembers(Watchers.List matching, AccountGroup.UUID startUUID) throws OrmException {
ReviewDb db = args.db.get();
Set<AccountGroup.UUID> seen = new HashSet<>();
List<AccountGroup.UUID> q = new ArrayList<>();
seen.add(startUUID);
q.add(startUUID);
while (!q.isEmpty()) {
AccountGroup.UUID uuid = q.remove(q.size() - 1);
GroupDescription.Basic group = args.groupBackend.get(uuid);
if (!Strings.isNullOrEmpty(group.getEmailAddress())) {
// If the group has an email address, do not expand membership.
matching.emails.add(new Address(group.getEmailAddress()));
continue;
}
AccountGroup ig = GroupDescriptions.toAccountGroup(group);
if (ig == null) {
// Non-internal groups cannot be expanded by the server.
continue;
}
for (AccountGroupMember m : db.accountGroupMembers().byGroup(ig.getId())) {
matching.accounts.add(m.getAccountId());
}
for (AccountGroup.UUID m : args.groupIncludes.subgroupsOf(uuid)) {
if (seen.add(m)) {
q.add(m);
}
}
}
}
use of com.google.gerrit.reviewdb.client.AccountGroupMember in project gerrit by GerritCodeReview.
the class DbGroupMemberAuditListener method logOrmExceptionForAccounts.
private void logOrmExceptionForAccounts(String header, Account.Id me, Collection<AccountGroupMember> values, OrmException e) {
List<String> descriptions = new ArrayList<>();
for (AccountGroupMember m : values) {
Account.Id accountId = m.getAccountId();
String userName = accountCache.get(accountId).getUserName();
AccountGroup.Id groupId = m.getAccountGroupId();
String groupName = groupCache.get(groupId).getName();
descriptions.add(MessageFormat.format("account {0}/{1}, group {2}/{3}", accountId, userName, groupId, groupName));
}
logOrmException(header, me, descriptions, e);
}
Aggregations