-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
88 lines (67 loc) · 2.19 KB
/
server.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
// This is going to be our server page. Backend ONLY!
const express = require('express');
const app = express();
//login posts and bcrypt, hashing the passwords
require('dotenv').config()
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')
app.use(express.json());
app.get('/posts', authenticateToken, (req, res) => {
res.json(posts.filter(post => post.username === req.user.name))
})
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[1]
if (token == null) return res.sendStatus(401)
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403)
req.user = user
next()
})
}
app.post('/api./users', async (req, res) => {
try {
const salt= await bcrypt.genSalt()
const hashedPassword = await bcrypt.hash(req.body.password, salt)
console.log(salt)
console.log(hashedPassword)
const user = { name: req.body.name, password: hashedPassword}
users.push(user)
res.status(201).send()
} catch {
res.status(500).send()
}
})
app.post('users/login', async (req, res) => {
const user = users.find(user => user.name = req.body.name)
if (user == null) {
return res.status(400).send('Cannot find user')
}
try {
if (await bcrypt.compare(req.body.password, user.password)) {
res.send('Success')
} else {
res.send('Incorrect')
}
} catch {
res.status(500).send()
}
})
// to be continued? ...
const { engine } = require('express-handlebars');
const mainRouter = require('./controllers');
const PORT = process.env.PORT || 3001;
const sequelize = require('./config/sequelize');
require('./models');
app.engine('handlebars', engine());
app.set('view engine', 'handlebars');
app.use(express.json());
app.use(express.urlencoded({extended:true}));
app.use(express.static("public"));
app.use('/public', express.static(__dirname + '/public'));
app.use(mainRouter);
sequelize.sync().then(() => {
app.listen(PORT, () => {
console.log("Listening on http://localhost:" + PORT);
});
});