#16-user-registration #18

Merged
juggy1233 merged 5 commits from #16-user-registration into master 2023-03-18 23:27:38 -04:00
12 changed files with 186 additions and 81 deletions

View File

@@ -3,8 +3,14 @@ FROM python:3.10.9
WORKDIR /tmp
RUN python -m venv venv
COPY ./requirements.txt /code/requirements.txt
RUN . venv/bin/activate
RUN python -m pip install -r /code/requirements.txt
COPY venv /code/venv
WORKDIR /code
COPY ./ /code
COPY app app
COPY main.py main.py
COPY config.py config.py
COPY boot.sh boot.sh
COPY migrations migrations
CMD sh boot.sh

View File

@@ -1,28 +1,20 @@
from app import db
from flask_login import UserMixin
from datetime import datetime
from werkzeug.security import check_password_hash, generate_password_hash
from werkzeug.security import generate_password_hash, check_password_hash
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
role = db.Column(db.String(32), index=True)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
about_me = db.Column(db.String(140))
last_seen = db.Column(db.DateTime, default=datetime.utcnow)
token = db.Column(db.String(32), index=True, unique=True)
def __repr__(self):
return f'<User {self.username}>'
def to_dict(self):
return {
"id": self.id,
"username": self.username,
"email": self.email,
"about_me": self.about_me,
}
return f"<User {self.username}>"
def set_password(self, password):
self.password_hash = generate_password_hash(password)
@@ -30,3 +22,16 @@ class User(UserMixin, db.Model):
def check_password(self, password):
return check_password_hash(self.password_hash, password)
def to_dict(self):
return {
"id": self.id,
"username": self.username,
"email": self.email,
}
def from_dict(self, data, new_user=False):
for field in ["role", "username", "email"]:
if field in data:
setattr(self, field, data[field])
if new_user and "password" in data:
self.set_password(data["password"])

View File

@@ -4,7 +4,7 @@ from flask import Response, jsonify, request
from app.errors import error_response
from flask_login import current_user
from app import login
from app import login, db
from app.models import User
@@ -18,7 +18,7 @@ def login_route():
data = request.get_json()
if current_user.is_authenticated:
return error_response(400, 'A user is already logged in!')
return error_response(400, "A user is already logged in!")
if not data.get("user_id") or not data.get("password"):
return error_response(400, "Must supply user_id and password")
@@ -32,13 +32,38 @@ def login_route():
login_user(user)
resp = jsonify(user.to_dict())
resp.status_code = 200
return resp
@bp.route("/logout", methods=["POST"])
def logout_route():
if not current_user.is_authenticated:
return error_response(400, "No users are logged in!")
resp = jsonify(current_user.to_dict())
logout_user()
return Response(status=200)
return resp
@bp.route("/register", methods=["POST"])
def register():
data = request.get_json()
required_fields = ["role", "username", "email", "password", "password2"]
for f in required_fields:
if f not in data:
return error_response(400, f"Must supply {f}")
if User.query.filter_by(username=data["username"]).first():
return error_response(409, "User with that username already exists")
if User.query.filter_by(email=data["email"]).first():
return error_response(409, "User with that email already exists")
u = User()
u.from_dict(data, new_user=True)
db.session.add(u)
db.session.commit()
resp = jsonify(u.to_dict())
return resp

View File

@@ -2,8 +2,6 @@
. ./venv/bin/activate
pip install -r ./requirements.txt
flask db upgrade
exec gunicorn -b :5000 --access-logfile - --error-logfile - main:app

View File

@@ -0,0 +1,36 @@
"""empty message
Revision ID: 8e48199f1417
Revises: 7736bc740f9b
Create Date: 2023-03-18 21:18:21.923362
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '8e48199f1417'
down_revision = '7736bc740f9b'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('user', schema=None) as batch_op:
batch_op.add_column(sa.Column('role', sa.String(length=32), nullable=True))
batch_op.create_index(batch_op.f('ix_user_role'), ['role'], unique=False)
batch_op.drop_column('about_me')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('user', schema=None) as batch_op:
batch_op.add_column(sa.Column('about_me', sa.VARCHAR(length=140), nullable=True))
batch_op.drop_index(batch_op.f('ix_user_role'))
batch_op.drop_column('role')
# ### end Alembic commands ###

View File

@@ -1,14 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<meta name="description" content="Web site created using create-react-app" />
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
@@ -25,9 +23,16 @@
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<script src="https://cdn.jsdelivr.net/npm/react/umd/react.production.min.js" crossorigin></script>
<script src="https://cdn.jsdelivr.net/npm/react-dom/umd/react-dom.production.min.js" crossorigin></script>
<script src="https://cdn.jsdelivr.net/npm/react-bootstrap@next/dist/react-bootstrap.min.js" crossorigin></script>
<div id="root"></div>
<!--
This HTML file is a template.
@@ -39,5 +44,6 @@
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</body>
</html>

View File

@@ -1,38 +0,0 @@
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

View File

@@ -1,13 +1,13 @@
import "./App.css";
import { Route } from "wouter";
import HomePage from "./pages/HomePage";
import LoginPage from "./pages/LoginPage";
function App() {
return (
<div className="App">
<Route path="/">
<HomePage />
</Route>
<Route path="/" component={HomePage} />
<Route path="/login" component={LoginPage} />
</div>
);
}

View File

@@ -0,0 +1,20 @@
import { Nav, Container, Navbar, NavDropdown } from "react-bootstrap";
const MyNavbar = () => {
return (
<Navbar variant="dark" bg="dark" expand="lg">
<Container>
<Navbar.Brand href="/">LearningTree</Navbar.Brand>
<Navbar.Toggle aria-controls="navbar-nav" />
<Navbar.Collapse id="navbar-nav">
<Nav className="ms-auto">
<Nav.Link href="/">Home</Nav.Link>
<Nav.Link href="/login">Login</Nav.Link>
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
);
};
export default MyNavbar;

View File

@@ -3,6 +3,7 @@ import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.min.css';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(

View File

@@ -1,8 +1,16 @@
import { Container } from "react-bootstrap";
import MyNavbar from "../components/MyNavbar";
const HomePage = () => {
return (
<div>
<MyNavbar />
<Container>
<div>
<h1>This is the home page</h1>
</div>
</Container>
</div>
);
};

View File

@@ -0,0 +1,38 @@
import React from "react";
import { Col, Container, Form, Row } from "react-bootstrap";
import MyNavbar from "../components/MyNavbar";
const LoginPage = () => {
return (
<React.Fragment>
<MyNavbar />
<Container className="p-5">
<Form>
<Form.Group as={Row} className="mb-3" controlId="username">
<Form.Label column sm={2}>
Username
</Form.Label>
<Col sm={10}>
<Form.Control type="username" placeholder="username" />
</Col>
</Form.Group>
<Form.Group as={Row} className="mb-3" controlId="password">
<Form.Label column sm={2}>
Password
</Form.Label>
<Col sm={10}>
<Form.Control type="password" placeholder="password" />
</Col>
</Form.Group>
<Form.Group as={Row}>
<p>
Don't have an account? <a href="/register">Register here</a>
</p>
</Form.Group>
</Form>
</Container>
</React.Fragment>
);
};
export default LoginPage;