如何在laravel 4.2中创建登录功能

时间:2014-12-02 13:12:39

标签: php session laravel

嗨,我对laravel很新。我被要求在Laravel中创建应用程序。最初,我正在使用登录模块。

基本要求

        
  • 在用户登录时将登录页面显示为登录页面。
  •     
  • 在提供用户凭据后,应设置会话,用户必须重定向到内部页面。
  •     
  • 成功登录后,除非已注销,否则不应显示登录页面。

因此,为了检查登录状态,我使用了filters.php中的过滤器,如下所示。

App::before(function($request)
{
    // $myApp Singleton object
    App::singleton('myApp', function(){
        $app = new stdClass;
        $app->title = "APD | Dealership Invoicing";
        if (Auth::check()) {
            $app->user = Auth::User();
            $app->isLogedin = TRUE;
        }
        else
        {
            $app->isLogedin = FALSE;
            $app->user = FALSE;
        }
        return $app;
    });
    $app = App::make('myApp');
    View::share('myApp', $app);
});

我基于"中发布的博客实现了上述代码。 http://heera.it/laravel-4-view-composer-master-layout#.VH280nvB25s"。

当用户从视图中单击“登录”按钮时,我将数据发送到控制器并检查数据库中的数据,如果数据正确,那么我将用户详细信息放入会话并重定向到内部页面。 / p>

控制器代码

public function validateLogin()
{
    $data = Input::all();
    $user_data = $this->validate_user_login($data);
    if(is_array($user_data) && !empty($user_data) && count($user_data) > 0)
    {
        /* The below conversion is used, because there seems to be difficulty in returning the Arrays from the Eloquent ORM.*/
        $user_array = (array)$user_data[0];
        Session::put('user_data', $user_array);            
        return Redirect::to('/jobs');
    }
}

Route.php代码

Route::get('/', function()
{
    #return View::make('login/login');
    return Redirect::to('/login');
});

Route::get('/login', 'UserController@login');

Route::post('/user/validate_login', 'UserController@validateLogin');

Route::group(array('before' => 'auth'), function()
{
    Route::get('/jobs', 'JobsController@jobs_list');
});

但我的问题是,重定向将我带回登录页面。

问题

        
  • 如何在登录后将登录状态设置为true?
  •     
  • 如何发起会话。我在控制器中设置会话密钥,是否足以验证用户会话?
  •     
  • 将来我必须为此开发REST API,我必须为Web和服务平台使用相同的应用程序。那么基于将控件放入过滤器会对API调用造成任何困难吗?
  •     
  • 我在哪里可以找到Auth类和Check功能" Auth :: Check()"?

1 个答案:

答案 0 :(得分:0)

我使用Jeffrey在“https://laracasts.com/series/laravel-from-scratch/episodes/15”中的教程实现了登录功能。这是简单的很好的解释。我用Jeffrey解释的方式更改了我编写的代码。它运作得很好。

我会提供简短的登录功能,我是在视频之后构建的。

路由器文件

Router.php
----------

/* This route is used to show the login page, when there is no session created.*/

Route::group(array('before' => 'login'), function()
{
    Route::get('login', 'UserController@create');
});

/* This below route is used when user is clicked on the login button in the log in page. */

Route::post('/user/store','UserController@store');

过滤文件

Filter.php
----------
App::before(function($request)
{
    // $myApp Singleton object
    App::singleton('myApp', function(){
        $app = new stdClass;
        $app->title = "APD | Dealership Invoicing";
        if (Auth::check()) {
            $app->user = Auth::User();
            $app->isLogedin = TRUE;
        }
        else
        {
            $app->isLogedin = FALSE;
            $app->user = FALSE;
        }
        return $app;
    });
$app = App::make('myApp');
View::share('myApp', $app);
});


App::after(function($request, $response)
{
    /* The below headers are used to restrict the browser to cache the pages.           
    */
    $response->headers->set("Cache-Control","no-cache,no-store, must-revalidate");
    $response->headers->set("Pragma", "no-cache"); //HTTP 1.0
    $response->headers->set("Expires"," Sat, 26 Jul 1986 05:00:00 GMT");
});

/*
| Authentication Filters    
|
| The following filters are used to verify that the user of the current
| session is logged into this application. The "basic" filter easily
| integrates HTTP Basic authentication for quick, simple checking.
|
*/

Route::filter('auth', function()
{
    if (Auth::guest())
    {
        if (Request::ajax())
        {
            /*return Response::make('Unauthorized', 401);*/
            return Response::make('common.unauthorized');
        }
        else
        {
            return Redirect::guest('login');
        }
    }
});

控制器文件

UserController.php
------------------
/**
 * The below function is used to show the login screen.
 */
public function create()
{
    /*
       This helps us to restrict the display of login page when clicked on browser back button after login.
    */

    $headers = array();
    $headers['Expires'] = 'Tue, 1 Jan 1980 00:00:00 GMT';
    $headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0';
    $headers['Pragma'] = 'no-cache';

    return Response::make(View::make('login.login'), 200, $headers);
    //return View::make('login.login');
}    

public function store()
{
    $input_data = Input::all();
    $credentials = array(
        'user_name' => htmlEncode(trim($input_data['user_name'])),
        'password' => $input_data['password'],
        'status' => 1
    );

    /* Here I am calling a function in the parent class. My UserController is extending the BaseController. The code will be available below. */

    $loginStatus = $this->validateUserLogin($credentials);

    if($loginStatus['status'] == 200)
    {
        $roleId = Auth::User()->role_id;
        $loggedInUserId = Auth::User()->id;
        $redirectPage = '/products';
        switch ($roleId)
        {
            case 'super':
                $redirectPage = '/manage_users';
                break;
            case 'admin':
                $redirectPage = '/products';
                break;                
        }
        return Redirect::to($redirectPage);
    }
    else
    {
        return Redirect::to('login')->with('status_data',$loginStatus);
    }
}

基本控制器文件

BaseController.php
------------------

protected function validateUserLogin($userData = '')
{
    $this->return_array = array();        
    if(!empty($userData))
    {
        if(Auth::attempt($userData))
        {
            $this->return_array['status'] = 200;
            $this->return_array['message'] = 'Login successfull.';
        }
        else
        {
            $userData['status'] = 0;
            if(Auth::validate($userData)) // This is to verify weather user is existed with status '0'. That means De-active user.
            {
                $this->return_array['status'] = 100;
                $this->return_array['message'] = 'Your account is deactivated, Please contact your admin.';
            }
            else
            {
                $this->return_array['status'] = 100;
                $this->return_array['message'] = 'Login failed. Please enter valid user name and password.';
            }
        }
    }
    else
    {
        $this->return_array['status'] = 100;
        $this->return_array['message'] = 'Unable to login please try after some time.';
    }

    return $this->return_array;
}