Fleshed out session system...

This commit is contained in:
Maxim Stewart 2020-03-14 03:43:04 -05:00
parent ea56c43eab
commit a88e89c7d9
10 changed files with 84 additions and 41 deletions

View File

@ -1,5 +1,6 @@
from flask import Flask from flask import Flask
from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt
from flask_login import current_user, login_user, logout_user, LoginManager
app = Flask(__name__) app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///static/db/database.db" app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///static/db/database.db"
@ -9,9 +10,12 @@ app.config['TITLE'] = ':::APP TITLE:::'
# For csrf...change!! # For csrf...change!!
app.config['SECRET_KEY'] = '48e80dcf4ed6ea952ca1b7b564be22d665e6e178f7fda84828fdd5e7cdca097a' app.config['SECRET_KEY'] = '48e80dcf4ed6ea952ca1b7b564be22d665e6e178f7fda84828fdd5e7cdca097a'
from core.models import db
db.init_app(app)
login_manager = LoginManager(app)
bcrypt = Bcrypt(app)
from core.models import db, User
db.init_app(app)
from core.forms import RegisterForm, LoginForm from core.forms import RegisterForm, LoginForm
from core import routes from core import routes

View File

@ -1,6 +1,7 @@
from flask_wtf import FlaskForm from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Length, Email, EqualTo from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
from core import User
@ -12,6 +13,11 @@ class RegisterForm(FlaskForm):
validators=[DataRequired(), EqualTo('password', message="Passwords must match!")]) validators=[DataRequired(), EqualTo('password', message="Passwords must match!")])
submit = SubmitField("Sign Up") submit = SubmitField("Sign Up")
def validate_username(self, username):
user = User.query.filter_by(username=username.data).first()
if user:
raise ValidationError("User exists already! Please use a different name!")
class LoginForm(FlaskForm): class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=4, max=24)]) username = StringField('Username', validators=[DataRequired(), Length(min=4, max=24)])

View File

@ -1,17 +1,17 @@
from flask_sqlalchemy import SQLAlchemy from flask_sqlalchemy import SQLAlchemy
from core import app, login_manager
db = SQLAlchemy() from flask_login import UserMixin
class Table(db.Model): db = SQLAlchemy(app)
id = db.Column(db.Integer, nullable=False, primary_key=True, unique=True, autoincrement=True)
def __repr__(self): @login_manager.user_loader
return f"['{self.title}', '{self.icon}', '{self.link}', '{self.id}']" def load_user(user_id):
return User.query.get(int(user_id))
class User(db.Model): class User(db.Model, UserMixin):
username = db.Column(db.String, nullable=False) username = db.Column(db.String, unique=True, nullable=False)
email = db.Column(db.String, nullable=False) email = db.Column(db.String, nullable=False)
password = db.Column(db.String, nullable=False) password = db.Column(db.String, nullable=False)
id = db.Column(db.Integer, nullable=False, primary_key=True, unique=True, autoincrement=True) id = db.Column(db.Integer, nullable=False, primary_key=True, unique=True, autoincrement=True)

View File

@ -5,7 +5,6 @@ from flask import request, render_template
# App imports # App imports
from core import app, db # Get from __init__ from core import app, db # Get from __init__
from core.models import Table # Get db models
from core.MessageHandler import MessageHandler # Get simple message processor from core.MessageHandler import MessageHandler # Get simple message processor

View File

@ -1,10 +1,11 @@
# Python imports # Python imports
# Lib imports # Lib imports
from flask import request, render_template from flask import request, render_template, flash, redirect, url_for
from flask_login import current_user, login_user, logout_user
# App imports # App imports
from core import app, db, LoginForm from core import app, bcrypt, db, User, LoginForm
from core.MessageHandler import MessageHandler # Get simple message processor from core.MessageHandler import MessageHandler # Get simple message processor
@ -13,8 +14,25 @@ TITLE = app.config['TITLE']
@app.route('/login', methods=['GET', 'POST']) @app.route('/login', methods=['GET', 'POST'])
def login(): def login():
_form = LoginForm() if current_user.is_authenticated:
return redirect(url_for("home"))
return render_template('login.html', _form = LoginForm()
title=TITLE, if _form.validate_on_submit():
form=_form) user = db.session.query(User).filter(User.username == _form.username.data).first()
if user and bcrypt.check_password_hash(user.password, _form.password.data):
login_user(user, remember=False)
flash("Logged in successfully!", "success")
return redirect(url_for("home"))
flash("Username or password incorrect! Please try again...", "danger")
return render_template('login.html', title=TITLE, form=_form)
@app.route('/logout')
def logout():
logout_user()
flash("Logged out successfully!", "success")
return redirect(url_for("home"))

View File

@ -4,7 +4,8 @@
from flask import request, render_template, url_for, redirect, flash from flask import request, render_template, url_for, redirect, flash
# App imports # App imports
from core import app, db, RegisterForm from core import app, bcrypt, db, current_user, RegisterForm # Get from __init__
from core.models import User
from core.MessageHandler import MessageHandler # Get simple message processor from core.MessageHandler import MessageHandler # Get simple message processor
@ -13,12 +14,18 @@ TITLE = app.config['TITLE']
@app.route('/register', methods=['GET', 'POST']) @app.route('/register', methods=['GET', 'POST'])
def register(): def register():
_form = RegisterForm() if current_user.is_authenticated:
if _form.validate_on_submit():
flash("Account created successfully!", "success")
return redirect(url_for("home")) return redirect(url_for("home"))
_form = RegisterForm()
if _form.validate_on_submit():
hashed_password = bcrypt.generate_password_hash(_form.password.data).decode("utf-8")
user = User(username=_form.username.data, email=_form.email.data, password=hashed_password)
db.session.add(user)
db.session.commit()
flash("Account created successfully!", "success")
return redirect(url_for("login"))
return render_template('register.html', return render_template('register.html',
title=TITLE, title=TITLE,
form=_form) form=_form)

Binary file not shown.

View File

@ -22,19 +22,22 @@
</li> </li>
<!-- Dropdowns --> <!-- Dropdowns -->
<!-- Others Dropdown -->
{% if not current_user.is_authenticated %}
<li class="nav-item dropdown"> <li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown">
Account Account
</a> </a>
<div class="dropdown-menu"> <div class="dropdown-menu">
<a class="dropdown-item" href="{{ url_for('login') }}"> <a class="dropdown-item" href="{{ url_for('login') }}">
<i title="Send Us an Email" class="fas fa-user"></i>&nbsp;&nbsp;Login</a> <i title="Login" class="fas fa-user"></i>&nbsp;&nbsp;Login</a>
<a class="dropdown-item" href="{{ url_for('register') }}"> <a class="dropdown-item" href="{{ url_for('register') }}">
<i title="Find Us on Twitter" class="fas fa-user-plus"></i>&nbsp;&nbsp;Register</a> <i title="Register A User..." class="fas fa-user-plus"></i>&nbsp;&nbsp;Register</a>
</div> </div>
</li> </li>
{% endif %}
<!-- Others Dropdown -->
<li class="nav-item dropdown"> <li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown">
Projects Projects
@ -80,6 +83,13 @@
<a class="nav-link" href="{{ url_for('about') }}"> <a class="nav-link" href="{{ url_for('about') }}">
<i class="far fa-address-card"></i> About</a> <i class="far fa-address-card"></i> About</a>
</li> </li>
{% if current_user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="{{ url_for('logout') }}">
<i class="fas fa-sign-out-alt"></i> Logout</a>
</li>
{% endif %}
</ul> </ul>
</div> </div>

View File

@ -30,6 +30,22 @@
{% endblock header_css_additional %} {% endblock header_css_additional %}
{% endblock %} {% endblock %}
{% block header_scripts %}
{% block header_scripts_additional %}
{% endblock header_scripts_additional %}
{% endblock %}
</head>
<body>
<img id="bg" src="{{ url_for('static', filename='imgs/backgrounds/background.jpg')}}" alt="{{title}} Background Logo" />
{% block body_header %}
{% include "body-header.html" %}
{% block body_header_additional %}
{% endblock body_header_additional%}
{% endblock %}
<!-- System flashed messages! --> <!-- System flashed messages! -->
{% with messages = get_flashed_messages(with_categories=true) %} {% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %} {% if messages %}
@ -41,23 +57,6 @@
{% endif %} {% endif %}
{% endwith %} {% endwith %}
{% block header_scripts %}
{% block header_scripts_additional %}
{% endblock header_scripts_additional %}
{% endblock %}
</head>
<body>
<img id="bg" src="{{ url_for('static', filename='imgs/backgrounds/background.jpg')}}" alt="{{title}} Background Logo" />
{% block body_header %}
{% include "body-header.html" %}
{% block body_header_additional %}
{% endblock body_header_additional%}
{% endblock %}
{% block body_content %} {% block body_content %}
{% block body_content_additional %} {% block body_content_additional %}
{% endblock body_content_additional%} {% endblock body_content_additional%}

View File

@ -30,10 +30,10 @@
<div class="form-group"> <div class="form-group">
{{ form.password.label(class="form-control-label") }} {{ form.password.label(class="form-control-label") }}
{% if form.email.errors %} {% if form.password.errors %}
{{ form.email(class="form-control form-control-sm is-invalid", autocomplete="off") }} {{ form.password(class="form-control form-control-sm is-invalid", autocomplete="off") }}
<div class="invalid-feedback"> <div class="invalid-feedback">
{% for error in form.email.errors %} {% for error in form.password.errors %}
<span class="">{{ error }}</span> <span class="">{{ error }}</span>
{% endfor %} {% endfor %}
{% else %} {% else %}