Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import * as bcrypt from 'bcryptjs';
- import * as bodyParser from 'body-parser';
- import * as express from 'express';
- import * as fs from 'fs';
- import * as https from 'https';
- import * as ip from 'ip';
- import * as jwt from 'jsonwebtoken';
- import * as path from 'path';
- import * as uuidv1 from 'uuid/v1';
- import { adminuserInstance } from './models/db';
- export class Auth {
- private app: express.Express;
- public httpsServer: any;
- constructor(private User: any, private SECRET_KEY: string) {
- const self = this;
- const privateKey = fs.readFileSync(path.join(__dirname, '..', '..', 'keys', 'XPD-Server.key'), 'utf8');
- const certificate = fs.readFileSync(path.join(__dirname, '..', '..', 'keys', 'XPD-Server.crt'), 'utf8');
- const credentials = { key: privateKey, cert: certificate };
- const app = express();
- self.createXpdHome();
- app.use((req: any, res: any, next) => {
- // CORS
- res.header('Access-Control-Allow-Origin', '*');
- res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
- // if (req.client.authorized) {
- next();
- // } else {
- // res.writeHead(401);
- // res.end('denied\n');
- // }
- });
- self.httpsServer = https.createServer(credentials, app);
- app.use('/auth', self.getRoutes());
- self.app = app;
- }
- public login(user: adminuserInstance, req, res) {
- const self = this;
- try {
- this.User.findOne({
- where: {
- username: user.username,
- },
- }).then((userInstance: any) => {
- if (userInstance === null) {
- res.status(401).json({ message: 'Invalid credentials' });
- } else {
- this.comparePassword(userInstance, req.body.password).then((success) => {
- if (success === false) {
- res.status(401).json({ message: 'Invalid credentials' });
- } else {
- jwt.sign({ userInstance }, self.SECRET_KEY, (err, token) => {
- res.json({
- token,
- });
- });
- }
- });
- }
- }, (err) => {
- res.status(401).json({ message: 'Invalid credentials', errors: err });
- });
- } catch (err) {
- res.status(401).json({ message: 'Invalid credentials', errors: err });
- }
- }
- public listen(port: number, cb: any) {
- const self = this;
- console.log('Server started @' + ip.address() + ':' + port);
- self.httpsServer.listen(port, '0.0.0.0', () => {
- cb(self.app);
- });
- }
- public verifyToken(req: any, res: any, next) {
- const self = this;
- // tslint:disable-next-line:no-string-literal
- const bearerHeader = req.headers['authorization'];
- if (typeof bearerHeader !== 'undefined') {
- const bearer = bearerHeader.split(' ');
- const bearerToken = bearer[1];
- req.token = bearerToken;
- jwt.verify(req.token, self.SECRET_KEY, (err, authData) => {
- if (err) {
- res.sendStatus(403);
- } else {
- req.authData = authData;
- next();
- }
- });
- } else {
- res.sendStatus(403);
- }
- }
- private comparePassword(user: adminuserInstance, candidatePassword: string): Promise<boolean> {
- const password = user.password;
- return new Promise((resolve, reject) => {
- bcrypt.compare(candidatePassword, password, (err, success) => {
- if (err) { return reject(err); }
- return resolve(success);
- });
- });
- }
- private getRoutes() {
- const router = express.Router();
- router.use(bodyParser.json()); // for parsing application/json
- router.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
- router.post('/login', (req, res) => {
- this.login(req.body, req, res);
- });
- router.post('/register', (req, res) => {
- if (req.body.masterUser !== 'JBaldassim' && req.body.masterPassword !== '4p1PfH4') {
- res.status(401).json({ message: 'Invalid Master Credentials' });
- } else {
- this.User.build({
- username: req.body.username,
- email: req.body.email,
- name: req.body.name,
- password: bcrypt.hashSync(req.body.password, 10),
- })
- .save()
- .then((user) => {
- this.login(user, req, res);
- })
- .catch((error) => {
- res.status(401).json({ message: 'Could not create user', errors: error });
- });
- }
- });
- return router;
- }
- private createXpdHome() {
- const XPD_HOME = path.join('/', '.xpd');
- try {
- if (!fs.existsSync(XPD_HOME)) {
- fs.mkdirSync(XPD_HOME);
- }
- } catch (error) {
- console.log(error);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement