Created
January 17, 2017 21:19
-
-
Save didierfranc/bb9a41f0d745a5a84dd0f798b9acd4d5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs') | |
const path = require('path') | |
const express = require('express') | |
const compression = require('compression') | |
const bodyParser = require('body-parser') | |
const jwt = require('jsonwebtoken') | |
// Allow CORS | |
const origin = '*' | |
const app = express() | |
app.use(bodyParser.json()) | |
app.use((req, res, next) => { | |
res.header('Access-Control-Allow-Origin', origin) | |
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept') | |
next() | |
}) | |
// API | |
const secret = 'secret' | |
const generateToken = (user) => jwt.sign(user, secret) | |
app.post('/signup', async (req, res) => { | |
const { email, password } = req.body | |
if (email === '' || password === '') { | |
res.status('400').send('Empty fields') | |
return | |
} | |
const exist = '' // check if user exist in your db | |
const id = '' // generate an id | |
if (exist) { | |
res.status('409').send('Try again') | |
} else { | |
// save your user | |
const token = generateToken({ email, user: id }) | |
res.send({ exist: false, token, id, email }) | |
} | |
}) | |
app.post('/login', async (req, res) => { | |
const { email, password } = req.body | |
const id = '' // find id of the user | |
const storedPassword = '' // get pass hash | |
const valid = '' // compare | |
const token = generateToken({ email, user: id }) | |
if (valid) { | |
res.send({ exist: true, token, id, email }) | |
} else { | |
res.status('409').send('Wrong password/username') | |
} | |
}) | |
app.post('/token', async (req, res) => { | |
const { token } = req.body | |
jwt.verify(token, secret, (err, d) => { | |
err | |
? res.status('400').send('Try again') | |
: res.send({ exist: true, token, id: d.id, email: d.email }) | |
}) | |
}) | |
// Static | |
app.use(compression()) | |
app.use('/', express.static(__dirname + '/public', { maxAge: 86400000 })); | |
app.get('*', (req, res) => res.sendFile(__dirname + '/public/index.html')) | |
// Run server | |
app.listen(process.env.PORT || 5000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment