Auth fixes

This commit is contained in:
Jori Lallo
2016-08-27 11:13:02 -07:00
parent ac6cf2ea8f
commit c28a403321

View File

@ -1,12 +1,17 @@
import httpErrors from 'http-errors';
import JWT from 'jsonwebtoken';
import { User } from '../../models';
import {
User,
ApiKey,
} from '../../models';
export default function auth({ require = true } = {}) {
return async function authMiddleware(ctx, next) {
let token;
console.log(ctx.body);
const authorizationHeader = ctx.request.get('authorization');
if (authorizationHeader) {
const parts = authorizationHeader.split(' ');
@ -23,6 +28,8 @@ export default function auth({ require = true } = {}) {
Format is "Authorization: Bearer <token>"\n`);
}
}
} else if (ctx.body.token) {
token = ctx.body.token;
} else if (ctx.request.query.token) {
token = ctx.request.query.token;
}
@ -32,21 +39,45 @@ export default function auth({ require = true } = {}) {
}
if (token) {
// Get user without verifying payload signature
let payload;
try {
payload = JWT.decode(token);
} catch (e) {
throw httpErrors.Unauthorized('Unable to decode JWT token');
}
const user = await User.findOne({
where: { id: payload.id },
});
let user;
try {
JWT.verify(token, user.jwtSecret);
} catch (e) {
throw httpErrors.Unauthorized('Invalid token');
if (token.match(/^[\w]{38}$/)) {
// API key
let apiKey;
try {
apiKey = await ApiKey.findOne({ where: {
secret: token,
} });
} catch (e) {
throw httpErrors.Unauthorized('Invalid api key');
}
user = await User.findOne({
where: { id: apiKey.userId },
});
if (!user) throw httpErrors.Unauthorized('Invalid token');
} else {
// JWT
// Get user without verifying payload signature
let payload;
try {
payload = JWT.decode(token);
} catch (e) {
throw httpErrors.Unauthorized('Unable to decode JWT token');
}
if (!payload) throw httpErrors.Unauthorized('Invalid token');
user = await User.findOne({
where: { id: payload.id },
});
try {
JWT.verify(token, user.jwtSecret);
} catch (e) {
throw httpErrors.Unauthorized('Invalid token');
}
}
ctx.state.token = token;