-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwithGuest.tsx
More file actions
48 lines (40 loc) · 1.19 KB
/
Copy pathwithGuest.tsx
File metadata and controls
48 lines (40 loc) · 1.19 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import React from 'react'
import Router from 'next/router'
import authVerifyCookie from './authVerifyCookie'
import PAGE from 'config/page.config'
import type { NextPageContext } from 'next'
const withGuest = (PageComponent: any) => {
// Initialize wrapper component
const WrapperComponent: any= (props: any) => {
return <PageComponent {...props} />
}
WrapperComponent.getInitialProps = async (ctx: NextPageContext) => {
// Get initial properties from page component
const initialProps = PageComponent.getInitialProps ? await PageComponent.getInitialProps(ctx) : {}
// Verify user token from cookie
const userData = await authVerifyCookie(ctx)
// Check whether user token is valid
if (userData) {
// Redirect to home page
if (ctx.res) {
ctx.res.writeHead(302, {
Location: ctx.query.redirect || PAGE.homePagePath,
})
ctx.res.end()
} else {
Router.push((Router.query.redirect as string) || PAGE.homePagePath)
}
return {
...initialProps,
userData,
}
}
return {
...initialProps,
userData: null,
}
}
// Inject page component attributes to wrapper component
return Object.assign(WrapperComponent, PageComponent)
}
export default withGuest