Move auth token logic to useApi hook.

This commit is contained in:
Mike Cao 2022-02-26 15:53:45 -08:00
parent d19b6b5a82
commit 3a8bfd1dbd
7 changed files with 56 additions and 28 deletions

View File

@ -46,7 +46,9 @@ export default function LoginForm() {
setUser(data.user); setUser(data.user);
return router.push('/'); await router.push('/');
return null;
} else { } else {
setMessage( setMessage(
status === 401 ? ( status === 401 ? (

View File

@ -9,10 +9,11 @@
.version { .version {
text-align: right; text-align: right;
padding-right: 10px;
} }
@media only screen and (max-width: 768px) { @media only screen and (max-width: 768px) {
.version { .footer .version {
text-align: center; text-align: center;
} }
} }

View File

@ -18,6 +18,10 @@ export default function Settings() {
const router = useRouter(); const router = useRouter();
const { pathname } = router; const { pathname } = router;
if (!user) {
return null;
}
const menuOptions = [ const menuOptions = [
{ {
label: <FormattedMessage id="label.websites" defaultMessage="Websites" />, label: <FormattedMessage id="label.websites" defaultMessage="Websites" />,

View File

@ -1,25 +1,48 @@
import { useCallback } from 'react'; import { useCallback } from 'react';
import { useRouter } from 'next/router'; import { useRouter } from 'next/router';
import { get, post, put, del } from 'lib/web'; import { get, post, put, del, getItem } from 'lib/web';
import { AUTH_TOKEN } from 'lib/constants';
function includeAuthToken(headers) {
const authToken = getItem(AUTH_TOKEN);
if (authToken) {
headers.Authorization = `Bearer ${authToken}`;
}
return headers;
}
export default function useApi() { export default function useApi() {
const { basePath } = useRouter(); const { basePath } = useRouter();
return { return {
get: useCallback(async (url, params, headers) => { get: useCallback(
return get(`${basePath}/api/${url}`, params, headers); async (url, params, headers = {}) => {
}, []), return get(`${basePath}/api/${url}`, params, includeAuthToken(headers));
},
[get],
),
post: useCallback(async (url, params, headers) => { post: useCallback(
return post(`${basePath}/api/${url}`, params, headers); async (url, params, headers) => {
}, []), return post(`${basePath}/api/${url}`, params, includeAuthToken(headers));
},
[post],
),
put: useCallback(async (url, params, headers) => { put: useCallback(
return put(`${basePath}/api/${url}`, params, headers); async (url, params, headers) => {
}, []), return put(`${basePath}/api/${url}`, params, includeAuthToken(headers));
},
[put],
),
del: useCallback(async (url, params, headers) => { del: useCallback(
return del(`${basePath}/api/${url}`, params, headers); async (url, params, headers) => {
}, []), return del(`${basePath}/api/${url}`, params, includeAuthToken(headers));
},
[del],
),
}; };
} }

View File

@ -1,20 +1,22 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { useRouter } from 'next/router'; import { useRouter } from 'next/router';
import useUser from 'hooks/useUser'; import useUser from 'hooks/useUser';
import { get } from 'lib/web'; import useApi from 'hooks/useApi';
export default function useRequireLogin() { export default function useRequireLogin() {
const router = useRouter(); const router = useRouter();
const { get } = useApi();
const { user, setUser } = useUser(); const { user, setUser } = useUser();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
async function loadUser() { async function loadUser() {
setLoading(true); setLoading(true);
const { ok, data } = await get(`${router.basePath}/api/auth/verify`); const { ok, data } = await get('/auth/verify');
if (!ok) { if (!ok) {
return router.push('/login'); await router.push('/login');
return null;
} }
setUser(data); setUser(data);
@ -23,12 +25,12 @@ export default function useRequireLogin() {
} }
useEffect(() => { useEffect(() => {
if (!loading && user) { if (loading || user) {
return; return;
} }
loadUser(); loadUser();
}, []); }, [user, loading]);
return { user, loading }; return { user, loading };
} }

View File

@ -3,7 +3,7 @@ import { getSession } from './session';
import { getAuthToken } from './auth'; import { getAuthToken } from './auth';
import { unauthorized, badRequest, serverError } from './response'; import { unauthorized, badRequest, serverError } from './response';
export function use(middleware) { export function createMiddleware(middleware) {
return (req, res) => return (req, res) =>
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
middleware(req, res, result => { middleware(req, res, result => {
@ -15,9 +15,9 @@ export function use(middleware) {
}); });
} }
export const useCors = use(cors()); export const useCors = createMiddleware(cors());
export const useSession = use(async (req, res, next) => { export const useSession = createMiddleware(async (req, res, next) => {
let session; let session;
try { try {
@ -35,7 +35,7 @@ export const useSession = use(async (req, res, next) => {
next(); next();
}); });
export const useAuth = use(async (req, res, next) => { export const useAuth = createMiddleware(async (req, res, next) => {
const token = await getAuthToken(req); const token = await getAuthToken(req);
if (!token) { if (!token) {

View File

@ -1,9 +1,6 @@
import { makeUrl } from './url'; import { makeUrl } from './url';
import { AUTH_TOKEN } from './constants';
export const apiRequest = (method, url, body, headers) => { export const apiRequest = (method, url, body, headers) => {
const authToken = getItem(AUTH_TOKEN);
return fetch(url, { return fetch(url, {
method, method,
cache: 'no-cache', cache: 'no-cache',
@ -11,7 +8,6 @@ export const apiRequest = (method, url, body, headers) => {
headers: { headers: {
Accept: 'application/json', Accept: 'application/json',
'Content-Type': 'application/json', 'Content-Type': 'application/json',
...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),
...headers, ...headers,
}, },
body, body,