1. 程式人生 > >Lumen實現用戶註冊登錄認證

Lumen實現用戶註冊登錄認證

brew 文件中 ever mina 必須 eth providers rac exceptio

Lumen實現用戶註冊登錄認證

前言

Lumen是一個基於Laravel的微框架,號稱是以速度為生。截用Lumen官網的一段,號稱是比silex和slim還要快。

本文將用Lumen來實現一個完整的用戶註冊、登錄及獲取用戶信息的API。

Lumen官方網站:https://lumen.laravel.com/
Lumen中文網站:http://lumen.laravel-china.org/

安裝

composer create-project --prefer-dist laravel/lumen lumen

數據庫配置

跟全棧框架 Laravel 框架不一樣的是,所有的 Lumen 框架的配置信息都存儲在 .env 文件中。一旦 Lumen 成功安裝,你需要 配置本地環境,如果沒有在目錄下新建.env文件

APP_ENV=local APP_DEBUG=true APP_KEY=SomeRandomString!!! DB_CONNECTION=mysql DB_HOST=localhost DB_PORT=3306 DB_DATABASE=lumen DB_USERNAME=root DB_PASSWORD=charlie CACHE_DRIVER=memcached QUEUE_DRIVER=sync APP_TIMEZONE=PRC DB_TIMEZONE=+08:00

三 配置遷移數據庫

php artisan make:migration create_users_table --create=users

執行這條命令後,會在項目目錄lumen/database/migrations/ 目錄下生成一個php文件,這個文件主要包括兩個函數,在up()函數中根據你的需求定義數據庫字段。

<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void
*/ public function up() { Schema::create(‘users‘, function (Blueprint $table) { $table->increments(‘id‘); $table->string(‘username‘); $table->string(‘password‘); $table->string(‘email‘); $table->string(‘api_token‘, 60)->unique(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists(‘users‘); } }

執行命令,創建數據庫

php artisan migrate

數據庫會生成一張users表
技術分享

創建用戶數據模型

如果你的項目文件夾lumen\app\文件夾下沒有User.php文件,那麽新建一個User.php文件,文件內容如下:

<?php namespace App; use Illuminate\Auth\Authenticatable; use Laravel\Lumen\Auth\Authorizable; use Illuminate\Database\Eloquent\Model; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; class User extends Model implements AuthenticatableContract, AuthorizableContract { use Authenticatable, Authorizable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ ‘username‘, ‘email‘, ‘password‘, ‘api_token‘ ]; /** * The attributes excluded from the model‘s JSON form. * * @var array */ protected $hidden = [ ‘password‘, ]; }

路由定義

定義三個路由,實現用戶登錄,註冊及獲取用戶信息

路由類型路由路徑路由控制器
POST user/register [email protected]
POST user/login [email protected]
GET user/info [email protected]

根據上述表的內容,在routes/web.php中定義路由

<?php $app->get(‘/‘, function () use ($app) { return $app->version(); }); //登錄註冊 $app->post(‘user/login‘, [email protected]); $app->post(‘user/register‘, [email protected]); $app->get(‘user/info‘, [ ‘middleware‘ => ‘authToken‘, ‘uses‘ => [email protected] ]);

Controller邏輯

在Lumen\app\Http\Controllers\文件夾下新建用戶控制器UserController.php,實現用戶註冊、登錄和用戶信息獲取功能

<?php namespace App\Http\Controllers; use App\User; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class UserController extends Controller { private $salt; public function __construct() { $this->salt = "userloginregister"; } //登錄 public function login(Request $request) { if($request->has(‘username‘) && $request->has(‘password‘)){ $user = User::where(‘username‘, ‘=‘, $request->input(‘username‘))->where(‘password‘, ‘=‘, sha1($this->salt.$request->input(‘password‘)))->first(); if($user){ $token = str_random(60); $user->api_token = $token; $user->save(); return $user->api_token; }else{ return ‘用戶名或密碼不正確,登錄失敗‘; } }else{ return ‘登錄信息不完整,請輸入用戶名和密碼‘; } } //註冊 public function register(Request $request) { if($request->has(‘username‘) && $request->has(‘password‘) && $request->has(‘email‘)){ $user = new User; $user->username = $request->input(‘username‘); $user->password = sha1($this->salt.$request->input(‘password‘)); $user->email = $request->input(‘email‘); $user->api_token = str_random(60); if($user->save()){ return ‘用戶註冊成功!‘; }else{ return ‘用戶註冊失敗!‘; } }else{ return ‘請輸入完整用戶信息!‘; } } //信息 public function info() { return Auth::user(); }

認證服務

必須要通過token驗證才能獲取用戶信息。在Lumen\app\Http\Providers\AuthServiceProvider.php中定義驗證服務。我們使用header包含token的形式來驗證。修改Lumen\app\Http\Providers\AuthServiceProvider.php文件代碼。

<?php namespace App\Providers; use App\User; use Illuminate\Support\Facades\Gate; use Illuminate\Support\ServiceProvider; class AuthServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { // } /** * Boot the authentication services for the application. * * @return void */ public function boot() { // Here you may define how you wish users to be authenticated for your Lumen // application. The callback which receives the incoming request instance // should return either a User instance or null. You‘re free to obtain // the User instance via an API token or any other method necessary. $this->app[‘auth‘]->viaRequest(‘api‘, function ($request) { if ($request->header(‘api_token‘)) { return User::where(‘api_token‘, ‘=‘, $request->header(‘api_token‘))->first(); } }); }

定義認證中間件

在Lumen\app\Http\Middleware\文件夾下定義認證路由中間件AuthToken.php,就是之前在路由中定義的”authToken”。

<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; class AuthToken { public function handle($request, Closure $next) { if(Auth::check()){ return $next($request); }else{ abort(401); } } }

啟用配置信息

在lumen\app\bootstrap\app.php中取消註釋

<?php //讓數據庫信息和認證服務修改生效 $app->withFacades(); $app->withEloquent(); //認證中間件 $app->routeMiddleware([ ‘authToken‘ => App\Http\Middleware\AuthToken::class ]); //開啟註冊提供者 $app->register(App\Providers\AppServiceProvider::class); $app->register(App\Providers\AuthServiceProvider::class);

啟動服務,測試

php -S localhost:8000

1.用戶註冊
技術分享

查看數據庫
技術分享

2.用戶登錄
技術分享

登錄後會更新數據庫的api_token
技術分享

3.獲取用戶信息
技術分享


錯誤信息:

1.

[Symfony\Component\Debug\Exception\FatalErrorException] Class ‘Memcached‘ not found

解決辦法,安裝memcached 和php擴展

brew install memcached brew install php56-memcached 啟動memcached memcached -D

2.

PHP Fatal error: Call to a member function connection() on null in /Users/03315/www/lumen/vendor/illuminate/database/Eloquent/Model.php on line 1013

解決辦法,需要開啟,路徑app/bootstrap/app.php

$app->withEloquent();

Lumen實現用戶註冊登錄認證