import Router from 'next/router' ; import nextCookie from 'next-cookies' ; import { NextPageContext , NextApiRequest , NextApiResponse } from 'next' ; import { generateToken , checkToken , removeToken } from './token' ; export const login = ( ) : string => { return generateToken ( ) ; } ; export const auth = ( ctx ) : string => { const { token } = nextCookie ( ctx ) ; if ( ! checkToken ( token ) ) { if ( typeof window === 'undefined' ) { ctx . res . writeHead ( 302 , { Location : '/login' } ) ; ctx . res . end ( ) ; } else { Router . push ( '/login' ) ; } return null ; } return token ; } ; export const apiAuth = ( req , res ) : boolean => { let token = nextCookie ( { req } ) . token ; if ( ! token ) { token = String ( req . query . token ) ; } if ( ! checkToken ( token ) ) { res . status ( 401 ) . end ( ) ; return false ; } return true ; } ; export const logout = ( req ) : void => { const { token } = nextCookie ( { req } ) ; removeToken ( token ) ; } ; export interface InjectedCounterProps { getInitialProps ( ) : InjectedCounterProps ; } export const withAuthSync = ( WrappedComponent ) => { const Wrapper = ( props ) => { return < WrappedComponent { ... props } / > ; } ; Wrapper . getInitialProps = async ( ctx ) => { if ( ! auth ( ctx ) ) { return { } ; } const componentProps = WrappedComponent . getInitialProps && ( await WrappedComponent . getInitialProps ( ctx ) ) ; return { ... componentProps } ; } ; return Wrapper ; } ;