-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
75 lines (59 loc) · 2.92 KB
/
app.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
const express = require('express');
const http = require('http');
const bcrypt = require('bcrypt');
const path = require("path");
const bodyParser = require('body-parser');
const users = require('./data').userDB;
const app = express();
const server = http.createServer(app);
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname,'./public')));
app.get('/',(req,res) => {
res.sendFile(path.join(__dirname,'./public/registration.html'));
});
app.post('/register', async (req, res) => {
try{
let foundUser = users.find((data) => req.body.email === data.email);
if (!foundUser) {
let hashPassword = await bcrypt.hash(req.body.password, 10);
let newUser = {
id: Date.now(),
username: req.body.username,
email: req.body.email,
password: hashPassword,
};
users.push(newUser);
console.log('User list', users);
res.send("<div align ='center' style = 'padding-top: 2rem'><h2>Registration successful !</h2></div><br><br><div align='center'><a type = 'button' class='btn btn-primary btn-lg btn-block' href='./login.html'>Login</a></div>");
} else {
res.send("<div align ='center' style = 'padding-top: 2rem'><h2>Email already used! </h2></div><br><br><div align='center'><a type = 'button' class='btn btn-primary btn-lg btn-block' href='./registration.html'>Register again</a></div>");
}
} catch{
res.send("Internal server error");
}
});
app.post('/login', async (req, res) => {
try{
let foundUser = users.find((data) => req.body.email === data.email);
if (foundUser) {
let submittedPass = req.body.password;
let storedPass = foundUser.password;
const passwordMatch = await bcrypt.compare(submittedPass, storedPass);
if (passwordMatch) {
let usrname = foundUser.username;
res.send(`<div align ='center'><h2>login successful</h2></div><br><br><br><div align ='center'><h3>Hello ${usrname}</h3></div><br><br><div align='center'><a href='./login.html'>logout</a></div>`);
} else {
res.send("<div align ='center'><h2>Invalid email or password</h2></div><br><br><div align ='center'><a href='./login.html'>Login again</a></div>");
}
}
else {
let fakePass = `$2b$$10$ifgfgfgfgfgfgfggfgfgfggggfgfgfga`;
await bcrypt.compare(req.body.password, fakePass);
res.send("<div align ='center'><h2>Invalid email or password</h2></div><br><br><div align='center'><a href='./login.html'>Login again<a><div>");
}
} catch{
res.send("Internal server error");
}
});
server.listen(5501, '127.0.0.1');
console.log("server is listening on port: 5501");