Skip to content
关注公众号,获取新课通知
【重要通知】uniapp实战社区交友交流群更换为:602180461,靓仔/靓女可以重新申请加入哦~

账号密码登录api


controller层:application\api\controller\v1\User.php

php
// 账号密码登录
public function login(){
    // 验证登录信息
    (new UserValidate())->goCheck('login');
    // 登录
    $token = (new UserModel())->login();
    return self::showResCode('登录成功',['token'=>$token]);
}

route层:route\route.php

php
// 不需要验证token
Route::group('api/:version/',function(){
    ...
    // 账号密码登录
	Route::post('user/login','api/:version.User/login');
    ...
});

validate层:application\common\validate\UserValidate.php

php
// 验证规则
protected $rule = [
    ...
        'username'=>'require',
        'password'=>'require|alphaDash',
    ...
];

// 验证场景
protected $scene = [
    ...
        'login'=>['username','password'],
    ...
];

model层:application\common\model\User.php

php
// 判断用户是否存在(在前面课程的基础上扩充)
public function isExist($arr=[]){
    if(!is_array($arr)) return false;
    if (array_key_exists('phone',$arr)) { // 手机号码
        return $this->where('phone',$arr['phone'])->find();
    }
    // 用户id
    if (array_key_exists('id',$arr)) { // 用户名
        return $this->where('id',$arr['id'])->find();
    }
    if (array_key_exists('email',$arr)) { // 邮箱
        return $this->where('email',$arr['email'])->find();
    }
    if (array_key_exists('username',$arr)) { // 用户名
        return $this->where('username',$arr['username'])->find();
    }
    return false;
}

// 账号登录
public function login(){
    // 获取所有参数
    $param = request()->param();
    // 验证用户是否存在
    $user = $this->isExist($this->filterUserData($param['username']));
    // 用户不存在
    if(!$user) throw new BaseException(['code'=>200,'msg'=>'.../邮箱/手机号错误','errorCode'=>20000]);
    // 用户是否被禁用
    $this->checkStatus($user->toArray());
    // 验证密码
    $this->checkPassword($param['password'],$user->password);
    // 登录成功 生成token,进行缓存,返回客户端
    return $this->CreateSaveToken($user->toArray());
}

// 验证用户名是什么格式,.../邮箱/手机号
public function filterUserData($data){
    $arr=[];
    // 验证是否是手机号码
    if(preg_match('^1(3|4|5|7|8)[0-9]\d{8}$^', $data)){
        $arr['phone']=$data; 
        return $arr;
    }
    // 验证是否是邮箱
    if(preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/', $data)){
        $arr['email']=$data; 
        return $arr;
    }
    $arr['username']=$data; 
    return $arr;
}

// 验证密码
public function checkPassword($password,$hash){
    if (!$hash) throw new BaseException(['code'=>200,'msg'=>'密码错误','errorCode'=>20002]);
    // 密码错误
    if(!password_verify($password,$hash)) throw new BaseException(['code'=>200,'msg'=>'密码错误','errorCode'=>20002]);
    return true;
}