Created
June 7, 2019 11:25
-
-
Save kousherAlam/35b89af266cd156ed129c92532066d97 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Request, Response } from "express"; | |
import { successResponse } from "../../Helpers/Responses/successResponse"; | |
import { ApiConfig } from "../../Configs/Api.Config"; | |
import { errorResponse } from "../../Helpers/Responses"; | |
const { OAuth2Client } = require("google-auth-library"); | |
const { google } = require("googleapis"); | |
export default async function googleLogin(request: Request, response: Response) { | |
console.log(ApiConfig.THIRD_PARTY_LOGIN_API.GOOGLE.SCOPES); | |
const code = request.query.code; | |
const KEYS = require("../../Configs/" + ApiConfig.THIRD_PARTY_LOGIN_API.GOOGLE.KEY); | |
const CLIENT_SECRET = KEYS.web.client_secret; | |
const CLIENT_ID = KEYS.web.client_id; | |
const REDIRECT_URIS = KEYS.web.redirect_uris[1]; | |
const oAuth2Client = new OAuth2Client( | |
CLIENT_ID, | |
CLIENT_SECRET, | |
REDIRECT_URIS | |
); | |
if (!code) { | |
const authorizeUrl = oAuth2Client.generateAuthUrl({ | |
access_type: "online", | |
scope: ApiConfig.THIRD_PARTY_LOGIN_API.GOOGLE.SCOPES, | |
}); | |
// const theResponse = successResponse({ | |
// isRedirect: true, | |
// url: authorizeUrl | |
// }, "success redirect"); | |
response.redirect(authorizeUrl); | |
} else { | |
async function main() { | |
oAuth2Client.getToken(code, async (err, toekenResponse) => { | |
if (!err) { | |
oAuth2Client.setCredentials(toekenResponse); | |
const data = await getGoogleData(oAuth2Client); | |
return response.json(data); | |
} else { | |
console.log(err); | |
} | |
}); | |
} | |
main().catch(console.error); | |
} | |
} | |
async function getGoogleData(auth): Promise<object> { | |
const service = google.people({ version: "v1", auth }); | |
return new Promise((resolve, reject) => { | |
service.people.get({ | |
resourceName: "people/me", | |
personFields: ["names", "emailAddresses", "photos", "birthdays", "genders"], | |
}, (err, res) => { | |
if (err) { | |
console.log(err); | |
reject(errorResponse(err, "error happpend")); | |
} | |
resolve(successResponse(res.data, "success")); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment