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