Skip to content
Snippets Groups Projects
Commit 8e52c4a7 authored by Alexandros Georgantas's avatar Alexandros Georgantas Committed by Yannis Barlas
Browse files

feat(*): add function to make authenticated oauth calls

parent de9a5e83
No related branches found
No related tags found
1 merge request!58Connection to providers
......@@ -41,6 +41,10 @@ const fileStorage = {
const { callMicroservice } = require('./utils/microservices')
const {
authenticatedCall: makeOAuthCall,
} = require('./utils/authenticatedCall')
const createJWT = authentication.token.create
const verifyJWT = authentication.token.verify
......@@ -70,5 +74,6 @@ module.exports = {
connectToJobQueue,
callMicroservice,
makeOAuthCall,
WaxToDocxConverter,
}
const axios = require('axios')
const { authenticatedCall } = require('../authenticatedCall')
jest.mock('../getAuthTokens.js', () => {
return jest.fn(() => 'token')
})
jest.mock('axios')
describe('Authenticated call', () => {
it('calls provider with auth', async () => {
axios.mockResolvedValue(true)
const res = await authenticatedCall('123', 'lulu', {})
expect(res).toBe(true)
})
})
const makeCall = require('./makeCall')
const getAuthTokens = require('./getAuthTokens')
const authenticatedCall = async (userId, providerLabel, callParameters) => {
try {
if (!callParameters) throw new Error(`Call parameters are required`)
const accessToken = await getAuthTokens(userId, providerLabel)
return makeCall(callParameters, accessToken)
} catch (e) {
throw new Error(e)
}
}
module.exports = {
authenticatedCall,
getAuthTokens,
}
const config = require('config')
const axios = require('axios')
const { Identity } = require('../models')
const getAuthTokens = async (userId, providerLabel) => {
try {
const providerUserIdentity = await Identity.findOne({
userId,
provider: providerLabel,
})
if (!providerUserIdentity) {
throw new Error(`identity for provider ${providerLabel} does not exist`)
}
const {
oauthAccessToken,
oauthAccessTokenExpiration,
oauthRefreshToken,
oauthRefreshTokenExpiration,
} = providerUserIdentity
const accessTokenExpired = oauthAccessTokenExpiration < new Date().getTime()
if (!accessTokenExpired) {
return oauthAccessToken
}
const refreshTokenExpired =
oauthRefreshTokenExpiration < new Date().getTime()
if (refreshTokenExpired) {
throw new Error(
`refresh token for provider ${providerLabel} expired, authorization flow should (provider login) be followed by the user`,
)
}
const integrations =
config.has('integrations') && config.get('integrations')
if (!integrations) {
throw new Error('Integrations are undefined in config')
}
const externalProvider = integrations[providerLabel]
if (!externalProvider) {
throw new Error(
`Integration ${providerLabel} configuration is undefined `,
)
}
const { tokenUrl, clientId } = integrations[providerLabel]
if (!tokenUrl) {
throw new Error(`Integration ${providerLabel} tokenUrl is undefined `)
}
if (!clientId) {
throw new Error(`Integration ${providerLabel} clientId is undefined `)
}
const tokenData = new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: oauthRefreshToken,
client_id: clientId,
})
const { data } = await axios({
method: 'post',
url: tokenUrl,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: tokenData.toString(),
})
/* eslint-disable camelcase */
const { access_token, expires_in, refresh_token, refresh_expires_in } = data
await Identity.patchAndFetchById(providerUserIdentity.id, {
oauthAccessToken: access_token,
oauthRefreshToken: refresh_token,
oauthAccessTokenExpiration:
new Date().getTime() + 1000 * parseInt(expires_in, 10),
oauthRefreshTokenExpiration:
new Date().getTime() + 1000 * parseInt(refresh_expires_in, 10),
})
return access_token
/* eslint-enable camelcase */
} catch (e) {
throw new Error(e)
}
}
module.exports = getAuthTokens
const axios = require('axios')
const clone = require('lodash/clone')
const makeCall = async (callParameters, token) => {
const axiosParams = clone(callParameters)
const { headers } = axiosParams
if (!headers) {
axiosParams.headers = {
authorization: `Bearer ${token}`,
}
} else {
axiosParams.headers.authorization = `Bearer ${token}`
}
return axios(axiosParams)
}
module.exports = makeCall
const axios = require('axios')
const clone = require('lodash/clone')
const makeCall = require('./makeCall')
const getAccessToken = require('./getAccessToken')
......@@ -32,24 +31,9 @@ const callMicroservice = async (serviceName, callParameters) => {
`communication parameters needed for calling ${serviceName} microservice`,
)
const makeCall = async token => {
const axiosParams = clone(callParameters)
const { headers } = axiosParams
if (!headers) {
axiosParams.headers = {
authorization: `Bearer ${token}`,
}
} else {
axiosParams.headers.authorization = `Bearer ${token}`
}
return axios(axiosParams)
}
const accessToken = await getAccessToken(serviceName)
return makeCall(accessToken).catch(async err => {
return makeCall(callParameters, accessToken).catch(async err => {
const { response } = err
if (!response) {
......@@ -61,7 +45,7 @@ const callMicroservice = async (serviceName, callParameters) => {
if (status === 401 && msg === 'expired token') {
const freshToken = await getAccessToken(serviceName, true)
return makeCall(freshToken)
return makeCall(callParameters, freshToken)
}
throw new Error(err)
......
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment