study sauce | authorize app to read profile info | create a study sauce user directory | Search

This code utilizes oauth2Client to interact with Google services, generating unique IDs and extracting user profile data, which is then stored in a Google Sheets document. It consists of four main functions: safeName for string modification, extractProfile for user data extraction, receiveCode for handling OAuth authorization, and exports the receiveCode and extractProfile functions.

Run example

npm run import -- "receive an authentication code from google"

receive an authentication code from google

var uuid = require('uuid/v1');
var uuidSess = require('uuid/v4');

function safeName(name) {
    return name.replace(/[^a-z0-9\-]/ig, '-').substr(0, 40).toLowerCase();
}

function extractProfile(oauth2Client) {
    return util.promisify(oauth2Client.request.bind(oauth2Client))({
            url: 'https://www.googleapis.com/oauth2/v3/userinfo?alt=json'
        })
        .then(r => {
            var profile = r.data;
            var rowData = {
                link: safeName(profile.name) + '-' + uuid().substr(0, 5),
                first: profile.given_name,
                last: profile.family_name,
                email: profile.email,
                token: JSON.stringify(oauth2Client.credentials),
                image: profile.picture || profile.photos[0].value,
                google: profile.id,
                username: profile.name,
                session: uuidSess(),
                date: (new Date).getTime()
            }
            return updateRow(process.env.DOCID, u => u.email === profile.email, rowData, 'User data')
        })
}

function receiveCode(req, res) {
    var oauth2Client = new OAuth2Client(
        credentials.installed.client_id,
        credentials.installed.client_secret,
        process.env.AUTH_REDIRECT)

    var token;
    return util.promisify(oauth2Client.getToken.bind(oauth2Client))(req.query['code'])
        .then(t => token = t)
        .then(() => oauth2Client.setCredentials(token))
        .then(() => extractProfile(oauth2Client))
        .then(profile => {
            res.cookie('__session', profile.session);
            return res.redirect(process.env.DOMAIN + '/home/' + profile.link);
        })
}

module.exports = receiveCode
module.exports.extractProfile = extractProfile

What the code could have been:

const { v4: uuidv4 } = require('uuid');
const OAuth2Client = require('google-auth-library').OAuth2Client;
const { promisify } = require('util');

// Function to sanitize user name for database
const safeName = (name) => name.replace(/[^a-z0-9\-]/gi, '-').substr(0, 40).toLowerCase();

// Function to extract user profile from OAuth2 client
async function extractProfile(oauth2Client) {
    // TODO: Add error handling for request failures
    const response = await promisify(oauth2Client.request.bind(oauth2Client))({
        url: 'https://www.googleapis.com/oauth2/v3/userinfo?alt=json',
    });

    // Extract user profile data from response
    const profile = response.data;
    const rowData = {
        link: safeName(profile.name) + '-' + uuidv4().slice(0, 5),
        first: profile.given_name,
        last: profile.family_name,
        email: profile.email,
        token: JSON.stringify(oauth2Client.credentials),
        image: profile.picture || profile.photos[0].value,
        google: profile.id,
        username: profile.name,
        session: uuidv4(),
        date: Date.now(),
    };

    // TODO: Implement database update logic
    // Update user data in database
    // return updateRow(process.env.DOCID, u => u.email === profile.email, rowData, 'User data');
}

// Function to handle code reception
async function receiveCode(req, res) {
    // Create OAuth2 client with client ID, secret, and redirect URL
    const oauth2Client = new OAuth2Client(
        process.env.GCP_CLIENT_ID,
        process.env.GCP_CLIENT_SECRET,
        process.env.AUTH_REDIRECT
    );

    // Get authorization code from URL query parameter
    const code = req.query['code'];

    // TODO: Add error handling for token retrieval failures
    const token = await promisify(oauth2Client.getToken.bind(oauth2Client))(code);
    oauth2Client.setCredentials(token);

    // Extract user profile using OAuth2 client
    const profile = await extractProfile(oauth2Client);

    // Set session cookie and redirect to home page
    res.cookie('__session', profile.session);
    return res.redirect(`${process.env.DOMAIN}/home/${profile.link}`);
}

module.exports = receiveCode;
module.exports.extractProfile = extractProfile;

Code Breakdown

Requirements and Dependencies

Functions

safeName(name)

extractProfile(oauth2Client)

receiveCode(req, res)

Exports