Advertisement
Guest User

Untitled

a guest
Feb 19th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.35 KB | None | 0 0
  1. import {AsyncStorage} from 'react-native';
  2. import moment from 'moment';
  3. import WarmupController from "../controllers/WarmupController";
  4.  
  5. /**
  6. * This middleware is meant to be the refresher of the authentication token, on each request to the API,
  7. * it will first call refresh token endpoint
  8. * @returns {function(*=): Function}
  9. * @param store
  10. */
  11. const tokenMiddleware = store => next => action => {
  12. if (typeof action === 'object') {
  13. Promise.all([
  14. AsyncStorage.getItem('rToken'),
  15. AsyncStorage.getItem('eToken')
  16. ]).then((values => {
  17. if (isExpired(values[1])) {
  18. // this will expand the validity of our token
  19. WarmupController.refreshAccessToken(values[0]).then(() => {
  20. return next(action);
  21. }).catch(() => {
  22. return next(action);
  23. });
  24. } else {
  25. return next(action);
  26. }
  27. }));
  28. } else {
  29. return next(action);
  30. }
  31. };
  32.  
  33. function isExpired(expiresIn) {
  34. // We refresh the token 3.5 hours before it expires(12600 seconds) (lifetime on server 25200seconds)
  35. return moment.unix(expiresIn).diff(moment(), 'seconds') < 12600;
  36. }
  37.  
  38. export default tokenMiddleware;
  39.  
  40. static async refreshAccessToken(rToken) {
  41. if (rToken) {
  42. let formData = new FormData();
  43. formData.append("refresh_token", rToken);
  44.  
  45. return await fetch('/token/refresh',
  46. {
  47. method: 'POST',
  48. body: formData
  49. })
  50. .then(response => response.json())
  51. .then((data) => {
  52. let decoded = jwt_decode(data.token);
  53. LoginController._storeToken(data, decoded)
  54. .catch((err) => {
  55. console.log(err);
  56. });
  57. })
  58. .catch((err) => {
  59. console.log(err);
  60. });
  61. }
  62. }
  63.  
  64. static _storeToken = async (uTokens, decoded) => {
  65. try {
  66. await AsyncStorage.setItem('token', uTokens.token);
  67. await AsyncStorage.setItem('rToken', uTokens.refresh_token);
  68. await AsyncStorage.setItem('eToken', decoded.exp.toString());
  69. } catch (err) {
  70. throw err;
  71. }
  72. };
  73.  
  74. import { AsyncStorage } from 'react-native';
  75. import GLOBALS from '../constants/Globals';
  76. import {toast} from "./Toast";
  77. import I18n from "../i18n/i18n";
  78.  
  79. const jsonLdMimeType = 'application/ld+json';
  80.  
  81. export default async function (url, options = {}, noApi = false) {
  82. if ('undefined' === typeof options.headers) options.headers = new Headers();
  83. if (null === options.headers.get('Accept')) options.headers.set('Accept', jsonLdMimeType);
  84.  
  85. if ('undefined' !== options.body && !(options.body instanceof FormData) && null === options.headers.get('Content-Type')) {
  86. options.headers.set('Content-Type', jsonLdMimeType);
  87. }
  88.  
  89. const token = await AsyncStorage.getItem('token');
  90. if (token) {
  91. options.headers.set('Authorization', 'Bearer ' + token);
  92. }
  93.  
  94. let api = '/api';
  95.  
  96. if (noApi) {
  97. api = "";
  98. }
  99.  
  100. const link = GLOBALS.BASE_URL + api + url;
  101. return fetch(link, options).then(response => {
  102. if (response.ok) return response;
  103.  
  104. return response
  105. .json()
  106. .then(json => {
  107. if (json.code === 401) {
  108. toast(I18n.t("session_being_refreshed"), "success", 3000);
  109. }
  110.  
  111. const error = json['message'] ? json['message'] : response.statusText;
  112. throw Error(I18n.t(error));
  113. })
  114. .catch(err => {
  115. throw err;
  116. });
  117. })
  118. .catch(err => {
  119. throw err;
  120. });
  121. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement