Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add AuthProvider component

Marcin Gębala3fce0dc019b0
diff --git a/saleor/static/dashboard-next/AppRoot.tsx b/saleor/static/dashboard-next/AppRoot.tsx
index 39a7a02bc2..4a0213c042 100644
--- a/saleor/static/dashboard-next/AppRoot.tsx
+++ b/saleor/static/dashboard-next/AppRoot.tsx
@@ -91,11 +91,15 @@ const ResponsiveDrawer = decorate<ResponsiveDrawerProps>(
)
);
+interface AppRootProps {
+ logout: () => void;
+}
+
interface AppRootState {
open: boolean;
}
-export const AppRoot = decorate<{}>(
+export const AppRoot = decorate<AppRootProps>(
class InnerAppRoot extends React.Component<
WithStyles<
| "root"
@@ -107,7 +111,7 @@ export const AppRoot = decorate<{}>(
| "content"
| "contentShift"
| "toolBar"
- >,
+ > & AppRootProps,
AppRootState
> {
state = { open: false };
@@ -117,7 +121,7 @@ export const AppRoot = decorate<{}>(
};
render() {
- const { children, classes } = this.props;
+ const { children, classes, logout } = this.props;
const { open } = this.state;
return (
@@ -188,6 +192,13 @@ export const AppRoot = decorate<{}>(
>
<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>
diff --git a/saleor/static/dashboard-next/auth/AuthProvider.tsx b/saleor/static/dashboard-next/auth/AuthProvider.tsx
new file mode 100644
index 0000000000..68f918f839
--- /dev/null
+++ b/saleor/static/dashboard-next/auth/AuthProvider.tsx
@@ -0,0 +1,96 @@
+import * as React from "react";
+
+import { MutationFn } from "../../../../node_modules/react-apollo";
+import {
+ UserFragment,
+ VerifyTokenMutation,
+ VerifyTokenMutationVariables
+} from "../gql-types";
+import { getAuthToken, removeAuthToken } from "./index";
+import { tokenVerifyMutation, TypedVerifyTokenMutation } from "./mutations";
+
+interface AuthProviderProps {
+ children: any;
+ verifyToken: MutationFn<VerifyTokenMutation, VerifyTokenMutationVariables>;
+}
+
+interface AuthProviderState {
+ user: UserFragment;
+}
+
+class AuthProvider extends React.Component<
+ AuthProviderProps,
+ AuthProviderState
+> {
+ constructor(props) {
+ super(props);
+ this.state = { user: undefined };
+ }
+
+ componentDidMount() {
+ const { verifyToken } = this.props;
+ const { user } = this.state;
+ const token = getAuthToken();
+ if (!!token && !user) {
+ verifyToken({ variables: { token } })
+ .then(response => {
+ if (response) {
+ this.setState({ user: response.data.tokenVerify.user })
+ }
+ })
+ .catch(error => {
+ this.clearUser();
+ });
+ }
+ }
+
+ clearUser = () => {
+ this.setState({ user: undefined });
+ removeAuthToken();
+ };
+
+ setUser = (user: UserFragment) => {
+ this.setState({ user });
+ };
+
+ render() {
+ const { children } = 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 AuthProviderOperations: React.StatelessComponent<any> = ({
+ children,
+ logout
+}) => (
+ <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>
+ )}
+ </TypedVerifyTokenMutation>
+);
+
+export default AuthProviderOperations;
diff --git a/saleor/static/dashboard-next/auth/mutations.ts b/saleor/static/dashboard-next/auth/mutations.ts
index f1348f5fba..0b80882b1a 100644
--- a/saleor/static/dashboard-next/auth/mutations.ts
+++ b/saleor/static/dashboard-next/auth/mutations.ts
@@ -2,12 +2,38 @@ import gql from "graphql-tag";
import * as React from "react";
import { Mutation, MutationProps } from "react-apollo";
-import { TokenAuthMutation, TokenAuthMutationVariables } from "../gql-types";
+import {
+ TokenAuthMutation,
+ TokenAuthMutationVariables,
+ VerifyTokenMutation,
+ VerifyTokenMutationVariables
+} from "../gql-types";
+
+export const fragmentUser = gql`
+ fragment User on User {
+ id
+ email
+ isStaff
+ note
+ permissions {
+ code
+ name
+ }
+ }
+`;
export const tokenAuthMutation = gql`
+ ${fragmentUser}
mutation TokenAuth($email: String!, $password: String!) {
tokenCreate(email: $email, password: $password) {
token
+ errors {
+ field
+ message
+ }
+ user {
+ ...User
+ }
}
}
`;
@@ -15,3 +41,19 @@ export const tokenAuthMutation = gql`
export const TypedTokenAuthMutation: React.ComponentType<
MutationProps<TokenAuthMutation, TokenAuthMutationVariables>
> = Mutation;
+
+export const tokenVerifyMutation = gql`
+ ${fragmentUser}
+ mutation VerifyToken($token: String!) {
+ tokenVerify(token: $token) {
+ payload
+ user {
+ ...User
+ }
+ }
+ }
+`;
+
+export const TypedVerifyTokenMutation: React.ComponentType<
+ MutationProps<VerifyTokenMutation, VerifyTokenMutationVariables>
+> = Mutation;
diff --git a/saleor/static/dashboard-next/auth/views/LoginPage.tsx b/saleor/static/dashboard-next/auth/views/LoginPage.tsx
index 67f30036f3..e0230d4c84 100644
--- a/saleor/static/dashboard-next/auth/views/LoginPage.tsx
+++ b/saleor/static/dashboard-next/auth/views/LoginPage.tsx
@@ -1,6 +1,5 @@
import { withStyles } from "@material-ui/core/styles";
import * as React from "react";
-import { Redirect } from "react-router-dom";
import Form, { FormProps } from "../../components/Form";
import LoginCard from "../../components/LoginCard";
@@ -36,7 +35,7 @@ const TokenAuthProvider: React.StatelessComponent<TokenAuthProviderProps> = ({
if (called && !loading && !error) {
const { token } = data.tokenCreate;
onAccept(token);
- return <Redirect to="/" />;
+ // FIXME: set user in AuthProvider's state
}
if (typeof children === "function") {
return children((email, password) =>
diff --git a/saleor/static/dashboard-next/gql-types.ts b/saleor/static/dashboard-next/gql-types.ts
index 33d0ec7ec6..b626451373 100644
--- a/saleor/static/dashboard-next/gql-types.ts
+++ b/saleor/static/dashboard-next/gql-types.ts
@@ -16,6 +16,50 @@ export interface TokenAuthMutationVariables {
export interface TokenAuthMutation {
tokenCreate: {
token: string | null,
+ errors: Array< {
+ // Name of a field that caused the error. A value of
+ // `null` indicates that the error isn't associated with a particular
+ // field.
+ field: string | null,
+ // The error message.
+ message: string | null,
+ } | null > | null,
+ user: {
+ // The ID of the object.
+ id: string,
+ email: string,
+ isStaff: boolean,
+ note: string | null,
+ permissions: Array< {
+ // Internal code for permission.
+ code: string,
+ // Describe action(s) allowed to do by permission.
+ name: string,
+ } | null > | null,
+ } | null,
+ } | null,
+};
+
+export interface VerifyTokenMutationVariables {
+ token: string,
+};
+
+export interface VerifyTokenMutation {
+ tokenVerify: {
+ payload: string | null,
+ user: {
+ // The ID of the object.
+ id: string,
+ email: string,
+ isStaff: boolean,
+ note: string | null,
+ permissions: Array< {
+ // Internal code for permission.
+ code: string,
+ // Describe action(s) allowed to do by permission.
+ name: string,
+ } | null > | null,
+ } | null,
} | null,
};
@@ -1081,6 +1125,20 @@ export interface ProductVariantDetailsQuery {
} | null,
};
+export interface UserFragment {
+ // The ID of the object.
+ id: string,
+ email: string,
+ isStaff: boolean,
+ note: string | null,
+ permissions: Array< {
+ // Internal code for permission.
+ code: string,
+ // Describe action(s) allowed to do by permission.
+ name: string,
+ } | null > | null,
+};
+
export interface MoneyFragment {
// Amount of money.
amount: number,
diff --git a/saleor/static/dashboard-next/index.tsx b/saleor/static/dashboard-next/index.tsx
index 6b19cee82d..8bc9c1e065 100644
--- a/saleor/static/dashboard-next/index.tsx
+++ b/saleor/static/dashboard-next/index.tsx
@@ -13,6 +13,7 @@ import * as Cookies from "universal-cookie";
import AppRoot from "./AppRoot";
import Auth, { getAuthToken, removeAuthToken } from "./auth";
+import AuthProvider from "./auth/AuthProvider";
import CategorySection from "./categories";
import { MessageManager } from "./components/messages";
import "./i18n";
@@ -65,13 +66,23 @@ render(
<MuiThemeProvider theme={theme}>
<MessageManager>
<CssBaseline />
- <AppRoot>
- <Switch>
- <Route path="/categories" component={CategorySection} />
- <Route path="/pages" component={PageSection} />
- <Route path="/products" component={ProductSection} />
- </Switch>
- </AppRoot>
+ <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} />
+ )
+ )
+ }}
+ </AuthProvider>
</MessageManager>
</MuiThemeProvider>
</BrowserRouter>