หน้าล็อกอิน Authentication Login manual บน Laravel 5


Authentication Login manual

1. Create controller cmd command Or custom create php file

สร้างไว้ที่ App\Http\Controller\AccountController.php
php artisan make:controller [Name]Controller
code: AccountCobtroller.php

<?php

namespace App\Http\Controllers;

use Input;
use Session;
use Auth;
use View;
use Hash;
use App\Account;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;

class AccountController extends Controller {

    public function __construct() {
        //        
    }
    
    /**********************************************************************/
    /*******************************Login**********************************/
    /**********************************************************************/
    
    public function getLogin() {

        if (Auth::check()) {
//            return Redirect::to('')->with('success', 'You are already logged in');
            return 'You are already logged in <a href="logout">Logout</a>';
        } else {
            return View::make('account.login');
        }
    }

    public function postLogin() {
        $dataAttempt = array(
            'name' => Input::get('name'),
            'password' => Input::get('password'),
            'active_account' => '1'
        );
//        dd(Auth::attempt($dataAttempt)); //dd ฟังก์ชั่นเอาไว้ตรวจสอบค่า return True และ False
        $rules = array(
            'name' => 'Required',
            'password' => 'Required'
        );

        $validator = Validator::make($dataAttempt, $rules);

        if ($validator->passes()) {
//                if(Auth::loginUsingId($dataAttempt['id')){ //Auth กรณี เป็นค่า id
            if (Auth::attempt($dataAttempt)) {
                return Redirect::to('login')->with('success', 'You have logged in successfully');
            } else {
                return Redirect::to('login')->withErrors(array('password' => 'Password invalid & Not active account for Administrator.'))->withInput(Input::except('password'));
            }
        }        
        return Redirect::to('login')->withErrors($validator)->withInput(Input::except('password'));
    }
    
    /**********************************************************************/
    /*******************************Register*******************************/
    /**********************************************************************/
    
    public function getRegister() {
        if(Auth::check()){
            return 'You are already logged in <a href="logout">Logout</a>';
        }else{
            return view('account.register');
        }        
    }

    public function postRegister() {
//      $data = Input::only(['name', 'email', 'passwd', 'passwd_confirmation', 'permission', 'active_account']);
        $data = Input::all(); //ดึงข้อมูลจะหน้า view มาจาก attribute name ของ <form></form>

        $rules = array(//สร้าง rule เพื่อตรวจสอบข้อมูลที่กรอกเข้ามา 
            'name' => 'required|min:6',
            'email' => 'required|email',
            'password' => 'required|min:6|confirmed',
            'password_confirmation' => 'required|min:6'
        );

        $vadidate = Validator::make($data, $rules);

        if ($vadidate->passes()) { //ตรวจสอบข้อมูลที่กรอกเข้ามา
            $accountModel = new Account(); //สร้าง object model ที่เชื่อมต่อ database 
            $validateAlready = $accountModel->getEmailAlready($data['email']); //เรียก method ใน model Account [App\Http\Account.php]
//            print_r(!$validateAlready->isEmpty()); //Debug ค่า ว่ามีข้อมูลหรือไม่
            if (!$validateAlready->isEmpty()) {
                if ($validateAlready[0]->email == $data['email']) { //ตรวจสอบค่าที่ดึงมาจาก db กับหน้า form เพื่อตรวจสอบว่า ชื่อนี้เคยถูกสมัครแล้วหรือยัง
                    Session::flash('message', 'Email Already to use.'); //ใช้งาน session เพื่อส่ง alarm แจ้งเตือนไปยังหน้า view
                    return Redirect::to('register');  //กลับคืนหน้า register
                }
            }

            $accountModel = new Account; //สร้าง object model เพื่อเก็บค่าก่อนเซฟลงฐานข้อมูล
            $accountModel->name = $data['name'];
            $accountModel->email = $data['email'];
            $accountModel->password = Hash::make($data['password']);
            $accountModel->permission = $data['permission'];
            $accountModel->active_account = $data['active_account'];
            $accountModel->save();

            if ($accountModel) {
                return redirect::to('login');
            } 
        }
        return Redirect::to('register')->withErrors($vadidate);
    }
    
    /**********************************************************************/
    /*******************************Logout*******************************/
    /**********************************************************************/
    
    public function getLogout(){
        Auth::logout();
        return Redirect::to('/')->with('success', 'You are logged out');
    }
}

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */


2. Create Model cmd command Or custom create php file

สร้างไว้ที่ App\Http\Account.php
php artisan make:model User
code : Account.php


<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;

class Account extends Model implements AuthenticatableContract {

    use Authenticatable;

    protected $table = 'users';
    protected $fillable = ['name', 'email', 'password', 'permission', 'active_account'];

//        protected $hidden = ['password', 'email']; //ไม่สามารถ query ออกมาได้
//        protected $guarded = array('id', 'password'); //

    public function getAuthPassword() {
        return $this->password;
    }   

    public function getEmailAlready($condition) {
//            print_r($condition.'\\');
        $query = Account::where('email', '=', $condition)->get();
        return $query;
    }

}
3. Create View 

3.1 Login View

สร้างไว้ที่ resources\views\account\login.blade.php
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

<br>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Login</div>
                <div class="panel-body">
                    <!--                                    @if ($error = $errors->first('password'))
                                                            <div class="alert alert-danger">
                                                              {{ $error }}
                                                            </div>
                                                        @endif-->
                    @if (count($errors) > 0)
                    <div class="alert alert-danger">
                        <strong>Whoops!</strong> There were some problems with your input.<br><br>
                        <ul>
                            @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                    @endif

                    <form class="form-horizontal" role="form" method="POST" action="{{ url('login') }}">
                        <input type="hidden" name="_token" value="{{ csrf_token() }}">

                        <div class="form-group">
                            <label class="col-md-4 control-label">Username</label>
                            <div class="col-md-6">
                                <input type="text" class="form-control" name="name" value="{{ old('username') }}">
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-md-4 control-label">Password</label>
                            <div class="col-md-6">
                                <input type="password" class="form-control" name="password">
                            </div>
                        </div>

                        <!--      <div class="form-group">
                                                                                <div class="col-md-6 col-md-offset-4">
                                                                                        <div class="checkbox">
                                                                                                <label>
                                                                                                    <input type="checkbox" name="remember"> Remember Me
                                                                                                </label>
                                                                                        </div>
                                                                                </div>
                                                                        </div>-->

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">Login</button>

                                <!--<a class="btn btn-link" href="{{ url('/password/email') }}">Forgot Your Password?</a>-->
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
3.2 Register View

สร้างไว้ที่ resources\views\account\register.blade.php
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

<br>
<div class="container-fluid">
 <div class="row">
  <div class="col-md-8 col-md-offset-2">
   <div class="panel panel-default">
    <div class="panel-heading">Register</div>
    <div class="panel-body">
                                        @if(Session::has('message'))
                                            <div class="alert alert-danger">
                                                {{ Session::get('message') }}
                                            </div>
                                        @endif
                                        
     @if (count($errors) > 0)
      <div class="alert alert-danger">
       <strong>Whoops!</strong> There were some problems with your input.<br><br>
       <ul>
        @foreach ($errors->all() as $error)
         <li>{{ $error }}</li>
        @endforeach
       </ul>
      </div>
     @endif

     <form class="form-horizontal" role="form" method="POST" action="{{ url('/register') }}">
      <input type="hidden" name="_token" value="{{ csrf_token() }}">
                                                <input type="hidden" name="permission" value="0">
                                                <input type="hidden" name="active_account" value="0">
                                                
      <div class="form-group">
       <label class="col-md-4 control-label">Name</label>
       <div class="col-md-6">
        <input type="text" class="form-control" name="name" value="{{ old('name') }}">
       </div>
      </div>

      <div class="form-group">
       <label class="col-md-4 control-label">E-Mail Address</label>
       <div class="col-md-6">
        <input type="text" class="form-control" name="email" value="{{ old('email') }}">
       </div>
      </div>

      <div class="form-group">
       <label class="col-md-4 control-label">Password</label>
       <div class="col-md-6">
        <input type="password" class="form-control" name="password">
       </div>
      </div>

      <div class="form-group">
       <label class="col-md-4 control-label">Confirm Password</label>
       <div class="col-md-6">
        <input type="password" class="form-control" name="password_confirmation">
       </div>
      </div>

      <div class="form-group">
       <div class="col-md-6 col-md-offset-4">
        <button type="submit" class="btn btn-primary">
         Register
        </button>
       </div>
      </div>
     </form>
    </div>
   </div>
  </div>
 </div>
</div>

4. Config route.php  App\Http\route.php

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
//Default
Route::get('/', 'WelcomeController@index');

//Authentication
Route::get('login', 'AccountController@getLogin');
Route::post('login', 'AccountController@postLogin');

Route::get('register', 'AccountController@getRegister');
Route::post('register', 'AccountController@postRegister');

Route::get('logout', 'AccountController@getLogout');

//Redirect Login Successfully จาก Auto Authentication
Route::get('home', 'AccountController@getLogin');
5. Config auth.php in folder \config

<?php

return [

 /*
 |--------------------------------------------------------------------------
 | Default Authentication Driver
 |--------------------------------------------------------------------------
 | Supported: "database", "eloquent" 
 */

// 'driver' => 'eloquent',
    'driver' => 'database',

 /*
 |--------------------------------------------------------------------------
 | Authentication Model
 |--------------------------------------------------------------------------
 */
 'model' => 'App\Account',

 /*
 |--------------------------------------------------------------------------
 | Authentication Table
 |--------------------------------------------------------------------------
 */
 'table' => 'users',

 /*
 |--------------------------------------------------------------------------
 | Password Reset Settings
 |--------------------------------------------------------------------------
 */
 'password' => [
  'email' => 'emails.password',
  'table' => 'password_resets',
  'expire' => 60,
 ],

];
6. Service http://localhost/laravelfresh/public/login


Thank : http://laravel.com/docs/5.0/eloquent



Comments

Popular posts from this blog

รู้จักกับ Breakpoints ใน Responsive Web Design

IS-IS & OSPF

RIP Routing Information Protocol