Created
May 10, 2020 08:48
-
-
Save radzionc/e8f4ac03c53b3328f4834e01e5ac431e to your computer and use it in GitHub Desktop.
This file contains 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
const { URLSearchParams } = require('url') | |
const { AuthenticationError } = require('apollo-server') | |
const jwt = require('jsonwebtoken') | |
const fetch = require('node-fetch') | |
const Sentry = require('@sentry/node') | |
const { AuthorizationError } = require('../errors') | |
const { | |
LINKEDIN_ACCESS_TOKEN, | |
LINKEDIN_CLIENT_ID, | |
LINKEDIN_CLIENT_SECRET, | |
LINKEDIN_RIDERECT_URI, | |
LINKEDIN_NAME_URL, | |
LINKEDIN_EMAIL_URL | |
} = require('../constants/auth') | |
const fetchJSON = (...args) => fetch(...args).then(r => r.json()) | |
module.exports = { | |
getValidatedWithLinkedinUser: async code => { | |
const body = new URLSearchParams({ | |
grant_type: 'authorization_code', | |
code, | |
redirect_uri: LINKEDIN_RIDERECT_URI, | |
client_id: LINKEDIN_CLIENT_ID, | |
client_secret: LINKEDIN_CLIENT_SECRET | |
}) | |
const { access_token } = await fetchJSON(LINKEDIN_ACCESS_TOKEN, { | |
method: 'POST', | |
body | |
}) | |
const payload = { | |
method: 'GET', | |
headers: { Authorization: `Bearer ${access_token}` } | |
} | |
const { localizedFirstName, localizedLastName, id } = await fetchJSON( | |
LINKEDIN_NAME_URL, | |
payload | |
) | |
const response = await fetchJSON(LINKEDIN_EMAIL_URL, payload) | |
if (response.elements) { | |
return { | |
name: `${localizedFirstName} ${localizedLastName}`, | |
email: response.elements[0]['handle~'].emailAddress, | |
id | |
} | |
} else { | |
Sentry.withScope(scope => { | |
scope.setExtra('response', response) | |
Sentry.captureException('LinkedIn returned no elements') | |
}) | |
await Sentry.flush(2000) | |
throw new AuthorizationError('LINKEDIN_EMAIL_NOT_PROVIDED') | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment