-
Notifications
You must be signed in to change notification settings - Fork 215
/
server.js
123 lines (104 loc) · 3.53 KB
/
server.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
const fs = require('fs')
const bodyParser = require('body-parser')
const jsonServer = require('json-server')
const jwt = require('jsonwebtoken')
const server = jsonServer.create()
const router = jsonServer.router('./database.json')
const userdb = JSON.parse(fs.readFileSync('./users.json', 'UTF-8'))
server.use(bodyParser.urlencoded({extended: true}))
server.use(bodyParser.json())
server.use(jsonServer.defaults());
const SECRET_KEY = '123456789'
const expiresIn = '1h'
// Create a token from a payload
function createToken(payload){
return jwt.sign(payload, SECRET_KEY, {expiresIn})
}
// Verify the token
function verifyToken(token){
return jwt.verify(token, SECRET_KEY, (err, decode) => decode !== undefined ? decode : err)
}
// Check if the user exists in database
function isAuthenticated({email, password}){
return userdb.users.findIndex(user => user.email === email && user.password === password) !== -1
}
// Register New User
server.post('/auth/register', (req, res) => {
console.log("register endpoint called; request body:");
console.log(req.body);
const {email, password} = req.body;
if(isAuthenticated({email, password}) === true) {
const status = 401;
const message = 'Email and Password already exist';
res.status(status).json({status, message});
return
}
fs.readFile("./users.json", (err, data) => {
if (err) {
const status = 401
const message = err
res.status(status).json({status, message})
return
};
// Get current users data
var data = JSON.parse(data.toString());
// Get the id of last user
var last_item_id = data.users[data.users.length-1].id;
//Add new user
data.users.push({id: last_item_id + 1, email: email, password: password}); //add some data
var writeData = fs.writeFile("./users.json", JSON.stringify(data), (err, result) => { // WRITE
if (err) {
const status = 401
const message = err
res.status(status).json({status, message})
return
}
});
});
// Create token for new user
const access_token = createToken({email, password})
console.log("Access Token:" + access_token);
res.status(200).json({access_token})
})
// Login to one of the users from ./users.json
server.post('/auth/login', (req, res) => {
console.log("login endpoint called; request body:");
console.log(req.body);
const {email, password} = req.body;
if (isAuthenticated({email, password}) === false) {
const status = 401
const message = 'Incorrect email or password'
res.status(status).json({status, message})
return
}
const access_token = createToken({email, password})
console.log("Access Token:" + access_token);
res.status(200).json({access_token})
})
server.use(/^(?!\/auth).*$/, (req, res, next) => {
if (req.headers.authorization === undefined || req.headers.authorization.split(' ')[0] !== 'Bearer') {
const status = 401
const message = 'Error in authorization format'
res.status(status).json({status, message})
return
}
try {
let verifyTokenResult;
verifyTokenResult = verifyToken(req.headers.authorization.split(' ')[1]);
if (verifyTokenResult instanceof Error) {
const status = 401
const message = 'Access token not provided'
res.status(status).json({status, message})
return
}
next()
} catch (err) {
const status = 401
const message = 'Error access_token is revoked'
res.status(status).json({status, message})
}
})
server.use(router)
server.listen(8000, () => {
console.log('Run Auth API Server')
})