-
Notifications
You must be signed in to change notification settings - Fork 49
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
jameshadfield
wants to merge
1
commit into
master
Choose a base branch
from
james/groups-helper-script
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,130 @@ | ||||||
#!/usr/bin/env node | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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.'`) | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
} | ||||||
} else { | ||||||
console.log(`${existingMsg} (and you haven't specified a username)`) | ||||||
} | ||||||
} | ||||||
} | ||||||
} | ||||||
|
||||||
reportUnhandledRejectionsAtExit(); | ||||||
main(parseArgs()) | ||||||
.catch((error) => { | ||||||
process.exitCode = 1; | ||||||
console.error(error) | ||||||
}); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
There was a problem hiding this comment.
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.
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.There was a problem hiding this comment.
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
In the future when user creation is self-service, it would be good to add an extra confirmation step to this scenario.