-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
90 lines (74 loc) · 2.02 KB
/
index.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
var express = require('express');
var jwt = require('jsonwebtoken');
const app = express();
require("dotenv").config();
const fs = require("fs");
const bodyParser = require('body-parser');
const importdata = require("./users.json")
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.get('/api', (req,res) =>{
res.json({
text:'Demo API for Signup and Login flow with AUTH Token'
});
});
// app.post('/api/login', (req,res) => {
// const user = { name : "Apoorv" };
// const token = jwt.sign({ user},process.env.JWT_KEY);
// res.json({
// token: token
// })
// });
app.post('/api/login', ensureToken,(req,res) => {
jwt.verify(req.token,process.env.JWT_KEY, function(err,data){
if(err){
res.status(400);
// res.send(400).json({message:"UnAuthorize Access"});
}else{
res.json({
text: 'Welcome',
data : data,
});
}
})
});
app.post('/api/signup', (req,res) => {
const udata={
password : req.body.password,
user : req.body.user
}
const token = jwt.sign({udata},process.env.JWT_KEY);
res.json({
token: token
})
});
app.post('/api/updatepassword',(req,res)=> {
const oldpwd = req.body.oldpassword;
const newpwd = req.body.newpassword;
const usr = req.body.user;
const token = jwt.sign({newpwd,usr},process.env.JWT_KEY);
res.json({
token: token,
newpassword:newpwd,
user:usr
})
})
//Get all User Route
app.get('/getusers',(req,res) =>{
res.send(importdata);
res.status(200)
})
function ensureToken (req,res,next) {
const bearerHeader = req.headers.authorization;
if(typeof bearerHeader !== 'undefined'){
const bearer = bearerHeader.split(" ");
req.token = bearer[1];
console.log(bearer)
next();
}else{
res.sendStatus(403);
}
}
app.listen(3000, function(){
console.log('App listening on port 3000!');
});