-
Notifications
You must be signed in to change notification settings - Fork 0
/
Authserver.js
100 lines (89 loc) · 2.05 KB
/
Authserver.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
var express = require('express');
var app=express();
var bodyParser= require('body-parser');
var jwt=require('jsonwebtoken');
const secret = 'secret';
var users=[
{
name:"Alice",
password:"Alice@01"
},
{
name:"Bob",
password:"Bob@11"
}
];
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static('./'));
app.get('/', (req,res)=>{
res.sendFile('index.html');
});
app.post('/login',(req,res)=>{
var message;
for(var user of users){
if(user.name!=req.body.name){
message="Wrong Name";
}else{
if(user.password!=req.body.password){
message="Wrong Password";
break;
}
else{
var token=jwt.sign(user,secret,{ expiresIn: '2m' });
console.log(token);
message="Login Successful";
break;
}
}
}
if(token){
res.status(200).json({
message,
token
});
}
else{
res.status(403).json({
message
});
}
});
app.use((req, res, next)=>{
// check header or url parameters or post parameters for token
console.log(req.body);
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if(token){
console.log("token");
jwt.verify(token,secret,(err,decod)=>{
if(err){
res.status(403).json({
message:"Wrong Token"
});
}
else{
console.log("success");
req.decoded=decod;
next();
}
});
}
else{
res.status(403).json({
message:"No Token"
});
}
});
app.post('/getusers',(req,res)=>{
var user_list=[];
console.log("here");
users.forEach((user)=>{
user_list.push({"name":user.name});
})
res.send(JSON.stringify({users:user_list}));
});
app.listen(3000, function(){
console.log('listening on port 3000');
});