-
Notifications
You must be signed in to change notification settings - Fork 136
/
Copy pathuser.service.js
35 lines (26 loc) · 924 Bytes
/
user.service.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
const config = require('config.json');
const jwt = require('jsonwebtoken');
// users hardcoded for simplicity, store in a db for production applications
const users = [{ id: 1, username: 'test', password: 'test', firstName: 'Test', lastName: 'User' }];
module.exports = {
authenticate,
getAll
};
async function authenticate({ username, password }) {
const user = users.find(u => u.username === username && u.password === password);
if (!user) throw 'Username or password is incorrect';
// create a jwt token that is valid for 7 days
const token = jwt.sign({ sub: user.id }, config.secret, { expiresIn: '7d' });
return {
...omitPassword(user),
token
};
}
async function getAll() {
return users.map(u => omitPassword(u));
}
// helper functions
function omitPassword(user) {
const { password, ...userWithoutPassword } = user;
return userWithoutPassword;
}