46 lines
1.8 KiB
JavaScript
46 lines
1.8 KiB
JavaScript
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
|
import httpsRequest from "../../backend/httpsRequest";
|
|
/**
|
|
* # Login/signup a github user
|
|
*/
|
|
export default async function githubLogin({ code, clientId, clientSecret, }) {
|
|
let gitHubUser;
|
|
try {
|
|
const response = await httpsRequest({
|
|
method: "POST",
|
|
hostname: "github.com",
|
|
path: `/login/oauth/access_token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}`,
|
|
headers: {
|
|
Accept: "application/json",
|
|
"User-Agent": "*",
|
|
},
|
|
scheme: "https",
|
|
});
|
|
const accessTokenObject = JSON.parse(response);
|
|
if (!(accessTokenObject === null || accessTokenObject === void 0 ? void 0 : accessTokenObject.access_token)) {
|
|
return gitHubUser;
|
|
}
|
|
const userDataResponse = await httpsRequest({
|
|
method: "GET",
|
|
hostname: "api.github.com",
|
|
path: "/user",
|
|
headers: {
|
|
Authorization: `Bearer ${accessTokenObject.access_token}`,
|
|
"User-Agent": "*",
|
|
},
|
|
scheme: "https",
|
|
});
|
|
gitHubUser = JSON.parse(userDataResponse);
|
|
if (!(gitHubUser === null || gitHubUser === void 0 ? void 0 : gitHubUser.email) && gitHubUser) {
|
|
const existingGithubUser = await DB_HANDLER(`SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id='${gitHubUser.id}'`);
|
|
if (existingGithubUser && existingGithubUser[0]) {
|
|
gitHubUser.email = existingGithubUser[0].email;
|
|
}
|
|
}
|
|
}
|
|
catch ( /** @type {any} */error) {
|
|
console.log("ERROR in githubLogin.ts backend function =>", error.message);
|
|
}
|
|
return gitHubUser;
|
|
}
|