user authentication
This commit is contained in:
parent
9805d64bac
commit
19b584cbe7
10
forms.py
10
forms.py
@ -1,5 +1,5 @@
|
|||||||
from flask_wtf import FlaskForm
|
from flask_wtf import FlaskForm
|
||||||
from wtforms import StringField, SubmitField, TextAreaField
|
from wtforms import StringField, SubmitField, TextAreaField, BooleanField, PasswordField
|
||||||
from wtforms.validators import DataRequired, Email
|
from wtforms.validators import DataRequired, Email
|
||||||
|
|
||||||
|
|
||||||
@ -8,3 +8,11 @@ class ContactForm(FlaskForm):
|
|||||||
email = StringField("Email: ", validators=[Email()])
|
email = StringField("Email: ", validators=[Email()])
|
||||||
message = TextAreaField("Message", validators=[DataRequired()])
|
message = TextAreaField("Message", validators=[DataRequired()])
|
||||||
submit = SubmitField("Submit")
|
submit = SubmitField("Submit")
|
||||||
|
|
||||||
|
|
||||||
|
class LoginForm(FlaskForm):
|
||||||
|
username = StringField("Username", validators=[DataRequired()])
|
||||||
|
password = PasswordField("Password", validators=[DataRequired()])
|
||||||
|
remember = BooleanField("Remember Me")
|
||||||
|
submit = SubmitField()
|
||||||
|
|
||||||
|
67
main.py
67
main.py
@ -1,12 +1,14 @@
|
|||||||
import flask
|
import flask
|
||||||
from flask import Flask, request, current_app, url_for, render_template, flash, redirect
|
from flask import Flask, request, current_app, url_for, render_template, flash, redirect
|
||||||
|
from werkzeug.security import generate_password_hash, check_password_hash
|
||||||
from flask_script import Manager, Shell
|
from flask_script import Manager, Shell
|
||||||
from flask_migrate import Migrate, MigrateCommand
|
from flask_migrate import Migrate, MigrateCommand
|
||||||
|
from flask_login import LoginManager, UserMixin, login_required, login_user, current_user, logout_user
|
||||||
from jinja2 import Template
|
from jinja2 import Template
|
||||||
from flask_sqlalchemy import SQLAlchemy
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from forms import ContactForm
|
from forms import ContactForm, LoginForm
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
app.debug = True
|
app.debug = True
|
||||||
@ -14,6 +16,8 @@ app.config['SECRET_KEY'] = '0d6e368e-bd0c-11ea-921d-9342d47f60ca'
|
|||||||
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
||||||
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///db.sqlite"
|
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///db.sqlite"
|
||||||
db = SQLAlchemy(app)
|
db = SQLAlchemy(app)
|
||||||
|
login_manager = LoginManager(app)
|
||||||
|
login_manager.login_view = 'login'
|
||||||
migrate = Migrate(app, db)
|
migrate = Migrate(app, db)
|
||||||
manager = Manager(app)
|
manager = Manager(app)
|
||||||
manager.add_command('db', MigrateCommand)
|
manager.add_command('db', MigrateCommand)
|
||||||
@ -75,6 +79,37 @@ class Feedback(db.Model):
|
|||||||
return "<{}:{}>".format(self.id, self.name)
|
return "<{}:{}>".format(self.id, self.name)
|
||||||
|
|
||||||
|
|
||||||
|
class User(db.Model, UserMixin):
|
||||||
|
__tablename__ = 'users'
|
||||||
|
id = db.Column(db.Integer(), primary_key=True)
|
||||||
|
name = db.Column(db.String(100))
|
||||||
|
username = db.Column(db.String(50), nullable=False, unique=True)
|
||||||
|
email = db.Column(db.String(100), nullable=False, unique=True)
|
||||||
|
password_hash = db.Column(db.String(100), nullable=False)
|
||||||
|
created_on = db.Column(db.DateTime(), default=datetime.utcnow)
|
||||||
|
updated_on = db.Column(db.DateTime(), default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return "<{}:{}>".format(self.id, self.username)
|
||||||
|
|
||||||
|
def set_password(self, password):
|
||||||
|
self.password_hash = generate_password_hash(password)
|
||||||
|
|
||||||
|
def check_password(self, password):
|
||||||
|
return check_password_hash(self.password_hash, password)
|
||||||
|
|
||||||
|
|
||||||
|
@login_manager.user_loader
|
||||||
|
def load_user(user_id):
|
||||||
|
return db.session.query(User).get(user_id)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/admin/')
|
||||||
|
@login_required
|
||||||
|
def admin():
|
||||||
|
return render_template('admin.html')
|
||||||
|
|
||||||
|
|
||||||
@manager.command
|
@manager.command
|
||||||
def faker():
|
def faker():
|
||||||
print("Команда для добавления поддельных данных в таблицы")
|
print("Команда для добавления поддельных данных в таблицы")
|
||||||
@ -87,20 +122,26 @@ def index():
|
|||||||
|
|
||||||
@app.route('/login/', methods=['post', 'get'])
|
@app.route('/login/', methods=['post', 'get'])
|
||||||
def login():
|
def login():
|
||||||
username = ''
|
if current_user.is_authenticated:
|
||||||
password = ''
|
return redirect(url_for('admin'))
|
||||||
message = ''
|
form = LoginForm()
|
||||||
if request.method == 'POST':
|
if form.validate_on_submit():
|
||||||
username = request.form.get('username') # запрос к данным формы
|
user = db.session.query(User).filter(User.username == form.username.data).first()
|
||||||
password = request.form.get('password')
|
if user and user.check_password(form.password.data):
|
||||||
|
login_user(user, remember=form.remember.data)
|
||||||
|
nextpage = request.args.get('next', url_for('admin'))
|
||||||
|
return redirect(nextpage)
|
||||||
|
else:
|
||||||
|
flash("Invalid username/password", 'error')
|
||||||
|
return render_template('login.html', form=form)
|
||||||
|
|
||||||
if username == 'root' and password == 'pass':
|
|
||||||
message = "Correct username and password"
|
|
||||||
else:
|
|
||||||
message = "Wrong username or password"
|
|
||||||
|
|
||||||
return render_template('login.html', message=message)
|
|
||||||
|
|
||||||
|
@app.route('/logout/')
|
||||||
|
@login_required
|
||||||
|
def logout():
|
||||||
|
logout_user()
|
||||||
|
flash("You have been logged out.")
|
||||||
|
return redirect(url_for('login'))
|
||||||
|
|
||||||
@app.route('/contact/', methods=['get', 'post'])
|
@app.route('/contact/', methods=['get', 'post'])
|
||||||
def contact():
|
def contact():
|
||||||
|
39
migrations/versions/d0915c4b79cd_add_users_table.py
Normal file
39
migrations/versions/d0915c4b79cd_add_users_table.py
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
"""add users table
|
||||||
|
|
||||||
|
Revision ID: d0915c4b79cd
|
||||||
|
Revises: 60a6132e925b
|
||||||
|
Create Date: 2020-07-03 14:14:52.140939
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'd0915c4b79cd'
|
||||||
|
down_revision = '60a6132e925b'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table('users',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(length=100), nullable=True),
|
||||||
|
sa.Column('username', sa.String(length=50), nullable=False),
|
||||||
|
sa.Column('email', sa.String(length=100), nullable=False),
|
||||||
|
sa.Column('password_hash', sa.String(length=100), nullable=False),
|
||||||
|
sa.Column('created_on', sa.DateTime(), nullable=True),
|
||||||
|
sa.Column('updated_on', sa.DateTime(), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('email'),
|
||||||
|
sa.UniqueConstraint('username')
|
||||||
|
)
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_table('users')
|
||||||
|
# ### end Alembic commands ###
|
@ -4,4 +4,5 @@ Flask-Script==2.0.6
|
|||||||
email_validator==1.1.1
|
email_validator==1.1.1
|
||||||
Flask_SQLAlchemy==2.4.3
|
Flask_SQLAlchemy==2.4.3
|
||||||
SQLAlchemy==1.3.18
|
SQLAlchemy==1.3.18
|
||||||
flask-migrate==2.5.3
|
flask-migrate==2.5.3
|
||||||
|
flask_login==0.5.0
|
||||||
|
21
templates/admin.html
Normal file
21
templates/admin.html
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Title</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<h2>Logged in User details</h2>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li>Username: {{ current_user.username }}</li>
|
||||||
|
<li>Email: {{ current_user.email }}</li>
|
||||||
|
<li>Created on: {{ current_user.created_on }}</li>
|
||||||
|
<li>Updated on: {{ current_user.updated_on }}</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<p><a href="{{ url_for('logout') }}">Logout</a></p>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
@ -6,21 +6,36 @@
|
|||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|
||||||
{% if message %}
|
{% for category, message in get_flashed_messages(with_categories=true) %}
|
||||||
<p>{{ message }}</p>
|
<spam class="{{ category }}">{{ message }}</spam>
|
||||||
{% endif %}
|
{% endfor %}
|
||||||
|
|
||||||
<form action="" method="post">
|
<form action="" method="post">
|
||||||
<p>
|
{{ form.csrf_token }}
|
||||||
<label for="username">Username</label>
|
<p>
|
||||||
<input type="text" name="username">
|
{{ form.username.label() }}
|
||||||
|
{{ form.username() }}
|
||||||
|
{% if form.username.errors %}
|
||||||
|
{% for error in form.username.errors %}
|
||||||
|
{{ error }}
|
||||||
|
{% endfor %}
|
||||||
|
{% endif %}
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
<label for="password">Password</label>
|
{{ form.password.label() }}
|
||||||
<input type="password" name="password">
|
{{ form.password() }}
|
||||||
|
{% if form.password.errors %}
|
||||||
|
{% for error in form.password.errors %}
|
||||||
|
{{ error }}
|
||||||
|
{% endfor %}
|
||||||
|
{% endif %}
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
<input type="submit">
|
{{ form.remember.label() }}
|
||||||
|
{{ form.remember() }}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
{{ form.submit() }}
|
||||||
</p>
|
</p>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user