SHARE
TWEET

Untitled

a guest Oct 20th, 2019 71 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const { OAuth2Client } = require('google-auth-library');
  2.  
  3. function decodedTokenToUser({
  4.   // protocole concerns
  5.   iss,
  6.   azp,
  7.   aud,
  8.   at_hash,
  9.   iat,
  10.   exp,
  11.  
  12.   // actual user info
  13.   sub: id,
  14.   email,
  15.   email_verified,
  16.   name,
  17.   picture,
  18.   given_name,
  19.   family_name,
  20.   locale,
  21. }){
  22.   return {
  23.     id,
  24.     email,
  25.     email_verified,
  26.     name,
  27.     picture,
  28.     given_name,
  29.     family_name,
  30.     locale,
  31.   }
  32. }
  33.  
  34. function verifier(client_id) {
  35.  
  36.   const client = new OAuth2Client(client_id);
  37.  
  38.   async function verifyAndDecode(token) {
  39.     const ticket = await client.verifyIdToken({
  40.         idToken: token,
  41.         audience: client_id,
  42.     });
  43.     return ticket.getPayload();
  44.   }
  45.  
  46.   return verifyAndDecode
  47.  
  48. }
  49.  
  50.  
  51. module.exports = client_id => {
  52.   verify = verifier(client_id)
  53.  
  54.   return async (request, response, next) => {
  55.     const auth_header = request.get('Authorization')
  56.     const unauthorized = body => response.status(401).send(body)
  57.  
  58.     if (!auth_header || !auth_header.match(/^Bearer\s/)) {
  59.       return unauthorized('missing authorization header')
  60.     }
  61.  
  62.     const token = auth_header.replace(/^Bearer\s/, '')
  63.  
  64.     try {
  65.       const payload = await verify(token)
  66.       request.user = decodedTokenToUser(payload)
  67.       next()
  68.     } catch (err) {
  69.       return unauthorized(err)
  70.     }
  71.   }
  72.  
  73. }
  74.  
  75.  
  76.  
  77. /* USAGE *
  78.  
  79.   app.use(
  80.     '/authenticated',
  81.     googleJWT(GOOGLE_CLIENT_IDS),
  82.   )
  83.  
  84. /* */
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top