This repository was archived by the owner on Dec 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauthenticationFlow.js
97 lines (81 loc) · 2.52 KB
/
authenticationFlow.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
88
89
90
91
92
93
94
95
96
97
exports.loginByUsernamePassword =
function * loginByUsernamePassword (username, password, {
log = (message) => console.log('[loginByUsernamePassword]', message),
// (usernameOrEmail, password) => Promise
// - If result contain `idToken` property => OK.
// - Otherwise, invalid username or password.
usernamePasswordLogin,
// (username) => Promise
// - If result contain `playerId` property => OK.
// - Otherwise, player not found.
resolvePlayerId,
// (idToken) => Promise
// - Result should contain `playerId` and `playerName` property.
ensureLink
}) {
{
const { idToken } = yield * obtainIdToken()
log('Loading profile...')
yield ensureLink(idToken)
return { idToken }
}
function * obtainIdToken () {
let triedEmail = false
if (/@/.test(username)) {
log('Authenticating using email...')
const email = username
const { idToken } = yield usernamePasswordLogin(email, password)
if (idToken) {
log('Authenticated using email.')
return { idToken }
}
}
log('Resolving player...')
const { playerId } = yield resolvePlayerId(username)
if (!playerId) {
throw new Error(triedEmail
? 'Invalid email or password'
: 'Player not registered'
)
}
log('Authenticating player...')
const { idToken } = yield usernamePasswordLogin(playerId, password)
if (!idToken) {
throw new Error('Invalid password')
}
return { idToken }
}
}
exports.signUp =
function * signUp (username, email, password, {
log = (message) => console.log('[signUp]', message),
// (username, email, password) => Promise
// - Result should always contain `idToken` property.
// - Otherwise, it should reject (throw).
userSignUp,
// (playerId) => Promise
// - Result should be a string.
reservePlayerId,
// (playerId) => Promise
// - Result is a boolean.
checkPlayerNameAvailability,
// (idToken) => Promise
// - Result should contain `playerId` and `playerName` property.
ensureLink
}) {
log('Checking player name availability...')
const available = yield checkPlayerNameAvailability(username)
if (!available) {
throw new Error('Player name already taken')
}
log('Registering player name...')
const playerId = yield reservePlayerId(username)
log('Creating account...')
const { idToken } = yield userSignUp(playerId, email, password)
if (!idToken) {
throw new Error('Cannot sign up (unknown error)')
}
log('Linking account...')
yield ensureLink(idToken)
return { idToken }
}