Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- =================
- Auth.js
- =================
- import React, {Component} from 'react';
- import {connect} from 'react-redux';
- import * as userActions from 'app/auth/store/actions';
- import {bindActionCreators} from 'redux';
- import * as Actions from 'app/store/actions';
- import firebaseService from 'app/services/firebaseService';
- import auth0Service from 'app/services/auth0Service';
- import jwtService from 'app/services/jwtService';
- import FuseSplashScreen from "../../@fuse/components/FuseSplashScreen/FuseSplashScreen";
- class Auth extends Component {
- /*eslint-disable-next-line no-useless-constructor*/
- constructor(props)
- {
- super(props);
- // Custom logging state to show/hide FuseSplashScreen loading spinner during signInWithToken() at the page refresh
- // If there's no token logging state is false and FuseSplashScreen doesn't show
- this.state = {
- logging: (window.localStorage.getItem('jwt_access_token')) ? true : false
- };
- /**
- * Comment the line if you do not use JWt
- */
- this.jwtCheck();
- /**
- * Comment the line if you do not use Auth0
- */
- //this.auth0Check();
- /**
- * Comment the line if you do not use Firebase
- */
- //this.firebaseCheck();
- }
- jwtCheck = () => {
- jwtService.on('onAutoLogin', () => {
- this.props.showMessage({message: 'Logging in with JWT'});
- /**
- * Sign in and retrieve user data from Api
- */
- jwtService.signInWithToken()
- .then(user => {
- this.props.setUserData(user);
- this.props.showMessage({message: 'Logged in with JWT'});
- this.setState({logging: false});
- })
- .catch(error => {
- this.props.showMessage({message: error});
- this.setState({logging: false});
- })
- });
- jwtService.on('onAutoLogout', (message) => {
- if ( message )
- {
- this.props.showMessage({message});
- }
- this.props.logout();
- this.setState({logging: false});
- });
- jwtService.init();
- };
- auth0Check = () => {
- auth0Service.init();
- if ( auth0Service.isAuthenticated() )
- {
- this.props.showMessage({message: 'Logging in with Auth0'});
- /**
- * Retrieve user data from Auth0
- */
- auth0Service.getUserData().then(tokenData => {
- this.props.setUserDataAuth0(tokenData);
- this.props.showMessage({message: 'Logged in with Auth0'});
- })
- }
- };
- firebaseCheck = () => {
- firebaseService.init();
- firebaseService.onAuthStateChanged(authUser => {
- if ( authUser )
- {
- this.props.showMessage({message: 'Logging in with Firebase'});
- /**
- * Retrieve user data from Firebase
- */
- firebaseService.getUserData(authUser.uid).then(user => {
- this.props.setUserDataFirebase(user, authUser);
- this.props.showMessage({message: 'Logged in with Firebase'});
- })
- }
- });
- };
- render()
- {
- const {children} = this.props;
- if (this.state.logging) {
- return (
- <FuseSplashScreen />
- )
- }
- return (
- <React.Fragment>
- {children}
- </React.Fragment>
- );
- }
- }
- function mapDispatchToProps(dispatch)
- {
- return bindActionCreators({
- logout : userActions.logoutUser,
- setUserData : userActions.setUserData,
- setUserDataAuth0 : userActions.setUserDataAuth0,
- setUserDataFirebase: userActions.setUserDataFirebase,
- showMessage : Actions.showMessage,
- hideMessage : Actions.hideMessage
- },
- dispatch);
- }
- export default connect(null, mapDispatchToProps)(Auth);
- ====================
- jwtService.js
- ====================
- import axios from 'axios';
- import FuseUtils from '@fuse/FuseUtils';
- class jwtService extends FuseUtils.EventEmitter {
- init()
- {
- this.setInterceptors();
- this.handleAuthentication();
- }
- setInterceptors = () => {
- axios.interceptors.response.use(response => {
- return response;
- }, err => {
- return new Promise((resolve, reject) => {
- if ( err.response.status === 401 && err.config && !err.config.__isRetryRequest )
- {
- // if you ever get an unauthorized response, logout the user
- this.emit('onAutoLogout', 'Invalid access_token');
- this.setSession(null);
- }
- throw err;
- });
- });
- };
- handleAuthentication = () => {
- let access_token = this.getAccessToken();
- if ( !access_token )
- {
- return;
- }
- this.setSession(access_token);
- this.emit('onAutoLogin', true);
- };
- signInWithEmailAndPassword = (email, password) => {
- return new Promise((resolve, reject) => {
- axios.post('http://localhost:8000/rest-auth/login/', {
- email,
- password
- }).then(response => {
- if ( response.data.user )
- {
- this.setSession(response.data.access_token);
- resolve(response.data.user);
- }
- else
- {
- reject(response.data.error);
- }
- });
- });
- };
- signInWithToken = () => {
- return new Promise((resolve, reject) => {
- axios.get('http://localhost:8000/rest-auth/token-login/', {
- access_token: this.getAccessToken()
- })
- .then(response => {
- if ( response.data.user )
- {
- resolve(response.data.user);
- }
- else
- {
- reject(response.data.error);
- }
- });
- });
- };
- setSession = access_token => {
- if ( access_token )
- {
- localStorage.setItem('jwt_access_token', access_token);
- axios.defaults.headers.common['Authorization'] = 'Token ' + access_token;
- }
- else
- {
- localStorage.removeItem('jwt_access_token');
- delete axios.defaults.headers.common['Authorization'];
- }
- };
- logout = () => {
- this.setSession(null);
- };
- getAccessToken = () => {
- return window.localStorage.getItem('jwt_access_token');
- };
- }
- const instance = new jwtService();
- export default instance;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement