Skip to content

Instantly share code, notes, and snippets.

@nwaughachukwuma
Last active October 29, 2019 06:31
Show Gist options
  • Save nwaughachukwuma/14b2b2f8f5b5370a04cfb3e156db186a to your computer and use it in GitHub Desktop.
Save nwaughachukwuma/14b2b2f8f5b5370a04cfb3e156db186a to your computer and use it in GitHub Desktop.
import { admin } from './admin'
import * as APIRequest from 'request-promise-native'
import { get } from 'lodash'
async function verifyUser(token: string) {
try {
const options = {
uri:'https://www.googleapis.com/oauth2/v3/tokeninfo',
method: 'POST',
body: {
access_token: token
},
json: true
}
// google apps script token info
const tokenInfo = await APIRequest(options);
console.info('user token info is: ', tokenInfo);
if (!get(tokenInfo, 'aud', undefined) || !get(tokenInfo, 'email', undefined)) {
throw new Error('The request is likely not coming from an authentic source')
}
// get userRecord from tokenInfo email
const userRecord = await admin.auth().getUserByEmail(tokenInfo.email);
if (!userRecord.uid) {
throw new Error('Cannot find user record.')
}
// check user's claim for admin role. If not admin, return false
console.info(userRecord.customClaims)
if (!get(userRecord, 'customClaims.admin', undefined)) {
throw new Error('User does not have the permission to access the resource')
}
return true
} catch (error) {
console.warn('error verifying idToken from google apps script')
console.error(error)
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment