|
| 1 | +import { |
| 2 | + getOrCreateUser, |
| 3 | + sendOnboardingEmail, |
| 4 | + setAuthCookie, |
| 5 | + updateLastLogin, |
| 6 | +} from '@/helpers/auth' |
| 7 | +import { getLdFlagValue } from '@/helpers/launch-darkly' |
| 8 | +import logger from '@/helpers/logger' |
| 9 | +import { ssoClient } from '@/helpers/sso-client' |
| 10 | + |
| 11 | +import type { MutationResolvers } from '../__generated__/types.generated' |
| 12 | + |
| 13 | +const loginWithSso: MutationResolvers['loginWithSso'] = async ( |
| 14 | + _parent, |
| 15 | + params, |
| 16 | + context, |
| 17 | +) => { |
| 18 | + const { authCode, nonce, verifier } = params.input |
| 19 | + |
| 20 | + const ssoEnabled = await getLdFlagValue<boolean>( |
| 21 | + 'ogp-sso-enabled', |
| 22 | + null, |
| 23 | + false, |
| 24 | + ) |
| 25 | + |
| 26 | + if (!ssoEnabled) { |
| 27 | + throw new Error('SSO is not enabled') |
| 28 | + } |
| 29 | + |
| 30 | + try { |
| 31 | + const { accessToken, sub } = await ssoClient.callback({ |
| 32 | + code: authCode, |
| 33 | + nonce, |
| 34 | + codeVerifier: verifier, |
| 35 | + }) |
| 36 | + const userInfo = await ssoClient.userinfo({ |
| 37 | + accessToken, |
| 38 | + sub, |
| 39 | + }) |
| 40 | + |
| 41 | + if (!userInfo) { |
| 42 | + throw new Error('Received nullish user info') |
| 43 | + } |
| 44 | + |
| 45 | + const userEmail = userInfo.email.toLowerCase().trim() |
| 46 | + |
| 47 | + // TODO: Remove this once it's public release |
| 48 | + if (!userEmail.endsWith('@open.gov.sg')) { |
| 49 | + throw new Error('Only OGP officers are allowed to login with SSO') |
| 50 | + } |
| 51 | + |
| 52 | + const user = await getOrCreateUser(userEmail) |
| 53 | + await sendOnboardingEmail(user) |
| 54 | + await updateLastLogin(user.id) |
| 55 | + setAuthCookie(context.res, { userId: user.id, isSso: true }) |
| 56 | + } catch (error) { |
| 57 | + // Small log event to make it easier to get pulse on sgid error rate. |
| 58 | + logger.error('SSO: Unable to query user info', { |
| 59 | + event: 'sso-login-failed-user-info', |
| 60 | + }) |
| 61 | + |
| 62 | + throw error |
| 63 | + } |
| 64 | + |
| 65 | + return true |
| 66 | +} |
| 67 | + |
| 68 | +export default loginWithSso |
0 commit comments