Skip to content

Instantly share code, notes, and snippets.

@ArcticZeroo
Created October 27, 2020 19:22
Show Gist options
  • Save ArcticZeroo/a8739a4edb02184d8d1d443c287d090f to your computer and use it in GitHub Desktop.
Save ArcticZeroo/a8739a4edb02184d8d1d443c287d090f to your computer and use it in GitHub Desktop.
import { Profile } from 'passport-google-oauth';
import { User } from '@prisma/client';
import config from '../../config';
import Nullable from '../../models/nullable';
import client from './client';
// Export the User type from here so that it is easier to find, instead of needing to import from client each time
export { User };
/**
* A static utility class which provides methods to operate on the User table in the repository.
*/
export default abstract class UserRepository {
static isDomainPermitted(email: string) {
// If no domains are whitelisted, any domain is permitted
if (config.google.permittedEmailDomains.length === 0) {
return true;
}
for (const domain of config.google.permittedEmailDomains) {
if (email.endsWith(`@${domain}`)) {
return true;
}
}
return false;
}
static async findOrCreateFromProfile(profile: Profile): Promise<User> {
const existingUser = await UserRepository.findByGoogleId(profile.id);
if (existingUser) {
return existingUser;
}
return await UserRepository.createFromProfile(profile);
}
/**
* Given a Google profile, create a user in the database.
* If the Google profile's domain is not in the list of permitted domains, an error will be thrown.
* @param profile - The Google profile used to create the user
* @returns The created user, though its properties shouldn't surprise you
*/
static async createFromProfile(profile: Profile): Promise<User> {
const email = profile.emails[0]?.value;
return await client.user.create({
data: {
googleId: profile.id,
email
}
});
}
/**
* Given a google account email, retrieve the stored user (if it exists)
* @param email - The email to retrieve by
*/
static async findByEmail(email: string): Promise<Nullable<User>> {
return await client.user.findOne({
where: {
email
}
});
}
/**
* Given a google account id, retrieve the stored user (if it exists)
* @param googleId - The google id to retrieve by
*/
static async findByGoogleId(googleId: string): Promise<Nullable<User>> {
return await client.user.findOne({
where: {
googleId
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment