import { GetServerSidePropsContext } from 'next' ; import nookies from 'nookies' ; import UserAPI from 'shared/lib/api/user' ; import { logout } from './functions/logout' ; type AuthUserType = User | undefined ; param { String } unauthedRedirect return { Object } return { Object } return { AuthUserType } const withAuth = ( { unauthedRedirect } = { unauthedRedirect : '/' } ) => ( getServerSidePropsFunc ? ) => async ( ctx ) => { const cookies = nookies . get ( ctx ) ; let AuthUser ; if ( cookies ?. token ) { const tokens = JSON . parse ( cookies . token ) ; AuthUser = await UserAPI . getCurrent ( tokens ) ; } if ( ! AuthUser || ! AuthUser . id ) { await logout ( ) ; return { redirect : { destination : unauthedRedirect , permanent : false } , props : { } as never , } ; } let returnData = { props : { AuthUser } } ; if ( getServerSidePropsFunc ) { ctx . AuthUser = AuthUser ; const composedProps = ( await getServerSidePropsFunc ( ctx ) ) || { } ; if ( composedProps ) { if ( composedProps . props ) { returnData = { ... composedProps } ; returnData . props . AuthUser = AuthUser ; } else if ( composedProps . notFound || composedProps . redirect ) { returnData = { ... composedProps } ; } } } return returnData ; } ; export default withAuth ;