Last active
January 20, 2019 15:56
-
-
Save AlexisTM/98f709b241b358c81955ff2532853d5b to your computer and use it in GitHub Desktop.
To create a token with expiration
This file contains hidden or 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
// Express web app | |
const express = require('express'); | |
const app = express() | |
const md5 = require('md5'); | |
// Redis client | |
const redis = require("redis"); | |
const client = redis.createClient({ host: '192.168.178.23' }); | |
// Token generator | |
const TokenGenerator = require('uuid-token-generator'); | |
const tokgen = new TokenGenerator(); | |
// Express login & token generation | |
app.get("/login", function(req, res){ | |
const {username, password} = req.query; | |
if(username && password) { | |
client.get('users/' + username + ':mmd5', function(err, data) { // Check password. | |
if(data == md5(password)) { | |
let token = tokgen.generate(); | |
// Send the token back for use by the frontend (typically store it in the cookies) | |
res.send(token); | |
// Save the token in the Redis DB | |
client.set('users/' + username + ':token-'+token, { 'whatever': 'data' }, 'EX', 10*86400); | |
} else { | |
res.status(403).send('Invalid password or username.'); | |
}; | |
res.end(); | |
}); | |
} else { | |
res.status(403).send('No password or username given.'); | |
} | |
}); | |
// Token verification on the cookies: | |
// success, data = check_token(username, token); | |
function check_token(username, token) { | |
if(username && token) { | |
client.get('users/' + username + ':token-'+token, function(err, data) { | |
// data is null if the key is not found. | |
return data!=null, data; | |
}); | |
} | |
return false, null; | |
} | |
app.listen(3000, () => console.log(`Listening on port 3000.`)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment