-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthServer.js
172 lines (143 loc) · 5.47 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
const express = require("express");
const bcrypt = require("bcrypt");
const crypto = require("crypto");
const mysql = require("mysql");
const app = new express();
app.use(express.json());
const port = 3000;
// Create connection pool
const pool = mysql.createPool({
host : 'localhost',
user : 'root',
password : '',
database : 'auth'
});
/* Sign up */
app.post("/signup", async(req,res) => {
try {
const { username , password } = req.body;
pool.getConnection((err, connection) => {
if(err) {
console.log(`Error connecting MySQL : ${err}`);
return;
}
console.log("Mysql connected as id : " + connection.threadId);
// Check user already exists
const sql = `select username from user_session where username = '${username}'`;
connection.query(sql, async(err,rows) =>{
try{
if(err) {
console.log(err);
return;
}
if(rows.length ===0 ) { //Create new user
// Generate a new salt for every user
const salt = await bcrypt.genSalt();
// Create password hash
const hashedPassword = await bcrypt.hash(req.body.password,salt);
const user = {"username": req.body.username,"password": hashedPassword};
const sql = "insert into user_session (username,user_password) values('" + username + "','" + hashedPassword + "')";
connection.query(sql, (err,rows) =>{
if(err) {
console.log(err);
return;
}
console.log("User created!");
res.status(201).send(user);
});
}
else{
console.log("User alreday exists");
res.send({"error": "User already exists!"});
}
}
catch {
res.send({"error": "Unable to access data"});
}
});
});
}
catch {
res.status(500).send();
}
});
// Login route
app.post("/login", async (req, res) => {
try {
const { username,password } = req.body;
if(username) {
pool.getConnection((err, connection) => {
if(err) {
console.error(err);
return;
}
const sql =`select * from user_session where username='${username}'`;
connection.query(sql, async(err,rows) =>{
if(err) {
console.log(err);
return;
}
if(rows.length ===0) {
res.status(400).send("Username not found!");
return;
}
// Username found Compare the password now
const saltedPassword = rows[0].user_password;
const compareResult = await bcrypt.compare(password, saltedPassword);
if(compareResult === true) {
// Generate new SessionId
const sessionId = await randomSessionId();
//Associate sessionId with the user by updating record
const sql= `update user_session set sessionId ='${sessionId}' where username='${username}'`
connection.query(sql, (err,rows) => {
if(err) {
console.error(err);
}
else {
res.setHeader("set-cookie", [`SESSION_ID=${sessionId}; httponly; samesite=lax`]);
res.send({"success": "Logged in successfully!"});
}
});
}
else {
res.send("Error : password incorrect !");
}
});
});
}
else {
res.status(400).send("Username is required");
}
}
catch (ex){
console.error(ex);
}
});
app.post("/logout", async (req,res) => {
const sessionId = req.cookies.SESSION_ID;
if(sessionId) {
pool.getConnection((err, connection) => {
if(err) {
console.error(err);
}
else
{
const sql=`update user_session set sessionId = null where sessionId = '${sessionId}'`
connection.query(sql, (err,rows) => {
if(err) {
console.error(err);
res.send({"error" : err});
}
else {
res.send({"success": "logged out successfully"})
}
});
}
});
}
});
app.listen(port,() => {console.log(`Authentication server running at port ${port}`)});
// Function to Gneretae random string for session id
async function randomSessionId() {
return crypto.randomBytes(64).toString('hex');
}