User Context (#51)

* feat(frontend): user Context / useUser hook

Adds a UserContext to wrap the app and load/cache the user when the website renders. Also adds the
useUser hook to pull in user data anywhere its needed on the site. This commit also adds redirection
to the login page for users who are not signed in

* fix(frontend): use process.env.PORT for user request on server side (defaults to 3000)

* docs(frontend): added documentation/notes for how the user context/login works
This commit is contained in:
sct
2020-09-05 13:16:26 +09:00
committed by GitHub
parent 350af66129
commit 190a8831c7
7 changed files with 173 additions and 14 deletions

View File

@@ -1,7 +1,38 @@
import React from 'react';
import React, { useEffect, useState } from 'react';
import PlexLoginButton from '../PlexLoginButton';
import { useUser } from '../../hooks/useUser';
import axios from 'axios';
import { useRouter } from 'next/dist/client/router';
const Login: React.FC = () => {
const [authToken, setAuthToken] = useState<string | undefined>(undefined);
const { user, revalidate } = useUser();
const router = useRouter();
// Effect that is triggered when the `authToken` comes back from the Plex OAuth
// We take the token and attempt to login. If we get a success message, we will
// ask swr to revalidate the user which _shouid_ come back with a valid user.
useEffect(() => {
const login = async () => {
const response = await axios.post('/api/v1/auth/login', { authToken });
if (response.data?.status === 'OK') {
revalidate();
}
};
if (authToken) {
login();
}
}, [authToken, revalidate]);
// Effect that is triggered whenever `useUser`'s user changes. If we get a new
// valid user, we redirect the user to the home page as the login was successful.
useEffect(() => {
if (user) {
router.push('/');
}
}, [user, router]);
return (
<div className="w-full pt-10">
<form className="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
@@ -13,9 +44,7 @@ const Login: React.FC = () => {
</div>
<div className="flex items-center justify-center">
<PlexLoginButton
onAuthToken={(authToken) =>
console.log(`auth token is: ${authToken}`)
}
onAuthToken={(authToken) => setAuthToken(authToken)}
/>
</div>
</form>