Skip to content

Commit

Permalink
feat: logout route/sign out button (#54)
Browse files Browse the repository at this point in the history
  • Loading branch information
sct committed Sep 6, 2020
1 parent e6349c1 commit cb9098f
Show file tree
Hide file tree
Showing 7 changed files with 79 additions and 29 deletions.
23 changes: 18 additions & 5 deletions server/overseerr-api.yml
Original file line number Diff line number Diff line change
Expand Up @@ -457,10 +457,7 @@ paths:
content:
application/json:
schema:
type: object
properties:
status:
type: string
$ref: '#/components/schemas/User'
requestBody:
required: true
content:
Expand All @@ -472,7 +469,23 @@ paths:
type: string
required:
- 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:
get:
summary: Returns a list of all users
Expand Down
15 changes: 14 additions & 1 deletion server/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ authRoutes.post('/login', async (req, res) => {
req.session.userId = user.id;
}

return res.status(200).json({ status: 'ok' });
return res.status(200).json(user?.filter() ?? {});
} catch (e) {
console.error(e);
res
Expand All @@ -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;
12 changes: 11 additions & 1 deletion src/components/Layout/UserDropdown/index.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import React, { useState } from 'react';
import Transition from '../../Transition';
import { useUser } from '../../../hooks/useUser';
import axios from 'axios';

const UserDropdown: React.FC = () => {
const { user } = useUser();
const { user, revalidate } = useUser();
const [isDropdownOpen, setDropdownOpen] = useState(false);

const logout = async () => {
const response = await axios.get('/api/v1/auth/logout');

if (response.data?.status === 'ok') {
revalidate();
}
};

return (
<div className="ml-3 relative">
<div>
Expand Down Expand Up @@ -53,6 +62,7 @@ const UserDropdown: React.FC = () => {
href="#"
className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition ease-in-out duration-150"
role="menuitem"
onClick={() => logout()}
>
Sign out
</a>
Expand Down
2 changes: 1 addition & 1 deletion src/components/Login/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const Login: React.FC = () => {
const login = async () => {
const response = await axios.post('/api/v1/auth/login', { authToken });

if (response.data?.status === 'OK') {
if (response.data?.email) {
revalidate();
}
};
Expand Down
15 changes: 11 additions & 4 deletions src/context/UserContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,25 @@ export const UserContext: React.FC<UserContextProps> = ({
initialUser,
children,
}) => {
const { user, revalidate } = useUser({ initialData: initialUser });
const { user, error, revalidate } = useUser({ initialData: initialUser });
const router = useRouter();

useEffect(() => {
revalidate();
}, [router.pathname, revalidate]);

useEffect(() => {
if (!router.pathname.match(/(setup|login)/) && !user) {
router.push('/login');
let routing = false;

if (
!router.pathname.match(/(setup|login)/) &&
(!user || error) &&
!routing
) {
routing = true;
location.href = '/login';
}
}, [router, user]);
}, [router, user, error]);

return <>{children}</>;
};
7 changes: 6 additions & 1 deletion src/hooks/useUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,12 @@ export const useUser = ({
const initialRef = useRef(initialData);
const { data, error, revalidate } = useSwr<User>(
id ? `/api/v1/user/${id}` : `/api/v1/auth/me`,
{ initialData: initialRef.current }
{
initialData: initialRef.current,
refreshInterval: 30000,
errorRetryInterval: 30000,
shouldRetryOnError: false,
}
);

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

Expand Down

0 comments on commit cb9098f

Please sign in to comment.