forked from fourTheorem/slic-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cognito-util.js
87 lines (71 loc) · 2.27 KB
/
cognito-util.js
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
'use strict'
const awscred = require('awscred')
const AWS = require('aws-sdk')
const jwt = require('jsonwebtoken')
const chance = require('chance').Chance()
const { generateEmailAddress } = require('test-common/real-email-config')
const { loadBackendConfig } = require('./backend-config')
const generatePassword = () => `${chance.string({ length: 10 })}!Aa0`
const awsRegion = awscred.loadRegionSync()
const cognitoServiceProvider = new AWS.CognitoIdentityServiceProvider({ region: awsRegion })
async function createUser () {
const email = generateEmailAddress()
const password = generatePassword()
const backendConfig = await loadBackendConfig()
const createRequest = {
UserPoolId: backendConfig.userPoolId,
Username: email,
MessageAction: 'SUPPRESS',
TemporaryPassword: password,
UserAttributes: [{ Name: 'email', Value: email }]
}
await cognitoServiceProvider.adminCreateUser(createRequest).promise()
const authRequest = {
AuthFlow: 'ADMIN_NO_SRP_AUTH',
UserPoolId: backendConfig.userPoolId,
ClientId: backendConfig.userPoolClientId,
AuthParameters: {
USERNAME: email,
PASSWORD: password
}
}
const authResponse = await cognitoServiceProvider
.adminInitiateAuth(authRequest)
.promise()
const challengeRequest = {
UserPoolId: backendConfig.userPoolId,
ClientId: backendConfig.userPoolClientId,
ChallengeName: authResponse.ChallengeName,
Session: authResponse.Session,
ChallengeResponses: {
USERNAME: email,
NEW_PASSWORD: generatePassword()
}
}
const challengeResponse = await cognitoServiceProvider
.adminRespondToAuthChallenge(challengeRequest)
.promise()
const { 'cognito:username': userId } = jwt.decode(
challengeResponse.AuthenticationResult.IdToken
)
const user = {
userId,
email,
username: email,
accessToken: challengeResponse.AuthenticationResult.AccessToken,
idToken: challengeResponse.AuthenticationResult.IdToken
}
return user
}
async function deleteUser (user) {
const backendConfig = await loadBackendConfig()
const deleteRequest = {
UserPoolId: backendConfig.userPoolId,
Username: user.email
}
await cognitoServiceProvider.adminDeleteUser(deleteRequest).promise()
}
module.exports = {
createUser,
deleteUser
}