"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const jsonwebtoken_1 = __importStar(require("jsonwebtoken"));
const is_jwt_1 = __importDefault(require("../utils/is-jwt"));
const database_1 = __importDefault(require("../database"));
const express_async_handler_1 = __importDefault(require("express-async-handler"));
const exceptions_1 = require("../exceptions");
/**
 * Verify the passed JWT and assign the user ID and role to `req`
 */
const authenticate = express_async_handler_1.default((req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
    req.user = null;
    req.role = null;
    req.admin = false;
    if (!req.token)
        return next();
    if (is_jwt_1.default(req.token)) {
        let payload;
        try {
            payload = jsonwebtoken_1.default.verify(req.token, process.env.SECRET);
        }
        catch (err) {
            if (err instanceof jsonwebtoken_1.TokenExpiredError) {
                throw new exceptions_1.InvalidCredentialsException('Token expired.');
            }
            else {
                throw err;
            }
        }
        const user = yield database_1.default
            .select('role', 'directus_roles.admin')
            .from('directus_users')
            .leftJoin('directus_roles', 'directus_users.role', 'directus_roles.id')
            .where({ 'directus_users.id': payload.id })
            .first();
        /** @TODO verify user status */
        req.user = payload.id;
        req.role = user.role;
        req.admin = user.admin;
        return next();
    }
    /**
     * @TODO
     * Implement static tokens
     *
     * @NOTE
     * We'll silently ignore wrong tokens. This makes sure we prevent brute-forcing static tokens
     */
    return next();
}));
exports.default = authenticate;
