开发者

login through XHR

开发者 https://www.devze.com 2023-02-20 09:02 出处:网络
i want to modify authentication behaviour so that the whole process can be done on the client side through xhr. so for example when i sumbit the login form login_handler would return a some json data

i want to modify authentication behaviour so that the whole process can be done on the client side through xhr. so for example when i sumbit the login form login_handler would return a some json data on success and error instead of loa开发者_开发技巧ding up new html pages or having a redirect of any sort. what should i look into to do this?


You should be able to write your own login controller by getting the identifier and calling the remember method.

First retrieve your user from the database, validate the password and then if everything is correct you can set the authentication cookie:

response.headers = request.environ['repoze.who.plugins']['main_identifier'].remember(request.environ, {'repoze.who.userid':user_name})

Also return a json dict from the controller at the end confirming success or not for UI purpose


I was trying to do the exact same thing with TG2. This is an extending the answer from amol. I am using it and it works fine for me.

@expose("json")
def login(self, login, password):

    identity = {"login": login,
                "password": password}

    # Authenticate the credentials
    username =  request.environ['repoze.who.plugins']['sqlauth'].authenticate(request.environ, identity)

    if username:
        print("Logged into " + username)
        # Remember this user
        response.headers = request.environ['repoze.who.plugins']['main_identifier'].remember(request.environ, {'repoze.who.userid':username})

        return {"status": True, "username": username}
    else:
        print("Could not authenticate")
        return {"status": False, "username": None}


If you extract the username and password and send them to a login script as parameters, you could then validate the user and return results accordingly.

$.ajax({
    url: "login.php",
    data: "username="+$("#username")+"&password="+$("#password"),
    method: 'GET',
    dataType: 'json',
    async: false,
    success: function(msg){
        if(msg.success){
            $("#content_area").html(msg.data);
        }
    }
});

Where the script would look something like this:

if( $_REQUEST['username'] == "correct_username" && $_REQUEST['password'] == "correct_password"){
     return json_encode( array( "success" => true, "data" => "stuff" ) );
}else{
     return json_encode( array( "success" => false ) );
}

I would suggest against this, though, since the process itself is riddled with security issues and vulnerabilities. If you can get away with posting credentials securely to a server and allowing the web server to handle the session, setting the cookie, and properly authenticating, then try to do so.

0

精彩评论

暂无评论...
验证码 换一张
取 消