javascript - 在登录到 React App 时添加基于角色的重定向

标签 javascript reactjs authentication role-base-authorization role-based-access-control

所以我有一个当前在登录时运行良好的应用程序,只是将您带到基本应用程序。我创建了一个名为 AdminDashboard.js 的新页面,并在 json 中添加了一个名为“Admin”的新部分,它为管理员用户设置为 1,为其他所有人设置为 0。我不知道在哪里添加重定向,如果登录的用户是管理员,他们将转到 AdminDashboard.js 而不是 App.js 部分。

JSON 看起来像

{
    "FirstName": "", 
    "LastName": "", 
    "Email": "admin", 
    "ID": 12, 
    "Admin": 1, 
    "Submitted": 0, 
    "Token": "eyJ0e1NiJ9.eNTYzMjA0NTkEyfQ._K5qNdsqJJXCiKq3XmIjFhU"
}

并且目前使用的页面总结代码与此类似,不包括AdminDashboard.js

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { Route, BrowserRouter as Router } from 'react-router-dom';

// Our Components
import Login from './components/Login';

ReactDOM.render(
    <Router>
        <div>
            <Route exact path="/" component={App} />
            <Route exact path="/login" component={Login} />
        </div>
    </Router>
    , document.getElementById('root')
);
registerServiceWorker();

App.js

import logo from './logo.svg';
import './App.css';
import AuthService from './components/AuthService';
import withAuth from './components/withAuth';
const Auth = new AuthService();

class App extends Component {

  handleLogout(){
    Auth.logout()
    this.props.history.replace('/login');
  }

  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome {this.props.user.email}</h2>
        </div>
        <p className="App-intro">
          <button type="button" className="form-submit" onClick={this.handleLogout.bind(this)}>Logout</button>
        </p>
      </div>
    );
  }
}

export default withAuth(App);

AuthService.js

export default class AuthService {
    constructor(domain) {
        this.domain = domain || 'http://10.123.456.321'
        this.fetch = this.fetch.bind(this)
        this.login = this.login.bind(this)
        this.getProfile = this.getProfile.bind(this)
    }

    login(email, password) {
        // Get a token
        return this.fetch(`${this.domain}/Login/`, {
            method: 'POST',
            body: JSON.stringify({
                email,
                password
            })
        }).then(res => {
            this.setToken(res.Token)
            return Promise.resolve(res);
        })
    }

    loggedIn() {
        // Checks if there is a saved token and it's still valid
        const token = this.getToken()
        return !!token && !this.isTokenExpired(token) // handwaiving here
    }

    isTokenExpired(token) {
        try {
            const decoded = decode(token);
            if (decoded.exp < Date.now() / 1000) {
                return true;
            }
            else
                return false;
        }
        catch (err) {
            return false;
        }
    }

    setToken(idToken) {
        // Saves user token to localStorage
        localStorage.setItem('id_token', idToken)
    }

    getToken() {
        // Retrieves the user token from localStorage
        return localStorage.getItem('id_token')
    }

    logout() {
        // Clear user token and profile data from localStorage
        localStorage.removeItem('id_token');
    }

    getProfile() {
        return decode(this.getToken());
    }


    fetch(url, options) {
        // performs api calls sending the required authentication headers
        const headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }

        if (this.loggedIn()) {
            headers['Authorization'] = 'Bearer ' + this.getToken()
        }

        return fetch(url, {
            headers,
            ...options
        })
            .then(this._checkStatus)
            .then(response => response.json())
    }

    _checkStatus(response) {
        // raises an error in case response status is not a success
        if (response.status >= 200 && response.status < 300) {
            return response
        } else {
            var error = new Error(response.statusText)
            error.response = response
            throw error
        }
    }
}

withAuth.js

import React, { Component } from 'react';
import AuthService from './AuthService';

export default function withAuth(AuthComponent) {
    const Auth = new AuthService('http://10.123.456.321');
    return class AuthWrapped extends Component {
        constructor() {
            super();
            this.state = {
                user: null
            }
        }
        componentWillMount() {
            if (!Auth.loggedIn()) {
                this.props.history.replace('/login')
            }
            else {
                try {
                    const profile = Auth.getProfile()
                    this.setState({
                        user: profile
                    })
                }
                catch(err){
                    Auth.logout()
                    this.props.history.replace('/login')
                }
            }
        }

        render() {
            if (this.state.user) {
                return (
                    <AuthComponent history={this.props.history} user={this.state.user} />
                )
            }
            else {
                return null
            }
        }
    };
}

登录.js

import React, { Component } from 'react';
import './Login.css';
import AuthService from './AuthService';

class Login extends Component {
    constructor(){
        super();
        this.handleChange = this.handleChange.bind(this);
        this.handleFormSubmit = this.handleFormSubmit.bind(this);
        this.Auth = new AuthService();
    }
    componentWillMount(){
        if(this.Auth.loggedIn())
            this.props.history.replace('/');
    }
    render() {
        return (
            <div className="center">
                <div className="card">
                    <h1>Login</h1>
                    <form onSubmit={this.handleFormSubmit}>
                        <input
                            className="form-item"
                            placeholder="Username goes here..."
                            name="username"
                            type="text"
                            onChange={this.handleChange}
                        />
                        <input
                            className="form-item"
                            placeholder="Password goes here..."
                            name="password"
                            type="password"
                            onChange={this.handleChange}
                        />
                        <input
                            className="form-submit"
                            value="SUBMIT"
                            type="submit"
                        />
                    </form>
                </div>
            </div>
        );
    }

    handleFormSubmit(e){
        e.preventDefault();

        this.Auth.login(this.state.username,this.state.password)
            .then(res =>{
               this.props.history.replace('/');
            })
            .catch(err =>{
                alert(err);
            })
    }

    handleChange(e){
        this.setState(
            {
                [e.target.name]: e.target.value
            }
        )
    }
}

export default Login;

最佳答案

你应该遵循React基于 Angular 色的访问控制方式,登录成功后你可以检查用户是否是admin然后你必须为组件AdminDashboard.js添加路由否则路由到'/'。

你可以看看我做的例子:https://github.com/NemerSahli/React-Role-Based-Access-Control

关于javascript - 在登录到 React App 时添加基于角色的重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57048047/

相关文章:

javascript - 在 JavaScript 中选择具有特定数据属性的特定元素的更好方法?

javascript - 保持后端验证与前端验证同步

javascript - http POST 请求响应 "status": 200 but with an empty object

当使用不同的函数渲染时,ReactJS 子组件会丢失其状态

reactjs - 如何告诉 react-create-app 构建脚本不要最小化文件的某些部分?

ruby-on-rails - rails 3.2 中的 f.hidden_​​field

javascript - 将 JQuery UI Datepicker 与 Jquery UI 主题中的图标一起使用

javascript - z-index 未按预期工作

authentication - 如何以寄存器形式在中间件auth中添加一些变量数据?

java - 在 Java 中中断 for 循环