Simple login and registration in Flask with MongoDB
This commit is contained in:
parent
e856c71eff
commit
3fe56893b6
107
app.py
107
app.py
|
@ -1,10 +1,16 @@
|
||||||
from urllib.request import Request, urlopen
|
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 logging
|
||||||
import json
|
import json
|
||||||
import sys
|
import sys
|
||||||
import os
|
import os
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
level=logging.INFO,
|
level=logging.INFO,
|
||||||
format="%(asctime)s [%(levelname)s] %(message)s",
|
format="%(asctime)s [%(levelname)s] %(message)s",
|
||||||
|
@ -15,8 +21,9 @@ logging.basicConfig(
|
||||||
)
|
)
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
IMAGE_FOLDER = os.path.join('static', 'images')
|
app.secret_key = "testing"
|
||||||
app.config['UPLOAD_FOLDER'] = IMAGE_FOLDER
|
PASSWORD_MONGODB = os.getenv('PASSWORD_MONGODB') #Password for MongoDB
|
||||||
|
URL_MONGODB = os.getenv('URL_MONGODB') #URL for MongoDB
|
||||||
|
|
||||||
@app.route('/')
|
@app.route('/')
|
||||||
def homepage():
|
def homepage():
|
||||||
|
@ -37,6 +44,100 @@ def orario():
|
||||||
day = str(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"])
|
day = str(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"])
|
||||||
return render_template('orario/orario.html', data=dict, number=number, day=day)
|
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__':
|
if __name__ == '__main__':
|
||||||
logging.info("Web server started!")
|
logging.info("Web server started!")
|
||||||
app.run(port=4999, debug=True)
|
app.run(port=4999, debug=True)
|
|
@ -71,5 +71,4 @@ def send_xlsx():
|
||||||
update_time_school()
|
update_time_school()
|
||||||
os.remove(f"{DOWNLOAD_FOLDER}/school_time.xlsx") # Delete file
|
os.remove(f"{DOWNLOAD_FOLDER}/school_time.xlsx") # Delete file
|
||||||
recheck_email()
|
recheck_email()
|
||||||
|
|
||||||
check_email()
|
check_email()
|
|
@ -0,0 +1,35 @@
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta charset="utf-8">
|
||||||
|
|
||||||
|
|
||||||
|
<title>{% block title %}{%endblock %}</title>
|
||||||
|
|
||||||
|
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
|
||||||
|
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<nav class="navbar navbar-light" style="background-color: #e3f2fd;">
|
||||||
|
<a class="navbar-brand" href="#">Registration Form</a>
|
||||||
|
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
|
||||||
|
<span class="navbar-toggler-icon"></span>
|
||||||
|
</button>
|
||||||
|
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
|
||||||
|
<div class="navbar-nav">
|
||||||
|
<a class="nav-item nav-link active" href="/">Register <span class="sr-only">(current)</span></a>
|
||||||
|
<a class="nav-item nav-link" href="/login">Login</a>
|
||||||
|
<a class="nav-item nav-link" href="/logout">Logout</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
|
||||||
|
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
|
||||||
|
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
|
||||||
|
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
|
||||||
|
|
||||||
|
{% block content %}{% endblock %}
|
||||||
|
</body>
|
||||||
|
</html>
|
|
@ -1,13 +1,40 @@
|
||||||
<!DOCTYPE html>
|
{% extends "base.html" %}
|
||||||
<html lang="en">
|
{% block title %}Register System{% endblock %}
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8">
|
|
||||||
<title>2 Elci - Homepage</title>
|
|
||||||
<meta name="viewport" content="width=device-width" >
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
|
|
||||||
<p>Hello World!</p>
|
{% block content %}
|
||||||
|
|
||||||
</body>
|
{% if message %}
|
||||||
</html>
|
<div class="alert alert-secondary" role="alert">
|
||||||
|
<p>{{ message }}</p>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<form action="" method="post">
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="Fullname">Full name</label>
|
||||||
|
<input name="fullname" class="form-control" id="inputFullName" aria-describedby="emailHelp" placeholder="Enter full name">
|
||||||
|
<small id="fullName" class="form-text text-muted">Please enter your full name(First name and Last name)</small>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="InputEmail">Email address</label>
|
||||||
|
<input name="email" class="form-control" id="InputEmail" placeholder="Enter email">
|
||||||
|
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="InputPassword">Password</label>
|
||||||
|
<input type="password" name="password1" class="form-control" id="InputPassword" placeholder="Password">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="InputPassword2">Repeat Password</label>
|
||||||
|
<input type="password" name="password2" class="form-control" id="InputPassword2" placeholder="Repeat Password">
|
||||||
|
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="btn btn-primary">Submit</button>
|
||||||
|
|
||||||
|
|
||||||
|
</form>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
{% endblock %}
|
|
@ -0,0 +1,7 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
{% block title %}Youv'e logged in {% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<p>Hello You have Logged in as {{ email }}</p>
|
||||||
|
|
||||||
|
{% endblock %}
|
|
@ -0,0 +1,24 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
{% block title %}Login System{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
|
||||||
|
{% if message %}
|
||||||
|
<div class="alert alert-secondary" role="alert">
|
||||||
|
<p>{{ message }}</p>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<form action="" method="post">
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="InputEmail">Email address</label>
|
||||||
|
<input name="email" class="form-control" id="InputEmail" placeholder="Enter email">
|
||||||
|
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="InputPassword">Password</label>
|
||||||
|
<input type="password" name="password" class="form-control" id="InputPassword" placeholder="Password">
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="btn btn-primary">Submit</button>
|
||||||
|
</form>
|
||||||
|
{% endblock %}
|
|
@ -0,0 +1,7 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
{% block title %}Register System{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h1>You are signed out!</h1>
|
||||||
|
|
||||||
|
{% endblock %}
|
|
@ -0,0 +1,54 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<title>Login with mongodb flask</title>
|
||||||
|
|
||||||
|
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||||
|
<link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
|
||||||
|
<link href="../static/signup.css" rel="stylesheet">
|
||||||
|
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<div class="container">
|
||||||
|
<div class="header">
|
||||||
|
<nav>
|
||||||
|
<ul class="nav nav-pills pull-right">
|
||||||
|
<li role="presentation" ><a href="/main">Home</a></li>
|
||||||
|
<li role="presentation"><a href="/signin">Sign In</a></li>
|
||||||
|
<li role="presentation" class="active"><a href="#">Sign Up</a></li>
|
||||||
|
</ul>
|
||||||
|
</nav>
|
||||||
|
<h3 class="text-muted">Login with mongodb flask</h3>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="jumbotron">
|
||||||
|
<h1>Signup</h1>
|
||||||
|
{% with messages = get_flashed_messages() %}
|
||||||
|
{% if messages %}
|
||||||
|
<ul class=flashes>
|
||||||
|
{% for message in messages %}
|
||||||
|
<li>{{ message }}</li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
{% endif %}
|
||||||
|
{% endwith %}
|
||||||
|
<form class="form-signin" action="/signup" method="post">
|
||||||
|
<label for="inputName" class="sr-only">Username</label>
|
||||||
|
<input type="name" name="username" id="inputName" class="form-control" placeholder="Username" required autofocus>
|
||||||
|
<label for="inputEmail" class="sr-only">Email address</label>
|
||||||
|
<input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
|
||||||
|
<label for="inputPassword" class="sr-only">Password</label>
|
||||||
|
<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>
|
||||||
|
<button id="btnSignUp" class="btn btn-lg btn-primary btn-block" onclick = 'this.form.submit();' type="button">Signup</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<footer class="footer">
|
||||||
|
<p>© 2017</p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
Loading…
Reference in New Issue