-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
77 lines (60 loc) · 2.04 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
76
77
const express = require('express');
const app = express();
const port = 3000;
const session = require('express-session');
const SQLiteStore = require('connect-sqlite3')(session);
const { join } = require('path');
const crypto = require('crypto');
// Add authentication module
const { passport } = require('./modules/auth');
// Add database module
const { db } = require('./modules/db');
// Middleware
app.use(express.json());
app.use(express.static(join(__dirname, 'public')));
app.use(session({
secret: 'express-postgresql-auth',
resave: false,
saveUninitialized: false,
store: new SQLiteStore({ db: 'sessions.db', dir: './var/db' })
}));
app.use(passport.authenticate('session'));
app.post("/auth/login", function (req, res, next) {
passport.authenticate("local", (err, user, info) => {
if (err) return next(err);
if (!user) return res.status(401).json({ message: info.message });
req.login(user, (loginErr) => {
if (loginErr) return next(loginErr);
res.json({ message: "Login successful", user });
});
})(req, res, next);
});
app.post("/auth/signout", function (req, res) {
req.logout(function (err) {
if (err) { return next(err); }
res.json({ message: "Signout successful" });
})
});
app.post("/auth/signup", function (req, res, next) {
const salt = crypto.randomBytes(16);
const { username, password } = req.body;
const userId = Date.now();
crypto.pbkdf2(password, salt, 310000, 32, 'sha256', async function (err, hashedPassword) {
if (err) { return next(err); }
// Convert params to JSON
const hashedPasswordJson = JSON.stringify(hashedPassword);
const saltJson = JSON.stringify(salt);
await db.users.insert(userId, username, hashedPasswordJson, saltJson, function (err, user) {
if (err) { return res.json({ message: 'Failed to sign up' }) };
if (user) {
return res.json({ user: user });
}
})
})
});
app.get('/', async (req, res) => {
res.send('Hello World');
})
app.listen(port, () => {
console.log(`App listening on port http://localhost:${port}`);
})