"use strict";
(() => {
var exports = {};
exports.id = 6134;
exports.ids = [6134];
exports.modules = {

/***/ 9538:
/***/ ((module) => {

module.exports = require("datasquirel");

/***/ }),

/***/ 2029:
/***/ ((module) => {

module.exports = require("datasquirel/functions/hashPassword");

/***/ }),

/***/ 6517:
/***/ ((module) => {

module.exports = require("lodash");

/***/ }),

/***/ 5184:
/***/ ((module) => {

module.exports = require("nodemailer");

/***/ }),

/***/ 6109:
/***/ ((module) => {

module.exports = require("sanitize-html");

/***/ }),

/***/ 2261:
/***/ ((module) => {

module.exports = require("serverless-mysql");

/***/ }),

/***/ 4300:
/***/ ((module) => {

module.exports = require("buffer");

/***/ }),

/***/ 6113:
/***/ ((module) => {

module.exports = require("crypto");

/***/ }),

/***/ 7147:
/***/ ((module) => {

module.exports = require("fs");

/***/ }),

/***/ 1017:
/***/ ((module) => {

module.exports = require("path");

/***/ }),

/***/ 9842:
/***/ ((module) => {

// @ts-check
/**
 * Delay async function
 *
 * @param {number} [milliseconds]
 *
 * @returns {Promise<boolean>} new user auth object payload
 */ 
module.exports = async function delay(milliseconds) {
    await new Promise((resolve, reject)=>{
        setTimeout(()=>{
            resolve(true);
        }, milliseconds || 1000);
    });
    return true;
}; ////////////////////////////////////////////////
 ////////////////////////////////////////////////
 ////////////////////////////////////////////////


/***/ }),

/***/ 4150:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ handler)
/* harmony export */ });
/* harmony import */ var _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2224);
/* harmony import */ var _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _functions_backend_addAdminUserOnLogin__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(613);
/* harmony import */ var _functions_backend_addAdminUserOnLogin__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_addAdminUserOnLogin__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2163);
/* harmony import */ var _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_serverError__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _functions_backend_handleNodemailer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6926);
/* harmony import */ var _functions_backend_handleNodemailer__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_handleNodemailer__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _functions_backend_delay__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(9842);
/* harmony import */ var _functions_backend_delay__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_delay__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var datasquirel_functions_hashPassword__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(2029);
/* harmony import */ var datasquirel_functions_hashPassword__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(datasquirel_functions_hashPassword__WEBPACK_IMPORTED_MODULE_5__);
// @ts-check
/**
 * ==============================================================================
 * Imports
 * ==============================================================================
 */ const fs = __webpack_require__(7147);






const encrypt = __webpack_require__(7547);
/** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /**
 * API handler
 * ==============================================================================
 * @type {import("next").NextApiHandler}
 */ async function handler(req, res) {
    if (req.method === "POST") {
        /** ********************* Get Page Data */ const sanitizedReqBody = req.body;
        // let { email, password, query } = reqBody;
        let email = sanitizedReqBody.email;
        let password = sanitizedReqBody.password;
        let query = sanitizedReqBody.query;
        if (email.match(/ /)) return res.json({
            user: null,
            msg: "Invalid Email"
        });
        try {
            const allowedAuthKeysPath = process.env.DSQL_USER_LOGIN_KEYS_PATH;
            if (!allowedAuthKeysPath) throw new Error("loginUser error: process.env.DSQL_USER_LOGIN_KEYS_PATH not present");
            if (!fs.existsSync(allowedAuthKeysPath)) {
                fs.mkdirSync(allowedAuthKeysPath, {
                    recursive: true
                });
            }
            const ip = req.headers["x-real-ip"] || req.headers["x-forwarded-for"] || req.connection.remoteAddress;
            const site = process.env.DSQL_HOST || "https://datasquirel.com";
            let hashedPassword = datasquirel_functions_hashPassword__WEBPACK_IMPORTED_MODULE_5___default()({
                encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD || "",
                password: password
            });
            ////////////////////////////////////////////////
            ////////////////////////////////////////////////
            ////////////////////////////////////////////////
            if (password?.match(/ /) || email?.match(/ /)) {
                return res.json({
                    msg: "Failed!",
                    user: null
                });
            }
            ////////////////////////////////////////////////
            ////////////////////////////////////////////////
            ////////////////////////////////////////////////
            let foundUser = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`SELECT * FROM users WHERE email=? OR username=?`, [
                email,
                email
            ]);
            ////////////////////////////////////////////////
            ////////////////////////////////////////////////
            ////////////////////////////////////////////////
            if (!foundUser || !foundUser[0]) {
                return res.json({
                    msg: "No user found",
                    user: null
                });
            }
            ////////////////////////////////////////////////
            ////////////////////////////////////////////////
            ////////////////////////////////////////////////
            let isPasswordCorrect = false;
            if (foundUser && foundUser[0]) isPasswordCorrect = hashedPassword === foundUser[0].password;
            ////////////////////////////////////////////////
            ////////////////////////////////////////////////
            ////////////////////////////////////////////////
            if (!isPasswordCorrect) {
                await _functions_backend_delay__WEBPACK_IMPORTED_MODULE_4___default()();
                if (true) {
                    _functions_backend_handleNodemailer__WEBPACK_IMPORTED_MODULE_3___default()({
                        to: process.env.DSQL_CONTACT_EMAIL,
                        subject: `Failed Login from ${email}`,
                        html: `<h1><u>${email}</u> tried to login with a wrong password</h1><p><b>${email}</b> attempted a login on ${site} from ${ip} with a wrong password.</p>`
                    });
                }
                return res.json({
                    msg: "Wrong Password, Wrong Social Media Credentials",
                    user: null
                });
            }
            ////////////////////////////////////////////////
            ////////////////////////////////////////////////
            ////////////////////////////////////////////////
            let csrfKey = Math.random().toString(36).substring(2) + "-" + Math.random().toString(36).substring(2);
            let userPayload = {
                id: foundUser[0].id,
                stripe_id: foundUser[0].stripe_id || "",
                first_name: foundUser[0].first_name,
                last_name: foundUser[0].last_name,
                username: foundUser[0].username,
                email: foundUser[0].email,
                social_id: foundUser[0].social_id,
                image: foundUser[0].image,
                image_thumbnail: foundUser[0].image_thumbnail,
                verification_status: foundUser[0].verification_status,
                social_login: foundUser[0].social_login,
                social_platform: foundUser[0].social_platform,
                csrf_k: csrfKey,
                logged_in_status: true,
                date: Date.now()
            };
            let encryptedPayload = encrypt(JSON.stringify(userPayload));
            res.setHeader("Set-Cookie", [
                `datasquirelAuthKey=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`,
                `csrf=${csrfKey};samesite=strict;path=/;HttpOnly=true`, 
            ]);
            fs.appendFile("./.tmp/userLoginLogs.log", `${foundUser[0].first_name} ${foundUser[0].last_name} Logged in from ${foundUser[0].social_login ? foundUser[0].social_platform : "Regular Email Login"} at ${Date()} \n\n\n`, "utf8", (err)=>{
                if (err) console.log(`Loging log write error`);
            });
            fs.writeFileSync(`${allowedAuthKeysPath}/${csrfKey}`, JSON.stringify(userPayload));
            ////////////////////////////////////////////////
            ////////////////////////////////////////////////
            ////////////////////////////////////////////////
            if (query?.invite) {
                _functions_backend_addAdminUserOnLogin__WEBPACK_IMPORTED_MODULE_1___default()({
                    query: query,
                    user: {
                        ...userPayload,
                        phone: foundUser[0].phone
                    }
                });
            }
            ////////////////////////////////////////////////
            ////////////////////////////////////////////////
            ////////////////////////////////////////////////
            await _functions_backend_delay__WEBPACK_IMPORTED_MODULE_4___default()();
            if (true) {
                _functions_backend_handleNodemailer__WEBPACK_IMPORTED_MODULE_3___default()({
                    to: process.env.DSQL_CONTACT_EMAIL,
                    subject: `${email} Logged in successfully`,
                    html: `<h1><u>${email}</u> successfully logged in</h1><p><b>${email}</b> successfully logged in on ${site} from ${ip} on ${Date().substring(0, 16)}.</p>`
                });
            }
            ////////////////////////////////////////////////
            ////////////////////////////////////////////////
            ////////////////////////////////////////////////
            /** ********************* Send Response */ res.json({
                msg: "User Found",
                user: {
                    auth: true,
                    userid: foundUser[0].id,
                    csrf_k: csrfKey,
                    stripe_id: foundUser[0].stripe_id || ""
                },
                userPayload
            });
        } catch (/** @type {any} */ error) {
            console.log("Login Error =>", error.message);
            _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_2___default()({
                component: "/api/loginUser/main-catch-error",
                message: error.message,
                user: {
                    email: email
                }
            });
        }
    ////////////////////////////////////////////////
    ////////////////////////////////////////////////
    ////////////////////////////////////////////////
    } else {
        res.json({
            msg: "Oops ..."
        });
    }
}


/***/ })

};
;

// load runtime
var __webpack_require__ = require("../../webpack-api-runtime.js");
__webpack_require__.C(exports);
var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
var __webpack_exports__ = __webpack_require__.X(0, [2224,2163,3017,3403,7547,5886,5338,6926,613], () => (__webpack_exec__(4150)));
module.exports = __webpack_exports__;

})();