Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const bcrypt = require( "bcryptjs" );
- const bodyParser = require( "body-parser" );
- const express = require( "express" );
- const fs = require( "fs" );
- const jwt = require( "jwt-simple" );
- const mongodb = require( "mongodb" );
- const spdy = require( "spdy" );
- const MongoClient = mongodb.MongoClient;
- const Server = mongodb.Server;
- const app = express();
- app.use( bodyParser.json() );
- const secretKey = "secretKey";
- // register
- app.post( "/fb/register", async ( reqt, resp ) => {
- try {
- const u = reqt.body.username;
- const p = reqt.body.password;
- const h = await bcrypt.hashSync( p, 10 );
- const svr = new Server( "localhost", 27017 );
- const con = await MongoClient.connect( svr );
- const col = con.db( "fb" ).collection( "auth" );
- const res = await col.updateOne( { username : u }
- , { $set : { password : h } }
- , { upsert : true }
- );
- con.close();
- resp.status( 204 ).end(); // No Content
- } catch ( exn ) {
- resp.status( 500 ).end(); // Internal Server Error
- 2
- }
- });
- // issue a token
- app.post( "/fb/issue/:username", async ( reqt, resp ) => {
- try {
- const u = reqt.params.username
- const p = reqt.body.password
- const svr = new Server( "localhost", 27017 );
- const con = await MongoClient.connect( svr );
- const doc = await col.findOne( { username : u } );
- con.close();
- if ( doc ) {
- const vld = await bcrypt.compareSync( p, doc.password );
- 3
- if ( vld ) {
- const uid = { username : u };
- const tkn = jwt.encode( uid, secretKey );
- resp.status( 200 ).json( tkn ).end(); // OK
- } else {
- resp.status( 401 ).end(); // Unauthorised
- }
- } else {
- resp.status( 401 ).end(); // Unauthorised
- }
- } catch ( exn ) {
- resp.status( 500 ).end(); // Internal Server Error
- }
- });
- // given token, return session object
- app.get( "/fb/session", async ( reqt, resp ) => {
- try {
- const tkn = reqt.headers[ "x-auth" ]
- const uid = jwt.decode( tkn, secretKey )
- resp.status( 200 ).json( uid ).end(); // OK
- } catch ( exn ) {
- resp.status( 401 ).end(); // Unauthorised
- }
- });
- // run
- const server = spdy.createServer( {
- key : fs.readFileSync( "key.pem" ),
- cert : fs.readFileSync( "cert.pem" )
- }, app );
- server.listen( 8443, () => {
- console.log( "listening on port 8443..." )
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement