feat: logout route/sign out button (#54)

pull/50/head
sct 4 years ago committed by GitHub
parent e6349c13a0
commit cb9098f457
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -457,10 +457,7 @@ paths:
content: content:
application/json: application/json:
schema: schema:
type: object $ref: '#/components/schemas/User'
properties:
status:
type: string
requestBody: requestBody:
required: true required: true
content: content:
@ -472,7 +469,23 @@ paths:
type: string type: string
required: required:
- authToken - authToken
/auth/logout:
get:
summary: Logout and clear session cookie
description: This endpoint will completely clear the session cookie and associated values, logging out the user
tags:
- auth
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
properties:
status:
type: string
example: 'ok'
/user: /user:
get: get:
summary: Returns a list of all users summary: Returns a list of all users

@ -75,7 +75,7 @@ authRoutes.post('/login', async (req, res) => {
req.session.userId = user.id; req.session.userId = user.id;
} }
return res.status(200).json({ status: 'ok' }); return res.status(200).json(user?.filter() ?? {});
} catch (e) { } catch (e) {
console.error(e); console.error(e);
res res
@ -84,4 +84,17 @@ authRoutes.post('/login', async (req, res) => {
} }
}); });
authRoutes.get('/logout', (req, res, next) => {
req.session?.destroy((err) => {
if (err) {
return next({
status: 500,
message: 'Something went wrong while attempting to logout',
});
}
return res.status(200).json({ status: 'ok' });
});
});
export default authRoutes; export default authRoutes;

@ -1,11 +1,20 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import Transition from '../../Transition'; import Transition from '../../Transition';
import { useUser } from '../../../hooks/useUser'; import { useUser } from '../../../hooks/useUser';
import axios from 'axios';
const UserDropdown: React.FC = () => { const UserDropdown: React.FC = () => {
const { user } = useUser(); const { user, revalidate } = useUser();
const [isDropdownOpen, setDropdownOpen] = useState(false); const [isDropdownOpen, setDropdownOpen] = useState(false);
const logout = async () => {
const response = await axios.get('/api/v1/auth/logout');
if (response.data?.status === 'ok') {
revalidate();
}
};
return ( return (
<div className="ml-3 relative"> <div className="ml-3 relative">
<div> <div>
@ -53,6 +62,7 @@ const UserDropdown: React.FC = () => {
href="#" href="#"
className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition ease-in-out duration-150" className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition ease-in-out duration-150"
role="menuitem" role="menuitem"
onClick={() => logout()}
> >
Sign out Sign out
</a> </a>

@ -16,7 +16,7 @@ const Login: React.FC = () => {
const login = async () => { const login = async () => {
const response = await axios.post('/api/v1/auth/login', { authToken }); const response = await axios.post('/api/v1/auth/login', { authToken });
if (response.data?.status === 'OK') { if (response.data?.email) {
revalidate(); revalidate();
} }
}; };

@ -15,7 +15,7 @@ export const UserContext: React.FC<UserContextProps> = ({
initialUser, initialUser,
children, children,
}) => { }) => {
const { user, revalidate } = useUser({ initialData: initialUser }); const { user, error, revalidate } = useUser({ initialData: initialUser });
const router = useRouter(); const router = useRouter();
useEffect(() => { useEffect(() => {
@ -23,10 +23,17 @@ export const UserContext: React.FC<UserContextProps> = ({
}, [router.pathname, revalidate]); }, [router.pathname, revalidate]);
useEffect(() => { useEffect(() => {
if (!router.pathname.match(/(setup|login)/) && !user) { let routing = false;
router.push('/login');
if (
!router.pathname.match(/(setup|login)/) &&
(!user || error) &&
!routing
) {
routing = true;
location.href = '/login';
} }
}, [router, user]); }, [router, user, error]);
return <>{children}</>; return <>{children}</>;
}; };

@ -21,7 +21,12 @@ export const useUser = ({
const initialRef = useRef(initialData); const initialRef = useRef(initialData);
const { data, error, revalidate } = useSwr<User>( const { data, error, revalidate } = useSwr<User>(
id ? `/api/v1/user/${id}` : `/api/v1/auth/me`, id ? `/api/v1/user/${id}` : `/api/v1/auth/me`,
{ initialData: initialRef.current } {
initialData: initialRef.current,
refreshInterval: 30000,
errorRetryInterval: 30000,
shouldRetryOnError: false,
}
); );
return { return {

@ -25,22 +25,24 @@ class CoreApp extends App<AppProps> {
); );
const { ctx, router } = initialProps; const { ctx, router } = initialProps;
let user = undefined; let user = undefined;
try { if (ctx.res) {
// Attempt to get the user by running a request to the local api try {
const response = await axios.get<User>( // Attempt to get the user by running a request to the local api
`http://localhost:${process.env.PORT || 3000}/api/v1/auth/me`, const response = await axios.get<User>(
{ headers: ctx.req ? { cookie: ctx.req.headers.cookie } : undefined } `http://localhost:${process.env.PORT || 3000}/api/v1/auth/me`,
); { headers: ctx.req ? { cookie: ctx.req.headers.cookie } : undefined }
user = response.data; );
} catch (e) { user = response.data;
// If there is no user, and ctx.res is set (to check if we are on the server side) } catch (e) {
// _AND_ we are not already on the login or setup route, redirect to /login with a 307 // If there is no user, and ctx.res is set (to check if we are on the server side)
// before anything actually renders // _AND_ we are not already on the login or setup route, redirect to /login with a 307
if (ctx.res && !router.pathname.match(/(login|setup)/)) { // before anything actually renders
ctx.res.writeHead(307, { if (!router.pathname.match(/(login|setup)/)) {
Location: '/login', ctx.res.writeHead(307, {
}); Location: '/login',
ctx.res.end(); });
ctx.res.end();
}
} }
} }

Loading…
Cancel
Save