You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
2.0 KiB
PHTML

3 years ago
<?php
namespace app\index\controller;
use think\facade\Request;
use think\facade\Config;
use think\facade\Cache;
use app\common\model\User;
use app\common\model\UserToken;
use app\common\model\UserRelation;
use app\common\controller\JsonReturn;
use app\common\exception\ServiceException;
class Auth extends Home
{
public function login()
{
if (Request::isPost()) {
$account = Request::post('account', '', 'trim');
$password = Request::post('password', '', 'trim');
$web_salt = Config::get('app.web_salt');
if (empty($account) || empty($password)) {
throw new ServiceException('请提供账号或密码!');
}
$user = User::where('account', $account)->with(['userRelation' => function($query) {
$query->where('status', UserRelation::STATUS_ACTIVE);
}])->find();
if (empty($user) || $user->password != md5(md5($password . $user->salt) . $web_salt)) {
throw new ServiceException('账号不存在或密码错误!');
}
if ($user->status == User::STATUS_INVALID) {
throw new ServiceException('账号不可用!');
}
$user->login_time = time();
$user->login_ip = Request::ip();
$user->save();
$user_data = $user->toArray();
unset($user_data['password']);
unset($user_data['salt']);
unset($user_data['fd']);
$token = hash_hmac('sha256', json_encode($user_data), $web_salt);
Cache::set($token, $user);
$user_token = UserToken::where('uid', $user['id'])->find();
$user_token = $user_token ?: new UserToken();
$user_token->uid = $user['id'];
$user_token->token = $token;
$user_token->expire = time() + 3600 * 24; // 一天有效期
$user_token->save();
return JsonReturn::success('登录成功!', ['token' => $token]);
}
}
}