Skip to content

Commit

Permalink
UPD: Refactored google oauth to make the function testable
Browse files Browse the repository at this point in the history
  • Loading branch information
MennaTullahTaha committed May 11, 2024
1 parent b20a498 commit b652da1
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 27 deletions.
31 changes: 4 additions & 27 deletions packages/backend/src/plugins/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
},
}),
},
});
},
});
}
43 changes: 43 additions & 0 deletions packages/backend/src/plugins/plugins_helper/googleAuthResolver.ts
Original file line number Diff line number Diff line change
@@ -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<OAuthResult>,
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],
},
});
};

0 comments on commit b652da1

Please sign in to comment.