Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[provision group] Check emails / usernames against existing users #987

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 130 additions & 0 deletions scripts/provision-group-check-users.js
Copy link
Member

@victorlin victorlin Aug 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there are a few emails with multiple usernames in the production pool, which I don't think is ideal.

The ability to do so seems intentional. Skimming through the code, everything is keyed on username (also apparent on https://nextstrain.org/login). Many services allow multiple accounts for a single email. This can be useful for things such as one person having separate accounts for different levels of access.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah - for sure cognito is keyed off username, and by extension nextstrain is as well.

This can be useful for things such as one person having separate accounts for different levels of access

I guess so? Outside of testing purposes I don't quite see the point of one person maintaining different access levels for the same group, but I'm sure there are use cases.

In the few examples I've seen (and thus anecdotal) I think we've created a username/email combo for one group, then for a subsequent group been given a list of emails and used the provision-groups script to add a new username for the same email. From the users perspective that's not ideal (need to login with different usernames to see different groups), but for the users in question I believe their usage is very low at the moment.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Example use case for multiple usernames under the same email.

I don't doubt that some of the existing many-to-one username/email instances are not ideal, so maybe it'd be good to print a warning such as

WARNING: Email <email> exists with username(s) <name> and you are asking for the new username <name> to be created. Confirm that this is intentional.

In the future when user creation is self-service, it would be good to add an extra confirmation step to this scenario.

Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
#!/usr/bin/env node
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shebang indicates that this should be executable but it isn't:

$ ./scripts/provision-group-check-users.js members.yaml       
zsh: permission denied: ./scripts/provision-group-check-users.js

Fix:

chmod a+x scripts/provision-group-check-users.js

import { ArgumentParser } from 'argparse';
import {
CognitoIdentityProviderClient,
ListUsersCommand,
} from '@aws-sdk/client-cognito-identity-provider';
import fs from 'fs';
import yaml from 'js-yaml';
import process from 'process';
import { COGNITO_USER_POOL_ID } from '../src/config.js';
import { reportUnhandledRejectionsAtExit } from '../src/utils/scripts.js';

const REGION = COGNITO_USER_POOL_ID.split("_")[0];
const cognito = new CognitoIdentityProviderClient({ region: REGION });

function parseArgs() {
const argparser = new ArgumentParser({
description: `
A helper script to check provided emails against existing cognito users.
If a username is provided that is also checked against existing users.
Messages are printed to STDOUT.
Set 'CONFIG_FILE=env/production/config.json' to use the production cognito
user pool (default: pool defined in env/testing/config.json)
`,
});
argparser.addArgument("--members", {
dest: "membersFile",
metavar: "<file.yaml>",
required: true,
help: `
A YAML file intended for 'provision-group.js'. Each entry must contain a 'email'
key and optionally a 'username' key.
`,
});

return argparser.parseArgs();
}


async function main({membersFile}) {
const members = readMembersFile(membersFile)
const {usersByEmail, usersByUsername} = await cognitoUsers()
queryUsernames(members, usersByEmail, usersByUsername)
}


function readMembersFile(file) {
const members = yaml.load(fs.readFileSync(file));

const validationErrors = !Array.isArray(members)
? ["Not an array"]
: members.filter(m => !m.email)
.map(m => `Email missing for member ${JSON.stringify(m)}`)
;

if (validationErrors.length) {
const msg = validationErrors.map((err, i) => ` ${i+1}. ${err}`).join("\n");
const s = validationErrors.length === 1 ? "" : "s";
throw new Error(`Members file contains ${validationErrors.length} error${s}:\n${msg}`);
}

return members;
}

function getEmailFromUser(user) {
return user.Attributes.filter(({Name}) => Name==='email')[0].Value;
}

async function cognitoUsers() {
// https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/ListUsersCommand/
const params = {
AttributesToGet: ['email'], // all users must have this else cmd fails
UserPoolId: COGNITO_USER_POOL_ID,
// Limit: 60, // default: 60
}
let {Users, PaginationToken} = await cognito.send(new ListUsersCommand(params));
while (PaginationToken) {
const data = await cognito.send(new ListUsersCommand({...params, PaginationToken}));
Users = [...Users, ...data.Users]
PaginationToken = data.PaginationToken
}
// there may be duplicate emails (different users)
const [usersByEmail, usersByUsername] = [{}, {}]
for (const user of Users) {
const email = getEmailFromUser(user);
Object.hasOwn(usersByEmail, email) ? usersByEmail[email].push(user) : (usersByEmail[email]=[user])
usersByUsername[user.Username] = user; // Username is unique (within a user pool)
}

return {usersByEmail, usersByUsername};
}


function queryUsernames(members, usersByEmail, usersByUsername) {
for (const member of members) {
if (Object.hasOwn(usersByEmail, member.email)) {
const existingMsg = `Email ${member.email} exists with username(s) ${usersByEmail[member.email].map((u) => `'${u.Username}'`).join(', ')}`
if (member.username) {
const usernameAssociatedWithEmail = usersByEmail[member.email].filter((u) => u.Username===member.username).length>0
if (usernameAssociatedWithEmail) {
console.log(`${existingMsg} ALL GOOD.`)
} else if (Object.hasOwn(usersByUsername, member.username)) {
console.log(`${existingMsg} but the username '${member.username}' is already associated with '${getEmailFromUser(usersByUsername[member.username])}'`)
} else {
console.log(`${existingMsg} and you are asking for the new username '${member.username}' to be created. ALL GOOD.`)
}
} else {
console.log(existingMsg)
}
} else { // new email (not associated with any cognito user)
const existingMsg = `Email ${member.email} doesn't yet exist`
if (member.username) {
if (Object.hasOwn(usersByUsername, member.username)) {
console.log(`${existingMsg} but the username '${member.username}' is already associated with '${getEmailFromUser(usersByUsername[member.username])}'`)
} else {
console.log(`${existingMsg} and neither does the username '${member.username}. ALL GOOD.'`)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
console.log(`${existingMsg} and neither does the username '${member.username}. ALL GOOD.'`)
console.log(`${existingMsg} and neither does the username '${member.username}'. ALL GOOD.`)

}
} else {
console.log(`${existingMsg} (and you haven't specified a username)`)
}
}
}
}

reportUnhandledRejectionsAtExit();
main(parseArgs())
.catch((error) => {
process.exitCode = 1;
console.error(error)
});