Created
October 27, 2020 19:22
-
-
Save ArcticZeroo/a8739a4edb02184d8d1d443c287d090f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
} | |
}); | |
} | |
/** | |
* 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: { | |
} | |
}); | |
} | |
/** | |
* 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