Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. const bcrypt = require( "bcryptjs" );
  2. const bodyParser = require( "body-parser" );
  3. const express = require( "express" );
  4. const fs = require( "fs" );
  5. const jwt = require( "jwt-simple" );
  6. const mongodb = require( "mongodb" );
  7. const spdy = require( "spdy" );
  8.  
  9. const MongoClient = mongodb.MongoClient;
  10. const Server = mongodb.Server;
  11.  
  12. const app = express();
  13. app.use( bodyParser.json() );
  14.  
  15. const secretKey = "secretKey";
  16.  
  17. // register
  18. app.post( "/fb/register", async ( reqt, resp ) => {
  19. try {
  20. const u = reqt.body.username;
  21. const p = reqt.body.password;
  22. const h = await bcrypt.hashSync( p, 10 );
  23. const svr = new Server( "localhost", 27017 );
  24. const con = await MongoClient.connect( svr );
  25. const col = con.db( "fb" ).collection( "auth" );
  26. const res = await col.updateOne( { username : u }
  27. , { $set : { password : h } }
  28. , { upsert : true }
  29. );
  30. con.close();
  31. resp.status( 204 ).end(); // No Content
  32. } catch ( exn ) {
  33. resp.status( 500 ).end(); // Internal Server Error
  34. 2
  35. }
  36. });
  37.  
  38.  
  39.  
  40. // issue a token
  41. app.post( "/fb/issue/:username", async ( reqt, resp ) => {
  42. try {
  43. const u = reqt.params.username
  44. const p = reqt.body.password
  45. const svr = new Server( "localhost", 27017 );
  46. const con = await MongoClient.connect( svr );
  47.  
  48. const doc = await col.findOne( { username : u } );
  49. con.close();
  50. if ( doc ) {
  51. const vld = await bcrypt.compareSync( p, doc.password );
  52. 3
  53. if ( vld ) {
  54. const uid = { username : u };
  55. const tkn = jwt.encode( uid, secretKey );
  56. resp.status( 200 ).json( tkn ).end(); // OK
  57. } else {
  58. resp.status( 401 ).end(); // Unauthorised
  59. }
  60. } else {
  61. resp.status( 401 ).end(); // Unauthorised
  62. }
  63. } catch ( exn ) {
  64. resp.status( 500 ).end(); // Internal Server Error
  65. }
  66. });
  67.  
  68.  
  69.  
  70.  
  71. // given token, return session object
  72. app.get( "/fb/session", async ( reqt, resp ) => {
  73. try {
  74. const tkn = reqt.headers[ "x-auth" ]
  75. const uid = jwt.decode( tkn, secretKey )
  76. resp.status( 200 ).json( uid ).end(); // OK
  77. } catch ( exn ) {
  78. resp.status( 401 ).end(); // Unauthorised
  79. }
  80. });
  81.  
  82.  
  83.  
  84. // run
  85. const server = spdy.createServer( {
  86. key : fs.readFileSync( "key.pem" ),
  87. cert : fs.readFileSync( "cert.pem" )
  88. }, app );
  89. server.listen( 8443, () => {
  90. console.log( "listening on port 8443..." )
  91. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement