Javascript 在登录到React应用程序时添加基于角色的重定向
因此,我有一个应用程序,目前可以很好地登录,只是带你到基本的应用程序。我创建了一个名为AdminDashboard.js的新页面,并在json中添加了一个名为“Admin”的新部分,该部分对管理员用户设置为1,对其他用户设置为0。我不知道在哪里添加重定向,如果登录的用户是管理员,他们将转到AdminDashboard.js而不是App.js部分 JSON看起来像Javascript 在登录到React应用程序时添加基于角色的重定向,javascript,reactjs,authentication,role-base-authorization,role-based-access-control,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",
{
"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();
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);
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
}
}
}
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
}
}
};
}
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”导入React;
从“react dom”导入react dom;
导入“./index.css”;
从“./App”导入应用程序;
从“./registerServiceWorker”导入registerServiceWorker;
从“react Router dom”导入{Route,BrowserRouter as Router};
//我们的组件
从“./components/Login”导入登录名;
ReactDOM.render(
,document.getElementById('root'))
);
registerServiceWorker();
App.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();
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);
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
}
}
}
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
}
}
};
}
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;
从“/logo.svg”导入徽标;
导入“/App.css”;
从“./components/AuthService”导入AuthService;
从“/components/withAuth”导入withAuth;
const Auth=new AuthService();
类应用程序扩展组件{
handleLogout(){
Auth.logout()
this.props.history.replace('/login');
}
render(){
返回(
欢迎{this.props.user.email}
注销
);
}
}
使用auth(App)导出默认值;
AuthService.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();
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);
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
}
}
}
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
}
}
};
}
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;
导出默认类AuthService{
构造函数(域){
this.domain=域| |'http://10.123.456.321'
this.fetch=this.fetch.bind(this)
this.login=this.login.bind(this)
this.getProfile=this.getProfile.bind(this)
}
登录(电子邮件、密码){
//拿到代币
返回this.fetch(`${this.domain}/Login/`{
方法:“POST”,
正文:JSON.stringify({
电子邮件,
密码
})
})。然后(res=>{
this.setToken(res.Token)
返回承诺。解决(res);
})
}
loggedIn(){
//检查是否存在已保存的令牌,并且该令牌仍然有效
const token=this.getToken()
return!!token&&!this.isTokenExpired(token)//在这里手动操作
}
isTokenExpired(令牌){
试一试{
const decoded=解码(令牌);
if(decoded.expresponse.json())
}
_检查状态(响应){
//如果响应状态不成功,则引发错误
如果(response.status>=200&&response.status<300){
返回响应
}否则{
var error=新错误(response.statusText)
error.response=响应
抛出错误
}
}
}
withAuth.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();
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);
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
}
}
}
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
}
}
};
}
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;
import React,{Component}来自'React';
从“/AuthService”导入AuthService;
使用Auth导出默认函数(AuthComponent){
const Auth=new AuthService('http://10.123.456.321');
返回类AuthWrapped扩展组件{
构造函数(){
超级();
此.state={
用户:空
}
}
组件willmount(){
如果(!Auth.loggedIn()){
this.props.history.replace(“/login”)
}
否则{
试一试{
const profile=Auth.getProfile()
这是我的国家({
用户:个人资料
})
}
捕捉(错误){
Auth.logout()
this.props.history.replace(“/login”)
}
}
}
render(){
if(this.state.user){
返回(
)
}
否则{
返回空
}
}
};
}
Login.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();
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);
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
}
}
}
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
}
}
};
}
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;
import React,{Component}来自'React';
导入“./Login.css”;
从“/AuthService”导入AuthService;
类登录扩展组件{
构造函数(){
超级();
this.handleChange=this.handleChange.bind(this);
this.handleFormSubmit=this.handleFormSubmit.bind(this);
this.Auth=new AuthService();
}
组件willmount(){
if(this.Auth.loggedIn())
this.props.history.replace('/');
}
render(){
返回(
登录
);
}
handleFormSubmit(e){
e、 防止违约(