代码之家  ›  专栏  ›  技术社区  ›  Dennis

在codeigniter中通过ajax登录

  •  0
  • Dennis  · 技术社区  · 7 年前

    我的codeigniter解决方案中存在通过ajax登录的问题。 该解决方案是一个已经存在的代码库,它使用社区身份验证库作为身份验证部分。 我希望用户通过ajax登录,如果成功,让他登录并立即重定向到上一页,如果不成功,只显示一条错误消息。

    我在尝试了3个多小时来响应所有内容并尝试一步一步地调试之后感到很沮丧。

    这是我目前掌握的密码。

    我的后端控制器功能:

    public function logInWithAjax() {
    
    
            if( $this->input->is_ajax_request() )
            {
                // Allow this page to be an accepted login page
                $this->config->set_item('allowed_pages_for_login', ['backend/backend/logInWithAjax'] );
    
                // Make sure we aren't redirecting after a successful login
                $this->authentication->redirect_after_login = FALSE;
    
                // Do the login attempt
                $this->auth_data = $this->authentication->user_status( 0 );
    
                // Set user variables if successful login
                if( $this->auth_data )
                    $this->_set_user_variables();
    
                // Call the post auth hook
                $this->post_auth_hook();
    
                // Login attempt was successful
                if( $this->auth_data )
                {
                    echo json_encode([
                        'status'   => 1,
                        'user_id'  => $this->auth_user_id,
                        'username' => $this->auth_username,
                        'level'    => $this->auth_level,
                        'role'     => $this->auth_role,
                        'email'    => $this->auth_email
                    ]);
                }
    
                // Login attempt not successful
                else
                {
                    $this->tokens->name = 'login_token';
    
                    $on_hold = (
                        $this->authentication->on_hold === TRUE OR
                        $this->authentication->current_hold_status()
                    )
                        ? 1 : 0;
    
                    echo json_encode([
                        'status'  => 0,
                        'count'   => $this->authentication->login_errors_count,
                        'on_hold' => $on_hold,
                        'token'   => $this->tokens->token()
                    ]);
                }
            }
    
            // Show 404 if not AJAX
            else
            {
                show_404();
            }
        }
    

    问题是在loginWithAJAX函数中,它在user_status方法中将所有内容都传递到下面的代码行:

    // Verify that the form token and flash session token are the same
                if( $this->CI->tokens->token_check( 'token', TRUE ) )
    

    不管发生什么事,这个函数的结果总是错误的。 这个函数是正常的库代码,我将在下面粘贴它。

    /**
     * Check the token status with a provided token name, or "token" by default
     */
    public function token_check( $rename = '', $dump_jar_on_match = FALSE )
    {
        // If rename provided, check that token name
        $this->name = ( $rename == '' ) ? config_item('token_name') : $rename;
    
        // If no token jar contents, no reason to proceed
        if( ! empty( $this->jar ) )
        {
            // Set the posted_value variable
            if( $this->posted_value = $this->CI->input->post( $this->name ) )
            {
                // If the posted value matches one in the jar
                if( in_array( $this->posted_value, $this->jar ) )
                {
                    // Successful token match !
                    $this->match = TRUE;
    
                    // Dump all tokens ?
                    if( $dump_jar_on_match )
                    {
                        $this->jar = [];
    
                        $this->save_tokens_cookie();
                    }
    
                    // Just delete the matching token
                    else
                    {
                        // What token jar key was the matching token ?
                        $matching_key = array_search( $this->posted_value, $this->jar );
    
                        // Remove the matching token from the jar
                        unset( $this->jar[ $matching_key ] );
    
                        // Auto generate a new token
                        $this->generate_form_token();
                    }
    
                    if( $this->debug )
                    {
                        log_message( 'debug', count( $this->jar ) . '@token_check' );
                        log_message( 'debug', json_encode( $this->jar ) );
                    }
    
                    return TRUE;
                }
            }
        }
    
        return FALSE;
    }
    

    我注意到,$this->匹配项正确地设置为true。之后,$dump_jar_on_match的值是真的,因为我逐字传递这个值。但是,当我把一个return放在那里测试时,它拒绝进入if子句,它不返回任何内容。整个函数一直返回false。

    我的登录页面是一个使用form_open打开的简单表单,因此填写“token”隐藏字段。

    <div class="card-content">
    <div class="card-body">
        <?php
        echo form_open('', array('class' => 'form-horizontal loginform', 'id' => 'loginform', 'novalidate' => 'novalidate'));
        ?>
        <!--<form id="loginform" class="form-horizontal loginform" action="#" novalidate="novalidate">-->
            <fieldset class="form-group position-relative has-icon-left">
                <input type="text" class="form-control input-lg" id="user-name" name="login_string" placeholder="Gebruikersnaam of e-mail"
                       tabindex="1" required data-validation-required-message="Gelieve je gebruikersnaam of e-mail in te vullen aub.">
                <div class="form-control-position">
                    <i class="ft-user"></i>
                </div>
                <div class="help-block font-small-3"></div>
            </fieldset>
            <fieldset class="form-group position-relative has-icon-left">
                <input type="password" class="form-control input-lg" id="password" name="login_pass" placeholder="Wachtwoord"
                       tabindex="2" required data-validation-required-message="Gelieve je wachtwoord in te vullen aub.">
                <div class="form-control-position">
                    <i class="la la-key"></i>
                </div>
                <div class="help-block font-small-3"></div>
            </fieldset>
            <div class="form-group row">
                <!--<div class="col-md-6 col-12 text-center text-md-left">
                    <fieldset>
                        <input type="checkbox" id="remember-me" class="chk-remember">
                        <label for="remember-me"> Remember Me</label>
                    </fieldset>
                </div>-->
                <div class="col-md-12 col-12 text-center text-md-right"><a href="recover-password.html" class="card-link">Wachtwoord vergeten?</a></div>
            </div>
            <button type="submit" class="btn btn-danger btn-block btn-lg login-button"><i class="ft-unlock"></i> Log in</button>
            <div class="hidden loader-wrapper login-ajax-loader">
                <div class="loader-container">
                    <div class="ball-pulse-sync loader-green">
                        <div></div>
                        <div></div>
                        <div></div>
                    </div>
                </div>
            </div>
        </form>
    </div>
    

    我现在使用的javascript是:

    var getUrl = window.location;
    var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
    
    /*** START Log In Page JS ***/
    //Login Register Validation
    if($("form.loginform").attr("novalidate")!=undefined){
        $("input,select,textarea").not("[type=submit]").jqBootstrapValidation({
            submitSuccess: function ($form, event) {
                $('.login-button').addClass("hidden");
                $('.login-ajax-loader').removeClass("hidden");
                $.ajax({
                    type: 'POST',
                    url: baseUrl + '/backend/backend/logInWithAjax',
                    data: $form.serialize(),
                    success: function(data)
                    {
                        //TODO: de ajax moet checken of de log in kan. Zoja -> redirect naar gewoon log in systeem (met redirect URL mee te geven)
                        //Zonee -> toon de error class stuff
                        if (!data.result) {
                            $('.login-page-alert').removeClass("hidden");
                        } else {
                            $('.login-page-alert').addClass("hidden");
                        }
    
                        //console.log($form.serialize());
                        //console.log('submitted successfully!');
                        //console.log(data);
    
                        $('.login-button').removeClass("hidden");
                        $('.login-ajax-loader').addClass("hidden");
                    }
                });
    
                // will not trigger the default submission in favor of the ajax function
                event.preventDefault();
            }
        });
    }
    
    0 回复  |  直到 7 年前