Hej. Mam sobie aplikację napisaną w django, którą staram się przerobić, żeby działała razem z Reactem (backend Django REST, frontend react). Chciałem się zapytać bardziej doświadczonych programistów o dobre praktyki w zakresie logowania, przechowywania stanu aplikacji jeśli chodzi uwierzytelnianie użytkowników. Strona główna ma wyświetlać tablicę wyników przyporządkowaną do poszczególnych użytkowników. Jeśli użytkownik nie będzie zalogowany, ma nastąpić przejście do strony logowania. Analogicznie po zalogowaniu ma nastąpić przejście do strony głównej i wyświetlenie listy wyników. Poniżej kod który napisałem z prośbą o wytknięcie błędów (ewentualnie wskazanie, że moje rozwiązanie jest poprawne). Klucz logowania przechowuję w localstorage
.
Strona główna:
import React, { Component } from "react";
import axios from "axios";
import SiteTable from './SitesTable';
import { Redirect } from 'react-router-dom';
class Home extends Component {
constructor(props) {
super(props);
this.state = {
sites: [],
username: localStorage.getItem('username') ? (localStorage.getItem('username')) : (''),
token: localStorage.getItem('token') ? (localStorage.getItem('token')) : ('')};
}
componentDidMount() {
if (this.state.username) {
axios.get("http://127.0.0.1:8000/api/sites/", {
headers: {
Authorization: `Token ${this.state.token}`
}
}).then(res => {
this.setState({
sites: res.data
});
});
} else {
console.log('Something went wrong')
}
}
handleLogout = () => {
localStorage.clear()
this.setState({username: ''})
}
render() {
if (!this.state.username) {
return (
<Redirect to='/login' />
)
}
return (
<div className="containter">
<SiteTable sites={this.state.sites} />
<button type="submit" onClick={this.handleLogout}>Logout</button>
</div>
);
}
}
export default Home;
Strona logowania:
import React, { Component } from 'react';
import axios from 'axios';
import { Redirect } from 'react-router-dom';
class Login extends Component {
constructor(props) {
super(props);
this.state = {
username: "",
password: "",
isAuthenticated: false};
}
componentDidUpdate() {
console.log(this.state)
}
handleChange(e, param) {
e.preventDefault()
this.setState({[param]: e.target.value})
}
handleSubmit = (e) => {
e.preventDefault()
axios.post('http://127.0.0.1:8000/rest-auth/login/', {
username: this.state.username,
password: this.state.password
})
.then(response => {
const token = response.data.key;
localStorage.setItem('username', this.state.username)
localStorage.setItem('token', token)
this.setState({isAuthenticated: true})
})
.catch(error => {
console.log(error.response.statusText);
alert('Please fill correct credentials')
this.setState({username: "", password: ""})
});
console.log('Submitted')
}
render() {
if (this.state.isAuthenticated) {
return <Redirect to={{pathname: '/'}} />
}
return (
<div className="container">
<form onSubmit={this.handleSubmit}>
<input type="text" placeholder="Enter username" value={this.state.username} onChange={(e) => this.handleChange(e, 'username')}/>
<input type="password" placeholder="Enter password" value={this.state.password} onChange={(e) => this.handleChange(e, 'password')}/>
<button type="submit">Submit</button>
</form>
</div>
)
}
}
export default Login
Z góry dziękuję za wszelkie rady.