Skip to content

Commit

Permalink
move initial oauth user profile logic
Browse files Browse the repository at this point in the history
  • Loading branch information
genox committed Oct 8, 2024
1 parent 87a2b1f commit 44afb6d
Show file tree
Hide file tree
Showing 7 changed files with 112 additions and 65 deletions.
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,5 @@ GOTENBERG_PDF_URL=http://localhost:3030

OAUTH_CLIENT_ID=secret
OAUTH_CLIENT_SECRET=secret

NEXT_PUBLIC_URL=http://localhost:3000
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Tegonal CV Manager

This is a customised Payload 3 App for managing your company's CVs.

## License
MIT
12 changes: 1 addition & 11 deletions payload.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import { Levels } from '@/payload/collections/Level';
import { Companies } from '@/payload/collections/Companies';
import { Projects } from '@/payload/collections/Projects';
import { OAuth2Plugin } from 'payload-oauth2';
import { ROLE_USER } from '@/payload/utilities/constants';

const filename = fileURLToPath(import.meta.url);
const dirname = path.dirname(filename);
Expand Down Expand Up @@ -118,24 +117,15 @@ export default buildConfig({
tokenEndpoint: 'https://scm.tegonal.com/oauth/token',
scopes: ['email', 'profile', 'openid'],
providerAuthorizationUrl: 'https://scm.tegonal.com/oauth/authorize',
getUserInfo: async (accessToken: string) => {
getUserInfo: async (accessToken) => {
try {
const response = await fetch('https://scm.tegonal.com/oauth/userinfo', {
headers: { Authorization: `Bearer ${accessToken}` },
});
const user = await response.json();
console.log(user);
return {
email: user.email,
sub: user.sub,
roles: [ROLE_USER],
selectedOrganisation: 1,
organisations: [
{
organisation: 1,
roles: [ROLE_USER],
},
],
};
} catch (error) {
console.error(error);
Expand Down
30 changes: 0 additions & 30 deletions src/payload/collections/Users/hooks/loginAfterCreate.ts

This file was deleted.

56 changes: 34 additions & 22 deletions src/payload/collections/Users/hooks/recordSelectedOrganisation.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,44 @@
import { CollectionAfterLoginHook } from 'payload';
import { User } from '@/types/payload-types';
import { getIdFromRelation } from '@/payload/utilities/getIdFromRelation';
import { isNumber } from 'lodash-es';

export const recordSelectedOrganisation: CollectionAfterLoginHook = async ({ req, user }) => {
req.payload.logger.info(`Setting selected organisation for user ${user.id}`);
try {
let selectedOrgId = user.selectedOrganisation;
export const recordSelectedOrganisation: CollectionAfterLoginHook<User> = async ({ req, user }) => {
if (!user.selectedOrganisation) {
req.payload.logger.info({
msg: `Setting selected organisation for user ${user.id} because there is none`,
});

req.payload.logger.info({
msg: `No selected organisation found for user ${user.id}, setting a default`,
});

if (!selectedOrgId) {
req.payload.logger.info({
msg: `No selected organisation found for user ${user.id}, setting a default`,
if (user.organisations?.length === 0) {
req.payload.logger.error({
msg: `No organisations assigned to user ${user.id}, cannot set default!`,
});
selectedOrgId = user.organisations?.[0]?.organisation;
return;
}

if (!selectedOrgId) {
req.payload.logger.warn({ msg: `No organisations found for user ${user.id}`, user });
return user;
const selectedOrgId = getIdFromRelation(user.organisations?.[0]?.organisation);
if (!selectedOrgId || !isNumber(selectedOrgId)) {
req.payload.logger.error({
msg: `Cannot find organisation ID for user ${user.id}, cannot set default!`,
});
return;
}
try {
await req.payload.update({
id: user.id,
collection: 'users',
data: {
selectedOrganisation: 1,
},
req,
});
} catch (err: unknown) {
req.payload.logger.error(`Error recording selected organisation for user ${user.id}: ${err}`);
}

await req.payload.update({
id: user.id,
collection: 'users',
data: {
selectedOrganisation: selectedOrgId || null,
},
req,
});
} catch (err: unknown) {
req.payload.logger.error(`Error recording selected organisation for user ${user.id}: ${err}`);
}

return user;
Expand Down
67 changes: 67 additions & 0 deletions src/payload/collections/Users/hooks/userDefaultsAfterCreate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { CollectionAfterChangeHook } from 'payload';
import { User } from '@/types/payload-types';
import { ROLE_USER } from '@/payload/utilities/constants';
import { Users } from '@/payload/collections/Users';

export const userDefaultsAfterCreate: CollectionAfterChangeHook<User> = async ({
collection,
doc,
req,
operation,
}) => {
if (collection.slug !== Users.slug) {
req.payload.logger.warn({ msg: `Skipping defaultsAfterCreate hook for ${collection.slug}` });
}

if (operation === 'create') {
const { roles, organisations, selectedOrganisation } = doc;
let updatedDoc = doc;

if (!roles || roles.length === 0) {
req.payload.logger.info({ msg: 'Setting default role to user' });
await req.payload.update({
id: doc.id,
collection: 'users',
data: {
roles: [ROLE_USER],
},
req,
});
}

if (!organisations || organisations.length === 0) {
req.payload.logger.info({ msg: 'Setting default organisation to 1' });
updatedDoc.organisations = [
{
organisation: 1,
roles: [ROLE_USER],
},
];
await req.payload.update({
id: doc.id,
collection: 'users',
data: {
organisations: [
{
organisation: 1,
roles: [ROLE_USER],
},
],
},
req,
});
}

if (!selectedOrganisation) {
req.payload.logger.info({ msg: 'Setting default selected organisation to 1' });
await req.payload.update({
id: doc.id,
collection: 'users',
data: {
selectedOrganisation: 1,
},
req,
});
}
}
};
4 changes: 2 additions & 2 deletions src/payload/collections/Users/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { recordSelectedOrganisation } from '@/payload/collections/Users/hooks/re
import { superAdminFieldAccess } from '@/payload/access/superAdmins';
import { organisationAdmins } from '@/payload/collections/Users/access/organisationAdmins';
import { ROLE_SUPER_ADMIN, ROLE_USER } from '@/payload/utilities/constants';
import { userDefaultsAfterCreate } from '@/payload/collections/Users/hooks/userDefaultsAfterCreate';

export const Users: CollectionConfig = {
slug: 'users',
Expand All @@ -25,7 +26,7 @@ export const Users: CollectionConfig = {
// admin: isSuperOrOrganisationAdmin,
},
hooks: {
// afterChange: [loginAfterCreate],
afterChange: [userDefaultsAfterCreate],
afterLogin: [recordSelectedOrganisation],
},
fields: [
Expand All @@ -47,7 +48,6 @@ export const Users: CollectionConfig = {
name: 'roles',
type: 'select',
hasMany: true,
required: true,
access: {
create: superAdminFieldAccess,
update: superAdminFieldAccess,
Expand Down

0 comments on commit 44afb6d

Please sign in to comment.