-1

I have created separate Blueprints for separate modules of my project. I am having trouble with @login_required decorator. I read a very similar question but it couldn't help me.

The model.py file is as following:

from application import db
from datetime import datetime



class User(db.Model):
    uid = db.Column(db.Integer, primary_key=True)
    AccountName=db.Column(db.String(60))
    UserID=db.Column(db.String(60))
    firstName = db.Column(db.String(60))
    lastName = db.Column(db.String(60))
    email = db.Column(db.String(60), unique=True)
    UserPassword = db.Column(db.String(60))
    DateCreated = db.Column(db.DateTime())
    DateUpdated = db.Column(db.DateTime())
    UserType=db.Column(db.Enum('Owner', 'Admin', 'Operator'))
    is_verified = db.Column(db.Boolean)

    @property
    def is_authenticated(self):
        return True

    @property
    def is_active(self):
        return True

    @property
    def is_anonymous(self):
        return False

    def get_id(self):
        return str(self.uid)  # python 3


    def __init__(self, firstName, lastName, email, UserPassword, DateCreated, AccountName, UserType, UserID, DateUpdated):
        self.firstName = firstName
        self.lastName = lastName
        self.email = email
        self.UserPassword = UserPassword
        self.DateCreated = DateCreated
        self.is_verified = False
        self.AccountName = AccountName
        self.UserType = UserType
        self.UserID = UserID
        self.DateUpdated=DateUpdated

    @classmethod
    def get(cls, uid):  #
        return cls.get(uid)

    def __repr__(self):
        return "\n"+str(self.uid)+"\t"+self.firstName+"\t"+self.lastName+"\t"+self.email+"\t"+str(self.is_verified)+"\t"+self.AccountName+"\t"+self.UserType+"\t"+self.UserID +"\n"

application.py is as:

from flask import Flask, render_template, request, Blueprint
from flask_mail import Mail
from application import db, application
from application.forms import EnterDBInfo, RetrieveDBInfo

application = Flask(__name__)
application.debug = True

# Flask Login
login_manager = LoginManager()
login_manager.init_app(application)

application.secret_key = 'njzJTsRxA/pd3k4PXiHvMay/BeBseeUAG15GLA/t'



@application.route('/', methods=['GET', 'POST'])
@application.route('/index', methods=['GET', 'POST'])
def index():
    #returning someTemplate()


if __name__ == '__main__':
    application.run(host='0.0.0.0')

the init.py is as:

from flask import Flask, Blueprint
from flask_sqlalchemy import SQLAlchemy


application = Flask(__name__)
application.config.from_object('config')
db = SQLAlchemy(application)

from user.user_management import mod as userModule
application.register_blueprint(userModule)

from site_license.license import modLicense as licenseModule
application.register_blueprint(licenseModule)

and finally in the blueprint where the problem is, I have following:

from datetime import datetime
from flask import Flask, Blueprint, request, jsonify, flash, g, url_for, abort, session, redirect
from application import db
from application.models import User
from application.ErrorCodes import ErrorCode
from flask_login import login_user, logout_user, LoginManager, login_required, current_user, wraps


application = Flask(__name__)
application.debug = True

mod = Blueprint('user', __name__, url_prefix='/user')

# Flask Login
login_manager = LoginManager()
login_manager.init_app(application)

application.secret_key = 'njzJTsRxA/pd3k4PXiHvMay/BeBseeUAG15GLA/t'


@login_manager.user_loader
def load_user(uid):
    return User.get(uid)

@mod.route('/login', methods=['GET', 'POST'])
def login():
    if request.headers['Content-Type'] == 'application/json':
        try:
            login = request.json
            UserID = login["UserID"]
            UserPassword = login["UserPassword"]
            AccountName = login["AccountName"]
            registered_user = User.query.filter_by(UserID=UserID, UserPassword=UserPassword, AccountName=AccountName).first()
            print(registered_user)
            if registered_user is None:
                code = ErrorCode().Invalid_Credentials_CODE
                msg = ErrorCode().Invalid_Credentials_MSG
            else:
                login_user(registered_user, remember=True)

                UserType = registered_user.UserType
                flash("Successfully logged in")
                code = ErrorCode().Success_CODE
                msg = ErrorCode().Success_MSG
                SessionID = registered_user.get_id()

        except:
            code = ErrorCode().Invalid_JSON_CODE
            msg = ErrorCode().Invalid_JSON_MSG
    else:
        code = ErrorCode().Wrong_Content_CODE
        msg = ErrorCode().Wrong_Content_MSG
    if code==1:
        return jsonify({"ResponseValue": code, "ResponseText": msg, "SessionID":SessionID, "UserType":UserType})
    else:
        return jsonify({"ResponseValue": code, "ResponseText": msg})


@mod.route('/logout', methods=['GET', 'POST'])
@login_required
def logout():
    # print(g.user)
    logout_user()
    # session['logged_in'] = False
    code = 1
    success = "Success"
    # return "\n\nSuccessfully logged out\n\n"
    return jsonify({"code": code, "msg": success})

What is it that I'm missing here?

Community
  • 1
  • 1
Abhishek
  • 1
  • 1
  • 7

1 Answers1

0

You have two different applications: the one in __init__ and the one in your blueprint module. This is wrong. You're registering Flask-Login with the second application, but that application is never run (and shouldn't be).

Remove the following from your blueprint module.

application = Flask(__name__)
application.debug = True
login_manager.init_app(application)
application.secret_key = 'njzJTsRxA/pd3k4PXiHvMay/BeBseeUAG15GLA/t'

Instead, import login_manager in __init__ and register it on the real application.

from my_app.my_blueprint import login_manager

login_manager.init_app(application)

Or define the login manager in __init__ and import login_required where needed (preferable).

davidism
  • 121,510
  • 29
  • 395
  • 339