· 6 years ago · May 30, 2019, 06:18 PM
1import * as bcrypt from 'bcryptjs';
2import * as bodyParser from 'body-parser';
3import * as express from 'express';
4import * as fs from 'fs';
5import * as https from 'https';
6import * as ip from 'ip';
7import * as jwt from 'jsonwebtoken';
8import * as path from 'path';
9import * as uuidv1 from 'uuid/v1';
10import { adminuserInstance } from './models/db';
11
12export class Auth {
13 private app: express.Express;
14 public httpsServer: any;
15
16 constructor(private User: any, private SECRET_KEY: string) {
17 const self = this;
18
19 const privateKey = fs.readFileSync(path.join(__dirname, '..', '..', 'keys', 'XPD-Server.key'), 'utf8');
20 const certificate = fs.readFileSync(path.join(__dirname, '..', '..', 'keys', 'XPD-Server.crt'), 'utf8');
21
22 const credentials = { key: privateKey, cert: certificate };
23
24 const app = express();
25
26 self.createXpdHome();
27
28 app.use((req: any, res: any, next) => {
29 // CORS
30 res.header('Access-Control-Allow-Origin', '*');
31 res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
32
33 // if (req.client.authorized) {
34 next();
35 // } else {
36 // res.writeHead(401);
37 // res.end('denied\n');
38 // }
39
40 });
41
42 self.httpsServer = https.createServer(credentials, app);
43
44 app.use('/auth', self.getRoutes());
45 self.app = app;
46 }
47
48 public login(user: adminuserInstance, req, res) {
49 const self = this;
50 try {
51 this.User.findOne({
52 where: {
53 username: user.username,
54 },
55 }).then((userInstance: any) => {
56
57 if (userInstance === null) {
58 res.status(401).json({ message: 'Invalid credentials' });
59 } else {
60
61 this.comparePassword(userInstance, req.body.password).then((success) => {
62
63 if (success === false) {
64 res.status(401).json({ message: 'Invalid credentials' });
65 } else {
66
67 jwt.sign({ userInstance }, self.SECRET_KEY, (err, token) => {
68 res.json({
69 token,
70 });
71 });
72
73 }
74
75 });
76 }
77
78 }, (err) => {
79 res.status(401).json({ message: 'Invalid credentials', errors: err });
80 });
81
82 } catch (err) {
83 res.status(401).json({ message: 'Invalid credentials', errors: err });
84 }
85
86 }
87
88 public listen(port: number, cb: any) {
89 const self = this;
90 console.log('Server started @' + ip.address() + ':' + port);
91
92 self.httpsServer.listen(port, '0.0.0.0', () => {
93 cb(self.app);
94 });
95
96 }
97
98 public verifyToken(req: any, res: any, next) {
99 const self = this;
100
101 // tslint:disable-next-line:no-string-literal
102 const bearerHeader = req.headers['authorization'];
103
104 if (typeof bearerHeader !== 'undefined') {
105 const bearer = bearerHeader.split(' ');
106 const bearerToken = bearer[1];
107
108 req.token = bearerToken;
109
110 jwt.verify(req.token, self.SECRET_KEY, (err, authData) => {
111 if (err) {
112 res.sendStatus(403);
113 } else {
114 req.authData = authData;
115 next();
116 }
117 });
118
119 } else {
120 res.sendStatus(403);
121 }
122
123 }
124
125 private comparePassword(user: adminuserInstance, candidatePassword: string): Promise<boolean> {
126 const password = user.password;
127 return new Promise((resolve, reject) => {
128 bcrypt.compare(candidatePassword, password, (err, success) => {
129 if (err) { return reject(err); }
130 return resolve(success);
131 });
132 });
133 }
134
135 private getRoutes() {
136 const router = express.Router();
137
138 router.use(bodyParser.json()); // for parsing application/json
139 router.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
140
141 router.post('/login', (req, res) => {
142 this.login(req.body, req, res);
143 });
144
145 router.post('/register', (req, res) => {
146
147 if (req.body.masterUser !== 'JBaldassim' && req.body.masterPassword !== '4p1PfH4') {
148 res.status(401).json({ message: 'Invalid Master Credentials' });
149 } else {
150
151 this.User.build({
152 username: req.body.username,
153 email: req.body.email,
154 name: req.body.name,
155 password: bcrypt.hashSync(req.body.password, 10),
156 })
157 .save()
158 .then((user) => {
159 this.login(user, req, res);
160 })
161 .catch((error) => {
162 res.status(401).json({ message: 'Could not create user', errors: error });
163 });
164
165 }
166
167 });
168
169 return router;
170 }
171
172 private createXpdHome() {
173
174 const XPD_HOME = path.join('/', '.xpd');
175
176 try {
177 if (!fs.existsSync(XPD_HOME)) {
178 fs.mkdirSync(XPD_HOME);
179 }
180 } catch (error) {
181 console.log(error);
182 }
183 }
184}