Skip to content

Commit

Permalink
feat: useAuthentication hook updates (#2151)
Browse files Browse the repository at this point in the history
* auth code colocation

* auth: return `update` function
  • Loading branch information
thiskevinwang authored Aug 31, 2023
1 parent f8ece3a commit 1b890d2
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 65 deletions.
48 changes: 41 additions & 7 deletions src/hooks/use-authentication/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,52 @@
* SPDX-License-Identifier: MPL-2.0
*/

import { useEffect, useMemo, useState } from 'react'
import { useEffect, useMemo } from 'react'
import { useRouter } from 'next/router'
import { useSession } from 'next-auth/react'
import {
signIn,
SignInOptions,
signOut,
SignOutParams,
useSession,
} from 'next-auth/react'
import { Session } from 'next-auth'
import { saveAndLoadAnalytics } from '@hashicorp/react-consent-manager'
import { preferencesSavedAndLoaded } from '@hashicorp/react-consent-manager/util/cookies'
import { AuthErrors, SessionStatus, ValidAuthProviderId } from 'types/auth'
import { UseAuthenticationOptions, UseAuthenticationResult } from './types'
import { AuthErrors, ValidAuthProviderId } from 'types/auth'
import { makeSignIn, makeSignOut, signUp } from './helpers'
import { canAnalyzeUser, safeGetSegmentId } from 'lib/analytics'

export const DEFAULT_PROVIDER_ID = ValidAuthProviderId.CloudIdp

interface UseAuthenticationOptions {
/**
* Optional boolean. If true, `onUnauthenticated` is invoked if the user is
* not been authenticated.
*/
isRequired?: boolean

/**
* Optional callback function. Invoked by next-auth when `isRequired` is true.
* By default, we invoke our custom `signIn` callback with no parameters.
*/
onUnauthenticated?: () => void
}

interface UseAuthenticationResult {
isAuthenticated: boolean
isLoading: boolean
session?: Omit<Session, 'user'>
signIn: (
provider?: ValidAuthProviderId,
options?: SignInOptions
) => ReturnType<typeof signIn>
signOut: (options?: SignOutParams) => ReturnType<typeof signOut>
signUp: typeof signUp
user: null | Session['user']
update: (data?: any) => Promise<Session | null>
}

/**
* Hook for consuming user, session, and authentication state. Sources all data
* from next-auth/react's `useSession` hook.
Expand All @@ -41,11 +74,11 @@ const useAuthentication = (
// Get option properties from `options` parameter
const { isRequired = false, onUnauthenticated = () => signIn() } = options

// Pull data and status from next-auth's hook, and pass options
const { data, status } = useSession({
// Pass options to `useSession` hook and use values
const { data, status, update } = useSession({
required: isRequired,
onUnauthenticated,
}) as { data: Session; status: SessionStatus }
})

// Deriving booleans about auth state
const isLoading = status === 'loading'
Expand Down Expand Up @@ -101,6 +134,7 @@ const useAuthentication = (
signOut,
signUp,
user,
update,
}
}

Expand Down
39 changes: 0 additions & 39 deletions src/hooks/use-authentication/types.ts

This file was deleted.

23 changes: 4 additions & 19 deletions src/pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
*/

import createFetch from '@vercel/fetch'
import NextAuth, { Account, Session, Profile } from 'next-auth'
import { JWT } from 'next-auth/jwt'
import NextAuth from 'next-auth'
import { URL } from 'url'
import { AuthErrors } from 'types/auth'
import CloudIdpProvider from 'lib/auth/cloud-idp-provider'
Expand All @@ -27,7 +26,7 @@ export default NextAuth({
* ourselves in this signOut event.
* https://github.com/nextauthjs/next-auth/discussions/3938
*/
async signOut({ token }: { token: JWT }) {
async signOut({ token }) {
if (isDev) {
console.log('Inside of NextAuth.events.signOut')
}
Expand Down Expand Up @@ -63,15 +62,7 @@ export default NextAuth({
*
* ref: https://next-auth.js.org/configuration/callbacks#jwt-callback
*/
async jwt({
token,
account,
profile,
}: {
token: JWT
account?: Account
profile?: Profile
}) {
async jwt({ token, account, profile }) {
const isInitial = !!account && !!profile
isDev &&
console.log('jwt callback (%s)', isInitial ? 'initial' : 'subsequent')
Expand Down Expand Up @@ -133,13 +124,7 @@ export default NextAuth({
*
* ref: https://next-auth.js.org/configuration/callbacks#session-callback
*/
async session({
session,
token,
}: {
token: JWT
session: Session
}): Promise<Session> {
async session({ session, token }) {
return {
...session,
accessToken: token.access_token,
Expand Down

1 comment on commit 1b890d2

@vercel
Copy link

@vercel vercel bot commented on 1b890d2 Aug 31, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.