forked from tdjsnelling/sqtracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwithAuth.js
More file actions
93 lines (79 loc) · 2.18 KB
/
Copy pathwithAuth.js
File metadata and controls
93 lines (79 loc) · 2.18 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { useEffect } from "react";
import { useRouter } from "next/router";
import getConfig from "next/config";
import { useCookies } from "react-cookie";
import getReqCookies from "./getReqCookies";
const Redirect = ({ path }) => {
const router = useRouter();
useEffect(() => {
router.push(path);
}, []);
return <></>;
};
export const withAuth = (Component, noRedirect = false) => {
const Auth = (props) => {
const [cookies] = useCookies();
if (!cookies.token && !noRedirect) {
return <Redirect path="/login" />;
}
return (
<Component token={cookies.token} userId={cookies.userId} {...props} />
);
};
return Auth;
};
export const withAuthServerSideProps = (
getServerSideProps,
publicAccess = false,
noRedirect = false
) => {
return async (ctx) => {
let { token, userId } = getReqCookies(ctx.req);
const {
serverRuntimeConfig: { SQ_SERVER_SECRET },
publicRuntimeConfig: { SQ_ALLOW_UNREGISTERED_VIEW },
} = getConfig();
const isPublicAccess = publicAccess && SQ_ALLOW_UNREGISTERED_VIEW && !token;
if (!token && !noRedirect && !isPublicAccess)
return {
redirect: {
permanent: false,
destination: "/login",
},
};
if (!token && noRedirect && !isPublicAccess) return { props: {} };
if (isPublicAccess) {
token = null;
userId = null;
}
try {
const fetchHeaders = {
"Content-Type": "application/json",
"X-Forwarded-For":
ctx.req.headers["x-forwarded-for"] ?? ctx.req.socket.remoteAddress,
"X-Sq-Server-Secret": SQ_SERVER_SECRET,
"X-Sq-Public-Access": isPublicAccess,
};
if (token) {
fetchHeaders["Authorization"] = `Bearer ${token}`;
}
const { props: ssProps, notFound } = await getServerSideProps({
...ctx,
token,
userId,
fetchHeaders,
isPublicAccess,
});
return { props: { ...ssProps, token }, notFound };
} catch (e) {
if (e === "banned")
return {
redirect: {
permanent: false,
destination: "/logout",
},
};
return { props: {} };
}
};
};