"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const entities_1 = require("../entities");
function getToken(context) {
    const req = context.request;
    const res = context.response;
    var token = context.cookies.get('access_token') ||
        req.headers['x-access-token'] ||
        req.headers['authorization'] ||
        req.query.token ||
        null;
    if (token && token.startsWith('Bearer ')) {
        // Remove Bearer from string
        return token.slice(7, token.length);
    }
    context.state.token = token;
    return token;
}
exports.getToken = getToken;
async function authMiddleware(context, next) {
    try {
        var token = getToken(context);
        if (!token) {
            throw Error('not logged in');
        }
        context.state.user = await entities_1.User.check(token);
        next();
    }
    catch (e) {
        context.status = 401;
        context.body = {
            success: false,
            message: e.message
        };
    }
}
exports.authMiddleware = authMiddleware;
//# sourceMappingURL=auth-middleware.js.map