2020年8月24日月曜日

laravel projectにてhtpasswd でbase認証をかける

1)base認証用password fileを作成

mkdir /etc/htpasswd (必要に応じて)

htpasswd -c /etc/htpasswd/.htpasswd username(コマンドを実行すると、PW入力を要求される)


2)/var/www/html/site/public/.htaccess を変更

一番上に、以下を追加


AuthType Basic

AuthName "Authentication Required"

AuthUserFile "/etc/htpasswd/.htpasswd"

Require valid-user

サクラVPSにSSLを導入

 1)certbotインストール

yum install certbot python2-certbot-apache


2)apache confファイルの最後に下記VirtualHost追加


NameVirtualHost *:80


<VirtualHost *:80>

ServerAdmin root@xxx.com

DocumentRoot /var/www/html/site/public

ServerName xxx.com


3)certbotコマンドを実行して証明書をインストール

certbot --apache -d xxx.com

※実施中、httpをhttpsへredirectするか聞いてくる際、redirectするようにします。


初期ドメイン→独自ドメイン リダイレクト

以下の内容をapache confファイルに追加

<VirtualHost *:80>

ServerAdmin root@xxx.com

DocumentRoot /var/www/html/site/public

ServerName os1-234-56789.vs.sakura.ne.jp

RewriteEngine on

RewriteCond %{SERVER_NAME} =os1-234-56789.vs.sakura.ne.jp

RewriteRule ^ https://xxx.com%{REQUEST_URI} [END,NE,R=permanent]


4)証明書を更新

certbot renew

2019年7月5日金曜日

ssh転送でremote mysqlをlocal開発に利用


ssh -f -N -L 13306:localhost:3306 username@10.10.10.10 -p 22

2019年6月3日月曜日

laravel type hintでobjとれない件

以下のrouting定義がある。
Route::resource('tokus', 'TokuController')

controllerで下記のtype hintがあるが、dd($toku)であるはずのobjがとれない。
public function show(Toku $toku)
    {
        return view('tokus.show', compact('toku'));
    }

route:listで確認したところ、show actionのURIは、tokes/{tokes}になっている。
type hintの引数は{tokes}と一致しないといけないため、public function show(Toku $tokus)に変更したら解決できた。それが嫌なら、引数を指定できる。

Route::resource('tokus', 'TokuController')->parameters([
    'tokus' => 'toku'
]);

参考:https://laracasts.com/discuss/channels/laravel/controller-method-with-type-hinting-give-empty-eloquent-object

2019年5月30日木曜日

laravel middleware

Controllers also allow you to register middleware using a Closure. This provides a convenient way to define a middleware for a single controller without defining an entire middleware class:

$this->middleware(function ($request, $next) {
    // ...

    return $next($request);
});

resource controller

php artisan make:controller PhotoController --resource
Route::resource('photos', 'PhotoController');
Route::resources([
    'photos' => 'PhotoController',
    'posts' => 'PostController'
]);

Partial Resource Routes

Route::resource('photos', 'PhotoController')->only([
    'index', 'show'
]);

Route::resource('photos', 'PhotoController')->except([
    'create', 'store', 'update', 'destroy'
]);

Route::apiResources([
    'photos' => 'PhotoController',
    'posts' => 'PostController'
]);

If you need to add additional routes to a resource controller beyond the default set of resource routes, you should define those routes before your call to Route::resource

Route::get('photos/popular', 'PhotoController@method');
Route::resource('photos', 'PhotoController');

You may even restrict the middleware to only certain methods on the controller class:

public function __construct()
    {
        $this->middleware('auth');

        $this->middleware('log')->only('index');

        $this->middleware('subscribed')->except('store');
    }

// 一覧
GET /projects (index)

// 新規ページ
GET /projects/create (create)

// 保存
POST /projects (store)

// show project
GET /projects/{id}

// 編集ページ
GET /projects/{id}/edit (edit)

// 更新
PATCH /projects/{id} (update)

// 削除
DELETE /projects/{id} (destroy)

Dependency Injection & Controllers

Injectionの場所は2つある
1)Constructor Injection
class UserController extends Controller
{
    /**
     * The user repository instance.
     */
    protected $users;

    /**
     * Create a new controller instance.
     *
     * @param  UserRepository  $users
     * @return void
     */
    public function __construct(UserRepository $users)
    {
        $this->users = $users;
    }
}

2)Method Injection
class UserController extends Controller
{
    /**
     * Store a new user.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $name = $request->name;

        //
    }
}

laravel Authorization

Gates provide a simple, Closure based approach to authorization while policies, like controllers, group their logic around a particular model or resource.
Gates are most applicable to actions which are not related to any model or resource, such as viewing an administrator dashboard. In contrast, policies should be used when you wish to authorize an action for a particular model or resource.

Gates are Closures that determine if a user is authorized to perform a given action and are typically defined in the App\Providers\AuthServiceProvider class using the Gate facade. Gates always receive a user instance as their first argument, and may optionally receive additional arguments such as a relevant Eloquent model:

public function boot()
{
    $this->registerPolicies();

    Gate::define('update-post', function ($user, $post) {
        return $user->id == $post->user_id;
    });

    Gate::define('update-post', 'App\Policies\PostPolicy@update');
}

Authorizing Actions

To authorize an action using gates, you should use the allows or denies methods. Note that you are not required to pass the currently authenticated user to these methods. Laravel will automatically take care of passing the user into the gate Closure:

if (Gate::allows('update-post', $post)) {
    // The current user can update the post...
}

if (Gate::denies('update-post', $post)) {
    // The current user can't update the post...
}

If you would like to determine if a particular user is authorized to perform an action, you may use the forUser method on the Gate facade:

if (Gate::forUser($user)->allows('update-post', $post)) {
    // The user can update the post...
}

if (Gate::forUser($user)->denies('update-post', $post)) {
    // The user can't update the post...
}

You may use the before method to define a callback that is run before all other authorization checks:

boot function中で下記追加

Gate::before(function ($user, $ability) {
    if ($user->isSuperAdmin()) {
        return true;
    }
});
If the before callback returns a non-null result that result will be considered the result of the check.

You may use the after method to define a callback to be executed after all other authorization checks:

Gate::after(function ($user, $ability, $result, $arguments) {
    if ($user->isSuperAdmin()) {
        return true;
    }
});

Generating Policies

php artisan make:policy PostPolicy
php artisan make:policy PostPolicy --model=Post

Registering Policies

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        Post::class => PostPolicy::class,
    ];

Policy Auto-Discovery
Laravel can auto-discover policies as long as the model and policy follow standard Laravel naming conventions.

Any policies that are explicitly mapped in your AuthServiceProvider will take precedence over any potential auto-discovered policies.

class PostPolicy
{
    /**
     * Determine if the given post can be updated by the user.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return bool
     */
    public function update(User $user, Post $post)
    {
        return $user->id === $post->user_id;
    }
}

Guest Users

By default, all gates and policies automatically return false if the incoming HTTP request was not initiated by an authenticated user. However, you may allow these authorization checks to pass through to your gates and policies by declaring an "optional" type-hint or supplying a  null default value for the user argument definition:
public function update(?User $user, Post $post)
    {
        return $user->id === $post->user_id;
    }

For certain users, you may wish to authorize all actions within a given policy. To accomplish this, define a before method on the policy. The before method will be executed before any other methods on the policy

public function before($user, $ability)
{
    if ($user->isSuperAdmin()) {
        return true;
    }
}
If you would like to deny all authorizations for a user you should return false from the before method. If null is returned, the authorization will fall through to the policy method.
The before method of a policy class will not be called if the class doesn't contain a method with a name matching the name of the ability being checked.

Authorizing Actions Using Policies

if ($user->can('update', $post)) {
    // Via The User Model
}

use App\Post;
if ($user->can('create', Post::class)) {
    // Executes the "create" method on the relevant policy...
}

Laravel includes a middleware that can authorize actions before the incoming request even reaches your routes or controllers.
Route::put('/post/{post}', function (Post $post) {
    // The current user may update the post...
})->middleware('can:update,post');
we're passing the can middleware two arguments. The first is the name of the action we wish to authorize and the second is the route parameter we wish to pass to the policy method.
Actions That Don't Require Model Instance
Route::post('/post', function () {
    // The current user may create posts...
})->middleware('can:create,App\Post');

Via Controller Helpers

public function update(Request $request, Post $post)
    {
        $this->authorize('update', $post);

        // The current user can update the blog post...
    }

Via Blade Templates

@can('update', $post)
    <!-- The Current User Can Update The Post -->
@elsecan('create', App\Post::class)
    <!-- The Current User Can Create New Post -->
@endcan

@cannot('update', $post)
    <!-- The Current User Can't Update The Post -->
@elsecannot('create', App\Post::class)
    <!-- The Current User Can't Create New Post -->
@endcannot