diff --git a/packages/backend/src/plugins/auth.ts b/packages/backend/src/plugins/auth.ts index fb555cd..f6dbdd2 100644 --- a/packages/backend/src/plugins/auth.ts +++ b/packages/backend/src/plugins/auth.ts @@ -5,7 +5,7 @@ import { } from '@backstage/plugin-auth-backend'; import { Router } from 'express'; import { PluginEnvironment } from '../types'; -import { DEFAULT_NAMESPACE, stringifyEntityRef, } from '@backstage/catalog-model'; +import { resolverResult } from './plugins_helper/googleAuthResolver'; export default async function createPlugin( env: PluginEnvironment, @@ -52,32 +52,9 @@ export default async function createPlugin( }), google: providers.google.create({ signIn: { - resolver: async ({ profile }, ctx) => { - if (!profile.email) { - throw new Error( - 'Login failed, user profile does not contain an email', - ); - } - const [localPart, domain] = profile.email.split('@'); - if (domain !== 'code.berlin') { - throw new Error( - `Login failed, '${profile.email}' does not belong to the expected domain`, - ); - } - const userEntityRef = stringifyEntityRef({ - kind: 'User', - name: localPart, - namespace: DEFAULT_NAMESPACE, - }); - return ctx.issueToken({ - claims: { - sub: userEntityRef, - ent: [userEntityRef], - }, - }); - }, + resolver: resolverResult, }, }), - }, -}); + }, + }); } diff --git a/packages/backend/src/plugins/plugins_helper/googleAuthResolver.ts b/packages/backend/src/plugins/plugins_helper/googleAuthResolver.ts new file mode 100644 index 0000000..b6633d3 --- /dev/null +++ b/packages/backend/src/plugins/plugins_helper/googleAuthResolver.ts @@ -0,0 +1,43 @@ +import { + stringifyEntityRef, + DEFAULT_NAMESPACE, +} from '@backstage/catalog-model'; +import { OAuthResult } from '@backstage/plugin-auth-backend'; +import { SignInInfo, AuthResolverContext } from '@backstage/plugin-auth-node'; + +export const resolverResult = async ( + profile_input: SignInInfo, + ctx: AuthResolverContext, +) => { + const profile = profile_input.profile; + const regexp = new RegExp( + /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, + ); + + if (!profile.email || !regexp.test(profile.email)) { + throw new Error( + 'Login failed, user profile does not contain a valid email', + ); + } + + const [localPart, domain] = profile.email.split('@'); + + if (domain !== 'code.berlin') { + throw new Error( + `Login failed, '${profile.email}' does not belong to the expected domain`, + ); + } + + const userEntityRef = stringifyEntityRef({ + kind: 'User', + name: localPart, + namespace: DEFAULT_NAMESPACE, + }); + + return ctx.issueToken({ + claims: { + sub: userEntityRef, + ent: [userEntityRef], + }, + }); +};