Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
WIP Move auth mutations to AuthProvider; use context to store user
Marcin Gębala3ac660e6c0a7
diff --git a/saleor/static/dashboard-next/AppRoot.tsx b/saleor/static/dashboard-next/AppRoot.tsxindex 4a0213c042..cff96cca42 100644--- a/saleor/static/dashboard-next/AppRoot.tsx+++ b/saleor/static/dashboard-next/AppRoot.tsx@@ -11,6 +11,7 @@ import Typography from "@material-ui/core/Typography";import MenuIcon from "@material-ui/icons/Menu";import * as React from "react";+import { UserContext } from "./auth";import Navigator from "./components/Navigator";import i18n from "./i18n";@@ -91,15 +92,11 @@ const ResponsiveDrawer = decorate<ResponsiveDrawerProps>());-interface AppRootProps {- logout: () => void;-}-interface AppRootState {open: boolean;}-export const AppRoot = decorate<AppRootProps>(+export const AppRoot = decorate(class InnerAppRoot extends React.Component<WithStyles<| "root"@@ -111,7 +108,7 @@ export const AppRoot = decorate<AppRootProps>(| "content"| "contentShift"| "toolBar"- > & AppRootProps,+ >,AppRootState> {state = { open: false };@@ -121,90 +118,96 @@ export const AppRoot = decorate<AppRootProps>(};render() {- const { children, classes, logout } = this.props;+ const { children, classes } = this.props;const { open } = this.state;return (- <Navigator>- {navigate => (- <div className={classes.appFrame}>- <AppBar className={classes.appBar}>- <Toolbar disableGutters className={classes.toolBar}>- <Hidden mdUp>- <IconButton- color="inherit"- aria-label="open drawer"- onClick={() =>- this.setState(({ open }) => ({- open: !open- }))- }- className={classes.menuButton}- >- <MenuIcon />- </IconButton>- </Hidden>- <Typography- noWrap- variant="title"- color="inherit"- dangerouslySetInnerHTML={{- __html: i18n.t("<strong>Saleor</strong> Dashboard")- }}- />- </Toolbar>- </AppBar>- <ResponsiveDrawer onClose={this.closeDrawer} open={open}>- <List component="nav">- <ListItem- button- onClick={() => {- this.closeDrawer();- navigate("/");- }}- >- <ListItemText primary={i18n.t("Home")} />- </ListItem>- <ListItem- button- onClick={() => {- this.closeDrawer();- navigate("/categories/");- }}- >- <ListItemText primary={i18n.t("Categories")} />- </ListItem>- <ListItem- button- onClick={() => {- this.closeDrawer();- navigate("/pages/");- }}- >- <ListItemText primary={i18n.t("Pages")} />- </ListItem>- <ListItem- button- onClick={() => {- this.closeDrawer();- navigate("/products/");- }}- >- <ListItemText primary={i18n.t("Products")} />- </ListItem>- <ListItem- button- onClick={() => logout()}- >- {/* FIXME: move logout button to appropriate place */}- <ListItemText primary={i18n.t("Logout")} />- </ListItem>- </List>- </ResponsiveDrawer>- <main className={classes.content}>{children}</main>- </div>- )}- </Navigator>+ <UserContext.Consumer>+ {({ logout }) => {+ return (+ <Navigator>+ {navigate => (+ <div className={classes.appFrame}>+ <AppBar className={classes.appBar}>+ <Toolbar disableGutters className={classes.toolBar}>+ <Hidden mdUp>+ <IconButton+ color="inherit"+ aria-label="open drawer"+ onClick={() =>+ this.setState(({ open }) => ({+ open: !open+ }))+ }+ className={classes.menuButton}+ >+ <MenuIcon />+ </IconButton>+ </Hidden>+ <Typography+ noWrap+ variant="title"+ color="inherit"+ dangerouslySetInnerHTML={{+ __html: i18n.t("<strong>Saleor</strong> Dashboard")+ }}+ />+ </Toolbar>+ </AppBar>+ <ResponsiveDrawer onClose={this.closeDrawer} open={open}>+ <List component="nav">+ <ListItem+ button+ onClick={() => {+ this.closeDrawer();+ navigate("/");+ }}+ >+ <ListItemText primary={i18n.t("Home")} />+ </ListItem>+ <ListItem+ button+ onClick={() => {+ this.closeDrawer();+ navigate("/categories/");+ }}+ >+ <ListItemText primary={i18n.t("Categories")} />+ </ListItem>+ <ListItem+ button+ onClick={() => {+ this.closeDrawer();+ navigate("/pages/");+ }}+ >+ <ListItemText primary={i18n.t("Pages")} />+ </ListItem>+ <ListItem+ button+ onClick={() => {+ this.closeDrawer();+ navigate("/products/");+ }}+ >+ <ListItemText primary={i18n.t("Products")} />+ </ListItem>+ <ListItem+ button+ onClick={() => logout()}+ >+ {/* FIXME: move logout button to appropriate place */}+ <ListItemText primary={i18n.t("Logout")} />+ </ListItem>+ </List>+ </ResponsiveDrawer>+ <main className={classes.content}>{children}</main>+ </div>+ )}+ </Navigator>+ )+ }}+ </UserContext.Consumer>);}}diff --git a/saleor/static/dashboard-next/auth/AuthProvider.tsx b/saleor/static/dashboard-next/auth/AuthProvider.tsxindex 68f918f839..92475d970a 100644--- a/saleor/static/dashboard-next/auth/AuthProvider.tsx+++ b/saleor/static/dashboard-next/auth/AuthProvider.tsx@@ -2,16 +2,31 @@ import * as React from "react";import { MutationFn } from "../../../../node_modules/react-apollo";import {+ TokenAuthMutation,+ TokenAuthMutationVariables,UserFragment,VerifyTokenMutation,VerifyTokenMutationVariables} from "../gql-types";-import { getAuthToken, removeAuthToken } from "./index";-import { tokenVerifyMutation, TypedVerifyTokenMutation } from "./mutations";+import {+ getAuthToken,+ removeAuthToken,+ setAuthToken,+ UserContext+} from "./index";+import {+ tokenAuthMutation,+ tokenVerifyMutation,+ TypedTokenAuthMutation,+ TypedVerifyTokenMutation+} from "./mutations";interface AuthProviderProps {+ authenticate: MutationFn<TokenAuthMutation, TokenAuthMutationVariables>;+ authResult: any;children: any;verifyToken: MutationFn<VerifyTokenMutation, VerifyTokenMutationVariables>;+ verifyResult: any;}interface AuthProviderState {@@ -27,24 +42,35 @@ class AuthProvider extends React.Component<this.state = { user: undefined };}+ componentWillReceiveProps(props) {+ if (props.authResult.called && !props.authResult.loading) {+ this.setState({ user: props.authResult.data.tokenCreate.user });+ setAuthToken(props.authResult.data.tokenCreate.token);+ }+ }+componentDidMount() {- const { verifyToken } = this.props;const { user } = this.state;const token = getAuthToken();if (!!token && !user) {- verifyToken({ variables: { token } })+ this.props+ .verifyToken({ variables: { token } }).then(response => {if (response) {- this.setState({ user: response.data.tokenVerify.user })+ this.setState({ user: response.data.tokenVerify.user });}}).catch(error => {- this.clearUser();+ this.logout();});}}- clearUser = () => {+ login = (email: string, password: string) => {+ this.props.authenticate({ variables: { email, password } });+ };++ logout = () => {this.setState({ user: undefined });removeAuthToken();};@@ -54,43 +80,46 @@ class AuthProvider extends React.Component<};render() {- const { children } = this.props;+ const { authResult, verifyResult } = this.props;const { user } = this.state;const isAuthenticated = !!user;-- if (typeof children === "function") {- return children({ isAuthenticated, logout: this.clearUser });- }- if (React.Children.count(children) > 0) {- return React.Children.only(children);- }- return null;+ const loading = authResult.loading || verifyResult.loading;+ return (+ <UserContext.Provider+ value={{ user, login: this.login, logout: this.logout }}+ >+ {loading ? (+ // FIXME: render loading state+ <div>Loading</div>+ ) : (+ this.props.children({ isAuthenticated, logout: this.logout })+ )}+ </UserContext.Provider>+ );}}const AuthProviderOperations: React.StatelessComponent<any> = ({- children,- logout+ children}) => (- <TypedVerifyTokenMutation mutation={tokenVerifyMutation}>- {(verifyToken, { loading, data, error }) => (- <AuthProvider verifyToken={verifyToken}>- {({ isAuthenticated, logout }) => {- if (loading) {- // FIXME: "Show more serious loading state here"- return <div>Loading...</div>- }- if (typeof children === "function") {- return children({ isAuthenticated, logout });- }- if (React.Children.count(children) > 0) {- return React.Children.only(children);- }- return null;- }}- </AuthProvider>+ <TypedTokenAuthMutation mutation={tokenAuthMutation}>+ {(authenticate, tokenAuthResult) => (+ <TypedVerifyTokenMutation mutation={tokenVerifyMutation}>+ {(verifyToken, verifyTokenResult) => (+ <AuthProvider+ authenticate={authenticate}+ authResult={tokenAuthResult}+ verifyToken={verifyToken}+ verifyResult={verifyTokenResult}+ >+ {({ isAuthenticated }) => {+ return children({ isAuthenticated });+ }}+ </AuthProvider>+ )}+ </TypedVerifyTokenMutation>)}- </TypedVerifyTokenMutation>+ </TypedTokenAuthMutation>);export default AuthProviderOperations;diff --git a/saleor/static/dashboard-next/auth/index.tsx b/saleor/static/dashboard-next/auth/index.tsxindex 9cf1def45b..3168385ff5 100644--- a/saleor/static/dashboard-next/auth/index.tsx+++ b/saleor/static/dashboard-next/auth/index.tsx@@ -7,9 +7,17 @@ const Component: React.StatelessComponent<RouteComponentProps<any>> = ({location,match}) => {- return <LoginPage onAccept={setAuthToken} />;+ return <LoginPage />;};+interface UserContext {+ user?: any;+ login?: (username: string, password: string) => void;+ logout?: () => void;+}++export const UserContext = React.createContext<UserContext>({});+export const getAuthToken = () => localStorage.getItem("dashboardAuth");export const setAuthToken = (token: string) =>diff --git a/saleor/static/dashboard-next/auth/views/LoginPage.tsx b/saleor/static/dashboard-next/auth/views/LoginPage.tsxindex e0230d4c84..de771c5aba 100644--- a/saleor/static/dashboard-next/auth/views/LoginPage.tsx+++ b/saleor/static/dashboard-next/auth/views/LoginPage.tsx@@ -4,7 +4,7 @@ import * as React from "react";import Form, { FormProps } from "../../components/Form";import LoginCard from "../../components/LoginCard";import { TokenAuthMutationVariables } from "../../gql-types";-import { tokenAuthMutation, TypedTokenAuthMutation } from "../mutations";+import { UserContext } from "../index";const decorate = withStyles(theme => ({root: {@@ -17,50 +17,13 @@ const decorate = withStyles(theme => ({}}));-interface TokenAuthProviderProps {- children:- | ((- authorize: (email: string, password: string) => void- ) => React.ReactElement<any>)- | React.ReactNode;- onAccept(token: string);-}--const TokenAuthProvider: React.StatelessComponent<TokenAuthProviderProps> = ({- children,- onAccept-}) => (- <TypedTokenAuthMutation mutation={tokenAuthMutation}>- {(mutate, { called, data, error, loading }) => {- if (called && !loading && !error) {- const { token } = data.tokenCreate;- onAccept(token);- // FIXME: set user in AuthProvider's state- }- if (typeof children === "function") {- return children((email, password) =>- mutate({ variables: { email, password } })- );- }- if (React.Children.count(children) > 0) {- return React.Children.only(children);- }- return null;- }}- </TypedTokenAuthMutation>-);-const LoginForm: React.ComponentType<FormProps<TokenAuthMutationVariables>> = Form;-interface LoginPageProps {- onAccept(token: string);-}--const LoginPage = decorate<LoginPageProps>(({ classes, onAccept }) => (- <TokenAuthProvider onAccept={onAccept}>- {login => (+const LoginPage = decorate(({ classes }) => (+ <UserContext.Consumer>+ {({ login }) => (<LoginForminitial={{ email: "", password: "" }}onSubmit={data => login(data.email, data.password)}@@ -77,7 +40,7 @@ const LoginPage = decorate<LoginPageProps>(({ classes, onAccept }) => ()}</LoginForm>)}- </TokenAuthProvider>+ </UserContext.Consumer>));export default LoginPage;diff --git a/saleor/static/dashboard-next/index.tsx b/saleor/static/dashboard-next/index.tsxindex 8bc9c1e065..5309fc5e6c 100644--- a/saleor/static/dashboard-next/index.tsx+++ b/saleor/static/dashboard-next/index.tsx@@ -67,21 +67,19 @@ render(<MessageManager><CssBaseline /><AuthProvider>- {({ isAuthenticated, logout }) => {- return (- isAuthenticated ? (- <AppRoot logout={ logout }>- <Switch>- <Route path="/categories" component={CategorySection} />- <Route path="/pages" component={PageSection} />- <Route path="/products" component={ProductSection} />- </Switch>- </AppRoot>- ) : (- <Route component={Auth} />- )+ {({ isAuthenticated }) => (+ isAuthenticated ? (+ <AppRoot>+ <Switch>+ <Route path="/categories" component={CategorySection} />+ <Route path="/pages" component={PageSection} />+ <Route path="/products" component={ProductSection} />+ </Switch>+ </AppRoot>+ ) : (+ <Route component={Auth} />)- }}+ )}</AuthProvider></MessageManager></MuiThemeProvider>