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

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

module.exports = require("datasquirel");

/***/ }),

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

module.exports = require("generate-password");

/***/ }),

/***/ 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");

/***/ }),

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

module.exports = require("http");

/***/ }),

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

module.exports = require("https");

/***/ }),

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

module.exports = require("path");

/***/ }),

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

module.exports = require("url");

/***/ }),

/***/ 7911:
/***/ ((__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_functions_backend_decrypt__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5425);
/* harmony import */ var _package_shared_functions_backend_decrypt__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_package_shared_functions_backend_decrypt__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2163);
/* harmony import */ var _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _functions_backend_social_login_handleSocialDb__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7839);
/* harmony import */ var _functions_backend_social_login_handleSocialDb__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_social_login_handleSocialDb__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _shell_utils_camelJoinedtoCamelSpace__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2127);
/* harmony import */ var _shell_utils_camelJoinedtoCamelSpace__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_shell_utils_camelJoinedtoCamelSpace__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _package_shared_functions_backend_api_cred__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1007);
/* harmony import */ var _package_shared_functions_backend_api_cred__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_package_shared_functions_backend_api_cred__WEBPACK_IMPORTED_MODULE_4__);
// @ts-check
/**
 * Imports
 * ==============================================================================
 */ const fs = __webpack_require__(7147);





const githubLogin = __webpack_require__(6069);
/** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /**
 * API handler
 * ==============================================================================
 * @type {import("next").NextApiHandler}
 */ async function handler(req, res) {
    /**
     * Check method
     *
     * @description Check request method and return if invalid
     */ if (req.method !== "POST") return res.json({
        success: false,
        msg: "Failed!"
    });
    /**
     * Send Response
     *
     * @description Send a boolean response
     */ try {
        /**
         * User auth
         *
         * @description Authenticate user
         */ const { code , email , clientId , clientSecret , database , additionalFields ,  } = req.body;
        const authorization = req.headers.authorization || "";
        const apiCred = _package_shared_functions_backend_api_cred__WEBPACK_IMPORTED_MODULE_4___default()({
            key: authorization,
            database
        });
        if (!apiCred?.user_id) {
            throw new Error("Api Credentials invalid!");
        }
        if (!apiCred.full_access || !apiCred.sign) return res.json({
            success: false,
            msg: "Unauthorized"
        });
        /**
         * User auth
         *
         * @description Authenticate user
         */ if (!code || !clientId || !clientSecret || !database) {
            return res.json({
                success: false,
                msg: "Missing query params"
            });
        }
        if (typeof code !== "string" || typeof clientId !== "string" || typeof clientSecret !== "string" || typeof database !== "string") {
            return res.json({
                success: false,
                msg: "Wrong Parameters"
            });
        }
        /**
         * Create new user folder and file
         *
         * @description Create new user folder and file
         */ const gitHubUser = await githubLogin({
            code: code,
            clientId: clientId,
            clientSecret: clientSecret
        });
        if (!gitHubUser) {
            return res.json({
                success: false,
                msg: "No github user returned"
            });
        }
        const targetDbName = `datasquirel_user_${apiCred.user_id}_${database}`;
        const socialId = gitHubUser.name || gitHubUser.id || gitHubUser.login;
        const targetName = gitHubUser.name || gitHubUser.login;
        const nameArray = targetName?.match(/ /) ? targetName?.split(" ") : targetName?.match(/\-/) ? targetName?.split("-") : [
            targetName
        ];
        const payload = {
            email: gitHubUser.email,
            first_name: _shell_utils_camelJoinedtoCamelSpace__WEBPACK_IMPORTED_MODULE_3___default()(nameArray[0]),
            last_name: _shell_utils_camelJoinedtoCamelSpace__WEBPACK_IMPORTED_MODULE_3___default()(nameArray[1]),
            social_id: socialId,
            social_platform: "github",
            image: gitHubUser.avatar_url,
            image_thumbnail: gitHubUser.avatar_url,
            username: "github-user-" + socialId
        };
        if (additionalFields && Object.keys(additionalFields).length > 0) {
            Object.keys(additionalFields).forEach((key)=>{
                // @ts-ignore
                payload[key] = additionalFields[key];
            });
        }
        const loggedInGithubUser = await _functions_backend_social_login_handleSocialDb__WEBPACK_IMPORTED_MODULE_2___default()({
            database: targetDbName,
            email: gitHubUser.email,
            payload: payload,
            social_platform: "github",
            res: res,
            social_id: socialId,
            supEmail: email,
            additionalFields
        });
        ////////////////////////////////////////////////
        ////////////////////////////////////////////////
        ////////////////////////////////////////////////
        res.json({
            ...loggedInGithubUser,
            dsqlUserId: apiCred.user_id
        });
    ////////////////////////////////////////
    } catch (/** @type {any} */ error) {
        ////////////////////////////////////////
        console.log("ERROR in 'github-auth' API route =>", error.message);
        _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1___default()({
            component: "/api/social-login/github-auth/catch-error",
            message: error.message
        });
        res.json({
            success: false,
            msg: "Failed!"
        });
    ////////////////////////////////////////////////
    ////////////////////////////////////////////////
    ////////////////////////////////////////////////
    ////////////////////////////////////////
    }
}


/***/ })

};
;

// 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,8326,1311,1007,6926,7487,613,4294,6968,722,9971], () => (__webpack_exec__(7911)));
module.exports = __webpack_exports__;

})();