Skip to content

Instantly share code, notes, and snippets.

@ArcticZeroo
Created October 27, 2020 19:18
Show Gist options
  • Save ArcticZeroo/c28676443ab43c2ccfa9e3c2f415cb1c to your computer and use it in GitHub Desktop.
Save ArcticZeroo/c28676443ab43c2ccfa9e3c2f415cb1c to your computer and use it in GitHub Desktop.
/**
* This file defines the "google strategy" for passport.
* Passport requires three main things for a strategy to work:
* - A deserialize method to turn an ID into a database object (a User)
* - A serialize method to turn a database object (a User) into an ID
* - The actual Strategy used to perform authentication
*/
import passport from 'passport';
import { OAuth2Strategy as GoogleStrategy } from 'passport-google-oauth';
import config from '../../config';
import * as callbackify from '../../util/callbackify';
import UserRepository, { User } from '../storage/user';
/**
* Deserialize a given user by their google ID (this is the defined method of serde as contractually defined
* in serializeUser, which requires us to accept ids)
* @param googleId - The google ID of the database user
*/
export async function deserializeUser(googleId: string): Promise<User> {
return await UserRepository.findByGoogleId(googleId);
}
/**
* Serialize a given user from a database object to their google ID.
* @param user - The database User object
*/
export async function serializeUser(user: User): Promise<string> {
return user.googleId;
}
/**
* Create a Google strategy suitable for passport.use
*/
export function createGoogleStrategy(): GoogleStrategy {
return new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
// todo: replace with a better callback URL once this is running somewhere else
callbackURL: `http://localhost:${config.port}/auth/google/callback`,
// only allow accounts from msu.edu for now
hostedDomain: config.google.permittedEmailDomains.join(',')
},(accessToken, refreshToken, profile, done) => {
callbackify.attachResultToCallback(UserRepository.findOrCreateFromProfile(profile), done);
});
}
export const strategyName = 'google';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment