Laravel 5 Https 적용하기

  • 작업 조건
    • php
    • laravel 5.3
  • 작업 내용
    • laravel에 https route 적용하기
  • 작업 과정
    • 1. 미들웨어 ForceSSL를 생성합니다.
      php artisan make:middleware ForceSSL
    • 2. 미들웨어의 형태는 다음과 같습니다.
    • <?php
      
      namespace App\Http\Middleware;
      
      use Closure;
      
      class ForceSSL
      {
      
          public function handle($request, Closure $next)
          {
      
              if (!$request->secure()) {
                  return redirect()->secure($request->getRequestUri());
              }
      
              return $next($request);
          }
      }
    • 로컬 개발 및 프로덕션 모두에 대해 HTTPS설정을 사용하므로 환경을 기반으로 필터링 할 필요가 없습니다.

      다음을 App\kernel.php에 추가하면 SSL을 강제 적용할 경로 그룹을 선택하고 선택할 수 있습니다.

    •     protected $routeMiddleware = [
          'auth' => \App\Http\Middleware\Authenticate::class,
          'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
          'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
          'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
          'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
          'forceSSL' => \App\Http\Middleware\ForceSSL::class,
      ];
  • 작업 과정 중 참고사항
  • 작업 중 발생한 문제 해결
  • 작업과 관련된 주제
  • 참고 문헌
Advertisements

Laravel 5.4~5.5 다중 사용자인증

  • 작업 조건
    • PHP >= 5.6.4
    • OpenSSL PHP Extension
    • PDO PHP Extension
    • Mbstring PHP Extension
    • Tokenizer PHP Extension
    • XML PHP Extension
  • 작업 내용
    • Laravel 5.4에서 다중 사용자 인증 만들기
  • 작업 과정
    • 1. Laravel 5.4 project를 설치합니다.
      • composer create-project –prefer-dist laravel/laravel blog “5.4.*”
    • 2. admins migration table과 Model을 만듭니다.
      • &amp;amp;amp;amp;amp;amp;lt;?php
        use Illuminate\Support\Facades\Schema;
        use Illuminate\Database\Schema\Blueprint;
        use Illuminate\Database\Migrations\Migration;
        class CreateAdminsTable extends Migration
        {
         /**
         * Run the migrations.
         *
         * @return void
         */
         public function up()
         {
         Schema::create('admins', function (Blueprint $table) {
         $table-&amp;amp;amp;amp;amp;amp;gt;increments('id');
         $table-&amp;amp;amp;amp;amp;amp;gt;string('name');
         $table-&amp;amp;amp;amp;amp;amp;gt;string('email')-&amp;amp;amp;amp;amp;amp;gt;unique();
         $table-&amp;amp;amp;amp;amp;amp;gt;string('job_title');
         $table-&amp;amp;amp;amp;amp;amp;gt;string('password');
         $table-&amp;amp;amp;amp;amp;amp;gt;rememberToken();
         $table-&amp;amp;amp;amp;amp;amp;gt;timestamps();
         });
         }
         /**
         * Reverse the migrations.
         *
         * @return void
         */
         public function down()
         {
         Schema::dropIfExists('admins');
         }
        }
        
      • &amp;amp;amp;amp;amp;amp;lt;?php
        
        namespace App;
        
        use Illuminate\Notifications\Notifiable;
        use Illuminate\Foundation\Auth\User as Authenticatable;
        
        class Admin extends Authenticatable
        {
         use Notifiable;
        
         protected $guard = 'admin';
        
         /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
         protected $fillable = [
         'name', 'email', 'password', 'job_title',
         ];
        
         /**
         * The attributes that should be hidden for arrays.
         *
         * @var array
         */
         protected $hidden = [
         'password', 'remember_token',
         ];
        }
        
      • 3. App/Exceiptions/Handler.php 에 다음 코드를 복사합니다.
        &amp;amp;amp;amp;amp;amp;lt;?php
        namespace App\Exceptions;
        use Exception;
        use Illuminate\Auth\AuthenticationException;
        use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
        class Handler extends ExceptionHandler
        {
         /**
         * A list of the exception types that should not be reported.
         *
         * @var array
         */
         protected $dontReport = [
         \Illuminate\Auth\AuthenticationException::class,
         \Illuminate\Auth\Access\AuthorizationException::class,
         \Symfony\Component\HttpKernel\Exception\HttpException::class,
         \Illuminate\Database\Eloquent\ModelNotFoundException::class,
         \Illuminate\Session\TokenMismatchException::class,
         \Illuminate\Validation\ValidationException::class,
         ];
         /**
         * Report or log an exception.
         *
         * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
         *
         * @param \Exception $exception
         * @return void
         */
         public function report(Exception $exception)
         {
         parent::report($exception);
         }
         /**
         * Render an exception into an HTTP response.
         *
         * @param \Illuminate\Http\Request $request
         * @param \Exception $exception
         * @return \Illuminate\Http\Response
         */
         public function render($request, Exception $exception)
         {
         return parent::render($request, $exception);
         }
         /**
         * Convert an authentication exception into an unauthenticated response.
         *
         * @param \Illuminate\Http\Request $request
         * @param \Illuminate\Auth\AuthenticationException $exception
         * @return \Illuminate\Http\Response
         */
         protected function unauthenticated($request, AuthenticationException $exception)
         {
         if ($request-&amp;amp;amp;amp;amp;amp;gt;expectsJson()) {
         return response()-&amp;amp;amp;amp;amp;amp;gt;json(['error' =&amp;amp;amp;amp;amp;amp;gt; 'Unauthenticated.'], 401);
         }
         $guard = array_get($exception-&amp;amp;amp;amp;amp;amp;gt;guards(), 0);
         switch ($guard) {
         case 'admin':
         $login = 'admin.login';
         break;
         default:
         $login = 'login';
         break;
         }
         return redirect()-&amp;amp;amp;amp;amp;amp;gt;guest(route($login));
         }
        }
        
      • 4. app/Http/Middleware/RedirectIfAuthenticated.php 으로 이동한 후 이 코드를 붙여넣습니다.
        &amp;amp;amp;amp;amp;lt;?php
        namespace App\Http\Middleware;
        use Closure;
        use Illuminate\Support\Facades\Auth;
        class RedirectIfAuthenticated
        {
         /**
         * Handle an incoming request.
         *
         * @param \Illuminate\Http\Request $request
         * @param \Closure $next
         * @param string|null $guard
         * @return mixed
         */
         public function handle($request, Closure $next, $guard = null)
         {
         switch ($guard) {
         case 'admin':
         if (Auth::guard($guard)-&amp;amp;amp;amp;amp;gt;check()) {
         return redirect()-&amp;amp;amp;amp;amp;gt;route('admin.dashboard');
         }
         break;
         default:
         if (Auth::guard($guard)-&amp;amp;amp;amp;amp;gt;check()) {
         return redirect('/home');
         }
         break;
         }
         return $next($request);
         }
        }
        
      • 5. Admin Controller를 만듭니다.
        &amp;amp;amp;amp;amp;lt;?php
        namespace App\Http\Controllers;
        use Illuminate\Http\Request;
        class AdminController extends Controller
        {
         /**
         * Create a new controller instance.
         *
         * @return void
         */
         public function __construct()
         {
         $this-&amp;amp;amp;amp;amp;gt;middleware('auth:admin');
         }
         /**
         * Show the application dashboard.
         *
         * @return \Illuminate\Http\Response
         */
         public function index()
         {
         return view('admin');
         }
        }
        
      • 6. 다음 명령어를 실행합니다. php artisan make:controller auth/AdminLoginController
      • 또는 AdminLoginController/Http/ Controllers/Auth/AdminLoginController.php를 생성하고 이 코드를 붙여넣습니다.
        &amp;amp;lt;?php
        namespace App\Http\Controllers\Auth;
        use Illuminate\Http\Request;
        use App\Http\Controllers\Controller;
        use Auth;
        class AdminLoginController extends Controller
        {
         public function __construct()
         {
         $this-&amp;amp;gt;middleware('guest:admin');
         }
         public function showLoginForm()
         {
         return view('auth.admin-login');
         }
         public function login(Request $request)
         {
         // Validate the form data
         $this-&amp;amp;gt;validate($request, [
         'email' =&amp;amp;gt; 'required|email',
         'password' =&amp;amp;gt; 'required|min:6'
         ]);
         // Attempt to log the user in
         if (Auth::guard('admin')-&amp;amp;gt;attempt(['email' =&amp;amp;gt; $request-&amp;amp;gt;email, 'password' =&amp;amp;gt; $request-&amp;amp;gt;password], $request-&amp;amp;gt;remember)) {
         // if successful, then redirect to their intended location
         return redirect()-&amp;amp;gt;intended(route('admin.dashboard'));
         }
         // if unsuccessful, then redirect back to the login with the form data
         return redirect()-&amp;amp;gt;back()-&amp;amp;gt;withInput($request-&amp;amp;gt;only('email', 'remember'));
         }
        }
        
      • 7. config/auth.php 파일에 이 코드를 붙여넣습니다.
        &amp;amp;lt;?php
        return [
         /*
         |--------------------------------------------------------------------------
         | Authentication Defaults
         |--------------------------------------------------------------------------
         |
         | This option controls the default authentication "guard" and password
         | reset options for your application. You may change these defaults
         | as required, but they're a perfect start for most applications.
         |
         */
         'defaults' =&amp;amp;gt; [
         'guard' =&amp;amp;gt; 'web',
         'passwords' =&amp;amp;gt; 'users',
         ],
         /*
         |--------------------------------------------------------------------------
         | Authentication Guards
         |--------------------------------------------------------------------------
         |
         | Next, you may define every authentication guard for your application.
         | Of course, a great default configuration has been defined for you
         | here which uses session storage and the Eloquent user provider.
         |
         | All authentication drivers have a user provider. This defines how the
         | users are actually retrieved out of your database or other storage
         | mechanisms used by this application to persist your user's data.
         |
         | Supported: "session", "token"
         |
         */
         'guards' =&amp;amp;gt; [
         'web' =&amp;amp;gt; [
         'driver' =&amp;amp;gt; 'session',
         'provider' =&amp;amp;gt; 'users',
         ],
         'api' =&amp;amp;gt; [
         'driver' =&amp;amp;gt; 'token',
         'provider' =&amp;amp;gt; 'users',
         ],
         'admin' =&amp;amp;gt; [
         'driver' =&amp;amp;gt; 'session',
         'provider' =&amp;amp;gt; 'admins',
         ],
         'admin-api' =&amp;amp;gt; [
         'driver' =&amp;amp;gt; 'token',
         'provider' =&amp;amp;gt; 'admins',
         ],
         ],
         /*
         |--------------------------------------------------------------------------
         | User Providers
         |--------------------------------------------------------------------------
         |
         | All authentication drivers have a user provider. This defines how the
         | users are actually retrieved out of your database or other storage
         | mechanisms used by this application to persist your user's data.
         |
         | If you have multiple user tables or models you may configure multiple
         | sources which represent each model / table. These sources may then
         | be assigned to any extra authentication guards you have defined.
         |
         | Supported: "database", "eloquent"
         |
         */
         'providers' =&amp;amp;gt; [
         'users' =&amp;amp;gt; [
         'driver' =&amp;amp;gt; 'eloquent',
         'model' =&amp;amp;gt; App\User::class,
         ],
         'admins' =&amp;amp;gt; [
         'driver' =&amp;amp;gt; 'eloquent',
         'model' =&amp;amp;gt; App\Admin::class,
         ],
         // 'users' =&amp;amp;gt; [
         // 'driver' =&amp;amp;gt; 'database',
         // 'table' =&amp;amp;gt; 'users',
         // ],
         ],
         /*
         |--------------------------------------------------------------------------
         | Resetting Passwords
         |--------------------------------------------------------------------------
         |
         | You may specify multiple password reset configurations if you have more
         | than one user table or model in the application and you want to have
         | separate password reset settings based on the specific user types.
         |
         | The expire time is the number of minutes that the reset token should be
         | considered valid. This security feature keeps tokens short-lived so
         | they have less time to be guessed. You may change this as needed.
         |
         */
         'passwords' =&amp;amp;gt; [
         'users' =&amp;amp;gt; [
         'provider' =&amp;amp;gt; 'users',
         'table' =&amp;amp;gt; 'password_resets',
         'expire' =&amp;amp;gt; 60,
         ],
         'admins' =&amp;amp;gt; [
         'provider' =&amp;amp;gt; 'admins',
         'table' =&amp;amp;gt; 'password_resets',
         'expire' =&amp;amp;gt; 15,
         ],
         ],
        ];
        
      • 8. Route file
        &amp;amp;lt;?php
        /*
        |--------------------------------------------------------------------------
        | Web Routes
        |--------------------------------------------------------------------------
        |
        | Here is where you can register web routes for your application. These
        | routes are loaded by the RouteServiceProvider within a group which
        | contains the "web" middleware group. Now create something great!
        |
        */
        Route::get('/', function () {
         return view('welcome');
        });
        Auth::routes();
        Route::get('/home', 'HomeController@index');
         Route::prefix('admin')-&amp;amp;gt;group(function() {
         Route::get('/login', 'Auth\AdminLoginController@showLoginForm')-&amp;amp;gt;name('admin.login');
         Route::post('/login', 'Auth\AdminLoginController@login')-&amp;amp;gt;name('admin.login.submit');
         Route::get('/', 'AdminController@index')-&amp;amp;gt;name('admin.dashboard');
         });
        
      • 9. admin.blade.php를 home.blade.php와 동일하게 만듭니다.
        @extends('layouts.app')
        
        @section('content')
        &lt;div class="container"&gt;
         &lt;div class="row"&gt;
         &lt;div class="col-md-8 col-md-offset-2"&gt;
         &lt;div class="panel panel-default"&gt;
         &lt;div class="panel-heading"&gt;ADMIN Dashboard&lt;/div&gt;
        
         &lt;div class="panel-body"&gt;
         You are logged in as &lt;strong&gt;ADMIN&lt;/strong&gt;
         &lt;/div&gt;
         &lt;/div&gt;
         &lt;/div&gt;
         &lt;/div&gt;
        &lt;/div&gt;
        @endsection
        

        10.views/auth/admin-login.blade.php를 만듭니다.

        @extends('layouts.app')
        
        @section('content')
        <div class="container">
        <div class="row">
        <div class="col-md-8 col-md-offset-2">
        <div class="panel panel-default">
        <div class="panel-heading">ADMIN Login</div>
        <div class="panel-body">
        
        {{ csrf_field() }}
        <div>has('email') ? ' has-error' : '' }}"&gt;
        E-Mail Address
        <div class="col-md-6">
        
        
        @if ($errors-&gt;has('email'))
        <span class="help-block">
        <strong>{{ $errors-&gt;first('email') }}</strong>
        </span>
        @endif
        </div>
        </div>
        <div>has('password') ? ' has-error' : '' }}"&gt;
        Password
        <div class="col-md-6">
        
        
        @if ($errors-&gt;has('password'))
        <span class="help-block">
        <strong>{{ $errors-&gt;first('password') }}</strong>
        </span>
        @endif
        </div>
        </div>
        <div class="form-group">
        <div class="col-md-6 col-md-offset-4">
        <div class="checkbox">
        
         Remember Me
        
        </div>
        </div>
        </div>
        <div class="form-group">
        <div class="col-md-8 col-md-offset-4">
        
        Login
        
        
        <a class="btn btn-link" href="{{ route('password.request') }}">
        Forgot Your Password?
        </a>
        </div>
        </div>
        
        </div>
        </div>
        </div>
        </div>
        </div>
        @endsection
        
  • 작업 중 참고사항
  • 작업 중 발생한 문제 해결
  • 작업과 관련된 주제
  • 참고 문헌

cafe24에 Laravel 설치하기

  • 작업 조건
    • php
    • Composer
  • 작업 내용
    • cafe24 호스팅 서버에 Laravel 설치하기.
  • 작업 과정
    • 1. Composer create-project laravel/laravel로 Laravel 프로젝트 생성
    • 2. 생성된 laravel 폴더를 Cafe24의 www directory로 복사
    • 3. laravel/public 가 웹경로의 루트(/)가 되어야 하므로 www 폴더를 삭제(rm -rf www)하고 www 의 심볼릭 링크를 laravel/publilc 를 www 로 만든 후 permalink 확인
      • $ rm -rf www
      • $ ln -s laravel/public
      • ll
  • 선택 사항
  • 작업 과정 중 참고사항
  • 작업 중 발생한 문제 해결
  • 작업과 관련된 주제
  • 참고 문헌

Windows 10 Apache 서버의 가상 호스트에 Laravel 설치

  • 작업 조건
    • Windwos 10
    • Apache 2.4
    • Laravel 5.5
    • Php 7
    • Composer
    • php mod_fgcid 모듈
    • php mod_rewrite 모듈
  • 작업 내용
    • Windows 10에 설치된 Apache 2.4에 Laravel Frame Work 설치하기
  • 작업 과정
    •  1. Apache24/conf/httpd.conf 파일에
      LoadModule rewrite_module modules/mod_rewrite.so 에 있는 주석을 해제한다.
      setup_laravel_in_apache_on_windows_01.png
      2. Apache24/conf/extra/htpd-vhosts.conf에 다음과 같이 설정한다.
      setup_laravel_in_apache_on_windows_02.png
      <VirtualHost dev2.sjcompany.stage4.com:80>
      #ServerAdmin webmaster@dummy-host2.example.com
      DocumentRoot “c:/Apache24/htdocs/dev2.sjcompany.stage4.com/public” // Laravel의 Public Folder로 문서 Root를 설정해야한다.
      ServerName dev2.sjcompany.stage4.com
      ErrorLog “logs/dev2.sjcompany.stage4.com-error.log”
      CustomLog “logs/dev2.sjcompany.stage4.com-access.log” common
      <Directory “c:/Apache24/htdocs/dev2.sjcompany.stage4.com”>
      Options Indexes FollowSymLinks MultiViews
      AllowOverride All
      Order allow,deny
      allow from all
      Require all granted
      </Directory>
      FcgidInitialEnv PHPRC “c:/Development/php7”
      AddHandler fcgid-script .php
      FcgidWrapper “c:/Development/php7/php-cgi.exe” .php
      </VirtualHost>
      3. Laravel을 Composer를 사용해서 설치한다.setup_laravel_in_apache_on_windows_03.png
      4. Laravel을 Apache24/conf/extra/httpd-vhosts에서 설정한 경로로 이동시킨다.
      setup_laravel_in_apache_on_windows_04.png
      5. 테스트
      setup_laravel_in_apache_on_windows_05
    • 작업 과정 중 참고사항
    • 작업 중 발생한 문제 해결
  • 작업과 관련된 주제
  • 참고 문헌