Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import cookie from 'react-cookie';
- import Router from 'next/router';
- import { create } from 'apisauce';
- // Authenticate with a JWT retrieved through some API call.
- export const authenticate = token => {
- cookie.save('userToken', token, { path: '/' }); // Stores token for later auth check.
- Router.push('/profile'); // Navigates.
- };
- // Method to get the JWT token.
- export const getUserToken = () => cookie.load('userToken');
- // Check if your authenticated by checking the cookie.
- // This works both on the server and client because `react-cookie` is isomorphic.
- export const isAuthenticated = () => Boolean(getUserToken());
- // Uses apisauce to make requests to the API.
- export const api = create({ baseURL: BASE_URL });
- // Uses the stored token to authenticate.
- const authAPI = () => api.setHeaders({ 'x-access-token': getUserToken() });
- // Call it immidiately: If a token cookie already exists API calls will be authenticated.
- authAPI();
- /*
- -----------------------------------------------------------------------------------
- |
- | Usage
- |
- -----------------------------------------------------------------------------------
- */
- // To login: 1) get a token 2) store token 3) update apisauce.
- const res = api.post(AUTH_PATH, {
- username,
- password,
- });
- authenticate(res.data.cookie);
- authAPI();
- // To check what to render:
- const App = () => (
- isAuthenticated() ? <div>Authenticated</div> : <div>Please login</div>
- );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement