import { AuthenticationError } from 'apollo-server'; import { AuthChecker } from 'type-graphql'; import { ContextType, UnverifiedUserError, UserRole, UserStatus, } from '@/types'; import { User } from '@/entities'; const checkRoles = (roles: string[], user: User) => { if (roles.length === 0 || user.roles.some((role) => roles.includes(role))) { return true; } return false; }; const checkAuth: AuthChecker = async ( { context }, roles ) => { const { user, authError } = context; if (!user) { // Forward all Authentication Errors or create a generic one if (authError && authError instanceof AuthenticationError) { throw authError; } else { throw new AuthenticationError('You are not authorized to access this.'); } } if ( !roles.includes(UserStatus.ANONYMOUS) && (await user.isAnonymous(context)) ) { throw new UnverifiedUserError('Anonymous users cannot access this.'); } // Check if resolver is allowed to be accessed by unverified users const isVerified = await user.isVerified(context); const resolverAllowsUnverified = roles.includes(UserStatus.UNVERIFIED) || roles.includes(UserStatus.ANONYMOUS); if (isVerified || resolverAllowsUnverified) { const filteredUserRoles = roles.filter((role) => role in UserRole); return checkRoles(filteredUserRoles, user); } else { throw new UnverifiedUserError('You are not verified.'); } }; export default checkAuth;