8000 Add user context flow and fix bugs by davisengeler · Pull Request #2 · Vibe-House-LLC/memeSRC · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Add user context flow and fix bugs #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Dec 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion src/App.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,36 @@
import { useState } from 'react';
import { Auth } from 'aws-amplify';
// routes
import Router from './routes';
// theme
import ThemeProvider from './theme';
// components
import ScrollToTop from './components/scroll-to-top';
import { StyledChart } from './components/chart';
import { UserContext } from './UserContext';

// ----------------------------------------------------------------------

export default function App() {
// Set up the user context
const [user, setUser] = useState(null);
if (!user) {
Auth.currentAuthenticatedUser().then((x) => {
setUser(x) // if an authenticated user is found, set it into the context
console.log(x)
}).catch(() => {
setUser({username: false}) // indicate the context is ready but user is not auth'd
console.log("There wasn't an authenticated user found")
});
}
// Return the App
return (
<ThemeProvider>
<ScrollToTop />
<StyledChart />
<Router />
<UserContext.Provider value={{user, setUser}}>
<Router />
</UserContext.Provider>
</ThemeProvider>
);
}
3 changes: 3 additions & 0 deletions src/UserContext.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { createContext } from 'react'

export const UserContext = createContext(null);
18 changes: 12 additions & 6 deletions src/layouts/dashboard/header/AccountPopover.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { useState } from 'react';
import { useState, useContext } from 'react';
// @mui
import { alpha } from '@mui/material/styles';
import { Box, Divider, Typography, Stack, MenuItem, Avatar, IconButton, Popover } from '@mui/material';
// mocks_
import { useNavigate } from 'react-router-dom';
import { Auth } from 'aws-amplify';
import { UserContext } from '../../../UserContext';
import account from '../../../_mock/account';

// ----------------------------------------------------------------------
Expand All @@ -27,6 +28,8 @@ const MENU_OPTIONS = [
// ----------------------------------------------------------------------

export default function AccountPopover() {
const {user, setUser} = useContext(UserContext)

const [open, setOpen] = useState(null);

const navigate = useNavigate();
Expand All @@ -40,9 +43,12 @@ export default function AccountPopover() {
};

const logout = () => {
Auth.signOut().then(
() => navigate('/login', { replace: true })
).catch((err) => alert(err))
Auth.signOut().then(() => {
setUser(null);
navigate('/login', { replace: true })
}).catch((err) => {
alert(err)
})
}

return (
Expand Down Expand Up @@ -88,10 +94,10 @@ export default function AccountPopover() {
>
<Box sx={{ my: 1.5, px: 2.5 }}>
<Typography variant="subtitle2" noWrap>
{account.displayName}
{user.username}
</Typography>
<Typography variant="body2" sx={{ color: 'text.secondary' }} noWrap>
{account.email}
{user.attributes.email}
</Typography>
</Box>

Expand Down
2 changes: 1 addition & 1 deletion src/layouts/dashboard/header/NotificationsPopover.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export default function NotificationsPopover() {
description: item.message,
avatar: null,
type: 'example',
createdAt: item.createdAt,
createdAt: new Date(item.createdAt),
isUnRead: true,
}
))
Expand Down
53 changes: 17 additions & 36 deletions src/pages/AuthPage.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,12 @@
import { Helmet } from 'react-helmet-async';

import { useState } from 'react';
// @mui
import { useContext } from 'react';
import { styled } from '@mui/material/styles';

import { Container, Typography } from '@mui/material';
import { LoginForm } from '../sections/auth/login';

// hooks
import useResponsive from '../hooks/useResponsive';

// components
import Logo from '../components/logo';
// sections
import VerifyForm from '../sections/auth/login/VerifyForm';
import SignupForm from '../sections/auth/login/SignupForm';
import { UserContext } from '../UserContext';

// ----------------------------------------------------------------------

Expand Down Expand Up @@ -47,26 +39,24 @@ const StyledContent = styled('div')(({ theme }) => ({
// ----------------------------------------------------------------------

export default function AuthPage(props) {
const mdUp = useResponsive('up', 'md');

const [userState, setUserState] = useState("");

const AuthForm = () => {
let formType = <LoginForm />
if (props.method === "signup") {
if (userState.username) {
formType = <VerifyForm username={userState.username} />
} else {
formType = <SignupForm setUserState={setUserState}/>
}
}
return formType
// Set up the user context
const {user, setUser} = useContext(UserContext)

// Prep the auth page content depending on the situation
// TODO: fix issue where you can get "stuck" verifying
// TODO: add auto-login functionality after confirmation
let formType = props.method === "signin" ? <LoginForm /> : <SignupForm setUser={setUser}/>
let formTitle = props.method === "signup" ? "Create Account" : "Sign in"
if (user && user.userConfirmed === false) {
formType = <VerifyForm username={user.username} />
formTitle = "Verify Account"
}

// Return the page
return (
<>
<Helmet>
<title> Verify Email | Minimal UI </title>
<title> {formTitle} • memeSRC </title>
</Helmet>

<StyledRoot>
Expand All @@ -78,21 +68,12 @@ export default function AuthPage(props) {
}}
/>

{mdUp && (
<StyledSection>
<Typography variant="h3" sx={{ px: 5, mt: 10, mb: 5 }}>
Hi, Welcome Back
</Typography>
<img src="/assets/illustrations/illustration_login.png" alt="login" />
</StyledSection>
)}

<Container maxWidth="sm">
<StyledContent>
<Typography variant="h4" gutterBottom marginBottom={8}>
Verify your account
{formTitle}
</Typography>
<AuthForm />
{formType}
</StyledContent>
</Container>
</StyledRoot>
Expand Down
32 changes: 16 additions & 16 deletions src/pages/DashboardAppPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,25 +26,25 @@ import { createGlobalMessage } from '../graphql/mutations';
export default function DashboardAppPage() {
const theme = useTheme();

async function createNewGlobalMessage(title, message, timestamp) {
const newGlobalMessage = {
input: {
title,
message,
timestamp,
},
};
// async function createNewGlobalMessage(title, message, timestamp) {
// const newGlobalMessage = {
// input: {
// title,
// message,
// timestamp,
// },
// };

const result = await API.graphql(graphqlOperation(createGlobalMessage, newGlobalMessage));
// const result = await API.graphql(graphqlOperation(createGlobalMessage, newGlobalMessage));

return result.data.createGlobalMessage;
}
// return result.data.createGlobalMessage;
// }

createNewGlobalMessage("Example 1", "This is the first example message.", Date.now()).then( x => {
console.log(x)
}).catch( x => {
console.log(x)
})
// createNewGlobalMessage("Example 1", "This is the first example message.", Date.now()).then( x => {
// console.log(x)
// }).catch( x => {
// console.log(x)
// })

return (
<>
Expand Down
29 changes: 13 additions & 16 deletions src/sections/auth/login/CheckAuth.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
import { Auth } from "aws-amplify";
import { useEffect, useState } from "react";
import { useContext, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { UserContext } from "../../../UserContext";

export default function CheckAuth(props) {
const navigate = useNavigate();
const [isSignedIn, setSignedIn] = useState(null);
const [content, setContent] = useState(null);
const {user, setUser} = useContext(UserContext);

useEffect(() => {
Auth.currentAuthenticatedUser().then(() =>
{
setSignedIn(true)
}).catch(() => {
setSignedIn(false)
});
});
if (user) { // we only want this logic to occur after user context is prepped
if (user.username) {
setContent(props.children);
} else {
navigate('/login', { replace: true });
}
}
})

if (isSignedIn === true) {
return props.children;
}

if (isSignedIn === false) {
navigate('/login', { replace: true });
}
return content
}
25 changes: 19 additions & 6 deletions src/sections/auth/login/LoginForm.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { useState } from 'react';
import { useContext, useState } from 'react';
import { useNavigate } from 'react-router-dom';
// @mui
import { Link, Stack, IconButton, InputAdornment, TextField, Checkbox } from '@mui/material';
import { Link, Stack, IconButton, InputAdornment, TextField, Checkbox, FormControlLabel } from '@mui/material';
import { LoadingButton } from '@mui/lab';
// components
import { Auth } from 'aws-amplify';
import Iconify from '../../../components/iconify';
import { UserContext } from '../../../UserContext';


// ----------------------------------------------------------------------
Expand All @@ -16,18 +17,22 @@ export default function LoginForm() {
const [showPassword, setShowPassword] = useState(false);

const [staySignedIn, setStaySignedIn] = useState(false);

const [username, setUsername] = useState(null);

const [password, setPassword] = useState(null);

const {user, setUser} = useContext(UserContext)


const handleClick = () => {
if (!staySignedIn) {
Auth.configure({ storage: window.sessionStorage })
} else {
Auth.configure({ storage: window.localStorage })
}
Auth.signIn(username, password).then(() => {
Auth.signIn(username, password).then((x) => {
setUser(x)
navigate('/dashboard/app', { replace: true })
}).catch((err DB95 ) => {
alert(err);
Expand Down Expand Up @@ -57,9 +62,17 @@ export default function LoginForm() {
</Stack>

<Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ my: 2 }}>
<Checkbox name="remember" label="Remember me" => setStaySignedIn(x.target.checked)}/>
<FormControlLabel
control={
<Checkbox
name="remember"
=> setStaySignedIn(event.target.checked)}
/>
}
label="Remember me"
/>
<Link variant="subtitle2" underline="hover">
Forgot password?
Forgot your password?
</Link>
</Stack>

Expand Down
5 changes: 2 additions & 3 deletions src/sections/auth/login/SignupForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,8 @@ export default function SignupForm(props) {
'disabled': true,
'text': 'Sign Up Complete'
});
props.setUserState({
username: result.user.username
})
console.log(result)
props.setUser(result.user)
console.log(result);
}).catch((err) => {
setSignupStatus({
Expand Down
0