From bd70d001092238542d365e3ae7d9008d90a661c6 Mon Sep 17 00:00:00 2001 From: Ahmed Meftah Date: Fri, 24 Jun 2022 20:14:11 +0100 Subject: [PATCH 1/8] Install prettier --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index bed071c..6f003dd 100644 --- a/package.json +++ b/package.json @@ -55,6 +55,7 @@ "@types/node": "^12.12.17", "awesome-typescript-loader": "^5.2.0", "mocha": "^5.2.0", + "prettier": "^2.7.1", "typescript": "^3.0.1", "typescript-eslint-parser": "^18.0.0" }, From 554b23f825c841f95adaa09f5796d66eb2a4e7ef Mon Sep 17 00:00:00 2001 From: Ahmed Meftah Date: Fri, 24 Jun 2022 20:14:22 +0100 Subject: [PATCH 2/8] Add format script --- package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 6f003dd..460ad61 100644 --- a/package.json +++ b/package.json @@ -63,7 +63,8 @@ "build": "tsc --project './tsconfig.json'", "dev": "tsc --project './tsconfig.json' --watch & NODE_ENV=development nodemon dist", "test": "tsc --project './tsconfig.json' && ./node_modules/.bin/mocha dist/**/*.spec.js", - "lint": "./node_modules/.bin/tslint -c tslint.json 'src/**/**.ts'" + "lint": "./node_modules/.bin/tslint -c tslint.json 'src/**/**.ts'", + "format": "prettier --write ./src" }, "author": "Faiz A. Farooqui ", "license": "ISC" From 6ef1875821cce4093adacf052e5176d76e537b3b Mon Sep 17 00:00:00 2001 From: Ahmed Meftah Date: Fri, 24 Jun 2022 20:14:29 +0100 Subject: [PATCH 3/8] Add prettier config file --- .prettierrc | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 .prettierrc diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..a4e66c2 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,28 @@ +{ + "semi": false, + "overrides": [ + { + "files": ["*.js", "*.jsx", "*.ts", "*.tsx"], + "options": { + "printWidth": 100, + "tabWidth": 2, + "useTabs": false, + "semi": false, + "singleQuote": true, + "jsxSingleQuote": true, + "trailingComma": "es5", + "bracketSpacing": true, + "arrowParens": "avoid", + "endOfLine": "lf" + } + }, + { + "files": ["*.css", "*.json", "*.scss", "*.html", "*.pug"], + "options": { + "printWidth": 100, + "useTabs": false, + "tabWidth": 2 + } + } + ] +} From 7f2c960dffdc2662b247f657b3a5db44d93d3be2 Mon Sep 17 00:00:00 2001 From: Ahmed Meftah Date: Fri, 24 Jun 2022 20:14:34 +0100 Subject: [PATCH 4/8] Format project --- src/controllers/Account.ts | 14 +- src/controllers/Api/Auth/Login.ts | 118 +++++++++-------- src/controllers/Api/Auth/RefreshToken.ts | 130 ++++++++++--------- src/controllers/Api/Auth/Register.ts | 106 ++++++++-------- src/controllers/Api/Home.ts | 14 +- src/controllers/Auth/Login.ts | 92 +++++++------- src/controllers/Auth/Logout.ts | 24 ++-- src/controllers/Auth/Register.ts | 96 +++++++------- src/controllers/Auth/Social.ts | 8 +- src/controllers/Home.ts | 14 +- src/exception/Handler.ts | 132 ++++++++++--------- src/exception/NativeEvent.ts | 74 +++++------ src/index.ts | 94 +++++++------- src/interfaces/models/user.ts | 42 +++--- src/interfaces/vendors/INext.ts | 2 +- src/interfaces/vendors/IRequest.ts | 10 +- src/interfaces/vendors/IResponse.ts | 2 +- src/interfaces/vendors/index.ts | 8 +- src/middlewares/CORS.ts | 28 ++-- src/middlewares/CsrfToken.ts | 89 ++++++------- src/middlewares/Http.ts | 140 ++++++++++---------- src/middlewares/Kernel.ts | 54 ++++---- src/middlewares/Log.ts | 141 +++++++++++---------- src/middlewares/Statics.ts | 28 ++-- src/middlewares/StatusMonitor.ts | 106 ++++++++-------- src/middlewares/Views.ts | 24 ++-- src/models/User.ts | 143 +++++++++++---------- src/providers/App.ts | 113 +++++++++-------- src/providers/Cache.ts | 44 +++---- src/providers/Database.ts | 46 +++---- src/providers/Express.ts | 106 ++++++++-------- src/providers/Locals.ts | 126 +++++++++--------- src/providers/Passport.ts | 94 +++++++------- src/providers/Queue.ts | 100 ++++++++------- src/providers/Routes.ts | 30 ++--- src/routes/Api.ts | 30 +++-- src/routes/Web.ts | 85 +++++++------ src/services/strategies/Google.ts | 155 ++++++++++++----------- src/services/strategies/Local.ts | 82 ++++++------ src/services/strategies/Twitter.ts | 133 ++++++++++--------- 40 files changed, 1463 insertions(+), 1414 deletions(-) diff --git a/src/controllers/Account.ts b/src/controllers/Account.ts index 7c409f8..252a238 100644 --- a/src/controllers/Account.ts +++ b/src/controllers/Account.ts @@ -4,14 +4,14 @@ * @author Faiz A. Farooqui */ -import { IRequest, IResponse } from '../interfaces/vendors'; +import { IRequest, IResponse } from '../interfaces/vendors' class Account { - public static index (req: IRequest, res: IResponse): void { - return res.render('pages/dashboard', { - title: 'Home' - }); - } + public static index(req: IRequest, res: IResponse): void { + return res.render('pages/dashboard', { + title: 'Home', + }) + } } -export default Account; +export default Account diff --git a/src/controllers/Api/Auth/Login.ts b/src/controllers/Api/Auth/Login.ts index 91791f6..69a25c6 100644 --- a/src/controllers/Api/Auth/Login.ts +++ b/src/controllers/Api/Auth/Login.ts @@ -4,78 +4,76 @@ * @author Faiz A. Farooqui */ -import * as jwt from 'jsonwebtoken'; +import * as jwt from 'jsonwebtoken' -import User from '../../../models/User'; +import User from '../../../models/User' class Login { - public static perform (req, res): any { - req.assert('email', 'E-mail cannot be blank').notEmpty(); - req.assert('email', 'E-mail is not valid').isEmail(); - req.assert('password', 'Password cannot be blank').notEmpty(); - req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }); - req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }); + public static perform(req, res): any { + req.assert('email', 'E-mail cannot be blank').notEmpty() + req.assert('email', 'E-mail is not valid').isEmail() + req.assert('password', 'Password cannot be blank').notEmpty() + req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }) + req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }) - const errors = req.validationErrors(); - if (errors) { - return res.json({ - errors - }); - } + const errors = req.validationErrors() + if (errors) { + return res.json({ + errors, + }) + } - const _email = req.body.email.toLowerCase(); - const _password = req.body.password; + const _email = req.body.email.toLowerCase() + const _password = req.body.password - User.findOne({email: _email}, (err, user) => { - if (err) { - return res.json({ - error: err - }); - } + User.findOne({ email: _email }, (err, user) => { + if (err) { + return res.json({ + error: err, + }) + } - if (! user) { - return res.json({ - error: ['User not found!'] - }); - } + if (!user) { + return res.json({ + error: ['User not found!'], + }) + } - if (! user.password) { - return res.json({ - error: ['Please login using your social creds'] - }); - } + if (!user.password) { + return res.json({ + error: ['Please login using your social creds'], + }) + } - user.comparePassword(_password, (err, isMatch) => { - if (err) { - return res.json({ - error: err - }); - } + user.comparePassword(_password, (err, isMatch) => { + if (err) { + return res.json({ + error: err, + }) + } - if (! isMatch) { - return res.json({ - error: ['Password does not match!'] - }); - } + if (!isMatch) { + return res.json({ + error: ['Password does not match!'], + }) + } - const token = jwt.sign( - { email: _email, password: _password }, - res.locals.app.appSecret, - { expiresIn: res.locals.app.jwtExpiresIn * 60 } - ); + const token = jwt.sign({ email: _email, password: _password }, res.locals.app.appSecret, { + expiresIn: res.locals.app.jwtExpiresIn * 60, + }) - // Hide protected columns - user.tokens = undefined; - user.password = undefined; + // Hide protected columns + user.tokens = undefined + user.password = undefined - return res.json({ - user, - token, - token_expires_in: res.locals.app.jwtExpiresIn * 60 - }); - }); - }); - } + return res.json({ + user, + token, + token_expires_in: res.locals.app.jwtExpiresIn * 60, + }) + }) + }) + } } -export default Login; +export default Login diff --git a/src/controllers/Api/Auth/RefreshToken.ts b/src/controllers/Api/Auth/RefreshToken.ts index 732d33f..78fdf6a 100644 --- a/src/controllers/Api/Auth/RefreshToken.ts +++ b/src/controllers/Api/Auth/RefreshToken.ts @@ -4,85 +4,83 @@ * @author Faiz A. Farooqui */ -import * as jwt from 'jsonwebtoken'; +import * as jwt from 'jsonwebtoken' -import User from '../../../models/User'; +import User from '../../../models/User' class RefreshToken { - public static getToken (req): string { - if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { - return req.headers.authorization.split(' ')[1]; - } else if (req.query && req.query.token) { - return req.query.token; - } + public static getToken(req): string { + if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { + return req.headers.authorization.split(' ')[1] + } else if (req.query && req.query.token) { + return req.query.token + } - return ''; - } + return '' + } - public static perform (req, res): any { - const _token = RefreshToken.getToken(req); - if (_token === '') { - return res.json({ - error: ['Invalid Token!'] - }); - } + public static perform(req, res): any { + const _token = RefreshToken.getToken(req) + if (_token === '') { + return res.json({ + error: ['Invalid Token!'], + }) + } - const decode = jwt.decode( - _token, - res.locals.app.appSecret, - { expiresIn: res.locals.app.jwtExpiresIn } - ); + const decode = jwt.decode(_token, res.locals.app.appSecret, { + expiresIn: res.locals.app.jwtExpiresIn, + }) - User.findOne({email: decode.email}, (err, user) => { - if (err) { - return res.json({ - error: err - }); - } + User.findOne({ email: decode.email }, (err, user) => { + if (err) { + return res.json({ + error: err, + }) + } - if (! user) { - return res.json({ - error: ['User not found!'] - }); - } + if (!user) { + return res.json({ + error: ['User not found!'], + }) + } - if (! user.password) { - return res.json({ - error: ['Please login using your social creds'] - }); - } + if (!user.password) { + return res.json({ + error: ['Please login using your social creds'], + }) + } - user.comparePassword(decode.password, (err, isMatch) => { - if (err) { - return res.json({ - error: err - }); - } + user.comparePassword(decode.password, (err, isMatch) => { + if (err) { + return res.json({ + error: err, + }) + } - if (! isMatch) { - return res.json({ - error: ['Password does not match!'] - }); - } + if (!isMatch) { + return res.json({ + error: ['Password does not match!'], + }) + } - const token = jwt.sign( - { email: decode.email, password: decode.password }, - res.locals.app.appSecret, - { expiresIn: res.locals.app.jwtExpiresIn * 60 } - ); + const token = jwt.sign( + { email: decode.email, password: decode.password }, + res.locals.app.appSecret, + { expiresIn: res.locals.app.jwtExpiresIn * 60 } + ) - // Hide protected columns - user.tokens = undefined; - user.password = undefined; + // Hide protected columns + user.tokens = undefined + user.password = undefined - return res.json({ - user, - token, - token_expires_in: res.locals.app.jwtExpiresIn * 60 - }); - }); - }); - } + return res.json({ + user, + token, + token_expires_in: res.locals.app.jwtExpiresIn * 60, + }) + }) + }) + } } -export default RefreshToken; +export default RefreshToken diff --git a/src/controllers/Api/Auth/Register.ts b/src/controllers/Api/Auth/Register.ts index 261a319..a35991e 100644 --- a/src/controllers/Api/Auth/Register.ts +++ b/src/controllers/Api/Auth/Register.ts @@ -4,59 +4,61 @@ * @author Faiz A. Farooqui */ -import User from '../../../models/User'; +import User from '../../../models/User' class Register { - public static perform (req, res): any { - req.assert('email', 'E-mail cannot be blank').notEmpty(); - req.assert('email', 'E-mail is not valid').isEmail(); - req.assert('password', 'Password cannot be blank').notEmpty(); - req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }); - req.assert('confirmPassword', 'Confirmation Password cannot be blank').notEmpty(); - req.assert('confirmPassword', 'Password & Confirmation password does not match').equals(req.body.password); - req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }); - - const errors = req.validationErrors(); - if (errors) { - return res.json({ - error: errors - }); - } - - const _email = req.body.email; - const _password = req.body.password; - - const user = new User({ - email: _email, - password: _password - }); - - User.findOne({ email: _email }, (err, existingUser) => { - if (err) { - return res.json({ - error: err - }); - } - - if (existingUser) { - return res.json({ - error: ['Account with the e-mail address already exists.'] - }); - } - - user.save((err) => { - if (err) { - return res.json({ - error: err - }); - } - - return res.json({ - message: ['You have been successfully registered with us!'] - }); - }); - }); - } + public static perform(req, res): any { + req.assert('email', 'E-mail cannot be blank').notEmpty() + req.assert('email', 'E-mail is not valid').isEmail() + req.assert('password', 'Password cannot be blank').notEmpty() + req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }) + req.assert('confirmPassword', 'Confirmation Password cannot be blank').notEmpty() + req + .assert('confirmPassword', 'Password & Confirmation password does not match') + .equals(req.body.password) + req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }) + + const errors = req.validationErrors() + if (errors) { + return res.json({ + error: errors, + }) + } + + const _email = req.body.email + const _password = req.body.password + + const user = new User({ + email: _email, + password: _password, + }) + + User.findOne({ email: _email }, (err, existingUser) => { + if (err) { + return res.json({ + error: err, + }) + } + + if (existingUser) { + return res.json({ + error: ['Account with the e-mail address already exists.'], + }) + } + + user.save(err => { + if (err) { + return res.json({ + error: err, + }) + } + + return res.json({ + message: ['You have been successfully registered with us!'], + }) + }) + }) + } } -export default Register; +export default Register diff --git a/src/controllers/Api/Home.ts b/src/controllers/Api/Home.ts index 63f5c07..dba956b 100644 --- a/src/controllers/Api/Home.ts +++ b/src/controllers/Api/Home.ts @@ -4,14 +4,14 @@ * @author Faiz A. Farooqui */ -import Locals from '../../providers/Locals'; +import Locals from '../../providers/Locals' class Home { - public static index(req, res, next): any { - return res.json({ - message: Locals.config().name - }); - } + public static index(req, res, next): any { + return res.json({ + message: Locals.config().name, + }) + } } -export default Home; +export default Home diff --git a/src/controllers/Auth/Login.ts b/src/controllers/Auth/Login.ts index 24b9726..da8cc34 100644 --- a/src/controllers/Auth/Login.ts +++ b/src/controllers/Auth/Login.ts @@ -4,55 +4,53 @@ * @author Faiz A. Farooqui */ -import * as passport from 'passport'; +import * as passport from 'passport' -import { - IRequest, IResponse, INext -} from '../../interfaces/vendors'; -import Log from '../../middlewares/Log'; +import { IRequest, IResponse, INext } from '../../interfaces/vendors' +import Log from '../../middlewares/Log' class Login { - public static show (req: IRequest, res: IResponse): any { - return res.render('pages/login', { - title: 'LogIn' - }); - } - - public static perform (req: IRequest, res: IResponse, next: INext): any { - req.assert('email', 'E-mail cannot be blank').notEmpty(); - req.assert('email', 'E-mail is not valid').isEmail(); - req.assert('password', 'Password cannot be blank').notEmpty(); - req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }); - req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }); - - const errors = req.validationErrors(); - if (errors) { - req.flash('errors', errors); - return res.redirect('/login'); - } - - Log.info('Here in the login controller #1!'); - passport.authenticate('local', (err, user, info) => { - Log.info('Here in the login controller #2!'); - if (err) { - return next(err); - } - - if (! user) { - req.flash('errors', info); - return res.redirect('/login'); - } - - req.logIn(user, (err) => { - if (err) { - return next(err); - } - - req.flash('success', { msg: 'You are successfully logged in now!' }); - res.redirect('/account'); - }); - })(req, res, next); - } + public static show(req: IRequest, res: IResponse): any { + return res.render('pages/login', { + title: 'LogIn', + }) + } + + public static perform(req: IRequest, res: IResponse, next: INext): any { + req.assert('email', 'E-mail cannot be blank').notEmpty() + req.assert('email', 'E-mail is not valid').isEmail() + req.assert('password', 'Password cannot be blank').notEmpty() + req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }) + req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }) + + const errors = req.validationErrors() + if (errors) { + req.flash('errors', errors) + return res.redirect('/login') + } + + Log.info('Here in the login controller #1!') + passport.authenticate('local', (err, user, info) => { + Log.info('Here in the login controller #2!') + if (err) { + return next(err) + } + + if (!user) { + req.flash('errors', info) + return res.redirect('/login') + } + + req.logIn(user, err => { + if (err) { + return next(err) + } + + req.flash('success', { msg: 'You are successfully logged in now!' }) + res.redirect('/account') + }) + })(req, res, next) + } } -export default Login; +export default Login diff --git a/src/controllers/Auth/Logout.ts b/src/controllers/Auth/Logout.ts index 7656488..39423b7 100644 --- a/src/controllers/Auth/Logout.ts +++ b/src/controllers/Auth/Logout.ts @@ -4,20 +4,20 @@ * @author Faiz A. Farooqui */ -import { IRequest, IResponse } from '../../interfaces/vendors'; +import { IRequest, IResponse } from '../../interfaces/vendors' class Logout { - public static perform (req: IRequest, res: IResponse): any { - req.logout(); - req.session.destroy((err) => { - if (err) { - console.log('Error : Failed to destroy the session during logout.', err); - } + public static perform(req: IRequest, res: IResponse): any { + req.logout() + req.session.destroy(err => { + if (err) { + console.log('Error : Failed to destroy the session during logout.', err) + } - req.user = null; - return res.redirect('/'); - }); - } + req.user = null + return res.redirect('/') + }) + } } -export default Logout; +export default Logout diff --git a/src/controllers/Auth/Register.ts b/src/controllers/Auth/Register.ts index 472065f..125bba2 100644 --- a/src/controllers/Auth/Register.ts +++ b/src/controllers/Auth/Register.ts @@ -4,61 +4,63 @@ * @author Faiz A. Farooqui */ -import User from '../../models/User'; -import { IRequest, IResponse, INext } from '../../interfaces/vendors'; +import User from '../../models/User' +import { IRequest, IResponse, INext } from '../../interfaces/vendors' class Register { - public static show (req: IRequest, res: IResponse): any { - return res.render('pages/signup', { - title: 'SignUp' - }); - } + public static show(req: IRequest, res: IResponse): any { + return res.render('pages/signup', { + title: 'SignUp', + }) + } - public static perform (req: IRequest, res: IResponse, next: INext): any { - req.assert('email', 'E-mail cannot be blank').notEmpty(); - req.assert('email', 'E-mail is not valid').isEmail(); - req.assert('password', 'Password cannot be blank').notEmpty(); - req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }); - req.assert('confirmPassword', 'Confirmation Password cannot be blank').notEmpty(); - req.assert('confirmPassword', 'Password & Confirmation password does not match').equals(req.body.password); - req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }); + public static perform(req: IRequest, res: IResponse, next: INext): any { + req.assert('email', 'E-mail cannot be blank').notEmpty() + req.assert('email', 'E-mail is not valid').isEmail() + req.assert('password', 'Password cannot be blank').notEmpty() + req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }) + req.assert('confirmPassword', 'Confirmation Password cannot be blank').notEmpty() + req + .assert('confirmPassword', 'Password & Confirmation password does not match') + .equals(req.body.password) + req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }) - const errors = req.validationErrors(); - if (errors) { - req.flash('errors', errors); - return res.redirect('/signup'); - } + const errors = req.validationErrors() + if (errors) { + req.flash('errors', errors) + return res.redirect('/signup') + } - const user = new User({ - email: req.body.email, - password: req.body.password - }); + const user = new User({ + email: req.body.email, + password: req.body.password, + }) - User.findOne({ email: req.body.email }, (err, existingUser) => { - if (err) { - return next(err); - } + User.findOne({ email: req.body.email }, (err, existingUser) => { + if (err) { + return next(err) + } - if (existingUser) { - req.flash('errors', { msg: 'Account with the e-mail address already exists.' }); - return res.redirect('/signup'); - } + if (existingUser) { + req.flash('errors', { msg: 'Account with the e-mail address already exists.' }) + return res.redirect('/signup') + } - user.save((err) => { - if (err) { - return next(err); - } + user.save(err => { + if (err) { + return next(err) + } - req.logIn(user, (err) => { - if (err) { - return next(err); - } - req.flash('success', { msg: 'You are successfully logged in now!' }); - res.redirect('/signup'); - }); - }); - }); - } + req.logIn(user, err => { + if (err) { + return next(err) + } + req.flash('success', { msg: 'You are successfully logged in now!' }) + res.redirect('/signup') + }) + }) + }) + } } -export default Register; +export default Register diff --git a/src/controllers/Auth/Social.ts b/src/controllers/Auth/Social.ts index fb2cee3..db53ac1 100644 --- a/src/controllers/Auth/Social.ts +++ b/src/controllers/Auth/Social.ts @@ -5,9 +5,9 @@ */ class Social { - public static googleCallback(req, res): any { - return res.redirect('/account'); - } + public static googleCallback(req, res): any { + return res.redirect('/account') + } } -export default Social; +export default Social diff --git a/src/controllers/Home.ts b/src/controllers/Home.ts index 6e012a0..12e5b7c 100644 --- a/src/controllers/Home.ts +++ b/src/controllers/Home.ts @@ -4,14 +4,14 @@ * @author Faiz A. Farooqui */ -import { IRequest, IResponse } from '../interfaces/vendors'; +import { IRequest, IResponse } from '../interfaces/vendors' class Home { - public static index (req: IRequest, res: IResponse, next): void { - return res.render('pages/home', { - title: 'Home' - }); - } + public static index(req: IRequest, res: IResponse, next): void { + return res.render('pages/home', { + title: 'Home', + }) + } } -export default Home; +export default Home diff --git a/src/exception/Handler.ts b/src/exception/Handler.ts index 27dfcf4..1f7e3c3 100644 --- a/src/exception/Handler.ts +++ b/src/exception/Handler.ts @@ -4,86 +4,82 @@ * @author Faiz A. Farooqui */ -import Log from '../middlewares/Log'; -import Locals from '../providers/Locals'; +import Log from '../middlewares/Log' +import Locals from '../providers/Locals' class Handler { - /** - * Handles all the not found routes - */ - public static notFoundHandler(_express): any { - const apiPrefix = Locals.config().apiPrefix; + /** + * Handles all the not found routes + */ + public static notFoundHandler(_express): any { + const apiPrefix = Locals.config().apiPrefix - _express.use('*', (req, res) => { - const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; + _express.use('*', (req, res) => { + const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress - Log.error(`Path '${req.originalUrl}' not found [IP: '${ip}']!`); - if (req.xhr || req.originalUrl.includes(`/${apiPrefix}/`)) { - return res.json({ - error: 'Page Not Found' - }); - } else { - res.status(404); - return res.render('pages/error', { - title: 'Page Not Found', - error: [] - }); - } - }); + Log.error(`Path '${req.originalUrl}' not found [IP: '${ip}']!`) + if (req.xhr || req.originalUrl.includes(`/${apiPrefix}/`)) { + return res.json({ + error: 'Page Not Found', + }) + } else { + res.status(404) + return res.render('pages/error', { + title: 'Page Not Found', + error: [], + }) + } + }) - return _express; - } + return _express + } - /** - * Handles your api/web routes errors/exception - */ - public static clientErrorHandler(err, req, res, next): any { - Log.error(err.stack); + /** + * Handles your api/web routes errors/exception + */ + public static clientErrorHandler(err, req, res, next): any { + Log.error(err.stack) - if (req.xhr) { - return res.status(500).send({error: 'Something went wrong!'}); - } else { - return next(err); - } - } + if (req.xhr) { + return res.status(500).send({ error: 'Something went wrong!' }) + } else { + return next(err) + } + } - /** - * Show undermaintenance page incase of errors - */ - public static errorHandler(err, req, res, next): any { - Log.error(err.stack); - res.status(500); + /** + * Show undermaintenance page incase of errors + */ + public static errorHandler(err, req, res, next): any { + Log.error(err.stack) + res.status(500) - const apiPrefix = Locals.config().apiPrefix; - if (req.originalUrl.includes(`/${apiPrefix}/`)) { + const apiPrefix = Locals.config().apiPrefix + if (req.originalUrl.includes(`/${apiPrefix}/`)) { + if (err.name && err.name === 'UnauthorizedError') { + const innerMessage = err.inner && err.inner.message ? err.inner.message : undefined + return res.json({ + error: ['Invalid Token!', innerMessage], + }) + } - if (err.name && err.name === 'UnauthorizedError') { - const innerMessage = err.inner && err.inner.message ? err.inner.message : undefined; - return res.json({ - error: [ - 'Invalid Token!', - innerMessage - ] - }); - } + return res.json({ + error: err, + }) + } - return res.json({ - error: err - }); - } + return res.render('pages/error', { error: err.stack, title: 'Under Maintenance' }) + } - return res.render('pages/error', { error: err.stack, title: 'Under Maintenance' }); - } + /** + * Register your error / exception monitoring + * tools right here ie. before "next(err)"! + */ + public static logErrors(err, req, res, next): any { + Log.error(err.stack) - /** - * Register your error / exception monitoring - * tools right here ie. before "next(err)"! - */ - public static logErrors(err, req, res, next): any { - Log.error(err.stack); - - return next(err); - } + return next(err) + } } -export default Handler; +export default Handler diff --git a/src/exception/NativeEvent.ts b/src/exception/NativeEvent.ts index 7c43abe..d5ab293 100644 --- a/src/exception/NativeEvent.ts +++ b/src/exception/NativeEvent.ts @@ -4,44 +4,44 @@ * @author Faiz A. Farooqui */ -import Log from '../middlewares/Log'; +import Log from '../middlewares/Log' class NativeEvent { - public cluster (_cluster): void { - // Catch cluster listening event... - _cluster.on('listening', (worker) => - Log.info(`Server :: Cluster with ProcessID '${worker.process.pid}' Connected!`) - ); - - // Catch cluster once it is back online event... - _cluster.on('online', (worker) => - Log.info(`Server :: Cluster with ProcessID '${worker.process.pid}' has responded after it was forked! `) - ); - - // Catch cluster disconnect event... - _cluster.on('disconnect', (worker) => - Log.info(`Server :: Cluster with ProcessID '${worker.process.pid}' Disconnected!`) - ); - - // Catch cluster exit event... - _cluster.on('exit', (worker, code, signal) => { - Log.info(`Server :: Cluster with ProcessID '${worker.process.pid}' is Dead with Code '${code}, and signal: '${signal}'`); - // Ensuring a new cluster will start if an old one dies - _cluster.fork(); - }); - } - - public process (): void { - // Catch the Process's uncaught-exception - process.on('uncaughtException', (exception) => - Log.error(exception.stack) - ); - - // Catch the Process's warning event - process.on('warning', (warning) => - Log.warn(warning.stack) - ); - } + public cluster(_cluster): void { + // Catch cluster listening event... + _cluster.on('listening', worker => + Log.info(`Server :: Cluster with ProcessID '${worker.process.pid}' Connected!`) + ) + + // Catch cluster once it is back online event... + _cluster.on('online', worker => + Log.info( + `Server :: Cluster with ProcessID '${worker.process.pid}' has responded after it was forked! ` + ) + ) + + // Catch cluster disconnect event... + _cluster.on('disconnect', worker => + Log.info(`Server :: Cluster with ProcessID '${worker.process.pid}' Disconnected!`) + ) + + // Catch cluster exit event... + _cluster.on('exit', (worker, code, signal) => { + Log.info( + `Server :: Cluster with ProcessID '${worker.process.pid}' is Dead with Code '${code}, and signal: '${signal}'` + ) + // Ensuring a new cluster will start if an old one dies + _cluster.fork() + }) + } + + public process(): void { + // Catch the Process's uncaught-exception + process.on('uncaughtException', exception => Log.error(exception.stack)) + + // Catch the Process's warning event + process.on('warning', warning => Log.warn(warning.stack)) + } } -export default new NativeEvent; +export default new NativeEvent() diff --git a/src/index.ts b/src/index.ts index 865285b..a4e8002 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,64 +4,62 @@ * @author Faiz A. Farooqui */ -import * as os from 'os'; -import * as cluster from 'cluster'; +import * as os from 'os' +import * as cluster from 'cluster' -import App from './providers/App'; -import NativeEvent from './exception/NativeEvent'; +import App from './providers/App' +import NativeEvent from './exception/NativeEvent' if (cluster.isMaster) { - /** - * Catches the process events - */ - NativeEvent.process(); + /** + * Catches the process events + */ + NativeEvent.process() - /** - * Clear the console before the app runs - */ - App.clearConsole(); + /** + * Clear the console before the app runs + */ + App.clearConsole() - /** - * Load Configuration - */ - App.loadConfiguration(); + /** + * Load Configuration + */ + App.loadConfiguration() - /** - * Find the number of available CPUS - */ - const CPUS: any = os.cpus(); + /** + * Find the number of available CPUS + */ + const CPUS: any = os.cpus() - /** - * Fork the process, the number of times we have CPUs available - */ - CPUS.forEach(() => cluster.fork()); + /** + * Fork the process, the number of times we have CPUs available + */ + CPUS.forEach(() => cluster.fork()) - /** - * Catches the cluster events - */ - NativeEvent.cluster(cluster); + /** + * Catches the cluster events + */ + NativeEvent.cluster(cluster) - /** - * Loads the Queue Monitor iff enabled - */ - App.loadQueue(); - - /** - * Run the Worker every minute - * Note: we normally start worker after - * the entire app is loaded - */ - setTimeout(() => App.loadWorker(), 1000 * 60); + /** + * Loads the Queue Monitor iff enabled + */ + App.loadQueue() + /** + * Run the Worker every minute + * Note: we normally start worker after + * the entire app is loaded + */ + setTimeout(() => App.loadWorker(), 1000 * 60) } else { + /** + * Run the Database pool + */ + App.loadDatabase() - /** - * Run the Database pool - */ - App.loadDatabase(); - - /** - * Run the Server on Clusters - */ - App.loadServer(); + /** + * Run the Server on Clusters + */ + App.loadServer() } diff --git a/src/interfaces/models/user.ts b/src/interfaces/models/user.ts index 881ceaa..98504eb 100644 --- a/src/interfaces/models/user.ts +++ b/src/interfaces/models/user.ts @@ -5,31 +5,31 @@ */ export interface Tokens { - kind: string; - accessToken: string; - tokenSecret?: string; + kind: string + accessToken: string + tokenSecret?: string } export interface IUser { - email: string; - password: string; - passwordResetToken: string; - passwordResetExpires: Date; + email: string + password: string + passwordResetToken: string + passwordResetExpires: Date - facebook: string; - twitter: string; - google: string; - github: string; - instagram: string; - linkedin: string; - tokens: Tokens[]; - steam: string; + facebook: string + twitter: string + google: string + github: string + instagram: string + linkedin: string + tokens: Tokens[] + steam: string - fullname: string; - gender: string; - geolocation: string; - website: string; - picture: string; + fullname: string + gender: string + geolocation: string + website: string + picture: string } -export default IUser; +export default IUser diff --git a/src/interfaces/vendors/INext.ts b/src/interfaces/vendors/INext.ts index 9140092..8f44d55 100644 --- a/src/interfaces/vendors/INext.ts +++ b/src/interfaces/vendors/INext.ts @@ -4,6 +4,6 @@ * @author Faiz A. Farooqui */ -import { NextFunction } from 'express'; +import { NextFunction } from 'express' export interface INext extends NextFunction {} diff --git a/src/interfaces/vendors/IRequest.ts b/src/interfaces/vendors/IRequest.ts index f1f83c5..0348852 100644 --- a/src/interfaces/vendors/IRequest.ts +++ b/src/interfaces/vendors/IRequest.ts @@ -4,12 +4,12 @@ * @author Faiz A. Farooqui */ -import { Request } from 'express'; +import { Request } from 'express' export interface IRequest extends Request { - flash(message: string, callback: any): any; + flash(message: string, callback: any): any - logIn(user: any, callback: any): any; - user(): any; - logout(): void; + logIn(user: any, callback: any): any + user(): any + logout(): void } diff --git a/src/interfaces/vendors/IResponse.ts b/src/interfaces/vendors/IResponse.ts index 485b2a1..5d8499c 100644 --- a/src/interfaces/vendors/IResponse.ts +++ b/src/interfaces/vendors/IResponse.ts @@ -4,6 +4,6 @@ * @author Faiz A. Farooqui */ -import { Response } from 'express'; +import { Response } from 'express' export interface IResponse extends Response {} diff --git a/src/interfaces/vendors/index.ts b/src/interfaces/vendors/index.ts index 8aae50d..da96853 100644 --- a/src/interfaces/vendors/index.ts +++ b/src/interfaces/vendors/index.ts @@ -4,8 +4,8 @@ * @author Faiz A. Farooqui */ -import { IRequest } from './IRequest'; -import { IResponse } from './IResponse'; -import { INext } from './INext'; +import { IRequest } from './IRequest' +import { IResponse } from './IResponse' +import { INext } from './INext' -export { IRequest, IResponse, INext }; +export { IRequest, IResponse, INext } diff --git a/src/middlewares/CORS.ts b/src/middlewares/CORS.ts index 2644886..d7c9679 100644 --- a/src/middlewares/CORS.ts +++ b/src/middlewares/CORS.ts @@ -4,25 +4,25 @@ * @author Faiz A. Farooqui */ -import * as cors from 'cors'; -import { Application } from 'express'; +import * as cors from 'cors' +import { Application } from 'express' -import Log from './Log'; -import Locals from '../providers/Locals'; +import Log from './Log' +import Locals from '../providers/Locals' class CORS { - public mount(_express: Application): Application { - Log.info('Booting the \'CORS\' middleware...'); + public mount(_express: Application): Application { + Log.info("Booting the 'CORS' middleware...") - const options = { - origin: Locals.config().url, - optionsSuccessStatus: 200 // Some legacy browsers choke on 204 - }; + const options = { + origin: Locals.config().url, + optionsSuccessStatus: 200, // Some legacy browsers choke on 204 + } - _express.use(cors(options)); + _express.use(cors(options)) - return _express; - } + return _express + } } -export default new CORS; +export default new CORS() diff --git a/src/middlewares/CsrfToken.ts b/src/middlewares/CsrfToken.ts index 4bdf379..5ee8624 100644 --- a/src/middlewares/CsrfToken.ts +++ b/src/middlewares/CsrfToken.ts @@ -5,60 +5,61 @@ * @author Faiz A. Farooqui */ -import { Application } from 'express'; -import * as lusca from 'lusca'; +import { Application } from 'express' +import * as lusca from 'lusca' -import Log from './Log'; -import Locals from '../providers/Locals'; +import Log from './Log' +import Locals from '../providers/Locals' class CsrfToken { - public static mount(_express: any): Application { - Log.info('Booting the \'CsrfToken\' middleware...'); + public static mount(_express: any): Application { + Log.info("Booting the 'CsrfToken' middleware...") - _express.set('trust proxy', 1); + _express.set('trust proxy', 1) - // Interpolate the user variable into your pug files - _express.use((req, res, next) => { - res.locals.user = req.user; - res.locals.app = Locals.config(); - next(); - }); + // Interpolate the user variable into your pug files + _express.use((req, res, next) => { + res.locals.user = req.user + res.locals.app = Locals.config() + next() + }) - // Check for CSRF token iff the original url - // does not contains the api substring - _express.use((req, res, next) => { - const apiPrefix = Locals.config().apiPrefix; + // Check for CSRF token iff the original url + // does not contains the api substring + _express.use((req, res, next) => { + const apiPrefix = Locals.config().apiPrefix - if (req.originalUrl.includes(`/${apiPrefix}/`)) { - next(); - } else { - lusca.csrf()(req, res, next); - } - }); + if (req.originalUrl.includes(`/${apiPrefix}/`)) { + next() + } else { + lusca.csrf()(req, res, next) + } + }) - // Enables x-frame-options headers - _express.use(lusca.xframe('SAMEORIGIN')); + // Enables x-frame-options headers + _express.use(lusca.xframe('SAMEORIGIN')) - // Enables xss-protection headers - _express.use(lusca.xssProtection(true)); + // Enables xss-protection headers + _express.use(lusca.xssProtection(true)) - _express.use((req, res, next) => { - // After successful login, redirect back to the intended page - if (!req.user - && req.path !== '/login' - && req.path !== '/signup' - && !req.path.match(/^\/auth/) - && !req.path.match(/\./)) { - req.session.returnTo = req.originalUrl; - } else if (req.user - && (req.path === '/account' || req.path.match(/^\/api/))) { - req.session.returnTo = req.originalUrl; - } - next(); - }); + _express.use((req, res, next) => { + // After successful login, redirect back to the intended page + if ( + !req.user && + req.path !== '/login' && + req.path !== '/signup' && + !req.path.match(/^\/auth/) && + !req.path.match(/\./) + ) { + req.session.returnTo = req.originalUrl + } else if (req.user && (req.path === '/account' || req.path.match(/^\/api/))) { + req.session.returnTo = req.originalUrl + } + next() + }) - return _express; - } + return _express + } } -export default CsrfToken; +export default CsrfToken diff --git a/src/middlewares/Http.ts b/src/middlewares/Http.ts index 9e3200f..74b8efb 100644 --- a/src/middlewares/Http.ts +++ b/src/middlewares/Http.ts @@ -4,77 +4,81 @@ * @author Faiz A. Farooqui */ -import * as cors from 'cors'; -import { Application } from 'express'; -import * as flash from 'express-flash'; -import * as compress from 'compression'; -import * as connect from 'connect-mongo'; -import * as bodyParser from 'body-parser'; -import * as session from 'express-session'; -import * as expressValidator from 'express-validator'; +import * as cors from 'cors' +import { Application } from 'express' +import * as flash from 'express-flash' +import * as compress from 'compression' +import * as connect from 'connect-mongo' +import * as bodyParser from 'body-parser' +import * as session from 'express-session' +import * as expressValidator from 'express-validator' -import Log from './Log'; -import Locals from '../providers/Locals'; -import Passport from '../providers/Passport'; +import Log from './Log' +import Locals from '../providers/Locals' +import Passport from '../providers/Passport' -const MongoStore = connect(session); +const MongoStore = connect(session) class Http { - public static mount(_express: Application): Application { - Log.info('Booting the \'HTTP\' middleware...'); - - // Enables the request body parser - _express.use(bodyParser.json({ - limit: Locals.config().maxUploadLimit - })); - - _express.use(bodyParser.urlencoded({ - limit: Locals.config().maxUploadLimit, - parameterLimit: Locals.config().maxParameterLimit, - extended: false - })); - - // Disable the x-powered-by header in response - _express.disable('x-powered-by'); - - // Enables the request payload validator - _express.use(expressValidator()); - - // Enables the request flash messages - _express.use(flash()); - - /** - * Enables the session store - * - * Note: You can also add redis-store - * into the options object. - */ - const options = { - resave: true, - saveUninitialized: true, - secret: Locals.config().appSecret, - cookie: { - maxAge: 1209600000 // two weeks (in ms) - }, - store: new MongoStore({ - url: process.env.MONGOOSE_URL, - autoReconnect: true - }) - }; - - _express.use(session(options)); - - // Enables the CORS - _express.use(cors()); - - // Enables the "gzip" / "deflate" compression for response - _express.use(compress()); - - // Loads the passport configuration - _express = Passport.mountPackage(_express); - - return _express; - } + public static mount(_express: Application): Application { + Log.info("Booting the 'HTTP' middleware...") + + // Enables the request body parser + _express.use( + bodyParser.json({ + limit: Locals.config().maxUploadLimit, + }) + ) + + _express.use( + bodyParser.urlencoded({ + limit: Locals.config().maxUploadLimit, + parameterLimit: Locals.config().maxParameterLimit, + extended: false, + }) + ) + + // Disable the x-powered-by header in response + _express.disable('x-powered-by') + + // Enables the request payload validator + _express.use(expressValidator()) + + // Enables the request flash messages + _express.use(flash()) + + /** + * Enables the session store + * + * Note: You can also add redis-store + * into the options object. + */ + const options = { + resave: true, + saveUninitialized: true, + secret: Locals.config().appSecret, + cookie: { + maxAge: 1209600000, // two weeks (in ms) + }, + store: new MongoStore({ + url: process.env.MONGOOSE_URL, + autoReconnect: true, + }), + } + + _express.use(session(options)) + + // Enables the CORS + _express.use(cors()) + + // Enables the "gzip" / "deflate" compression for response + _express.use(compress()) + + // Loads the passport configuration + _express = Passport.mountPackage(_express) + + return _express + } } -export default Http; +export default Http diff --git a/src/middlewares/Kernel.ts b/src/middlewares/Kernel.ts index d2d6f0e..1c6d47c 100644 --- a/src/middlewares/Kernel.ts +++ b/src/middlewares/Kernel.ts @@ -4,42 +4,42 @@ * @author Faiz A. Farooqui */ -import { Application } from 'express'; +import { Application } from 'express' -import CORS from './CORS'; -import Http from './Http'; -import Views from './Views'; -import Statics from './Statics'; -import CsrfToken from './CsrfToken'; -import StatusMonitor from './StatusMonitor'; +import CORS from './CORS' +import Http from './Http' +import Views from './Views' +import Statics from './Statics' +import CsrfToken from './CsrfToken' +import StatusMonitor from './StatusMonitor' -import Locals from '../providers/Locals'; +import Locals from '../providers/Locals' class Kernel { - public static init (_express: Application): Application { - // Check if CORS is enabled - if (Locals.config().isCORSEnabled) { - // Mount CORS middleware - _express = CORS.mount(_express); - } + public static init(_express: Application): Application { + // Check if CORS is enabled + if (Locals.config().isCORSEnabled) { + // Mount CORS middleware + _express = CORS.mount(_express) + } - // Mount basic express apis middleware - _express = Http.mount(_express); + // Mount basic express apis middleware + _express = Http.mount(_express) - // Mount csrf token verification middleware - _express = CsrfToken.mount(_express); + // Mount csrf token verification middleware + _express = CsrfToken.mount(_express) - // Mount view engine middleware - _express = Views.mount(_express); + // Mount view engine middleware + _express = Views.mount(_express) - // Mount statics middleware - _express = Statics.mount(_express); + // Mount statics middleware + _express = Statics.mount(_express) - // Mount status monitor middleware - _express = StatusMonitor.mount(_express); + // Mount status monitor middleware + _express = StatusMonitor.mount(_express) - return _express; - } + return _express + } } -export default Kernel; +export default Kernel diff --git a/src/middlewares/Log.ts b/src/middlewares/Log.ts index aea6005..20b5068 100644 --- a/src/middlewares/Log.ts +++ b/src/middlewares/Log.ts @@ -2,87 +2,92 @@ * Creates & maintains the log */ -import * as fs from 'fs'; -import * as path from 'path'; +import * as fs from 'fs' +import * as path from 'path' class Log { - public baseDir: string; - public fileName: string; - public linePrefix: string; + public baseDir: string + public fileName: string + public linePrefix: string - public today: Date = new Date(); + public today: Date = new Date() - constructor() { - let _dateString = `${this.today.getFullYear()}-${(this.today.getMonth() + 1)}-${this.today.getDate()}`; - let _timeString = `${this.today.getHours()}:${this.today.getMinutes()}:${this.today.getSeconds()}`; + constructor() { + let _dateString = `${this.today.getFullYear()}-${ + this.today.getMonth() + 1 + }-${this.today.getDate()}` + let _timeString = `${this.today.getHours()}:${this.today.getMinutes()}:${this.today.getSeconds()}` - this.baseDir = path.join(__dirname, '../../.logs/'); + this.baseDir = path.join(__dirname, '../../.logs/') - this.fileName = `${_dateString}.log`; - this.linePrefix = `[${_dateString} ${_timeString}]`; - } + this.fileName = `${_dateString}.log` + this.linePrefix = `[${_dateString} ${_timeString}]` + } - // Adds INFO prefix string to the log string - public info (_string: string): void { - this.addLog('INFO', _string); - } + // Adds INFO prefix string to the log string + public info(_string: string): void { + this.addLog('INFO', _string) + } - // Adds WARN prefix string to the log string - public warn (_string: string): void { - this.addLog('WARN', _string); - } + // Adds WARN prefix string to the log string + public warn(_string: string): void { + this.addLog('WARN', _string) + } - // Adds ERROR prefix string to the log string - public error (_string: string): void { - // Line break and show the first line - console.log('\x1b[31m%s\x1b[0m', '[ERROR] :: ' + _string.split(/r?\n/)[0]); + // Adds ERROR prefix string to the log string + public error(_string: string): void { + // Line break and show the first line + console.log('\x1b[31m%s\x1b[0m', '[ERROR] :: ' + _string.split(/r?\n/)[0]) - this.addLog('ERROR', _string); - } + this.addLog('ERROR', _string) + } - // Adds the custom prefix string to the log string - public custom (_filename: string, _string: string): void { - this.addLog(_filename, _string); - } + // Adds the custom prefix string to the log string + public custom(_filename: string, _string: string): void { + this.addLog(_filename, _string) + } - /** - * Creates the file if does not exist, and - * append the log kind & string into the file. - */ - private addLog (_kind: string, _string: string): void { - const _that = this; - _kind = _kind.toUpperCase(); + /** + * Creates the file if does not exist, and + * append the log kind & string into the file. + */ + private addLog(_kind: string, _string: string): void { + const _that = this + _kind = _kind.toUpperCase() - fs.open(`${_that.baseDir}${_that.fileName}`, 'a', (_err, _fileDescriptor) => { - if (!_err && _fileDescriptor) { - // Append to file and close it - fs.appendFile(_fileDescriptor, `${_that.linePrefix} [${_kind}] ${_string}\n`, (_err) => { - if (! _err) { - fs.close(_fileDescriptor, (_err) => { - if (! _err) { - return true; - } else { - return console.log('\x1b[31m%s\x1b[0m', 'Error closing log file that was being appended'); - } - }); - } else { - return console.log('\x1b[31m%s\x1b[0m', 'Error appending to the log file'); - } - }); - } else { - return console.log('\x1b[31m%s\x1b[0m', 'Error cloudn\'t open the log file for appending'); - } - }); - } + fs.open(`${_that.baseDir}${_that.fileName}`, 'a', (_err, _fileDescriptor) => { + if (!_err && _fileDescriptor) { + // Append to file and close it + fs.appendFile(_fileDescriptor, `${_that.linePrefix} [${_kind}] ${_string}\n`, _err => { + if (!_err) { + fs.close(_fileDescriptor, _err => { + if (!_err) { + return true + } else { + return console.log( + '\x1b[31m%s\x1b[0m', + 'Error closing log file that was being appended' + ) + } + }) + } else { + return console.log('\x1b[31m%s\x1b[0m', 'Error appending to the log file') + } + }) + } else { + return console.log('\x1b[31m%s\x1b[0m', "Error cloudn't open the log file for appending") + } + }) + } - /** - * Deletes the log files older than 'X' days - * - * Note: 'X' is defined in .env file - */ - public clean (): void { - // - } + /** + * Deletes the log files older than 'X' days + * + * Note: 'X' is defined in .env file + */ + public clean(): void { + // + } } -export default new Log; +export default new Log() diff --git a/src/middlewares/Statics.ts b/src/middlewares/Statics.ts index 1b7afd2..cfa4b0f 100644 --- a/src/middlewares/Statics.ts +++ b/src/middlewares/Statics.ts @@ -4,26 +4,26 @@ * @author Faiz A. Farooqui */ -import * as path from 'path'; -import * as express from 'express'; +import * as path from 'path' +import * as express from 'express' -import Log from './Log'; +import Log from './Log' class Statics { - public static mount(_express: express.Application): express.Application { - Log.info('Booting the \'Statics\' middleware...'); + public static mount(_express: express.Application): express.Application { + Log.info("Booting the 'Statics' middleware...") - // Loads Options - const options = { maxAge: 31557600000 }; + // Loads Options + const options = { maxAge: 31557600000 } - // Load Statics - _express.use('/public', express.static(path.join(__dirname, '../../public'), options)); + // Load Statics + _express.use('/public', express.static(path.join(__dirname, '../../public'), options)) - // Load NPM Statics - _express.use('/vendor', express.static(path.join(__dirname, '../../node_modules'), options)); + // Load NPM Statics + _express.use('/vendor', express.static(path.join(__dirname, '../../node_modules'), options)) - return _express; - } + return _express + } } -export default Statics; +export default Statics diff --git a/src/middlewares/StatusMonitor.ts b/src/middlewares/StatusMonitor.ts index 2810ef8..7427538 100644 --- a/src/middlewares/StatusMonitor.ts +++ b/src/middlewares/StatusMonitor.ts @@ -4,65 +4,65 @@ * @author Faiz A. Farooqui */ -import { Application } from 'express'; -import * as expressStatusMonitor from 'express-status-monitor'; +import { Application } from 'express' +import * as expressStatusMonitor from 'express-status-monitor' -import Log from './Log'; -import Locals from '../providers/Locals'; +import Log from './Log' +import Locals from '../providers/Locals' class StatusMonitor { - public mount (_express: Application): Application { - Log.info('Booting the \'StatusMonitor\' middleware...'); + public mount(_express: Application): Application { + Log.info("Booting the 'StatusMonitor' middleware...") - const api: string = Locals.config().apiPrefix; + const api: string = Locals.config().apiPrefix - // Define your status monitor config - const monitorOptions: object = { - title: Locals.config().name, - path: '/status-monitor', - spans: [ - { - interval: 1, // Every second - retention: 60 // Keep 60 data-points in memory - }, - { - interval: 5, - retention: 60 - }, - { - interval: 15, - retention: 60 - } - ], - chartVisibility: { - mem: true, - rps: true, - cpu: true, - load: true, - statusCodes: true, - responseTime: true - }, - healthChecks: [ - { - protocol: 'http', - host: 'localhost', - path: '/', - port: '4040' - }, - { - protocol: 'http', - host: 'localhost', - path: `/${api}`, - port: '4040' - } - ] - }; + // Define your status monitor config + const monitorOptions: object = { + title: Locals.config().name, + path: '/status-monitor', + spans: [ + { + interval: 1, // Every second + retention: 60, // Keep 60 data-points in memory + }, + { + interval: 5, + retention: 60, + }, + { + interval: 15, + retention: 60, + }, + ], + chartVisibility: { + mem: true, + rps: true, + cpu: true, + load: true, + statusCodes: true, + responseTime: true, + }, + healthChecks: [ + { + protocol: 'http', + host: 'localhost', + path: '/', + port: '4040', + }, + { + protocol: 'http', + host: 'localhost', + path: `/${api}`, + port: '4040', + }, + ], + } - // Loads the express status monitor middleware - _express.use(expressStatusMonitor(monitorOptions)); + // Loads the express status monitor middleware + _express.use(expressStatusMonitor(monitorOptions)) - return _express; - } + return _express + } } -export default new StatusMonitor; +export default new StatusMonitor() diff --git a/src/middlewares/Views.ts b/src/middlewares/Views.ts index 4450080..706734c 100644 --- a/src/middlewares/Views.ts +++ b/src/middlewares/Views.ts @@ -4,22 +4,22 @@ * @author Faiz A. Farooqui */ -import * as path from 'path'; -import { Application } from 'express'; +import * as path from 'path' +import { Application } from 'express' -import Log from './Log'; +import Log from './Log' class Views { - public static mount(_express: Application): Application { - Log.info('Booting the \'Views\' middleware...'); + public static mount(_express: Application): Application { + Log.info("Booting the 'Views' middleware...") - _express.set('view engine', 'pug'); - _express.set('view options', { pretty: true }); - _express.set('views', path.join(__dirname, '../../views')); - _express.locals.pretty = true; + _express.set('view engine', 'pug') + _express.set('view options', { pretty: true }) + _express.set('views', path.join(__dirname, '../../views')) + _express.locals.pretty = true - return _express; - } + return _express + } } -export default Views; +export default Views diff --git a/src/models/User.ts b/src/models/User.ts index a985c11..b8bb031 100644 --- a/src/models/User.ts +++ b/src/models/User.ts @@ -4,97 +4,100 @@ * @author Faiz A. Farooqui */ -import * as crypto from 'crypto'; -import * as bcrypt from 'bcrypt-nodejs'; +import * as crypto from 'crypto' +import * as bcrypt from 'bcrypt-nodejs' -import { IUser } from '../interfaces/models/user'; -import mongoose from '../providers/Database'; +import { IUser } from '../interfaces/models/user' +import mongoose from '../providers/Database' // Create the model schema & register your custom methods here export interface IUserModel extends IUser, mongoose.Document { - billingAddress(): string; - comparePassword(password: string, cb: any): string; - validPassword(password: string, cb: any): string; - gravatar(_size: number): string; + billingAddress(): string + comparePassword(password: string, cb: any): string + validPassword(password: string, cb: any): string + gravatar(_size: number): string } // Define the User Schema -export const UserSchema = new mongoose.Schema({ - email: { type: String, unique: true }, - password: { type: String }, - passwordResetToken: { type: String }, - passwordResetExpires: Date, - - facebook: { type: String }, - twitter: { type: String }, - google: { type: String }, - github: { type: String }, - instagram: { type: String }, - linkedin: { type: String }, - steam: { type: String }, - tokens: Array, - - fullname: { type: String }, - gender: { type: String }, - geolocation: { type: String }, - website: { type: String }, - picture: { type: String } -}, { - timestamps: true -}); +export const UserSchema = new mongoose.Schema( + { + email: { type: String, unique: true }, + password: { type: String }, + passwordResetToken: { type: String }, + passwordResetExpires: Date, + + facebook: { type: String }, + twitter: { type: String }, + google: { type: String }, + github: { type: String }, + instagram: { type: String }, + linkedin: { type: String }, + steam: { type: String }, + tokens: Array, + + fullname: { type: String }, + gender: { type: String }, + geolocation: { type: String }, + website: { type: String }, + picture: { type: String }, + }, + { + timestamps: true, + } +) // Password hash middleware UserSchema.pre('save', function (_next) { - const user = this; - if (!user.isModified('password')) { - return _next(); - } - - bcrypt.genSalt(10, (_err, _salt) => { - if (_err) { - return _next(_err); - } - - bcrypt.hash(user.password, _salt, null, (_err, _hash) => { - if (_err) { - return _next(_err); - } - - user.password = _hash; - return _next(); - }); - }); -}); + const user = this + if (!user.isModified('password')) { + return _next() + } + + bcrypt.genSalt(10, (_err, _salt) => { + if (_err) { + return _next(_err) + } + + bcrypt.hash(user.password, _salt, null, (_err, _hash) => { + if (_err) { + return _next(_err) + } + + user.password = _hash + return _next() + }) + }) +}) // Custom Methods // Get user's full billing address UserSchema.methods.billingAddress = function (): string { - const fulladdress = `${this.fullname.trim()} ${this.geolocation.trim()}`; - return fulladdress; -}; + const fulladdress = `${this.fullname.trim()} ${this.geolocation.trim()}` + return fulladdress +} // Compares the user's password with the request password UserSchema.methods.comparePassword = function (_requestPassword, _cb): any { - bcrypt.compare(_requestPassword, this.password, (_err, _isMatch) => { - return _cb(_err, _isMatch); - }); -}; + bcrypt.compare(_requestPassword, this.password, (_err, _isMatch) => { + return _cb(_err, _isMatch) + }) +} // User's gravatar UserSchema.methods.gravatar = function (_size): any { - if (! _size) { - _size = 200; - } + if (!_size) { + _size = 200 + } - const url = 'https://gravatar.com/avatar'; - if (! this.email) { - return `${url}/?s=${_size}&d=retro`; - } + const url = 'https://gravatar.com/avatar' + if (!this.email) { + return `${url}/?s=${_size}&d=retro` + } - const md5 = crypto.createHash('md5').update(this.email).digest('hex'); - return `${url}/${md5}?s=${_size}&d=retro`; -}; + const md5 = crypto.createHash('md5').update(this.email).digest('hex') + return `${url}/${md5}?s=${_size}&d=retro` +} -const User = mongoose.model('User', UserSchema); +const User = mongoose.model('User', UserSchema) -export default User; +export default User diff --git a/src/providers/App.ts b/src/providers/App.ts index a424d3f..cc9ca98 100644 --- a/src/providers/App.ts +++ b/src/providers/App.ts @@ -4,64 +4,67 @@ * @author Faiz A. Farooqui */ -import * as kue from 'kue'; -import * as path from 'path'; -import * as dotenv from 'dotenv'; +import * as kue from 'kue' +import * as path from 'path' +import * as dotenv from 'dotenv' -import Express from './Express'; -import { Database } from './Database'; +import Express from './Express' +import { Database } from './Database' -import Queue from './Queue'; -import Locals from './Locals'; -import Log from '../middlewares/Log'; +import Queue from './Queue' +import Locals from './Locals' +import Log from '../middlewares/Log' class App { - // Clear the console - public clearConsole (): void { - process.stdout.write('\x1B[2J\x1B[0f'); - - Queue.dispatch('checkout', {foo: 'bar', fizz: 'buzz'}, function (data) { - console.log('>> here is the data', data); - }); - } - - // Loads your dotenv file - public loadConfiguration (): void { - Log.info('Configuration :: Booting @ Master...'); - - dotenv.config({ path: path.join(__dirname, '../../.env') }); - } - - // Loads your Server - public loadServer (): void { - Log.info('Server :: Booting @ Master...'); - - Express.init(); - } - - // Loads the Database Pool - public loadDatabase (): void { - Log.info('Database :: Booting @ Master...'); - - Database.init(); - } - - // Loads the Worker Cluster - public loadWorker (): void { - Log.info('Worker :: Booting @ Master...'); - } - - // Loads the Queue Monitor - public loadQueue (): void { - const isQueueMonitorEnabled: boolean = Locals.config().queueMonitor; - const queueMonitorPort: number = Locals.config().queueMonitorHttpPort; - - if (isQueueMonitorEnabled) { - kue.app.listen(queueMonitorPort); - - console.log('\x1b[33m%s\x1b[0m', `Queue Monitor :: Running @ 'http://localhost:${queueMonitorPort}'`); - } - } + // Clear the console + public clearConsole(): void { + process.stdout.write('\x1B[2J\x1B[0f') + + Queue.dispatch('checkout', { foo: 'bar', fizz: 'buzz' }, function (data) { + console.log('>> here is the data', data) + }) + } + + // Loads your dotenv file + public loadConfiguration(): void { + Log.info('Configuration :: Booting @ Master...') + + dotenv.config({ path: path.join(__dirname, '../../.env') }) + } + + // Loads your Server + public loadServer(): void { + Log.info('Server :: Booting @ Master...') + + Express.init() + } + + // Loads the Database Pool + public loadDatabase(): void { + Log.info('Database :: Booting @ Master...') + + Database.init() + } + + // Loads the Worker Cluster + public loadWorker(): void { + Log.info('Worker :: Booting @ Master...') + } + + // Loads the Queue Monitor + public loadQueue(): void { + const isQueueMonitorEnabled: boolean = Locals.config().queueMonitor + const queueMonitorPort: number = Locals.config().queueMonitorHttpPort + + if (isQueueMonitorEnabled) { + kue.app.listen(queueMonitorPort) + + console.log( + '\x1b[33m%s\x1b[0m', + `Queue Monitor :: Running @ 'http://localhost:${queueMonitorPort}'` + ) + } + } } -export default new App; +export default new App() diff --git a/src/providers/Cache.ts b/src/providers/Cache.ts index bd31f03..644e498 100644 --- a/src/providers/Cache.ts +++ b/src/providers/Cache.ts @@ -4,30 +4,30 @@ * @author Faiz A. Farooqui */ -import * as mcache from 'memory-cache'; +import * as mcache from 'memory-cache' class Cache { - /** - * Checks for the available cached data - * or adds if not available - */ - public cache(_duration: number): any { - return (req, res, next) => { - let key = '__express__' + req.originalUrl || req.url; + /** + * Checks for the available cached data + * or adds if not available + */ + public cache(_duration: number): any { + return (req, res, next) => { + let key = '__express__' + req.originalUrl || req.url - let cachedBody = mcache.get(key); - if (cachedBody) { - res.send(cachedBody); - } else { - res.sendResponse = res.send; - res.send = (body) => { - mcache.put(key, body, _duration * 1000); - res.sendResponse(body); - }; - next(); - } - }; - } + let cachedBody = mcache.get(key) + if (cachedBody) { + res.send(cachedBody) + } else { + res.sendResponse = res.send + res.send = body => { + mcache.put(key, body, _duration * 1000) + res.sendResponse(body) + } + next() + } + } + } } -export default new Cache; +export default new Cache() diff --git a/src/providers/Database.ts b/src/providers/Database.ts index 4ea5139..0053da8 100644 --- a/src/providers/Database.ts +++ b/src/providers/Database.ts @@ -4,34 +4,34 @@ * @author Faiz A. Farooqui */ -import * as mongoose from 'mongoose'; -import * as bluebird from 'bluebird'; -import { MongoError } from 'mongodb'; +import * as mongoose from 'mongoose' +import * as bluebird from 'bluebird' +import { MongoError } from 'mongodb' -import Locals from './Locals'; -import Log from '../middlewares/Log'; +import Locals from './Locals' +import Log from '../middlewares/Log' export class Database { - // Initialize your database pool - public static init (): any { - const dsn = Locals.config().mongooseUrl; - const options = { useNewUrlParser: true, useUnifiedTopology: true }; + // Initialize your database pool + public static init(): any { + const dsn = Locals.config().mongooseUrl + const options = { useNewUrlParser: true, useUnifiedTopology: true } - (mongoose).Promise = bluebird; + ;(mongoose).Promise = bluebird - mongoose.set('useCreateIndex', true); + mongoose.set('useCreateIndex', true) - mongoose.connect(dsn, options, (error: MongoError) => { - // handle the error case - if (error) { - Log.info('Failed to connect to the Mongo server!!'); - console.log(error); - throw error; - } else { - Log.info('connected to mongo server at: ' + dsn); - } - }); - } + mongoose.connect(dsn, options, (error: MongoError) => { + // handle the error case + if (error) { + Log.info('Failed to connect to the Mongo server!!') + console.log(error) + throw error + } else { + Log.info('connected to mongo server at: ' + dsn) + } + }) + } } -export default mongoose; +export default mongoose diff --git a/src/providers/Express.ts b/src/providers/Express.ts index ba097c1..8a6aa63 100644 --- a/src/providers/Express.ts +++ b/src/providers/Express.ts @@ -4,69 +4,71 @@ * @author Faiz A. Farooqui */ -import * as express from 'express'; +import * as express from 'express' -import Locals from './Locals'; -import Routes from './Routes'; -import Bootstrap from '../middlewares/Kernel'; -import ExceptionHandler from '../exception/Handler'; +import Locals from './Locals' +import Routes from './Routes' +import Bootstrap from '../middlewares/Kernel' +import ExceptionHandler from '../exception/Handler' class Express { - /** - * Create the express object - */ - public express: express.Application; + /** + * Create the express object + */ + public express: express.Application - /** - * Initializes the express server - */ - constructor () { - this.express = express(); + /** + * Initializes the express server + */ + constructor() { + this.express = express() - this.mountDotEnv(); - this.mountMiddlewares(); - this.mountRoutes(); - } + this.mountDotEnv() + this.mountMiddlewares() + this.mountRoutes() + } - private mountDotEnv (): void { - this.express = Locals.init(this.express); - } + private mountDotEnv(): void { + this.express = Locals.init(this.express) + } - /** - * Mounts all the defined middlewares - */ - private mountMiddlewares (): void { - this.express = Bootstrap.init(this.express); - } + /** + * Mounts all the defined middlewares + */ + private mountMiddlewares(): void { + this.express = Bootstrap.init(this.express) + } - /** - * Mounts all the defined routes - */ - private mountRoutes (): void { - this.express = Routes.mountWeb(this.express); - this.express = Routes.mountApi(this.express); - } + /** + * Mounts all the defined routes + */ + private mountRoutes(): void { + this.express = Routes.mountWeb(this.express) + this.express = Routes.mountApi(this.express) + } - /** - * Starts the express server - */ - public init (): any { - const port: number = Locals.config().port; + /** + * Starts the express server + */ + public init(): any { + const port: number = Locals.config().port - // Registering Exception / Error Handlers - this.express.use(ExceptionHandler.logErrors); - this.express.use(ExceptionHandler.clientErrorHandler); - this.express.use(ExceptionHandler.errorHandler); - this.express = ExceptionHandler.notFoundHandler(this.express); + // Registering Exception / Error Handlers + this.express.use(ExceptionHandler.logErrors) + this.express.use(ExceptionHandler.clientErrorHandler) + this.express.use(ExceptionHandler.errorHandler) + this.express = ExceptionHandler.notFoundHandler(this.express) - // Start the server on the specified port - this.express.listen(port, () => { - return console.log('\x1b[33m%s\x1b[0m', `Server :: Running @ 'http://localhost:${port}'`); - }).on('error', (_error) => { - return console.log('Error: ', _error.message); - });; - } + // Start the server on the specified port + this.express + .listen(port, () => { + return console.log('\x1b[33m%s\x1b[0m', `Server :: Running @ 'http://localhost:${port}'`) + }) + .on('error', _error => { + return console.log('Error: ', _error.message) + }) + } } /** Export the express module */ -export default new Express(); +export default new Express() diff --git a/src/providers/Locals.ts b/src/providers/Locals.ts index 5357671..9726f4b 100644 --- a/src/providers/Locals.ts +++ b/src/providers/Locals.ts @@ -4,78 +4,78 @@ * @author Faiz A. Farooqui */ -import { Application } from 'express'; -import * as path from 'path'; -import * as dotenv from 'dotenv'; +import { Application } from 'express' +import * as path from 'path' +import * as dotenv from 'dotenv' class Locals { - /** - * Makes env configs available for your app - * throughout the app's runtime - */ - public static config(): any { - dotenv.config({ path: path.join(__dirname, '../../.env') }); + /** + * Makes env configs available for your app + * throughout the app's runtime + */ + public static config(): any { + dotenv.config({ path: path.join(__dirname, '../../.env') }) - const url = process.env.APP_URL || `http://localhost:${process.env.PORT}`; - const port = process.env.PORT || 4040; - const appSecret = process.env.APP_SECRET || 'This is your responsibility!'; - const mongooseUrl = process.env.MONGOOSE_URL; - const maxUploadLimit = process.env.APP_MAX_UPLOAD_LIMIT || '50mb'; - const maxParameterLimit = process.env.APP_MAX_PARAMETER_LIMIT || '50mb'; + const url = process.env.APP_URL || `http://localhost:${process.env.PORT}` + const port = process.env.PORT || 4040 + const appSecret = process.env.APP_SECRET || 'This is your responsibility!' + const mongooseUrl = process.env.MONGOOSE_URL + const maxUploadLimit = process.env.APP_MAX_UPLOAD_LIMIT || '50mb' + const maxParameterLimit = process.env.APP_MAX_PARAMETER_LIMIT || '50mb' - const name = process.env.APP_NAME || 'NodeTS Dashboard'; - const keywords = process.env.APP_KEYWORDS || 'somethings'; - const year = (new Date()).getFullYear(); - const copyright = `Copyright ${year} ${name} | All Rights Reserved`; - const company = process.env.COMPANY_NAME || 'GeekyAnts'; - const description = process.env.APP_DESCRIPTION || 'Here goes the app description'; + const name = process.env.APP_NAME || 'NodeTS Dashboard' + const keywords = process.env.APP_KEYWORDS || 'somethings' + const year = new Date().getFullYear() + const copyright = `Copyright ${year} ${name} | All Rights Reserved` + const company = process.env.COMPANY_NAME || 'GeekyAnts' + const description = process.env.APP_DESCRIPTION || 'Here goes the app description' - const isCORSEnabled = process.env.CORS_ENABLED || true; - const jwtExpiresIn = process.env.JWT_EXPIRES_IN || 3; - const apiPrefix = process.env.API_PREFIX || 'api'; + const isCORSEnabled = process.env.CORS_ENABLED || true + const jwtExpiresIn = process.env.JWT_EXPIRES_IN || 3 + const apiPrefix = process.env.API_PREFIX || 'api' - const logDays = process.env.LOG_DAYS || 10; + const logDays = process.env.LOG_DAYS || 10 - const queueMonitor = process.env.QUEUE_HTTP_ENABLED || true; - const queueMonitorHttpPort = process.env.QUEUE_HTTP_PORT || 5550; + const queueMonitor = process.env.QUEUE_HTTP_ENABLED || true + const queueMonitorHttpPort = process.env.QUEUE_HTTP_PORT || 5550 - const redisHttpPort = process.env.REDIS_QUEUE_PORT || 6379; - const redisHttpHost = process.env.REDIS_QUEUE_HOST || '127.0.0.1'; - const redisPrefix = process.env.REDIS_QUEUE_DB || 'q'; - const redisDB = process.env.REDIS_QUEUE_PREFIX || 3; + const redisHttpPort = process.env.REDIS_QUEUE_PORT || 6379 + const redisHttpHost = process.env.REDIS_QUEUE_HOST || '127.0.0.1' + const redisPrefix = process.env.REDIS_QUEUE_DB || 'q' + const redisDB = process.env.REDIS_QUEUE_PREFIX || 3 - return { - appSecret, - apiPrefix, - company, - copyright, - description, - isCORSEnabled, - jwtExpiresIn, - keywords, - logDays, - maxUploadLimit, - maxParameterLimit, - mongooseUrl, - name, - port, - redisDB, - redisHttpPort, - redisHttpHost, - redisPrefix, - url, - queueMonitor, - queueMonitorHttpPort - }; - } + return { + appSecret, + apiPrefix, + company, + copyright, + description, + isCORSEnabled, + jwtExpiresIn, + keywords, + logDays, + maxUploadLimit, + maxParameterLimit, + mongooseUrl, + name, + port, + redisDB, + redisHttpPort, + redisHttpHost, + redisPrefix, + url, + queueMonitor, + queueMonitorHttpPort, + } + } - /** - * Injects your config to the app's locals - */ - public static init (_express: Application): Application { - _express.locals.app = this.config(); - return _express; - } + /** + * Injects your config to the app's locals + */ + public static init(_express: Application): Application { + _express.locals.app = this.config() + return _express + } } -export default Locals; +export default Locals diff --git a/src/providers/Passport.ts b/src/providers/Passport.ts index 2809490..9dd370e 100644 --- a/src/providers/Passport.ts +++ b/src/providers/Passport.ts @@ -4,64 +4,64 @@ * @author Faiz A. Farooqui */ -import { Application } from 'express'; -import * as passport from 'passport'; +import { Application } from 'express' +import * as passport from 'passport' -import LocalStrategy from '../services/strategies/Local'; -import GoogleStrategy from '../services/strategies/Google'; -import TwitterStrategy from '../services/strategies/Twitter'; +import LocalStrategy from '../services/strategies/Local' +import GoogleStrategy from '../services/strategies/Google' +import TwitterStrategy from '../services/strategies/Twitter' -import User from '../models/User'; -import Log from '../middlewares/Log'; +import User from '../models/User' +import Log from '../middlewares/Log' class Passport { - public mountPackage (_express: Application): Application { - _express = _express.use(passport.initialize()); - _express = _express.use(passport.session()); + public mountPackage(_express: Application): Application { + _express = _express.use(passport.initialize()) + _express = _express.use(passport.session()) - passport.serializeUser((user, done) => { - done(null, user.id); - }); + passport.serializeUser((user, done) => { + done(null, user.id) + }) - passport.deserializeUser((id, done) => { - User.findById(id, (err, user) => { - done(err, user); - }); - }); + passport.deserializeUser((id, done) => { + User.findById(id, (err, user) => { + done(err, user) + }) + }) - this.mountLocalStrategies(); + this.mountLocalStrategies() - return _express; - } + return _express + } - public mountLocalStrategies(): void { - try { - LocalStrategy.init(passport); - GoogleStrategy.init(passport); - TwitterStrategy.init(passport); - } catch (_err) { - Log.error(_err.stack); - } - } + public mountLocalStrategies(): void { + try { + LocalStrategy.init(passport) + GoogleStrategy.init(passport) + TwitterStrategy.init(passport) + } catch (_err) { + Log.error(_err.stack) + } + } - public isAuthenticated (req, res, next): any { - if (req.isAuthenticated()) { - return next(); - } + public isAuthenticated(req, res, next): any { + if (req.isAuthenticated()) { + return next() + } - req.flash('errors', { msg: 'Please Log-In to access any further!'}); - return res.redirect('/login'); - } + req.flash('errors', { msg: 'Please Log-In to access any further!' }) + return res.redirect('/login') + } - public isAuthorized (req, res, next): any { - const provider = req.path.split('/').slice(-1)[0]; - const token = req.user.tokens.find(token => token.kind === provider); - if (token) { - return next(); - } else { - return res.redirect(`/auth/${provider}`); - } - } + public isAuthorized(req, res, next): any { + const provider = req.path.split('/').slice(-1)[0] + const token = req.user.tokens.find(token => token.kind === provider) + if (token) { + return next() + } else { + return res.redirect(`/auth/${provider}`) + } + } } -export default new Passport; +export default new Passport() diff --git a/src/providers/Queue.ts b/src/providers/Queue.ts index 7ed86e4..853020b 100644 --- a/src/providers/Queue.ts +++ b/src/providers/Queue.ts @@ -4,56 +4,60 @@ * @author Faiz A. Farooqui */ -import * as kue from 'kue'; +import * as kue from 'kue' -import Locals from './Locals'; -import Log from '../middlewares/Log'; +import Locals from './Locals' +import Log from '../middlewares/Log' class Queue { - public jobs: any; - - constructor() { - this.jobs = kue.createQueue({ - prefix: Locals.config().redisPrefix, - redis: { - port: Locals.config().redisHttpPort, - host: Locals.config().redisHttpHost, - db: Locals.config().redisDB - } - }); - - this.jobs - .on('job enqueue', (_id, _type) => Log.info(`Queue :: #${_id} Processing of type '${_type}'`)) - .on('job complete', (_id) => this.removeProcessedJob(_id)); - } - - public dispatch (_jobName: string, _args: object, _callback: Function): void { - this.jobs.create(_jobName, _args).save(); - - this.process(_jobName, 3, _callback); - } - - private removeProcessedJob (_id): void { - Log.info(`Queue :: #${_id} Processed`); - - kue.Job.get(_id, (_err, _job) => { - if (_err) { return; } - - _job.remove((_err) => { - if (_err) { throw _err; } - - Log.info(`Queue :: #${_id} Removed Processed Job`); - }); - }); - } - - private process (_jobName: string, _count: number, _callback: Function): void { - this.jobs.process(_jobName, _count, (_job, _done) => { - _done(); // Notifies KUE about the completion of the job! - - _callback(_job.data); - }); - } + public jobs: any + + constructor() { + this.jobs = kue.createQueue({ + prefix: Locals.config().redisPrefix, + redis: { + port: Locals.config().redisHttpPort, + host: Locals.config().redisHttpHost, + db: Locals.config().redisDB, + }, + }) + + this.jobs + .on('job enqueue', (_id, _type) => Log.info(`Queue :: #${_id} Processing of type '${_type}'`)) + .on('job complete', _id => this.removeProcessedJob(_id)) + } + + public dispatch(_jobName: string, _args: object, _callback: Function): void { + this.jobs.create(_jobName, _args).save() + + this.process(_jobName, 3, _callback) + } + + private removeProcessedJob(_id): void { + Log.info(`Queue :: #${_id} Processed`) + + kue.Job.get(_id, (_err, _job) => { + if (_err) { + return + } + + _job.remove(_err => { + if (_err) { + throw _err + } + + Log.info(`Queue :: #${_id} Removed Processed Job`) + }) + }) + } + + private process(_jobName: string, _count: number, _callback: Function): void { + this.jobs.process(_jobName, _count, (_job, _done) => { + _done() // Notifies KUE about the completion of the job! + + _callback(_job.data) + }) + } } -export default new Queue; +export default new Queue() diff --git a/src/providers/Routes.ts b/src/providers/Routes.ts index 097ad84..49bd074 100644 --- a/src/providers/Routes.ts +++ b/src/providers/Routes.ts @@ -4,26 +4,26 @@ * @author Faiz A. Farooqui */ -import { Application } from 'express'; -import Locals from './Locals'; -import Log from '../middlewares/Log'; +import { Application } from 'express' +import Locals from './Locals' +import Log from '../middlewares/Log' -import webRouter from './../routes/Web'; -import apiRouter from './../routes/Api'; +import webRouter from './../routes/Web' +import apiRouter from './../routes/Api' class Routes { - public mountWeb(_express: Application): Application { - Log.info('Routes :: Mounting Web Routes...'); + public mountWeb(_express: Application): Application { + Log.info('Routes :: Mounting Web Routes...') - return _express.use('/', webRouter); - } + return _express.use('/', webRouter) + } - public mountApi(_express: Application): Application { - const apiPrefix = Locals.config().apiPrefix; - Log.info('Routes :: Mounting API Routes...'); + public mountApi(_express: Application): Application { + const apiPrefix = Locals.config().apiPrefix + Log.info('Routes :: Mounting API Routes...') - return _express.use(`/${apiPrefix}`, apiRouter); - } + return _express.use(`/${apiPrefix}`, apiRouter) + } } -export default new Routes; +export default new Routes() diff --git a/src/routes/Api.ts b/src/routes/Api.ts index 81f4262..6c9a079 100644 --- a/src/routes/Api.ts +++ b/src/routes/Api.ts @@ -4,22 +4,26 @@ * @author Faiz A. Farooqui */ -import { Router } from 'express'; -import * as expressJwt from 'express-jwt'; +import { Router } from 'express' +import * as expressJwt from 'express-jwt' -import Locals from '../providers/Locals'; +import Locals from '../providers/Locals' -import HomeController from '../controllers/Api/Home'; -import LoginController from '../controllers/Api/Auth/Login'; -import RegisterController from '../controllers/Api/Auth/Register'; -import RefreshTokenController from '../controllers/Api/Auth/RefreshToken'; +import HomeController from '../controllers/Api/Home' +import LoginController from '../controllers/Api/Auth/Login' +import RegisterController from '../controllers/Api/Auth/Register' +import RefreshTokenController from '../controllers/Api/Auth/RefreshToken' -const router = Router(); +const router = Router() -router.get('/', HomeController.index); +router.get('/', HomeController.index) -router.post('/auth/login', LoginController.perform); -router.post('/auth/register', RegisterController.perform); -router.post('/auth/refresh-token', expressJwt({ secret: Locals.config().appSecret }), RefreshTokenController.perform); +router.post('/auth/login', LoginController.perform) +router.post('/auth/register', RegisterController.perform) +router.post( + '/auth/refresh-token', + expressJwt({ secret: Locals.config().appSecret }), + RefreshTokenController.perform +) -export default router; +export default router diff --git a/src/routes/Web.ts b/src/routes/Web.ts index 99f7cd9..d1e5556 100644 --- a/src/routes/Web.ts +++ b/src/routes/Web.ts @@ -4,40 +4,51 @@ * @author Faiz A. Farooqui */ -import * as passport from 'passport'; -import { Router } from 'express'; - -import Cache from './../providers/Cache'; -import Passport from './../providers/Passport'; - -import HomeController from '../controllers/Home'; -import AccountController from '../controllers/Account'; -import LoginController from '../controllers/Auth/Login'; -import LogoutController from '../controllers/Auth/Logout'; -import SocialController from '../controllers/Auth/Social'; -import RegisterController from '../controllers/Auth/Register'; - -const router = Router(); -const cache = Cache.cache; - -router.get('/', cache(10), HomeController.index); - -router.get('/signup', cache(10), RegisterController.show); -router.post('/signup', RegisterController.perform); - -router.get('/login', cache(10), LoginController.show); -router.post('/login', LoginController.perform); - -router.get('/logout', LogoutController.perform); - -router.get('/account', Passport.isAuthenticated, AccountController.index); - -router.get('/auth/google', passport.authenticate('google', { scope: ['email', 'profile'], failureRedirect: '/login' })); -router.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), SocialController.googleCallback); - -router.get('/auth/twitter', passport.authenticate('twitter')); -router.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), (req, res) => { - res.redirect('/'); -}); - -export default router; +import * as passport from 'passport' +import { Router } from 'express' + +import Cache from './../providers/Cache' +import Passport from './../providers/Passport' + +import HomeController from '../controllers/Home' +import AccountController from '../controllers/Account' +import LoginController from '../controllers/Auth/Login' +import LogoutController from '../controllers/Auth/Logout' +import SocialController from '../controllers/Auth/Social' +import RegisterController from '../controllers/Auth/Register' + +const router = Router() +const cache = Cache.cache + +router.get('/', cache(10), HomeController.index) + +router.get('/signup', cache(10), RegisterController.show) +router.post('/signup', RegisterController.perform) + +router.get('/login', cache(10), LoginController.show) +router.post('/login', LoginController.perform) + +router.get('/logout', LogoutController.perform) + +router.get('/account', Passport.isAuthenticated, AccountController.index) + +router.get( + '/auth/google', + passport.authenticate('google', { scope: ['email', 'profile'], failureRedirect: '/login' }) +) +router.get( + '/auth/google/callback', + passport.authenticate('google', { failureRedirect: '/login' }), + SocialController.googleCallback +) + +router.get('/auth/twitter', passport.authenticate('twitter')) +router.get( + '/auth/twitter/callback', + passport.authenticate('twitter', { failureRedirect: '/login' }), + (req, res) => { + res.redirect('/') + } +) + +export default router diff --git a/src/services/strategies/Google.ts b/src/services/strategies/Google.ts index 947708c..8fe7a88 100644 --- a/src/services/strategies/Google.ts +++ b/src/services/strategies/Google.ts @@ -4,86 +4,95 @@ * @author Faiz A. Farooqui */ -import { Strategy } from 'passport-google-oauth20'; -import User from '../../models/User'; -import Locals from '../../providers/Locals'; +import { Strategy } from 'passport-google-oauth20' +import User from '../../models/User' +import Locals from '../../providers/Locals' class Google { - public static init (_passport: any): any { - _passport.use(new Strategy({ - clientID: process.env.GOOGLE_ID, - clientSecret: process.env.GOOGLE_SECRET, - callbackURL: `${Locals.config().url}/auth/google/callback`, - passReqToCallback: true - }, (req, accessToken, refreshToken, profile, done) => { - if (req.user) { - User.findOne({ google: profile.id }, (err, existingUser) => { - if (err) { - return done(err); - } + public static init(_passport: any): any { + _passport.use( + new Strategy( + { + clientID: process.env.GOOGLE_ID, + clientSecret: process.env.GOOGLE_SECRET, + callbackURL: `${Locals.config().url}/auth/google/callback`, + passReqToCallback: true, + }, + (req, accessToken, refreshToken, profile, done) => { + if (req.user) { + User.findOne({ google: profile.id }, (err, existingUser) => { + if (err) { + return done(err) + } - if (existingUser) { - req.flash('errors', { msg: 'There is already a Google account that belongs to you. Sign in with that account or delete it, then link it with your current account.' }); - return done(err); - } else { - User.findById(req.user.id, (err, user) => { - if (err) { - return done(err); - } + if (existingUser) { + req.flash('errors', { + msg: 'There is already a Google account that belongs to you. Sign in with that account or delete it, then link it with your current account.', + }) + return done(err) + } else { + User.findById(req.user.id, (err, user) => { + if (err) { + return done(err) + } - user.google = profile.id; - user.tokens.push({ kind: 'google', accessToken }); - user.fullname = user.fullname || profile.displayName; - user.gender = user.gender || profile._json.gender; - if (profile.photos) { - user.picture = user.picture || profile.photos[0].value; - } - user.save((err) => { - req.flash('info', { msg: 'Google account has been linked.' }); - return done(err, user); - }); - }); - } - }); - } else { - User.findOne({ google: profile.id }, (err, existingUser) => { - if (err) { - return done(err); - } + user.google = profile.id + user.tokens.push({ kind: 'google', accessToken }) + user.fullname = user.fullname || profile.displayName + user.gender = user.gender || profile._json.gender + if (profile.photos) { + user.picture = user.picture || profile.photos[0].value + } + user.save(err => { + req.flash('info', { msg: 'Google account has been linked.' }) + return done(err, user) + }) + }) + } + }) + } else { + User.findOne({ google: profile.id }, (err, existingUser) => { + if (err) { + return done(err) + } - if (existingUser) { - return done(null, existingUser); - } + if (existingUser) { + return done(null, existingUser) + } - User.findOne({ email: profile.emails[0].value }, (err, existingEmailUser) => { - if (err) { - return done(err); - } + User.findOne({ email: profile.emails[0].value }, (err, existingEmailUser) => { + if (err) { + return done(err) + } - if (existingEmailUser) { - req.flash('errors', { msg: 'There is already an account using this email address. Sing in to that accoount and link it with Google manually from Account Settings.' }); - return done(err); - } else { - const user = new User(); + if (existingEmailUser) { + req.flash('errors', { + msg: 'There is already an account using this email address. Sing in to that accoount and link it with Google manually from Account Settings.', + }) + return done(err) + } else { + const user = new User() - user.email = profile.emails[0].value; - user.google = profile.id; - user.tokens.push({ kind: 'google', accessToken }); - user.fullname = user.fullname || profile.displayName; - user.gender = user.gender || profile._json.gender; - if (profile.photos) { - user.picture = user.picture || profile.photos[0].value; - } - - user.save((err) => { - return done(err, user); - }); - } - }); - }); - } - })); - } + user.email = profile.emails[0].value + user.google = profile.id + user.tokens.push({ kind: 'google', accessToken }) + user.fullname = user.fullname || profile.displayName + user.gender = user.gender || profile._json.gender + if (profile.photos) { + user.picture = user.picture || profile.photos[0].value + } + + user.save(err => { + return done(err, user) + }) + } + }) + }) + } + } + ) + ) + } } -export default Google; +export default Google diff --git a/src/services/strategies/Local.ts b/src/services/strategies/Local.ts index 569256b..cf8dabb 100644 --- a/src/services/strategies/Local.ts +++ b/src/services/strategies/Local.ts @@ -4,46 +4,50 @@ * @author Faiz A. Farooqui */ -import { Strategy } from 'passport-local'; -import User from '../../models/User'; -import Log from '../../middlewares/Log'; +import { Strategy } from 'passport-local' +import User from '../../models/User' +import Log from '../../middlewares/Log' class Local { - public static init (_passport: any): any { - _passport.use(new Strategy({ usernameField: 'email' }, (email, password, done) => { - Log.info(`Email is ${email}`); - Log.info(`Password is ${password}`); - - User.findOne({ email: email.toLowerCase() }, (err, user) => { - Log.info(`user is ${user.email}`); - Log.info(`error is ${err}`); - - if (err) { - return done(err); - } - - if (! user) { - return done(null, false, { msg: `E-mail ${email} not found.`}); - } - - if (user && !user.password) { - return done(null, false, { msg: `E-mail ${email} was not registered with us using any password. Please use the appropriate providers to Log-In again!`}); - } - - Log.info('comparing password now!'); - - user.comparePassword(password, (_err, _isMatch) => { - if (_err) { - return done(_err); - } - if (_isMatch) { - return done(null, user); - } - return done(null, false, { msg: 'Invalid E-mail or password.'}); - }); - }); - })); - } + public static init(_passport: any): any { + _passport.use( + new Strategy({ usernameField: 'email' }, (email, password, done) => { + Log.info(`Email is ${email}`) + Log.info(`Password is ${password}`) + + User.findOne({ email: email.toLowerCase() }, (err, user) => { + Log.info(`user is ${user.email}`) + Log.info(`error is ${err}`) + + if (err) { + return done(err) + } + + if (!user) { + return done(null, false, { msg: `E-mail ${email} not found.` }) + } + + if (user && !user.password) { + return done(null, false, { + msg: `E-mail ${email} was not registered with us using any password. Please use the appropriate providers to Log-In again!`, + }) + } + + Log.info('comparing password now!') + + user.comparePassword(password, (_err, _isMatch) => { + if (_err) { + return done(_err) + } + if (_isMatch) { + return done(null, user) + } + return done(null, false, { msg: 'Invalid E-mail or password.' }) + }) + }) + }) + ) + } } -export default Local; +export default Local diff --git a/src/services/strategies/Twitter.ts b/src/services/strategies/Twitter.ts index c188692..c768149 100644 --- a/src/services/strategies/Twitter.ts +++ b/src/services/strategies/Twitter.ts @@ -4,75 +4,82 @@ * @author Faiz A. Farooqui */ -import { Strategy } from 'passport-twitter'; -import User from '../../models/User'; -import Locals from '../../providers/Locals'; +import { Strategy } from 'passport-twitter' +import User from '../../models/User' +import Locals from '../../providers/Locals' class Twitter { - public static init (_passport: any): any { - _passport.use(new Strategy({ - consumerKey: process.env.TWITTER_KEY, - consumerSecret: process.env.TWITTER_SECRET, - callbackURL: `${Locals.config().url}/auth/twitter/callback`, - passReqToCallback: true - }, (req, accessToken, tokenSecret, profile, done) => { - if (req.user) { - User.findOne({ twitter: profile.id }, (err, existingUser) => { - if (err) { - return done(err); - } + public static init(_passport: any): any { + _passport.use( + new Strategy( + { + consumerKey: process.env.TWITTER_KEY, + consumerSecret: process.env.TWITTER_SECRET, + callbackURL: `${Locals.config().url}/auth/twitter/callback`, + passReqToCallback: true, + }, + (req, accessToken, tokenSecret, profile, done) => { + if (req.user) { + User.findOne({ twitter: profile.id }, (err, existingUser) => { + if (err) { + return done(err) + } - if (existingUser) { - req.flash('errors', { msg: 'There is already a Twitter account that belongs to you. Sign in with that account or delete it, then link it with your current account.' }); - return done(err); - } else { - User.findById(req.user.id, (err, user) => { - if (err) { - return done(err); - } + if (existingUser) { + req.flash('errors', { + msg: 'There is already a Twitter account that belongs to you. Sign in with that account or delete it, then link it with your current account.', + }) + return done(err) + } else { + User.findById(req.user.id, (err, user) => { + if (err) { + return done(err) + } - user.twitter = profile.id; - user.tokens.push({ kind: 'twitter', accessToken, tokenSecret }); - user.fullname = user.fullname || profile.displayName; - user.geolocation = user.geolocation || profile._json.location; - user.picture = user.picture || profile._json.profile_image_url_https; - user.save((err) => { - if (err) { - return done(err); - } + user.twitter = profile.id + user.tokens.push({ kind: 'twitter', accessToken, tokenSecret }) + user.fullname = user.fullname || profile.displayName + user.geolocation = user.geolocation || profile._json.location + user.picture = user.picture || profile._json.profile_image_url_https + user.save(err => { + if (err) { + return done(err) + } - req.flash('info', { msg: 'Twitter account has been linked.' }); - return done(err, user); - }); - }); - } - }); - } else { - User.findOne({ twitter: profile.id }, (err, existingUser) => { - if (err) { - return done(err); - } + req.flash('info', { msg: 'Twitter account has been linked.' }) + return done(err, user) + }) + }) + } + }) + } else { + User.findOne({ twitter: profile.id }, (err, existingUser) => { + if (err) { + return done(err) + } - if (existingUser) { - return done(null, existingUser); - } + if (existingUser) { + return done(null, existingUser) + } - const user = new User(); - // Twitter does not provides the user's e-mail address. - // We can "fake" a twitter email address as follows: - user.email = `${profile.username}@twitter.com`; - user.twitter = profile.id; - user.tokens.push({ kind: 'twitter', accessToken, tokenSecret }); - user.fullname = profile.displayName; - user.geolocation = profile._json.location; - user.picture = profile._json.profile_image_url_https; - user.save((err) => { - done(err, user); - }); - }); - } - })); - } + const user = new User() + // Twitter does not provides the user's e-mail address. + // We can "fake" a twitter email address as follows: + user.email = `${profile.username}@twitter.com` + user.twitter = profile.id + user.tokens.push({ kind: 'twitter', accessToken, tokenSecret }) + user.fullname = profile.displayName + user.geolocation = profile._json.location + user.picture = profile._json.profile_image_url_https + user.save(err => { + done(err, user) + }) + }) + } + } + ) + ) + } } -export default Twitter; +export default Twitter From 99e5a24134d249c5a5293103bece67e2ecea712a Mon Sep 17 00:00:00 2001 From: Ahmed Meftah Date: Fri, 24 Jun 2022 20:24:39 +0100 Subject: [PATCH 5/8] Add semicolumns to code --- .prettierrc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.prettierrc b/.prettierrc index a4e66c2..c370980 100644 --- a/.prettierrc +++ b/.prettierrc @@ -4,10 +4,10 @@ { "files": ["*.js", "*.jsx", "*.ts", "*.tsx"], "options": { - "printWidth": 100, + "printWidth": 120, "tabWidth": 2, "useTabs": false, - "semi": false, + "semi": true, "singleQuote": true, "jsxSingleQuote": true, "trailingComma": "es5", @@ -19,7 +19,7 @@ { "files": ["*.css", "*.json", "*.scss", "*.html", "*.pug"], "options": { - "printWidth": 100, + "printWidth": 120, "useTabs": false, "tabWidth": 2 } From 1fd9f449d6161d71355ce50c0dcd71fdd863a962 Mon Sep 17 00:00:00 2001 From: Ahmed Meftah Date: Fri, 24 Jun 2022 20:24:50 +0100 Subject: [PATCH 6/8] Update tab width --- .prettierrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.prettierrc b/.prettierrc index c370980..ac3d4b7 100644 --- a/.prettierrc +++ b/.prettierrc @@ -5,7 +5,7 @@ "files": ["*.js", "*.jsx", "*.ts", "*.tsx"], "options": { "printWidth": 120, - "tabWidth": 2, + "tabWidth": 4, "useTabs": false, "semi": true, "singleQuote": true, From e461a3d603de897bc0ce8ac29bbe7524d57c2c11 Mon Sep 17 00:00:00 2001 From: Ahmed Meftah Date: Fri, 24 Jun 2022 20:26:18 +0100 Subject: [PATCH 7/8] Re format code --- src/controllers/Account.ts | 14 +- src/controllers/Api/Auth/Login.ts | 116 ++++++++-------- src/controllers/Api/Auth/RefreshToken.ts | 126 +++++++++--------- src/controllers/Api/Auth/Register.ts | 102 +++++++-------- src/controllers/Api/Home.ts | 14 +- src/controllers/Auth/Login.ts | 82 ++++++------ src/controllers/Auth/Logout.ts | 24 ++-- src/controllers/Auth/Register.ts | 96 +++++++------- src/controllers/Auth/Social.ts | 8 +- src/controllers/Home.ts | 14 +- src/exception/Handler.ts | 126 +++++++++--------- src/exception/NativeEvent.ts | 72 +++++----- src/index.ts | 92 ++++++------- src/interfaces/models/user.ts | 42 +++--- src/interfaces/vendors/INext.ts | 2 +- src/interfaces/vendors/IRequest.ts | 10 +- src/interfaces/vendors/IResponse.ts | 2 +- src/interfaces/vendors/index.ts | 8 +- src/middlewares/CORS.ts | 28 ++-- src/middlewares/CsrfToken.ts | 90 ++++++------- src/middlewares/Http.ts | 142 ++++++++++---------- src/middlewares/Kernel.ts | 54 ++++---- src/middlewares/Log.ts | 144 ++++++++++---------- src/middlewares/Statics.ts | 28 ++-- src/middlewares/StatusMonitor.ts | 106 +++++++-------- src/middlewares/Views.ts | 24 ++-- src/models/User.ts | 138 +++++++++---------- src/providers/App.ts | 89 ++++++------- src/providers/Cache.ts | 42 +++--- src/providers/Database.ts | 46 +++---- src/providers/Express.ts | 108 +++++++-------- src/providers/Locals.ts | 124 +++++++++--------- src/providers/Passport.ts | 90 ++++++------- src/providers/Queue.ts | 104 +++++++-------- src/providers/Routes.ts | 30 ++--- src/routes/Api.ts | 30 ++--- src/routes/Web.ts | 67 +++++----- src/services/strategies/Google.ts | 160 +++++++++++------------ src/services/strategies/Local.ts | 84 ++++++------ src/services/strategies/Twitter.ts | 140 ++++++++++---------- 40 files changed, 1397 insertions(+), 1421 deletions(-) diff --git a/src/controllers/Account.ts b/src/controllers/Account.ts index 252a238..5ace505 100644 --- a/src/controllers/Account.ts +++ b/src/controllers/Account.ts @@ -4,14 +4,14 @@ * @author Faiz A. Farooqui */ -import { IRequest, IResponse } from '../interfaces/vendors' +import { IRequest, IResponse } from '../interfaces/vendors'; class Account { - public static index(req: IRequest, res: IResponse): void { - return res.render('pages/dashboard', { - title: 'Home', - }) - } + public static index(req: IRequest, res: IResponse): void { + return res.render('pages/dashboard', { + title: 'Home', + }); + } } -export default Account +export default Account; diff --git a/src/controllers/Api/Auth/Login.ts b/src/controllers/Api/Auth/Login.ts index 69a25c6..d176208 100644 --- a/src/controllers/Api/Auth/Login.ts +++ b/src/controllers/Api/Auth/Login.ts @@ -4,76 +4,76 @@ * @author Faiz A. Farooqui */ -import * as jwt from 'jsonwebtoken' +import * as jwt from 'jsonwebtoken'; -import User from '../../../models/User' +import User from '../../../models/User'; class Login { - public static perform(req, res): any { - req.assert('email', 'E-mail cannot be blank').notEmpty() - req.assert('email', 'E-mail is not valid').isEmail() - req.assert('password', 'Password cannot be blank').notEmpty() - req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }) - req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }) + public static perform(req, res): any { + req.assert('email', 'E-mail cannot be blank').notEmpty(); + req.assert('email', 'E-mail is not valid').isEmail(); + req.assert('password', 'Password cannot be blank').notEmpty(); + req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }); + req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }); - const errors = req.validationErrors() - if (errors) { - return res.json({ - errors, - }) - } + const errors = req.validationErrors(); + if (errors) { + return res.json({ + errors, + }); + } - const _email = req.body.email.toLowerCase() - const _password = req.body.password + const _email = req.body.email.toLowerCase(); + const _password = req.body.password; - User.findOne({ email: _email }, (err, user) => { - if (err) { - return res.json({ - error: err, - }) - } + User.findOne({ email: _email }, (err, user) => { + if (err) { + return res.json({ + error: err, + }); + } - if (!user) { - return res.json({ - error: ['User not found!'], - }) - } + if (!user) { + return res.json({ + error: ['User not found!'], + }); + } - if (!user.password) { - return res.json({ - error: ['Please login using your social creds'], - }) - } + if (!user.password) { + return res.json({ + error: ['Please login using your social creds'], + }); + } - user.comparePassword(_password, (err, isMatch) => { - if (err) { - return res.json({ - error: err, - }) - } + user.comparePassword(_password, (err, isMatch) => { + if (err) { + return res.json({ + error: err, + }); + } - if (!isMatch) { - return res.json({ - error: ['Password does not match!'], - }) - } + if (!isMatch) { + return res.json({ + error: ['Password does not match!'], + }); + } - const token = jwt.sign({ email: _email, password: _password }, res.locals.app.appSecret, { - expiresIn: res.locals.app.jwtExpiresIn * 60, - }) + const token = jwt.sign({ email: _email, password: _password }, res.locals.app.appSecret, { + expiresIn: res.locals.app.jwtExpiresIn * 60, + }); - // Hide protected columns - user.tokens = undefined - user.password = undefined + // Hide protected columns + user.tokens = undefined; + user.password = undefined; - return res.json({ - user, - token, - token_expires_in: res.locals.app.jwtExpiresIn * 60, - }) - }) - }) - } + return res.json({ + user, + token, + token_expires_in: res.locals.app.jwtExpiresIn * 60, + }); + }); + }); + } } -export default Login +export default Login; diff --git a/src/controllers/Api/Auth/RefreshToken.ts b/src/controllers/Api/Auth/RefreshToken.ts index 78fdf6a..41be6de 100644 --- a/src/controllers/Api/Auth/RefreshToken.ts +++ b/src/controllers/Api/Auth/RefreshToken.ts @@ -4,83 +4,81 @@ * @author Faiz A. Farooqui */ -import * as jwt from 'jsonwebtoken' +import * as jwt from 'jsonwebtoken'; -import User from '../../../models/User' +import User from '../../../models/User'; class RefreshToken { - public static getToken(req): string { - if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { - return req.headers.authorization.split(' ')[1] - } else if (req.query && req.query.token) { - return req.query.token - } - - return '' - } + public static getToken(req): string { + if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { + return req.headers.authorization.split(' ')[1]; + } else if (req.query && req.query.token) { + return req.query.token; + } - public static perform(req, res): any { - const _token = RefreshToken.getToken(req) - if (_token === '') { - return res.json({ - error: ['Invalid Token!'], - }) + return ''; } - const decode = jwt.decode(_token, res.locals.app.appSecret, { - expiresIn: res.locals.app.jwtExpiresIn, - }) + public static perform(req, res): any { + const _token = RefreshToken.getToken(req); + if (_token === '') { + return res.json({ + error: ['Invalid Token!'], + }); + } + + const decode = jwt.decode(_token, res.locals.app.appSecret, { + expiresIn: res.locals.app.jwtExpiresIn, + }); - User.findOne({ email: decode.email }, (err, user) => { - if (err) { - return res.json({ - error: err, - }) - } + User.findOne({ email: decode.email }, (err, user) => { + if (err) { + return res.json({ + error: err, + }); + } - if (!user) { - return res.json({ - error: ['User not found!'], - }) - } + if (!user) { + return res.json({ + error: ['User not found!'], + }); + } - if (!user.password) { - return res.json({ - error: ['Please login using your social creds'], - }) - } + if (!user.password) { + return res.json({ + error: ['Please login using your social creds'], + }); + } - user.comparePassword(decode.password, (err, isMatch) => { - if (err) { - return res.json({ - error: err, - }) - } + user.comparePassword(decode.password, (err, isMatch) => { + if (err) { + return res.json({ + error: err, + }); + } - if (!isMatch) { - return res.json({ - error: ['Password does not match!'], - }) - } + if (!isMatch) { + return res.json({ + error: ['Password does not match!'], + }); + } - const token = jwt.sign( - { email: decode.email, password: decode.password }, - res.locals.app.appSecret, - { expiresIn: res.locals.app.jwtExpiresIn * 60 } - ) + const token = jwt.sign({ email: decode.email, password: decode.password }, res.locals.app.appSecret, { + expiresIn: res.locals.app.jwtExpiresIn * 60, + }); - // Hide protected columns - user.tokens = undefined - user.password = undefined + // Hide protected columns + user.tokens = undefined; + user.password = undefined; - return res.json({ - user, - token, - token_expires_in: res.locals.app.jwtExpiresIn * 60, - }) - }) - }) - } + return res.json({ + user, + token, + token_expires_in: res.locals.app.jwtExpiresIn * 60, + }); + }); + }); + } } -export default RefreshToken +export default RefreshToken; diff --git a/src/controllers/Api/Auth/Register.ts b/src/controllers/Api/Auth/Register.ts index a35991e..5f51fc3 100644 --- a/src/controllers/Api/Auth/Register.ts +++ b/src/controllers/Api/Auth/Register.ts @@ -4,61 +4,59 @@ * @author Faiz A. Farooqui */ -import User from '../../../models/User' +import User from '../../../models/User'; class Register { - public static perform(req, res): any { - req.assert('email', 'E-mail cannot be blank').notEmpty() - req.assert('email', 'E-mail is not valid').isEmail() - req.assert('password', 'Password cannot be blank').notEmpty() - req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }) - req.assert('confirmPassword', 'Confirmation Password cannot be blank').notEmpty() - req - .assert('confirmPassword', 'Password & Confirmation password does not match') - .equals(req.body.password) - req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }) - - const errors = req.validationErrors() - if (errors) { - return res.json({ - error: errors, - }) - } - - const _email = req.body.email - const _password = req.body.password - - const user = new User({ - email: _email, - password: _password, - }) - - User.findOne({ email: _email }, (err, existingUser) => { - if (err) { - return res.json({ - error: err, - }) - } - - if (existingUser) { - return res.json({ - error: ['Account with the e-mail address already exists.'], - }) - } - - user.save(err => { - if (err) { - return res.json({ - error: err, - }) + public static perform(req, res): any { + req.assert('email', 'E-mail cannot be blank').notEmpty(); + req.assert('email', 'E-mail is not valid').isEmail(); + req.assert('password', 'Password cannot be blank').notEmpty(); + req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }); + req.assert('confirmPassword', 'Confirmation Password cannot be blank').notEmpty(); + req.assert('confirmPassword', 'Password & Confirmation password does not match').equals(req.body.password); + req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }); + + const errors = req.validationErrors(); + if (errors) { + return res.json({ + error: errors, + }); } - return res.json({ - message: ['You have been successfully registered with us!'], - }) - }) - }) - } + const _email = req.body.email; + const _password = req.body.password; + + const user = new User({ + email: _email, + password: _password, + }); + + User.findOne({ email: _email }, (err, existingUser) => { + if (err) { + return res.json({ + error: err, + }); + } + + if (existingUser) { + return res.json({ + error: ['Account with the e-mail address already exists.'], + }); + } + + user.save(err => { + if (err) { + return res.json({ + error: err, + }); + } + + return res.json({ + message: ['You have been successfully registered with us!'], + }); + }); + }); + } } -export default Register +export default Register; diff --git a/src/controllers/Api/Home.ts b/src/controllers/Api/Home.ts index dba956b..ecd79df 100644 --- a/src/controllers/Api/Home.ts +++ b/src/controllers/Api/Home.ts @@ -4,14 +4,14 @@ * @author Faiz A. Farooqui */ -import Locals from '../../providers/Locals' +import Locals from '../../providers/Locals'; class Home { - public static index(req, res, next): any { - return res.json({ - message: Locals.config().name, - }) - } + public static index(req, res, next): any { + return res.json({ + message: Locals.config().name, + }); + } } -export default Home +export default Home; diff --git a/src/controllers/Auth/Login.ts b/src/controllers/Auth/Login.ts index da8cc34..adf421e 100644 --- a/src/controllers/Auth/Login.ts +++ b/src/controllers/Auth/Login.ts @@ -4,53 +4,53 @@ * @author Faiz A. Farooqui */ -import * as passport from 'passport' +import * as passport from 'passport'; -import { IRequest, IResponse, INext } from '../../interfaces/vendors' -import Log from '../../middlewares/Log' +import { IRequest, IResponse, INext } from '../../interfaces/vendors'; +import Log from '../../middlewares/Log'; class Login { - public static show(req: IRequest, res: IResponse): any { - return res.render('pages/login', { - title: 'LogIn', - }) - } - - public static perform(req: IRequest, res: IResponse, next: INext): any { - req.assert('email', 'E-mail cannot be blank').notEmpty() - req.assert('email', 'E-mail is not valid').isEmail() - req.assert('password', 'Password cannot be blank').notEmpty() - req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }) - req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }) - - const errors = req.validationErrors() - if (errors) { - req.flash('errors', errors) - return res.redirect('/login') + public static show(req: IRequest, res: IResponse): any { + return res.render('pages/login', { + title: 'LogIn', + }); } - Log.info('Here in the login controller #1!') - passport.authenticate('local', (err, user, info) => { - Log.info('Here in the login controller #2!') - if (err) { - return next(err) - } - - if (!user) { - req.flash('errors', info) - return res.redirect('/login') - } - - req.logIn(user, err => { - if (err) { - return next(err) + public static perform(req: IRequest, res: IResponse, next: INext): any { + req.assert('email', 'E-mail cannot be blank').notEmpty(); + req.assert('email', 'E-mail is not valid').isEmail(); + req.assert('password', 'Password cannot be blank').notEmpty(); + req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }); + req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }); + + const errors = req.validationErrors(); + if (errors) { + req.flash('errors', errors); + return res.redirect('/login'); } - req.flash('success', { msg: 'You are successfully logged in now!' }) - res.redirect('/account') - }) - })(req, res, next) - } + Log.info('Here in the login controller #1!'); + passport.authenticate('local', (err, user, info) => { + Log.info('Here in the login controller #2!'); + if (err) { + return next(err); + } + + if (!user) { + req.flash('errors', info); + return res.redirect('/login'); + } + + req.logIn(user, err => { + if (err) { + return next(err); + } + + req.flash('success', { msg: 'You are successfully logged in now!' }); + res.redirect('/account'); + }); + })(req, res, next); + } } -export default Login +export default Login; diff --git a/src/controllers/Auth/Logout.ts b/src/controllers/Auth/Logout.ts index 39423b7..81639e4 100644 --- a/src/controllers/Auth/Logout.ts +++ b/src/controllers/Auth/Logout.ts @@ -4,20 +4,20 @@ * @author Faiz A. Farooqui */ -import { IRequest, IResponse } from '../../interfaces/vendors' +import { IRequest, IResponse } from '../../interfaces/vendors'; class Logout { - public static perform(req: IRequest, res: IResponse): any { - req.logout() - req.session.destroy(err => { - if (err) { - console.log('Error : Failed to destroy the session during logout.', err) - } + public static perform(req: IRequest, res: IResponse): any { + req.logout(); + req.session.destroy(err => { + if (err) { + console.log('Error : Failed to destroy the session during logout.', err); + } - req.user = null - return res.redirect('/') - }) - } + req.user = null; + return res.redirect('/'); + }); + } } -export default Logout +export default Logout; diff --git a/src/controllers/Auth/Register.ts b/src/controllers/Auth/Register.ts index 125bba2..db83e5a 100644 --- a/src/controllers/Auth/Register.ts +++ b/src/controllers/Auth/Register.ts @@ -4,63 +4,61 @@ * @author Faiz A. Farooqui */ -import User from '../../models/User' -import { IRequest, IResponse, INext } from '../../interfaces/vendors' +import User from '../../models/User'; +import { IRequest, IResponse, INext } from '../../interfaces/vendors'; class Register { - public static show(req: IRequest, res: IResponse): any { - return res.render('pages/signup', { - title: 'SignUp', - }) - } + public static show(req: IRequest, res: IResponse): any { + return res.render('pages/signup', { + title: 'SignUp', + }); + } - public static perform(req: IRequest, res: IResponse, next: INext): any { - req.assert('email', 'E-mail cannot be blank').notEmpty() - req.assert('email', 'E-mail is not valid').isEmail() - req.assert('password', 'Password cannot be blank').notEmpty() - req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }) - req.assert('confirmPassword', 'Confirmation Password cannot be blank').notEmpty() - req - .assert('confirmPassword', 'Password & Confirmation password does not match') - .equals(req.body.password) - req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }) + public static perform(req: IRequest, res: IResponse, next: INext): any { + req.assert('email', 'E-mail cannot be blank').notEmpty(); + req.assert('email', 'E-mail is not valid').isEmail(); + req.assert('password', 'Password cannot be blank').notEmpty(); + req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }); + req.assert('confirmPassword', 'Confirmation Password cannot be blank').notEmpty(); + req.assert('confirmPassword', 'Password & Confirmation password does not match').equals(req.body.password); + req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }); - const errors = req.validationErrors() - if (errors) { - req.flash('errors', errors) - return res.redirect('/signup') - } + const errors = req.validationErrors(); + if (errors) { + req.flash('errors', errors); + return res.redirect('/signup'); + } - const user = new User({ - email: req.body.email, - password: req.body.password, - }) + const user = new User({ + email: req.body.email, + password: req.body.password, + }); - User.findOne({ email: req.body.email }, (err, existingUser) => { - if (err) { - return next(err) - } + User.findOne({ email: req.body.email }, (err, existingUser) => { + if (err) { + return next(err); + } - if (existingUser) { - req.flash('errors', { msg: 'Account with the e-mail address already exists.' }) - return res.redirect('/signup') - } + if (existingUser) { + req.flash('errors', { msg: 'Account with the e-mail address already exists.' }); + return res.redirect('/signup'); + } - user.save(err => { - if (err) { - return next(err) - } + user.save(err => { + if (err) { + return next(err); + } - req.logIn(user, err => { - if (err) { - return next(err) - } - req.flash('success', { msg: 'You are successfully logged in now!' }) - res.redirect('/signup') - }) - }) - }) - } + req.logIn(user, err => { + if (err) { + return next(err); + } + req.flash('success', { msg: 'You are successfully logged in now!' }); + res.redirect('/signup'); + }); + }); + }); + } } -export default Register +export default Register; diff --git a/src/controllers/Auth/Social.ts b/src/controllers/Auth/Social.ts index db53ac1..a63d798 100644 --- a/src/controllers/Auth/Social.ts +++ b/src/controllers/Auth/Social.ts @@ -5,9 +5,9 @@ */ class Social { - public static googleCallback(req, res): any { - return res.redirect('/account') - } + public static googleCallback(req, res): any { + return res.redirect('/account'); + } } -export default Social +export default Social; diff --git a/src/controllers/Home.ts b/src/controllers/Home.ts index 12e5b7c..8312210 100644 --- a/src/controllers/Home.ts +++ b/src/controllers/Home.ts @@ -4,14 +4,14 @@ * @author Faiz A. Farooqui */ -import { IRequest, IResponse } from '../interfaces/vendors' +import { IRequest, IResponse } from '../interfaces/vendors'; class Home { - public static index(req: IRequest, res: IResponse, next): void { - return res.render('pages/home', { - title: 'Home', - }) - } + public static index(req: IRequest, res: IResponse, next): void { + return res.render('pages/home', { + title: 'Home', + }); + } } -export default Home +export default Home; diff --git a/src/exception/Handler.ts b/src/exception/Handler.ts index 1f7e3c3..229c607 100644 --- a/src/exception/Handler.ts +++ b/src/exception/Handler.ts @@ -4,82 +4,82 @@ * @author Faiz A. Farooqui */ -import Log from '../middlewares/Log' -import Locals from '../providers/Locals' +import Log from '../middlewares/Log'; +import Locals from '../providers/Locals'; class Handler { - /** - * Handles all the not found routes - */ - public static notFoundHandler(_express): any { - const apiPrefix = Locals.config().apiPrefix + /** + * Handles all the not found routes + */ + public static notFoundHandler(_express): any { + const apiPrefix = Locals.config().apiPrefix; - _express.use('*', (req, res) => { - const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress + _express.use('*', (req, res) => { + const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; - Log.error(`Path '${req.originalUrl}' not found [IP: '${ip}']!`) - if (req.xhr || req.originalUrl.includes(`/${apiPrefix}/`)) { - return res.json({ - error: 'Page Not Found', - }) - } else { - res.status(404) - return res.render('pages/error', { - title: 'Page Not Found', - error: [], - }) - } - }) + Log.error(`Path '${req.originalUrl}' not found [IP: '${ip}']!`); + if (req.xhr || req.originalUrl.includes(`/${apiPrefix}/`)) { + return res.json({ + error: 'Page Not Found', + }); + } else { + res.status(404); + return res.render('pages/error', { + title: 'Page Not Found', + error: [], + }); + } + }); - return _express - } + return _express; + } - /** - * Handles your api/web routes errors/exception - */ - public static clientErrorHandler(err, req, res, next): any { - Log.error(err.stack) + /** + * Handles your api/web routes errors/exception + */ + public static clientErrorHandler(err, req, res, next): any { + Log.error(err.stack); - if (req.xhr) { - return res.status(500).send({ error: 'Something went wrong!' }) - } else { - return next(err) + if (req.xhr) { + return res.status(500).send({ error: 'Something went wrong!' }); + } else { + return next(err); + } } - } - /** - * Show undermaintenance page incase of errors - */ - public static errorHandler(err, req, res, next): any { - Log.error(err.stack) - res.status(500) + /** + * Show undermaintenance page incase of errors + */ + public static errorHandler(err, req, res, next): any { + Log.error(err.stack); + res.status(500); - const apiPrefix = Locals.config().apiPrefix - if (req.originalUrl.includes(`/${apiPrefix}/`)) { - if (err.name && err.name === 'UnauthorizedError') { - const innerMessage = err.inner && err.inner.message ? err.inner.message : undefined - return res.json({ - error: ['Invalid Token!', innerMessage], - }) - } + const apiPrefix = Locals.config().apiPrefix; + if (req.originalUrl.includes(`/${apiPrefix}/`)) { + if (err.name && err.name === 'UnauthorizedError') { + const innerMessage = err.inner && err.inner.message ? err.inner.message : undefined; + return res.json({ + error: ['Invalid Token!', innerMessage], + }); + } - return res.json({ - error: err, - }) - } + return res.json({ + error: err, + }); + } - return res.render('pages/error', { error: err.stack, title: 'Under Maintenance' }) - } + return res.render('pages/error', { error: err.stack, title: 'Under Maintenance' }); + } - /** - * Register your error / exception monitoring - * tools right here ie. before "next(err)"! - */ - public static logErrors(err, req, res, next): any { - Log.error(err.stack) + /** + * Register your error / exception monitoring + * tools right here ie. before "next(err)"! + */ + public static logErrors(err, req, res, next): any { + Log.error(err.stack); - return next(err) - } + return next(err); + } } -export default Handler +export default Handler; diff --git a/src/exception/NativeEvent.ts b/src/exception/NativeEvent.ts index d5ab293..08cfcf7 100644 --- a/src/exception/NativeEvent.ts +++ b/src/exception/NativeEvent.ts @@ -4,44 +4,42 @@ * @author Faiz A. Farooqui */ -import Log from '../middlewares/Log' +import Log from '../middlewares/Log'; class NativeEvent { - public cluster(_cluster): void { - // Catch cluster listening event... - _cluster.on('listening', worker => - Log.info(`Server :: Cluster with ProcessID '${worker.process.pid}' Connected!`) - ) - - // Catch cluster once it is back online event... - _cluster.on('online', worker => - Log.info( - `Server :: Cluster with ProcessID '${worker.process.pid}' has responded after it was forked! ` - ) - ) - - // Catch cluster disconnect event... - _cluster.on('disconnect', worker => - Log.info(`Server :: Cluster with ProcessID '${worker.process.pid}' Disconnected!`) - ) - - // Catch cluster exit event... - _cluster.on('exit', (worker, code, signal) => { - Log.info( - `Server :: Cluster with ProcessID '${worker.process.pid}' is Dead with Code '${code}, and signal: '${signal}'` - ) - // Ensuring a new cluster will start if an old one dies - _cluster.fork() - }) - } - - public process(): void { - // Catch the Process's uncaught-exception - process.on('uncaughtException', exception => Log.error(exception.stack)) - - // Catch the Process's warning event - process.on('warning', warning => Log.warn(warning.stack)) - } + public cluster(_cluster): void { + // Catch cluster listening event... + _cluster.on('listening', worker => + Log.info(`Server :: Cluster with ProcessID '${worker.process.pid}' Connected!`) + ); + + // Catch cluster once it is back online event... + _cluster.on('online', worker => + Log.info(`Server :: Cluster with ProcessID '${worker.process.pid}' has responded after it was forked! `) + ); + + // Catch cluster disconnect event... + _cluster.on('disconnect', worker => + Log.info(`Server :: Cluster with ProcessID '${worker.process.pid}' Disconnected!`) + ); + + // Catch cluster exit event... + _cluster.on('exit', (worker, code, signal) => { + Log.info( + `Server :: Cluster with ProcessID '${worker.process.pid}' is Dead with Code '${code}, and signal: '${signal}'` + ); + // Ensuring a new cluster will start if an old one dies + _cluster.fork(); + }); + } + + public process(): void { + // Catch the Process's uncaught-exception + process.on('uncaughtException', exception => Log.error(exception.stack)); + + // Catch the Process's warning event + process.on('warning', warning => Log.warn(warning.stack)); + } } -export default new NativeEvent() +export default new NativeEvent(); diff --git a/src/index.ts b/src/index.ts index a4e8002..12df513 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,62 +4,62 @@ * @author Faiz A. Farooqui */ -import * as os from 'os' -import * as cluster from 'cluster' +import * as os from 'os'; +import * as cluster from 'cluster'; -import App from './providers/App' -import NativeEvent from './exception/NativeEvent' +import App from './providers/App'; +import NativeEvent from './exception/NativeEvent'; if (cluster.isMaster) { - /** - * Catches the process events - */ - NativeEvent.process() + /** + * Catches the process events + */ + NativeEvent.process(); - /** - * Clear the console before the app runs - */ - App.clearConsole() + /** + * Clear the console before the app runs + */ + App.clearConsole(); - /** - * Load Configuration - */ - App.loadConfiguration() + /** + * Load Configuration + */ + App.loadConfiguration(); - /** - * Find the number of available CPUS - */ - const CPUS: any = os.cpus() + /** + * Find the number of available CPUS + */ + const CPUS: any = os.cpus(); - /** - * Fork the process, the number of times we have CPUs available - */ - CPUS.forEach(() => cluster.fork()) + /** + * Fork the process, the number of times we have CPUs available + */ + CPUS.forEach(() => cluster.fork()); - /** - * Catches the cluster events - */ - NativeEvent.cluster(cluster) + /** + * Catches the cluster events + */ + NativeEvent.cluster(cluster); - /** - * Loads the Queue Monitor iff enabled - */ - App.loadQueue() + /** + * Loads the Queue Monitor iff enabled + */ + App.loadQueue(); - /** - * Run the Worker every minute - * Note: we normally start worker after - * the entire app is loaded - */ - setTimeout(() => App.loadWorker(), 1000 * 60) + /** + * Run the Worker every minute + * Note: we normally start worker after + * the entire app is loaded + */ + setTimeout(() => App.loadWorker(), 1000 * 60); } else { - /** - * Run the Database pool - */ - App.loadDatabase() + /** + * Run the Database pool + */ + App.loadDatabase(); - /** - * Run the Server on Clusters - */ - App.loadServer() + /** + * Run the Server on Clusters + */ + App.loadServer(); } diff --git a/src/interfaces/models/user.ts b/src/interfaces/models/user.ts index 98504eb..a03aaa7 100644 --- a/src/interfaces/models/user.ts +++ b/src/interfaces/models/user.ts @@ -5,31 +5,31 @@ */ export interface Tokens { - kind: string - accessToken: string - tokenSecret?: string + kind: string; + accessToken: string; + tokenSecret?: string; } export interface IUser { - email: string - password: string - passwordResetToken: string - passwordResetExpires: Date + email: string; + password: string; + passwordResetToken: string; + passwordResetExpires: Date; - facebook: string - twitter: string - google: string - github: string - instagram: string - linkedin: string - tokens: Tokens[] - steam: string + facebook: string; + twitter: string; + google: string; + github: string; + instagram: string; + linkedin: string; + tokens: Tokens[]; + steam: string; - fullname: string - gender: string - geolocation: string - website: string - picture: string + fullname: string; + gender: string; + geolocation: string; + website: string; + picture: string; } -export default IUser +export default IUser; diff --git a/src/interfaces/vendors/INext.ts b/src/interfaces/vendors/INext.ts index 8f44d55..9140092 100644 --- a/src/interfaces/vendors/INext.ts +++ b/src/interfaces/vendors/INext.ts @@ -4,6 +4,6 @@ * @author Faiz A. Farooqui */ -import { NextFunction } from 'express' +import { NextFunction } from 'express'; export interface INext extends NextFunction {} diff --git a/src/interfaces/vendors/IRequest.ts b/src/interfaces/vendors/IRequest.ts index 0348852..e4cea3d 100644 --- a/src/interfaces/vendors/IRequest.ts +++ b/src/interfaces/vendors/IRequest.ts @@ -4,12 +4,12 @@ * @author Faiz A. Farooqui */ -import { Request } from 'express' +import { Request } from 'express'; export interface IRequest extends Request { - flash(message: string, callback: any): any + flash(message: string, callback: any): any; - logIn(user: any, callback: any): any - user(): any - logout(): void + logIn(user: any, callback: any): any; + user(): any; + logout(): void; } diff --git a/src/interfaces/vendors/IResponse.ts b/src/interfaces/vendors/IResponse.ts index 5d8499c..485b2a1 100644 --- a/src/interfaces/vendors/IResponse.ts +++ b/src/interfaces/vendors/IResponse.ts @@ -4,6 +4,6 @@ * @author Faiz A. Farooqui */ -import { Response } from 'express' +import { Response } from 'express'; export interface IResponse extends Response {} diff --git a/src/interfaces/vendors/index.ts b/src/interfaces/vendors/index.ts index da96853..8aae50d 100644 --- a/src/interfaces/vendors/index.ts +++ b/src/interfaces/vendors/index.ts @@ -4,8 +4,8 @@ * @author Faiz A. Farooqui */ -import { IRequest } from './IRequest' -import { IResponse } from './IResponse' -import { INext } from './INext' +import { IRequest } from './IRequest'; +import { IResponse } from './IResponse'; +import { INext } from './INext'; -export { IRequest, IResponse, INext } +export { IRequest, IResponse, INext }; diff --git a/src/middlewares/CORS.ts b/src/middlewares/CORS.ts index d7c9679..1d7d270 100644 --- a/src/middlewares/CORS.ts +++ b/src/middlewares/CORS.ts @@ -4,25 +4,25 @@ * @author Faiz A. Farooqui */ -import * as cors from 'cors' -import { Application } from 'express' +import * as cors from 'cors'; +import { Application } from 'express'; -import Log from './Log' -import Locals from '../providers/Locals' +import Log from './Log'; +import Locals from '../providers/Locals'; class CORS { - public mount(_express: Application): Application { - Log.info("Booting the 'CORS' middleware...") + public mount(_express: Application): Application { + Log.info("Booting the 'CORS' middleware..."); - const options = { - origin: Locals.config().url, - optionsSuccessStatus: 200, // Some legacy browsers choke on 204 - } + const options = { + origin: Locals.config().url, + optionsSuccessStatus: 200, // Some legacy browsers choke on 204 + }; - _express.use(cors(options)) + _express.use(cors(options)); - return _express - } + return _express; + } } -export default new CORS() +export default new CORS(); diff --git a/src/middlewares/CsrfToken.ts b/src/middlewares/CsrfToken.ts index 5ee8624..32cf700 100644 --- a/src/middlewares/CsrfToken.ts +++ b/src/middlewares/CsrfToken.ts @@ -5,61 +5,61 @@ * @author Faiz A. Farooqui */ -import { Application } from 'express' -import * as lusca from 'lusca' +import { Application } from 'express'; +import * as lusca from 'lusca'; -import Log from './Log' -import Locals from '../providers/Locals' +import Log from './Log'; +import Locals from '../providers/Locals'; class CsrfToken { - public static mount(_express: any): Application { - Log.info("Booting the 'CsrfToken' middleware...") + public static mount(_express: any): Application { + Log.info("Booting the 'CsrfToken' middleware..."); - _express.set('trust proxy', 1) + _express.set('trust proxy', 1); - // Interpolate the user variable into your pug files - _express.use((req, res, next) => { - res.locals.user = req.user - res.locals.app = Locals.config() - next() - }) + // Interpolate the user variable into your pug files + _express.use((req, res, next) => { + res.locals.user = req.user; + res.locals.app = Locals.config(); + next(); + }); - // Check for CSRF token iff the original url - // does not contains the api substring - _express.use((req, res, next) => { - const apiPrefix = Locals.config().apiPrefix + // Check for CSRF token iff the original url + // does not contains the api substring + _express.use((req, res, next) => { + const apiPrefix = Locals.config().apiPrefix; - if (req.originalUrl.includes(`/${apiPrefix}/`)) { - next() - } else { - lusca.csrf()(req, res, next) - } - }) + if (req.originalUrl.includes(`/${apiPrefix}/`)) { + next(); + } else { + lusca.csrf()(req, res, next); + } + }); - // Enables x-frame-options headers - _express.use(lusca.xframe('SAMEORIGIN')) + // Enables x-frame-options headers + _express.use(lusca.xframe('SAMEORIGIN')); - // Enables xss-protection headers - _express.use(lusca.xssProtection(true)) + // Enables xss-protection headers + _express.use(lusca.xssProtection(true)); - _express.use((req, res, next) => { - // After successful login, redirect back to the intended page - if ( - !req.user && - req.path !== '/login' && - req.path !== '/signup' && - !req.path.match(/^\/auth/) && - !req.path.match(/\./) - ) { - req.session.returnTo = req.originalUrl - } else if (req.user && (req.path === '/account' || req.path.match(/^\/api/))) { - req.session.returnTo = req.originalUrl - } - next() - }) + _express.use((req, res, next) => { + // After successful login, redirect back to the intended page + if ( + !req.user && + req.path !== '/login' && + req.path !== '/signup' && + !req.path.match(/^\/auth/) && + !req.path.match(/\./) + ) { + req.session.returnTo = req.originalUrl; + } else if (req.user && (req.path === '/account' || req.path.match(/^\/api/))) { + req.session.returnTo = req.originalUrl; + } + next(); + }); - return _express - } + return _express; + } } -export default CsrfToken +export default CsrfToken; diff --git a/src/middlewares/Http.ts b/src/middlewares/Http.ts index 74b8efb..8491031 100644 --- a/src/middlewares/Http.ts +++ b/src/middlewares/Http.ts @@ -4,81 +4,81 @@ * @author Faiz A. Farooqui */ -import * as cors from 'cors' -import { Application } from 'express' -import * as flash from 'express-flash' -import * as compress from 'compression' -import * as connect from 'connect-mongo' -import * as bodyParser from 'body-parser' -import * as session from 'express-session' -import * as expressValidator from 'express-validator' +import * as cors from 'cors'; +import { Application } from 'express'; +import * as flash from 'express-flash'; +import * as compress from 'compression'; +import * as connect from 'connect-mongo'; +import * as bodyParser from 'body-parser'; +import * as session from 'express-session'; +import * as expressValidator from 'express-validator'; -import Log from './Log' -import Locals from '../providers/Locals' -import Passport from '../providers/Passport' +import Log from './Log'; +import Locals from '../providers/Locals'; +import Passport from '../providers/Passport'; -const MongoStore = connect(session) +const MongoStore = connect(session); class Http { - public static mount(_express: Application): Application { - Log.info("Booting the 'HTTP' middleware...") - - // Enables the request body parser - _express.use( - bodyParser.json({ - limit: Locals.config().maxUploadLimit, - }) - ) - - _express.use( - bodyParser.urlencoded({ - limit: Locals.config().maxUploadLimit, - parameterLimit: Locals.config().maxParameterLimit, - extended: false, - }) - ) - - // Disable the x-powered-by header in response - _express.disable('x-powered-by') - - // Enables the request payload validator - _express.use(expressValidator()) - - // Enables the request flash messages - _express.use(flash()) - - /** - * Enables the session store - * - * Note: You can also add redis-store - * into the options object. - */ - const options = { - resave: true, - saveUninitialized: true, - secret: Locals.config().appSecret, - cookie: { - maxAge: 1209600000, // two weeks (in ms) - }, - store: new MongoStore({ - url: process.env.MONGOOSE_URL, - autoReconnect: true, - }), + public static mount(_express: Application): Application { + Log.info("Booting the 'HTTP' middleware..."); + + // Enables the request body parser + _express.use( + bodyParser.json({ + limit: Locals.config().maxUploadLimit, + }) + ); + + _express.use( + bodyParser.urlencoded({ + limit: Locals.config().maxUploadLimit, + parameterLimit: Locals.config().maxParameterLimit, + extended: false, + }) + ); + + // Disable the x-powered-by header in response + _express.disable('x-powered-by'); + + // Enables the request payload validator + _express.use(expressValidator()); + + // Enables the request flash messages + _express.use(flash()); + + /** + * Enables the session store + * + * Note: You can also add redis-store + * into the options object. + */ + const options = { + resave: true, + saveUninitialized: true, + secret: Locals.config().appSecret, + cookie: { + maxAge: 1209600000, // two weeks (in ms) + }, + store: new MongoStore({ + url: process.env.MONGOOSE_URL, + autoReconnect: true, + }), + }; + + _express.use(session(options)); + + // Enables the CORS + _express.use(cors()); + + // Enables the "gzip" / "deflate" compression for response + _express.use(compress()); + + // Loads the passport configuration + _express = Passport.mountPackage(_express); + + return _express; } - - _express.use(session(options)) - - // Enables the CORS - _express.use(cors()) - - // Enables the "gzip" / "deflate" compression for response - _express.use(compress()) - - // Loads the passport configuration - _express = Passport.mountPackage(_express) - - return _express - } } -export default Http +export default Http; diff --git a/src/middlewares/Kernel.ts b/src/middlewares/Kernel.ts index 1c6d47c..9169205 100644 --- a/src/middlewares/Kernel.ts +++ b/src/middlewares/Kernel.ts @@ -4,42 +4,42 @@ * @author Faiz A. Farooqui */ -import { Application } from 'express' +import { Application } from 'express'; -import CORS from './CORS' -import Http from './Http' -import Views from './Views' -import Statics from './Statics' -import CsrfToken from './CsrfToken' -import StatusMonitor from './StatusMonitor' +import CORS from './CORS'; +import Http from './Http'; +import Views from './Views'; +import Statics from './Statics'; +import CsrfToken from './CsrfToken'; +import StatusMonitor from './StatusMonitor'; -import Locals from '../providers/Locals' +import Locals from '../providers/Locals'; class Kernel { - public static init(_express: Application): Application { - // Check if CORS is enabled - if (Locals.config().isCORSEnabled) { - // Mount CORS middleware - _express = CORS.mount(_express) - } + public static init(_express: Application): Application { + // Check if CORS is enabled + if (Locals.config().isCORSEnabled) { + // Mount CORS middleware + _express = CORS.mount(_express); + } - // Mount basic express apis middleware - _express = Http.mount(_express) + // Mount basic express apis middleware + _express = Http.mount(_express); - // Mount csrf token verification middleware - _express = CsrfToken.mount(_express) + // Mount csrf token verification middleware + _express = CsrfToken.mount(_express); - // Mount view engine middleware - _express = Views.mount(_express) + // Mount view engine middleware + _express = Views.mount(_express); - // Mount statics middleware - _express = Statics.mount(_express) + // Mount statics middleware + _express = Statics.mount(_express); - // Mount status monitor middleware - _express = StatusMonitor.mount(_express) + // Mount status monitor middleware + _express = StatusMonitor.mount(_express); - return _express - } + return _express; + } } -export default Kernel +export default Kernel; diff --git a/src/middlewares/Log.ts b/src/middlewares/Log.ts index 20b5068..526be6a 100644 --- a/src/middlewares/Log.ts +++ b/src/middlewares/Log.ts @@ -2,92 +2,90 @@ * Creates & maintains the log */ -import * as fs from 'fs' -import * as path from 'path' +import * as fs from 'fs'; +import * as path from 'path'; class Log { - public baseDir: string - public fileName: string - public linePrefix: string + public baseDir: string; + public fileName: string; + public linePrefix: string; - public today: Date = new Date() + public today: Date = new Date(); - constructor() { - let _dateString = `${this.today.getFullYear()}-${ - this.today.getMonth() + 1 - }-${this.today.getDate()}` - let _timeString = `${this.today.getHours()}:${this.today.getMinutes()}:${this.today.getSeconds()}` + constructor() { + let _dateString = `${this.today.getFullYear()}-${this.today.getMonth() + 1}-${this.today.getDate()}`; + let _timeString = `${this.today.getHours()}:${this.today.getMinutes()}:${this.today.getSeconds()}`; - this.baseDir = path.join(__dirname, '../../.logs/') + this.baseDir = path.join(__dirname, '../../.logs/'); - this.fileName = `${_dateString}.log` - this.linePrefix = `[${_dateString} ${_timeString}]` - } + this.fileName = `${_dateString}.log`; + this.linePrefix = `[${_dateString} ${_timeString}]`; + } - // Adds INFO prefix string to the log string - public info(_string: string): void { - this.addLog('INFO', _string) - } + // Adds INFO prefix string to the log string + public info(_string: string): void { + this.addLog('INFO', _string); + } - // Adds WARN prefix string to the log string - public warn(_string: string): void { - this.addLog('WARN', _string) - } + // Adds WARN prefix string to the log string + public warn(_string: string): void { + this.addLog('WARN', _string); + } - // Adds ERROR prefix string to the log string - public error(_string: string): void { - // Line break and show the first line - console.log('\x1b[31m%s\x1b[0m', '[ERROR] :: ' + _string.split(/r?\n/)[0]) + // Adds ERROR prefix string to the log string + public error(_string: string): void { + // Line break and show the first line + console.log('\x1b[31m%s\x1b[0m', '[ERROR] :: ' + _string.split(/r?\n/)[0]); - this.addLog('ERROR', _string) - } + this.addLog('ERROR', _string); + } - // Adds the custom prefix string to the log string - public custom(_filename: string, _string: string): void { - this.addLog(_filename, _string) - } + // Adds the custom prefix string to the log string + public custom(_filename: string, _string: string): void { + this.addLog(_filename, _string); + } - /** - * Creates the file if does not exist, and - * append the log kind & string into the file. - */ - private addLog(_kind: string, _string: string): void { - const _that = this - _kind = _kind.toUpperCase() + /** + * Creates the file if does not exist, and + * append the log kind & string into the file. + */ + private addLog(_kind: string, _string: string): void { + const _that = this; + _kind = _kind.toUpperCase(); - fs.open(`${_that.baseDir}${_that.fileName}`, 'a', (_err, _fileDescriptor) => { - if (!_err && _fileDescriptor) { - // Append to file and close it - fs.appendFile(_fileDescriptor, `${_that.linePrefix} [${_kind}] ${_string}\n`, _err => { - if (!_err) { - fs.close(_fileDescriptor, _err => { - if (!_err) { - return true - } else { - return console.log( - '\x1b[31m%s\x1b[0m', - 'Error closing log file that was being appended' - ) - } - }) - } else { - return console.log('\x1b[31m%s\x1b[0m', 'Error appending to the log file') - } - }) - } else { - return console.log('\x1b[31m%s\x1b[0m', "Error cloudn't open the log file for appending") - } - }) - } + fs.open(`${_that.baseDir}${_that.fileName}`, 'a', (_err, _fileDescriptor) => { + if (!_err && _fileDescriptor) { + // Append to file and close it + fs.appendFile(_fileDescriptor, `${_that.linePrefix} [${_kind}] ${_string}\n`, _err => { + if (!_err) { + fs.close(_fileDescriptor, _err => { + if (!_err) { + return true; + } else { + return console.log( + '\x1b[31m%s\x1b[0m', + 'Error closing log file that was being appended' + ); + } + }); + } else { + return console.log('\x1b[31m%s\x1b[0m', 'Error appending to the log file'); + } + }); + } else { + return console.log('\x1b[31m%s\x1b[0m', "Error cloudn't open the log file for appending"); + } + }); + } - /** - * Deletes the log files older than 'X' days - * - * Note: 'X' is defined in .env file - */ - public clean(): void { - // - } + /** + * Deletes the log files older than 'X' days + * + * Note: 'X' is defined in .env file + */ + public clean(): void { + // + } } -export default new Log() +export default new Log(); diff --git a/src/middlewares/Statics.ts b/src/middlewares/Statics.ts index cfa4b0f..e9cbd0e 100644 --- a/src/middlewares/Statics.ts +++ b/src/middlewares/Statics.ts @@ -4,26 +4,26 @@ * @author Faiz A. Farooqui */ -import * as path from 'path' -import * as express from 'express' +import * as path from 'path'; +import * as express from 'express'; -import Log from './Log' +import Log from './Log'; class Statics { - public static mount(_express: express.Application): express.Application { - Log.info("Booting the 'Statics' middleware...") + public static mount(_express: express.Application): express.Application { + Log.info("Booting the 'Statics' middleware..."); - // Loads Options - const options = { maxAge: 31557600000 } + // Loads Options + const options = { maxAge: 31557600000 }; - // Load Statics - _express.use('/public', express.static(path.join(__dirname, '../../public'), options)) + // Load Statics + _express.use('/public', express.static(path.join(__dirname, '../../public'), options)); - // Load NPM Statics - _express.use('/vendor', express.static(path.join(__dirname, '../../node_modules'), options)) + // Load NPM Statics + _express.use('/vendor', express.static(path.join(__dirname, '../../node_modules'), options)); - return _express - } + return _express; + } } -export default Statics +export default Statics; diff --git a/src/middlewares/StatusMonitor.ts b/src/middlewares/StatusMonitor.ts index 7427538..1bba352 100644 --- a/src/middlewares/StatusMonitor.ts +++ b/src/middlewares/StatusMonitor.ts @@ -4,65 +4,65 @@ * @author Faiz A. Farooqui */ -import { Application } from 'express' -import * as expressStatusMonitor from 'express-status-monitor' +import { Application } from 'express'; +import * as expressStatusMonitor from 'express-status-monitor'; -import Log from './Log' -import Locals from '../providers/Locals' +import Log from './Log'; +import Locals from '../providers/Locals'; class StatusMonitor { - public mount(_express: Application): Application { - Log.info("Booting the 'StatusMonitor' middleware...") + public mount(_express: Application): Application { + Log.info("Booting the 'StatusMonitor' middleware..."); - const api: string = Locals.config().apiPrefix + const api: string = Locals.config().apiPrefix; - // Define your status monitor config - const monitorOptions: object = { - title: Locals.config().name, - path: '/status-monitor', - spans: [ - { - interval: 1, // Every second - retention: 60, // Keep 60 data-points in memory - }, - { - interval: 5, - retention: 60, - }, - { - interval: 15, - retention: 60, - }, - ], - chartVisibility: { - mem: true, - rps: true, - cpu: true, - load: true, - statusCodes: true, - responseTime: true, - }, - healthChecks: [ - { - protocol: 'http', - host: 'localhost', - path: '/', - port: '4040', - }, - { - protocol: 'http', - host: 'localhost', - path: `/${api}`, - port: '4040', - }, - ], - } + // Define your status monitor config + const monitorOptions: object = { + title: Locals.config().name, + path: '/status-monitor', + spans: [ + { + interval: 1, // Every second + retention: 60, // Keep 60 data-points in memory + }, + { + interval: 5, + retention: 60, + }, + { + interval: 15, + retention: 60, + }, + ], + chartVisibility: { + mem: true, + rps: true, + cpu: true, + load: true, + statusCodes: true, + responseTime: true, + }, + healthChecks: [ + { + protocol: 'http', + host: 'localhost', + path: '/', + port: '4040', + }, + { + protocol: 'http', + host: 'localhost', + path: `/${api}`, + port: '4040', + }, + ], + }; - // Loads the express status monitor middleware - _express.use(expressStatusMonitor(monitorOptions)) + // Loads the express status monitor middleware + _express.use(expressStatusMonitor(monitorOptions)); - return _express - } + return _express; + } } -export default new StatusMonitor() +export default new StatusMonitor(); diff --git a/src/middlewares/Views.ts b/src/middlewares/Views.ts index 706734c..b81f536 100644 --- a/src/middlewares/Views.ts +++ b/src/middlewares/Views.ts @@ -4,22 +4,22 @@ * @author Faiz A. Farooqui */ -import * as path from 'path' -import { Application } from 'express' +import * as path from 'path'; +import { Application } from 'express'; -import Log from './Log' +import Log from './Log'; class Views { - public static mount(_express: Application): Application { - Log.info("Booting the 'Views' middleware...") + public static mount(_express: Application): Application { + Log.info("Booting the 'Views' middleware..."); - _express.set('view engine', 'pug') - _express.set('view options', { pretty: true }) - _express.set('views', path.join(__dirname, '../../views')) - _express.locals.pretty = true + _express.set('view engine', 'pug'); + _express.set('view options', { pretty: true }); + _express.set('views', path.join(__dirname, '../../views')); + _express.locals.pretty = true; - return _express - } + return _express; + } } -export default Views +export default Views; diff --git a/src/models/User.ts b/src/models/User.ts index b8bb031..551fdd9 100644 --- a/src/models/User.ts +++ b/src/models/User.ts @@ -4,100 +4,100 @@ * @author Faiz A. Farooqui */ -import * as crypto from 'crypto' -import * as bcrypt from 'bcrypt-nodejs' +import * as crypto from 'crypto'; +import * as bcrypt from 'bcrypt-nodejs'; -import { IUser } from '../interfaces/models/user' -import mongoose from '../providers/Database' +import { IUser } from '../interfaces/models/user'; +import mongoose from '../providers/Database'; // Create the model schema & register your custom methods here export interface IUserModel extends IUser, mongoose.Document { - billingAddress(): string - comparePassword(password: string, cb: any): string - validPassword(password: string, cb: any): string - gravatar(_size: number): string + billingAddress(): string; + comparePassword(password: string, cb: any): string; + validPassword(password: string, cb: any): string; + gravatar(_size: number): string; } // Define the User Schema export const UserSchema = new mongoose.Schema( - { - email: { type: String, unique: true }, - password: { type: String }, - passwordResetToken: { type: String }, - passwordResetExpires: Date, - - facebook: { type: String }, - twitter: { type: String }, - google: { type: String }, - github: { type: String }, - instagram: { type: String }, - linkedin: { type: String }, - steam: { type: String }, - tokens: Array, - - fullname: { type: String }, - gender: { type: String }, - geolocation: { type: String }, - website: { type: String }, - picture: { type: String }, - }, - { - timestamps: true, - } -) + { + email: { type: String, unique: true }, + password: { type: String }, + passwordResetToken: { type: String }, + passwordResetExpires: Date, + + facebook: { type: String }, + twitter: { type: String }, + google: { type: String }, + github: { type: String }, + instagram: { type: String }, + linkedin: { type: String }, + steam: { type: String }, + tokens: Array, + + fullname: { type: String }, + gender: { type: String }, + geolocation: { type: String }, + website: { type: String }, + picture: { type: String }, + }, + { + timestamps: true, + } +); // Password hash middleware UserSchema.pre('save', function (_next) { - const user = this - if (!user.isModified('password')) { - return _next() - } - - bcrypt.genSalt(10, (_err, _salt) => { - if (_err) { - return _next(_err) + const user = this; + if (!user.isModified('password')) { + return _next(); } - bcrypt.hash(user.password, _salt, null, (_err, _hash) => { - if (_err) { - return _next(_err) - } + bcrypt.genSalt(10, (_err, _salt) => { + if (_err) { + return _next(_err); + } + + bcrypt.hash(user.password, _salt, null, (_err, _hash) => { + if (_err) { + return _next(_err); + } - user.password = _hash - return _next() - }) - }) -}) + user.password = _hash; + return _next(); + }); + }); +}); // Custom Methods // Get user's full billing address UserSchema.methods.billingAddress = function (): string { - const fulladdress = `${this.fullname.trim()} ${this.geolocation.trim()}` - return fulladdress -} + const fulladdress = `${this.fullname.trim()} ${this.geolocation.trim()}`; + return fulladdress; +}; // Compares the user's password with the request password UserSchema.methods.comparePassword = function (_requestPassword, _cb): any { - bcrypt.compare(_requestPassword, this.password, (_err, _isMatch) => { - return _cb(_err, _isMatch) - }) -} + bcrypt.compare(_requestPassword, this.password, (_err, _isMatch) => { + return _cb(_err, _isMatch); + }); +}; // User's gravatar UserSchema.methods.gravatar = function (_size): any { - if (!_size) { - _size = 200 - } + if (!_size) { + _size = 200; + } - const url = 'https://gravatar.com/avatar' - if (!this.email) { - return `${url}/?s=${_size}&d=retro` - } + const url = 'https://gravatar.com/avatar'; + if (!this.email) { + return `${url}/?s=${_size}&d=retro`; + } - const md5 = crypto.createHash('md5').update(this.email).digest('hex') - return `${url}/${md5}?s=${_size}&d=retro` -} + const md5 = crypto.createHash('md5').update(this.email).digest('hex'); + return `${url}/${md5}?s=${_size}&d=retro`; +}; -const User = mongoose.model('User', UserSchema) +const User = mongoose.model('User', UserSchema); -export default User +export default User; diff --git a/src/providers/App.ts b/src/providers/App.ts index cc9ca98..0a5638b 100644 --- a/src/providers/App.ts +++ b/src/providers/App.ts @@ -4,67 +4,64 @@ * @author Faiz A. Farooqui */ -import * as kue from 'kue' -import * as path from 'path' -import * as dotenv from 'dotenv' +import * as kue from 'kue'; +import * as path from 'path'; +import * as dotenv from 'dotenv'; -import Express from './Express' -import { Database } from './Database' +import Express from './Express'; +import { Database } from './Database'; -import Queue from './Queue' -import Locals from './Locals' -import Log from '../middlewares/Log' +import Queue from './Queue'; +import Locals from './Locals'; +import Log from '../middlewares/Log'; class App { - // Clear the console - public clearConsole(): void { - process.stdout.write('\x1B[2J\x1B[0f') + // Clear the console + public clearConsole(): void { + process.stdout.write('\x1B[2J\x1B[0f'); - Queue.dispatch('checkout', { foo: 'bar', fizz: 'buzz' }, function (data) { - console.log('>> here is the data', data) - }) - } + Queue.dispatch('checkout', { foo: 'bar', fizz: 'buzz' }, function (data) { + console.log('>> here is the data', data); + }); + } - // Loads your dotenv file - public loadConfiguration(): void { - Log.info('Configuration :: Booting @ Master...') + // Loads your dotenv file + public loadConfiguration(): void { + Log.info('Configuration :: Booting @ Master...'); - dotenv.config({ path: path.join(__dirname, '../../.env') }) - } + dotenv.config({ path: path.join(__dirname, '../../.env') }); + } - // Loads your Server - public loadServer(): void { - Log.info('Server :: Booting @ Master...') + // Loads your Server + public loadServer(): void { + Log.info('Server :: Booting @ Master...'); - Express.init() - } + Express.init(); + } - // Loads the Database Pool - public loadDatabase(): void { - Log.info('Database :: Booting @ Master...') + // Loads the Database Pool + public loadDatabase(): void { + Log.info('Database :: Booting @ Master...'); - Database.init() - } + Database.init(); + } - // Loads the Worker Cluster - public loadWorker(): void { - Log.info('Worker :: Booting @ Master...') - } + // Loads the Worker Cluster + public loadWorker(): void { + Log.info('Worker :: Booting @ Master...'); + } - // Loads the Queue Monitor - public loadQueue(): void { - const isQueueMonitorEnabled: boolean = Locals.config().queueMonitor - const queueMonitorPort: number = Locals.config().queueMonitorHttpPort + // Loads the Queue Monitor + public loadQueue(): void { + const isQueueMonitorEnabled: boolean = Locals.config().queueMonitor; + const queueMonitorPort: number = Locals.config().queueMonitorHttpPort; - if (isQueueMonitorEnabled) { - kue.app.listen(queueMonitorPort) + if (isQueueMonitorEnabled) { + kue.app.listen(queueMonitorPort); - console.log( - '\x1b[33m%s\x1b[0m', - `Queue Monitor :: Running @ 'http://localhost:${queueMonitorPort}'` - ) + console.log('\x1b[33m%s\x1b[0m', `Queue Monitor :: Running @ 'http://localhost:${queueMonitorPort}'`); + } } - } } -export default new App() +export default new App(); diff --git a/src/providers/Cache.ts b/src/providers/Cache.ts index 644e498..caaa23c 100644 --- a/src/providers/Cache.ts +++ b/src/providers/Cache.ts @@ -4,30 +4,30 @@ * @author Faiz A. Farooqui */ -import * as mcache from 'memory-cache' +import * as mcache from 'memory-cache'; class Cache { - /** - * Checks for the available cached data - * or adds if not available - */ - public cache(_duration: number): any { - return (req, res, next) => { - let key = '__express__' + req.originalUrl || req.url + /** + * Checks for the available cached data + * or adds if not available + */ + public cache(_duration: number): any { + return (req, res, next) => { + let key = '__express__' + req.originalUrl || req.url; - let cachedBody = mcache.get(key) - if (cachedBody) { - res.send(cachedBody) - } else { - res.sendResponse = res.send - res.send = body => { - mcache.put(key, body, _duration * 1000) - res.sendResponse(body) - } - next() - } + let cachedBody = mcache.get(key); + if (cachedBody) { + res.send(cachedBody); + } else { + res.sendResponse = res.send; + res.send = body => { + mcache.put(key, body, _duration * 1000); + res.sendResponse(body); + }; + next(); + } + }; } - } } -export default new Cache() +export default new Cache(); diff --git a/src/providers/Database.ts b/src/providers/Database.ts index 0053da8..c2d785b 100644 --- a/src/providers/Database.ts +++ b/src/providers/Database.ts @@ -4,34 +4,34 @@ * @author Faiz A. Farooqui */ -import * as mongoose from 'mongoose' -import * as bluebird from 'bluebird' -import { MongoError } from 'mongodb' +import * as mongoose from 'mongoose'; +import * as bluebird from 'bluebird'; +import { MongoError } from 'mongodb'; -import Locals from './Locals' -import Log from '../middlewares/Log' +import Locals from './Locals'; +import Log from '../middlewares/Log'; export class Database { - // Initialize your database pool - public static init(): any { - const dsn = Locals.config().mongooseUrl - const options = { useNewUrlParser: true, useUnifiedTopology: true } + // Initialize your database pool + public static init(): any { + const dsn = Locals.config().mongooseUrl; + const options = { useNewUrlParser: true, useUnifiedTopology: true }; - ;(mongoose).Promise = bluebird + (mongoose).Promise = bluebird; - mongoose.set('useCreateIndex', true) + mongoose.set('useCreateIndex', true); - mongoose.connect(dsn, options, (error: MongoError) => { - // handle the error case - if (error) { - Log.info('Failed to connect to the Mongo server!!') - console.log(error) - throw error - } else { - Log.info('connected to mongo server at: ' + dsn) - } - }) - } + mongoose.connect(dsn, options, (error: MongoError) => { + // handle the error case + if (error) { + Log.info('Failed to connect to the Mongo server!!'); + console.log(error); + throw error; + } else { + Log.info('connected to mongo server at: ' + dsn); + } + }); + } } -export default mongoose +export default mongoose; diff --git a/src/providers/Express.ts b/src/providers/Express.ts index 8a6aa63..ab5165b 100644 --- a/src/providers/Express.ts +++ b/src/providers/Express.ts @@ -4,71 +4,71 @@ * @author Faiz A. Farooqui */ -import * as express from 'express' +import * as express from 'express'; -import Locals from './Locals' -import Routes from './Routes' -import Bootstrap from '../middlewares/Kernel' -import ExceptionHandler from '../exception/Handler' +import Locals from './Locals'; +import Routes from './Routes'; +import Bootstrap from '../middlewares/Kernel'; +import ExceptionHandler from '../exception/Handler'; class Express { - /** - * Create the express object - */ - public express: express.Application + /** + * Create the express object + */ + public express: express.Application; - /** - * Initializes the express server - */ - constructor() { - this.express = express() + /** + * Initializes the express server + */ + constructor() { + this.express = express(); - this.mountDotEnv() - this.mountMiddlewares() - this.mountRoutes() - } + this.mountDotEnv(); + this.mountMiddlewares(); + this.mountRoutes(); + } - private mountDotEnv(): void { - this.express = Locals.init(this.express) - } + private mountDotEnv(): void { + this.express = Locals.init(this.express); + } - /** - * Mounts all the defined middlewares - */ - private mountMiddlewares(): void { - this.express = Bootstrap.init(this.express) - } + /** + * Mounts all the defined middlewares + */ + private mountMiddlewares(): void { + this.express = Bootstrap.init(this.express); + } - /** - * Mounts all the defined routes - */ - private mountRoutes(): void { - this.express = Routes.mountWeb(this.express) - this.express = Routes.mountApi(this.express) - } + /** + * Mounts all the defined routes + */ + private mountRoutes(): void { + this.express = Routes.mountWeb(this.express); + this.express = Routes.mountApi(this.express); + } - /** - * Starts the express server - */ - public init(): any { - const port: number = Locals.config().port + /** + * Starts the express server + */ + public init(): any { + const port: number = Locals.config().port; - // Registering Exception / Error Handlers - this.express.use(ExceptionHandler.logErrors) - this.express.use(ExceptionHandler.clientErrorHandler) - this.express.use(ExceptionHandler.errorHandler) - this.express = ExceptionHandler.notFoundHandler(this.express) + // Registering Exception / Error Handlers + this.express.use(ExceptionHandler.logErrors); + this.express.use(ExceptionHandler.clientErrorHandler); + this.express.use(ExceptionHandler.errorHandler); + this.express = ExceptionHandler.notFoundHandler(this.express); - // Start the server on the specified port - this.express - .listen(port, () => { - return console.log('\x1b[33m%s\x1b[0m', `Server :: Running @ 'http://localhost:${port}'`) - }) - .on('error', _error => { - return console.log('Error: ', _error.message) - }) - } + // Start the server on the specified port + this.express + .listen(port, () => { + return console.log('\x1b[33m%s\x1b[0m', `Server :: Running @ 'http://localhost:${port}'`); + }) + .on('error', _error => { + return console.log('Error: ', _error.message); + }); + } } /** Export the express module */ -export default new Express() +export default new Express(); diff --git a/src/providers/Locals.ts b/src/providers/Locals.ts index 9726f4b..890e185 100644 --- a/src/providers/Locals.ts +++ b/src/providers/Locals.ts @@ -4,78 +4,78 @@ * @author Faiz A. Farooqui */ -import { Application } from 'express' -import * as path from 'path' -import * as dotenv from 'dotenv' +import { Application } from 'express'; +import * as path from 'path'; +import * as dotenv from 'dotenv'; class Locals { - /** - * Makes env configs available for your app - * throughout the app's runtime - */ - public static config(): any { - dotenv.config({ path: path.join(__dirname, '../../.env') }) + /** + * Makes env configs available for your app + * throughout the app's runtime + */ + public static config(): any { + dotenv.config({ path: path.join(__dirname, '../../.env') }); - const url = process.env.APP_URL || `http://localhost:${process.env.PORT}` - const port = process.env.PORT || 4040 - const appSecret = process.env.APP_SECRET || 'This is your responsibility!' - const mongooseUrl = process.env.MONGOOSE_URL - const maxUploadLimit = process.env.APP_MAX_UPLOAD_LIMIT || '50mb' - const maxParameterLimit = process.env.APP_MAX_PARAMETER_LIMIT || '50mb' + const url = process.env.APP_URL || `http://localhost:${process.env.PORT}`; + const port = process.env.PORT || 4040; + const appSecret = process.env.APP_SECRET || 'This is your responsibility!'; + const mongooseUrl = process.env.MONGOOSE_URL; + const maxUploadLimit = process.env.APP_MAX_UPLOAD_LIMIT || '50mb'; + const maxParameterLimit = process.env.APP_MAX_PARAMETER_LIMIT || '50mb'; - const name = process.env.APP_NAME || 'NodeTS Dashboard' - const keywords = process.env.APP_KEYWORDS || 'somethings' - const year = new Date().getFullYear() - const copyright = `Copyright ${year} ${name} | All Rights Reserved` - const company = process.env.COMPANY_NAME || 'GeekyAnts' - const description = process.env.APP_DESCRIPTION || 'Here goes the app description' + const name = process.env.APP_NAME || 'NodeTS Dashboard'; + const keywords = process.env.APP_KEYWORDS || 'somethings'; + const year = new Date().getFullYear(); + const copyright = `Copyright ${year} ${name} | All Rights Reserved`; + const company = process.env.COMPANY_NAME || 'GeekyAnts'; + const description = process.env.APP_DESCRIPTION || 'Here goes the app description'; - const isCORSEnabled = process.env.CORS_ENABLED || true - const jwtExpiresIn = process.env.JWT_EXPIRES_IN || 3 - const apiPrefix = process.env.API_PREFIX || 'api' + const isCORSEnabled = process.env.CORS_ENABLED || true; + const jwtExpiresIn = process.env.JWT_EXPIRES_IN || 3; + const apiPrefix = process.env.API_PREFIX || 'api'; - const logDays = process.env.LOG_DAYS || 10 + const logDays = process.env.LOG_DAYS || 10; - const queueMonitor = process.env.QUEUE_HTTP_ENABLED || true - const queueMonitorHttpPort = process.env.QUEUE_HTTP_PORT || 5550 + const queueMonitor = process.env.QUEUE_HTTP_ENABLED || true; + const queueMonitorHttpPort = process.env.QUEUE_HTTP_PORT || 5550; - const redisHttpPort = process.env.REDIS_QUEUE_PORT || 6379 - const redisHttpHost = process.env.REDIS_QUEUE_HOST || '127.0.0.1' - const redisPrefix = process.env.REDIS_QUEUE_DB || 'q' - const redisDB = process.env.REDIS_QUEUE_PREFIX || 3 + const redisHttpPort = process.env.REDIS_QUEUE_PORT || 6379; + const redisHttpHost = process.env.REDIS_QUEUE_HOST || '127.0.0.1'; + const redisPrefix = process.env.REDIS_QUEUE_DB || 'q'; + const redisDB = process.env.REDIS_QUEUE_PREFIX || 3; - return { - appSecret, - apiPrefix, - company, - copyright, - description, - isCORSEnabled, - jwtExpiresIn, - keywords, - logDays, - maxUploadLimit, - maxParameterLimit, - mongooseUrl, - name, - port, - redisDB, - redisHttpPort, - redisHttpHost, - redisPrefix, - url, - queueMonitor, - queueMonitorHttpPort, + return { + appSecret, + apiPrefix, + company, + copyright, + description, + isCORSEnabled, + jwtExpiresIn, + keywords, + logDays, + maxUploadLimit, + maxParameterLimit, + mongooseUrl, + name, + port, + redisDB, + redisHttpPort, + redisHttpHost, + redisPrefix, + url, + queueMonitor, + queueMonitorHttpPort, + }; } - } - /** - * Injects your config to the app's locals - */ - public static init(_express: Application): Application { - _express.locals.app = this.config() - return _express - } + /** + * Injects your config to the app's locals + */ + public static init(_express: Application): Application { + _express.locals.app = this.config(); + return _express; + } } -export default Locals +export default Locals; diff --git a/src/providers/Passport.ts b/src/providers/Passport.ts index 9dd370e..5a7ef12 100644 --- a/src/providers/Passport.ts +++ b/src/providers/Passport.ts @@ -4,64 +4,64 @@ * @author Faiz A. Farooqui */ -import { Application } from 'express' -import * as passport from 'passport' +import { Application } from 'express'; +import * as passport from 'passport'; -import LocalStrategy from '../services/strategies/Local' -import GoogleStrategy from '../services/strategies/Google' -import TwitterStrategy from '../services/strategies/Twitter' +import LocalStrategy from '../services/strategies/Local'; +import GoogleStrategy from '../services/strategies/Google'; +import TwitterStrategy from '../services/strategies/Twitter'; -import User from '../models/User' -import Log from '../middlewares/Log' +import User from '../models/User'; +import Log from '../middlewares/Log'; class Passport { - public mountPackage(_express: Application): Application { - _express = _express.use(passport.initialize()) - _express = _express.use(passport.session()) + public mountPackage(_express: Application): Application { + _express = _express.use(passport.initialize()); + _express = _express.use(passport.session()); - passport.serializeUser((user, done) => { - done(null, user.id) - }) + passport.serializeUser((user, done) => { + done(null, user.id); + }); - passport.deserializeUser((id, done) => { - User.findById(id, (err, user) => { - done(err, user) - }) - }) + passport.deserializeUser((id, done) => { + User.findById(id, (err, user) => { + done(err, user); + }); + }); - this.mountLocalStrategies() + this.mountLocalStrategies(); - return _express - } - - public mountLocalStrategies(): void { - try { - LocalStrategy.init(passport) - GoogleStrategy.init(passport) - TwitterStrategy.init(passport) - } catch (_err) { - Log.error(_err.stack) + return _express; } - } - public isAuthenticated(req, res, next): any { - if (req.isAuthenticated()) { - return next() + public mountLocalStrategies(): void { + try { + LocalStrategy.init(passport); + GoogleStrategy.init(passport); + TwitterStrategy.init(passport); + } catch (_err) { + Log.error(_err.stack); + } } - req.flash('errors', { msg: 'Please Log-In to access any further!' }) - return res.redirect('/login') - } + public isAuthenticated(req, res, next): any { + if (req.isAuthenticated()) { + return next(); + } + + req.flash('errors', { msg: 'Please Log-In to access any further!' }); + return res.redirect('/login'); + } - public isAuthorized(req, res, next): any { - const provider = req.path.split('/').slice(-1)[0] - const token = req.user.tokens.find(token => token.kind === provider) - if (token) { - return next() - } else { - return res.redirect(`/auth/${provider}`) + public isAuthorized(req, res, next): any { + const provider = req.path.split('/').slice(-1)[0]; + const token = req.user.tokens.find(token => token.kind === provider); + if (token) { + return next(); + } else { + return res.redirect(`/auth/${provider}`); + } } - } } -export default new Passport() +export default new Passport(); diff --git a/src/providers/Queue.ts b/src/providers/Queue.ts index 853020b..1bef62d 100644 --- a/src/providers/Queue.ts +++ b/src/providers/Queue.ts @@ -4,60 +4,60 @@ * @author Faiz A. Farooqui */ -import * as kue from 'kue' +import * as kue from 'kue'; -import Locals from './Locals' -import Log from '../middlewares/Log' +import Locals from './Locals'; +import Log from '../middlewares/Log'; class Queue { - public jobs: any - - constructor() { - this.jobs = kue.createQueue({ - prefix: Locals.config().redisPrefix, - redis: { - port: Locals.config().redisHttpPort, - host: Locals.config().redisHttpHost, - db: Locals.config().redisDB, - }, - }) - - this.jobs - .on('job enqueue', (_id, _type) => Log.info(`Queue :: #${_id} Processing of type '${_type}'`)) - .on('job complete', _id => this.removeProcessedJob(_id)) - } - - public dispatch(_jobName: string, _args: object, _callback: Function): void { - this.jobs.create(_jobName, _args).save() - - this.process(_jobName, 3, _callback) - } - - private removeProcessedJob(_id): void { - Log.info(`Queue :: #${_id} Processed`) - - kue.Job.get(_id, (_err, _job) => { - if (_err) { - return - } - - _job.remove(_err => { - if (_err) { - throw _err - } - - Log.info(`Queue :: #${_id} Removed Processed Job`) - }) - }) - } - - private process(_jobName: string, _count: number, _callback: Function): void { - this.jobs.process(_jobName, _count, (_job, _done) => { - _done() // Notifies KUE about the completion of the job! - - _callback(_job.data) - }) - } + public jobs: any; + + constructor() { + this.jobs = kue.createQueue({ + prefix: Locals.config().redisPrefix, + redis: { + port: Locals.config().redisHttpPort, + host: Locals.config().redisHttpHost, + db: Locals.config().redisDB, + }, + }); + + this.jobs + .on('job enqueue', (_id, _type) => Log.info(`Queue :: #${_id} Processing of type '${_type}'`)) + .on('job complete', _id => this.removeProcessedJob(_id)); + } + + public dispatch(_jobName: string, _args: object, _callback: Function): void { + this.jobs.create(_jobName, _args).save(); + + this.process(_jobName, 3, _callback); + } + + private removeProcessedJob(_id): void { + Log.info(`Queue :: #${_id} Processed`); + + kue.Job.get(_id, (_err, _job) => { + if (_err) { + return; + } + + _job.remove(_err => { + if (_err) { + throw _err; + } + + Log.info(`Queue :: #${_id} Removed Processed Job`); + }); + }); + } + + private process(_jobName: string, _count: number, _callback: Function): void { + this.jobs.process(_jobName, _count, (_job, _done) => { + _done(); // Notifies KUE about the completion of the job! + + _callback(_job.data); + }); + } } -export default new Queue() +export default new Queue(); diff --git a/src/providers/Routes.ts b/src/providers/Routes.ts index 49bd074..07afed8 100644 --- a/src/providers/Routes.ts +++ b/src/providers/Routes.ts @@ -4,26 +4,26 @@ * @author Faiz A. Farooqui */ -import { Application } from 'express' -import Locals from './Locals' -import Log from '../middlewares/Log' +import { Application } from 'express'; +import Locals from './Locals'; +import Log from '../middlewares/Log'; -import webRouter from './../routes/Web' -import apiRouter from './../routes/Api' +import webRouter from './../routes/Web'; +import apiRouter from './../routes/Api'; class Routes { - public mountWeb(_express: Application): Application { - Log.info('Routes :: Mounting Web Routes...') + public mountWeb(_express: Application): Application { + Log.info('Routes :: Mounting Web Routes...'); - return _express.use('/', webRouter) - } + return _express.use('/', webRouter); + } - public mountApi(_express: Application): Application { - const apiPrefix = Locals.config().apiPrefix - Log.info('Routes :: Mounting API Routes...') + public mountApi(_express: Application): Application { + const apiPrefix = Locals.config().apiPrefix; + Log.info('Routes :: Mounting API Routes...'); - return _express.use(`/${apiPrefix}`, apiRouter) - } + return _express.use(`/${apiPrefix}`, apiRouter); + } } -export default new Routes() +export default new Routes(); diff --git a/src/routes/Api.ts b/src/routes/Api.ts index 6c9a079..81f4262 100644 --- a/src/routes/Api.ts +++ b/src/routes/Api.ts @@ -4,26 +4,22 @@ * @author Faiz A. Farooqui */ -import { Router } from 'express' -import * as expressJwt from 'express-jwt' +import { Router } from 'express'; +import * as expressJwt from 'express-jwt'; -import Locals from '../providers/Locals' +import Locals from '../providers/Locals'; -import HomeController from '../controllers/Api/Home' -import LoginController from '../controllers/Api/Auth/Login' -import RegisterController from '../controllers/Api/Auth/Register' -import RefreshTokenController from '../controllers/Api/Auth/RefreshToken' +import HomeController from '../controllers/Api/Home'; +import LoginController from '../controllers/Api/Auth/Login'; +import RegisterController from '../controllers/Api/Auth/Register'; +import RefreshTokenController from '../controllers/Api/Auth/RefreshToken'; -const router = Router() +const router = Router(); -router.get('/', HomeController.index) +router.get('/', HomeController.index); -router.post('/auth/login', LoginController.perform) -router.post('/auth/register', RegisterController.perform) -router.post( - '/auth/refresh-token', - expressJwt({ secret: Locals.config().appSecret }), - RefreshTokenController.perform -) +router.post('/auth/login', LoginController.perform); +router.post('/auth/register', RegisterController.perform); +router.post('/auth/refresh-token', expressJwt({ secret: Locals.config().appSecret }), RefreshTokenController.perform); -export default router +export default router; diff --git a/src/routes/Web.ts b/src/routes/Web.ts index d1e5556..468b7f6 100644 --- a/src/routes/Web.ts +++ b/src/routes/Web.ts @@ -4,51 +4,44 @@ * @author Faiz A. Farooqui */ -import * as passport from 'passport' -import { Router } from 'express' +import * as passport from 'passport'; +import { Router } from 'express'; -import Cache from './../providers/Cache' -import Passport from './../providers/Passport' +import Cache from './../providers/Cache'; +import Passport from './../providers/Passport'; -import HomeController from '../controllers/Home' -import AccountController from '../controllers/Account' -import LoginController from '../controllers/Auth/Login' -import LogoutController from '../controllers/Auth/Logout' -import SocialController from '../controllers/Auth/Social' -import RegisterController from '../controllers/Auth/Register' +import HomeController from '../controllers/Home'; +import AccountController from '../controllers/Account'; +import LoginController from '../controllers/Auth/Login'; +import LogoutController from '../controllers/Auth/Logout'; +import SocialController from '../controllers/Auth/Social'; +import RegisterController from '../controllers/Auth/Register'; -const router = Router() -const cache = Cache.cache +const router = Router(); +const cache = Cache.cache; -router.get('/', cache(10), HomeController.index) +router.get('/', cache(10), HomeController.index); -router.get('/signup', cache(10), RegisterController.show) -router.post('/signup', RegisterController.perform) +router.get('/signup', cache(10), RegisterController.show); +router.post('/signup', RegisterController.perform); -router.get('/login', cache(10), LoginController.show) -router.post('/login', LoginController.perform) +router.get('/login', cache(10), LoginController.show); +router.post('/login', LoginController.perform); -router.get('/logout', LogoutController.perform) +router.get('/logout', LogoutController.perform); -router.get('/account', Passport.isAuthenticated, AccountController.index) +router.get('/account', Passport.isAuthenticated, AccountController.index); +router.get('/auth/google', passport.authenticate('google', { scope: ['email', 'profile'], failureRedirect: '/login' })); router.get( - '/auth/google', - passport.authenticate('google', { scope: ['email', 'profile'], failureRedirect: '/login' }) -) -router.get( - '/auth/google/callback', - passport.authenticate('google', { failureRedirect: '/login' }), - SocialController.googleCallback -) + '/auth/google/callback', + passport.authenticate('google', { failureRedirect: '/login' }), + SocialController.googleCallback +); -router.get('/auth/twitter', passport.authenticate('twitter')) -router.get( - '/auth/twitter/callback', - passport.authenticate('twitter', { failureRedirect: '/login' }), - (req, res) => { - res.redirect('/') - } -) - -export default router +router.get('/auth/twitter', passport.authenticate('twitter')); +router.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), (req, res) => { + res.redirect('/'); +}); + +export default router; diff --git a/src/services/strategies/Google.ts b/src/services/strategies/Google.ts index 8fe7a88..c76e40d 100644 --- a/src/services/strategies/Google.ts +++ b/src/services/strategies/Google.ts @@ -4,95 +4,95 @@ * @author Faiz A. Farooqui */ -import { Strategy } from 'passport-google-oauth20' -import User from '../../models/User' -import Locals from '../../providers/Locals' +import { Strategy } from 'passport-google-oauth20'; +import User from '../../models/User'; +import Locals from '../../providers/Locals'; class Google { - public static init(_passport: any): any { - _passport.use( - new Strategy( - { - clientID: process.env.GOOGLE_ID, - clientSecret: process.env.GOOGLE_SECRET, - callbackURL: `${Locals.config().url}/auth/google/callback`, - passReqToCallback: true, - }, - (req, accessToken, refreshToken, profile, done) => { - if (req.user) { - User.findOne({ google: profile.id }, (err, existingUser) => { - if (err) { - return done(err) - } + public static init(_passport: any): any { + _passport.use( + new Strategy( + { + clientID: process.env.GOOGLE_ID, + clientSecret: process.env.GOOGLE_SECRET, + callbackURL: `${Locals.config().url}/auth/google/callback`, + passReqToCallback: true, + }, + (req, accessToken, refreshToken, profile, done) => { + if (req.user) { + User.findOne({ google: profile.id }, (err, existingUser) => { + if (err) { + return done(err); + } - if (existingUser) { - req.flash('errors', { - msg: 'There is already a Google account that belongs to you. Sign in with that account or delete it, then link it with your current account.', - }) - return done(err) - } else { - User.findById(req.user.id, (err, user) => { - if (err) { - return done(err) - } + if (existingUser) { + req.flash('errors', { + msg: 'There is already a Google account that belongs to you. Sign in with that account or delete it, then link it with your current account.', + }); + return done(err); + } else { + User.findById(req.user.id, (err, user) => { + if (err) { + return done(err); + } - user.google = profile.id - user.tokens.push({ kind: 'google', accessToken }) - user.fullname = user.fullname || profile.displayName - user.gender = user.gender || profile._json.gender - if (profile.photos) { - user.picture = user.picture || profile.photos[0].value - } - user.save(err => { - req.flash('info', { msg: 'Google account has been linked.' }) - return done(err, user) - }) - }) - } - }) - } else { - User.findOne({ google: profile.id }, (err, existingUser) => { - if (err) { - return done(err) - } + user.google = profile.id; + user.tokens.push({ kind: 'google', accessToken }); + user.fullname = user.fullname || profile.displayName; + user.gender = user.gender || profile._json.gender; + if (profile.photos) { + user.picture = user.picture || profile.photos[0].value; + } + user.save(err => { + req.flash('info', { msg: 'Google account has been linked.' }); + return done(err, user); + }); + }); + } + }); + } else { + User.findOne({ google: profile.id }, (err, existingUser) => { + if (err) { + return done(err); + } - if (existingUser) { - return done(null, existingUser) - } + if (existingUser) { + return done(null, existingUser); + } - User.findOne({ email: profile.emails[0].value }, (err, existingEmailUser) => { - if (err) { - return done(err) - } + User.findOne({ email: profile.emails[0].value }, (err, existingEmailUser) => { + if (err) { + return done(err); + } - if (existingEmailUser) { - req.flash('errors', { - msg: 'There is already an account using this email address. Sing in to that accoount and link it with Google manually from Account Settings.', - }) - return done(err) - } else { - const user = new User() + if (existingEmailUser) { + req.flash('errors', { + msg: 'There is already an account using this email address. Sing in to that accoount and link it with Google manually from Account Settings.', + }); + return done(err); + } else { + const user = new User(); - user.email = profile.emails[0].value - user.google = profile.id - user.tokens.push({ kind: 'google', accessToken }) - user.fullname = user.fullname || profile.displayName - user.gender = user.gender || profile._json.gender - if (profile.photos) { - user.picture = user.picture || profile.photos[0].value - } + user.email = profile.emails[0].value; + user.google = profile.id; + user.tokens.push({ kind: 'google', accessToken }); + user.fullname = user.fullname || profile.displayName; + user.gender = user.gender || profile._json.gender; + if (profile.photos) { + user.picture = user.picture || profile.photos[0].value; + } - user.save(err => { - return done(err, user) - }) + user.save(err => { + return done(err, user); + }); + } + }); + }); + } } - }) - }) - } - } - ) - ) - } + ) + ); + } } -export default Google +export default Google; diff --git a/src/services/strategies/Local.ts b/src/services/strategies/Local.ts index cf8dabb..e2f5844 100644 --- a/src/services/strategies/Local.ts +++ b/src/services/strategies/Local.ts @@ -4,50 +4,50 @@ * @author Faiz A. Farooqui */ -import { Strategy } from 'passport-local' -import User from '../../models/User' -import Log from '../../middlewares/Log' +import { Strategy } from 'passport-local'; +import User from '../../models/User'; +import Log from '../../middlewares/Log'; class Local { - public static init(_passport: any): any { - _passport.use( - new Strategy({ usernameField: 'email' }, (email, password, done) => { - Log.info(`Email is ${email}`) - Log.info(`Password is ${password}`) - - User.findOne({ email: email.toLowerCase() }, (err, user) => { - Log.info(`user is ${user.email}`) - Log.info(`error is ${err}`) - - if (err) { - return done(err) - } - - if (!user) { - return done(null, false, { msg: `E-mail ${email} not found.` }) - } - - if (user && !user.password) { - return done(null, false, { - msg: `E-mail ${email} was not registered with us using any password. Please use the appropriate providers to Log-In again!`, + public static init(_passport: any): any { + _passport.use( + new Strategy({ usernameField: 'email' }, (email, password, done) => { + Log.info(`Email is ${email}`); + Log.info(`Password is ${password}`); + + User.findOne({ email: email.toLowerCase() }, (err, user) => { + Log.info(`user is ${user.email}`); + Log.info(`error is ${err}`); + + if (err) { + return done(err); + } + + if (!user) { + return done(null, false, { msg: `E-mail ${email} not found.` }); + } + + if (user && !user.password) { + return done(null, false, { + msg: `E-mail ${email} was not registered with us using any password. Please use the appropriate providers to Log-In again!`, + }); + } + + Log.info('comparing password now!'); + + user.comparePassword(password, (_err, _isMatch) => { + if (_err) { + return done(_err); + } + if (_isMatch) { + return done(null, user); + } + return done(null, false, { msg: 'Invalid E-mail or password.' }); + }); + }); }) - } - - Log.info('comparing password now!') - - user.comparePassword(password, (_err, _isMatch) => { - if (_err) { - return done(_err) - } - if (_isMatch) { - return done(null, user) - } - return done(null, false, { msg: 'Invalid E-mail or password.' }) - }) - }) - }) - ) - } + ); + } } -export default Local +export default Local; diff --git a/src/services/strategies/Twitter.ts b/src/services/strategies/Twitter.ts index c768149..4cfde1c 100644 --- a/src/services/strategies/Twitter.ts +++ b/src/services/strategies/Twitter.ts @@ -4,82 +4,82 @@ * @author Faiz A. Farooqui */ -import { Strategy } from 'passport-twitter' -import User from '../../models/User' -import Locals from '../../providers/Locals' +import { Strategy } from 'passport-twitter'; +import User from '../../models/User'; +import Locals from '../../providers/Locals'; class Twitter { - public static init(_passport: any): any { - _passport.use( - new Strategy( - { - consumerKey: process.env.TWITTER_KEY, - consumerSecret: process.env.TWITTER_SECRET, - callbackURL: `${Locals.config().url}/auth/twitter/callback`, - passReqToCallback: true, - }, - (req, accessToken, tokenSecret, profile, done) => { - if (req.user) { - User.findOne({ twitter: profile.id }, (err, existingUser) => { - if (err) { - return done(err) - } + public static init(_passport: any): any { + _passport.use( + new Strategy( + { + consumerKey: process.env.TWITTER_KEY, + consumerSecret: process.env.TWITTER_SECRET, + callbackURL: `${Locals.config().url}/auth/twitter/callback`, + passReqToCallback: true, + }, + (req, accessToken, tokenSecret, profile, done) => { + if (req.user) { + User.findOne({ twitter: profile.id }, (err, existingUser) => { + if (err) { + return done(err); + } - if (existingUser) { - req.flash('errors', { - msg: 'There is already a Twitter account that belongs to you. Sign in with that account or delete it, then link it with your current account.', - }) - return done(err) - } else { - User.findById(req.user.id, (err, user) => { - if (err) { - return done(err) - } + if (existingUser) { + req.flash('errors', { + msg: 'There is already a Twitter account that belongs to you. Sign in with that account or delete it, then link it with your current account.', + }); + return done(err); + } else { + User.findById(req.user.id, (err, user) => { + if (err) { + return done(err); + } - user.twitter = profile.id - user.tokens.push({ kind: 'twitter', accessToken, tokenSecret }) - user.fullname = user.fullname || profile.displayName - user.geolocation = user.geolocation || profile._json.location - user.picture = user.picture || profile._json.profile_image_url_https - user.save(err => { - if (err) { - return done(err) - } + user.twitter = profile.id; + user.tokens.push({ kind: 'twitter', accessToken, tokenSecret }); + user.fullname = user.fullname || profile.displayName; + user.geolocation = user.geolocation || profile._json.location; + user.picture = user.picture || profile._json.profile_image_url_https; + user.save(err => { + if (err) { + return done(err); + } - req.flash('info', { msg: 'Twitter account has been linked.' }) - return done(err, user) - }) - }) - } - }) - } else { - User.findOne({ twitter: profile.id }, (err, existingUser) => { - if (err) { - return done(err) - } + req.flash('info', { msg: 'Twitter account has been linked.' }); + return done(err, user); + }); + }); + } + }); + } else { + User.findOne({ twitter: profile.id }, (err, existingUser) => { + if (err) { + return done(err); + } - if (existingUser) { - return done(null, existingUser) - } + if (existingUser) { + return done(null, existingUser); + } - const user = new User() - // Twitter does not provides the user's e-mail address. - // We can "fake" a twitter email address as follows: - user.email = `${profile.username}@twitter.com` - user.twitter = profile.id - user.tokens.push({ kind: 'twitter', accessToken, tokenSecret }) - user.fullname = profile.displayName - user.geolocation = profile._json.location - user.picture = profile._json.profile_image_url_https - user.save(err => { - done(err, user) - }) - }) - } - } - ) - ) - } + const user = new User(); + // Twitter does not provides the user's e-mail address. + // We can "fake" a twitter email address as follows: + user.email = `${profile.username}@twitter.com`; + user.twitter = profile.id; + user.tokens.push({ kind: 'twitter', accessToken, tokenSecret }); + user.fullname = profile.displayName; + user.geolocation = profile._json.location; + user.picture = profile._json.profile_image_url_https; + user.save(err => { + done(err, user); + }); + }); + } + } + ) + ); + } } -export default Twitter +export default Twitter; From 6ca709c53e4c479878361a24b7d6e2c1afe5b73f Mon Sep 17 00:00:00 2001 From: Ahmed Meftah Date: Fri, 24 Jun 2022 20:29:41 +0100 Subject: [PATCH 8/8] Remove dist from git --- dist/controllers/Account.js | 16 ---- dist/controllers/Account.js.map | 1 - dist/controllers/Api/Auth/Login.js | 66 -------------- dist/controllers/Api/Auth/Login.js.map | 1 - dist/controllers/Api/Auth/RefreshToken.js | 69 --------------- dist/controllers/Api/Auth/RefreshToken.js.map | 1 - dist/controllers/Api/Auth/Register.js | 55 ------------ dist/controllers/Api/Auth/Register.js.map | 1 - dist/controllers/Api/Home.js | 17 ---- dist/controllers/Api/Home.js.map | 1 - dist/controllers/Home.js | 16 ---- dist/controllers/Home.js.map | 1 - dist/controllers/auth/Login.js | 48 ----------- dist/controllers/auth/Login.js.map | 1 - dist/controllers/auth/Logout.js | 21 ----- dist/controllers/auth/Logout.js.map | 1 - dist/controllers/auth/Register.js | 56 ------------ dist/controllers/auth/Register.js.map | 1 - dist/controllers/auth/Social.js | 14 --- dist/controllers/auth/Social.js.map | 1 - dist/exception/Handler.js | 79 ----------------- dist/exception/Handler.js.map | 1 - dist/exception/NativeEvent.js | 32 ------- dist/exception/NativeEvent.js.map | 1 - dist/index.js | 58 ------------- dist/index.js.map | 1 - dist/interfaces/models/user.js | 8 -- dist/interfaces/models/user.js.map | 1 - dist/interfaces/vendors/INext.js | 8 -- dist/interfaces/vendors/INext.js.map | 1 - dist/interfaces/vendors/IRequest.js | 8 -- dist/interfaces/vendors/IRequest.js.map | 1 - dist/interfaces/vendors/IResponse.js | 8 -- dist/interfaces/vendors/IResponse.js.map | 1 - dist/interfaces/vendors/index.js | 8 -- dist/interfaces/vendors/index.js.map | 1 - dist/middlewares/CORS.js | 23 ----- dist/middlewares/CORS.js.map | 1 - dist/middlewares/CsrfToken.js | 56 ------------ dist/middlewares/CsrfToken.js.map | 1 - dist/middlewares/Http.js | 66 -------------- dist/middlewares/Http.js.map | 1 - dist/middlewares/Kernel.js | 36 -------- dist/middlewares/Kernel.js.map | 1 - dist/middlewares/Log.js | 76 ----------------- dist/middlewares/Log.js.map | 1 - dist/middlewares/Statics.js | 24 ------ dist/middlewares/Statics.js.map | 1 - dist/middlewares/StatusMonitor.js | 62 -------------- dist/middlewares/StatusMonitor.js.map | 1 - dist/middlewares/Views.js | 21 ----- dist/middlewares/Views.js.map | 1 - dist/models/User.js | 79 ----------------- dist/models/User.js.map | 1 - dist/providers/App.js | 54 ------------ dist/providers/App.js.map | 1 - dist/providers/Cache.js | 33 ------- dist/providers/Cache.js.map | 1 - dist/providers/Database.js | 35 -------- dist/providers/Database.js.map | 1 - dist/providers/Express.js | 60 ------------- dist/providers/Express.js.map | 1 - dist/providers/Locals.js | 72 ---------------- dist/providers/Locals.js.map | 1 - dist/providers/Passport.js | 58 ------------- dist/providers/Passport.js.map | 1 - dist/providers/Queue.js | 51 ----------- dist/providers/Queue.js.map | 1 - dist/providers/Routes.js | 24 ------ dist/providers/Routes.js.map | 1 - dist/routes/Api.js | 21 ----- dist/routes/Api.js.map | 1 - dist/routes/Web.js | 34 -------- dist/routes/Web.js.map | 1 - dist/services/strategies/Google.js | 85 ------------------- dist/services/strategies/Google.js.map | 1 - dist/services/strategies/Local.js | 43 ---------- dist/services/strategies/Local.js.map | 1 - dist/services/strategies/Twitter.js | 75 ---------------- dist/services/strategies/Twitter.js.map | 1 - 80 files changed, 1715 deletions(-) delete mode 100644 dist/controllers/Account.js delete mode 100644 dist/controllers/Account.js.map delete mode 100644 dist/controllers/Api/Auth/Login.js delete mode 100644 dist/controllers/Api/Auth/Login.js.map delete mode 100644 dist/controllers/Api/Auth/RefreshToken.js delete mode 100644 dist/controllers/Api/Auth/RefreshToken.js.map delete mode 100644 dist/controllers/Api/Auth/Register.js delete mode 100644 dist/controllers/Api/Auth/Register.js.map delete mode 100644 dist/controllers/Api/Home.js delete mode 100644 dist/controllers/Api/Home.js.map delete mode 100644 dist/controllers/Home.js delete mode 100644 dist/controllers/Home.js.map delete mode 100644 dist/controllers/auth/Login.js delete mode 100644 dist/controllers/auth/Login.js.map delete mode 100644 dist/controllers/auth/Logout.js delete mode 100644 dist/controllers/auth/Logout.js.map delete mode 100644 dist/controllers/auth/Register.js delete mode 100644 dist/controllers/auth/Register.js.map delete mode 100644 dist/controllers/auth/Social.js delete mode 100644 dist/controllers/auth/Social.js.map delete mode 100644 dist/exception/Handler.js delete mode 100644 dist/exception/Handler.js.map delete mode 100644 dist/exception/NativeEvent.js delete mode 100644 dist/exception/NativeEvent.js.map delete mode 100644 dist/index.js delete mode 100644 dist/index.js.map delete mode 100644 dist/interfaces/models/user.js delete mode 100644 dist/interfaces/models/user.js.map delete mode 100644 dist/interfaces/vendors/INext.js delete mode 100644 dist/interfaces/vendors/INext.js.map delete mode 100644 dist/interfaces/vendors/IRequest.js delete mode 100644 dist/interfaces/vendors/IRequest.js.map delete mode 100644 dist/interfaces/vendors/IResponse.js delete mode 100644 dist/interfaces/vendors/IResponse.js.map delete mode 100644 dist/interfaces/vendors/index.js delete mode 100644 dist/interfaces/vendors/index.js.map delete mode 100644 dist/middlewares/CORS.js delete mode 100644 dist/middlewares/CORS.js.map delete mode 100644 dist/middlewares/CsrfToken.js delete mode 100644 dist/middlewares/CsrfToken.js.map delete mode 100644 dist/middlewares/Http.js delete mode 100644 dist/middlewares/Http.js.map delete mode 100644 dist/middlewares/Kernel.js delete mode 100644 dist/middlewares/Kernel.js.map delete mode 100644 dist/middlewares/Log.js delete mode 100644 dist/middlewares/Log.js.map delete mode 100644 dist/middlewares/Statics.js delete mode 100644 dist/middlewares/Statics.js.map delete mode 100644 dist/middlewares/StatusMonitor.js delete mode 100644 dist/middlewares/StatusMonitor.js.map delete mode 100644 dist/middlewares/Views.js delete mode 100644 dist/middlewares/Views.js.map delete mode 100644 dist/models/User.js delete mode 100644 dist/models/User.js.map delete mode 100644 dist/providers/App.js delete mode 100644 dist/providers/App.js.map delete mode 100644 dist/providers/Cache.js delete mode 100644 dist/providers/Cache.js.map delete mode 100644 dist/providers/Database.js delete mode 100644 dist/providers/Database.js.map delete mode 100644 dist/providers/Express.js delete mode 100644 dist/providers/Express.js.map delete mode 100644 dist/providers/Locals.js delete mode 100644 dist/providers/Locals.js.map delete mode 100644 dist/providers/Passport.js delete mode 100644 dist/providers/Passport.js.map delete mode 100644 dist/providers/Queue.js delete mode 100644 dist/providers/Queue.js.map delete mode 100644 dist/providers/Routes.js delete mode 100644 dist/providers/Routes.js.map delete mode 100644 dist/routes/Api.js delete mode 100644 dist/routes/Api.js.map delete mode 100644 dist/routes/Web.js delete mode 100644 dist/routes/Web.js.map delete mode 100644 dist/services/strategies/Google.js delete mode 100644 dist/services/strategies/Google.js.map delete mode 100644 dist/services/strategies/Local.js delete mode 100644 dist/services/strategies/Local.js.map delete mode 100644 dist/services/strategies/Twitter.js delete mode 100644 dist/services/strategies/Twitter.js.map diff --git a/dist/controllers/Account.js b/dist/controllers/Account.js deleted file mode 100644 index 40bc6a5..0000000 --- a/dist/controllers/Account.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; -/** - * Handler for Account - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -class Account { - static index(req, res) { - return res.render('pages/dashboard', { - title: 'Home' - }); - } -} -exports.default = Account; -//# sourceMappingURL=Account.js.map \ No newline at end of file diff --git a/dist/controllers/Account.js.map b/dist/controllers/Account.js.map deleted file mode 100644 index 8a78289..0000000 --- a/dist/controllers/Account.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Account.js","sourceRoot":"","sources":["../../src/controllers/Account.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAIH,MAAM,OAAO;IACL,MAAM,CAAC,KAAK,CAAE,GAAa,EAAE,GAAc;QACjD,OAAO,GAAG,CAAC,MAAM,CAAC,iBAAiB,EAAE;YACpC,KAAK,EAAE,MAAM;SACb,CAAC,CAAC;IACJ,CAAC;CACD;AAED,kBAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/dist/controllers/Api/Auth/Login.js b/dist/controllers/Api/Auth/Login.js deleted file mode 100644 index ecad1e9..0000000 --- a/dist/controllers/Api/Auth/Login.js +++ /dev/null @@ -1,66 +0,0 @@ -"use strict"; -/** - * Define Login Login for the API - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const jwt = require("jsonwebtoken"); -const User_1 = require("../../../models/User"); -class Login { - static perform(req, res) { - req.assert('email', 'E-mail cannot be blank').notEmpty(); - req.assert('email', 'E-mail is not valid').isEmail(); - req.assert('password', 'Password cannot be blank').notEmpty(); - req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }); - req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }); - const errors = req.validationErrors(); - if (errors) { - return res.json({ - errors - }); - } - const _email = req.body.email.toLowerCase(); - const _password = req.body.password; - User_1.default.findOne({ email: _email }, (err, user) => { - if (err) { - return res.json({ - error: err - }); - } - if (!user) { - return res.json({ - error: ['User not found!'] - }); - } - if (!user.password) { - return res.json({ - error: ['Please login using your social creds'] - }); - } - user.comparePassword(_password, (err, isMatch) => { - if (err) { - return res.json({ - error: err - }); - } - if (!isMatch) { - return res.json({ - error: ['Password does not match!'] - }); - } - const token = jwt.sign({ email: _email, password: _password }, res.locals.app.appSecret, { expiresIn: res.locals.app.jwtExpiresIn * 60 }); - // Hide protected columns - user.tokens = undefined; - user.password = undefined; - return res.json({ - user, - token, - token_expires_in: res.locals.app.jwtExpiresIn * 60 - }); - }); - }); - } -} -exports.default = Login; -//# sourceMappingURL=Login.js.map \ No newline at end of file diff --git a/dist/controllers/Api/Auth/Login.js.map b/dist/controllers/Api/Auth/Login.js.map deleted file mode 100644 index 9346f84..0000000 --- a/dist/controllers/Api/Auth/Login.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Login.js","sourceRoot":"","sources":["../../../../src/controllers/Api/Auth/Login.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,oCAAoC;AAEpC,+CAAwC;AAExC,MAAM,KAAK;IACH,MAAM,CAAC,OAAO,CAAE,GAAG,EAAE,GAAG;QAC9B,GAAG,CAAC,MAAM,CAAC,OAAO,EAAE,wBAAwB,CAAC,CAAC,QAAQ,EAAE,CAAC;QACzD,GAAG,CAAC,MAAM,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAC,OAAO,EAAE,CAAC;QACrD,GAAG,CAAC,MAAM,CAAC,UAAU,EAAE,0BAA0B,CAAC,CAAC,QAAQ,EAAE,CAAC;QAC9D,GAAG,CAAC,MAAM,CAAC,UAAU,EAAE,8CAA8C,CAAC,CAAC,QAAQ,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;QAC5F,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,cAAc,CAAC,EAAE,iBAAiB,EAAE,KAAK,EAAE,CAAC,CAAC;QAEnE,MAAM,MAAM,GAAG,GAAG,CAAC,gBAAgB,EAAE,CAAC;QACtC,IAAI,MAAM,EAAE;YACX,OAAO,GAAG,CAAC,IAAI,CAAC;gBACf,MAAM;aACN,CAAC,CAAC;SACH;QAED,MAAM,MAAM,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC;QAC5C,MAAM,SAAS,GAAG,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC;QAEpC,cAAI,CAAC,OAAO,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AC,GAAG,CAAC,YAAY,GAAG,EAAE;iBAClD,CAAC,CAAC;YACJ,CAAC,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;IACJ,CAAC;CACD;AAED,kBAAe,KAAK,CAAC"} \ No newline at end of file diff --git a/dist/controllers/Api/Auth/RefreshToken.js b/dist/controllers/Api/Auth/RefreshToken.js deleted file mode 100644 index 2b096ef..0000000 --- a/dist/controllers/Api/Auth/RefreshToken.js +++ /dev/null @@ -1,69 +0,0 @@ -"use strict"; -/** - * Refresh JWToken - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const jwt = require("jsonwebtoken"); -const User_1 = require("../../../models/User"); -class RefreshToken { - static getToken(req) { - if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { - return req.headers.authorization.split(' ')[1]; - } - else if (req.query && req.query.token) { - return req.query.token; - } - return ''; - } - static perform(req, res) { - const _token = RefreshToken.getToken(req); - if (_token === '') { - return res.json({ - error: ['Invalid Token!'] - }); - } - const decode = jwt.decode(_token, res.locals.app.appSecret, { expiresIn: res.locals.app.jwtExpiresIn }); - User_1.default.findOne({ email: decode.email }, (err, user) => { - if (err) { - return res.json({ - error: err - }); - } - if (!user) { - return res.json({ - error: ['User not found!'] - }); - } - if (!user.password) { - return res.json({ - error: ['Please login using your social creds'] - }); - } - user.comparePassword(decode.password, (err, isMatch) => { - if (err) { - return res.json({ - error: err - }); - } - if (!isMatch) { - return res.json({ - error: ['Password does not match!'] - }); - } - const token = jwt.sign({ email: decode.email, password: decode.password }, res.locals.app.appSecret, { expiresIn: res.locals.app.jwtExpiresIn * 60 }); - // Hide protected columns - user.tokens = undefined; - user.password = undefined; - return res.json({ - user, - token, - token_expires_in: res.locals.app.jwtExpiresIn * 60 - }); - }); - }); - } -} -exports.default = RefreshToken; -//# sourceMappingURL=RefreshToken.js.map \ No newline at end of file diff --git a/dist/controllers/Api/Auth/RefreshToken.js.map b/dist/controllers/Api/Auth/RefreshToken.js.map deleted file mode 100644 index 35fc9cb..0000000 --- a/dist/controllers/Api/Auth/RefreshToken.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"RefreshToken.js","sourceRoot":"","sources":["../../../../src/controllers/Api/Auth/RefreshToken.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,oCAAoC;AAEpC,+CAAwC;AAExC,MAAM,YAAY;IACV,MAAM,CAAC,QAAQ,CAAE,GAAG;QAC1B,IAAI,GAAG,CAAC,OAAO,CAAC,aAAa,IAAI,GAAG,CAAC,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,QAAQ,EAAE;YACtF,OAAO,GAAG,CAAC,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;SAC/C;aAAM,IAAI,GAAG,CAAC,KAAK,IAAI,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE;YACxC,OAAO,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC;SACvB;QAED,OAAO,EAAE,CAAC;IACX,CAAC;IAEM,MAAM,CAAC,OAAO,CAAE,GAAG,EAAE,GAAG;QAC9B,MAAM,MAAM,GAAG,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;QAC1C,IAAI,MAAM,KAAK,EAAE,EAAE;YAClB,OAAO,GAAG,CAAC,IAAI,CAAC;gBACf,KAAK,EAAE,CAAC,gBAAgB,CAAC;aACzB,CAAC,CAAC;SACH;QAED,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,CACxB,MAAM,EACN,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,SAAS,EACxB,EAAE,SAAS,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,YAAY,EAAE,CAC1C,CAAC;QAEF,cAAI,CAAC,OAAO,CAAC,EAAC,KAAK,EAAE,MAAM,CAAC,KAAK,EAAC,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,E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AClD,CAAC,CAAC;YACJ,CAAC,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;IACJ,CAAC;CACD;AAED,kBAAe,YAAY,CAAC"} \ No newline at end of file diff --git a/dist/controllers/Api/Auth/Register.js b/dist/controllers/Api/Auth/Register.js deleted file mode 100644 index 1c45aba..0000000 --- a/dist/controllers/Api/Auth/Register.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; -/** - * Define the Register API logic - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const User_1 = require("../../../models/User"); -class Register { - static perform(req, res) { - req.assert('email', 'E-mail cannot be blank').notEmpty(); - req.assert('email', 'E-mail is not valid').isEmail(); - req.assert('password', 'Password cannot be blank').notEmpty(); - req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }); - req.assert('confirmPassword', 'Confirmation Password cannot be blank').notEmpty(); - req.assert('confirmPassword', 'Password & Confirmation password does not match').equals(req.body.password); - req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }); - const errors = req.validationErrors(); - if (errors) { - return res.json({ - error: errors - }); - } - const _email = req.body.email; - const _password = req.body.password; - const user = new User_1.default({ - email: _email, - password: _password - }); - User_1.default.findOne({ email: _email }, (err, existingUser) => { - if (err) { - return res.json({ - error: err - }); - } - if (existingUser) { - return res.json({ - error: ['Account with the e-mail address already exists.'] - }); - } - user.save((err) => { - if (err) { - return res.json({ - error: err - }); - } - return res.json({ - message: ['You have been successfully registered with us!'] - }); - }); - }); - } -} -exports.default = Register; -//# sourceMappingURL=Register.js.map \ No newline at end of file diff --git a/dist/controllers/Api/Auth/Register.js.map b/dist/controllers/Api/Auth/Register.js.map deleted file mode 100644 index 28c0ebb..0000000 --- a/dist/controllers/Api/Auth/Register.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Register.js","sourceRoot":"","sources":["../../../../src/controllers/Api/Auth/Register.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,+CAAwC;AAExC,MAA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rD,IAAI,GAAG,EAAE;gBACR,OAAO,GAAG,CAAC,IAAI,CAAC;oBACf,KAAK,EAAE,GAAG;iBACV,CAAC,CAAC;aACH;YAED,IAAI,YAAY,EAAE;gBACjB,OAAO,GAAG,CAAC,IAAI,CAAC;oBACf,KAAK,EAAE,CAAC,iDAAiD,CAAC;iBAC1D,CAAC,CAAC;aACH;YAED,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE;gBACjB,IAAI,GAAG,EAAE;oBACR,OAAO,GAAG,CAAC,IAAI,CAAC;wBACf,KAAK,EAAE,GAAG;qBACV,CAAC,CAAC;iBACH;gBAED,OAAO,GAAG,CAAC,IAAI,CAAC;oBACf,OAAO,EAAE,CAAC,gDAAgD,CAAC;iBAC3D,CAAC,CAAC;YACJ,CAAC,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;IACJ,CAAC;CACD;AAED,kBAAe,QAAQ,CAAC"} \ No newline at end of file diff --git a/dist/controllers/Api/Home.js b/dist/controllers/Api/Home.js deleted file mode 100644 index 087fedd..0000000 --- a/dist/controllers/Api/Home.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; -/** - * Define the API base url - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const Locals_1 = require("../../providers/Locals"); -class Home { - static index(req, res, next) { - return res.json({ - message: Locals_1.default.config().name - }); - } -} -exports.default = Home; -//# sourceMappingURL=Home.js.map \ No newline at end of file diff --git a/dist/controllers/Api/Home.js.map b/dist/controllers/Api/Home.js.map deleted file mode 100644 index 6433952..0000000 --- a/dist/controllers/Api/Home.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Home.js","sourceRoot":"","sources":["../../../src/controllers/Api/Home.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,mDAA4C;AAE5C,MAAM,IAAI;IACF,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI;QACjC,OAAO,GAAG,CAAC,IAAI,CAAC;YACf,OAAO,EAAE,gBAAM,CAAC,MAAM,EAAE,CAAC,IAAI;SAC7B,CAAC,CAAC;IACJ,CAAC;CACD;AAED,kBAAe,IAAI,CAAC"} \ No newline at end of file diff --git a/dist/controllers/Home.js b/dist/controllers/Home.js deleted file mode 100644 index b62ebb5..0000000 --- a/dist/controllers/Home.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; -/** - * Handler for Home - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -class Home { - static index(req, res, next) { - return res.render('pages/home', { - title: 'Home' - }); - } -} -exports.default = Home; -//# sourceMappingURL=Home.js.map \ No newline at end of file diff --git a/dist/controllers/Home.js.map b/dist/controllers/Home.js.map deleted file mode 100644 index 337ac30..0000000 --- a/dist/controllers/Home.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Home.js","sourceRoot":"","sources":["../../src/controllers/Home.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAIH,MAAM,IAAI;IACF,MAAM,CAAC,KAAK,CAAE,GAAa,EAAE,GAAc,EAAE,IAAI;QACvD,OAAO,GAAG,CAAC,MAAM,CAAC,YAAY,EAAE;YAC/B,KAAK,EAAE,MAAM;SACb,CAAC,CAAC;IACJ,CAAC;CACD;AAED,kBAAe,IAAI,CAAC"} \ No newline at end of file diff --git a/dist/controllers/auth/Login.js b/dist/controllers/auth/Login.js deleted file mode 100644 index b0a9eb1..0000000 --- a/dist/controllers/auth/Login.js +++ /dev/null @@ -1,48 +0,0 @@ -"use strict"; -/** - * Handles your login routes - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const passport = require("passport"); -const Log_1 = require("../../middlewares/Log"); -class Login { - static show(req, res) { - return res.render('pages/login', { - title: 'LogIn' - }); - } - static perform(req, res, next) { - req.assert('email', 'E-mail cannot be blank').notEmpty(); - req.assert('email', 'E-mail is not valid').isEmail(); - req.assert('password', 'Password cannot be blank').notEmpty(); - req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }); - req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }); - const errors = req.validationErrors(); - if (errors) { - req.flash('errors', errors); - return res.redirect('/login'); - } - Log_1.default.info('Here in the login controller #1!'); - passport.authenticate('local', (err, user, info) => { - Log_1.default.info('Here in the login controller #2!'); - if (err) { - return next(err); - } - if (!user) { - req.flash('errors', info); - return res.redirect('/login'); - } - req.logIn(user, (err) => { - if (err) { - return next(err); - } - req.flash('success', { msg: 'You are successfully logged in now!' }); - res.redirect('/account'); - }); - })(req, res, next); - } -} -exports.default = Login; -//# sourceMappingURL=Login.js.map \ No newline at end of file diff --git a/dist/controllers/auth/Login.js.map b/dist/controllers/auth/Login.js.map deleted file mode 100644 index b6ddb8d..0000000 --- a/dist/controllers/auth/Login.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Login.js","sourceRoot":"","sources":["../../../src/controllers/Auth/Login.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,qCAAqC;AAKrC,+CAAwC;AAExC,MAAM,KAAK;IACH,MAAM,CAAC,IAAI,CAAE,GAAa,EAAE,GAAc;QAChD,OAAO,GAAG,CAAC,MAAM,CAAC,aAAa,EAAE;YAChC,KAAK,EAAE,OAAO;SACd,CAAC,CAAC;IACJ,CAAC;IAEM,MAAM,CAAC,OAAO,CAAE,GAAa,EAAE,GAAc,EAAE,IAAW;QAChE,GAAG,CAAC,MAAM,CAAC,OAAO,EAAE,wBAAwB,CAAC,CAAC,QAAQ,EAAE,CAAC;QACzD,GAAG,CAAC,MAAM,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAC,OAAO,EAAE,CAAC;QACrD,GAAG,CAAC,MAAM,CAAC,UAAU,EAAE,0BAA0B,CAAC,CAAC,QAAQ,EAAE,CAAC;QAC9D,GAAG,CAAC,MAAM,CAAC,UAAU,EAAE,8CAA8C,CAAC,CAAC,QAAQ,CAAC,EAAE,GAAG,EAAE,CAAC,EAA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6e0477c..0000000 --- a/dist/controllers/auth/Logout.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/** - * Handles the logout request - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -class Logout { - static perform(req, res) { - req.logout(); - req.session.destroy((err) => { - if (err) { - console.log('Error : Failed to destroy the session during logout.', err); - } - req.user = null; - return res.redirect('/'); - }); - } -} -exports.default = Logout; -//# sourceMappingURL=Logout.js.map \ No newline at end of file diff --git a/dist/controllers/auth/Logout.js.map b/dist/controllers/auth/Logout.js.map deleted file mode 100644 index ef16b54..0000000 --- a/dist/controllers/auth/Logout.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Logout.js","sourceRoot":"","sources":["../../../src/controllers/Auth/Logout.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAIH,MAAM,MAAM;IACJ,MAAM,CAAC,OAAO,CAAE,GAAa,EAAE,GAAc;QACnD,GAAG,CAAC,MAAM,EAAE,CAAC;QACb,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;YAC3B,IAAI,GAAG,EAAE;gBACR,OAAO,CAAC,GAAG,CAAC,sDAAsD,EAAE,GAAG,CAAC,CAAC;aACzE;YAED,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC;YAChB,OAAO,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;QAC1B,CAAC,CAAC,CAAC;IACJ,CAAC;CACD;AAED,kBAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/dist/controllers/auth/Register.js b/dist/controllers/auth/Register.js deleted file mode 100644 index 153662b..0000000 --- a/dist/controllers/auth/Register.js +++ /dev/null @@ -1,56 +0,0 @@ -"use strict"; -/** - * Handles your register route - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const User_1 = require("../../models/User"); -class Register { - static show(req, res) { - return res.render('pages/signup', { - title: 'SignUp' - }); - } - static perform(req, res, next) { - req.assert('email', 'E-mail cannot be blank').notEmpty(); - req.assert('email', 'E-mail is not valid').isEmail(); - req.assert('password', 'Password cannot be blank').notEmpty(); - req.assert('password', 'Password length must be atleast 8 characters').isLength({ min: 8 }); - req.assert('confirmPassword', 'Confirmation Password cannot be blank').notEmpty(); - req.assert('confirmPassword', 'Password & Confirmation password does not match').equals(req.body.password); - req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }); - const errors = req.validationErrors(); - if (errors) { - req.flash('errors', errors); - return res.redirect('/signup'); - } - const user = new User_1.default({ - email: req.body.email, - password: req.body.password - }); - User_1.default.findOne({ email: req.body.email }, (err, existingUser) => { - if (err) { - return next(err); - } - if (existingUser) { - req.flash('errors', { msg: 'Account with the e-mail address already exists.' }); - return res.redirect('/signup'); - } - user.save((err) => { - if (err) { - return next(err); - } - req.logIn(user, (err) => { - if (err) { - return next(err); - } - req.flash('success', { msg: 'You are successfully logged in now!' }); - res.redirect('/signup'); - }); - }); - }); - } -} -exports.default = Register; -//# sourceMappingURL=Register.js.map \ No newline at end of file diff --git a/dist/controllers/auth/Register.js.map b/dist/controllers/auth/Register.js.map deleted file mode 100644 index b9a979e..0000000 --- a/dist/controllers/auth/Register.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Register.js","sourceRoot":"","sources":["../../../src/controllers/Auth/Register.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,4CAAqC;AAGrC,MAAM,QAAQ;IACN,MAAM,CAAC,IAAI,CAAE,GAAa,EAAE,GAAc;QAChD,OAAO,GAAG,CAAC,MAAM,CAAC,cAAc,EAAE;YACjC,KAAK,EAAE,QAAQ;SACf,CAAC,CAAC;IACJ,CAAC;IAEM,MAAM,CAAC,OAAO,CAAE,GAAa,EAAE,GAAc,EAAE,IAAW;QAChE,GAAG,CAAC,MAAM,CAAC,OAAO,EAAE,wBAAwB,CAAC,CAAC,QAAQ,EAAE,CAAC;QACzD,GAAG,CAAC,MAAM,CAAC,OAAO,EAAE,qBA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OAAO,GAAG,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;aAC/B;YAED,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE;gBACjB,IAAI,GAAG,EAAE;oBACR,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;iBACjB;gBAED,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE;oBACvB,IAAI,GAAG,EAAE;wBACR,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;qBACjB;oBACD,GAAG,CAAC,KAAK,CAAC,SAAS,EAAE,EAAE,GAAG,EAAE,qCAAqC,EAAE,CAAC,CAAC;oBACrE,GAAG,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;gBACzB,CAAC,CAAC,CAAC;YACJ,CAAC,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;IACJ,CAAC;CACD;AAED,kBAAe,QAAQ,CAAC"} \ No newline at end of file diff --git a/dist/controllers/auth/Social.js b/dist/controllers/auth/Social.js deleted file mode 100644 index 6aa65ae..0000000 --- a/dist/controllers/auth/Social.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict"; -/** - * Handle all your social auth routesß - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -class Social { - static googleCallback(req, res) { - return res.redirect('/account'); - } -} -exports.default = Social; -//# sourceMappingURL=Social.js.map \ No newline at end of file diff --git a/dist/controllers/auth/Social.js.map b/dist/controllers/auth/Social.js.map deleted file mode 100644 index 3ce3f45..0000000 --- a/dist/controllers/auth/Social.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Social.js","sourceRoot":"","sources":["../../../src/controllers/Auth/Social.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,MAAM,MAAM;IACJ,MAAM,CAAC,cAAc,CAAC,GAAG,EAAE,GAAG;QACpC,OAAO,GAAG,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;IACjC,CAAC;CACD;AAED,kBAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/dist/exception/Handler.js b/dist/exception/Handler.js deleted file mode 100644 index 7547cf5..0000000 --- a/dist/exception/Handler.js +++ /dev/null @@ -1,79 +0,0 @@ -"use strict"; -/** - * Define the error & exception handlers - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const Log_1 = require("../middlewares/Log"); -const Locals_1 = require("../providers/Locals"); -class Handler { - /** - * Handles all the not found routes - */ - static notFoundHandler(_express) { - const apiPrefix = Locals_1.default.config().apiPrefix; - _express.use('*', (req, res) => { - const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; - Log_1.default.error(`Path '${req.originalUrl}' not found [IP: '${ip}']!`); - if (req.xhr || req.originalUrl.includes(`/${apiPrefix}/`)) { - return res.json({ - error: 'Page Not Found' - }); - } - else { - res.status(404); - return res.render('pages/error', { - title: 'Page Not Found', - error: [] - }); - } - }); - return _express; - } - /** - * Handles your api/web routes errors/exception - */ - static clientErrorHandler(err, req, res, next) { - Log_1.default.error(err.stack); - if (req.xhr) { - return res.status(500).send({ error: 'Something went wrong!' }); - } - else { - return next(err); - } - } - /** - * Show undermaintenance page incase of errors - */ - static errorHandler(err, req, res, next) { - Log_1.default.error(err.stack); - res.status(500); - const apiPrefix = Locals_1.default.config().apiPrefix; - if (req.originalUrl.includes(`/${apiPrefix}/`)) { - if (err.name && err.name === 'UnauthorizedError') { - const innerMessage = err.inner && err.inner.message ? err.inner.message : undefined; - return res.json({ - error: [ - 'Invalid Token!', - innerMessage - ] - }); - } - return res.json({ - error: err - }); - } - return res.render('pages/error', { error: err.stack, title: 'Under Maintenance' }); - } - /** - * Register your error / exception monitoring - * tools right here ie. before "next(err)"! - */ - static logErrors(err, req, res, next) { - Log_1.default.error(err.stack); - return next(err); - } -} -exports.default = Handler; -//# sourceMappingURL=Handler.js.map \ No newline at end of file diff --git a/dist/exception/Handler.js.map b/dist/exception/Handler.js.map deleted file mode 100644 index 667ffb7..0000000 --- a/dist/exception/Handler.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Handler.js","sourceRoot":"","sources":["../../src/exception/Handler.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,4CAAqC;AACrC,gDAAyC;AAEzC,MAAM,OAAO;IACZ;;OAEG;IACI,MAAM,CAAC,eAAe,CAAC,QAAQ;QACrC,MAAM,SAAS,GAAG,gBAAM,CAAC,MAAM,EAAE,CAAC,SAAS,CAAC;QAE5C,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;YAC9B,MAAM,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC,iBAAiB,CAAC,IAAI,GAAG,CAAC,UAAU,CAAC,aAAa,CAAC;YAE1E,aAAG,CAAC,KAAK,CAAC,SAAS,GAAG,CAAC,WAAW,qBAAqB,EAAE,KAAK,CAAC,CAAC;YAChE,IAAI,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,WAAW,CAAC,QAAQ,CAAC,IAAI,SAAS,GAAG,CAAC,EAAE;gBAC1D,OAAO,GAAG,CAAC,IAAI,CAAC;oBACf,KAAK,EAAE,gBAAgB;iBACvB,CAAC,CAAC;aACH;iBAAM;gBACN,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBAChB,OAAO,GAAG,CAAC,MAAM,CAAC,aAAa,EAAE;oBAChC,KAAK,EAAE,gBAAgB;oBACvB,KAAK,EAAE,EAAE;iBACT,CAAC,CAAC;aACH;QACF,CAAC,CAAC,CAAC;QAEH,OAAO,QAAQ,CAAC;IACjB,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,kBAAkB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI;QACnD,aAAG,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAErB,IAAI,GAAG,CAAC,GAAG,EAAE;YACZ,OAAO,GAAG,CAAC,MAAM,CAAC,GAAG,C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C;IAClB,CAAC;CACD;AAED,kBAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/dist/exception/NativeEvent.js b/dist/exception/NativeEvent.js deleted file mode 100644 index e96bee2..0000000 --- a/dist/exception/NativeEvent.js +++ /dev/null @@ -1,32 +0,0 @@ -"use strict"; -/** - * Catch all your node env's native event - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const Log_1 = require("../middlewares/Log"); -class NativeEvent { - cluster(_cluster) { - // Catch cluster listening event... - _cluster.on('listening', (worker) => Log_1.default.info(`Server :: Cluster with ProcessID '${worker.process.pid}' Connected!`)); - // Catch cluster once it is back online event... - _cluster.on('online', (worker) => Log_1.default.info(`Server :: Cluster with ProcessID '${worker.process.pid}' has responded after it was forked! `)); - // Catch cluster disconnect event... - _cluster.on('disconnect', (worker) => Log_1.default.info(`Server :: Cluster with ProcessID '${worker.process.pid}' Disconnected!`)); - // Catch cluster exit event... - _cluster.on('exit', (worker, code, signal) => { - Log_1.default.info(`Server :: Cluster with ProcessID '${worker.process.pid}' is Dead with Code '${code}, and signal: '${signal}'`); - // Ensuring a new cluster will start if an old one dies - _cluster.fork(); - }); - } - process() { - // Catch the Process's uncaught-exception - process.on('uncaughtException', (exception) => Log_1.default.error(exception.stack)); - // Catch the Process's warning event - process.on('warning', (warning) => Log_1.default.warn(warning.stack)); - } -} -exports.default = new NativeEvent; -//# sourceMappingURL=NativeEvent.js.map \ No newline at end of file diff --git a/dist/exception/NativeEvent.js.map b/dist/exception/NativeEvent.js.map deleted file mode 100644 index 097bb40..0000000 --- a/dist/exception/NativeEvent.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"NativeEvent.js","sourceRoot":"","sources":["../../src/exception/NativeEvent.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,4CAAqC;AAErC,MAAM,WAAW;IACT,OAAO,CAAE,QAAQ;QACvB,mCAAmC;QACnC,QAAQ,CAAC,EAAE,CAAC,WAAW,EAAE,CA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0 @@ -"use strict"; -/** - * Bootstrap your App - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const os = require("os"); -const cluster = require("cluster"); -const App_1 = require("./providers/App"); -const NativeEvent_1 = require("./exception/NativeEvent"); -if (cluster.isMaster) { - /** - * Catches the process events - */ - NativeEvent_1.default.process(); - /** - * Clear the console before the app runs - */ - App_1.default.clearConsole(); - /** - * Load Configuration - */ - App_1.default.loadConfiguration(); - /** - * Find the number of available CPUS - */ - const CPUS = os.cpus(); - /** - * Fork the process, the number of times we have CPUs available - */ - CPUS.forEach(() => cluster.fork()); - /** - * Catches the cluster events - */ - NativeEvent_1.default.cluster(cluster); - /** - * Loads the Queue Monitor iff enabled - */ - App_1.default.loadQueue(); - /** - * Run the Worker every minute - * Note: we normally start worker after - * the entire app is loaded - */ - setTimeout(() => App_1.default.loadWorker(), 1000 * 60); -} -else { - /** - * Run the Database pool - */ - App_1.default.loadDatabase(); - /** - * Run the Server on Clusters - */ - App_1.default.loadServer(); -} -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/index.js.map b/dist/index.js.map deleted file mode 100644 index 1f207bb..0000000 --- a/dist/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,yBAAyB;AACzB,mCAAmC;AAEnC,yCAAkC;AAClC,yDAAkD;AAElD,IAAI,OAAO,CAAC,QAAQ,EAAE;IACrB;;OAEG;IACH,qBAAW,CAAC,OAAO,EAAE,CAAC;IAEtB;;OAEG;IACH,aAAG,CAAC,YAAY,EAAE,CAAC;IAEnB;;OAEG;IACH,aAAG,CAAC,iBAAiB,EAAE,CAAC;IAExB;;OAEG;IACH,MAAM,IAAI,GAAQ,EAAE,CAAC,IAAI,EAAE,CAAC;IAE5B;;OAEG;IACH,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;IAEnC;;OAEG;IACH,qBAAW,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAE7B;;OAEG;IACH,aAAG,CAAC,SAAS,EAAE,CAAC;IAEhB;;;;OAIG;IACH,UAAU,CAAC,GAAG,EAAE,CAAC,aAAG,CAAC,UAAU,EAAE,EAAE,IAAI,GAAG,EAAE,CAAC,CAAC;CAE9C;KAAM;IAEN;;OAEG;IACH,aAAG,CAAC,YAAY,EAAE,CAAC;IAEnB;;OAEG;IACH,aAAG,CAAC,UAAU,EAAE,CAAC;CACjB"} \ No newline at end of file diff --git a/dist/interfaces/models/user.js b/dist/interfaces/models/user.js deleted file mode 100644 index 589b96d..0000000 --- a/dist/interfaces/models/user.js +++ /dev/null @@ -1,8 +0,0 @@ -"use strict"; -/** - * Define interface for User Model - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -//# sourceMappingURL=user.js.map \ No newline at end of file diff --git a/dist/interfaces/models/user.js.map b/dist/interfaces/models/user.js.map deleted file mode 100644 index 6969cee..0000000 --- a/dist/interfaces/models/user.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"user.js","sourceRoot":"","sources":["../../../src/interfaces/models/user.ts"],"names":[],"mappings":";AAAA;;;;GAIG"} \ No newline at end of file diff --git a/dist/interfaces/vendors/INext.js b/dist/interfaces/vendors/INext.js deleted file mode 100644 index ac7e275..0000000 --- a/dist/interfaces/vendors/INext.js +++ /dev/null @@ -1,8 +0,0 @@ -"use strict"; -/** - * Defines Custom method types over Express's NextFunction - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -//# sourceMappingURL=INext.js.map \ No newline at end of file diff --git a/dist/interfaces/vendors/INext.js.map b/dist/interfaces/vendors/INext.js.map deleted file mode 100644 index 920358a..0000000 --- a/dist/interfaces/vendors/INext.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"INext.js","sourceRoot":"","sources":["../../../src/interfaces/vendors/INext.ts"],"names":[],"mappings":";AAAA;;;;GAIG"} \ No newline at end of file diff --git a/dist/interfaces/vendors/IRequest.js b/dist/interfaces/vendors/IRequest.js deleted file mode 100644 index 18e0fba..0000000 --- a/dist/interfaces/vendors/IRequest.js +++ /dev/null @@ -1,8 +0,0 @@ -"use strict"; -/** - * Defines Custom method types over Express's Request - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -//# sourceMappingURL=IRequest.js.map \ No newline at end of file diff --git a/dist/interfaces/vendors/IRequest.js.map b/dist/interfaces/vendors/IRequest.js.map deleted file mode 100644 index 7802370..0000000 --- a/dist/interfaces/vendors/IRequest.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"IRequest.js","sourceRoot":"","sources":["../../../src/interfaces/vendors/IRequest.ts"],"names":[],"mappings":";AAAA;;;;GAIG"} \ No newline at end of file diff --git a/dist/interfaces/vendors/IResponse.js b/dist/interfaces/vendors/IResponse.js deleted file mode 100644 index bb09c34..0000000 --- a/dist/interfaces/vendors/IResponse.js +++ /dev/null @@ -1,8 +0,0 @@ -"use strict"; -/** - * Defines Custom method types over Express's Response - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -//# sourceMappingURL=IResponse.js.map \ No newline at end of file diff --git a/dist/interfaces/vendors/IResponse.js.map b/dist/interfaces/vendors/IResponse.js.map deleted file mode 100644 index eeaee3c..0000000 --- a/dist/interfaces/vendors/IResponse.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"IResponse.js","sourceRoot":"","sources":["../../../src/interfaces/vendors/IResponse.ts"],"names":[],"mappings":";AAAA;;;;GAIG"} \ No newline at end of file diff --git a/dist/interfaces/vendors/index.js b/dist/interfaces/vendors/index.js deleted file mode 100644 index fbf198b..0000000 --- a/dist/interfaces/vendors/index.js +++ /dev/null @@ -1,8 +0,0 @@ -"use strict"; -/** - * Contains all your vendors' types definition - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/interfaces/vendors/index.js.map b/dist/interfaces/vendors/index.js.map deleted file mode 100644 index 8eac15f..0000000 --- a/dist/interfaces/vendors/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/interfaces/vendors/index.ts"],"names":[],"mappings":";AAAA;;;;GAIG"} \ No newline at end of file diff --git a/dist/middlewares/CORS.js b/dist/middlewares/CORS.js deleted file mode 100644 index 95fde92..0000000 --- a/dist/middlewares/CORS.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -/** - * Enables the CORS - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const cors = require("cors"); -const Log_1 = require("./Log"); -const Locals_1 = require("../providers/Locals"); -class CORS { - mount(_express) { - Log_1.default.info('Booting the \'CORS\' middleware...'); - const options = { - origin: Locals_1.default.config().url, - optionsSuccessStatus: 200 // Some legacy browsers choke on 204 - }; - _express.use(cors(options)); - return _express; - } -} -exports.default = new CORS; -//# sourceMappingURL=CORS.js.map \ No newline at end of file diff --git a/dist/middlewares/CORS.js.map b/dist/middlewares/CORS.js.map deleted file mode 100644 index 24f3731..0000000 --- a/dist/middlewares/CORS.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"CORS.js","sourceRoot":"","sources":["../../src/middlewares/CORS.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,6BAA6B;AAG7B,+BAAwB;AACxB,gDAAyC;AAEzC,MAAM,IAAI;IACF,KAAK,CAAC,QAAqB;QACjC,aAAG,CAAC,IAAI,CAAC,oCAAoC,CAAC,CAAC;QAE/C,MAAM,OAAO,GAAG;YACf,MAAM,EAAE,gBAAM,CAAC,MAAM,EAAE,CAAC,GAAG;YAC3B,oBAAoB,EAAE,GAAG,CAAE,oCAAoC;SAC/D,CAAC;QAEF,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;QAE5B,OAAO,QAAQ,CAAC;IACjB,CAAC;CACD;AAED,kBAAe,IAAI,IAAI,CAAC"} \ No newline at end of file diff --git a/dist/middlewares/CsrfToken.js b/dist/middlewares/CsrfToken.js deleted file mode 100644 index 7a245f2..0000000 --- a/dist/middlewares/CsrfToken.js +++ /dev/null @@ -1,56 +0,0 @@ -"use strict"; -/** - * Enables CSRF Token authorizaton for - * your routes - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const lusca = require("lusca"); -const Log_1 = require("./Log"); -const Locals_1 = require("../providers/Locals"); -class CsrfToken { - static mount(_express) { - Log_1.default.info('Booting the \'CsrfToken\' middleware...'); - _express.set('trust proxy', 1); - // Interpolate the user variable into your pug files - _express.use((req, res, next) => { - res.locals.user = req.user; - res.locals.app = Locals_1.default.config(); - next(); - }); - // Check for CSRF token iff the original url - // does not contains the api substring - _express.use((req, res, next) => { - const apiPrefix = Locals_1.default.config().apiPrefix; - if (req.originalUrl.includes(`/${apiPrefix}/`)) { - next(); - } - else { - lusca.csrf()(req, res, next); - } - }); - // Enables x-frame-options headers - _express.use(lusca.xframe('SAMEORIGIN')); - // Enables xss-protection headers - _express.use(lusca.xssProtection(true)); - _express.use((req, res, next) => { - // After successful login, redirect back to the intended page - if (!req.user - && req.path !== '/login' - && req.path !== '/signup' - && !req.path.match(/^\/auth/) - && !req.path.match(/\./)) { - req.session.returnTo = req.originalUrl; - } - else if (req.user - && (req.path === '/account' || req.path.match(/^\/api/))) { - req.session.returnTo = req.originalUrl; - } - next(); - }); - return _express; - } -} -exports.default = CsrfToken; -//# sourceMappingURL=CsrfToken.js.map \ No newline at end of file diff --git a/dist/middlewares/CsrfToken.js.map b/dist/middlewares/CsrfToken.js.map deleted file mode 100644 index d1f19f0..0000000 --- a/dist/middlewares/CsrfToken.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"CsrfToken.js","sourceRoot":"","sources":["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6DAA6D;YAC7D,IAAI,CAAC,GAAG,CAAC,IAAI;mBACT,GAAG,CAAC,IAAI,KAAK,QAAQ;mBACrB,GAAG,CAAC,IAAI,KAAK,SAAS;mBACtB,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC;mBAC1B,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE;gBAC1B,GAAG,CAAC,OAAO,CAAC,QAAQ,GAAG,GAAG,CAAC,WAAW,CAAC;aACvC;iBAAM,IAAI,GAAG,CAAC,IAAI;mBACd,CAAC,GAAG,CAAC,IAAI,KAAK,UAAU,IAAI,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,EAAE;gBAC3D,GAAG,CAAC,OAAO,CAAC,QAAQ,GAAG,GAAG,CAAC,WAAW,CAAC;aACvC;YACD,IAAI,EAAE,CAAC;QACR,CAAC,CAAC,CAAC;QAEH,OAAO,QAAQ,CAAC;IACjB,CAAC;CACD;AAED,kBAAe,SAAS,CAAC"} \ No newline at end of file diff --git a/dist/middlewares/Http.js b/dist/middlewares/Http.js deleted file mode 100644 index c0be075..0000000 --- a/dist/middlewares/Http.js +++ /dev/null @@ -1,66 +0,0 @@ -"use strict"; -/** - * Defines all the requisites in HTTP - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const cors = require("cors"); -const flash = require("express-flash"); -const compress = require("compression"); -const connect = require("connect-mongo"); -const bodyParser = require("body-parser"); -const session = require("express-session"); -const expressValidator = require("express-validator"); -const Log_1 = require("./Log"); -const Locals_1 = require("../providers/Locals"); -const Passport_1 = require("../providers/Passport"); -const MongoStore = connect(session); -class Http { - static mount(_express) { - Log_1.default.info('Booting the \'HTTP\' middleware...'); - // Enables the request body parser - _express.use(bodyParser.json({ - limit: Locals_1.default.config().maxUploadLimit - })); - _express.use(bodyParser.urlencoded({ - limit: Locals_1.default.config().maxUploadLimit, - parameterLimit: Locals_1.default.config().maxParameterLimit, - extended: false - })); - // Disable the x-powered-by header in response - _express.disable('x-powered-by'); - // Enables the request payload validator - _express.use(expressValidator()); - // Enables the request flash messages - _express.use(flash()); - /** - * Enables the session store - * - * Note: You can also add redis-store - * into the options object. - */ - const options = { - resave: true, - saveUninitialized: true, - secret: Locals_1.default.config().appSecret, - cookie: { - maxAge: 1209600000 // two weeks (in ms) - }, - store: new MongoStore({ - url: process.env.MONGOOSE_URL, - autoReconnect: true - }) - }; - _express.use(session(options)); - // Enables the CORS - _express.use(cors()); - // Enables the "gzip" / "deflate" compression for response - _express.use(compress()); - // Loads the passport configuration - _express = Passport_1.default.mountPackage(_express); - return _express; - } -} -exports.default = Http; -//# sourceMappingURL=Http.js.map \ No newline at end of file diff --git a/dist/middlewares/Http.js.map b/dist/middlewares/Http.js.map deleted file mode 100644 index f966c27..0000000 --- a/dist/middlewares/Http.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Http.js","sourceRoot":"","sources":["../../src/middlewares/Http.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,6BAA6B;AAE7B,uCAAuC;AACvC,wCAAwC;AACxC,yCAAyC;AACzC,0CAA0C;AAC1C,2CAA2C;AAC3C,sDAAsD;AAEtD,+BAAwB;AACxB,gDAAyC;AACzC,oDAA6C;AAE7C,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;AAEpC,MAAM,IAAI;IACF,MAAM,CAAC,KAAK,CAAC,QAAqB;QACxC,aAAG,CAAC,IAAI,CAAC,oCAAoC,CAAC,CAAC;QAE/C,kCAAkC;QAClC,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC;YAC5B,KAAK,EAAE,gBAAM,CAAC,MAAM,EAAE,CAAC,cAAc;SACrC,CAAC,CAAC,CAAC;QAEJ,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC,UAAU,CAAC;YAClC,KAAK,EAAE,gBAAM,CAAC,MAAM,EAAE,CAAC,cAAc;YACrC,cAAc,EAAE,gBAAM,CAAC,MAAM,EAAE,CAAC,iBAAiB;YACjD,QAAQ,EAAE,KAAK;SACf,CAAC,CAAC,CAAC;QAEJ,8CAA8C;QAC9C,QAAQ,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;QAEjC,wCAAwC;QACxC,QAAQ,CAAC,GAAG,CAAC,gBAAgB,EAAE,CAAC,CAAC;QAEjC,qCAAqC;QACrC,QAAQ,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC;QAEtB;;;;;WAKG;QACH,MAAM,OAAO,GAAG;YACf,MAAM,EAAE,IAAI;YACZ,iBAAiB,EAAE,IAAI;YACvB,MAAM,EAAE,gBAAM,CAAC,MAAM,EAAE,CAAC,SAAS;YACjC,MAAM,EAAE;gBACP,MAAM,EAAE,UAAU,CAAC,oBAAoB;aACvC;YACD,KAAK,EAAE,IAAI,UAAU,CAAC;gBACrB,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,YAAY;gBAC7B,aAAa,EAAE,IAAI;aACnB,CAAC;SACF,CAAC;QAEF,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC;QAE/B,mBAAmB;QACnB,QAAQ,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;QAErB,0DAA0D;QAC1D,QAAQ,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;QAEzB,mCAAmC;QACnC,QAAQ,GAAG,kBAAQ,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC;QAE3C,OAAO,QAAQ,CAAC;IACjB,CAAC;CACD;AAED,kBAAe,IAAI,CAAC"} \ No newline at end of file diff --git a/dist/middlewares/Kernel.js b/dist/middlewares/Kernel.js deleted file mode 100644 index ea2b0d9..0000000 --- a/dist/middlewares/Kernel.js +++ /dev/null @@ -1,36 +0,0 @@ -"use strict"; -/** - * Register your Express middlewares - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const CORS_1 = require("./CORS"); -const Http_1 = require("./Http"); -const Views_1 = require("./Views"); -const Statics_1 = require("./Statics"); -const CsrfToken_1 = require("./CsrfToken"); -const StatusMonitor_1 = require("./StatusMonitor"); -const Locals_1 = require("../providers/Locals"); -class Kernel { - static init(_express) { - // Check if CORS is enabled - if (Locals_1.default.config().isCORSEnabled) { - // Mount CORS middleware - _express = CORS_1.default.mount(_express); - } - // Mount basic express apis middleware - _express = Http_1.default.mount(_express); - // Mount csrf token verification middleware - _express = CsrfToken_1.default.mount(_express); - // Mount view engine middleware - _express = Views_1.default.mount(_express); - // Mount statics middleware - _express = Statics_1.default.mount(_express); - // Mount status monitor middleware - _express = StatusMonitor_1.default.mount(_express); - return _express; - } -} -exports.default = Kernel; -//# sourceMappingURL=Kernel.js.map \ No newline at end of file diff --git a/dist/middlewares/Kernel.js.map b/dist/middlewares/Kernel.js.map deleted file mode 100644 index 35f1f15..0000000 --- a/dist/middlewares/Kernel.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Kernel.js","sourceRoot":"","sources":["../../src/middlewares/Kernel.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAIH,iCAA0B;AAC1B,iCAA0B;AAC1B,mCAA4B;AAC5B,uCAAgC;AAChC,2CAAoC;AACpC,mDAA4C;AAE5C,gDAAyC;AAEzC,MAAM,MAAM;IACJ,MAAM,CAAC,IAAI,CAAE,QAAqB;QACxC,2BAA2B;QAC3B,IAAI,gBAAM,CAAC,MAAM,EAAE,CAAC,aAAa,EAAE;YAClC,wBAAwB;YACxB,QAAQ,GAAG,cAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;SAChC;QAED,sCAAsC;QACtC,QAAQ,GAAG,cAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAEhC,2CAA2C;QAC3C,QAAQ,GAAG,mBAAS,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAErC,+BAA+B;QAC/B,QAAQ,GAAG,eAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAEjC,2BAA2B;QAC3B,QAAQ,GAAG,iBAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAEnC,kCAAkC;QAClC,QAAQ,GAAG,uBAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAEzC,OAAO,QAAQ,CAAC;IACjB,CAAC;CACD;AAED,kBAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/dist/middlewares/Log.js b/dist/middlewares/Log.js deleted file mode 100644 index 3c16e1d..0000000 --- a/dist/middlewares/Log.js +++ /dev/null @@ -1,76 +0,0 @@ -"use strict"; -/** - * Creates & maintains the log - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const fs = require("fs"); -const path = require("path"); -class Log { - constructor() { - this.today = new Date(); - let _dateString = `${this.today.getFullYear()}-${(this.today.getMonth() + 1)}-${this.today.getDate()}`; - let _timeString = `${this.today.getHours()}:${this.today.getMinutes()}:${this.today.getSeconds()}`; - this.baseDir = path.join(__dirname, '../../.logs/'); - this.fileName = `${_dateString}.log`; - this.linePrefix = `[${_dateString} ${_timeString}]`; - } - // Adds INFO prefix string to the log string - info(_string) { - this.addLog('INFO', _string); - } - // Adds WARN prefix string to the log string - warn(_string) { - this.addLog('WARN', _string); - } - // Adds ERROR prefix string to the log string - error(_string) { - // Line break and show the first line - console.log('\x1b[31m%s\x1b[0m', '[ERROR] :: ' + _string.split(/r?\n/)[0]); - this.addLog('ERROR', _string); - } - // Adds the custom prefix string to the log string - custom(_filename, _string) { - this.addLog(_filename, _string); - } - /** - * Creates the file if does not exist, and - * append the log kind & string into the file. - */ - addLog(_kind, _string) { - const _that = this; - _kind = _kind.toUpperCase(); - fs.open(`${_that.baseDir}${_that.fileName}`, 'a', (_err, _fileDescriptor) => { - if (!_err && _fileDescriptor) { - // Append to file and close it - fs.appendFile(_fileDescriptor, `${_that.linePrefix} [${_kind}] ${_string}\n`, (_err) => { - if (!_err) { - fs.close(_fileDescriptor, (_err) => { - if (!_err) { - return true; - } - else { - return console.log('\x1b[31m%s\x1b[0m', 'Error closing log file that was being appended'); - } - }); - } - else { - return console.log('\x1b[31m%s\x1b[0m', 'Error appending to the log file'); - } - }); - } - else { - return console.log('\x1b[31m%s\x1b[0m', 'Error cloudn\'t open the log file for appending'); - } - }); - } - /** - * Deletes the log files older than 'X' days - * - * Note: 'X' is defined in .env file - */ - clean() { - // - } -} -exports.default = new Log; -//# sourceMappingURL=Log.js.map \ No newline at end of file diff --git a/dist/middlewares/Log.js.map b/dist/middlewares/Log.js.map deleted file mode 100644 index 21236d5..0000000 --- a/dist/middlewares/Log.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Log.js","sourceRoot":"","sources":["../../src/middlewares/Log.ts"],"names":[],"mappings":";AAAA;;GAEG;;AAEH,yBAAyB;AACzB,6BAA6B;AAE7B,MAAM,GAAG;IAOR;QAFO,UAAK,GAAS,IAAI,IAAI,EAAE,CAAC;QAG/B,IAAI,WAAW,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,CAAC;QACvG,IAAI,WAAW,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,UAAU,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,UAAU,EAAE,EAAE,CAAC;QAEnG,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,cAAc,CAAC,CAAC;QAEpD,IAAI,CAAC,QAAQ,GAAG,GAAG,WAAW,MAAM,CAAC;QACrC,IAAI,CAAC,UAAU,GAAG,IAAI,WAAW,IAAI,WAAW,GAAG,CAAC;IACrD,CAAC;IAED,4CAA4C;IACrC,IAAI,CAAE,OAAe;QAC3B,IAAI,CAAC,M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AC,CAAC;6BAC1F;wBACF,CAAC,CAAC,CAAC;qBACH;yBAAM;wBACN,OAAO,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,iCAAiC,CAAC,CAAC;qBAC3E;gBACF,CAAC,CAAC,CAAC;aACH;iBAAM;gBACN,OAAO,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,iDAAiD,CAAC,CAAC;aAC3F;QACF,CAAC,CAAC,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACI,KAAK;QACX,EAAE;IACH,CAAC;CACD;AAED,kBAAe,IAAI,GAAG,CAAC"} \ No newline at end of file diff --git a/dist/middlewares/Statics.js b/dist/middlewares/Statics.js deleted file mode 100644 index 58488aa..0000000 --- a/dist/middlewares/Statics.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -/** - * Defines all the app-statics - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const path = require("path"); -const express = require("express"); -const Log_1 = require("./Log"); -class Statics { - static mount(_express) { - Log_1.default.info('Booting the \'Statics\' middleware...'); - // Loads Options - const options = { maxAge: 31557600000 }; - // Load Statics - _express.use('/public', express.static(path.join(__dirname, '../../public'), options)); - // Load NPM Statics - _express.use('/vendor', express.static(path.join(__dirname, '../../node_modules'), options)); - return _express; - } -} -exports.default = Statics; -//# sourceMappingURL=Statics.js.map \ No newline at end of file diff --git a/dist/middlewares/Statics.js.map b/dist/middlewares/Statics.js.map deleted file mode 100644 index 1a8daea..0000000 --- a/dist/middlewares/Statics.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Statics.js","sourceRoot":"","sources":["../../src/middlewares/Statics.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,6BAA6B;AAC7B,mCAAmC;AAEnC,+BAAwB;AAExB,MAAM,OAAO;IACL,MAAM,CAAC,KAAK,CAAC,QAA6B;QAChD,aAAG,CAAC,IAAI,CAAC,uCAAuC,CAAC,CAAC;QAElD,gBAAgB;QAChB,MAAM,OAAO,GAAG,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC;QAExC,eAAe;QACf,QAAQ,CAAC,GAAG,CAAC,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,cAAc,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;QAEvF,mBAAmB;QACnB,QAAQ,CAAC,GAAG,CAAC,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,oBAAoB,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;QAE7F,OAAO,QAAQ,CAAC;IACjB,CAAC;CACD;AAED,kBAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/dist/middlewares/StatusMonitor.js b/dist/middlewares/StatusMonitor.js deleted file mode 100644 index 59f192f..0000000 --- a/dist/middlewares/StatusMonitor.js +++ /dev/null @@ -1,62 +0,0 @@ -"use strict"; -/** - * Define & configure your status monitor - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const expressStatusMonitor = require("express-status-monitor"); -const Log_1 = require("./Log"); -const Locals_1 = require("../providers/Locals"); -class StatusMonitor { - mount(_express) { - Log_1.default.info('Booting the \'StatusMonitor\' middleware...'); - const api = Locals_1.default.config().apiPrefix; - // Define your status monitor config - const monitorOptions = { - title: Locals_1.default.config().name, - path: '/status-monitor', - spans: [ - { - interval: 1, - retention: 60 // Keep 60 data-points in memory - }, - { - interval: 5, - retention: 60 - }, - { - interval: 15, - retention: 60 - } - ], - chartVisibility: { - mem: true, - rps: true, - cpu: true, - load: true, - statusCodes: true, - responseTime: true - }, - healthChecks: [ - { - protocol: 'http', - host: 'localhost', - path: '/', - port: '4040' - }, - { - protocol: 'http', - host: 'localhost', - path: `/${api}`, - port: '4040' - } - ] - }; - // Loads the express status monitor middleware - _express.use(expressStatusMonitor(monitorOptions)); - return _express; - } -} -exports.default = new StatusMonitor; -//# sourceMappingURL=StatusMonitor.js.map \ No newline at end of file diff --git a/dist/middlewares/StatusMonitor.js.map b/dist/middlewares/StatusMonitor.js.map deleted file mode 100644 index 05e7c24..0000000 --- a/dist/middlewares/StatusMonitor.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"StatusMonitor.js","sourceRoot":"","sources":["../../src/middlewares/StatusMonitor.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAGH,+DAA+D;AAE/D,+BAAwB;AACxB,gDAAyC;AAEzC,MAAM,aAAa;IACX,KAAK,CAAE,QAAqB;QAClC,aAAG,CAAC,IAAI,CAAC,6CAA6C,CAAC,CAAC;QAExD,MAAM,GAAG,GAAW,gBAAM,CAAC,MAAM,EAAE,CAAC,SAAS,CAAC;QAE9C,oCAAoC;QACpC,MAAM,cAAc,GAAW;YAC9B,KAAK,EAAE,gBAAM,CAAC,MAAM,EAAE,CAAC,IAAI;YAC3B,IAAI,EAAE,iBAAiB;YACvB,KAAK,EAAE;gBACN;oBACC,QAAQ,EAAE,CAAC;oBACX,SAAS,EAAE,EAAE,CAAE,gCAAgC;iBAC/C;gBACD;oBACC,QAAQ,EAAE,CAAC;oBACX,SAAS,EAAE,EAAE;iBACb;gBACD;oBACC,QAAQ,EAAE,EAAE;oBACZ,SAAS,EAAE,EAAE;iBACb;aACD;YACD,eAAe,EAAE;gBAChB,GAAG,EAAE,IAAI;gBACT,GAAG,EAAE,IAAI;gBACT,GAAG,EAAE,IAAI;gBACT,IAAI,EAAE,IAAI;gBACV,WAAW,EAAE,IAAI;gBACjB,YAAY,EAAE,IAAI;aAClB;YACD,YAAY,EAAE;gBACb;oBACC,QAAQ,EAAE,MAAM;oBAChB,IAAI,EAAE,WAAW;oBACjB,IAAI,EAAE,GAAG;oBACT,IAAI,EAAE,MAAM;iBACZ;gBACD;oBACC,QAAQ,EAAE,MAAM;oBAChB,IAAI,EAAE,WAAW;oBACjB,IAAI,EAAE,IAAI,GAAG,EAAE;oBACf,IAAI,EAAE,MAAM;iBACZ;aACD;SACD,CAAC;QAEF,8CAA8C;QAC9C,QAAQ,CAAC,GAAG,CAAC,oBAAoB,CAAC,cAAc,CAAC,CAAC,CAAC;QAEnD,OAAO,QAAQ,CAAC;IACjB,CAAC;CACD;AAED,kBAAe,IAAI,aAAa,CAAC"} \ No newline at end of file diff --git a/dist/middlewares/Views.js b/dist/middlewares/Views.js deleted file mode 100644 index 8d87baa..0000000 --- a/dist/middlewares/Views.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/** - * Defines the view engines - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const path = require("path"); -const Log_1 = require("./Log"); -class Views { - static mount(_express) { - Log_1.default.info('Booting the \'Views\' middleware...'); - _express.set('view engine', 'pug'); - _express.set('view options', { pretty: true }); - _express.set('views', path.join(__dirname, '../../views')); - _express.locals.pretty = true; - return _express; - } -} -exports.default = Views; -//# sourceMappingURL=Views.js.map \ No newline at end of file diff --git a/dist/middlewares/Views.js.map b/dist/middlewares/Views.js.map deleted file mode 100644 index 64fd629..0000000 --- a/dist/middlewares/Views.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Views.js","sourceRoot":"","sources":["../../src/middlewares/Views.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,6BAA6B;AAG7B,+BAAwB;AAExB,MAAM,KAAK;IACH,MAAM,CAAC,KAAK,CAAC,QAAqB;QACxC,aAAG,CAAC,IAAI,CAAC,qCAAqC,CAAC,CAAC;QAEhD,QAAQ,CAAC,GAAG,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;QACnC,QAAQ,CAAC,GAAG,CAAC,cAAc,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QAC/C,QAAQ,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC,CAAC;QAC3D,QAAQ,CAAC,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC;QAE9B,OAAO,QAAQ,CAAC;IACjB,CAAC;CACD;AAED,kBAAe,KAAK,CAAC"} \ No newline at end of file diff --git a/dist/models/User.js b/dist/models/User.js deleted file mode 100644 index 6f03e89..0000000 --- a/dist/models/User.js +++ /dev/null @@ -1,79 +0,0 @@ -"use strict"; -/** - * Define User model - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.UserSchema = void 0; -const crypto = require("crypto"); -const bcrypt = require("bcrypt-nodejs"); -const Database_1 = require("../providers/Database"); -// Define the User Schema -exports.UserSchema = new Database_1.default.Schema({ - email: { type: String, unique: true }, - password: { type: String }, - passwordResetToken: { type: String }, - passwordResetExpires: Date, - facebook: { type: String }, - twitter: { type: String }, - google: { type: String }, - github: { type: String }, - instagram: { type: String }, - linkedin: { type: String }, - steam: { type: String }, - tokens: Array, - fullname: { type: String }, - gender: { type: String }, - geolocation: { type: String }, - website: { type: String }, - picture: { type: String } -}, { - timestamps: true -}); -// Password hash middleware -exports.UserSchema.pre('save', function (_next) { - const user = this; - if (!user.isModified('password')) { - return _next(); - } - bcrypt.genSalt(10, (_err, _salt) => { - if (_err) { - return _next(_err); - } - bcrypt.hash(user.password, _salt, null, (_err, _hash) => { - if (_err) { - return _next(_err); - } - user.password = _hash; - return _next(); - }); - }); -}); -// Custom Methods -// Get user's full billing address -exports.UserSchema.methods.billingAddress = function () { - const fulladdress = `${this.fullname.trim()} ${this.geolocation.trim()}`; - return fulladdress; -}; -// Compares the user's password with the request password -exports.UserSchema.methods.comparePassword = function (_requestPassword, _cb) { - bcrypt.compare(_requestPassword, this.password, (_err, _isMatch) => { - return _cb(_err, _isMatch); - }); -}; -// User's gravatar -exports.UserSchema.methods.gravatar = function (_size) { - if (!_size) { - _size = 200; - } - const url = 'https://gravatar.com/avatar'; - if (!this.email) { - return `${url}/?s=${_size}&d=retro`; - } - const md5 = crypto.createHash('md5').update(this.email).digest('hex'); - return `${url}/${md5}?s=${_size}&d=retro`; -}; -const User = Database_1.default.model('User', exports.UserSchema); -exports.default = User; -//# sourceMappingURL=User.js.map \ No newline at end of file diff --git a/dist/models/User.js.map b/dist/models/User.js.map deleted file mode 100644 index b66aad6..0000000 --- a/dist/models/User.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"User.js","sourceRoot":"","sources":["../../src/models/User.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;AAEH,iCAAiC;AACjC,wCAAwC;AAGxC,oDAA6C;AAU7C,yBAAyB;AACZ,QAAA,UAAU,GAAG,IAAI,kBAAQ,CAAC,MAAM,CAAa;IACzD,KAAK,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE;IACrC,QAAQ,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;IAC1B,kBAAkB,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;IACpC,oBAAoB,EAAE,IAAI;IAE1B,QAAQ,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;IAC1B,OAAO,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;IACzB,MAAM,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;IACxB,MAAM,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;IACxB,SAAS,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;IAC3B,QAAQ,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;IAC1B,KAAK,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;IACvB,MAAM,EAAE,KAAK;IAEb,QAAQ,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;IAC1B,MAAM,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;IACxB,WAAW,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;IAC7B,OAAO,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;IACzB,OAAO,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;CACzB,EAAE;IACF,UAAU,EAAE,IAAI;CAChB,CAAC,CAAC;AAE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AAC,OAAO,CAAC,QAAQ,GAAG,UAAU,KAAK;IAC5C,IAAI,CAAE,KAAK,EAAE;QACZ,KAAK,GAAG,GAAG,CAAC;KACZ;IAED,MAAM,GAAG,GAAG,6BAA6B,CAAC;IAC1C,IAAI,CAAE,IAAI,CAAC,KAAK,EAAE;QACjB,OAAO,GAAG,GAAG,OAAO,KAAK,UAAU,CAAC;KACpC;IAED,MAAM,GAAG,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACtE,OAAO,GAAG,GAAG,IAAI,GAAG,MAAM,KAAK,UAAU,CAAC;AAC3C,CAAC,CAAC;AAEF,MAAM,IAAI,GAAG,kBAAQ,CAAC,KAAK,CAAa,MAAM,EAAE,kBAAU,CAAC,CAAC;AAE5D,kBAAe,IAAI,CAAC"} \ No newline at end of file diff --git a/dist/providers/App.js b/dist/providers/App.js deleted file mode 100644 index de7f010..0000000 --- a/dist/providers/App.js +++ /dev/null @@ -1,54 +0,0 @@ -"use strict"; -/** - * Primary file for your Clustered API Server - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const kue = require("kue"); -const path = require("path"); -const dotenv = require("dotenv"); -const Express_1 = require("./Express"); -const Database_1 = require("./Database"); -const Queue_1 = require("./Queue"); -const Locals_1 = require("./Locals"); -const Log_1 = require("../middlewares/Log"); -class App { - // Clear the console - clearConsole() { - process.stdout.write('\x1B[2J\x1B[0f'); - Queue_1.default.dispatch('checkout', { foo: 'bar', fizz: 'buzz' }, function (data) { - console.log('>> here is the data', data); - }); - } - // Loads your dotenv file - loadConfiguration() { - Log_1.default.info('Configuration :: Booting @ Master...'); - dotenv.config({ path: path.join(__dirname, '../../.env') }); - } - // Loads your Server - loadServer() { - Log_1.default.info('Server :: Booting @ Master...'); - Express_1.default.init(); - } - // Loads the Database Pool - loadDatabase() { - Log_1.default.info('Database :: Booting @ Master...'); - Database_1.Database.init(); - } - // Loads the Worker Cluster - loadWorker() { - Log_1.default.info('Worker :: Booting @ Master...'); - } - // Loads the Queue Monitor - loadQueue() { - const isQueueMonitorEnabled = Locals_1.default.config().queueMonitor; - const queueMonitorPort = Locals_1.default.config().queueMonitorHttpPort; - if (isQueueMonitorEnabled) { - kue.app.listen(queueMonitorPort); - console.log('\x1b[33m%s\x1b[0m', `Queue Monitor :: Running @ 'http://localhost:${queueMonitorPort}'`); - } - } -} -exports.default = new App; -//# sourceMappingURL=App.js.map \ No newline at end of file diff --git a/dist/providers/App.js.map b/dist/providers/App.js.map deleted file mode 100644 index c62e8e5..0000000 --- a/dist/providers/App.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"App.js","sourceRoot":"","sources":["../../src/providers/App.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,2BAA2B;AAC3B,6BAA6B;AAC7B,iCAAiC;AAEjC,uCAAgC;AAChC,yCAAsC;AAEtC,mCAA4B;AAC5B,qCAA8B;AAC9B,4CAAqC;AAErC,MAAM,GAAG;IACR,oBAAoB;IACb,YAAY;QAClB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;QAEvC,eAAK,CAAC,QAAQ,CAAC,UAAU,EAAE,EAAC,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAC,EAAE,UAAU,IAAI;YACpE,OAAO,CAAC,GAAG,CAAC,qBAAqB,EAAE,IAAI,CAAC,CAAC;QAC1C,CAAC,CAAC,CAAC;IACJ,CAAC;IAED,yBAAyB;IAClB,iBAAiB;QACvB,aAAG,CAAC,IAAI,CAAC,sCAAsC,CAAC,CAAC;QAEjD,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,YAAY,CAAC,EAAE,CAAC,CAAC;IAC7D,CAAC;IAED,oBAAoB;IACb,UAAU;QAChB,aAAG,CAAC,IAAI,CAAC,+BAA+B,CAAC,CAAC;QAE1C,iBAAO,CAAC,IAAI,EAAE,CAAC;IAChB,CAAC;IAED,0BAA0B;IACnB,YAAY;QAClB,aAAG,CAAC,IAAI,CAAC,iCAAiC,CAAC,CAAC;QAE5C,mBAAQ,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;IAED,2BAA2B;IACpB,UAAU;QAChB,aAAG,CAAC,IAAI,CAAC,+BAA+B,CAAC,CAAC;IAC3C,CAAC;IAED,0BAA0B;IACnB,SAAS;QACf,MAAM,qBAAqB,GAAY,gBAAM,CAAC,MAAM,EAAE,CAAC,YAAY,CAAC;QACpE,MAAM,gBAAgB,GAAW,gBAAM,CAAC,MAAM,EAAE,CAAC,oBAAoB,CAAC;QAEtE,IAAI,qBAAqB,EAAE;YAC1B,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC;YAEjC,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,gDAAgD,gBAAgB,GAAG,CAAC,CAAC;SACtG;IACF,CAAC;CACD;AAED,kBAAe,IAAI,GAAG,CAAC"} \ No newline at end of file diff --git a/dist/providers/Cache.js b/dist/providers/Cache.js deleted file mode 100644 index b0698ed..0000000 --- a/dist/providers/Cache.js +++ /dev/null @@ -1,33 +0,0 @@ -"use strict"; -/** - * Define cache middleware - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const mcache = require("memory-cache"); -class Cache { - /** - * Checks for the available cached data - * or adds if not available - */ - cache(_duration) { - return (req, res, next) => { - let key = '__express__' + req.originalUrl || req.url; - let cachedBody = mcache.get(key); - if (cachedBody) { - res.send(cachedBody); - } - else { - res.sendResponse = res.send; - res.send = (body) => { - mcache.put(key, body, _duration * 1000); - res.sendResponse(body); - }; - next(); - } - }; - } -} -exports.default = new Cache; -//# sourceMappingURL=Cache.js.map \ No newline at end of file diff --git a/dist/providers/Cache.js.map b/dist/providers/Cache.js.map deleted file mode 100644 index 0c84311..0000000 --- a/dist/providers/Cache.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Cache.js","sourceRoot":"","sources":["../../src/providers/Cache.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,uCAAuC;AAEvC,MAAM,KAAK;IACV;;;OAGG;IACI,KAAK,CAAC,SAAiB;QAC7B,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;YACzB,IAAI,GAAG,GAAG,aAAa,GAAG,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,GAAG,CAAC;YAErD,IAAI,UAAU,GAAG,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YACjC,IAAI,UAAU,EAAE;gBACf,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;aACrB;iBAAM;gBACN,GAAG,CAAC,YAAY,GAAG,GAAG,CAAC,IAAI,CAAC;gBAC5B,GAAG,CAAC,IAAI,GAAG,CAAC,IAAI,EAAE,EAAE;oBACnB,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,SAAS,GAAG,IAAI,CAAC,CAAC;oBACxC,GAAG,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;gBACxB,CAAC,CAAC;gBACF,IAAI,EAAE,CAAC;aACP;QACF,CAAC,CAAC;IACH,CAAC;CACD;AAED,kBAAe,IAAI,KAAK,CAAC"} \ No newline at end of file diff --git a/dist/providers/Database.js b/dist/providers/Database.js deleted file mode 100644 index c6baf5b..0000000 --- a/dist/providers/Database.js +++ /dev/null @@ -1,35 +0,0 @@ -"use strict"; -/** - * Define Database connection - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Database = void 0; -const mongoose = require("mongoose"); -const bluebird = require("bluebird"); -const Locals_1 = require("./Locals"); -const Log_1 = require("../middlewares/Log"); -class Database { - // Initialize your database pool - static init() { - const dsn = Locals_1.default.config().mongooseUrl; - const options = { useNewUrlParser: true, useUnifiedTopology: true }; - mongoose.Promise = bluebird; - mongoose.set('useCreateIndex', true); - mongoose.connect(dsn, options, (error) => { - // handle the error case - if (error) { - Log_1.default.info('Failed to connect to the Mongo server!!'); - console.log(error); - throw error; - } - else { - Log_1.default.info('connected to mongo server at: ' + dsn); - } - }); - } -} -exports.Database = Database; -exports.default = mongoose; -//# sourceMappingURL=Database.js.map \ No newline at end of file diff --git a/dist/providers/Database.js.map b/dist/providers/Database.js.map deleted file mode 100644 index 80139af..0000000 --- a/dist/providers/Database.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Database.js","sourceRoot":"","sources":["../../src/providers/Database.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;AAEH,qCAAqC;AACrC,qCAAqC;AAGrC,qCAA8B;AAC9B,4CAAqC;AAErC,MAAa,QAAQ;IACpB,gCAAgC;IACzB,MAAM,CAAC,IAAI;QACjB,MAAM,GAAG,GAAG,gBAAM,CAAC,MAAM,EAAE,CAAC,WAAW,CAAC;QACxC,MAAM,OAAO,GAAG,EAAE,eAAe,EAAE,IAAI,EAAE,kBAAkB,EAAE,IAAI,EAAE,CAAC;QAE9D,QAAS,CAAC,OAAO,GAAG,QAAQ,CAAC;QAEnC,QAAQ,CAAC,GAAG,CAAC,gBAAgB,EAAE,IAAI,CAAC,CAAC;QAErC,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,OAAO,EAAE,CAAC,KAAiB,EAAE,EAAE;YACpD,wBAAwB;YACxB,IAAI,KAAK,EAAE;gBACV,aAAG,CAAC,IAAI,CAAC,yCAAyC,CAAC,CAAC;gBACpD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;gBACnB,MAAM,KAAK,CAAC;aACZ;iBAAM;gBACN,aAAG,CAAC,IAAI,CAAC,gCAAgC,GAAG,GAAG,CAAC,CAAC;aACjD;QACF,CAAC,CAAC,CAAC;IACJ,CAAC;CACD;AArBD,4BAqBC;AAED,kBAAe,QAAQ,CAAC"} \ No newline at end of file diff --git a/dist/providers/Express.js b/dist/providers/Express.js deleted file mode 100644 index df6f74f..0000000 --- a/dist/providers/Express.js +++ /dev/null @@ -1,60 +0,0 @@ -"use strict"; -/** - * Primary file for your Clustered API Server - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const express = require("express"); -const Locals_1 = require("./Locals"); -const Routes_1 = require("./Routes"); -const Kernel_1 = require("../middlewares/Kernel"); -const Handler_1 = require("../exception/Handler"); -class Express { - /** - * Initializes the express server - */ - constructor() { - this.express = express(); - this.mountDotEnv(); - this.mountMiddlewares(); - this.mountRoutes(); - } - mountDotEnv() { - this.express = Locals_1.default.init(this.express); - } - /** - * Mounts all the defined middlewares - */ - mountMiddlewares() { - this.express = Kernel_1.default.init(this.express); - } - /** - * Mounts all the defined routes - */ - mountRoutes() { - this.express = Routes_1.default.mountWeb(this.express); - this.express = Routes_1.default.mountApi(this.express); - } - /** - * Starts the express server - */ - init() { - const port = Locals_1.default.config().port; - // Registering Exception / Error Handlers - this.express.use(Handler_1.default.logErrors); - this.express.use(Handler_1.default.clientErrorHandler); - this.express.use(Handler_1.default.errorHandler); - this.express = Handler_1.default.notFoundHandler(this.express); - // Start the server on the specified port - this.express.listen(port, () => { - return console.log('\x1b[33m%s\x1b[0m', `Server :: Running @ 'http://localhost:${port}'`); - }).on('error', (_error) => { - return console.log('Error: ', _error.message); - }); - ; - } -} -/** Export the express module */ -exports.default = new Express(); -//# sourceMappingURL=Express.js.map \ No newline at end of file diff --git a/dist/providers/Express.js.map b/dist/providers/Express.js.map deleted file mode 100644 index b1da93e..0000000 --- a/dist/providers/Express.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Express.js","sourceRoot":"","sources":["../../src/providers/Express.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,mCAAmC;AAEnC,qCAA8B;AAC9B,qCAA8B;AAC9B,kDAA8C;AAC9C,kDAAoD;AAEpD,MAAM,OAAO;IAMZ;;OAEG;IACH;QACC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C,OAAO,EAAE,CAAC,MAAM,EAAE,EAAE;YACzB,OAAO,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;QAC9C,CAAC,CAAC,CAAC;QAAA,CAAC;IACN,CAAC;CACD;AAED,gCAAgC;AAChC,kBAAe,IAAI,OAAO,EAAE,CAAC"} \ No newline at end of file diff --git a/dist/providers/Locals.js b/dist/providers/Locals.js deleted file mode 100644 index d6e698f..0000000 --- a/dist/providers/Locals.js +++ /dev/null @@ -1,72 +0,0 @@ -"use strict"; -/** - * Define App Locals & Configs - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const path = require("path"); -const dotenv = require("dotenv"); -class Locals { - /** - * Makes env configs available for your app - * throughout the app's runtime - */ - static config() { - dotenv.config({ path: path.join(__dirname, '../../.env') }); - const url = process.env.APP_URL || `http://localhost:${process.env.PORT}`; - const port = process.env.PORT || 4040; - const appSecret = process.env.APP_SECRET || 'This is your responsibility!'; - const mongooseUrl = process.env.MONGOOSE_URL; - const maxUploadLimit = process.env.APP_MAX_UPLOAD_LIMIT || '50mb'; - const maxParameterLimit = process.env.APP_MAX_PARAMETER_LIMIT || '50mb'; - const name = process.env.APP_NAME || 'NodeTS Dashboard'; - const keywords = process.env.APP_KEYWORDS || 'somethings'; - const year = (new Date()).getFullYear(); - const copyright = `Copyright ${year} ${name} | All Rights Reserved`; - const company = process.env.COMPANY_NAME || 'GeekyAnts'; - const description = process.env.APP_DESCRIPTION || 'Here goes the app description'; - const isCORSEnabled = process.env.CORS_ENABLED || true; - const jwtExpiresIn = process.env.JWT_EXPIRES_IN || 3; - const apiPrefix = process.env.API_PREFIX || 'api'; - const logDays = process.env.LOG_DAYS || 10; - const queueMonitor = process.env.QUEUE_HTTP_ENABLED || true; - const queueMonitorHttpPort = process.env.QUEUE_HTTP_PORT || 5550; - const redisHttpPort = process.env.REDIS_QUEUE_PORT || 6379; - const redisHttpHost = process.env.REDIS_QUEUE_HOST || '127.0.0.1'; - const redisPrefix = process.env.REDIS_QUEUE_DB || 'q'; - const redisDB = process.env.REDIS_QUEUE_PREFIX || 3; - return { - appSecret, - apiPrefix, - company, - copyright, - description, - isCORSEnabled, - jwtExpiresIn, - keywords, - logDays, - maxUploadLimit, - maxParameterLimit, - mongooseUrl, - name, - port, - redisDB, - redisHttpPort, - redisHttpHost, - redisPrefix, - url, - queueMonitor, - queueMonitorHttpPort - }; - } - /** - * Injects your config to the app's locals - */ - static init(_express) { - _express.locals.app = this.config(); - return _express; - } -} -exports.default = Locals; -//# sourceMappingURL=Locals.js.map \ No newline at end of file diff --git a/dist/providers/Locals.js.map b/dist/providers/Locals.js.map deleted file mode 100644 index c2d99f1..0000000 --- a/dist/providers/Locals.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Locals.js","sourceRoot":"","sources":["../../src/providers/Locals.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAGH,6BAA6B;AAC7B,iCAAiC;AAEjC,MAAM,MAAM;IACX;;;OAGG;IACI,MAAM,CAAC,MAAM;QACnB,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,YAAY,CAAC,EAAE,CAAC,CAAC;QAE5D,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,OAAO,IAAI,oBAAoB,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;QAC1E,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,IAAI,CAAC;QACtC,MAAM,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,IAAI,8BAA8B,CAAC;QAC3E,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC;QAC7C,MAAM,cAAc,GAAG,OAAO,CAAC,GAAG,CAAC,oBAAoB,IAAI,MAAM,CAAC;QAClE,MAAM,iBAAiB,GAAG,OAAO,CAAC,GAAG,CAAC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ACT,SAAS;YACT,OAAO;YACP,SAAS;YACT,WAAW;YACX,aAAa;YACb,YAAY;YACZ,QAAQ;YACR,OAAO;YACP,cAAc;YACd,iBAAiB;YACjB,WAAW;YACX,IAAI;YACJ,IAAI;YACJ,OAAO;YACP,aAAa;YACb,aAAa;YACb,WAAW;YACX,GAAG;YACH,YAAY;YACZ,oBAAoB;SACpB,CAAC;IACH,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,IAAI,CAAE,QAAqB;QACxC,QAAQ,CAAC,MAAM,CAAC,GAAG,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;QACpC,OAAO,QAAQ,CAAC;IACjB,CAAC;CACD;AAED,kBAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/dist/providers/Passport.js b/dist/providers/Passport.js deleted file mode 100644 index 0cd40f8..0000000 --- a/dist/providers/Passport.js +++ /dev/null @@ -1,58 +0,0 @@ -"use strict"; -/** - * Defines the passport config - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const passport = require("passport"); -const Local_1 = require("../services/strategies/Local"); -const Google_1 = require("../services/strategies/Google"); -const Twitter_1 = require("../services/strategies/Twitter"); -const User_1 = require("../models/User"); -const Log_1 = require("../middlewares/Log"); -class Passport { - mountPackage(_express) { - _express = _express.use(passport.initialize()); - _express = _express.use(passport.session()); - passport.serializeUser((user, done) => { - done(null, user.id); - }); - passport.deserializeUser((id, done) => { - User_1.default.findById(id, (err, user) => { - done(err, user); - }); - }); - this.mountLocalStrategies(); - return _express; - } - mountLocalStrategies() { - try { - Local_1.default.init(passport); - Google_1.default.init(passport); - Twitter_1.default.init(passport); - } - catch (_err) { - Log_1.default.error(_err.stack); - } - } - isAuthenticated(req, res, next) { - if (req.isAuthenticated()) { - return next(); - } - req.flash('errors', { msg: 'Please Log-In to access any further!' }); - return res.redirect('/login'); - } - isAuthorized(req, res, next) { - const provider = req.path.split('/').slice(-1)[0]; - const token = req.user.tokens.find(token => token.kind === provider); - if (token) { - return next(); - } - else { - return res.redirect(`/auth/${provider}`); - } - } -} -exports.default = new Passport; -//# sourceMappingURL=Passport.js.map \ No newline at end of file diff --git a/dist/providers/Passport.js.map b/dist/providers/Passport.js.map deleted file mode 100644 index 5f799f8..0000000 --- a/dist/providers/Passport.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Passport.js","sourceRoot":"","sources":["../../src/providers/Passport.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAGH,qCAAqC;AAErC,wDAAyD;AACzD,0DAA2D;AAC3D,4DAA6D;AAE7D,yCAAkC;AAClC,4CAAqC;AAErC,MAAM,QAAQ;IACN,YAAY,CAAE,QAAqB;QACzC,QAAQ,GAAG,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAC;QAC/C,QAAQ,GAAG,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;QAE5C,QAAQ,CAAC,aAAa,CAAW,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE;YAC/C,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC;QACrB,CAAC,CAAC,CAAC;QAEH,QAAQ,CAAC,eAAe,CAAW,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE;YAC/C,cAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE;gBAC/B,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;YACjB,CAAC,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC,oBAAoB,EAAE,CAAC;QAE5B,OAAO,QAAQ,CAAC;IACjB,CAAC;IAEM,oBAAoB;QAC1B,IAAI;YACH,eAAa,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YAC7B,gBAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YAC9B,iBAAe,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;SAC/B;QAAC,OAAO,IAAI,EAAE;YACd,aAAG,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;SACtB;IACF,CAAC;IAEM,eAAe,CAAE,GAAG,EAAE,GAAG,EAAE,IAAI;QACrC,IAAI,GAAG,CAAC,eAAe,EAAE,EAAE;YAC1B,OAAO,IAAI,EAAE,CAAC;SACd;QAED,GAAG,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE,GAAG,EAAE,sCAAsC,EAAC,CAAC,CAAC;QACpE,OAAO,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAC/B,CAAC;IAEM,YAAY,CAAE,GAAG,EAAE,GAAG,EAAE,IAAI;QAClC,MAAM,QAAQ,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAClD,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC;QACrE,IAAI,KAAK,EAAE;YACV,OAAO,IAAI,EAAE,CAAC;SACd;aAAM;YACN,OAAO,GAAG,CAAC,QAAQ,CAAC,SAAS,QAAQ,EAAE,CAAC,CAAC;SACzC;IACF,CAAC;CACD;AAED,kBAAe,IAAI,QAAQ,CAAC"} \ No newline at end of file diff --git a/dist/providers/Queue.js b/dist/providers/Queue.js deleted file mode 100644 index 933a1ae..0000000 --- a/dist/providers/Queue.js +++ /dev/null @@ -1,51 +0,0 @@ -"use strict"; -/** - * Sends your verify email - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const kue = require("kue"); -const Locals_1 = require("./Locals"); -const Log_1 = require("../middlewares/Log"); -class Queue { - constructor() { - this.jobs = kue.createQueue({ - prefix: Locals_1.default.config().redisPrefix, - redis: { - port: Locals_1.default.config().redisHttpPort, - host: Locals_1.default.config().redisHttpHost, - db: Locals_1.default.config().redisDB - } - }); - this.jobs - .on('job enqueue', (_id, _type) => Log_1.default.info(`Queue :: #${_id} Processing of type '${_type}'`)) - .on('job complete', (_id) => this.removeProcessedJob(_id)); - } - dispatch(_jobName, _args, _callback) { - this.jobs.create(_jobName, _args).save(); - this.process(_jobName, 3, _callback); - } - removeProcessedJob(_id) { - Log_1.default.info(`Queue :: #${_id} Processed`); - kue.Job.get(_id, (_err, _job) => { - if (_err) { - return; - } - _job.remove((_err) => { - if (_err) { - throw _err; - } - Log_1.default.info(`Queue :: #${_id} Removed Processed Job`); - }); - }); - } - process(_jobName, _count, _callback) { - this.jobs.process(_jobName, _count, (_job, _done) => { - _done(); // Notifies KUE about the completion of the job! - _callback(_job.data); - }); - } -} -exports.default = new Queue; -//# sourceMappingURL=Queue.js.map \ No newline at end of file diff --git a/dist/providers/Queue.js.map b/dist/providers/Queue.js.map deleted file mode 100644 index 763ce8a..0000000 --- a/dist/providers/Queue.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Queue.js","sourceRoot":"","sources":["../../src/providers/Queue.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,2BAA2B;AAE3B,qCAA8B;AAC9B,4CAAqC;AAErC,MAAM,KAAK;IAGV;QACC,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,WAAW,CAAC;YAC3B,MAAM,EAAE,gBAAM,CAAC,MAAM,EAAE,CAAC,WAAW;YACnC,KAAK,EAAE;gBACN,IAAI,EAAE,gBAAM,CAAC,MAAM,EAAE,CAAC,aAAa;gBACnC,IAAI,EAAE,gBAAM,CAAC,MAAM,EAAE,CAAC,aAAa;gBACnC,EAAE,EAAG,gBAAM,CAAC,MAAM,EAAE,CAAC,OAAO;aAC5B;SACD,CAAC,CAAC;QAEH,IAAI,CAAC,IAAI;aACP,EAAE,CAAC,aAAa,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,E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ers/Routes.js b/dist/providers/Routes.js deleted file mode 100644 index 69afd69..0000000 --- a/dist/providers/Routes.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -/** - * Define all your routes - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const Locals_1 = require("./Locals"); -const Log_1 = require("../middlewares/Log"); -const Web_1 = require("./../routes/Web"); -const Api_1 = require("./../routes/Api"); -class Routes { - mountWeb(_express) { - Log_1.default.info('Routes :: Mounting Web Routes...'); - return _express.use('/', Web_1.default); - } - mountApi(_express) { - const apiPrefix = Locals_1.default.config().apiPrefix; - Log_1.default.info('Routes :: Mounting API Routes...'); - return _express.use(`/${apiPrefix}`, Api_1.default); - } -} -exports.default = new Routes; -//# sourceMappingURL=Routes.js.map \ No newline at end of file diff --git a/dist/providers/Routes.js.map b/dist/providers/Routes.js.map deleted file mode 100644 index e1cdc56..0000000 --- a/dist/providers/Routes.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Routes.js","sourceRoot":"","sources":["../../src/providers/Routes.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAGH,qCAA8B;AAC9B,4CAAqC;AAErC,yCAAwC;AACxC,yCAAwC;AAExC,MAAM,MAAM;IACJ,QAAQ,CAAC,QAAqB;QACpC,aAAG,CAAC,IAAI,CAAC,kCAAkC,CAAC,CAAC;QAE7C,OAAO,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,aAAS,CAAC,CAAC;IACrC,CAAC;IAEM,QAAQ,CAAC,QAAqB;QACpC,MAAM,SAAS,GAAG,gBAAM,CAAC,MAAM,EAAE,CAAC,SAAS,CAAC;QAC5C,aAAG,CAAC,IAAI,CAAC,kCAAkC,CAAC,CAAC;QAE7C,OAAO,QAAQ,CAAC,GAAG,CAAC,IAAI,SAAS,EAAE,EAAE,aAAS,CAAC,CAAC;IACjD,CAAC;CACD;AAED,kBAAe,IAAI,MAAM,CAAC"} \ No newline at end of file diff --git a/dist/routes/Api.js b/dist/routes/Api.js deleted file mode 100644 index 390b4b6..0000000 --- a/dist/routes/Api.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/** - * Define all your API web-routes - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const express_1 = require("express"); -const expressJwt = require("express-jwt"); -const Locals_1 = require("../providers/Locals"); -const Home_1 = require("../controllers/Api/Home"); -const Login_1 = require("../controllers/Api/Auth/Login"); -const Register_1 = require("../controllers/Api/Auth/Register"); -const RefreshToken_1 = require("../controllers/Api/Auth/RefreshToken"); -const router = express_1.Router(); -router.get('/', Home_1.default.index); -router.post('/auth/login', Login_1.default.perform); -router.post('/auth/register', Register_1.default.perform); -router.post('/auth/refresh-token', expressJwt({ secret: Locals_1.default.config().appSecret }), RefreshToken_1.default.perform); -exports.default = router; -//# sourceMappingURL=Api.js.map \ No newline at end of file diff --git a/dist/routes/Api.js.map b/dist/routes/Api.js.map deleted file mode 100644 index ef55d50..0000000 --- a/dist/routes/Api.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Api.js","sourceRoot":"","sources":["../../src/routes/Api.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,qCAAiC;AACjC,0CAA0C;AAE1C,gDAAyC;AAEzC,kDAAqD;AACrD,yDAA4D;AAC5D,+DAAkE;AAClE,uEAA0E;AAE1E,MAAM,MAAM,GAAG,gBAAM,EAAE,CAAC;AAExB,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,cAAc,CAAC,KAAK,CAAC,CAAC;AAEtC,MAAM,CAAC,IAAI,CAAC,aAAa,EAAE,eAAe,CAAC,OAAO,CAAC,CAAC;AACpD,MAAM,CAAC,IAAI,CAAC,gBAAgB,EAAE,kBAAkB,CAAC,OAAO,CAAC,CAAC;AAC1D,MAAM,CAAC,IAAI,CAAC,qBAAqB,EAAE,UAAU,CAAC,EAAE,MAAM,EAAE,gBAAM,CAAC,MAAM,EAAE,CAAC,SAAS,EAAE,CAAC,EAAE,sBAAsB,CAAC,OAAO,CAAC,CAAC;AAEtH,kBAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/dist/routes/Web.js b/dist/routes/Web.js deleted file mode 100644 index 00e8b30..0000000 --- a/dist/routes/Web.js +++ /dev/null @@ -1,34 +0,0 @@ -"use strict"; -/** - * Define all your Web routes - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const passport = require("passport"); -const express_1 = require("express"); -const Cache_1 = require("./../providers/Cache"); -const Passport_1 = require("./../providers/Passport"); -const Home_1 = require("../controllers/Home"); -const Account_1 = require("../controllers/Account"); -const Login_1 = require("../controllers/Auth/Login"); -const Logout_1 = require("../controllers/Auth/Logout"); -const Social_1 = require("../controllers/Auth/Social"); -const Register_1 = require("../controllers/Auth/Register"); -const router = express_1.Router(); -const cache = Cache_1.default.cache; -router.get('/', cache(10), Home_1.default.index); -router.get('/signup', cache(10), Register_1.default.show); -router.post('/signup', Register_1.default.perform); -router.get('/login', cache(10), Login_1.default.show); -router.post('/login', Login_1.default.perform); -router.get('/logout', Logout_1.default.perform); -router.get('/account', Passport_1.default.isAuthenticated, Account_1.default.index); -router.get('/auth/google', passport.authenticate('google', { scope: ['email', 'profile'], failureRedirect: '/login' })); -router.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), Social_1.default.googleCallback); -router.get('/auth/twitter', passport.authenticate('twitter')); -router.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), (req, res) => { - res.redirect('/'); -}); -exports.default = router; -//# sourceMappingURL=Web.js.map \ No newline at end of file diff --git a/dist/routes/Web.js.map b/dist/routes/Web.js.map deleted file mode 100644 index 0d5ef3d..0000000 --- a/dist/routes/Web.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Web.js","sourceRoot":"","sources":["../../src/routes/Web.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,qCAAqC;AACrC,qCAAiC;AAEjC,gDAAyC;AAC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AY,CAAC,SAAS,CAAC,CAAC,CAAC;AAC9D,MAAM,CAAC,GAAG,CAAC,wBAAwB,EAAE,QAAQ,CAAC,YAAY,CAAC,SAAS,EAAE,EAAE,eAAe,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;IAClH,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AACnB,CAAC,CAAC,CAAC;AAEH,kBAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/dist/services/strategies/Google.js b/dist/services/strategies/Google.js deleted file mode 100644 index 4c18e66..0000000 --- a/dist/services/strategies/Google.js +++ /dev/null @@ -1,85 +0,0 @@ -"use strict"; -/** - * Define Google OAuth2 - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const passport_google_oauth20_1 = require("passport-google-oauth20"); -const User_1 = require("../../models/User"); -const Locals_1 = require("../../providers/Locals"); -class Google { - static init(_passport) { - _passport.use(new passport_google_oauth20_1.Strategy({ - clientID: process.env.GOOGLE_ID, - clientSecret: process.env.GOOGLE_SECRET, - callbackURL: `${Locals_1.default.config().url}/auth/google/callback`, - passReqToCallback: true - }, (req, accessToken, refreshToken, profile, done) => { - if (req.user) { - User_1.default.findOne({ google: profile.id }, (err, existingUser) => { - if (err) { - return done(err); - } - if (existingUser) { - req.flash('errors', { msg: 'There is already a Google account that belongs to you. Sign in with that account or delete it, then link it with your current account.' }); - return done(err); - } - else { - User_1.default.findById(req.user.id, (err, user) => { - if (err) { - return done(err); - } - user.google = profile.id; - user.tokens.push({ kind: 'google', accessToken }); - user.fullname = user.fullname || profile.displayName; - user.gender = user.gender || profile._json.gender; - if (profile.photos) { - user.picture = user.picture || profile.photos[0].value; - } - user.save((err) => { - req.flash('info', { msg: 'Google account has been linked.' }); - return done(err, user); - }); - }); - } - }); - } - else { - User_1.default.findOne({ google: profile.id }, (err, existingUser) => { - if (err) { - return done(err); - } - if (existingUser) { - return done(null, existingUser); - } - User_1.default.findOne({ email: profile.emails[0].value }, (err, existingEmailUser) => { - if (err) { - return done(err); - } - if (existingEmailUser) { - req.flash('errors', { msg: 'There is already an account using this email address. Sing in to that accoount and link it with Google manually from Account Settings.' }); - return done(err); - } - else { - const user = new User_1.default(); - user.email = profile.emails[0].value; - user.google = profile.id; - user.tokens.push({ kind: 'google', accessToken }); - user.fullname = user.fullname || profile.displayName; - user.gender = user.gender || profile._json.gender; - if (profile.photos) { - user.picture = user.picture || profile.photos[0].value; - } - user.save((err) => { - return done(err, user); - }); - } - }); - }); - } - })); - } -} -exports.default = Google; -//# sourceMappingURL=Google.js.map \ No newline at end of file diff --git a/dist/services/strategies/Google.js.map b/dist/services/strategies/Google.js.map deleted file mode 100644 index 572d6bd..0000000 --- a/dist/services/strategies/Google.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Google.js","sourceRoot":"","sources":["../../../src/services/strategies/Google.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,qEAAmD;AACnD,4CAAqC;AACrC,mDAA4C;AAE5C,MAAM,MAAM;IACJ,MAAM,CAAC,IAAI,CAAE,SAAc;QACjC,SAAS,CAAC,GAAG,CAAC,IAAI,kCAAQ,CAAC;YAC1B,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS;YAC/B,YAAY,EAAE,OAAO,CAAC,GAAG,CAAC,aAAa;YACvC,WAAW,EAAE,GAAG,gBAAM,CAAC,MAAM,EAAE,CAAC,GAAG,uBAAuB;YAC1D,iBAAiB,EAAE,IAAI;SACvB,EAAE,CAAC,GAAG,EAAE,WAAW,EAAE,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE;YACpD,IAAI,GAAG,CAAC,IAAI,EAAE;gBACb,cAAI,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,GAAG,EAAE,YAAY,EAAE,EAAE;oBAC1D,IAAI,GAAG,EAAE;wBACR,OAAO,IAAI,CA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C,CAAC,GAAG,EAAE,EAAE;gCACjB,OAAO,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;4BACxB,CAAC,CAAC,CAAC;yBACH;oBACF,CAAC,CAAC,CAAC;gBACJ,CAAC,CAAC,CAAC;aACH;QACF,CAAC,CAAC,CAAC,CAAC;IACL,CAAC;CACD;AAED,kBAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/dist/services/strategies/Local.js b/dist/services/strategies/Local.js deleted file mode 100644 index 3b7f044..0000000 --- a/dist/services/strategies/Local.js +++ /dev/null @@ -1,43 +0,0 @@ -"use strict"; -/** - * Define passport's local strategy - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const passport_local_1 = require("passport-local"); -const User_1 = require("../../models/User"); -const Log_1 = require("../../middlewares/Log"); -class Local { - static init(_passport) { - _passport.use(new passport_local_1.Strategy({ usernameField: 'email' }, (email, password, done) => { - Log_1.default.info(`Email is ${email}`); - Log_1.default.info(`Password is ${password}`); - User_1.default.findOne({ email: email.toLowerCase() }, (err, user) => { - Log_1.default.info(`user is ${user.email}`); - Log_1.default.info(`error is ${err}`); - if (err) { - return done(err); - } - if (!user) { - return done(null, false, { msg: `E-mail ${email} not found.` }); - } - if (user && !user.password) { - return done(null, false, { msg: `E-mail ${email} was not registered with us using any password. Please use the appropriate providers to Log-In again!` }); - } - Log_1.default.info('comparing password now!'); - user.comparePassword(password, (_err, _isMatch) => { - if (_err) { - return done(_err); - } - if (_isMatch) { - return done(null, user); - } - return done(null, false, { msg: 'Invalid E-mail or password.' }); - }); - }); - })); - } -} -exports.default = Local; -//# sourceMappingURL=Local.js.map \ No newline at end of file diff --git a/dist/services/strategies/Local.js.map b/dist/services/strategies/Local.js.map deleted file mode 100644 index e6925d4..0000000 --- a/dist/services/strategies/Local.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Local.js","sourceRoot":"","sources":["../../../src/services/strategies/Local.ts"],"names":[],"mappings":";AAAA;;;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AQ,EAAE;wBACb,OAAO,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;qBACxB;oBACD,OAAO,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,GAAG,EAAE,6BAA6B,EAAC,CAAC,CAAC;gBACjE,CAAC,CAAC,CAAC;YACJ,CAAC,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC,CAAC;IACL,CAAC;CACD;AAED,kBAAe,KAAK,CAAC"} \ No newline at end of file diff --git a/dist/services/strategies/Twitter.js b/dist/services/strategies/Twitter.js deleted file mode 100644 index 81a6502..0000000 --- a/dist/services/strategies/Twitter.js +++ /dev/null @@ -1,75 +0,0 @@ -"use strict"; -/** - * Define Google OAuth2 - * - * @author Faiz A. Farooqui - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const passport_twitter_1 = require("passport-twitter"); -const User_1 = require("../../models/User"); -const Locals_1 = require("../../providers/Locals"); -class Twitter { - static init(_passport) { - _passport.use(new passport_twitter_1.Strategy({ - consumerKey: process.env.TWITTER_KEY, - consumerSecret: process.env.TWITTER_SECRET, - callbackURL: `${Locals_1.default.config().url}/auth/twitter/callback`, - passReqToCallback: true - }, (req, accessToken, tokenSecret, profile, done) => { - if (req.user) { - User_1.default.findOne({ twitter: profile.id }, (err, existingUser) => { - if (err) { - return done(err); - } - if (existingUser) { - req.flash('errors', { msg: 'There is already a Twitter account that belongs to you. Sign in with that account or delete it, then link it with your current account.' }); - return done(err); - } - else { - User_1.default.findById(req.user.id, (err, user) => { - if (err) { - return done(err); - } - user.twitter = profile.id; - user.tokens.push({ kind: 'twitter', accessToken, tokenSecret }); - user.fullname = user.fullname || profile.displayName; - user.geolocation = user.geolocation || profile._json.location; - user.picture = user.picture || profile._json.profile_image_url_https; - user.save((err) => { - if (err) { - return done(err); - } - req.flash('info', { msg: 'Twitter account has been linked.' }); - return done(err, user); - }); - }); - } - }); - } - else { - User_1.default.findOne({ twitter: profile.id }, (err, existingUser) => { - if (err) { - return done(err); - } - if (existingUser) { - return done(null, existingUser); - } - const user = new User_1.default(); - // Twitter does not provides the user's e-mail address. - // We can "fake" a twitter email address as follows: - user.email = `${profile.username}@twitter.com`; - user.twitter = profile.id; - user.tokens.push({ kind: 'twitter', accessToken, tokenSecret }); - user.fullname = profile.displayName; - user.geolocation = profile._json.location; - user.picture = profile._json.profile_image_url_https; - user.save((err) => { - done(err, user); - }); - }); - } - })); - } -} -exports.default = Twitter; -//# sourceMappingURL=Twitter.js.map \ No newline at end of file diff --git a/dist/services/strategies/Twitter.js.map b/dist/services/strategies/Twitter.js.map deleted file mode 100644 index 92b57a9..0000000 --- a/dist/services/strategies/Twitter.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"Twitter.js","sourceRoot":"","sources":["../../../src/services/strategies/Twitter.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAEH,uDAA4C;AAC5C,4CAAqC;AACrC,mDAA4C;AAE5C,MAAM,OAAO;IACL,MAAM,CAAC,IAAI,CAAE,SAAc;QACjC,SAAS,CAAC,GAAG,CAAC,IAAI,2BAAQ,CAAC;YAC1B,WAAW,EAAE,OAAO,CAAC,GAAG,CAAC,WAAW;YACpC,cAAc,EAAE,OAAO,CAAC,GAAG,CAAC,cAAc;YAC1C,WAAW,EAAE,GAAG,gBAAM,CAAC,MAAM,EAAE,CAAC,GAAG,wBAAwB;YAC3D,iBAAiB,EAAE,IAAI;SACvB,EAAE,CAAC,GAAG,EAAE,WAAW,EAAE,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE;YACnD,IAAI,GAAG,CAAC,IAAI,EAAE;gBACb,cAAI,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,GAAG,EAAE,YAAY,EAAE,EAAE;oBAC3D,IAAI,GAAG,EAAE;wBACR,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;qBACjB;oBAED,IAAI,YAAY,EAAE;wBACjB,GAAG,CAAC,KAAK,CAA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