-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
188 lines (167 loc) · 5.84 KB
/
auth.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
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
const crypto = require('crypto')
const jwt = require('jsonwebtoken')
const { encrypt, decrypt } = require('./crypto');
function genRandomString(length) {
return crypto.randomBytes(Math.ceil(length / 2)).toString('hex').slice(0, length);
};
function sha512(password, salt) {
const hash = crypto.createHmac('sha512', salt);
hash.update(password);
return hash.digest('hex');
};
function saltHashPassword(password) {
const salt = genRandomString(16);
const passwordHash = sha512(password, salt);
return {
salt,
passwordHash
}
}
function getToken(email) {
return jwt.sign({ email, timestamp: Date.now() }, 'secret', { algorithm: 'HS256' });
}
const register = async function ({ req, res, db }) {
const { email, password } = req.body
if (!email || !password) {
return res.status(400).send({})
}
// 要先確認這個 email 沒有註冊過
let emailExist = true
try {
await db.get(email)
} catch (err) {
if (err && err.type === 'NotFoundError') {
emailExist = false
}
}
if (emailExist) {
return res.status(400).send({ message: 'AccountAlreadyExist' })
}
const { salt, passwordHash } = saltHashPassword(password);
const acToken = genRandomString(16)
const actExpired = Date.now() + 60 * 60 * 24 * 2 * 1000 // 2天過期
const hash = encrypt(`${email}:${acToken}`);
// NOTE: 此處應該寄一封 email 給使用者, 附上啟用帳號的連結
// 目前先把連結印出來手動在瀏覽器輸入
console.log('Click this URL:')
console.log(`http://localhost:3000/activateAccount/${hash}`)
await db.put(email, JSON.stringify({ salt, passwordHash, acToken, actExpired }))
return res.status(200).send({ message: 'OK' });
}
const activateAccount = async function ({ req, res, db }) {
const { token } = req.body
const content = decrypt(token)
console.log('content = ', content)
const s = content.split(':')
if (s.length !== 2) {
return res.status(400).send({ message: 'InvalidToken' });
} else {
const email = s[0]
const acToken = s[1]
try {
const data = await db.get(email)
const jsonData = JSON.parse(data)
const { acToken: acTokenInDb, actExpired, ...userData } = jsonData
// 把收到的 acToken 和資料庫裡的 token 比對, 並確認 token 尚未過期
if (acToken !== acTokenInDb) {
return res.status(400).send({ message: 'InvalidToken' });
} else if (acTokenInDb < Date.now()) {
return res.status(400).send({ message: 'TokenExpired' });
}
// 移除 db 裡的 acToken
await db.put(email, JSON.stringify({ ...userData}))
return res.status(200).send({ message: 'OK' });
} catch (err) {
console.log(err)
return res.status(400).send({ message: 'InvalidToken' });
}
}
}
const login = async function ({ req, res, db }) {
const { email, password } = req.body
try {
const data = await db.get(email)
const jsonData = JSON.parse(data)
const { acToken, salt, passwordHash, ...userData } = jsonData
if (acToken) {
return res.status(400).send({ message: 'NotActivatedAccount' });
}
const passwordHashFromClient = sha512(password, salt);
if (passwordHash === passwordHashFromClient) {
const token = getToken(email)
return res.json({ ...userData, access: token })
} else {
return res.status(401).send({ message: 'WrongPassword' });
}
} catch (err) {
if (err.type === 'NotFoundError') {
return res.status(401).send({ message: 'UserNotFound' });
}
}
}
const getResetPasswordToken = async function ({ req, res, db }) {
const { email } = req.body
console.log(email)
try {
const data = await db.get(email)
const jsonData = JSON.parse(data)
console.log(JSON.stringify(jsonData, null, 4))
const { acToken } = jsonData
// 如果帳號還沒啟用, 不可以重設密碼
if (acToken) {
return res.status(400).send({ message: 'NotActivatedAccount' });
}
const rpToken = genRandomString(16)
const rptExpired = Date.now() + 60 * 60 * 24 * 2 * 1000 // 2天過期
await db.put(email, JSON.stringify({ ...jsonData, rpToken, rptExpired }))
const hash = encrypt(`${email}:${rpToken}`);
// NOTE: 此處應該寄一封 email 給使用者, 附上重設密碼用的連結
// 目前先把連結印出來手動在瀏覽器輸入
console.log('Click this URL:')
console.log(`http://localhost:3000/resetPassword/${hash}`)
return res.status(200).send({ message: 'OK' });
} catch (err) {
console.log(err)
if (err.type === 'NotFoundError') {
return res.status(401).send({ message: 'UserNotFound' });
}
}
}
const resetPassword = async function ({ req, res, db }) {
const { password, token } = req.body
const content = decrypt(token)
const s = content.split(':')
if (s.length !== 2) {
return res.status(400).send({ message: 'InvalidToken' });
} else {
const email = s[0]
const rpToken = s[1]
try {
const data = await db.get(email)
const jsonData = JSON.parse(data)
const { rpToken: rpTokenInDb, rptExpired, ...userData } = jsonData
// 把收到的 rpToken 和資料庫裡的 token 比對, 並確認 token 尚未過期
if (rpToken !== rpTokenInDb) {
return res.status(400).send({ message: 'InvalidToken' });
} else if (rptExpired < Date.now()) {
return res.status(400).send({ message: 'TokenExpired' });
}
if (password) {
// 更新 db 裡的 salt 和 password hash
const { salt, passwordHash } = saltHashPassword(password);
await db.put(email, JSON.stringify({ ...userData, salt, passwordHash }))
}
return res.status(200).send({ message: 'OK' });
} catch (err) {
console.log(err)
return res.status(400).send({ message: 'InvalidToken' });
}
}
}
module.exports = {
register,
activateAccount,
login,
getResetPasswordToken,
resetPassword,
}