2014-12-02 6 views
1

안녕하세요, 저는 꽤 재미있습니다. 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"에 게시 된 블로그를 기반으로 위의 코드를 구현했습니다.

사용자가보기에서 로그인 버튼을 클릭하면 컨트롤러에 데이터를 보내고 데이터를 확인하고 데이터가 올바른지 확인한 후 세션에 사용자 세부 정보를 입력하고 내부 페이지로 리디렉션합니다.

컨트롤러 코드

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를 개발해야하는데 웹과 서비스 플랫폼 모두에 동일한 애플리케이션을 사용해야합니다. 따라서 컨트롤을 필터에두면 API 호출에 어려움이 있습니까?
  • "Auth :: Check()"에서 Auth 클래스 및 Check 함수는 어디에서 찾을 수 있습니까?

답변

0

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

컨트롤러

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

나는이 코드를 coppied했지만 Auth :: check()가 작동하지 않습니다. –

관련 문제