xonecas.io
3517
Mt

meal_tracker / commit 5b52312

Add login view and UI

Add a simple ui modal to interact with the login view in order to
produce and authorized token to consume the rest of the api.

xonecas2020-03-06 5b52312cda0254e3dd88c31045a2650a153f0fb3 parent c22b36b

10 files changed

bmi_api/urls.py+2−1
@@ -1,6 +1,6 @@
11 from django.conf.urls import url, include
22 from rest_framework import routers
3-from .views import UserViewSet, MealViewSet
3+from .views import UserViewSet, MealViewSet, login
44
55 router = routers.DefaultRouter()
66 router.register(r'users', UserViewSet)
@@ -8,4 +8,5 @@ router.register(r'meals', MealViewSet)
88
99 urlpatterns = [
1010 url(r'^', include(router.urls)),
11+ url(r'login', login),
1112 ]
bmi_api/views.py+25−1
@@ -1,12 +1,36 @@
1+from django.contrib.auth import authenticate
12 from django.contrib.auth.models import User
23
3-from rest_framework import viewsets, permissions
4+from rest_framework import viewsets, permissions, status
5+from rest_framework.response import Response
6+from rest_framework.decorators import api_view, permission_classes
7+from rest_framework.authtoken.models import Token
48
59 from .models import Meal
610 from .permissions import IsOwnerOrReadOnly
711 from .serializers import MealSerializer, UserSerializer
812
913
14+@api_view(['POST'])
15+@permission_classes((permissions.AllowAny,))
16+def login(request):
17+ username = request.data.get("username")
18+ password = request.data.get("password")
19+
20+ if username is None or password is None:
21+ return Response(status=status.HTTP_400_BAD_REQUEST)
22+
23+ user = authenticate(username=username, password=password)
24+
25+ if not user:
26+ return Response(status=status.HTTP_404_NOT_FOUND)
27+
28+ serializer = UserSerializer(user)
29+ token, _ = Token.objects.get_or_create(user=user)
30+
31+ return Response({'token': token.key, **serializer.data}, status=status.HTTP_200_OK)
32+
33+
1034 class UserViewSet(viewsets.ModelViewSet):
1135 permission_classes = [permissions.IsAdminUser, IsOwnerOrReadOnly]
1236 queryset = User.objects.all()
bmi_ui/src/App.js+2−6
@@ -1,15 +1,11 @@
1-import React, { Fragment } from 'react';
1+import React from 'react';
22 import './App.css';
33
4-import Header from "./components/Header"
54 import Home from "./components/Home"
65
76 function App() {
87 return (
9- <Fragment>
10- <Header />
11- <Home />
12- </Fragment>
8+ <Home />
139 );
1410 }
1511
bmi_ui/src/components/Header.js+20−11
@@ -1,19 +1,28 @@
11 import React from 'react';
2-import { Nav, Navbar, NavbarBrand, NavItem, NavLink } from 'reactstrap';
2+import { Nav, Navbar, NavbarBrand, NavItem } from 'reactstrap';
33 import UserModal from './UserModal';
4+import LoginModal from './LoginModal';
45
56 const Header = (props) => {
7+ var login = '';
8+ if (!props.user) {
9+ login = (
10+ <NavItem>
11+ <LoginModal user={props.user} />
12+ </NavItem>
13+ );
14+ }
15+
616 return (
7- <div>
8- <Navbar color="dark" dark expand="md">
9- <NavbarBrand href="/">Meal Tracker</NavbarBrand>
10- <Nav className="ml-auto">
11- <NavItem>
12- <NavLink href=""><UserModal create={true}/></NavLink>
13- </NavItem>
14- </Nav>
15- </Navbar>
16- </div>
17+ <Navbar color="dark" dark expand="md">
18+ <NavbarBrand href="/">Meal Tracker</NavbarBrand>
19+ <Nav className="ml-auto" navbar>
20+ {login}
21+ <NavItem className="ml-1">
22+ <UserModal create={!props.user} user={props.user} />
23+ </NavItem>
24+ </Nav>
25+ </Navbar>
1726 );
1827 }
1928
bmi_ui/src/components/Home.js+18−22
@@ -1,6 +1,7 @@
1-import React, { Component } from "react";
1+import React, { Fragment, Component } from "react";
22 import axios from 'axios';
33 import { API_URL } from '../constants';
4+import Header from './Header';
45 import { Col, Container, Row } from "reactstrap";
56
67
@@ -11,7 +12,7 @@ class Home extends Component {
1112 }
1213
1314 componentDidMount() {
14- this.resetState();
15+ this.getMeals()
1516 }
1617
1718 getMeals = () => {
@@ -23,28 +24,23 @@ class Home extends Component {
2324 })
2425 };
2526
26- getUser = () => {
27-
28- };
29-
30- resetState = () => {
31- this.getMeals();
32- };
33-
3427 render() {
3528 return (
36- <Container style={{ marginTop: "20px" }}>
37- <Row>
38- <Col>
39- A list of meals will go here, with edit + delete
40- </Col>
41- </Row>
42- <Row>
43- <Col>
44- Add new meal cta
45- </Col>
46- </Row>
47- </Container>
29+ <Fragment>
30+ <Header user={this.state.user} />
31+ <Container style={{ marginTop: "20px" }}>
32+ <Row>
33+ <Col>
34+ A list of meals will go here, with edit + delete
35+ </Col>
36+ </Row>
37+ <Row>
38+ <Col>
39+ Add new meal cta
40+ </Col>
41+ </Row>
42+ </Container>
43+ </Fragment>
4844 );
4945 }
5046 }
bmi_ui/src/components/LoginForm.js+56−0
@@ -0,0 +1,56 @@
1+import React from 'react';
2+import { Button, Form, FormGroup, Input, Label } from 'reactstrap';
3+import axios from 'axios';
4+import { API_URL } from '../constants';
5+
6+
7+class UserForm extends React.Component {
8+ state = {
9+ username: '',
10+ password: ''
11+ };
12+
13+ onChange = e => {
14+ this.setState({ [e.target.name]: e.target.value });
15+ };
16+
17+ login = e => {
18+ e.preventDefault();
19+ axios.post(API_URL + 'login/', this.state, { crossdomain: true }).then(() => {
20+ this.props.toggle(e);
21+ });
22+ };
23+
24+ defaultIfEmpty = value => {
25+ return value === "" ? "" : value;
26+ };
27+
28+ render() {
29+ return (
30+ <Form onSubmit={this.login}>
31+ <FormGroup>
32+ <Label for="username">Username:</Label>
33+ <Input
34+ type="text"
35+ name="username"
36+ onChange={this.onChange}
37+ value={this.defaultIfEmpty(this.state.name)}
38+ />
39+ </FormGroup>
40+ <FormGroup>
41+ <Label for="examplePassword">Password</Label>
42+ <Input
43+ type="password"
44+ name="password"
45+ onChange={this.onChange}
46+ value={this.defaultIfEmpty(this.state.name)}
47+ />
48+ </FormGroup>
49+
50+ <Button className="float-right" color="primary">Login</Button>
51+ </Form>
52+ )
53+ }
54+}
55+
56+export default UserForm;
bmi_ui/src/components/LoginModal.js+38−0
@@ -0,0 +1,38 @@
1+import React, { Component, Fragment } from "react";
2+import { Button, Modal, ModalHeader, ModalBody } from "reactstrap";
3+import LoginForm from './LoginForm';
4+
5+
6+class UserModal extends Component {
7+ state = {
8+ modal: false
9+ }
10+
11+ toggle = (e) => {
12+ e && e.preventDefault();
13+
14+ this.setState(previous => ({
15+ modal: !previous.modal
16+ }));
17+ };
18+
19+ render() {
20+ return (
21+ <Fragment>
22+ <Button onClick={this.toggle} color="primary" size="sm">Login</Button>
23+ <Modal isOpen={this.state.modal} toggle={this.toggle}>
24+ <ModalHeader toggle={this.toggle}>Login</ModalHeader>
25+
26+ <ModalBody>
27+ <LoginForm
28+ toggle={this.toggle}
29+ />
30+ </ModalBody>
31+ </Modal>
32+ </Fragment>
33+ );
34+ }
35+}
36+
37+export default UserModal;
38+
bmi_ui/src/components/UserForm.js+23−9
@@ -8,13 +8,16 @@ class UserForm extends React.Component {
88 state = {
99 id: 0,
1010 username: '',
11- caloriesPerDay: 0
11+ preferences: { max_calories: 0 }
1212 };
1313
1414 componentDidMount() {
1515 if (this.props.user) {
16- const { id, username, caloriesPerDay } = this.props.user;
17- this.setState({ id, username, caloriesPerDay });
16+ this.setState({
17+ id: this.props.user.id,
18+ username: this.props.user.username,
19+ preferences: this.props.user.preferences
20+ });
1821 }
1922 }
2023
@@ -22,10 +25,13 @@ class UserForm extends React.Component {
2225 this.setState({ [e.target.name]: e.target.value });
2326 };
2427
28+ onCaloriesChange = e => {
29+ this.setState({ preferences: { max_calories: e.target.value }});
30+ };
31+
2532 createUser = e => {
2633 e.preventDefault();
2734 axios.post(API_URL + 'users/', this.state, { crossdomain: true }).then(() => {
28- this.props.resetState();
2935 this.props.toggle();
3036 });
3137 };
@@ -33,7 +39,6 @@ class UserForm extends React.Component {
3339 editUser = e => {
3440 e.preventDefault();
3541 axios.put(API_URL + 'users/' + this.state.id, this.state, { crossdomain: true }).then(() => {
36- this.props.resetState();
3742 this.props.toggle();
3843 });
3944 };
@@ -46,7 +51,7 @@ class UserForm extends React.Component {
4651 return (
4752 <Form onSubmit={this.props.user ? this.editUser : this.createUser}>
4853 <FormGroup>
49- <Label for="username">username:</Label>
54+ <Label for="username">Username:</Label>
5055 <Input
5156 type="text"
5257 name="username"
@@ -55,16 +60,25 @@ class UserForm extends React.Component {
5560 />
5661 </FormGroup>
5762 <FormGroup>
58- <Label for="caloriesPerDay">Calories per day:</Label>
63+ <Label for="examplePassword">Password:</Label>
64+ <Input
65+ type="password"
66+ name="password"
67+ onChange={this.onChange}
68+ value={this.defaultIfEmpty(this.state.name)}
69+ />
70+ </FormGroup>
71+ <FormGroup>
72+ <Label for="caloriesPerDay">Maximum Calories per Day:</Label>
5973 <Input
6074 type="text"
6175 name="caloriesPerDay"
62- onChange={this.onChange}
76+ onChange={this.onCaloriesChange}
6377 value={this.defaultIfEmpty(this.state.name)}
6478 />
6579 </FormGroup>
6680
67- <Button>Save</Button>
81+ <Button className="float-right" color="primary">Save</Button>
6882 </Form>
6983 )
7084 }
bmi_ui/src/components/UserModal.js+4−4
@@ -20,7 +20,7 @@ class UserModal extends Component {
2020 const create = this.props.create;
2121
2222 var title = "Editing user";
23- var button = <Button onClick={this.toggle} size="sm">Edit user</Button>;
23+ var button = <Button onClick={this.toggle} size="sm" outline>Edit user</Button>;
2424
2525 if (create) {
2626 title = 'Creating user';
@@ -29,8 +29,9 @@ class UserModal extends Component {
2929 <Button
3030 color='primary'
3131 size="sm"
32+ outline
3233 onClick={this.toggle}
33- >Signup or Login</Button>
34+ >Signup</Button>
3435 );
3536 }
3637
@@ -42,9 +43,8 @@ class UserModal extends Component {
4243
4344 <ModalBody>
4445 <UserForm
45- resetState={this.props.resetState}
4646 toggle={this.toggle}
47- student={this.props.student}
47+ user={this.props.student}
4848 />
4949 </ModalBody>
5050 </Modal>
db.sqlite3+0−0
Binary file, not shown.