Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lesson-7 #12

Open
wants to merge 2 commits into
base: lesson-6
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Django #
*.log
*.pot
*.pyc
__pycache__
db.sqlite3
media

# If you are using PyCharm #
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.xml
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/gradle.xml
.idea/**/libraries
*.iws /out/

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
44 changes: 44 additions & 0 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"react-dom": "^18.2.0",
"react-router-dom": "^6.0.0",
"react-scripts": "^5.0.1",
"universal-cookie": "^4.0.4",
"web-vitals": "^2.1.4"
},
"scripts": {
Expand Down
67 changes: 59 additions & 8 deletions frontend/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,17 @@ import axios from "axios";
import {
BrowserRouter as Router,
Route,
Routes
Routes,
Link,
} from 'react-router-dom'

import UserList from "./components/User";
import ToDoList from "./components/ToDo";
import ProjectList from "./components/Projects"
import Navbar from "./components/Menu";

import LoginForm from "./components/Auth";
import Cookies from 'universal-cookie';
import './components/bootstrap/css/bootstrap.min.css';

class App extends React.Component {
constructor(props) {
Expand All @@ -25,38 +28,84 @@ class App extends React.Component {
'notes': [],
'users': [],
'projects': [],
'auth': {'username': '', 'token': ''}
};
}

set_token(username, token) {
const cookies = new Cookies()
cookies.set('token', token)
cookies.set('username', username)
this.setState({'auth':{'username': username, 'token': token}}, ()=>this.load_data())
}

componentDidMount() {
axios.get('http://127.0.0.1:8000/api/notes/')
is_authenticated() {
return this.state.auth.token !== ''
}

logout() {
this.set_token('', '')
}

get_token_from_storage() {
const cookies = new Cookies()
const token = cookies.get('token')
const username = cookies.get('username')
this.setState({auth:{'username': username, 'token': token}}, ()=>this.load_data())
}

get_token(username, password) {
axios.post('http://127.0.0.1:8000/api-auth-token/', {username: username, password: password})
.then(response => {
this.set_token(username, response.data['token'])
}).catch(error => alert('Неверный логин или пароль'))
}

load_data() {
const headers = this.get_headers()

axios.get('http://127.0.0.1:8000/api/notes/', {headers})
.then(response =>{
this.setState({
'notes':response.data.results
})
}).catch(error => console.log(error));

axios.get('http://127.0.0.1:8000/api/projects/')
axios.get('http://127.0.0.1:8000/api/projects/', {headers})
.then(response =>{
this.setState({
'projects':response.data.results
})
}).catch(error => console.log(error));
}).catch(error => {
console.log(error);
this.setState({projects: []})
})

axios.get('http://127.0.0.1:8000/api/users/')
axios.get('http://127.0.0.1:8000/api/users/', {headers})
.then(response =>{
this.setState({
'users':response.data
})
}).catch(error => console.log(error));
}

get_headers() {
let headers = { 'Content-Type': 'application/json' }
if (this.is_authenticated()) {
headers['Authorization'] = 'Token ' + this.state.auth.token
}
return headers
}

componentDidMount() {
this.get_token_from_storage()
}

render() {
return (
<Router>
<header>
<Navbar navbarItems={this.state.navbar}/>
<Navbar navbarItems={this.state.navbar} username={this.state.auth.username} token={this.state.auth.token} logout={() => this.logout()}/>
</header>
<main role="main" className="flex-shrink-0">
<div className="container">
Expand All @@ -66,6 +115,8 @@ class App extends React.Component {
<Route exact path = '/notes' element = {<ToDoList items={this.state.notes} /> } />

<Route exact path = '/projects' element = {<ProjectList items={this.state.projects} /> } />

<Route exact path = '/login' element = {<LoginForm get_token={(username, password) => this.get_token(username, password)} />} />
</Routes>
</div>
</main>
Expand Down
41 changes: 41 additions & 0 deletions frontend/src/components/Auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import React from 'react'



class LoginForm extends React.Component {
constructor(props) {
super(props)
this.state = {login: '', password: ''}
}

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

handleSubmit(event) {
this.props.get_token(this.state.login, this.state.password)
event.preventDefault()
}

render() {
return (
<form onSubmit={(event)=> this.handleSubmit(event)}>
<div class="mb-3">
<label class="form-label">Логин</label>
<input type="text" class="form-control" name="login"
value={this.state.login} onChange={(event)=>this.handleChange(event)} />
</div>
<div class="mb-3">
<label class="form-label">Пароль</label>
<input type="password" class="form-control" name="password"
value={this.state.password} onChange={(event)=>this.handleChange(event)} />
</div>
<input type="submit" class="btn btn-primary" value="Войти" />
</form>
);
}
}

export default LoginForm
18 changes: 13 additions & 5 deletions frontend/src/components/Menu.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ import './bootstrap/css/bootstrap.min.css';

function NavbarItem({name, href}) {
return (
<li className="nav-item">
<Link className="nav-link" to={href}>{name}</Link>
</li>
<Link className="nav-link" to={href}>{name}</Link>
)
}

Expand All @@ -27,14 +25,24 @@ function NavbarItem({name, href}) {
)
}*/

function Navbar({navbarItems}) {
function Navbar({navbarItems, username, token, logout}) {
let login_button = ''
if (token !== '') {
login_button = <div style={{'position': 'absolute', 'right': '0'}}><span>Добро пожаловать {username} </span><button className="btn btn-outline-success my-2 my-sm-0" onClick={logout}>Logout</button></div>
}
else {
login_button = <Link style={{'position': 'absolute', 'right': '0'}} to='/login' className="btn btn-outline-success my-2 my-sm-0">Login</Link>
}

return (
<nav className="navbar navbar-expand-sm navbar-light" style={{'backgroundColor': '#78d2eb'}}>
<span className="navbar-brand" href="#">ToDo</span>
<div className="collapse navbar-collapse" id="navbarCollapse" style={{'position': 'absolute', 'right': '0'}}>
<div className="collapse navbar-collapse" id="navbarCollapse">
<ul className="navbar-nav mr-auto">
{navbarItems.map((item) => <NavbarItem name={item.name} href={item.href}/>)}
{login_button}
</ul>

</div>
</nav>
)
Expand Down
1 change: 0 additions & 1 deletion frontend/src/components/Projects.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React from "react";
import { Link } from 'react-router-dom'

const ProjectItem = ({ item }) => {
let link = `/project/${item.id}`
Expand Down
15 changes: 15 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
asgiref==3.5.2
certifi==2022.6.15
charset-normalizer==2.1.1
Django==3.2.8
django-cors-headers==3.13.0
django-filter==22.1
djangorestframework==3.13.1
idna==3.3
importlib-metadata==4.12.0
Markdown==3.4.1
pytz==2022.1
requests==2.28.1
sqlparse==0.4.2
urllib3==1.26.11
zipp==3.8.1
5 changes: 2 additions & 3 deletions to_do_list/to_do_list/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@

ALLOWED_HOSTS = ['*']

CORS_ALLOWED_ORIGINS = [
CORS_ALLOWED_ORIGINS =[
'http://127.0.0.1:3000',
'http://localhost:3000'
'http://localhost:3000',
]
# Application definition

Expand Down Expand Up @@ -148,7 +148,6 @@

'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
]
}
3 changes: 2 additions & 1 deletion to_do_list/todo_app/views.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework import status, permissions
from rest_framework.response import Response
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer
Expand All @@ -19,6 +19,7 @@ class ProjectModelViewSet(ModelViewSet):
renderer_classes = [JSONRenderer, BrowsableAPIRenderer]
queryset = Project.objects.all()
serializer_class = ProjectModelSerializer
permission_classes = [permissions.IsAuthenticated]
pagination_class = ProjectLimitOffsetPagination

#http://127.0.0.1:8000/api/projects/?project_name=2 - фильтр по имени
Expand Down
8 changes: 0 additions & 8 deletions to_do_list/token_test.py

This file was deleted.