Files
2024-07-12 22:44:33 +08:00

584 lines
16 KiB
PHP

<?php
declare(strict_types=1);
// +----------------------------------------------------------------------
// | swiftAdmin 极速开发框架 [基于ThinkPHP6开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2030 http://www.swiftadmin.net
// +----------------------------------------------------------------------
// | swiftAdmin.net High Speed Development Framework
// +----------------------------------------------------------------------
// | Author: meystack <coolsec@foxmail.com> MIT License Code
// +----------------------------------------------------------------------
namespace app\index\controller;
use app\common\exception\OperateException;
use app\common\library\ResultCode;
use app\common\library\Upload;
use app\common\model\system\User as UserModel;
use app\common\model\system\UserGroup;
use app\common\model\system\UserLog;
use app\common\model\system\UserNotice;
use app\common\service\user\UserService;
use app\common\validate\system\User as UserValidate;
use app\HomeController;
use PHPMailer\PHPMailer\Exception;
use system\Random;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Event;
use think\response\Json;
use think\response\View;
class User extends HomeController
{
/**
* 鉴权控制器
*/
public bool $needLogin = true;
/**
* 超时时间
*/
public int $expire = 604800;
/**
* 非登录鉴权方法f
*/
public array $noNeedLogin = ['login', 'register', 'forgot', 'ajaxLogin', 'mobileLogin', 'scanLogin', 'scanTicket'];
// 初始化函数
public function initialize()
{
parent::initialize();
$this->model = new UserModel();
$template = root_path('app/index/view');
app()->view->config(['view_path' => $template]);
}
/**
* 用户中心
*/
public function index(): View
{
// 未读短消息
$unread = UserNotice::where('user_id', $this->userId)->where('status', 0)->count();
return view('', [
'unread' => $unread,
]);
}
/**
* 用户控制台
* @return View
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
*/
public function center(): View
{
// 邀请的好友
$inviteList = $this->model->where('invite_id', $this->userId)
->limit(9)->field('id,nickname,url,avatar')
->order('id desc')
->select()
->toArray();
// 我发表的主题
$postsList = [];
// 获取用户组列表
$userGroup = UserGroup::find($this->userInfo['group_id']);
return $this->view('', [
'userGroup' => $userGroup,
'inviteList' => $inviteList,
'postsList' => $postsList,
]);
}
/**
* 用户资料
* @return View
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
* @throws OperateException
*/
public function profile(): View
{
if (request()->isPost()) {
$post = input('post.');
validate(UserValidate::class)->scene('nickname')->check($post);
UserService::editProfile($post, $this->userId);
return $this->success('更新资料成功');
}
return view('', [
'user' => UserModel::find($this->userId),
]);
}
/**
* 用户注册
* @return View
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
* @throws OperateException
*/
public function register(): View
{
if (request()->isPost()) {
$post = request()->post();
validate(UserValidate::class)->scene('register')->check($post);
UserService::register($post);
return $this->success('注册成功', (string)url("/user/index"));
}
return view('/user/register', [
'style' => saenv('user_register'),
]);
}
/**
* 用户登录
* @return View
* @throws OperateException
*/
public function login(): View
{
if (request()->isPost()) {
$nickname = input('nickname');
$password = input('pwd');
validate(UserValidate::class)->scene('login')->check([
'nickname' => $nickname,
'pwd' => $password
]);
UserService::accountLogin($nickname, $password);
return $this->success('登录成功', (string)url('/'));
}
return view('/user/login', [
'referer' => request()->server('HTTP_REFERER', '/'),
]);
}
/**
* 手机登录
* @return View
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
* @throws OperateException
*/
public function mobileLogin(): View
{
if (request()->isPost()) {
$mobile = input('mobile');
$captcha = input('captcha');
validate(UserValidate::class)->scene('mobile')->check([
'mobile' => $mobile,
'captcha' => $captcha
]);
UserService::mobileLogin($mobile, $captcha);
return $this->success('登录成功', (string)url('/'));
}
return $this->error('非法请求');
}
/**
* ajax登录
* @return View
*/
public function ajaxLogin(): View
{
return $this->view('', ['referer' => $this->referer]);
}
/**
* 用户扫码登录
* @return View
*/
public function scanLogin(): View
{
if (request()->isAjax()) {
if (!Event::hasListener('scanLoginBefore')) {
return $this->error('请安装扫码登录插件');
}
try {
$result = Event::trigger('scanLoginBefore', input(), true) ?? [];
$ticket = $result['ticket'] ?? time();
$qrcode = $result['qrcode'] ?? '/static/images/qrcode-qun.png';
} catch (\Throwable $e) {
return $this->error($e->getMessage());
}
return $this->success('获取成功', '/', ['ticket' => $ticket, 'qrcode' => $qrcode]);
}
return $this->error('非法请求');
}
/**
* 扫码登录
* @return Json
*/
public function scanTicket(): Json
{
if (request()->isPost()) {
$data = request()->param();
try {
$result = Event::trigger('scanLoginAfter', $data, true) ?? [];
if (!isset($result['code']) || $result['code'] != 200) {
throw new \Exception($result['msg'] ?: '登录异常');
}
} catch (\Throwable $e) {
return $this->error($e->getMessage());
}
return $this->success('登录成功', url('/') . '?ticket=' . input('ticket/s'));
}
return $this->error('缺少参数');
}
/**
* 修改密码
* @return View
* @throws OperateException
*/
public function changePwd(): View
{
if (request()->isPost()) {
$post = input('post.');
UserService::changePwd($post, $this->userId);
return $this->success('修改密码成功!');
}
return view();
}
/**
* 找回密码
* @return View
* @throws OperateException
*/
public function forgot(): View
{
if (request()->isPost()) {
$post = input('post.');
UserService::forgotPwd($post);
return $this->success('修改密码成功!');
}
return $this->view();
}
/**
* 消息列表
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
*/
public function message(): View
{
if (request()->isAjax()) {
$page = input('page/d', 1);
$limit = input('limit/d', 1);
$status = input('status', 'all');
$where[] = ['user_id', '=', $this->userId];
if ($status !== 'all') {
$where[] = ['status', '=', $status];
}
list($list, $count) = UserService::listMessage($limit, $page, $where);
return $this->success('查询成功', "", $list, $count);
}
return view('/user/message');
}
/**
* 查看消息
* @return View
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
* @throws OperateException
*/
public function viewMessage(): View
{
$id = input('id/d', 0);
$result = UserService::viewMessage($id, $this->userId);
return view('message_view', [
'msgInfo' => $result['msgInfo'],
'unread' => $result['unread'],
]);
}
/**
* 批量操作消息
* @return View
* @throws OperateException
*/
public function batchMessage(): View
{
if (\request()->isPost()) {
$ids = input('id');
$type = input('type', 'del');
UserService::batchMessage($ids, $type, $this->userId);
return $this->success('操作成功');
}
return $this->error('非法操作');
}
/**
* 我的邀请
* @return View
*/
public function invite(): View
{
$inviteList = $this->model->where('invite_id', $this->userId)
->limit(50)->field('id,nickname,url,avatar')
->order('id desc')
->select()
->toArray();
return $this->view('', ['inviteList' => $inviteList]);
}
/**
* 申请APP_KEY
*/
public function appid()
{
if (request()->isPost()) {
$data['id'] = $this->userId;
$data['app_id'] = 10000 + $this->userId;
$data['app_secret'] = Random::alpha(22);
if ($this->model->update($data)) {
return $this->success();
}
return $this->error();
}
return $this->error('非法请求');
}
/**
* 修改邮箱地址
* @return View
* @throws Exception|OperateException
*/
public function changeEmail(): View
{
if (request()->isPost()) {
$email = safe_input('email');
$captcha = safe_input('captcha');
$event = safe_input('event');
UserService::changeEmail($email, $captcha, $event, $this->userId);
return $this->success('修改邮箱成功!');
}
return $this->view();
}
/**
* 修改手机号
* @return View
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
* @throws OperateException
*/
public function changeMobile(): View
{
if (request()->isPost()) {
$mobile = safe_input('mobile');
$captcha = safe_input('captcha');
$event = safe_input('event');
UserService::changeMobile($mobile, $captcha, $event, $this->userId);
return $this->success('修改手机号成功!');
}
return $this->view();
}
/**
* 用户登录日志
* @return View
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
*/
public function loginLog(): View
{
if (request()->isAjax()) {
// 获取数据
$page = input('page', 1);
$limit = input('limit', 1);
$where[] = ['login_id', '=', $this->userId];
$count = UserLog::where($where)->count();
$page = ($count <= $limit) ? 1 : $page;
$list = UserLog::where($where)->order('id', 'desc')->limit((int)$limit)->page((int)$page)->select()->toArray();
return $this->success('查询成功', "", $list, $count);
}
return view('/user/login_log');
}
/**
* 实名认证
* @return View
*/
public function certification(): View
{
if (request()->isPost()) {
$name = input('name');
$mobile = input('mobile');
$idCard = input('idCard');
$captcha = input('captcha');
// 判断验证码
if (!captcha_check($captcha)) {
return $this->error('验证码错误!');
}
if (!empty($this->userInfo['prove'])) {
return $this->error('您已经实名认证过了!');
}
try {
// 对接API接口
// 更新系统认证信息
$this->model->where('id', $this->userId)->update([
'prove' => 1,
'name' => $name,
'idCard' => $idCard,
'mobile' => $mobile,
'prove_time' => date('Y-m-d H:i:s', time())
]);
} catch (\Exception $e) {
return $this->error('实名认证失败,请联系管理员');
}
return $this->success('实名认证成功!');
}
return view('/user/certification', ['prove' => $this->userInfo['prove']]);
}
/**
* 设置密保
* @return View
*/
public function protection(): View
{
$validate = [
'你家的宠物叫啥?',
'你的幸运数字是?',
'你不想上班的理由是?',
];
if (request()->isPost()) {
$question = safe_input('question/s');
$answer = safe_input('answer/s');
if (!$question || !$answer) {
return $this->error('设置失败');
}
if (!in_array($question, $validate)) {
$question = current($validate);
}
try {
$this->model->update([
'question' => $question,
'answer' => $answer
], ['id' => $this->userId]);
} catch (\Throwable $th) {
return $this->error();
}
return $this->success();
}
return $this->view('', [
'validate' => $validate
]);
}
/**
* 安全配置中心
* @return View
*/
public function security(): View
{
$maxProgress = 6;
$thisProgress = 1;
if ($this->userInfo['email']) {
$thisProgress++;
}
if ($this->userInfo['mobile']) {
$thisProgress++;
}
if ($this->userInfo['answer']) {
$thisProgress++;
}
if ($this->userInfo['wechat']) {
$thisProgress++;
}
// 计算比例
$progress = (($thisProgress / $maxProgress) * 100);
return $this->view('', ['progress' => $progress]);
}
/**
* 用户头像上传
* @return Json
* @throws \Exception
*/
public function avatar()
{
if (request()->isPost()) {
$response = Upload::instance()->upload();
if (empty($response)) {
return $this->error(Upload::instance()->getError());
}
$avatar = $response['url'] . '?' . Random::alpha(12);
$result = $this->model->where('id', $this->userId)->update(['avatar' => $avatar]);
if (!empty($result)) {
return json($response);
}
}
return $this->error('上传失败');
}
/**
* 单文件上传函数
* @return Json
* @throws \Exception
*/
public function upload(): Json
{
if (request()->isPost()) {
$response = Upload::instance()->upload();
if (empty($response)) {
return $this->error(Upload::instance()->getError());
}
return json($response);
}
return json(ResultCode::SUCCESS);
}
}