Skip to content

[Enhancement] Enhance useAuth hook with user context and session persistence #191

@kingksjo

Description

@kingksjo

Domain: Authentication


Issue [Enhancement] Enhance useAuth hook with user context and session persistence

Tier: 🟡 Medium

Description:

  • Problem: The useAuth hook in src/hooks/useAuth.ts only checks for the existence of a token string in localStorage. It provides no user information (role, email, org ID), no logout function, and no way to refresh auth state after login. Components needing user details (like CompanyDashboard for enterpriseId or UserManagement for role-based access) have no centralized source of truth.
  • Implementation: Enhance useAuth to: (1) decode the JWT payload to extract user info (id, email, role, organizationId), (2) expose a user object, logout() function, and refreshAuth() method, (3) create an AuthContext provider wrapping the app so all components can access auth state without prop drilling.

Dependencies:

Acceptance Criteria:

  • useAuth returns { isLoading, isAuthenticated, user, logout, refreshAuth }.
  • user object includes id, email, name, role, and organizationId from the token.
  • logout() clears token, resets state, and navigates to /login.
  • AuthContext provider wraps the app in the component tree.
  • Components can access useAuth() from any level without prop drilling.
  • Token expiration is detected and triggers automatic logout.

Testing Requirements:

  • Unit tests for token decoding with valid and expired JWTs.
  • Unit tests for logout() clearing state and storage.
  • Unit tests written for the core logic (target 80%+ coverage).
  • Context provider renders children correctly when authenticated and unauthenticated.

PR Checklist:

  • Branch is named conventionally (e.g., feature/issue-15-useauth-enhancement).
  • pnpm run lint and pnpm run build pass with zero warnings.
  • Screenshot of passing test terminal logs is attached to the PR.

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions