2014-12-02 4 views
1

Привет, я довольно новичок в laravel. Меня попросили создать приложение в Laravel. Теперь изначально я работаю над модулем входа.Как создать логин в laravel 4.2

Основное требование

  • Показать страницу входа в систему в качестве целевой страницы, когда пользователь вошел в систему.
  • После предоставления учетных данных пользователя, сеанс должен установить и пользователь должен перенаправить на внутренние страницы.
  • После успешного входа в систему страница входа в систему не должна отображаться, если она не вышла из системы.

Для проверки состояния входа я использовал фильтры в 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».

И когда пользователь нажимает кнопку «Вход» из представления, я отправляю данные на контроллер и проверяю db для данных, и если данные верны, я помещаю данные пользователя в сеанс и перенаправляю на внутренние страницы.

Controller Код

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', '[email protected]'); 

Route::post('/user/validate_login', '[email protected]'); 

Route::group(array('before' => 'auth'), function() 
{ 
    Route::get('/jobs', '[email protected]_list'); 
}); 

Но моя проблема, перенаправление принимает меня обратно на страницу входа в систему.

Вопросы

  • Как установить вошедший в состоянии, как верно после регистрации?
  • Как я могу начать сеанс. Я установил ключ сеанса в контроллер, достаточно ли для проверки сеанса пользователя?
  • В будущем я должен разработать API REST для этого же, я должен использовать одно и то же приложение для платформ как для веб-приложений, так и для сервисов. Итак, основываясь на том, что включение элемента управления в фильтры затрудняет вызов API?
  • Где я могу найти функцию Auth и функцию Check в «Auth :: Check()»?

ответ

0

Я получил функциональность входа в систему, используя учебник Джеффри в «https://laracasts.com/series/laravel-from-scratch/episodes/15». Это просто отличное объяснение. Я изменил код, который был написан мной, как объяснил Джеффри. Он отлично работал.

Я дам краткую функциональность входа, которую я создал после видео.

Router Файл

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', '[email protected]'); 
}); 

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

Route::post('/user/store','[email protected]'); 

Фильтр файлов

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'); 
     } 
    } 
}); 

Controller File

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); 
    } 
} 

Base Файл контроллера

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; 
} 
+0

Я скопировал этот код, но Auth :: check() не работает для меня –

Смежные вопросы