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);
return router.push('/');
await router.push('/');
return null;
} else {
setMessage(
status === 401 ? (

View File

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

View File

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

View File

@ -1,25 +1,48 @@
import { useCallback } from 'react';
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() {
const { basePath } = useRouter();
return {
get: useCallback(async (url, params, headers) => {
return get(`${basePath}/api/${url}`, params, headers);
}, []),
get: useCallback(
async (url, params, headers = {}) => {
return get(`${basePath}/api/${url}`, params, includeAuthToken(headers));
},
[get],
),
post: useCallback(async (url, params, headers) => {
return post(`${basePath}/api/${url}`, params, headers);
}, []),
post: useCallback(
async (url, params, headers) => {
return post(`${basePath}/api/${url}`, params, includeAuthToken(headers));
},
[post],
),
put: useCallback(async (url, params, headers) => {
return put(`${basePath}/api/${url}`, params, headers);
}, []),
put: useCallback(
async (url, params, headers) => {
return put(`${basePath}/api/${url}`, params, includeAuthToken(headers));
},
[put],
),
del: useCallback(async (url, params, headers) => {
return del(`${basePath}/api/${url}`, params, headers);
}, []),
del: useCallback(
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 { useRouter } from 'next/router';
import useUser from 'hooks/useUser';
import { get } from 'lib/web';
import useApi from 'hooks/useApi';
export default function useRequireLogin() {
const router = useRouter();
const { get } = useApi();
const { user, setUser } = useUser();
const [loading, setLoading] = useState(false);
async function loadUser() {
setLoading(true);
const { ok, data } = await get(`${router.basePath}/api/auth/verify`);
const { ok, data } = await get('/auth/verify');
if (!ok) {
return router.push('/login');
await router.push('/login');
return null;
}
setUser(data);
@ -23,12 +25,12 @@ export default function useRequireLogin() {
}
useEffect(() => {
if (!loading && user) {
if (loading || user) {
return;
}
loadUser();
}, []);
}, [user, loading]);
return { user, loading };
}

View File

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

View File

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