coupon-admin/app/controller/Login.php

284 lines
9.9 KiB
PHP
Raw Normal View History

2021-11-18 17:57:04 +08:00
<?php
namespace app\controller;
use app\exception\RepositoryException;
use app\repository\CommonRepository;
use app\validate\Account as VAccount;
use app\repository\AccountRepository;
use Exception;
use Overtrue\Socialite\SocialiteManager;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Config;
use think\facade\Log;
use think\response\Json;
use think\response\Redirect;
use think\response\View;
class Login extends Base
{
protected $middleware = ['csrf'];
public function index()
{
$referer = input('param.url/s', '/');
$referer = urldecode($referer);
$auth = session('frontend_auth');
if ($auth) {
return $this->redirect($referer);
}
session('login_return', $referer);
if ($this->request->isPost()) {
$username = input('post.username/s');
$password = input('post.password/s');
if (empty($username) || empty($password)) {
return $this->json(4001, '参数错误');
}
$user = AccountRepository::getInstance()->infoByPhone($username);
if (!$user) {
if (!$user = AccountRepository::getInstance()->infoByUsername($username)) {
return $this->json(4002, '账号或密码错误');
}
}
if ($user['password'] !== md5($password)) {
return $this->json(4003, '密码错误若手机验证码方式注册初始密码为手机号后6位');
}
unset($user['password']);
session('frontend_auth', $user->toArray());
$referer = session('login_return') ?? '/';
return $this->json(0, 'success', ['login_return' => $referer]);
}
return $this->view();
}
public function phone()
{
$referer = input('param.url/s', '/');
$referer = urldecode($referer);
$auth = session('frontend_auth');
if ($auth) {
return $this->redirect($referer);
}
session('login_return', $referer);
if ($this->request->isPost()) {
$phone = input('post.phone/s');
$code = input('post.code/s');
if (empty($phone) || empty($code)) {
return $this->json(4001, '参数错误');
}
if (!CommonRepository::getInstance()->checkSms($phone, $code, CommonRepository::SMS_TYPE_LOGIN)) {
return $this->json(4002, '短信验证码错误');
}
$user = AccountRepository::getInstance()->infoByPhone($phone);
if (!$user) {
$password = substr(trim($phone), -6);
$data['mobile'] = $phone;
$data['password'] = md5($password);
$data['nickname'] = trim($phone);
$data['status'] = 'normal';
$data['created_at'] = date('Y-m-d H:i:s');
$user = AccountRepository::getInstance()->create($data);
}
session('frontend_auth', $user);
$referer = session('login_return') ?? '/';
return $this->json(0, 'success', ['login_return' => $referer]);
}
return $this->view();
}
/**
* 微信登录
*
* @return Redirect|View
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
* @throws RepositoryException
*/
public function wechat()
{
$code = input('code/s');
Config::load('extra/wechat', 'wechat');
$wechatConfig = config('wechat');
$referer = session('login_return') ?? '/';
if ($this->auth) {
return $this->redirect($referer);
} else {
if ($code) {
$config = [
'wechat' => [
'client_id' => $wechatConfig['openAppId'],
'client_secret' => $wechatConfig['openAppSecret'],
'redirect' => $wechatConfig['open_notify_url'],
],
];
$socialite = new SocialiteManager($config);
$user = $socialite->driver('wechat')->user();
$wechatUser = $user->getOriginal();
// $wechatUser = [
// 'openid' => 'o05Qy6rt1l7NOjrZsViC2bvS75j0',
// 'nickname' => '拙言',
// 'sex' => '1',
// 'language' => 'language',
// 'city' => 'chengdu ',
// 'province' => '四川',
// 'country' => '中国',
// 'headimgurl' => 'https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIZib13lH3Sicc1BO189ibaqohRtXr3OuHw3xSHibn611kaGmmLvppOD5hHyE5IJmicTDpdwCEDw4LF9Xw/132',
// 'unionid' => 'oIrzJv6Vk8s8Hg_rJuNB8muquziw',
// ];
if (empty($wechatUser)) {
}
$account = AccountRepository::getInstance()->findOneByWhere(['unionid' => $wechatUser['unionid']]);
$data = [];
$now = date('Y-m-d H:i:s');
if (!$account) {
//无账号 新建账号
$data = $wechatUser;
$data['created_at'] = $now;
$data['status'] = AccountRepository::STATUS_NORMAL;
$account = AccountRepository::getInstance()->create($wechatUser);
}
$data['login_ip'] = $this->request->ip();
$data['last_login'] = $now;
session('frontend_auth', $account->toArray());
$account->save($data);
if (empty($account['mobile'])) {
//没有手机号 跳转绑定
return $this->redirect('/login/binding');
}
return $this->redirect($referer);
}
}
$openAppId = $wechatConfig['openAppId'] ?? '';
$redirect = $wechatConfig['open_notify_url'] ?? '';
$this->data['redirect'] = urlencode($redirect);
$this->data['openAppId'] = $openAppId;
return $this->view();
}
/**
* 常规注册
*
* @throws Exception
*/
public function register(): Json
{
if ($this->request->isPost()) {
$post = input('post.');
$validate = new VAccount();
if (!$validate->scene('register')->check($post)) {
return $this->json(4001, $validate->getError());
}
if (!CommonRepository::getInstance()->checkSms($post['phone'], $post['code'], CommonRepository::SMS_TYPE_REGISTER)) {
return $this->json(4002, '验证码错误');
}
try {
AccountRepository::getInstance()->registerByNormal($post);
} catch (RepositoryException $e) {
return $this->json(4003, $e->getMessage());
} catch (Exception $e) {
Log::error(sprintf("[注册失败]%s:%s %s", $e->getFile(), $e->getLine(), $e->getMessage()));
return $this->json(5001, '注册失败');
}
return $this->json();
}
}
/**
* 发送注册验证码
*
* @return Json
*/
public function sms(): Json
{
$post = input('post.');
$validate = new VAccount();
if (!$validate->scene('send_sms')->check($post)) {
return $this->json(4001, $validate->getError());
}
if (CommonRepository::getInstance()->sendSms($post['phone'], $post['type'])) {
return $this->json();
}
return $this->json(4002, '验证码发送失败');
}
/**
* 绑定手机号
*
* @return Redirect|Json|View
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
* @throws RepositoryException
*/
public function binding()
{
if ($this->request->isPost()) {
$post = input('post.');
$validate = new VAccount();
if (!$validate->scene('binding')->check($post)) {
return $this->json(4001, $validate->getError());
}
if (!$account = AccountRepository::getInstance()->info($this->auth['id'] ?? 0)) {
return $this->json(4006, '请先登录');
}
if (!empty($account['mobile'])) {
return $this->json(4007, '您已绑定手机号,无需重复绑定!');
}
if (AccountRepository::getInstance()->infoByPhone($post['phone'])) {
return $this->json(4005, '该手机已绑定账号');
}
if (!CommonRepository::getInstance()->checkSms($post['phone'], $post['code'], CommonRepository::SMS_TYPE_BINDING)) {
return $this->json(4002, '验证码错误');
}
try {
$account->save(['mobile' => $post['phone']]);
} catch (RepositoryException $e) {
return $this->json(4003, $e->getMessage());
} catch (Exception $e) {
CommonRepository::log('绑定手机号失败', $e, 'error');
return $this->json(5001, '绑定手机号失败');
}
return $this->json();
} else {
if (!$account = AccountRepository::getInstance()->info($this->auth['id'] ?? 0)) {
return $this->redirect('/login');
}
if (!empty($account['mobile'])) {
return $this->redirect('/');
}
}
return $this->view();
}
}