Advertisement
Guest User

Custom Fuse jwtService.js code

a guest
Feb 21st, 2019
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. =================
  2. Auth.js
  3. =================
  4.  
  5. import React, {Component} from 'react';
  6. import {connect} from 'react-redux';
  7. import * as userActions from 'app/auth/store/actions';
  8. import {bindActionCreators} from 'redux';
  9. import * as Actions from 'app/store/actions';
  10. import firebaseService from 'app/services/firebaseService';
  11. import auth0Service from 'app/services/auth0Service';
  12. import jwtService from 'app/services/jwtService';
  13. import FuseSplashScreen from "../../@fuse/components/FuseSplashScreen/FuseSplashScreen";
  14.  
  15. class Auth extends Component {
  16.     /*eslint-disable-next-line no-useless-constructor*/
  17.     constructor(props)
  18.     {
  19.         super(props);
  20.  
  21.         // Custom logging state to show/hide FuseSplashScreen loading spinner during signInWithToken() at the page refresh
  22.         // If there's no token logging state is false and FuseSplashScreen doesn't show
  23.         this.state = {
  24.             logging: (window.localStorage.getItem('jwt_access_token')) ? true : false
  25.         };
  26.  
  27.         /**
  28.          * Comment the line if you do not use JWt
  29.          */
  30.         this.jwtCheck();
  31.  
  32.         /**
  33.          * Comment the line if you do not use Auth0
  34.          */
  35.         //this.auth0Check();
  36.  
  37.         /**
  38.          * Comment the line if you do not use Firebase
  39.          */
  40.         //this.firebaseCheck();
  41.     }
  42.  
  43.     jwtCheck = () => {
  44.         jwtService.on('onAutoLogin', () => {
  45.  
  46.             this.props.showMessage({message: 'Logging in with JWT'});
  47.  
  48.             /**
  49.              * Sign in and retrieve user data from Api
  50.              */
  51.             jwtService.signInWithToken()
  52.                 .then(user => {
  53.                     this.props.setUserData(user);
  54.  
  55.                     this.props.showMessage({message: 'Logged in with JWT'});
  56.  
  57.                     this.setState({logging: false});
  58.                 })
  59.                 .catch(error => {
  60.                     this.props.showMessage({message: error});
  61.  
  62.                     this.setState({logging: false});
  63.                 })
  64.         });
  65.  
  66.         jwtService.on('onAutoLogout', (message) => {
  67.             if ( message )
  68.             {
  69.                 this.props.showMessage({message});
  70.             }
  71.             this.props.logout();
  72.  
  73.             this.setState({logging: false});
  74.         });
  75.  
  76.         jwtService.init();
  77.     };
  78.  
  79.     auth0Check = () => {
  80.  
  81.         auth0Service.init();
  82.  
  83.         if ( auth0Service.isAuthenticated() )
  84.         {
  85.             this.props.showMessage({message: 'Logging in with Auth0'});
  86.  
  87.             /**
  88.              * Retrieve user data from Auth0
  89.              */
  90.             auth0Service.getUserData().then(tokenData => {
  91.  
  92.                 this.props.setUserDataAuth0(tokenData);
  93.  
  94.                 this.props.showMessage({message: 'Logged in with Auth0'});
  95.             })
  96.         }
  97.     };
  98.  
  99.     firebaseCheck = () => {
  100.  
  101.         firebaseService.init();
  102.  
  103.         firebaseService.onAuthStateChanged(authUser => {
  104.             if ( authUser )
  105.             {
  106.                 this.props.showMessage({message: 'Logging in with Firebase'});
  107.  
  108.                 /**
  109.                  * Retrieve user data from Firebase
  110.                  */
  111.                 firebaseService.getUserData(authUser.uid).then(user => {
  112.  
  113.                     this.props.setUserDataFirebase(user, authUser);
  114.  
  115.                     this.props.showMessage({message: 'Logged in with Firebase'});
  116.                 })
  117.             }
  118.         });
  119.     };
  120.  
  121.     render()
  122.     {
  123.         const {children} = this.props;
  124.  
  125.         if (this.state.logging) {
  126.             return (
  127.                 <FuseSplashScreen />
  128.             )
  129.         }
  130.  
  131.         return (
  132.             <React.Fragment>
  133.                 {children}
  134.             </React.Fragment>
  135.         );
  136.     }
  137. }
  138.  
  139. function mapDispatchToProps(dispatch)
  140. {
  141.     return bindActionCreators({
  142.             logout             : userActions.logoutUser,
  143.             setUserData        : userActions.setUserData,
  144.             setUserDataAuth0   : userActions.setUserDataAuth0,
  145.             setUserDataFirebase: userActions.setUserDataFirebase,
  146.             showMessage        : Actions.showMessage,
  147.             hideMessage        : Actions.hideMessage
  148.         },
  149.         dispatch);
  150. }
  151.  
  152. export default connect(null, mapDispatchToProps)(Auth);
  153.  
  154.  
  155. ====================
  156. jwtService.js
  157. ====================
  158. import axios from 'axios';
  159. import FuseUtils from '@fuse/FuseUtils';
  160.  
  161. class jwtService extends FuseUtils.EventEmitter {
  162.  
  163.     init()
  164.     {
  165.         this.setInterceptors();
  166.         this.handleAuthentication();
  167.     }
  168.  
  169.     setInterceptors = () => {
  170.         axios.interceptors.response.use(response => {
  171.             return response;
  172.         }, err => {
  173.             return new Promise((resolve, reject) => {
  174.                 if ( err.response.status === 401 && err.config && !err.config.__isRetryRequest )
  175.                 {
  176.                     // if you ever get an unauthorized response, logout the user
  177.                     this.emit('onAutoLogout', 'Invalid access_token');
  178.                     this.setSession(null);
  179.                 }
  180.                 throw err;
  181.             });
  182.         });
  183.     };
  184.  
  185.     handleAuthentication = () => {
  186.  
  187.         let access_token = this.getAccessToken();
  188.  
  189.         if ( !access_token )
  190.         {
  191.             return;
  192.         }
  193.  
  194.         this.setSession(access_token);
  195.         this.emit('onAutoLogin', true);
  196.     };
  197.  
  198.     signInWithEmailAndPassword = (email, password) => {
  199.         return new Promise((resolve, reject) => {
  200.             axios.post('http://localhost:8000/rest-auth/login/', {
  201.                 email,
  202.                 password
  203.             }).then(response => {
  204.                 if ( response.data.user )
  205.                 {
  206.                     this.setSession(response.data.access_token);
  207.                     resolve(response.data.user);
  208.                 }
  209.                 else
  210.                 {
  211.                     reject(response.data.error);
  212.                 }
  213.             });
  214.         });
  215.     };
  216.  
  217.     signInWithToken = () => {
  218.         return new Promise((resolve, reject) => {
  219.             axios.get('http://localhost:8000/rest-auth/token-login/', {
  220.                 access_token: this.getAccessToken()
  221.             })
  222.                 .then(response => {
  223.                     if ( response.data.user )
  224.                     {
  225.                         resolve(response.data.user);
  226.                     }
  227.                     else
  228.                     {
  229.                         reject(response.data.error);
  230.                     }
  231.                 });
  232.         });
  233.     };
  234.  
  235.     setSession = access_token => {
  236.         if ( access_token )
  237.         {
  238.             localStorage.setItem('jwt_access_token', access_token);
  239.             axios.defaults.headers.common['Authorization'] = 'Token ' + access_token;
  240.         }
  241.         else
  242.         {
  243.             localStorage.removeItem('jwt_access_token');
  244.             delete axios.defaults.headers.common['Authorization'];
  245.         }
  246.     };
  247.  
  248.     logout = () => {
  249.         this.setSession(null);
  250.     };
  251.  
  252.     getAccessToken = () => {
  253.         return window.localStorage.getItem('jwt_access_token');
  254.     };
  255. }
  256.  
  257. const instance = new jwtService();
  258.  
  259. export default instance;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement