gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:14:28 24 4
gpt4 key购买 nike

所以我有一个当前在登录时运行良好的应用程序,只是将您带到基本应用程序。我创建了一个名为 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 时添加基于 Angular 色的重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57048047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com