This repository has been 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 pathcreateLegacyUserApi.js
90 lines (82 loc) · 2.39 KB
/
createLegacyUserApi.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
const express = require('express')
const bcrypt = require('bcrypt')
module.exports = function createLegacyUserApi ({
legacyUserApiKey: apiKey,
legacyUserRepository,
playerRepository
}) {
const router = express.Router()
router.use(require('body-parser').urlencoded({ extended: false }))
router.use(function (req, res, next) {
if (req.body.apiKey !== apiKey) {
res.status(400).json({ error: 'Invalid API key.' })
return
}
next()
})
router.post('/check', function (req, res, next) {
const playerIdOrEmail = String(req.body.playerIdOrEmail)
const password = String(req.body.password)
Promise.resolve(authenticate(playerIdOrEmail, password))
.then((user) => {
if (!user) {
res.status(401).json({ error: 'Unauthenticated' })
return
}
return findOrCreatePlayer(user.username)
.then((player) => {
res.json(formatResult(user, player))
})
})
.catch(next)
})
router.post('/get', function (req, res, next) {
const playerIdOrEmail = String(req.body.playerIdOrEmail)
findLegacyUser(playerIdOrEmail)
.then((user) => {
if (!user) {
res.status(404).json({ error: 'Not found' })
return
}
return findOrCreatePlayer(user.username)
.then((player) => {
res.json(formatResult(user, player))
})
})
.catch(next)
})
return router
function formatResult (user, player) {
return {
_id: user._id,
username: player._id,
email: user.email,
emailVerified: user.emailVerified,
createdAt: user.createdAt
}
}
function findOrCreatePlayer (name) {
return playerRepository.findByName(name)
.then(foundPlayer => {
return foundPlayer || playerRepository.register(name)
.then(() => playerRepository.findByName(name))
})
}
function findLegacyUser (playerIdOrEmail) {
return Promise.resolve(legacyUserRepository.findByEmail(playerIdOrEmail))
.then((user) => user ||
playerRepository.findById(playerIdOrEmail).then((player) => player &&
legacyUserRepository.findByUsername(player.playerName)
)
)
}
function authenticate (playerIdOrEmail, password) {
return findLegacyUser(playerIdOrEmail)
.then((user) => {
if (!user) return false
return bcrypt.compare(password, user.hashedPassword).then((result) =>
result && user
)
})
}
}