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 UserController@register
POST user/login UserController@login
GET user/info UserController@info

根据上述表的内容,在routes/web.php中定义路由

<?php
$app->get('/', function () use ($app) {
return $app->version();
});
//登录注册
$app->post('user/login', 'UserController@login');
$app->post('user/register', 'UserController@register');
$app->get('user/info', [
'middleware' => 'authToken',
'uses' => 'UserController@info'
]);

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实现用户注册登录认证的更多相关文章

  1. 基于SpringBoot搭建应用开发框架(二) —— 登录认证

    零.前言 本文基于<基于SpringBoot搭建应用开发框架(一)——基础架构>,通过该文,熟悉了SpringBoot的用法,完成了应用框架底层的搭建. 在开始本文之前,底层这块已经有了很 ...

  2. Luffy之登录认证以及JWT

    1.用户认证 在前面我们已经完成了,前端登录页面的搭建,以及路由分配,现在我们作关于登录认证部分的东西 Django提供了认证系统.认证系统包含: 用户 权限:二元(是/否)标志指示一个用户是否可以做 ...

  3. Django之auth登录认证

    前言:我们在开发一个网站的时候,无可避免的需要设计实现网站的用户系统.此时我们需要实现包括用户注册.用户登录.用户认证.注销.修改密码等功能,这还真是个麻烦的事情呢. Django作为一个完美主义者的 ...

  4. day59_9_25中间键与登录认证

    一.django中间件简介. 在django中,有这样的生命周期: 中间件就是处于wsgiref和urls模块中间,可以拦截所有的请求,其中有7个默认中间件: MIDDLEWARE = [ 'djan ...

  5. ELK日志系统:Filebeat使用及Kibana如何设置登录认证

    根据elastic上的说法: Filebeat is a lightweight, open source shipper for log file data. As the next-generat ...

  6. 传智播客JavaWeb day07、day08-自定义标签(传统标签和简单标签)、mvc设计模式、用户注册登录注销

    第七天的课程主要是讲了自定义标签.简单介绍了mvc设计模式.然后做了案例 1. 自定义标签 1.1 为什么要有自定义标签 前面所说的EL.JSTL等技术都是为了提高jsp的可读性.可维护性.方便性而取 ...

  7. Asp.Net MVC3.0网站统计登录认证的在线人数

    Asp.Net MVC3.0网站统计登录认证的在线人数 前言 对于一个网站来说,统计在线人数是一个很重要的工作.平时也发现很多的网站论坛等都有在线人数的显示.对于一个网站如果在线人数很多,用户看到了这 ...

  8. 基于xml的用户注册登录案例

    用户注册登录 要求:3层框架,使用验证码 1        功能分析 l  注册 l  登录 1.1 JSP页面 l  regist.jsp 注册表单:用户输入注册信息: 回显错误信息:当注册失败时, ...

  9. shiro实现APP、web统一登录认证和权限管理

    先说下背景,项目包含一个管理系统(web)和门户网站(web),还有一个手机APP(包括Android和IOS),三个系统共用一个后端,在后端使用shiro进行登录认证和权限控制.好的,那么问题来了w ...

随机推荐

  1. 自定义mousewheel事件,实现图片放大缩小功能实现

    本文是承接 上一篇的<自定义鼠标滚动事件>  的基础上实现的,建议大家先看一下上一篇的mousewheel的实现,再浏览下文: 上篇中我们介绍到: $element.mousewheel( ...

  2. 通过自动回复机器人学Mybatis:原始版本(包括JDBC、pom.xml等)

    imooc视频学习笔记 ----> URL:http://www.imooc.com/learn/154 list.jsp <%@ page contentType="text/ ...

  3. What is CRC and how does it works?

    What is CRC and how does it works? CRC errors refer to Layer 1 or 2 issues. Two things you should ch ...

  4. 修改AdminLTE左侧菜单展开延迟

    AdminLTE左侧菜单展开会有半秒钟的延迟. 看起来会慢半拍. 可修改 admin/dist/js/app.min.js中的 animationSpeed值(默认为500) 如下:

  5. Shell 实现找出两个目录下的同名文件方法

    # 首先我们来创建一些 2 个目录,里面的目录结构及相关文件如下所示: # 从上面的测试目录可以看到, lol.txt lol2.txt 两个文件是两个目录下的同名文件 # 有实际例子,思路就容易出来 ...

  6. Curator的监听机制

    原生的zookeeper的监听API所实现的方法存在一些缺点,对于开发者来说后续的开发会考虑的细节比较多. Curator所实现的方法希望摒弃原声API 的不足,是开发看起来更加的简单,一些重连等操作 ...

  7. 第一篇:Spark SQL源码分析之核心流程

    /** Spark SQL源码分析系列文章*/ 自从去年Spark Submit 2013 Michael Armbrust分享了他的Catalyst,到至今1年多了,Spark SQL的贡献者从几人 ...

  8. spark数据监控实战

    版权申明:转载请注明出处.文章来源:http://bigdataer.net/?p=248 排版乱?请移步原文获得更好的阅读体验   1.概述 数据准确性,稳定性,时效性是数据开发中需要重点关注的,一 ...

  9. SQL中去掉换行符 与空格符

    SELECT B.TradeOrderID AS '二段交易号',B.ZipCode AS '邮编', B.Province AS '省',B.City AS '市',B.District AS '区 ...

  10. Python基础笔记系列三:list列表

    本系列教程供个人学习笔记使用,如果您要浏览可能需要其它编程语言基础(如C语言),why?因为我写得烂啊,只有我自己看得懂!! python中的list列表是一种序列型数据类型,一有序数据集合用逗号间隔 ...