"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 express_1 = require("express");
const express_session_1 = __importDefault(require("express-session"));
const express_async_handler_1 = __importDefault(require("express-async-handler"));
const joi_1 = __importDefault(require("joi"));
const AuthService = __importStar(require("../services/auth"));
const grant_1 = __importDefault(require("grant"));
const get_grant_config_1 = __importDefault(require("../utils/get-grant-config"));
const get_email_from_profile_1 = __importDefault(require("../utils/get-email-from-profile"));
const invalid_payload_1 = require("../exceptions/invalid-payload");
const ActivityService = __importStar(require("../services/activity"));
const ms_1 = __importDefault(require("ms"));
const cookie_parser_1 = __importDefault(require("cookie-parser"));
const router = express_1.Router();
const loginSchema = joi_1.default.object({
    email: joi_1.default.string().email().required(),
    password: joi_1.default.string().required(),
    mode: joi_1.default.string().valid('cookie', 'json'),
});
router.post('/login', express_async_handler_1.default((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { error } = loginSchema.validate(req.body);
    if (error)
        throw new invalid_payload_1.InvalidPayloadException(error.message);
    const { email, password } = req.body;
    const mode = req.body.mode || 'json';
    const ip = req.ip;
    const userAgent = req.get('user-agent');
    const { accessToken, refreshToken, expires, id } = yield AuthService.authenticate({
        ip,
        userAgent,
        email,
        password,
    });
    ActivityService.createActivity({
        action: ActivityService.Action.AUTHENTICATE,
        collection: 'directus_users',
        item: id,
        ip: ip,
        user_agent: userAgent,
        action_by: id,
    });
    const payload = {
        data: { access_token: accessToken, expires },
    };
    if (mode === 'json') {
        payload.data.refresh_token = refreshToken;
    }
    if (mode === 'cookie') {
        res.cookie('directus_refresh_token', refreshToken, {
            httpOnly: true,
            maxAge: ms_1.default(process.env.REFRESH_TOKEN_TTL),
            secure: process.env.REFRESH_TOKEN_COOKIE_SECURE === 'true' ? true : false,
            sameSite: process.env.REFRESH_TOKEN_COOKIE_SAME_SITE ||
                'strict',
        });
    }
    return res.status(200).json(payload);
})));
router.post('/refresh', cookie_parser_1.default(), express_async_handler_1.default((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const currentRefreshToken = req.body.refresh_token || req.cookies.directus_refresh_token;
    if (!currentRefreshToken) {
        throw new invalid_payload_1.InvalidPayloadException(`"refresh_token" is required in either the JSON payload or Cookie`);
    }
    const mode = req.body.mode || req.body.refresh_token ? 'json' : 'cookie';
    const { accessToken, refreshToken, expires } = yield AuthService.refresh(currentRefreshToken);
    const payload = {
        data: { access_token: accessToken, expires },
    };
    if (mode === 'json') {
        payload.data.refresh_token = refreshToken;
    }
    if (mode === 'cookie') {
        res.cookie('directus_refresh_token', refreshToken, {
            httpOnly: true,
            maxAge: ms_1.default(process.env.REFRESH_TOKEN_TTL),
            secure: process.env.REFRESH_TOKEN_COOKIE_SECURE === 'true' ? true : false,
            sameSite: process.env.REFRESH_TOKEN_COOKIE_SAME_SITE ||
                'strict',
        });
    }
    return res.status(200).json(payload);
})));
router.post('/logout', cookie_parser_1.default(), express_async_handler_1.default((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const currentRefreshToken = req.body.refresh_token || req.cookies.directus_refresh_token;
    if (!currentRefreshToken) {
        throw new invalid_payload_1.InvalidPayloadException(`"refresh_token" is required in either the JSON payload or Cookie`);
    }
    yield AuthService.logout(currentRefreshToken);
    res.status(200).end();
})));
router.use('/sso', express_session_1.default({ secret: process.env.SECRET, saveUninitialized: false, resave: false }));
router.use(grant_1.default.express()(get_grant_config_1.default()));
/**
 * @todo allow json / cookie mode in SSO
 */
router.get('/sso/:provider/callback', express_async_handler_1.default((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const email = get_email_from_profile_1.default(req.params.provider, req.session.grant.response.profile);
    const { accessToken, refreshToken, expires, id } = yield AuthService.authenticate(email);
    ActivityService.createActivity({
        action: ActivityService.Action.AUTHENTICATE,
        collection: 'directus_users',
        item: id,
        ip: req.ip,
        user_agent: req.get('user-agent'),
        action_by: id,
    });
    return res.status(200).json({
        data: { access_token: accessToken, refresh_token: refreshToken, expires },
    });
})));
exports.default = router;
