-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (76 loc) · 2.27 KB
/
index.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
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const db = require("./dbFunctions");
const bcrypt = require("bcryptjs");
const path = require('path');
const server = express();
const { authenticate,generateToken } = require('./auth/authenticate');
const protectedRoutes = require("./protectedRoutes");
server.use(helmet());
server.use(cors());
server.use(express.json());
server.get("/", async (req,res) => {
res.status(200).sendFile(path.join(__dirname + '/index.html'));
})
// Maybe implement an automatic db call with the users info and necessary resources for the client
server.get("/regions", async (req,res) => {
try{
const regions = await db.getRegions();
res.status(200).json(regions);
}catch(err){
res.status(500).json({ message: `Server error`, error: err });
}
})
server.get("/resources", async (req, res) => {
try {
let resources = await db.getResources();
res.status(200).json(resources);
} catch (err) {
console.log(err);
res.status(500).json({ message: `Server error`, error: err });
}
});
async function register(req, res) {
let userInfo = req.body;
const hash = bcrypt.hashSync(userInfo.password, 12);
userInfo.password = hash;
try {
const response = await db.addMentor(userInfo);
console.log(response)
let user = await db.getMentor(userInfo);
const token = generateToken(user);
res.status(201).json({user,token});
} catch (err) {
console.log(err);
res.status(500).json(err);
}
}
async function login(req, res) {
const creds = req.body;
try {
let user = await db.getMentor(creds);
if (user && bcrypt.compareSync(creds.password, user.password)) {
const token = generateToken(user);
delete user.password
res.status(200).json({ user,token });
} else {
res
.status(401)
.json({ message: `Username and/or password are incorrect` });
}
} catch (err) {
console.log(err);
res.status(500).json({ message: `Server error`, error: err });
}
}
server.post('/register', register);
server.post('/login', login);
server.post('/twilio-callback', (req,res) => {
console.log(req.body);
res.status(200).end();
});
server.use('/api', authenticate ,protectedRoutes);
module.exports = {
server
};