there are two ways to reach your question solution:
- jwt :
first import your dependencies :
import jwt
from functools import wraps
from flask import session, request, abort, jsonify,
render_template, make_response, Blueprint, current_app
from flask_session import Session
import datetime
now you need a decorator called token_required() :
def token_required(Admin_Permission=False):
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
token = session.get("token")
if not token:
return jsonify({"message": "Token Is Missing"})
try:
data = jwt.decode(token, current_app.secret_key,
algorithms=["HS256"])
current_user = UserModel.find_by_id(data["user_id"])
if current_user is None:
return jsonify({"message": "Token Is Invalid"})
# for having some features Ignore this
if not (verify_admin(current_user=current_user, admin_Permission=Admin_Permission)):
return jsonify({"message": "ADMIN"})
except Exception as e:
return jsonify({"Error": e})
return func(current_user, *args, **kwargs)
return inner
return wrapper
your init.py file or your app.py file should be like this or at least set these configs :
from flask import Flask
from flask_session import Session
import uuid
from src.db import db
from src.Users.routes import blp as UserBlueprint
def create_app():
app = Flask(__name__)
app.config["SECRET_KEY"] = str(uuid.uuid4())
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///user.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config["SESSION_PERMANENT"] = False
app.secret_key = 'super secret key'
app.config['SESSION_TYPE'] = 'filesystem'
se = Session(app)
db.init_app(app)
app.register_blueprint(UserBlueprint)
return app
third your login route :
@blp.route('/login', methods=["GET", "POST"])
def Login():
if request.method == "POST":
auth = request.form
if auth:
user = UserModel.find_by_username(auth.get("username"))
if user and user.password == auth.get("password"):
token = jwt.encode({"user_id": user.id,
"exp": datetime.datetime.utcnow() +
datetime.timedelta(seconds=30)},
current_app.secret_key, algorithm="HS256")
session["token"] = token
return jsonify({"Current_Token": token})
return render_template("UserTemplates/signin.html")
@blp.route('/protected', methods=["GET", "POST"])
@token_required(Admin_Permission=True)
def protected(current_user):
print(current_user)
return f"This Link Is protected and you have the secret key. and this is current user {current_user.username} {current_user.email}"