"use strict";
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 });
exports.logout = exports.refresh = exports.authenticate = void 0;
const database_1 = __importDefault(require("../database"));
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const argon2_1 = __importDefault(require("argon2"));
const nanoid_1 = require("nanoid");
const ms_1 = __importDefault(require("ms"));
const exceptions_1 = require("../exceptions");
/**
 * Retrieve the tokens for a given user email.
 *
 * Password is optional to allow usage of this function within the SSO flow and extensions. Make sure
 * to handle password existence checks elsewhere
 */
exports.authenticate = ({ email, password, ip, userAgent }) => __awaiter(void 0, void 0, void 0, function* () {
    const user = yield database_1.default
        .select('id', 'password', 'role')
        .from('directus_users')
        .where({ email })
        .first();
    /** @todo check for status */
    if (!user) {
        throw new exceptions_1.InvalidCredentialsException();
    }
    if (password !== undefined && (yield argon2_1.default.verify(user.password, password)) === false) {
        throw new exceptions_1.InvalidCredentialsException();
    }
    const payload = {
        id: user.id,
    };
    /**
     * @TODO
     * Sign token with combination of server secret + user password hash
     * That way, old tokens are immediately invalidated whenever the user changes their password
     */
    const accessToken = jsonwebtoken_1.default.sign(payload, process.env.SECRET, {
        expiresIn: process.env.ACCESS_TOKEN_TTL,
    });
    const refreshToken = nanoid_1.nanoid(64);
    const refreshTokenExpiration = new Date(Date.now() + ms_1.default(process.env.REFRESH_TOKEN_TTL));
    yield database_1.default('directus_sessions').insert({
        token: refreshToken,
        user: user.id,
        expires: refreshTokenExpiration,
        ip,
        user_agent: userAgent,
    });
    return {
        accessToken,
        refreshToken,
        expires: ms_1.default(process.env.ACCESS_TOKEN_TTL) / 1000,
        id: user.id,
    };
});
exports.refresh = (refreshToken) => __awaiter(void 0, void 0, void 0, function* () {
    if (!refreshToken) {
        throw new exceptions_1.InvalidCredentialsException();
    }
    const record = yield database_1.default
        .select('directus_sessions.*', 'directus_users.email')
        .from('directus_sessions')
        .where({ 'directus_sessions.token': refreshToken })
        .leftJoin('directus_users', 'directus_sessions.user', 'directus_users.id')
        .first();
    /** @todo
     * Check if it's worth checking for ip address and/or user agent. We could make this a little
     * more secure by requiring the refresh token to be used from the same device / location as the
     * auth session was created in the first place
     */
    if (!record || !record.email || record.expires < new Date()) {
        throw new exceptions_1.InvalidCredentialsException();
    }
    yield database_1.default.delete().from('directus_sessions').where({ token: refreshToken });
    return yield exports.authenticate({ email: record.email, ip: record.ip, userAgent: record.user_agent });
});
exports.logout = (refreshToken) => __awaiter(void 0, void 0, void 0, function* () {
    yield database_1.default.delete().from('directus_sessions').where({ token: refreshToken });
});
