[php: Sentinel] Sentinel - PHP Auth/Login/PW Library. #sentinel #php
composerで導入できる新しめのユーザ管理・ログインライブラリ。基本的な部分は大体これで実装できちゃう便利なやつ。
<?php
// Import the necessary classes
use Cartalyst\Sentinel\Native\Facades\Sentinel;
use Illuminate\Database\Capsule\Manager as Capsule;
// Include the composer autoload file
require __DIR__.'/../vendor/autoload.php';
// Setup a new Eloquent Capsule instance
$capsule = new Capsule;
$capsule->addConnection([
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'sentinel',
'username' => 'xxxx',
'password' => 'xxxxxx',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
]);
$capsule->bootEloquent();
// ユーザー情報
$credentials = [
'email' => 'email@example.com',
'password' => 'pass'
];
// 登録済みかを確認
$user = Sentinel::getUserRepository()->findByCredentials($credentials);
if (is_null($user)) {
// 存在しない場合は、新規登録
$user = Sentinel::register($credentials);
print_r($user);
}
else {
// 存在する場合は削除
$user->delete();
echo "user deleted".PHP_EOL;
}
http://sukohi.blogspot.jp/2016/01/phpsentinel.html http://am1tanaka.hatenablog.com/entry/2016/03/05/183048
https://cartalyst.com/manual/sentinel/2.0#installation
"require": {
"cartalyst/sentinel": "2.0.*",
"cartalyst/support": "~1.0",
"illuminate/database": "~5.0",
"illuminate/events": "^5.2",
"illuminate/http": "~5.0",
"illuminate/support": "~5.0",
"paragonie/random_compat": "~1.1"
}
DB sentinel
を 作成
> create database sentinel default character set utf8mb4;
> grant all on sentinel.* to 'app'@'localhost' identified by ****;
Composerでライブラリぶち込む
composer require cartalyst/sentinel "2.0.*"
この時ローカルphp.iniでmbstringのdll拡張をOFFってるとエラー図れる。別にローカルで動かすわけじゃないけどコメントアウト外しといて。
スキーマのマイグレーション。 Composerによって導入されたSentinelパッケージ配下... vendor/cartalyst/sentinel/schema/mysql-5.6+.sql; (MYSQLが5.6以前の場合はmysql.sql)
に初回マイグレーション用SQLが格納されている。これを mysql> SOURCE コマンドで読み込ませる。いつものVagrant開発なら多分以下のようなコマンドになるかな。
mysql> use sentinel;
mysql> SOURCE /var/www/vendor/cartalyst/sentinel/schema/mysql-5.6+.sql;
(Sentinelの依存元)CapsuleにDB接続させる
// Sentinel必須クラス群のuse
use Cartalyst\Sentinel\Native\Facades\Sentinel;
use Illuminate\Database\Capsule\Manager as Capsule;
// autoloadを読み込む
require 'vendor/autoload.php';
// Eloquent Capsule インスタンスを生成
$capsule = new Capsule;
$capsule->addConnection([
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'sentinel',
'username' => 'user',
'password' => 'secret',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
]);
$capsule->bootEloquent();
// あとは操作TIPS / Usage 参照
認証が必要な場所だけでなく、Userテーブル(=Sentinel管理DB)への参照が必要な全ての箇所において、SentinelのDB接続を予めしておく必要がある。よってアプリケーションのベースファイルに初回接続コードを書いておいて継承したほうが楽。
$credentials = [
'email' => 'taro.yamada@example.com',
'password' => 'password',
'first_name' => '太郎', // 省略可
'last_name' => '山田' // 省略可
];
$user = Sentinel::registerAndActivate($credentials);
//パスワードは自動的に暗号化されているらしい
$credentials = [
'email' => 'taro.yamada@example.com',
'password' => 'password',
];
$user = Sentinel::authenticate($credentials);
// 次からのログインを省略する場合はauthentiate()の第二引数に true を
// for id
$user = Sentinel::findById(1);
// for mail
$credentials = [
'login' => 'taro.yamada@example.com',
];
$user = Sentinel::findByCredentials($credentials);
$user = Sentinel::findById(1);
$credentials = [
'email' => 'new.taro.yamada@example.com',
'password' => 'new_password',
'first_name' => '二郎',
'last_name' => '鈴木'
];
// edit
$user = \Sentinel::update($user, $credentials);
// del
$user = Sentinel::findById(1);
$user->delete();
// set
$role = Sentinel::getRoleRepository()
->createModel()
->create([
'name' => '管理者',
'slug' => 'admin'
]);
// edit
$user = Sentinel::findById(1);
$role = Sentinel::findRoleByName('管理者');
$role->users()->attach($user); // 割り当てる
$role->users()->detach($user); // 割り当てを解除する
// get
$role = Sentinel::findRoleById(1); // ID
$role = Sentinel::findRoleBySlug('admin'); // Slug(ユニークIDみたいなもの)
$role = Sentinel::findRoleByName('管理者'); // 役割の名前
ユーザー登録→「本登録URLメール送信」→URLクリック時点で本登録的な機能の実現。
// first step
$user = \Sentinel::register([
'email' => $email,
'password' => 'password'
]);
$activation = \Activation::create($user);
$activation_code = $activation->code;
// 上記コードでURL生成してる
// → ttp://example.com/activation/*******
// second step
$user = Sentinel::findById(1);
if (Activation::complete($user, '本登録コード'))
{
// 本登録完了!
}
else
{
// 失敗,,,
}
// ちなみに本登録していない状態でログイン
// →「NotActivatedException」例外がスロー
パスワードの再発行機能
// reminder code の取得
$user = \Sentinel::findById(1);
$reminder = \Reminder::create($user);
$reminder_code = $reminder->code;
// 新しいpwの設定
$user = Sentinel::findById(1);
if ($reminder = Reminder::complete($user, 'リマインダー・コード', '新パスワード'))
{
// 成功!
}
else
{
// 失敗,,,
}
$users = Sentinel::getUserRepository();
var_dump($users);
// ロールをパーミッション割当しつつ作成
$role = Sentinel::getRoleRepository()->createModel()->create([
'name' => 'Admin',
'slug' => 'admin',
'permissions' => [
'user.create'=>true,
'user.update'=>true,
'user.delete'=>true,
'user.view'=>true
],
]);
// ロールをユーザに割当
$user = Sentinel::findById(***);
$role = Sentinel::findRoleBySlug('admin');
$role->users()->attach($user); //detachで削除
// ロール別にユーザを呼び出す
$hogeUsersCollection = $role->users()->with('hoge')->get();
$usersIdArray = $hogeUsersCollection->modelKeys();
foreach($usersIdArray as $key => $value){
$users[] = Sentinel::findById($value);
}
``````