0
votes

I have a login page set using flask security, once the user login it redirect to admin page, now I want to create another login page for end user (Customers).

I have created a form that post email and password to flask. flask then check if the email and password exist in database, then login_user(user). the jquery suppose to load another page with current user id, but it return None.

Login.py

@login.route('/userLogin/log',  methods=['GET','POST'])
def Login():
     data = request.get_json()
     email = data["email"]
     passw = data["password"]



     user = UsersModel.query.filter_by(email=email).first()
     if user:
          if verify_password(user.password, passw):

              login_user(user)
              return  jsonify({'message':"done"})
     else: 
          return  jsonify({'message':gettext('Email and Password do not exist')}),422
          return render_template('front/cart.html')

@login.route('/homepage')
def homepage():
     id = "Hello" + str(current_user.get_id())
     return id

init.py

     app.config['SQLALCHEMY_DATABASE_URI'] ='mysql://root:@127.0.0.1/docwhere'
     app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
     #app.config['JWT_AUTH_USERNAME_KEY']='phoneNo'
     #app.config['WTF_CSRF_CHECK_DEFAULT']=False
     app.config['SECURITY_REGISTERABLE'] = False
     app.config['SECURITY_PASSWORD_SALT']='rreer##@'
     app.config['CKEDITOR_FILE_UPLOADER'] = '/admin/upload/'
     app.config['CKEDITOR_FILE_BROWSER']='/fm/index.html'
     app.config['UPLOADED_FILES_DEST'] = '/static/uploads'
     app.secret_key = 'EiEiO##$'
     app.config['FLASKFILEMANAGER_FILE_PATH'] = '/static/uploads'
     app.config['BABEL_DEFAULT_LOCALE']='en'
     app.path = '/static/uploads/'
     app.database_path = '/static/uploads/'
     db.init_app(app)
     class JSONEncoder(BaseEncoder):
          def default(self, o):
                if isinstance(o, _LazyString):
                     return text_type(o)

    return BaseEncoder.default(self, o)

 app.json_encoder = JSONEncoder
 babel = Babel(app)
 csrf = CSRFProtect(app)
 ckeditor = CKEditor(app)

 login_manager = LoginManager()
 login_manager.init_app(app)

 security = Security(app, user_datastore)

Update: Jquery submit button

  $('#login').click(function(e){
  e.preventDefault();
  url = "/userLogin/log "
  var csrf_token = "%% csrf_token() %%";
   var ob = {"email": $("#login-user").val(),
      "password": $('#login-pass').val()
    };      
  console.log(ob);
   $.ajax({
              url: url,
              type: 'post',
              headers: {
                  "Content-Type": "application/json",
                  "X-CSRFToken": csrf_token,
              },
              traditional: true,
              data: JSON.stringify(ob),

              success: function (message) {

                window.location.replace("%%  

           url_for('login.homepage')%%%%process_query_string(request)%%");

                },
        error: function (err) {

            error = "";
            $(".btn").removeAttr("disabled");
            for (key in err.responseJSON) {
                error +=  key + ":" + err.responseJSON[key] + "<br>";
            }
            if (error)
                $("#error").html("<p>" + error + "</p>");
            else
                $("#error").html("<p>" + err.responseText + "</p>");
            $("#error").show();
        }


     });
    return false;
     });
1
It looks like indents in your code are wrong. Can you paste your jQuery code?stasiekz
I just added the Jquery Code.mohammed joban

1 Answers

0
votes

What you are trying to do is fine. There isn't quite enough debugging info to know where the issue might be. It's possible that you are being stopped at CSRF time (I usually start w/o CSRF to make sure I get everything else working). In your code snippets - you are using Flask session auth (implicitly). You don't show your code where you are setting SECRET_KEY which is required in order for Flask to generate session cookies. I would start by using a browser debugger and look at the return from your /userLogin/log and make sure it is succeeding and returning a session cookie. Also - make sure that on your subsequent AJAX call - make sure the cookie is being sent. Note that just because you get a session cookie - doesn't mean you were logged in - so to help check that - add a @login_required to your endpoint that is referencing current_user.