Recv/lib/api/token.js

63 lines
1.3 KiB
JavaScript
Raw Normal View History

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({
codeId: req.body.code,
codeUserId: code.userId
}, 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;
}