71 lines
2.1 KiB
TypeScript
71 lines
2.1 KiB
TypeScript
import { GithubUserPayload } from "../../../types";
|
|
import dbHandler from "../../backend/dbHandler";
|
|
import httpsRequest from "../../backend/httpsRequest";
|
|
|
|
type Param = {
|
|
code: string;
|
|
clientId: string;
|
|
clientSecret: string;
|
|
};
|
|
|
|
/**
|
|
* # Login/signup a github user
|
|
*/
|
|
export default async function githubLogin({
|
|
code,
|
|
clientId,
|
|
clientSecret,
|
|
}: Param): Promise<GithubUserPayload | null | undefined> {
|
|
let gitHubUser: GithubUserPayload | undefined;
|
|
|
|
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 as string);
|
|
|
|
if (!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 as string);
|
|
|
|
if (!gitHubUser?.email && gitHubUser) {
|
|
const existingGithubUser = (await dbHandler({
|
|
query: `SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id='${gitHubUser.id}'`,
|
|
values: [gitHubUser.id],
|
|
})) as any[];
|
|
|
|
if (existingGithubUser && existingGithubUser[0]) {
|
|
gitHubUser.email = existingGithubUser[0].email;
|
|
}
|
|
}
|
|
} catch (error: any) {
|
|
console.log(
|
|
"ERROR in githubLogin.ts backend function =>",
|
|
error.message,
|
|
);
|
|
}
|
|
|
|
return gitHubUser;
|
|
}
|