All files / src/hooks afterLoginHook.ts

100% Statements 11/11
87.5% Branches 7/8
100% Functions 2/2
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 323x           3x   56x   6x 3x 3x           2x   2x       1x       6x      
import { getRolesSlug } from '../utils/getRolesSlug'
 
/**
 * Creates an afterLogin hook that populates the user's role
 * This ensures the role object is fully available in the login response
 */
export const createAfterLoginHook = () => {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  return async ({ user, req }: any) => {
    // If user has a role and it's just an ID (string or number), populate it
    if (user && user.role && (typeof user.role === 'string' || typeof user.role === 'number')) {
      try {
        const role = await req.payload.findByID({
          collection: getRolesSlug() as 'roles',
          id: String(user.role),
          depth: 0, // Don't need nested data
        })
 
        Eif (role) {
          // Replace the role ID with the full role object
          user.role = role
        }
      } catch (error) {
        // Log but don't fail the login if role population fails
        console.warn('Could not populate role in afterLogin:', error)
      }
    }
 
    return user
  }
}