Authentication Provider
In this chapter the authentication process with pseudocode will be demoed here.
At first create a react context for the authentication and export it as we will used the AuthContext in multiple places inside the containers, components.
export const AuthContext = React.createContext();
Then we will build the AuthProvider component.
const fakeUserData = {
id: 1,
name: 'Jhon Doe',
avatar: '',
roles: ['USER', 'ADMIN'],
};
/**
* We have used Fake JWT token from "jwt.io"
* This is a sample token to show auth is working
* Your token will come from your server when user successfully loggedIn.
*/
const fakeToken = 'FAKE-JWT-TOKEN-CODE';
const addItem = (key, value = '') => {};
const clearItem = key => {};
const isValidToken = () => {};
const AuthProvider = props => {
const [loggedIn, setLoggedIn] = useState(isValidToken());
const [user, setUser] = useState(null);
const [token, setToken] = useState(null);
const signIn = params => {}
const signUp = params => {};
/**
* For 3rd-party Authentication [e.g. Auth0, firebase, AWS etc]
*
*/
const tokenAuth = (token, user = {}) => {};
const forgetPass = params => {};
const changePass = params => {};
const logOut = () => {};
return (
<AuthContext.Provider
value={{
loggedIn,
logOut,
signIn,
signUp,
forgetPass,
changePass,
tokenAuth,
}}
>
<>{props.children}</>
</AuthContext.Provider>
);
};
export default AuthProvider;
In the code mentioned above, the AuthProvider is build up. All the authentication related functions loggedIn, logOut, signIn ,signUp , forgetPass , changePass, tokenAuth are passing through the AuthContext.
****** Example Usages ******
How to use AuthContext in Login component ??
Suppose you need to create a Login page for the users. But how to use the AuthProvider??
- At create a login form wrapper component using Formik via the initial values & validation schema.
// pseudocode
import { Formik } from 'formik';
import * as Yup from 'yup';
const initialValues = {
email: '',
password: '',
rememberMe: false,
};
const getLoginValidationSchema = () => {
return Yup.object().shape({
email: Yup.string()
.email('Invalid email')
.required('Email is Required!'),
password: Yup.string()
.min(6, 'Password has to be longer than 6 characters!')
.max(20, 'Too Long!')
.required('Password is required!'),
});
};
export default () => {
return (
<Formik
initialValues={initialValues}
onSubmit={handleSubmit}
render={RenderSignInForm}
validationSchema={getLoginValidationSchema}
/>
);
};
- Then Create the login form
// pseudocode
const RenderBasicInfoForm = props => {
const { values, submitCount, handleSubmit } = props;
return (
<FormWrapper>
<Form onSubmit={handleSubmit}>
<Field
component={AntInput}
name="email"
type="text"
size="large"
placeholder="Email"
submitCount={submitCount}
value={values.email}
hasFeedback
/>
<Field
component={AntInput}
name="password"
type="password"
size="large"
placeholder="Password"
value={values.password}
submitCount={submitCount}
hasFeedback
/>
<FieldWrapper className="field-container">
<SwitchWrapper>
<Field
component={AntSwitch}
name="rememberMe"
submitCount={submitCount}
value={values.rememberMe}
/>
<Label>Remember Me</Label>
</SwitchWrapper>
<Link to={FORGET_PASSWORD_PAGE}>Forget Password ?</Link>
</FieldWrapper>
<Button
className="signin-btn"
type="primary"
htmlType="submit"
size="large"
style={{ width: '100%' }}
>
<MdLockOpen />
Login
</Button>
</Form>
</FormWrapper>
);
};
export default RenderBasicInfoForm;
- Your login form is created, now connect the sign in form wrapper component [on step 1] with the AuthProvider!
// pseudocode
import { AuthContext } from '../../context/AuthProvider';
import { Formik } from 'formik';
import * as Yup from 'yup';
import { Redirect } from 'react-router-dom';
export default () => {
const { signIn, loggedIn } = useContext(AuthContext);
if (loggedIn) return <Redirect to={{ pathname: '/' }} />;
const handleSubmit = formProps => {
signIn(formProps);
};
return (
<Formik
initialValues={initialValues}
onSubmit={handleSubmit}
render={RenderSignInForm}
validationSchema={getLoginValidationSchema}
/>
);
};
You can see that we are using useContext _hook here. Using that hook we manipulate the values/functions from the AuthContext.
How to use AuthProvider in where some component need to use this ?
Suppose you need to display a post grid on a page for the user, where it's for the authenticate users only. Then wrap that post grid using the AuthProvider.
// pseudocode
import AuthProvider from 'AUTH-PROVIDER-IMPORT-PATH';
export default function DisplayPosts(props) {
return (
<DisplayPostsPage>
<AuthProvider>
.
.
. Your components will be here...
.
.
</AuthProvider>
</DisplayPostsPage>
);
}
That's the overall process how you can use the AuthProvider and AuthContext in isomorphic-hotel projects.