步骤

1、创建Login表单登录与Register表单注册验证器,并声明验证规则
2、创建User控制器,定义注册与登录逻辑
3、定义路由,规定返回格式,登录时的token验证

实现代码

1、创建Login表单登录与Register表单注册验证器,并声明验证规则

php artisan make:request \App\Http\Request\Login
php artisan make:request \App\Http\Request\Register

基础验证类

<?php

namespace App\Http\Request;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class Request extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }
    //定义错误验证值只返回一个错误
    protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
    {
        //使用http异常处理类抛出异常
        throw new HttpResponseException(response()->json([
            'ret' => 422,
            'msg' => $validator->errors()->first(),
            'data' => []
        ], 200));
    }


}

注册用户验证类

<?php

namespace App\Http\Request;

use App\Http\Request\Request;

class Register extends Request
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'username'=>'required|regex:/^1[345789][0-9]{9}$/|unique:user,username',
            'password'=>'required|min:8',
            'repassword'=>'required|same:password',
            'head_url'=>'required|url',
        ];
    }

    public function messages()
    {
        return [
            'username.required' => '账号不能为空',
            'username.regex' => '手机号格式错误',
            'username.unique' => '当前账号已注册',
            'password.required' => '密码不能为空',
            'password.min' => '密码不能少于8位',
            'repassword.required' => '请确认密码',
            'repassword.same' => '两次密码不一致',
            'head_url.required'=>'头像不能为空',
            'head_url.url'=>'头像地址错误',
        ];
    }
}

登录用户验证类

<?php

namespace App\Http\Request;

use App\Http\Request\Request;

class Login extends Request
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'username'=>'required|regex:/^1[345789][0-9]{9}$/',
            'password'=>'required|min:8',
        ];
    }

    public function messages()
    {
        return [
            'username.required' => '账号不能为空',
            'username.regex' => '手机号格式错误',
            'password.required' => '密码不能为空',
            'password.min' => '密码不能少于8位',
        ];
    }
}

2、创建User控制器,定义注册与登录逻辑

php artisan make:controller \App\Http\Controllers\Test\UserController
<?php

namespace App\Http\Controllers\Test;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Model\UserModel;
use Illuminate\Support\Facades\Cache;
use App\Http\Request\Register;
use App\Http\Request\Login;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{
    /**
     * @var \Medoo\Medoo
     */
    protected $medoo;
    protected $s_user;

    public function __construct(Request $request)
    {
        $this->medoo = app('medoo');
        //登录成功后,访问其他方法时,获取请求头存放的token信息进行验证
        $BearerToken = $request->server('HTTP_AUTHORIZATION');
        $authToken = str_replace('Bearer ', '', $BearerToken);
        //根据token值作为键名从redis缓存中获取用户详细信息
        $this->s_user = Cache::get($authToken);
    }

    public function registerApi(Register $request)
    {
        //1、获取表单数据并插入用户表
        $param = $request->post();
        $user = UserModel::create([
            'username' => $param['username'],
            'password' => Hash::make($param['password']),
            'head_url' => $param['head_url'],
            'admin' => 0,
            'is_delete' => 0,
            'status' => 1,
            'time' => time(),
            'create_time' => time(),
            'update_time' => time(),
        ]);

        //2、令牌创建后,并存入缓存
        $token = $user->createToken('login-token')->plainTextToken;
        //3、将token存入redis缓存,并根据token失效时间'expiration' => 60 * 2设置redis值的失效时间,因为sanctum是以分钟为单位,redis是以秒为单位需要乘60换算,缓存在redis中两小时
        $minutes = config('sanctum.expiration');
        $token = explode('|', $token);
        Cache::put($token[1], $user, $minutes * 60);
        //4、根据约定返回成功信息
        return [200, [
            'userinfo' => [
                'username' => $param['username'],
                'head_url' => $param['head_url'],
             ],
            'token'=>$token[1],
        ]];
    }

    public function loginApi(Login $request)
    {
        //获取登录用户信息
        $param = $request->post();
        $user = UserModel::where([
            'username'=> $param['username'],
            'admin' =>0,
            'status' => 1,
            'is_delete'=>0,
        ])->first();

        if(!$user){
            return [500,'该用户不存在'];
        }
        //1、删除api_personal_access_tokens表历史token信息,实现单点登录
        $user->tokens()->delete();
        //2、令牌创建后,并存入缓存
        $token = $user->createToken('login-token')->plainTextToken;
        //3、将token存入redis缓存,并根据token失效时间'expiration' => 60 * 2设置redis值的失效时间,因为sanctum是以分钟为单位,redis是以秒为单位需要乘60换算,缓存在redis中两小时
        $minutes = config('sanctum.expiration');
        $token = explode('|', $token);
        Cache::put($token[1], $user, $minutes * 60);
        //4、根据约定返回成功信息
        return [200, [
            'userinfo' => [
                'username' => $param['username'],
                'head_url' => $user['head_url'],
            ],
            'token'=>$token[1],
        ]];
    }

    public  function advertListApi()
    {
        $data = $this->medoo->select('advert',[
            'id','title','pos','img','url'
        ],['ORDER'=>['id'=>'DESC'],'LIMIT'=> 10,'is_delete'=>0]);

        return [200,$data];
    }
}

3、定义路由,规定返回格式,登录时的token验证

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;


Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::group([
    'namespace' => 'Test',
    'prefix' => 'test',
    'middleware' => 'apiAfter'
], function () {
    #用中间件做token验证,放入一下的路由都需要通过token验证
    //方法1:
    Route::group(['middleware'=>'apiAfter'],function(){
        //用户注册
        Route::any('userregister','UserController@registerApi');
        //用户登录
        Route::any('userlogin','UserController@loginApi');
    });

    Route::group(['middleware'=>'auth:sanctum'], function (){
        //获取广告详情
        Route::any('advertlist', 'UserController@advertListApi');
    });
    //方法2:
//    Route::any('userregister', 'UserController@registerApi');
//    Route::any('userlogin', 'UserController@loginApi');
//    Route::middleware('auth:sanctum')->any('advertlist', 'UserController@advertListApi');
});

展示:

注册用户页面展示:

laravel python交互 laravel登录接口_redis

登录用户页面展示:

laravel python交互 laravel登录接口_App_02


广告展示:

laravel python交互 laravel登录接口_redis_03