Guest User

Untitled

a guest
Apr 11th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. import * as jwt from 'jsonwebtoken';
  2.  
  3. export class Jwt {
  4. private secretKey = 'xxa94c1883329b47babf53df568c11d26569290c912a54d6bf884136e3ef4d120e';
  5.  
  6. sign(playload: any) {
  7. let token = jwt.sign(playload, this.secretKey, {
  8. expiresIn: '1d'
  9. });
  10. return token;
  11. }
  12.  
  13. verify(token: string) {
  14. return new Promise((resolve, reject) => {
  15. jwt.verify(token, this.secretKey, (err, decoded) => {
  16. if (err) {
  17. reject(err)
  18. } else {
  19. resolve(decoded)
  20. }
  21. });
  22. });
  23. }
  24.  
  25. }
  26.  
  27. ////////////////////
  28. // app.ts //
  29. require('dotenv').config();
  30.  
  31. import { MySqlConnectionConfig } from 'knex';
  32. import Knex = require('knex');
  33.  
  34. import { Jwt } from './models/jwt';
  35. const jwt = new Jwt();
  36.  
  37. let checkAuth = (req, res, next) => {
  38. let token: string = null;
  39.  
  40. if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
  41. token = req.headers.authorization.split(' ')[1];
  42. } else if (req.query && req.query.token) {
  43. token = req.query.token;
  44. } else {
  45. token = req.body.token;
  46. }
  47.  
  48. jwt.verify(token)
  49. .then((decoded: any) => {
  50. req.decoded = decoded;
  51. next();
  52. }, err => {
  53. return res.send({
  54. ok: false,
  55. error: 'No token provided.',
  56. code: 403
  57. });
  58. });
  59. }
  60.  
  61.  
  62. // MySQL Connection
  63.  
  64. let connection: MySqlConnectionConfig = {
  65. host: process.env.DB_HOST,
  66. port: process.env.DB_PORT,
  67. database: process.env.DB_NAME,
  68. user: process.env.DB_USER,
  69. password: process.env.DB_PASSWORD,
  70. multipleStatements: true,
  71. debug: false
  72. }
  73.  
  74. let db = Knex({
  75. client: 'mysql',
  76. connection: connection
  77. });
  78.  
  79. app.use((req, res, next) => {
  80. req.db = db;
  81. next();
  82. });
  83.  
  84. //
Add Comment
Please, Sign In to add comment