-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
111 lines (94 loc) · 2.29 KB
/
index.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
const cryptoJs = require("crypto-js");
const jwt = require("jsonwebtoken");
const STORAGE_KEY = "mock-amplify-auth.state";
const USER_ID_PREFIX = "mock-auth-";
let authState;
try {
authState = JSON.parse(window.localStorage.getItem(STORAGE_KEY)) || {};
} catch (err) {
authState = {};
}
Auth = {
signUp,
signIn,
currentSession,
confirmSignUp,
signOut,
resendSignUp,
extractEmail,
forgotPassword,
forgotPasswordSubmit
};
function signUp(email) {
updateState({ email, loggedIn: false });
return timerPromise(1200);
}
function signIn(email) {
updateState({ email, session: createSession({ email }), loggedIn: true });
return timerPromise(700);
}
function currentSession() {
return timerPromise(400, !!authState.loggedIn, authState.session);
}
function confirmSignUp() {
return timerPromise(400);
}
function signOut() {
updateState({ email: null, loggedIn: false, session: null });
return timerPromise(100);
}
function resendSignUp() {
return timerPromise(100);
}
function updateState(newState) {
Object.assign(authState, newState);
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(authState));
}
function timerPromise(ms, success = true, arg) {
if (!success && !arg) {
arg = new Error();
}
return new Promise((resolve, reject) =>
setTimeout(() => (success ? resolve : reject)(arg), ms)
);
}
function extractEmail(userId) {
return Buffer.from(
userId.substring(USER_ID_PREFIX.length),
"base64"
).toString();
}
function forgotPassword(email) {
updateState({ email, loggedIn: false });
return timerPromise(400);
}
function forgotPasswordSubmit() {
return timerPromise(400);
}
function createSession({ email }) {
const timeS = Math.floor(Date.now() / 1000);
const cognitoUsername = `${USER_ID_PREFIX}${Buffer.from(email).toString(
"base64"
)}`;
const idTokenPayload = {
sub: cognitoUsername,
token_use: "id",
email_verified: true,
aud: "mock-auth",
auth_time: timeS,
iat: timeS,
exp: timeS + 100000,
iss: "https://cognito-idp.local.amazonaws.com/local_mock-auth",
"cognito:username": cognitoUsername,
email
};
const idToken = {
jwtToken: jwt.sign(idTokenPayload, "mock-auth-secret"),
payload: idTokenPayload
};
return {
idToken,
clockDrift: 0
};
}
module.exports = Auth;