-
Notifications
You must be signed in to change notification settings - Fork 0
/
expressWithAuthentication.js
97 lines (81 loc) · 2.65 KB
/
expressWithAuthentication.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
const express = require('express');
const jwt = require('jsonwebtoken');
const session = require('express-session')
let users = []
//Function to check if the user exists
const doesExist = (username)=>{
let userswithsamename = users.filter((user)=>{
return user.username === username
});
if(userswithsamename.length > 0){
return true;
} else {
return false;
}
}
//Function to check if the user is authenticated
const authenticatedUser = (username,password)=>{
let validusers = users.filter((user)=>{
return (user.username === username && user.password === password)
});
if(validusers.length > 0){
return true;
} else {
return false;
}
}
const app = express();
app.use(express.json());
app.use(session({secret:"fingerpint"}))
app.use("/auth", function auth(req,res,next){
if(req.session.authorization) { //get the authorization object stored in the session
token = req.session.authorization['accessToken']; //retrieve the token from authorization object
jwt.verify(token, "access",(err,user)=>{ //Use JWT to verify token
if(!err){
req.user = user;
next();
}
else{
return res.status(403).json({message: "User not authenticated"})
}
});
} else {
return res.status(403).json({message: "User not logged in"})
}
});
app.post("/login", (req,res) => {
const username = req.query.username;
const password = req.query.password;
if (!username || !password) {
return res.status(404).json({message: "Error logging in"});
}
if (authenticatedUser(username,password)) {
let accessToken = jwt.sign({
data: password
}, 'access', { expiresIn: 60 * 60 });
req.session.authorization = {
accessToken,username
}
return res.status(200).send("User successfully logged in");
} else {
return res.status(208).json({message: "Invalid Login. Check username and password"});
}
});
app.post("/register", (req,res) => {
const username = req.query.username;
const password = req.query.password;
if (username && password) {
if (!doesExist(username)) {
users.push({"username":username,"password":password});
return res.status(200).json({message: "User successfully registred. Now you can login"});
} else {
return res.status(404).json({message: "User already exists!"});
}
}
return res.status(404).json({message: "Unable to register user."});
});
app.get("/auth/get_message", (req,res) => {
return res.status(200).json({message: "Hello, You are an authenticated user. Congratulations!"});
})
const PORT =5000;
app.listen(PORT,()=>console.log("Server is running"));