-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate-user.mjs
More file actions
194 lines (169 loc) · 4.67 KB
/
Copy pathcreate-user.mjs
File metadata and controls
194 lines (169 loc) · 4.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import process from 'node:process'
import { promisify } from 'node:util'
import inquirer from 'inquirer'
import crypto from 'node:crypto'
import { fileURLToPath } from 'node:url'
import path from 'node:path'
import { exec } from 'node:child_process'
import roleMapping from '../packages/shared/role-mapping.js'
import { UpdateCommand } from '@aws-sdk/lib-dynamodb'
import { ListTablesCommand } from '@aws-sdk/client-dynamodb'
import { createRequire } from 'node:module'
import { STSClient, GetCallerIdentityCommand } from '@aws-sdk/client-sts'
/* eslint-disable unicorn/no-process-exit */
const require = createRequire(import.meta.url)
const __dirname = path.dirname(fileURLToPath(import.meta.url))
if (!process.env.AWS_ACCESS_KEY_ID) {
console.error('\u001B[91mmissing aws credentials\u001B[0m')
process.exit(1)
}
let stackTableName
const sts = new STSClient({ region: 'us-east-1' })
const { Account: accountId } = await sts.send(new GetCallerIdentityCommand())
const { awsAccounts, regions } = require('../packages/settings.json')
const awsAccount = awsAccounts[accountId]
if (!awsAccount) {
console.error(
`\u001B[91maccount ${accountId} not found in ../packages/settings.json\u001B[0m`
)
process.exit(0)
}
const region = regions[awsAccount.stage]
process.env.AWS_REGION = region
process.env.AWS_DEFAULT_REGION = region
const { default: dynamodb } = await import(
path.join(__dirname, '..', 'packages', 'shared', 'dynamodb.js')
)
const { TableNames: tableNames = [] } = await dynamodb.send(
new ListTablesCommand({})
)
const stackTables = tableNames.filter((x) => x.includes('StackTable'))
if (stackTables.length === 0) {
console.error('\u001B[91mno stack tables found\u001B[0m')
process.exit(1)
} else if (stackTables.length > 1) {
const prRef = await getPullRequestRef()
if (prRef > 0) {
const stage = `pr-${prRef}`
const prTable = stackTables.find(function findPullRequestStackTable(table) {
return table.includes(stage)
})
if (prTable) {
stackTableName = prTable
}
}
if (!stackTableName) {
const { table } = await inquirer.prompt({
type: 'list',
name: 'table',
choices: stackTables,
message: 'DynamoDB Stack Table'
})
if (!table) {
process.exit(0)
}
stackTableName = table
}
} else {
stackTableName = stackTables[0]
}
const stage = stackTableName.match(/dynamodb-(.*)-DynamoDBStackTable/)[1]
const { email } = await inquirer.prompt({
type: 'input',
message: 'Email',
name: 'email',
validate(value) {
return value && !value.includes('@') ? 'no @' : true
}
})
if (!email) {
console.error('\u001B[91mNo email\u001B[0m')
process.exit(0)
}
const { addRoles } = await inquirer.prompt({
type: 'confirm',
message: 'Add roles',
default: true,
name: 'addRoles'
})
const { roles } =
(addRoles &&
(await inquirer.prompt({
type: 'checkbox',
message: 'Roles',
name: 'roles',
choices: Object.values(roleMapping)
.map((name) => ({ name }))
.filter(({ name }) => name !== 'notauthorized'),
validate(answer) {
if (answer.length === 0) {
return 'You need to select at least one role'
}
return true
}
}))) ??
{}
const roleEntries = Object.entries(roleMapping)
const roleSet =
addRoles &&
new Set(
(roles.includes('super')
? Object.keys(roleMapping).map(Number).filter(Boolean)
: roles.map((role) =>
Number(
roleEntries.find(([, value]) => value === role.toLowerCase())[0]
)
)
).filter(Boolean)
)
const hash = crypto.createHash('sha512').update(email).digest('hex')
await dynamodb.send(
new UpdateCommand({
TableName: stackTableName,
Key: {
pk: `user#${hash}`,
sk: `user#${hash}`
},
UpdateExpression: 'set #role = :role, #type = :type, #email = :email',
ExpressionAttributeNames: {
'#role': 'role',
'#type': 'type',
'#email': 'email'
},
ExpressionAttributeValues: {
':role': roleSet,
':type': 'user',
':email': email
},
ReturnValues: 'NONE'
})
)
console.log(
`✨ user upserted to stage ${stage} ${JSON.stringify(
{
id: `user#{hash}`,
...(email && { email }),
...(addRoles && {
roles: [...roleSet]
})
},
undefined,
2
)}✨`
)
async function getPullRequestRef() {
const run = promisify(exec)
try {
const { stdout } = await run(`
git ls-remote --refs origin | \
grep $(git rev-parse @{push}) | \
grep -oE 'pull/[0-9]+' | \
sed 's|^pull/||g'`)
const ref = stdout.replaceAll(/[\n\r]/g, '')
if (ref) {
return Number(ref)
}
} catch {
// eslint-disable-next-line no-empty
}
}