From 49ec609f5b4dc0c5577c398ff229d710db902d4d Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Mon, 29 Jan 2018 19:39:52 -0800 Subject: jwt auth --- app.js | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) (limited to 'app.js') diff --git a/app.js b/app.js index 242f2247..004bc263 100644 --- a/app.js +++ b/app.js @@ -9,6 +9,8 @@ import express from 'express' import fs from 'fs' import grpc from 'grpc' import passport from './passport' +import jwt from 'jsonwebtoken' +import bcrypt from 'bcrypt' import { graphqlExpress, graphiqlExpress } from 'apollo-server-express' dotenv.config() @@ -47,6 +49,43 @@ const l = console.log res.json(app.get('rates')) }) + app.post('/login', (req, res) => { + console.log('logging in') + db.User.findOne({ + where: { + username: req.body.username + } + }).then((user) => { + bcrypt.compare(req.body.password, user.password).then((result) => { + console.log('password was good') + if (result) { + let payload = { username: user.username } + let token = jwt.sign(payload, process.env.SECRET) + res.cookie('token', token, { expires: new Date(Date.now() + 9999999) }) + res.json({ token: token }) + } else { + res.status(401).end() + } + }).catch((err) => { + console.log(err) + res.status(401).end() + }) + }).catch((err) => { + console.log(err) + res.status(401).end() + }) + }) + + app.get('/secret', passport.authenticate('jwt', { session: false }), (req, res) => { + res.json({message: 'Success! You can not see this without a token'}) + }) + + app.get('/api/users/me', + passport.authenticate('basic', { session: false }), + function(req, res) { + res.json({ id: req.user.id, username: req.user.username }); + }); + app.use('/graphql', bodyParser.json(), graphqlExpress({ schema: db.gqlschema, context: {}, -- cgit v1.2.3