diff options
Diffstat (limited to 'app')
-rw-r--r-- | app/__init__.py | 40 | ||||
-rw-r--r-- | app/apis.py | 18 | ||||
-rw-r--r-- | app/config_dev.py | 14 | ||||
-rw-r--r-- | app/forms/app_forms.py | 23 | ||||
-rw-r--r-- | app/misc_func.py | 32 | ||||
-rw-r--r-- | app/models.py | 13 | ||||
-rw-r--r-- | app/tests/conftest.py | 16 | ||||
-rw-r--r-- | app/tests/test_admin.py | 23 | ||||
-rw-r--r-- | app/tests/test_cli.py | 9 | ||||
-rw-r--r-- | app/tests/test_fastapi.py | 22 | ||||
-rw-r--r-- | app/tests/test_forms.py | 37 | ||||
-rw-r--r-- | app/tests/test_models.py | 16 | ||||
-rw-r--r-- | app/tests/test_views.py | 222 | ||||
-rw-r--r-- | app/views/admin.py | 6 | ||||
-rw-r--r-- | app/views/auth.py | 77 | ||||
-rw-r--r-- | app/views/error_pages.py | 25 | ||||
-rw-r--r-- | app/views/main.py | 17 |
17 files changed, 344 insertions, 266 deletions
diff --git a/app/__init__.py b/app/__init__.py index 9d76abe..72aac8c 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -9,7 +9,7 @@ from flask_mailman import Mail from authlib.integrations.flask_client import OAuth app = Flask(__name__) -app.config.from_object('app.config') +app.config.from_object("app.config") bcrypt = Bcrypt(app) db = SQLAlchemy(app) @@ -18,36 +18,46 @@ oauth = OAuth(app) mail = Mail(app) oauth.register( - name="google", - server_metadata_url="https://accounts.google.com/.well-known/openid-configuration", - client_kwargs={"scope": "openid email profile"}) + name="google", + server_metadata_url="https://accounts.google.com/.well-known/openid-configuration", + client_kwargs={"scope": "openid email profile"}, +) login_manager.init_app(app) from app.models import User database_cli = AppGroup("database") + + @database_cli.command("create") def create_database(): - db.create_all() + db.create_all() + + @database_cli.command("delete") def delete_database(): - db.drop_all() + db.drop_all() + + @database_cli.command("admin-create") def make_superuser_database(): - user = User( - first_name="Supersu", - email=app.config["ADMIN_EMAIL"], - password=app.config["ADMIN_PASSWORD"], - role="SUPERUSER") - user.confirmation = True - db.session.add(user) - db.session.commit() + user = User( + first_name="Supersu", + email=app.config["ADMIN_EMAIL"], + password=app.config["ADMIN_PASSWORD"], + role="SUPERUSER", + ) + user.confirmation = True + db.session.add(user) + db.session.commit() + app.cli.add_command(database_cli) from app.views import main + @login_manager.user_loader def load_user(email): - return User.query.filter(User.email == email).first()
\ No newline at end of file + return User.query.filter(User.email == email).first() diff --git a/app/apis.py b/app/apis.py index 51e8987..b81882e 100644 --- a/app/apis.py +++ b/app/apis.py @@ -4,17 +4,17 @@ from fastapi import Body, FastAPI, HTTPException from fastapi.middleware.wsgi import WSGIMiddleware from pydantic import BaseModel + @app.get("/version") async def API_Version(): - return {"message":app.version} + return {"message": app.version} + @app.get("/v1/user-details") async def API_User_Details(email: str): - user = models.User.query.filter_by(email=email).first() - try: - assert user != None - except AssertionError: - raise HTTPException(status_code=404, detail="User Not Found") - return { - "first_name":user.first_name, - "last_name":user.last_name}
\ No newline at end of file + user = models.User.query.filter_by(email=email).first() + try: + assert user != None + except AssertionError: + raise HTTPException(status_code=404, detail="User Not Found") + return {"first_name": user.first_name, "last_name": user.last_name} diff --git a/app/config_dev.py b/app/config_dev.py index 6e77e55..b423943 100644 --- a/app/config_dev.py +++ b/app/config_dev.py @@ -1,6 +1,6 @@ import os -SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db' +SQLALCHEMY_DATABASE_URI = "sqlite:////tmp/test.db" SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = "tchtchtch" @@ -8,16 +8,16 @@ SECRET_KEY = "tchtchtch" ADMIN_EMAIL = "admin@example.com" ADMIN_PASSWORD = "iamgroot" -GOOGLE_CLIENT_ID=os.environ.get("GOOGLE_CLIENT_ID") -GOOGLE_CLIENT_SECRET=os.environ.get("GOOGLE_CLIENT_SECRET") +GOOGLE_CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID") +GOOGLE_CLIENT_SECRET = os.environ.get("GOOGLE_CLIENT_SECRET") -#MAIL_BACKEND = 'file' -#MAIL_FILE_PATH = '/tmp/app-messages' +# MAIL_BACKEND = 'file' +# MAIL_FILE_PATH = '/tmp/app-messages' MAIL_BACKEND = "smtp" MAIL_SERVER = os.environ.get("MAIL_SERVER") -MAIL_PORT = os.environ.get("MAIL_PORT") +MAIL_PORT = os.environ.get("MAIL_PORT") MAIL_USERNAME = os.environ.get("MAIL_USERNAME") MAIL_PASSWORD = os.environ.get("MAIL_PASSWORD") MAIL_FROM = os.environ.get("MAIL_FROM") -MAIL_USE_TLS = bool(os.environ.get("MAIL_USE_TLS"))
\ No newline at end of file +MAIL_USE_TLS = bool(os.environ.get("MAIL_USE_TLS")) diff --git a/app/forms/app_forms.py b/app/forms/app_forms.py index 005b53a..a7742cd 100644 --- a/app/forms/app_forms.py +++ b/app/forms/app_forms.py @@ -3,18 +3,21 @@ from wtforms import StringField, TextAreaField, PasswordField from wtforms.fields.html5 import EmailField from wtforms.validators import DataRequired, Email + class MyForm(FlaskForm): - name = StringField('Name', validators=[DataRequired()]) - email = EmailField('Email', validators=[DataRequired(), Email()]) - subject = StringField('Subject', validators=[DataRequired()]) - body = TextAreaField('Message', validators=[DataRequired()]) + name = StringField("Name", validators=[DataRequired()]) + email = EmailField("Email", validators=[DataRequired(), Email()]) + subject = StringField("Subject", validators=[DataRequired()]) + body = TextAreaField("Message", validators=[DataRequired()]) + class UserSignUp(FlaskForm): - first_name = StringField('First Name', validators=[DataRequired()]) - last_name = StringField('Last Name') - email = EmailField('Email',validators=[DataRequired(),Email()]) - password = PasswordField('Password',validators=[DataRequired()]) + first_name = StringField("First Name", validators=[DataRequired()]) + last_name = StringField("Last Name") + email = EmailField("Email", validators=[DataRequired(), Email()]) + password = PasswordField("Password", validators=[DataRequired()]) + class UserLogIn(FlaskForm): - email = EmailField('Email',validators=[DataRequired()]) - password = PasswordField('Password',validators=[DataRequired()])
\ No newline at end of file + email = EmailField("Email", validators=[DataRequired()]) + password = PasswordField("Password", validators=[DataRequired()]) diff --git a/app/misc_func.py b/app/misc_func.py index 73e920d..d560337 100644 --- a/app/misc_func.py +++ b/app/misc_func.py @@ -3,25 +3,29 @@ from flask import flash from flask_mailman import EmailMultiAlternatives from app import app, mail + def flash_errors(form): for field, errors in form.errors.items(): for error in errors: - flash(u"Error in the %s field - %s" % ( - getattr(form, field).label.text, - error - ), 'danger') - -# Sauce: https://github.com/alectrocute/flaskSaaS/blob/master/app/toolbox/email.py - -def send(to, subject, body, body_html,thread=True): - sender = app.config["MAIL_FROM"] - message = EmailMultiAlternatives( - subject,body,sender,[to]) - message.attach_alternative(body_html,"text/html") - thr = Thread(target=send_async, args=[app,message]) + flash( + u"Error in the %s field - %s" + % (getattr(form, field).label.text, error), + "danger", + ) + + +# Sauce: https://github.com/alectrocute/flaskSaaS/blob/master/app/toolbox/email.py + + +def send(to, subject, body, body_html, thread=True): + sender = app.config["MAIL_FROM"] + message = EmailMultiAlternatives(subject, body, sender, [to]) + message.attach_alternative(body_html, "text/html") + thr = Thread(target=send_async, args=[app, message]) thr.start() + def send_async(app, message): with app.app_context(): message.send() - print("Mail Sent")
\ No newline at end of file + print("Mail Sent") diff --git a/app/models.py b/app/models.py index 644c96d..47f7c96 100644 --- a/app/models.py +++ b/app/models.py @@ -3,8 +3,9 @@ from flask_login import UserMixin from app import bcrypt, db + class User(db.Model, UserMixin): - __tablename__ = 'users' + __tablename__ = "users" first_name = db.Column(db.String) last_name = db.Column(db.String) @@ -13,12 +14,12 @@ class User(db.Model, UserMixin): paid = db.Column(db.Boolean) role = db.Column(db.String) team = db.Column(db.String) - login_type = db.Column(db.String ,default="Normie") + login_type = db.Column(db.String, default="Normie") _password = db.Column(db.String) @property def full_name(self): - return '{} {}'.format(self.first_name, self.last_name) + return "{} {}".format(self.first_name, self.last_name) @hybrid_property def password(self): @@ -35,10 +36,10 @@ class User(db.Model, UserMixin): return self.email def get_role(self): - return self.role + return self.role def get_team(self): - return self.team + return self.team def is_paid(self): - return self.paid
\ No newline at end of file + return self.paid diff --git a/app/tests/conftest.py b/app/tests/conftest.py index 0fd1ef1..71eb677 100644 --- a/app/tests/conftest.py +++ b/app/tests/conftest.py @@ -5,14 +5,18 @@ from app import db import tempfile import os + @pytest.fixture def app(): - flask_app.config['WTF_CSRF_ENABLED'] = False - flask_app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///" + tempfile.mkstemp(suffix='.db')[-1] - flask_app.config['MAIL_BACKEND'] = "file" #"locmem" - flask_app.config["MAIL_FILE_PATH"] = '/tmp/app-messages' - db.create_all() - yield flask_app + flask_app.config["WTF_CSRF_ENABLED"] = False + flask_app.config["SQLALCHEMY_DATABASE_URI"] = ( + "sqlite:///" + tempfile.mkstemp(suffix=".db")[-1] + ) + flask_app.config["MAIL_BACKEND"] = "file" # "locmem" + flask_app.config["MAIL_FILE_PATH"] = "/tmp/app-messages" + db.create_all() + yield flask_app + @pytest.fixture def client(app): diff --git a/app/tests/test_admin.py b/app/tests/test_admin.py index 1a5df07..ae20f2b 100644 --- a/app/tests/test_admin.py +++ b/app/tests/test_admin.py @@ -1,14 +1,19 @@ from app import database_cli + def test_admin(app, client): - runner = app.test_cli_runner() - assert runner.invoke(database_cli,["admin-create"]).exit_code == 0 + runner = app.test_cli_runner() + assert runner.invoke(database_cli, ["admin-create"]).exit_code == 0 - res = client.post("/signin",data=dict( - email=app.config["ADMIN_EMAIL"], - password=app.config["ADMIN_PASSWORD"]),follow_redirects=True) + res = client.post( + "/signin", + data=dict( + email=app.config["ADMIN_EMAIL"], password=app.config["ADMIN_PASSWORD"] + ), + follow_redirects=True, + ) - print(res.data) - assert b"Supersu" in res.data - res = client.get("/admin/user/") - assert res.status_code == 200
\ No newline at end of file + print(res.data) + assert b"Supersu" in res.data + res = client.get("/admin/user/") + assert res.status_code == 200 diff --git a/app/tests/test_cli.py b/app/tests/test_cli.py index aec4cee..194dd64 100644 --- a/app/tests/test_cli.py +++ b/app/tests/test_cli.py @@ -1,7 +1,8 @@ from app import database_cli + def test_database_commands(app, client): - runner = app.test_cli_runner() - assert runner.invoke(database_cli,["delete"]).exit_code == 0 - assert runner.invoke(database_cli,["create"]).exit_code == 0 - assert runner.invoke(database_cli,["admin-create"]).exit_code == 0
\ No newline at end of file + runner = app.test_cli_runner() + assert runner.invoke(database_cli, ["delete"]).exit_code == 0 + assert runner.invoke(database_cli, ["create"]).exit_code == 0 + assert runner.invoke(database_cli, ["admin-create"]).exit_code == 0 diff --git a/app/tests/test_fastapi.py b/app/tests/test_fastapi.py index 89ae368..f8c304e 100644 --- a/app/tests/test_fastapi.py +++ b/app/tests/test_fastapi.py @@ -4,17 +4,19 @@ from api import app as fastapi_app fastapi_client = TestClient(fastapi_app) + def test_fastapi(app, client): - res = fastapi_client.get("/version") - assert res.status_code == 200 - assert res.json() == {"message":fastapi_app.version} + res = fastapi_client.get("/version") + assert res.status_code == 200 + assert res.json() == {"message": fastapi_app.version} + def test_fastapi_user_details(app, client): - # TODO Investigate why this is failing - #res = fastapi_client.get("/v1/user-details?email={}".format("admin@example.com")) - #assert res.status_code == 200 - #assert res.json()["first_name"] == "Supersu" + # TODO Investigate why this is failing + # res = fastapi_client.get("/v1/user-details?email={}".format("admin@example.com")) + # assert res.status_code == 200 + # assert res.json()["first_name"] == "Supersu" - res = fastapi_client.get("/v1/user-details?email={}".format("notadmin@example.com")) - assert res.status_code == 404 - assert res.json()["detail"] == "User Not Found" + res = fastapi_client.get("/v1/user-details?email={}".format("notadmin@example.com")) + assert res.status_code == 404 + assert res.json()["detail"] == "User Not Found" diff --git a/app/tests/test_forms.py b/app/tests/test_forms.py index 2da2c36..1a26635 100644 --- a/app/tests/test_forms.py +++ b/app/tests/test_forms.py @@ -1,19 +1,24 @@ -def test_incorrect_forms(app,client): - res = client.post("/signin",data={"email":"123"}) - assert b"This field is required." in res.data +def test_incorrect_forms(app, client): + res = client.post("/signin", data={"email": "123"}) + assert b"This field is required." in res.data - res = client.post("/signup",data={"email":"123"}) - assert b"This field is required." in res.data + res = client.post("/signup", data={"email": "123"}) + assert b"This field is required." in res.data - res = client.post("/ContactUs",data={"email":123}) - assert b"This field is required." in res.data + res = client.post("/ContactUs", data={"email": 123}) + assert b"This field is required." in res.data -def test_contactus(app,client): - res = client.post("/ContactUs",data={ - "name": "Test User", - "subject": "Test Contact", - "email": "testemail@email.com", - "body": "Test Message" - }, follow_redirects=True) - assert res.status_code == 200 - assert b"Wuhu" in res.data
\ No newline at end of file + +def test_contactus(app, client): + res = client.post( + "/ContactUs", + data={ + "name": "Test User", + "subject": "Test Contact", + "email": "testemail@email.com", + "body": "Test Message", + }, + follow_redirects=True, + ) + assert res.status_code == 200 + assert b"Wuhu" in res.data diff --git a/app/tests/test_models.py b/app/tests/test_models.py index 513f332..c84df92 100644 --- a/app/tests/test_models.py +++ b/app/tests/test_models.py @@ -1,11 +1,9 @@ from app.models import User -def test_usermodel(app,client): - user = User( - first_name="John", - email="test@example.com", - password="pass") - assert user.full_name == "John None" - assert user.get_role() == None - assert user.get_team() == None - assert user.is_paid() == None
\ No newline at end of file + +def test_usermodel(app, client): + user = User(first_name="John", email="test@example.com", password="pass") + assert user.full_name == "John None" + assert user.get_role() == None + assert user.get_team() == None + assert user.is_paid() == None diff --git a/app/tests/test_views.py b/app/tests/test_views.py index 0abd5e4..811815f 100644 --- a/app/tests/test_views.py +++ b/app/tests/test_views.py @@ -1,122 +1,120 @@ from itsdangerous.url_safe import URLSafeSerializer from app import app as flask_app + ts = URLSafeSerializer(flask_app.config["SECRET_KEY"]) data2check_visitors = { - "/index": { - "code": 200, "data": b"Nice Tagline" - }, - "/": { - "code": 200, "data": b"Nice Tagline" - }, - "/ContactUs":{ - "code": 200, "data": b"send us a message." - }, - "/doesnotexists":{ - "code": 404, "data": b"Page Not Found" - }, - "/logout":{ - "code": 200, "data": b"You have been logged out." - }, - "/dashboard":{ - "code":401,"data":b"You need to be logged in to access this resource" - }, - "/signup":{ - "code":200,"data":b"Register your account." - }, - "/signin":{ - "code":200,"data":b"Sign in to your account." - }, - "/Simulate500":{ - "code":500,"data":b"Server Could Not Process This." - }, - "/admin/user/":{ - "code":403,"data":b"Forbidden" - }, - "/confirm":{ - "code":200,"data":b"Token not provided in URL Parameter" - }, - "/confirm?confirmation_token=123":{ - "code":200,"data":b"Bad Token Provided" - } + "/index": {"code": 200, "data": b"Nice Tagline"}, + "/": {"code": 200, "data": b"Nice Tagline"}, + "/ContactUs": {"code": 200, "data": b"send us a message."}, + "/doesnotexists": {"code": 404, "data": b"Page Not Found"}, + "/logout": {"code": 200, "data": b"You have been logged out."}, + "/dashboard": { + "code": 401, + "data": b"You need to be logged in to access this resource", + }, + "/signup": {"code": 200, "data": b"Register your account."}, + "/signin": {"code": 200, "data": b"Sign in to your account."}, + "/Simulate500": {"code": 500, "data": b"Server Could Not Process This."}, + "/admin/user/": {"code": 403, "data": b"Forbidden"}, + "/confirm": {"code": 200, "data": b"Token not provided in URL Parameter"}, + "/confirm?confirmation_token=123": {"code": 200, "data": b"Bad Token Provided"}, } + def test_visitors(app, client): - for page in data2check_visitors: - res = client.get(page) - print("Testing %s",page) - assert res.status_code == data2check_visitors[page]["code"] - assert data2check_visitors[page]["data"] in res.data + for page in data2check_visitors: + res = client.get(page) + print("Testing %s", page) + assert res.status_code == data2check_visitors[page]["code"] + assert data2check_visitors[page]["data"] in res.data + def test_user_auth_flow(app, client): - res = client.post("/signup",data=dict( - email="test@example.com", - first_name="John", - password="testpassword", - ), follow_redirects=True) - - assert res.status_code == 200 - assert b"confirm your email" in res.data - - res = client.post("/signin",data=dict( - email="test@example.com", - password="testpassword"), - follow_redirects=True) - assert res.status_code == 200 - assert b"Please Confirm Your Email First." in res.data - - confirmation_token = ts.dumps("test@example.com",salt="email-confirm-key") - res = client.get("/confirm?confirmation_token={}".format(confirmation_token), - follow_redirects=True) - print(res.data) - assert b"Succesfully Verified" in res.data - - res = client.post("/signin",data=dict( - email="test@example.com", - password="testpassword"), - follow_redirects=True) - assert res.status_code == 200 - assert b"Hi John" in res.data - - res = client.get("/logout", follow_redirects=True) - assert res.status_code == 200 - assert b"You have been logged out." in res.data - - res = client.post("/signin",data=dict( - email="test@example.com", - password="testpassword"), - follow_redirects=True) - assert res.status_code == 200 - assert b"Hi John" in res.data - - res = client.get("/signin",follow_redirects=True) - assert res.status_code == 200 - assert b"Hi John" in res.data - - res = client.get("/signup",follow_redirects=True) - assert res.status_code == 200 - assert b"Hi John" in res.data - - res = client.get("/admin/user/") - assert res.status_code == 403 - - res = client.get("/logout") - res = client.post("/signin",data=dict( - email="testtest@example.com", - password="123456"),follow_redirects=True) - assert res.status_code == 200 - assert b"Incorrect Email" in res.data - res = client.post("/signin",data=dict( - email="test@example.com", - password="incorrectpassword"), - follow_redirects = True) - assert res.status_code == 200 - assert b"Incorrect Password" in res.data - - res = client.post("/signup",data=dict( - email="test@example.com", - first_name="John", - password="testpassword", - ), follow_redirects=True) - assert res.status_code == 200 - assert b"Oops! An account with that email already exists" in res.data
\ No newline at end of file + res = client.post( + "/signup", + data=dict( + email="test@example.com", + first_name="John", + password="testpassword", + ), + follow_redirects=True, + ) + + assert res.status_code == 200 + assert b"confirm your email" in res.data + + res = client.post( + "/signin", + data=dict(email="test@example.com", password="testpassword"), + follow_redirects=True, + ) + assert res.status_code == 200 + assert b"Please Confirm Your Email First." in res.data + + confirmation_token = ts.dumps("test@example.com", salt="email-confirm-key") + res = client.get( + "/confirm?confirmation_token={}".format(confirmation_token), + follow_redirects=True, + ) + print(res.data) + assert b"Succesfully Verified" in res.data + + res = client.post( + "/signin", + data=dict(email="test@example.com", password="testpassword"), + follow_redirects=True, + ) + assert res.status_code == 200 + assert b"Hi John" in res.data + + res = client.get("/logout", follow_redirects=True) + assert res.status_code == 200 + assert b"You have been logged out." in res.data + + res = client.post( + "/signin", + data=dict(email="test@example.com", password="testpassword"), + follow_redirects=True, + ) + assert res.status_code == 200 + assert b"Hi John" in res.data + + res = client.get("/signin", follow_redirects=True) + assert res.status_code == 200 + assert b"Hi John" in res.data + + res = client.get("/signup", follow_redirects=True) + assert res.status_code == 200 + assert b"Hi John" in res.data + + res = client.get("/admin/user/") + assert res.status_code == 403 + + res = client.get("/logout") + res = client.post( + "/signin", + data=dict(email="testtest@example.com", password="123456"), + follow_redirects=True, + ) + assert res.status_code == 200 + assert b"Incorrect Email" in res.data + res = client.post( + "/signin", + data=dict(email="test@example.com", password="incorrectpassword"), + follow_redirects=True, + ) + assert res.status_code == 200 + assert b"Incorrect Password" in res.data + + res = client.post( + "/signup", + data=dict( + email="test@example.com", + first_name="John", + password="testpassword", + ), + follow_redirects=True, + ) + assert res.status_code == 200 + assert b"Oops! An account with that email already exists" in res.data diff --git a/app/views/admin.py b/app/views/admin.py index b971a1a..7891e50 100644 --- a/app/views/admin.py +++ b/app/views/admin.py @@ -1,5 +1,5 @@ from app import app, login_manager, db -from flask import render_template, flash,url_for, redirect +from flask import render_template, flash, url_for, redirect import flask_login from app.models import User @@ -8,6 +8,7 @@ from flask_admin.contrib.sqla import ModelView admin = Admin(app, name="Admin", template_mode="bootstrap4") + class ModelView(ModelView): def is_accessible(self): try: @@ -17,4 +18,5 @@ class ModelView(ModelView): except AttributeError: return False -admin.add_view(ModelView(User, db.session))
\ No newline at end of file + +admin.add_view(ModelView(User, db.session)) diff --git a/app/views/auth.py b/app/views/auth.py index d6f02b8..2833479 100644 --- a/app/views/auth.py +++ b/app/views/auth.py @@ -1,6 +1,6 @@ from app import app, db, models, login_manager, oauth -from app.forms.app_forms import UserSignUp, UserLogIn -from flask import render_template, flash,url_for, redirect, request +from app.forms.app_forms import UserSignUp, UserLogIn +from flask import render_template, flash, url_for, redirect, request from app.misc_func import flash_errors, send, send_async import flask_login from sqlalchemy.exc import IntegrityError @@ -9,10 +9,11 @@ from itsdangerous.exc import BadSignature ts = URLSafeSerializer(app.config["SECRET_KEY"]) -@app.route("/signup", methods=['GET', 'POST']) + +@app.route("/signup", methods=["GET", "POST"]) def register_user(): if request.method == "GET" and flask_login.current_user.is_authenticated: - return redirect(url_for("user_dashboard")) + return redirect(url_for("user_dashboard")) form = UserSignUp() if form.validate_on_submit(): form.email.data = form.email.data.lower() @@ -22,31 +23,38 @@ def register_user(): email=form.email.data, confirmation=False, password=form.password.data, - ) + ) db.session.add(user) try: db.session.commit() except IntegrityError: flash("Oops! An account with that email already exists") - return render_template("auth/signup.html",form=form) - + return render_template("auth/signup.html", form=form) + subject = "Confirm Your Email" - confirmation_token = ts.dumps(user.email,salt="email-confirm-key") - confirmation_url = url_for("confirm_email",confirmation_token=confirmation_token,_external=True) - body_html = render_template("misc/email_confirm.html",confirmation_url=confirmation_url) - body = render_template("misc/email_confirm.txt",confirmation_url=confirmation_url) + confirmation_token = ts.dumps(user.email, salt="email-confirm-key") + confirmation_url = url_for( + "confirm_email", confirmation_token=confirmation_token, _external=True + ) + body_html = render_template( + "misc/email_confirm.html", confirmation_url=confirmation_url + ) + body = render_template( + "misc/email_confirm.txt", confirmation_url=confirmation_url + ) send(user.email, subject, body, body_html) - + flash("Please confirm your email before signing in..") return redirect(url_for("signin_user")) flash_errors(form) - return render_template("auth/signup.html",form=form) + return render_template("auth/signup.html", form=form) -@app.route("/signin", methods=['GET', 'POST']) + +@app.route("/signin", methods=["GET", "POST"]) def signin_user(): if request.method == "GET" and flask_login.current_user.is_authenticated: - return redirect(url_for("user_dashboard")) + return redirect(url_for("user_dashboard")) form = UserLogIn() if form.validate_on_submit(): form.email.data = form.email.data.lower() @@ -66,7 +74,8 @@ def signin_user(): flash("Incorrect Email") else: flash_errors(form) - return render_template("auth/signin.html",form=form) + return render_template("auth/signin.html", form=form) + @app.route("/login/with/google") def login_with_google(): @@ -85,7 +94,8 @@ def login_with_google_auth(): last_name=g_user["family_name"], email=g_user["email"].lower(), confirmation=True, - login_type="google") + login_type="google", + ) db.session.add(user) try: db.session.commit() @@ -98,7 +108,9 @@ def login_with_google_auth(): flask_login.login_user(user) return redirect(url_for("user_dashboard")) else: - flash("An account already exists for this email. Please use your password to log in.") + flash( + "An account already exists for this email. Please use your password to log in." + ) return redirect(url_for("signin_user")) else: return render_template( @@ -106,15 +118,18 @@ def login_with_google_auth(): message="To use sign-in with Google, you need a verified e-mail.", ) -@app.route("/confirm", methods=["GET","POST"]) + +@app.route("/confirm", methods=["GET", "POST"]) def confirm_email(): confirmation_token = request.args.get("confirmation_token") try: - email = ts.loads(confirmation_token, salt="email-confirm-key",max_age=86400) + email = ts.loads(confirmation_token, salt="email-confirm-key", max_age=86400) except TypeError: - return render_template("message.html",message="Token not provided in URL Parameter") + return render_template( + "message.html", message="Token not provided in URL Parameter" + ) except BadSignature: - return render_template("message.html",message="Bad Token Provided") + return render_template("message.html", message="Bad Token Provided") user = models.User.query.filter_by(email=email).first() print(email) user.confirmation = True @@ -122,16 +137,26 @@ def confirm_email(): flash("Email Has Been Succesfully Verified, You May Log In") return redirect(url_for("signin_user")) + @app.route("/dashboard") @flask_login.login_required def user_dashboard(): - return render_template("dashboard.html",user=flask_login.current_user) + return render_template("dashboard.html", user=flask_login.current_user) + -@app.route('/logout') +@app.route("/logout") def logout(): flask_login.logout_user() - return render_template("message.html",message="You have been logged out.") + return render_template("message.html", message="You have been logged out.") + @login_manager.unauthorized_handler def unauthorized(): - return render_template("message.html",message="You need to be logged in to access this resource", code=401), 401 + return ( + render_template( + "message.html", + message="You need to be logged in to access this resource", + code=401, + ), + 401, + ) diff --git a/app/views/error_pages.py b/app/views/error_pages.py index 5d995fc..1f066cc 100644 --- a/app/views/error_pages.py +++ b/app/views/error_pages.py @@ -1,18 +1,35 @@ from app import app from flask import render_template + @app.route("/Simulate500") def simulate_500(): - return 500 + return 500 + @app.errorhandler(403) def page_forbidden(e): - return render_template("message.html",code=403,message="Forbidden. You shall not pass"), 403 + return ( + render_template( + "message.html", code=403, message="Forbidden. You shall not pass" + ), + 403, + ) + @app.errorhandler(404) def page_not_found(e): - return render_template('message.html',code=404,message="Whoops! Page Not Found"), 404 + return ( + render_template("message.html", code=404, message="Whoops! Page Not Found"), + 404, + ) + @app.errorhandler(500) def page_server_error(e): - return render_template("message.html",code=500,message="Server Could Not Process This."), 500
\ No newline at end of file + return ( + render_template( + "message.html", code=500, message="Server Could Not Process This." + ), + 500, + ) diff --git a/app/views/main.py b/app/views/main.py index 003a46f..85df723 100644 --- a/app/views/main.py +++ b/app/views/main.py @@ -3,17 +3,20 @@ from app.forms.app_forms import MyForm from flask import render_template, flash from app.views import auth, error_pages, admin from app.misc_func import flash_errors + theme = "original" + @app.route("/") @app.route("/index") def index(): - return render_template("index.html") + return render_template("index.html") + -@app.route("/ContactUs", methods=['GET', 'POST']) +@app.route("/ContactUs", methods=["GET", "POST"]) def contact_us(): - form = MyForm() - if form.validate_on_submit(): - return "Wuhu" - flash_errors(form) - return render_template("contact.html",form=form)
\ No newline at end of file + form = MyForm() + if form.validate_on_submit(): + return "Wuhu" + flash_errors(form) + return render_template("contact.html", form=form) |