-
Notifications
You must be signed in to change notification settings - Fork 268
/
user-routes.js
113 lines (89 loc) · 2.69 KB
/
user-routes.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
var express = require('express'),
_ = require('lodash'),
config = require('./config'),
jwt = require('jsonwebtoken');
var app = module.exports = express.Router();
// XXX: This should be a database of users :).
var users = [{
id: 1,
username: 'gonto',
password: 'gonto'
}];
function createIdToken(user) {
return jwt.sign(_.omit(user, 'password'), config.secret, { expiresIn: 60*60*5 });
}
function createAccessToken() {
return jwt.sign({
iss: config.issuer,
aud: config.audience,
exp: Math.floor(Date.now() / 1000) + (60 * 60),
scope: 'full_access',
sub: "lalaland|gonto",
jti: genJti(), // unique identifier for the token
alg: 'HS256'
}, config.secret);
}
// Generate Unique Identifier for the access token
function genJti() {
let jti = '';
let possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < 16; i++) {
jti += possible.charAt(Math.floor(Math.random() * possible.length));
}
return jti;
}
function getUserScheme(req) {
var username;
var type;
var userSearch = {};
// The POST contains a username and not an email
if(req.body.username) {
username = req.body.username;
type = 'username';
userSearch = { username: username };
}
// The POST contains an email and not an username
else if(req.body.email) {
username = req.body.email;
type = 'email';
userSearch = { email: username };
}
return {
username: username,
type: type,
userSearch: userSearch
}
}
app.post('/users', function(req, res) {
var userScheme = getUserScheme(req);
if (!userScheme.username || !req.body.password) {
return res.status(400).send("You must send the username and the password");
}
if (_.find(users, userScheme.userSearch)) {
return res.status(400).send("A user with that username already exists");
}
var profile = _.pick(req.body, userScheme.type, 'password', 'extra');
profile.id = _.max(users, 'id').id + 1;
users.push(profile);
res.status(201).send({
id_token: createIdToken(profile),
access_token: createAccessToken()
});
});
app.post('/sessions/create', function(req, res) {
var userScheme = getUserScheme(req);
if (!userScheme.username || !req.body.password) {
return res.status(400).send("You must send the username and the password");
}
var user = _.find(users, userScheme.userSearch);
if (!user) {
return res.status(401).send("The username or password don't match");
}
if (user.password !== req.body.password) {
return res.status(401).send("The username or password don't match");
}
res.status(201).send({
id_token: createIdToken(user),
access_token: createAccessToken()
});
});