Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. import cookie from 'react-cookie';
  2. import Router from 'next/router';
  3. import { create } from 'apisauce';
  4.  
  5. // Authenticate with a JWT retrieved through some API call.
  6. export const authenticate = token => {
  7. cookie.save('userToken', token, { path: '/' }); // Stores token for later auth check.
  8. Router.push('/profile'); // Navigates.
  9. };
  10.  
  11. // Method to get the JWT token.
  12. export const getUserToken = () => cookie.load('userToken');
  13.  
  14. // Check if your authenticated by checking the cookie.
  15. // This works both on the server and client because `react-cookie` is isomorphic.
  16. export const isAuthenticated = () => Boolean(getUserToken());
  17.  
  18. // Uses apisauce to make requests to the API.
  19. export const api = create({ baseURL: BASE_URL });
  20.  
  21. // Uses the stored token to authenticate.
  22. const authAPI = () => api.setHeaders({ 'x-access-token': getUserToken() });
  23.  
  24. // Call it immidiately: If a token cookie already exists API calls will be authenticated.
  25. authAPI();
  26.  
  27.  
  28. /*
  29. -----------------------------------------------------------------------------------
  30. |
  31. | Usage
  32. |
  33. -----------------------------------------------------------------------------------
  34. */
  35.  
  36. // To login: 1) get a token 2) store token 3) update apisauce.
  37. const res = api.post(AUTH_PATH, {
  38. username,
  39. password,
  40. });
  41. authenticate(res.data.cookie);
  42. authAPI();
  43.  
  44. // To check what to render:
  45. const App = () => (
  46. isAuthenticated() ? <div>Authenticated</div> : <div>Please login</div>
  47. );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement