"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 __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupAuthRoutes = setupAuthRoutes;
var express = require("express");
var handlebars = require("handlebars");
var jwt = require("jsonwebtoken");
var jwt_decode_1 = require("jwt-decode");
var simpl_schema_1 = require("simpl-schema");
var user_collection_1 = require("../collections/user.collection");
var resolveio_server_app_1 = require("../resolveio-server-app");
var common_1 = require("../util/common");
var error_reporter_1 = require("../util/error-reporter");
function reportHttpValidationError(route, body, errors) {
    return __awaiter(this, void 0, void 0, function () {
        var correlationId, config;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    correlationId = (0, common_1.objectIdHexString)();
                    config = resolveio_server_app_1.ResolveIOServer.getServerConfig();
                    return [4 /*yield*/, error_reporter_1.ErrorReporter.report({
                            sourceApp: 'http-auth',
                            message: 'HTTP Validation Error - ' + route,
                            environment: config === null || config === void 0 ? void 0 : config.ROOT_URL,
                            clientSlug: resolveio_server_app_1.ResolveIOServer.getClientName(),
                            clientName: config === null || config === void 0 ? void 0 : config.CLIENT_NAME,
                            context: {
                                route: route,
                                body: body,
                                errors: errors
                            },
                            metadata: {
                                context: 'http-validation',
                                route: route,
                                correlationId: correlationId
                            },
                            correlationId: correlationId
                        })];
                case 1:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
function isEnrollmentPhoneVerificationRequired(body) {
    var value = body === null || body === void 0 ? void 0 : body.requireEnrollmentPhoneVerification;
    return value === true || String(value || '').toLowerCase() === 'true';
}
function normalizePhoneNumberDigits(value) {
    return String(value || '').replace(/\D/g, '');
}
function setupAuthRoutes(mainServer, app, serverConfig) {
    var _this = this;
    app.post('/login365', express.json(), function (request, response) { return __awaiter(_this, void 0, void 0, function () {
        var body, schema, errors_1, tokenData, token, decodedJWT, user, update;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!!(0, common_1.isAllowedOrigin)(request.headers.origin, serverConfig)) return [3 /*break*/, 1];
                    response.send(JSON.stringify({
                        error: true,
                        result: 'Invalid header'
                    }));
                    return [3 /*break*/, 16];
                case 1:
                    body = request.body;
                    schema = new simpl_schema_1.default({
                        id_token: {
                            type: String
                        }
                    });
                    _a.label = 2;
                case 2:
                    _a.trys.push([2, 3, , 6]);
                    schema.validate(body);
                    return [3 /*break*/, 6];
                case 3:
                    errors_1 = _a.sent();
                    if (!errors_1) return [3 /*break*/, 5];
                    console.error(new Date(), 'Error in HTTP Check (/login)', errors_1);
                    return [4 /*yield*/, reportHttpValidationError('/login365', body, errors_1)];
                case 4:
                    _a.sent();
                    response.send(JSON.stringify({
                        error: true,
                        result: 'Invalid Parameters'
                    }));
                    return [2 /*return*/];
                case 5: return [3 /*break*/, 6];
                case 6:
                    tokenData = body.id_token.split('&');
                    token = tokenData[0].split('=')[1];
                    decodedJWT = (0, jwt_decode_1.jwtDecode)(token);
                    if (!(decodedJWT && decodedJWT['name'] && decodedJWT['preferred_username'] && decodedJWT['oid'])) return [3 /*break*/, 15];
                    return [4 /*yield*/, user_collection_1.Users.findOne({ 'other.ms_oid': decodedJWT['oid'] })];
                case 7:
                    user = _a.sent();
                    if (!!user) return [3 /*break*/, 10];
                    return [4 /*yield*/, user_collection_1.Users.findOne({ email: decodedJWT['preferred_username'].toLowerCase() })];
                case 8:
                    user = _a.sent();
                    if (!user) return [3 /*break*/, 10];
                    return [4 /*yield*/, user_collection_1.Users.updateOne({ _id: user._id }, { $set: { 'other.ms_oid': decodedJWT['oid'] } })];
                case 9:
                    _a.sent();
                    _a.label = 10;
                case 10:
                    if (!!user) return [3 /*break*/, 12];
                    user = {
                        _id: (0, common_1.objectIdHexString)(),
                        __v: 0,
                        roles: {
                            super_admin: false,
                            approvals: [],
                            groups: [],
                            notifications: [],
                            miscs: []
                        },
                        username: decodedJWT['preferred_username'].toLowerCase(),
                        email: decodedJWT['preferred_username'].toLowerCase(),
                        fullname: decodedJWT['name'],
                        active: true,
                        phonenumber: '',
                        readonly: false,
                        other: {
                            ms_oid: decodedJWT['oid']
                        },
                        attempts: 0,
                        salt: jwt.sign({ now: (Date.now() - 1000).toString() }, serverConfig['JWT_SECRET'], {
                            expiresIn: 90 * 24 * 60 * 60 * 1000 // 90 days
                        }),
                        hash: jwt.sign({ now: (Date.now() + 1000).toString() }, serverConfig['JWT_SECRET'], {
                            expiresIn: 90 * 24 * 60 * 60 * 1000 // 90 days
                        }),
                        last: new Date(),
                        settings: null,
                        services: null,
                        is_customer: false
                    };
                    return [4 /*yield*/, user_collection_1.Users.create(user)];
                case 11:
                    _a.sent();
                    return [3 /*break*/, 14];
                case 12:
                    update = false;
                    if (user.email !== decodedJWT['preferred_username'].toLowerCase()) {
                        user.email = decodedJWT['preferred_username'].toLowerCase();
                        update = true;
                    }
                    if (user.fullname !== decodedJWT['name']) {
                        user.fullname = decodedJWT['name'];
                        update = true;
                    }
                    if (!update) return [3 /*break*/, 14];
                    return [4 /*yield*/, user_collection_1.Users.updateOne({ _id: user._id }, { $set: { email: user.email, fullname: user.fullname } })];
                case 13:
                    _a.sent();
                    _a.label = 14;
                case 14:
                    response.send(JSON.stringify({
                        error: false,
                        result: {
                            token: jwt.sign({ id_user: user._id }, serverConfig['JWT_SECRET'], {
                                expiresIn: 90 * 24 * 60 * 60 * 1000 // 90 days
                            })
                        }
                    }));
                    return [3 /*break*/, 16];
                case 15:
                    console.log('ERROR - 1', tokenData, token, decodedJWT);
                    response.send(JSON.stringify({
                        error: true,
                        result: 'Invalid Azure Token'
                    }));
                    _a.label = 16;
                case 16: return [2 /*return*/];
            }
        });
    }); });
    // Login via HTTP, return refresh token if authenticated
    app.post('/login', express.json(), function (request, response) { return __awaiter(_this, void 0, void 0, function () {
        var body, schema, errors_2, user, resAuth, emailData, html, template, emailData, html, template;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!!(0, common_1.isAllowedOrigin)(request.headers.origin, serverConfig)) return [3 /*break*/, 1];
                    response.send(JSON.stringify({
                        error: true,
                        result: 'Invalid header'
                    }));
                    return [3 /*break*/, 20];
                case 1:
                    body = request.body;
                    schema = new simpl_schema_1.default({
                        username: {
                            type: String
                        },
                        password: {
                            type: String
                        }
                    });
                    _a.label = 2;
                case 2:
                    _a.trys.push([2, 3, , 6]);
                    schema.validate(body);
                    return [3 /*break*/, 6];
                case 3:
                    errors_2 = _a.sent();
                    if (!errors_2) return [3 /*break*/, 5];
                    console.error(new Date(), 'Error in HTTP Check (/login)', errors_2);
                    return [4 /*yield*/, reportHttpValidationError('/login', body, errors_2)];
                case 4:
                    _a.sent();
                    response.send(JSON.stringify({
                        error: true,
                        result: 'Invalid Parameters'
                    }));
                    return [2 /*return*/];
                case 5: return [3 /*break*/, 6];
                case 6: return [4 /*yield*/, user_collection_1.Users.findOne({ active: true, username: body.username })];
                case 7:
                    user = _a.sent();
                    if (!!user) return [3 /*break*/, 9];
                    return [4 /*yield*/, user_collection_1.Users.findOne({ active: true, email: body.username })];
                case 8:
                    user = _a.sent();
                    _a.label = 9;
                case 9:
                    if (!user) {
                        response.send(JSON.stringify({
                            error: true,
                            result: 'Invalid Username And Password'
                        }));
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, user_collection_1.Users.authenticate(user, body.password)];
                case 10:
                    resAuth = _a.sent();
                    if (!resAuth['error']) return [3 /*break*/, 18];
                    if (!(resAuth['error'] === 'Too Many Attempts')) return [3 /*break*/, 13];
                    response.send(JSON.stringify({
                        error: true,
                        result: resAuth['error'] + '.  A password reset link has been sent to your email, please reset your password.'
                    }));
                    if (!user.services) {
                        user.services = {};
                    }
                    user.services['forgot_password'] = jwt.sign({ id_user: user._id }, serverConfig['JWT_SECRET']);
                    emailData = {
                        userToChangePassword: user.fullname,
                        userWhoResetPassword: resolveio_server_app_1.ResolveIOServer.getClientName() + ' System',
                        url: (serverConfig['ROOT_URL'] + '/forgot-password?' + encodeURIComponent(serverConfig['SERVER_URL']) + '&' + user.services['forgot_password'])
                    };
                    return [4 /*yield*/, user_collection_1.Users.updateOne({ _id: user._id }, { $set: { services: user.services } })];
                case 11:
                    _a.sent();
                    html = mainServer.getMethodManager().readFile('email-templates/forgot-password.html');
                    template = handlebars.compile(html);
                    handlebars.registerHelper('equals', function (a, b) {
                        return a === b;
                    });
                    return [4 /*yield*/, mainServer.getMethodManager().sendEmail(user.email, 'ResolveIO (' + resolveio_server_app_1.ResolveIOServer.getClientName() + ') - Forgot Password', '', template(emailData), null, null, '')];
                case 12:
                    _a.sent();
                    return [3 /*break*/, 17];
                case 13:
                    if (!(resAuth['error'] === 'No Salt Value Stored')) return [3 /*break*/, 16];
                    response.send(JSON.stringify({
                        error: true,
                        result: 'A password reset link has been sent to your email, please reset your password.'
                    }));
                    if (!user.services) {
                        user.services = {};
                    }
                    user.services['forgot_password'] = jwt.sign({ id_user: user._id }, serverConfig['JWT_SECRET']);
                    emailData = {
                        userToChangePassword: user.fullname,
                        userWhoResetPassword: resolveio_server_app_1.ResolveIOServer.getClientName() + ' System',
                        url: (serverConfig['ROOT_URL'] + '/forgot-password?' + encodeURIComponent(serverConfig['SERVER_URL']) + '&' + user.services['forgot_password'])
                    };
                    return [4 /*yield*/, user_collection_1.Users.updateOne({ _id: user._id }, { $set: { services: user.services } })];
                case 14:
                    _a.sent();
                    html = mainServer.getMethodManager().readFile('email-templates/forgot-password.html');
                    template = handlebars.compile(html);
                    handlebars.registerHelper('equals', function (a, b) {
                        return a === b;
                    });
                    return [4 /*yield*/, mainServer.getMethodManager().sendEmail(user.email, 'ResolveIO (' + resolveio_server_app_1.ResolveIOServer.getClientName() + ') - Forgot Password', '', template(emailData), null, null, '')];
                case 15:
                    _a.sent();
                    return [3 /*break*/, 17];
                case 16:
                    response.send(JSON.stringify({
                        error: true,
                        result: resAuth['error']
                    }));
                    _a.label = 17;
                case 17: return [3 /*break*/, 20];
                case 18:
                    if (!(resAuth && resAuth['data'] && resAuth['data'].active)) return [3 /*break*/, 20];
                    return [4 /*yield*/, user_collection_1.Users.resetAttempts(resAuth['data'])];
                case 19:
                    _a.sent();
                    response.send(JSON.stringify({
                        error: false,
                        result: {
                            token: jwt.sign({ id_user: resAuth['data']._id }, serverConfig['JWT_SECRET'], {
                                expiresIn: 90 * 24 * 60 * 60 * 1000 // 90 days
                            })
                        }
                    }));
                    _a.label = 20;
                case 20: return [2 /*return*/];
            }
        });
    }); });
    app.post('/accessToken', express.json(), function (request, response) { return __awaiter(_this, void 0, void 0, function () {
        var body, schema, errors_3;
        var _this = this;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!!(0, common_1.isAllowedOrigin)(request.headers.origin, serverConfig)) return [3 /*break*/, 1];
                    response.send(JSON.stringify({
                        error: true,
                        result: 'Invalid header'
                    }));
                    return [3 /*break*/, 7];
                case 1:
                    body = request.body;
                    schema = new simpl_schema_1.default({
                        refreshToken: {
                            type: String
                        }
                    });
                    _a.label = 2;
                case 2:
                    _a.trys.push([2, 3, , 6]);
                    schema.validate(body);
                    return [3 /*break*/, 6];
                case 3:
                    errors_3 = _a.sent();
                    if (!errors_3) return [3 /*break*/, 5];
                    console.error(new Date(), 'Error in HTTP Check (/accessToken)', errors_3);
                    return [4 /*yield*/, reportHttpValidationError('/accessToken', body, errors_3)];
                case 4:
                    _a.sent();
                    response.send(JSON.stringify({
                        error: true,
                        result: 'Invalid Parameters'
                    }));
                    return [2 /*return*/];
                case 5: return [3 /*break*/, 6];
                case 6:
                    jwt.verify(body.refreshToken, serverConfig['JWT_SECRET'], function (err, decoded) { return __awaiter(_this, void 0, void 0, function () {
                        var user, _a;
                        return __generator(this, function (_b) {
                            switch (_b.label) {
                                case 0:
                                    if (!err) return [3 /*break*/, 1];
                                    response.send(JSON.stringify({
                                        error: true,
                                        result: 'Invalid Token'
                                    }));
                                    return [3 /*break*/, 4];
                                case 1:
                                    _b.trys.push([1, 3, , 4]);
                                    return [4 /*yield*/, user_collection_1.Users.findById(decoded['id_user'])];
                                case 2:
                                    user = _b.sent();
                                    if (user) {
                                        if (user.active) {
                                            response.send(JSON.stringify({
                                                error: false,
                                                result: {
                                                    token: jwt.sign({ id_user: user._id }, serverConfig['JWT_SECRET'], {
                                                        expiresIn: 3 * 24 * 60 * 60 * 1000 // 3 days
                                                    }),
                                                    user: user
                                                }
                                            }));
                                        }
                                        else {
                                            response.send(JSON.stringify({
                                                error: true,
                                                result: 'Account is Disabled'
                                            }));
                                        }
                                    }
                                    else {
                                        response.send(JSON.stringify({
                                            error: true,
                                            result: 'Invalid User'
                                        }));
                                    }
                                    return [3 /*break*/, 4];
                                case 3:
                                    _a = _b.sent();
                                    response.send(JSON.stringify({
                                        error: true,
                                        result: 'Invalid Mongo Get User'
                                    }));
                                    return [3 /*break*/, 4];
                                case 4: return [2 /*return*/];
                            }
                        });
                    }); });
                    _a.label = 7;
                case 7: return [2 /*return*/];
            }
        });
    }); });
    app.post('/userWithEnrollmentToken', express.json(), function (request, response) { return __awaiter(_this, void 0, void 0, function () {
        var body_1, schema, errors_4;
        var _this = this;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!!(0, common_1.isAllowedOrigin)(request.headers.origin, serverConfig)) return [3 /*break*/, 1];
                    response.send(JSON.stringify({
                        error: true,
                        result: 'Invalid header'
                    }));
                    return [3 /*break*/, 7];
                case 1:
                    body_1 = request.body;
                    schema = new simpl_schema_1.default({
                        enrollmentToken: {
                            type: String
                        }
                    });
                    _a.label = 2;
                case 2:
                    _a.trys.push([2, 3, , 6]);
                    schema.validate(body_1);
                    return [3 /*break*/, 6];
                case 3:
                    errors_4 = _a.sent();
                    if (!errors_4) return [3 /*break*/, 5];
                    console.error(new Date(), 'Error in HTTP Check (/userWithEnrollmentToken)', errors_4);
                    return [4 /*yield*/, reportHttpValidationError('/userWithEnrollmentToken', body_1, errors_4)];
                case 4:
                    _a.sent();
                    response.send(JSON.stringify({
                        error: true,
                        result: 'Invalid Parameters'
                    }));
                    return [2 /*return*/];
                case 5: return [3 /*break*/, 6];
                case 6:
                    jwt.verify(body_1.enrollmentToken, serverConfig['JWT_SECRET'], function (err, decoded) { return __awaiter(_this, void 0, void 0, function () {
                        var user, _a;
                        return __generator(this, function (_b) {
                            switch (_b.label) {
                                case 0:
                                    if (!err) return [3 /*break*/, 1];
                                    response.send(JSON.stringify({
                                        error: true,
                                        result: 'Invalid Token'
                                    }));
                                    return [3 /*break*/, 4];
                                case 1:
                                    _b.trys.push([1, 3, , 4]);
                                    return [4 /*yield*/, user_collection_1.Users.findOne({
                                            $and: [
                                                { _id: decoded['id_user'] },
                                                { 'services.enrollment': body_1.enrollmentToken }
                                            ]
                                        }, { projection: { _id: 1, __v: 1, username: 1, active: 1 } })];
                                case 2:
                                    user = _b.sent();
                                    if (user) {
                                        if (user.active) {
                                            response.send(JSON.stringify({
                                                error: false,
                                                result: {
                                                    user: user
                                                }
                                            }));
                                        }
                                        else {
                                            response.send(JSON.stringify({
                                                error: true,
                                                result: 'Account is Disabled'
                                            }));
                                        }
                                    }
                                    else {
                                        response.send(JSON.stringify({
                                            error: true,
                                            result: 'Invalid User'
                                        }));
                                    }
                                    return [3 /*break*/, 4];
                                case 3:
                                    _a = _b.sent();
                                    response.send(JSON.stringify({
                                        error: true,
                                        result: 'Invalid Mongo Get User'
                                    }));
                                    return [3 /*break*/, 4];
                                case 4: return [2 /*return*/];
                            }
                        });
                    }); });
                    _a.label = 7;
                case 7: return [2 /*return*/];
            }
        });
    }); });
    app.post('/setUserWithEnrollmentToken', express.json(), function (request, response) { return __awaiter(_this, void 0, void 0, function () {
        var body_2, schema, errors_5;
        var _this = this;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!!(0, common_1.isAllowedOrigin)(request.headers.origin, serverConfig)) return [3 /*break*/, 1];
                    response.send(JSON.stringify({
                        error: true,
                        result: 'Invalid header'
                    }));
                    return [3 /*break*/, 7];
                case 1:
                    body_2 = request.body;
                    schema = new simpl_schema_1.default({
                        enrollmentToken: {
                            type: String
                        },
                        password: {
                            type: String
                        },
                        phonenumber: {
                            type: String,
                            optional: true
                        },
                        requireEnrollmentPhoneVerification: {
                            type: Boolean,
                            optional: true
                        }
                    });
                    _a.label = 2;
                case 2:
                    _a.trys.push([2, 3, , 6]);
                    schema.validate(body_2);
                    return [3 /*break*/, 6];
                case 3:
                    errors_5 = _a.sent();
                    if (!errors_5) return [3 /*break*/, 5];
                    console.error(new Date(), 'Error in HTTP Check (/setUserWithEnrollmentToken)', errors_5);
                    return [4 /*yield*/, reportHttpValidationError('/setUserWithEnrollmentToken', body_2, errors_5)];
                case 4:
                    _a.sent();
                    response.send(JSON.stringify({
                        error: true,
                        result: 'Invalid Parameters'
                    }));
                    return [2 /*return*/];
                case 5: return [3 /*break*/, 6];
                case 6:
                    jwt.verify(body_2.enrollmentToken, serverConfig['JWT_SECRET'], function (err, decoded) { return __awaiter(_this, void 0, void 0, function () {
                        var user, submittedPhone, userPhone, _a;
                        return __generator(this, function (_b) {
                            switch (_b.label) {
                                case 0:
                                    if (!err) return [3 /*break*/, 1];
                                    response.send(JSON.stringify({
                                        error: true,
                                        result: 'Invalid Token'
                                    }));
                                    return [3 /*break*/, 9];
                                case 1:
                                    _b.trys.push([1, 8, , 9]);
                                    return [4 /*yield*/, user_collection_1.Users.findOne({
                                            $and: [
                                                { _id: decoded['id_user'] },
                                                { 'services.enrollment': body_2.enrollmentToken }
                                            ]
                                        })];
                                case 2:
                                    user = _b.sent();
                                    if (!user) return [3 /*break*/, 6];
                                    if (!user.active) return [3 /*break*/, 4];
                                    if (isEnrollmentPhoneVerificationRequired(body_2)) {
                                        submittedPhone = normalizePhoneNumberDigits(body_2.phonenumber);
                                        userPhone = normalizePhoneNumberDigits(user.phonenumber);
                                        if (!submittedPhone || !userPhone || submittedPhone !== userPhone) {
                                            response.send(JSON.stringify({
                                                error: true,
                                                result: 'Invalid Phone Number'
                                            }));
                                            return [2 /*return*/];
                                        }
                                    }
                                    return [4 /*yield*/, user_collection_1.Users.setPassword(user, body_2.password)];
                                case 3:
                                    _b.sent();
                                    response.send(JSON.stringify({
                                        error: false,
                                        result: true
                                    }));
                                    return [3 /*break*/, 5];
                                case 4:
                                    response.send(JSON.stringify({
                                        error: true,
                                        result: 'Account is Disabled'
                                    }));
                                    _b.label = 5;
                                case 5: return [3 /*break*/, 7];
                                case 6:
                                    response.send(JSON.stringify({
                                        error: true,
                                        result: 'Invalid User'
                                    }));
                                    _b.label = 7;
                                case 7: return [3 /*break*/, 9];
                                case 8:
                                    _a = _b.sent();
                                    response.send(JSON.stringify({
                                        error: true,
                                        result: 'Invalid Mongo Get User'
                                    }));
                                    return [3 /*break*/, 9];
                                case 9: return [2 /*return*/];
                            }
                        });
                    }); });
                    _a.label = 7;
                case 7: return [2 /*return*/];
            }
        });
    }); });
    app.post('/userWithForgotPasswordToken', express.json(), function (request, response) { return __awaiter(_this, void 0, void 0, function () {
        var body_3, schema, errors_6;
        var _this = this;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!!(0, common_1.isAllowedOrigin)(request.headers.origin, serverConfig)) return [3 /*break*/, 1];
                    response.send(JSON.stringify({
                        error: true,
                        result: 'Invalid header'
                    }));
                    return [3 /*break*/, 7];
                case 1:
                    body_3 = request.body;
                    schema = new simpl_schema_1.default({
                        forgotPasswordToken: {
                            type: String
                        }
                    });
                    _a.label = 2;
                case 2:
                    _a.trys.push([2, 3, , 6]);
                    schema.validate(body_3);
                    return [3 /*break*/, 6];
                case 3:
                    errors_6 = _a.sent();
                    if (!errors_6) return [3 /*break*/, 5];
                    console.error(new Date(), 'Error in HTTP Check (/userWithForgotPasswordToken)', errors_6);
                    return [4 /*yield*/, reportHttpValidationError('/userWithForgotPasswordToken', body_3, errors_6)];
                case 4:
                    _a.sent();
                    response.send(JSON.stringify({
                        error: true,
                        result: 'Invalid Parameters'
                    }));
                    return [2 /*return*/];
                case 5: return [3 /*break*/, 6];
                case 6:
                    jwt.verify(body_3.forgotPasswordToken, serverConfig['JWT_SECRET'], function (err, decoded) { return __awaiter(_this, void 0, void 0, function () {
                        var user, _a;
                        return __generator(this, function (_b) {
                            switch (_b.label) {
                                case 0:
                                    if (!err) return [3 /*break*/, 1];
                                    response.send(JSON.stringify({
                                        error: true,
                                        result: 'Invalid Token'
                                    }));
                                    return [3 /*break*/, 4];
                                case 1:
                                    _b.trys.push([1, 3, , 4]);
                                    return [4 /*yield*/, user_collection_1.Users.findOne({
                                            $and: [
                                                { _id: decoded['id_user'] },
                                                { 'services.forgot_password': body_3.forgotPasswordToken }
                                            ]
                                        }, { projection: { _id: 1, __v: 1, username: 1, active: 1 } })];
                                case 2:
                                    user = _b.sent();
                                    if (user) {
                                        if (user.active) {
                                            response.send(JSON.stringify({
                                                error: false,
                                                result: {
                                                    user: user
                                                }
                                            }));
                                        }
                                        else {
                                            response.send(JSON.stringify({
                                                error: true,
                                                result: 'Account is Disabled'
                                            }));
                                        }
                                    }
                                    else {
                                        response.send(JSON.stringify({
                                            error: true,
                                            result: 'Invalid Token'
                                        }));
                                    }
                                    return [3 /*break*/, 4];
                                case 3:
                                    _a = _b.sent();
                                    response.send(JSON.stringify({
                                        error: true,
                                        result: 'Invalid Mongo Get User'
                                    }));
                                    return [3 /*break*/, 4];
                                case 4: return [2 /*return*/];
                            }
                        });
                    }); });
                    _a.label = 7;
                case 7: return [2 /*return*/];
            }
        });
    }); });
    app.post('/setUserWithForgotPasswordToken', express.json(), function (request, response) { return __awaiter(_this, void 0, void 0, function () {
        var body_4, schema, errors_7;
        var _this = this;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!!(0, common_1.isAllowedOrigin)(request.headers.origin, serverConfig)) return [3 /*break*/, 1];
                    response.send(JSON.stringify({
                        error: true,
                        result: 'Invalid header'
                    }));
                    return [3 /*break*/, 7];
                case 1:
                    body_4 = request.body;
                    schema = new simpl_schema_1.default({
                        forgotPasswordToken: {
                            type: String
                        },
                        password: {
                            type: String
                        },
                        phonenumber: {
                            type: String,
                            optional: true
                        },
                        requireEnrollmentPhoneVerification: {
                            type: Boolean,
                            optional: true
                        }
                    });
                    _a.label = 2;
                case 2:
                    _a.trys.push([2, 3, , 6]);
                    schema.validate(body_4);
                    return [3 /*break*/, 6];
                case 3:
                    errors_7 = _a.sent();
                    if (!errors_7) return [3 /*break*/, 5];
                    console.error(new Date(), 'Error in HTTP Check (/setUserWithForgotPasswordToken)', errors_7);
                    return [4 /*yield*/, reportHttpValidationError('/setUserWithForgotPasswordToken', body_4, errors_7)];
                case 4:
                    _a.sent();
                    response.send(JSON.stringify({
                        error: true,
                        result: 'Invalid Parameters'
                    }));
                    return [2 /*return*/];
                case 5: return [3 /*break*/, 6];
                case 6:
                    jwt.verify(body_4.forgotPasswordToken, serverConfig['JWT_SECRET'], function (err, decoded) { return __awaiter(_this, void 0, void 0, function () {
                        var user, submittedPhone, userPhone, _a;
                        return __generator(this, function (_b) {
                            switch (_b.label) {
                                case 0:
                                    if (!err) return [3 /*break*/, 1];
                                    response.send(JSON.stringify({
                                        error: true,
                                        result: 'Invalid Token'
                                    }));
                                    return [3 /*break*/, 9];
                                case 1:
                                    _b.trys.push([1, 8, , 9]);
                                    return [4 /*yield*/, user_collection_1.Users.findOne({
                                            $and: [
                                                { _id: decoded['id_user'] },
                                                { 'services.forgot_password': body_4.forgotPasswordToken }
                                            ]
                                        })];
                                case 2:
                                    user = _b.sent();
                                    if (!user) return [3 /*break*/, 6];
                                    if (!user.active) return [3 /*break*/, 4];
                                    if (isEnrollmentPhoneVerificationRequired(body_4)) {
                                        submittedPhone = normalizePhoneNumberDigits(body_4.phonenumber);
                                        userPhone = normalizePhoneNumberDigits(user.phonenumber);
                                        if (!submittedPhone || !userPhone || submittedPhone !== userPhone) {
                                            response.send(JSON.stringify({
                                                error: true,
                                                result: 'Invalid Phone Number'
                                            }));
                                            return [2 /*return*/];
                                        }
                                    }
                                    return [4 /*yield*/, user_collection_1.Users.setPassword(user, body_4.password)];
                                case 3:
                                    _b.sent();
                                    response.send(JSON.stringify({
                                        error: false,
                                        result: true
                                    }));
                                    return [3 /*break*/, 5];
                                case 4:
                                    response.send(JSON.stringify({
                                        error: true,
                                        result: 'Account is Disabled'
                                    }));
                                    _b.label = 5;
                                case 5: return [3 /*break*/, 7];
                                case 6:
                                    response.send(JSON.stringify({
                                        error: true,
                                        result: 'Invalid User'
                                    }));
                                    _b.label = 7;
                                case 7: return [3 /*break*/, 9];
                                case 8:
                                    _a = _b.sent();
                                    response.send(JSON.stringify({
                                        error: true,
                                        result: 'Invalid Mongo Get User'
                                    }));
                                    return [3 /*break*/, 9];
                                case 9: return [2 /*return*/];
                            }
                        });
                    }); });
                    _a.label = 7;
                case 7: return [2 /*return*/];
            }
        });
    }); });
    app.post('/resetPassword', express.json(), function (request, response) { return __awaiter(_this, void 0, void 0, function () {
        var body, schema, errors_8, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!!(0, common_1.isAllowedOrigin)(request.headers.origin, serverConfig)) return [3 /*break*/, 1];
                    response.send(JSON.stringify({
                        error: true,
                        result: 'Invalid header'
                    }));
                    return [3 /*break*/, 12];
                case 1:
                    body = request.body;
                    schema = new simpl_schema_1.default({
                        username: {
                            type: String
                        }
                    });
                    _a.label = 2;
                case 2:
                    _a.trys.push([2, 3, , 6]);
                    schema.validate(body);
                    return [3 /*break*/, 6];
                case 3:
                    errors_8 = _a.sent();
                    if (!errors_8) return [3 /*break*/, 5];
                    console.error(new Date(), 'Error in HTTP Check (/resetPassword)', errors_8);
                    return [4 /*yield*/, reportHttpValidationError('/resetPassword', body, errors_8)];
                case 4:
                    _a.sent();
                    response.send(JSON.stringify({
                        error: true,
                        result: 'Invalid Parameters'
                    }));
                    return [2 /*return*/];
                case 5: return [3 /*break*/, 6];
                case 6: return [4 /*yield*/, user_collection_1.Users.findOne({ active: true, username: body.username })];
                case 7:
                    user = _a.sent();
                    if (!!user) return [3 /*break*/, 9];
                    return [4 /*yield*/, user_collection_1.Users.findOne({ active: true, email: body.username })];
                case 8:
                    user = _a.sent();
                    _a.label = 9;
                case 9:
                    if (!user) return [3 /*break*/, 11];
                    return [4 /*yield*/, mainServer.getMethodManager().callMethod.call(mainServer.getMethodManager(), 'resetUserPassword', user._id)];
                case 10:
                    _a.sent();
                    _a.label = 11;
                case 11:
                    response.send(JSON.stringify({
                        error: false,
                        result: ''
                    }));
                    _a.label = 12;
                case 12: return [2 /*return*/];
            }
        });
    }); });
}

//# sourceMappingURL=auth.js.map
