【问题标题】:Kohana - AJAX - Authenticate to a model with no databaseKohana - AJAX - 对没有数据库的模型进行身份验证
【发布时间】:2012-12-07 01:18:26
【问题描述】:

好吧,我要疯了。这似乎应该如此简单,也许它只是盯着我的脸而我没有看到它。我有在 Kohana 3.2 中创建登录页面的具体说明,该页面使用 AJAX 处理表单并使用纯文本用户名和密码对模型进行身份验证。这只是一个明显设计为让我难堪的练习,嘿嘿。所以不,安全在这里不是问题。没有数据库,也没有可被利用的内容。

我目前的登录表单仅使用身份验证,使用身份验证配置文件中的默认“文件”驱动程序。

application/config/auth.php

  return array(

    'driver'       => 'file',
    'hash_method'  => 'sha256',
    'hash_key'     => 'testkey',
    'lifetime'     => 30000,
    'session_type' => Session::$default,
    'session_key'  => 'auth_user',

    // Username/password combinations for the Auth File driver
    'users' => array(
                    'admin' => 'be4039381cf04bb778de68e6520a77c7d8b5e6d146f932f0759e681a46bfc120',
                    ),

);

但是,我一直在搜索和搜索如何更改此以使用 AJAX 提交和授权的示例。我在 is_ajax 和 Controller_Templates 等的海洋中游泳。我已经使用 Kohana 大约 28 小时了。有人能帮我解决这个问题吗?

application/views/user/login.php

<?= Form::open('user/login',array('class'=>'form-signin')); ?>
<h2 class="form-signin-heading">Sign in</h2>
<?php if (isset($message)) : ?>
    <h3 class="message">
        <?= $message; ?>
    </h3>
<?php endif; ?>

<!-- Username Field -->
<?php $uArray = array('type'=>'text','class'=>'input-block-level','placeholder'=>'Username = admin'); ?>
<?= Form::input('username',NULL,$uArray); ?>

<!-- Password Field -->
<?php $pwArray = array('class'=>'input-block-level', 'placeholder'=>'Password = password'); ?>
<?= Form::password('password',NULL,$pwArray); ?>

<!-- Checkbox -->
<?= Form::checkbox('remember','remember'); ?>
<?= Form::label('remember', 'Remember Me',array('class'=>'checkbox','label'=>'Remember')); ?>
<br />

<!-- Submit Buton -->
<?= Form::submit('login', 'Login',array('class'=>'btn btn-large btn-primary')); ?>

<?= Form::close(); ?>

application/classes/controller/user.php

<?php defined('SYSPATH') or die('No direct script access.');

class Controller_User extends Controller_Template {

    public function action_index()
    {
        $this->template->content = View::factory('user/index');
        // Load the user information
        $user = Auth::instance()->get_user();
        // if a user is not logged in, redirect to login page
        if ($user)
        {
            $this->template->content = View::factory('user/welcome')
            ->bind('user', $user);
        }
    }

    public function action_login()
    {
        // if a user is already logged in then redirect them to the index.
        if (Auth::instance()->logged_in())
            {
                // User is logged in, continue on
                Request::current()->redirect('user/index');
            }

        $this->template->content = View::factory('user/login')
            ->bind('message', $message);

        if (HTTP_Request::POST == $this->request->method())
        {
            // Attempt to login user
            $remember = array_key_exists('remember', $this->request->post()) ? (bool) $this->request->post('remember') : FALSE;
            $user = Auth::instance()->login($this->request->post('username'), $this->request->post('password'), $remember);

            // If successful, redirect user
            if ($user)
            {
                $this->template->content = View::factory('user/welcome')
                ->bind('user', $user);
            }
            else
            {
                $message = 'Login failed';
            }
        }
    }

    public function action_logout()
    {
        // Log user out
        Auth::instance()->logout();

        // Redirect to login page
        Request::current()->redirect('user/login');
    }

}

application/classes/model/user.php

<?php defined('SYSPATH') OR die('No Direct Script Access');

我对 Kohana 不够熟悉,甚至不确定要在模型中添加什么。现在 Auth 正在使用它自己的文件来存储用户数组。但我的指示是让模型存储用户名和密码。

提前感谢您的任何帮助!

【问题讨论】:

  • 并不是说这条评论对你的情况有多大帮助,但请尽量不要这样做: $pwArray 总是声明 php:
  • @KaiQing 你当然是对的。这是一个古老而坏的习惯。已经在我的代码中修复了。

标签: php ajax forms authentication kohana


【解决方案1】:

我正在使用这个答案来尝试用代码作为评论进行交流,而不一定是作为答案。也就是说:

这对你有用吗?

public function action_index()
    {
        $this->template->content = View::factory('user/index')
            ->bind('user', $user);

$user 没有在那里定义,所以我认为这会导致错误。 另外,我不确定您的用户模型在哪里发挥作用。如果没有与用户绑定的数据库,那么 kohana 不会像使用 ORM 时那样依赖用户模型。那么,如果模型实例只会在页面更改时被丢弃,为什么还需要在模型实例中存储任何东西呢?假设这意味着在登录时您说$user = new User_Model(); 之类的内容,然后分配私有变量或其他内容。

还有这个“但我的指示是让模型存储用户名和密码。”此人请求的目标是什么?教你?还是在登录后提供用户信息?

【讨论】:

  • 很公平,现在是意图问题。让用户模型具有这些可用变量的目标是什么?我问因为它是否就像会话一样,那么您可以扩展身份验证或在登录时让您的用户模型自动加载。
  • 是的,确实有效。但是,您提出了一个很好的观点,如果甚至没有定义用户,则无需在此处绑定用户,并且如果用户未登录因此未定义,我唯一一次发送用户。我已修改该行以删除绑定方法。请求的原因也是我认为有点测试/教学的时刻。所以我正在努力遵守。实际上,我对 Kohana 框架可用的文档和示例感到失望。当我能看到一个如何完成某事的示例,然后拆开各个部分,看看会产生什么影响时,我学得最好。
  • 是的,就示例而言,kohana 文档可能没有太大帮助,但有很多示例可用。我是通过示例学习的,而不是通过阅读他们的文档。但是您仍然没有明确目标是什么。用户模型的最终目标是什么?
  • 哦,对不起。我认为使用模型的最终目标实际上只是为了展示我认为的完整 MVC 用法。如果我使用 ORM 和 MySQL,此时对我来说会更容易。
【解决方案2】:

好吧,我昨晚想通了。我将回答我自己的问题以供将来参考。虽然我仍在使用 Auth 来处理用户会话,但我没有对其进行身份验证。我正在使用

Auth::instance()->force_login($username)

按照要求对模型进行身份验证后强制登录。

首先我更改了登录页面以简化并添加一些 AJAX。

/application/views/user/login.php

<form id="loginForm" class="form-signin">

<h2 class="form-signin-heading">Sign in</h2>

<div class="message" id="message"></div>

<!-- Username Field -->
<input type="text" id="username" class="input-block-level" placeholder="Username = admin" />

<!-- Password Field -->
<input type="password" id="password" class="input-block-level" placeholder="Password = password" />

<!-- Submit Buton -->
<input type="submit" id="login" value="Sign In" class="btn btn-large btn-primary" />

</form>

<script type="text/javascript">
$(document).ready(function() {

    $("#login").click(function() {
        var action = $("#loginForm").attr('action');
        var form_data = {
            username: $("#username").val(),
            password: $("#password").val(),
            is_ajax: 1
        };

        $.ajax({
            type: "POST",
            url: '/user/checkLogin',
            data: form_data,
            success: function(response)
            {
                if(response == 'success')
                    window.location.replace('/user');
                else
                    $("#message").html("<div class='alert alert-error'><button type='button' class='close' data-dismiss='alert'>×</button>Invalid username and/or password.</div>");    
            }
        });
        return false;
    });

});
</script>

然后我添加了一个带有明文用户名和密码的简单模型。 (同样,这是概念上的证明,绝不是一种安全的身份验证方式)。

/application/classes/model/user.php

<?php defined('SYSPATH') OR die('No Direct Script Access');

Class Model_User extends Model
{
    public function checkLogin($username, $password)
    {
        // These are the username and password to verify against
        $user = "admin";
        $pass = "password";

        // Compare and return boolean
        if ($username === $user && $password === $pass){
            return TRUE;
        } else {
            return FALSE;
        }
    }
}

然后我将 checkLogin 操作添加到用户控制器(因为这是我在登录页面上从 AJAX 调用的操作)来处理登录。

/application/classes/controller/user.php

<?php defined('SYSPATH') or die('No direct script access.');

class Controller_User extends Controller_Template {

    public function action_index()
    {
        // Load the user information
        $user = Auth::instance()->get_user();

        // if a user is logged in, redirect to welcome page
        if ($user){
            $this->template->content = View::factory('user/welcome')
            ->bind('user', $user);
        } else {
            $this->template->content = View::factory('user/index');
        }
    }

    public function action_checkLogin()
    {
        //disable auto rendering if requested using ajax
        if($this->request->is_ajax()){
            $this->auto_render = FALSE;
        }

        // Check for post
        if($this->request->post()){
            // Instantiate the Model Object
            $user = new Model_User();

            // Get post variables
            $username = $this->request->post('username');
            $password = $this->request->post('password');

            // Check the login
            if($check = $user->checkLogin($username,$password)){
                // Login the user using auth
                $user = Auth::instance()->force_login($username);
                // Respond with a success
                echo 'success';
            } else {
                // Respond with a fail
                return "fail";
            }
        }
    }

    public function action_login()
    {
        // Load the user information
        $user = Auth::instance()->get_user();

        // if a user is logged in, redirect to welcome page
        if ($user){
            $this->template->content = View::factory('user/welcome')
            ->bind('user', $user);
        } else {
            $this->template->content = View::factory('user/login')
            ->bind('message', $message);
        }
    }

    public function action_logout()
    {
        // Log user out
        Auth::instance()->logout();

        // Redirect to login page
        Request::current()->redirect('user/login');
    }

}

现在我有一个漂亮的简单登录页面,它使用 Kohana 框架中的 AJAX 对模型进行身份验证。这不是火箭手术,但有趣的是弄清楚这些不同的框架是如何运作的。希望它对将来的人有所帮助。干杯!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 2012-10-05
    • 2013-06-27
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多