Recv/lib/api/token.js

65 lines
1.4 KiB
JavaScript
Raw Normal View History

const config = require('../../config');
2018-05-02 09:32:43 +00:00
const express = require('express');
const asyncHandler = require('express-async-handler');
const jwt = require('jsonwebtoken');
module.exports = (repository) =>
{
var router = express.Router();
router.post('/upload', asyncHandler(async (req, res) =>
{
if (!req.body.code)
{
res.sendStatus(400);
return;
}
var code = await repository.codes.get(req.body.code);
if (code !== null)
{
jwt.sign({
code: req.body.code,
codeUserId: code.userId,
codeExpirationDate: code.expirationDate
}, config.jwtSecret, (err, token) =>
{
if (err)
res.sendStatus(500);
else
res.send(token);
});
}
else
res.sendStatus(403);
}));
router.post('/login', asyncHandler(async (req, res) =>
{
if (!req.body.username || !req.body.password)
{
res.sendStatus(400);
return;
}
var user = await repository.users.getLoginUser(req.body.username, req.body.password);
if (user !== null)
{
jwt.sign({
userId: user.id
}, config.jwtSecret, (err, token) =>
{
if (err)
res.sendStatus(500);
else
res.send(token);
});
}
else
res.sendStatus(403);
}));
return router;
}