-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathapp.js
More file actions
73 lines (65 loc) · 2.18 KB
/
app.js
File metadata and controls
73 lines (65 loc) · 2.18 KB
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
const express = require('express');
require('dotenv').config();
require('./global_functions');
const userController = require('./controllers/UsersController');
const bodyParser = require('body-parser');
const passport = require('passport');
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const { poolPromise } = require('./data/db');
const sql = require('mssql');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(passport.initialize());
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = process.env.jwt_encryption;
passport.use(
new JwtStrategy(opts, async (jwtPayload, done) => {
let err, user;
const pool = await poolPromise;
try {
user = await pool
.request()
.input('Id', sql.Int, jwtPayload.user_id)
.query(
'select ID, UserName, RoleID, TavernID from users where Id = @Id',
);
user = user.recordset.shift();
} catch (e) {
console.error(e);
}
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
}
return done(null, false);
}),
);
// CORS
app.use((req, res, next) => {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader(
'Access-Control-Allow-Methods',
'GET, POST, OPTIONS, PUT, PATCH, DELETE',
);
// Request headers you wish to allow
res.setHeader(
'Access-Control-Allow-Headers',
'X-Requested-With, content-type, Authorization, Content-Type',
);
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
app.post('/users', userController.create);
app.post('/login', userController.login);
console.log('SERVER READY');
module.exports = app;