Skip to content

Instantly share code, notes, and snippets.

@godie007
Last active July 25, 2018 00:18
Show Gist options
  • Select an option

  • Save godie007/3a6080e8548782287e68d0f76873c4c3 to your computer and use it in GitHub Desktop.

Select an option

Save godie007/3a6080e8548782287e68d0f76873c4c3 to your computer and use it in GitHub Desktop.
Sistema de autenticacion con token
// configuración postman
header: {
x-access-token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6ImRpZWdvIiwiaWF0IjoxNTMyNDc2NDE2LCJleHAiOjE1MzI0ODAwMTZ9.Ev-x8tQPkmnA6FAYgTts0W2LwWQITmzAPy6oomKRKVc
}
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const middlewareJwt = require('express-jwt');
const secret = 'keysegurytiproffesinal';
const app = express();
const middleware = middlewareJwt({ secret })
app.use(bodyParser.json());
app.post('/signin', (req, res) => {
const { email, password } = req.body;
if (email === 'lolo' && password === 'lolo') {
const token = jwt.sign({
id: 'diego',
},secret, { expiresIn: '1h' });
res.send({ token });
return;
}
res.status(401).send({ error: 'bad credentials' });
});
app.post('/', (req, res) => {
try {
const id = validateToken(req)
res.send( id );
} catch ({ message }) {
res.status(401).send({ message });
}
});
const validateToken = (req) => {
var token = req.headers['x-access-token'];
if (!token) return res.status(401).send({ auth: false, message: 'No token provided.' });
return jwt.verify(token, secret);
}
app.get('/logout', function(req, res) {
res.status(200).send({ auth: false, token: null });
});
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment