mirror of
https://github.com/assenzostefano/class-website.git
synced 2025-06-06 00:39:12 +02:00
Simple login and registration in Flask with MongoDB
This commit is contained in:
107
app.py
107
app.py
@ -1,10 +1,16 @@
|
||||
from urllib.request import Request, urlopen
|
||||
from flask import Flask, render_template
|
||||
from flask import Flask, render_template, url_for, request, redirect, session, flash
|
||||
from flask_pymongo import PyMongo
|
||||
from dotenv import load_dotenv
|
||||
import bcrypt
|
||||
import urllib
|
||||
from pymongo import MongoClient
|
||||
import logging
|
||||
import json
|
||||
import sys
|
||||
import os
|
||||
|
||||
load_dotenv()
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(message)s",
|
||||
@ -15,8 +21,9 @@ logging.basicConfig(
|
||||
)
|
||||
|
||||
app = Flask(__name__)
|
||||
IMAGE_FOLDER = os.path.join('static', 'images')
|
||||
app.config['UPLOAD_FOLDER'] = IMAGE_FOLDER
|
||||
app.secret_key = "testing"
|
||||
PASSWORD_MONGODB = os.getenv('PASSWORD_MONGODB') #Password for MongoDB
|
||||
URL_MONGODB = os.getenv('URL_MONGODB') #URL for MongoDB
|
||||
|
||||
@app.route('/')
|
||||
def homepage():
|
||||
@ -37,6 +44,100 @@ def orario():
|
||||
day = str(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"])
|
||||
return render_template('orario/orario.html', data=dict, number=number, day=day)
|
||||
|
||||
# #connect to your Mongo DB database
|
||||
def MongoDB():
|
||||
client = MongoClient("mongodb+srv://elci:" + urllib.parse.quote_plus(PASSWORD_MONGODB) + URL_MONGODB)
|
||||
db = client.get_database('website-class')
|
||||
records = db.users
|
||||
return records
|
||||
|
||||
records = MongoDB()
|
||||
|
||||
|
||||
#assign URLs to have a particular route
|
||||
@app.route("/register", methods=['post', 'get'])
|
||||
def register():
|
||||
message = ''
|
||||
#if method post in index
|
||||
if "email" in session:
|
||||
return redirect(url_for("logged_in"))
|
||||
if request.method == "POST":
|
||||
user = request.form.get("fullname")
|
||||
email = request.form.get("email")
|
||||
password1 = request.form.get("password1")
|
||||
password2 = request.form.get("password2")
|
||||
#if found in database showcase that it's found
|
||||
user_found = records.find_one({"name": user})
|
||||
email_found = records.find_one({"email": email})
|
||||
if user_found:
|
||||
message = 'There already is a user by that name'
|
||||
return render_template('index.html', message=message)
|
||||
if email_found:
|
||||
message = 'This email already exists in database'
|
||||
return render_template('index.html', message=message)
|
||||
if password1 != password2:
|
||||
message = 'Passwords should match!'
|
||||
return render_template('index.html', message=message)
|
||||
else:
|
||||
#hash the password and encode it
|
||||
hashed = bcrypt.hashpw(password2.encode('utf-8'), bcrypt.gensalt())
|
||||
#assing them in a dictionary in key value pairs
|
||||
user_input = {'name': user, 'email': email, 'password': hashed}
|
||||
#insert it in the record collection
|
||||
records.insert_one(user_input)
|
||||
|
||||
#find the new created account and its email
|
||||
user_data = records.find_one({"email": email})
|
||||
new_email = user_data['email']
|
||||
#if registered redirect to logged in as the registered user
|
||||
return render_template('logged_in.html', email=new_email)
|
||||
return render_template('index.html')
|
||||
|
||||
@app.route("/login", methods=["POST", "GET"])
|
||||
def login():
|
||||
message = 'Please login to your account'
|
||||
if "email" in session:
|
||||
return redirect(url_for("logged_in"))
|
||||
|
||||
if request.method == "POST":
|
||||
email = request.form.get("email")
|
||||
password = request.form.get("password")
|
||||
|
||||
#check if email exists in database
|
||||
email_found = records.find_one({"email": email})
|
||||
if email_found:
|
||||
email_val = email_found['email']
|
||||
passwordcheck = email_found['password']
|
||||
#encode the password and check if it matches
|
||||
if bcrypt.checkpw(password.encode('utf-8'), passwordcheck):
|
||||
session["email"] = email_val
|
||||
return redirect(url_for('logged_in'))
|
||||
else:
|
||||
if "email" in session:
|
||||
return redirect(url_for("logged_in"))
|
||||
message = 'Wrong password'
|
||||
return render_template('login.html', message=message)
|
||||
else:
|
||||
message = 'Email not found'
|
||||
return render_template('login.html', message=message)
|
||||
return render_template('login.html', message=message)
|
||||
|
||||
@app.route('/logged_in')
|
||||
def logged_in():
|
||||
if "email" in session:
|
||||
email = session["email"]
|
||||
return render_template('logged_in.html', email=email)
|
||||
else:
|
||||
return redirect(url_for("login"))
|
||||
|
||||
@app.route("/logout", methods=["POST", "GET"])
|
||||
def logout():
|
||||
if "email" in session:
|
||||
session.pop("email", None)
|
||||
return render_template("signout.html")
|
||||
else:
|
||||
return render_template('index.html')
|
||||
|
||||
if __name__ == '__main__':
|
||||
logging.info("Web server started!")
|
||||
app.run(port=4999, debug=True)
|
Reference in New Issue
Block a user