-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter-auth.js
49 lines (39 loc) · 1.39 KB
/
router-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
const router = require('express').Router();
const Joi = require('joi');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const appUser = require('./db/models/app_user');
const auth = require('./authenticator');
const config = require('./config');
const appUserSchema = Joi.object({
username: Joi.string().required(),
password: Joi.string().required(),
});
router.post('/signUp', async (req, res, next) => {
try {
const { username, password } = req.body;
Joi.assert({ username, password }, appUserSchema);
const hashedPassword = bcrypt.hashSync(password, 12);
await appUser.insert({ username, password: hashedPassword });
const token = jwt.sign({ username }, config.jwt);
res.header({ Authorization: `Bearer ${token}` }).send('Signed up!');
} catch (error) {
next(error);
}
});
router.post('/signIn', async (req, res, next) => {
try {
const { username, password } = req.body;
Joi.assert({ username, password }, appUserSchema);
const response = await appUser.read(username);
if (!bcrypt.compareSync(password, response[0].password)) throw Error('Invalid credentials!');
const token = jwt.sign({ username }, config.jwt);
res.header({ Authorization: `Bearer ${token}` }).send('Signed in!');
} catch (error) {
next(error);
}
});
router.get('/signOut', auth, (req, res) => {
res.send('Signed out!');
});
module.exports = router;