-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
91 lines (80 loc) · 2.76 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
89
90
91
import express from 'express';
import db from './app/db/dbconfig';
import properties from './app/db/properties';
import userRoutes from './app/routes/routes.user';
import chatRoutes from './app/routes/routes.chats';
import logger from 'morgan';
import jwt from 'jsonwebtoken';
import config from './app/db/properties';
import middleware from './app/config/middleware';
//let jwt = require('jsonwebtoken');
//let config = require('./config');
//let middleware = require('./middleware');
class HandlerGenerator {
login(req, res) {
let username = req.body.username;
let password = req.body.password;
console.log("username :: ", username);
console.log("password :: ", password);
// For the given username fetch user from Database
let mockedUsername = 'admin';
let mockedPassword = 'password';
if (username && password) {
if (username === mockedUsername && password === mockedPassword) {
let token = jwt.sign({ username: username },
config.secret,
{
expiresIn: '24h' // expires in 24 hours
}
);
// return the JWT token for the future API calls
res.json({
success: true,
message: 'Authentication successful!',
token: token
});
} else {
res.status(403).json({
success: false,
message: 'Incorrect username or password'
});
}
} else {
res.status(400).json({
success: false,
message: 'Authentication failed! Please check the request'
});
}
}
index(req, res) {
res.json({
success: true,
message: 'Index page'
});
}
}
// Set up the express app
// Starting point of the server
function main() {
const app = express();
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json());
const cors = require('cors');
var corsOptions = {
origin: '*',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
db();
let handlers = new HandlerGenerator();
app.post('/login', handlers.login);
//app.get('/',middleware.checkToken, handlers.index);
app.use(cors(corsOptions));
app.use(logger('combined'))
app.use('/api/user', middleware.checkToken, userRoutes);
app.use('/api/chat', middleware.checkToken, chatRoutes);
app.listen(properties.PORT, (req, res) => {
console.log(`Server is running on ${properties.PORT} port.`);
})
}
main();