Files
nexusphp/app/Repositories/UserRepository.php

469 lines
18 KiB
PHP
Raw Normal View History

2021-04-17 19:01:33 +08:00
<?php
namespace App\Repositories;
2022-07-23 23:35:43 +08:00
use App\Exceptions\InsufficientPermissionException;
2021-05-14 20:41:43 +08:00
use App\Exceptions\NexusException;
2021-04-27 19:13:32 +08:00
use App\Http\Resources\ExamUserResource;
use App\Http\Resources\UserResource;
use App\Models\ExamUser;
use App\Models\Message;
2021-04-17 19:01:33 +08:00
use App\Models\Setting;
use App\Models\User;
2021-05-14 02:11:57 +08:00
use App\Models\UserBanLog;
2022-08-10 17:38:05 +08:00
use App\Models\UserMeta;
2022-08-10 23:38:10 +08:00
use App\Models\UsernameChangeLog;
use Carbon\Carbon;
2021-05-12 13:45:00 +08:00
use Illuminate\Database\Eloquent\Builder;
2022-08-10 17:38:05 +08:00
use Illuminate\Support\Arr;
2022-07-18 01:37:50 +08:00
use Illuminate\Support\Facades\Auth;
2021-05-14 02:11:57 +08:00
use Illuminate\Support\Facades\DB;
use Nexus\Database\NexusDB;
2021-04-17 19:01:33 +08:00
class UserRepository extends BaseRepository
{
public function getList(array $params)
{
$query = User::query();
2022-02-25 18:09:31 +08:00
if (!empty($params['id'])) {
$query->where('id', $params['id']);
}
if (!empty($params['username'])) {
$query->where('username', 'like',"%{$params['username']}%");
}
if (!empty($params['email'])) {
$query->where('email', 'like',"%{$params['email']}%");
}
if (isset($params['class']) && $params['class'] !== '') {
2022-03-04 16:16:56 +08:00
$query->where('class', $params['class']);
}
2021-04-17 19:01:33 +08:00
list($sortField, $sortType) = $this->getSortFieldAndType($params);
$query->orderBy($sortField, $sortType);
return $query->paginate();
}
2021-04-23 01:28:41 +08:00
public function getBase($id)
{
$user = User::query()->findOrFail($id, ['id', 'username', 'email', 'avatar']);
return $user;
}
2021-04-27 19:13:32 +08:00
public function getDetail($id)
{
2021-05-12 13:45:00 +08:00
$with = [
2022-01-19 23:54:55 +08:00
'inviter' => function ($query) {return $query->select(User::$commonFields);},
'valid_medals'
2021-05-12 13:45:00 +08:00
];
2022-05-13 17:55:49 +08:00
$user = User::query()->with($with)->findOrFail($id);
2021-04-27 19:13:32 +08:00
$userResource = new UserResource($user);
$baseInfo = $userResource->response()->getData(true)['data'];
$examRep = new ExamRepository();
2022-04-17 16:38:44 +08:00
$examProgress = $examRep->getUserExamProgress($id, ExamUser::STATUS_NORMAL);
2021-04-27 19:13:32 +08:00
if ($examProgress) {
$examResource = new ExamUserResource($examProgress);
$examInfo = $examResource->response()->getData(true)['data'];
} else {
$examInfo = null;
}
return [
'base_info' => $baseInfo,
'exam_info' => $examInfo,
];
}
/**
* create user
*
* @param array $params must: username, email, password, password_confirmation. optional: id, class
* @return User
*/
2021-04-17 19:01:33 +08:00
public function store(array $params)
{
$password = $params['password'];
if ($password != $params['password_confirmation']) {
throw new \InvalidArgumentException("password confirmation != password");
}
$username = $params['username'];
if (!validusername($username)) {
2022-08-10 17:38:05 +08:00
throw new \InvalidArgumentException("Invalid username: $username");
}
$email = htmlspecialchars(trim($params['email']));
$email = safe_email($email);
if (!check_email($email)) {
2022-08-10 17:38:05 +08:00
throw new \InvalidArgumentException("Invalid email: $email");
}
if (User::query()->where('email', $email)->exists()) {
throw new \InvalidArgumentException("The email address: $email is already in use");
}
2022-05-15 02:31:05 +08:00
if (User::query()->where('username', $username)->exists()) {
throw new \InvalidArgumentException("The username: $username is already in use");
}
if (mb_strlen($password) < 6 || mb_strlen($password) > 40) {
2022-08-10 17:38:05 +08:00
throw new \InvalidArgumentException("Invalid password: $password, it should be more than 6 character and less than 40 character");
}
$class = !empty($params['class']) ? intval($params['class']) : User::CLASS_USER;
if (!isset(User::$classes[$class])) {
throw new \InvalidArgumentException("Invalid user class: $class");
}
2021-04-17 19:01:33 +08:00
$setting = Setting::get('main');
$secret = mksecret();
$passhash = md5($secret . $password . $secret);
$data = [
'username' => $username,
'email' => $email,
2021-04-17 19:01:33 +08:00
'secret' => $secret,
'editsecret' => '',
'passhash' => $passhash,
'stylesheet' => $setting['defstylesheet'],
'added' => now()->toDateTimeString(),
'status' => User::STATUS_CONFIRMED,
'class' => $class
2021-04-17 19:01:33 +08:00
];
$user = new User($data);
2022-06-27 01:39:01 +08:00
if (!empty($params['id'])) {
if (User::query()->where('id', $params['id'])->exists()) {
throw new \InvalidArgumentException("uid: {$params['id']} already exists.");
}
do_log("[CREATE_USER], specific id: " . $params['id']);
$user->id = $params['id'];
}
$user->save();
2021-04-17 19:01:33 +08:00
return $user;
}
2021-05-14 20:41:43 +08:00
public function resetPassword($id, $password, $passwordConfirmation)
2021-04-17 19:01:33 +08:00
{
if ($password != $passwordConfirmation) {
throw new \InvalidArgumentException("password confirmation != password");
}
2022-07-18 01:37:50 +08:00
$user = User::query()->findOrFail($id, ['id', 'username', 'class']);
2022-07-23 23:35:43 +08:00
$this->checkPermission(Auth::user(), $user);
2021-04-17 19:01:33 +08:00
$secret = mksecret();
$passhash = md5($secret . $password . $secret);
$update = [
'secret' => $secret,
'passhash' => $passhash,
];
$user->update($update);
2021-05-14 20:41:43 +08:00
return true;
2021-04-17 19:01:33 +08:00
}
2021-04-19 20:13:21 +08:00
public function listClass()
{
$out = [];
foreach(User::$classes as $key => $value) {
$out[(string)$key] = $value['text'];
}
return $out;
}
2021-05-14 02:11:57 +08:00
public function disableUser(User $operator, $uid, $reason)
{
$targetUser = User::query()->findOrFail($uid, ['id', 'enabled', 'username', 'class']);
2021-05-14 20:41:43 +08:00
if ($targetUser->enabled == User::ENABLED_NO) {
throw new NexusException('Already disabled !');
}
2022-07-23 23:35:43 +08:00
$this->checkPermission($operator, $targetUser);
2021-05-14 02:11:57 +08:00
$banLog = [
'uid' => $uid,
'username' => $targetUser->username,
'reason' => $reason,
'operator' => $operator->id,
];
$modCommentText = sprintf("%s - Disable by %s, reason: %s.", now()->format('Y-m-d'), $operator->username, $reason);
2021-05-14 02:11:57 +08:00
DB::transaction(function () use ($targetUser, $banLog, $modCommentText) {
2021-05-14 20:41:43 +08:00
$targetUser->updateWithModComment(['enabled' => User::ENABLED_NO], $modCommentText);
2021-05-14 02:11:57 +08:00
UserBanLog::query()->insert($banLog);
});
2021-05-14 20:41:43 +08:00
do_log("user: $uid, $modCommentText");
2022-07-30 15:06:51 +08:00
$this->clearCache($targetUser);
2021-05-14 20:41:43 +08:00
return true;
}
public function enableUser(User $operator, $uid, $reason = '')
2021-05-14 20:41:43 +08:00
{
2021-05-15 12:59:59 +08:00
$targetUser = User::query()->findOrFail($uid, ['id', 'enabled', 'username', 'class']);
2021-05-14 20:41:43 +08:00
if ($targetUser->enabled == User::ENABLED_YES) {
throw new NexusException('Already enabled !');
2021-05-14 20:41:43 +08:00
}
2022-07-23 23:35:43 +08:00
$this->checkPermission($operator, $targetUser);
2021-05-15 12:59:59 +08:00
$update = [
'enabled' => User::ENABLED_YES
];
if ($targetUser->class == User::CLASS_PEASANT) {
// warn users until 30 days
$until = now()->addDays(30)->toDateTimeString();
$update['leechwarn'] = 'yes';
$update['leechwarnuntil'] = $until;
} else {
$update['leechwarn'] = 'no';
$update['leechwarnuntil'] = null;
}
$modCommentText = sprintf("%s - Enable by %s, reason: %s", now()->format('Y-m-d'), $operator->username, $reason);
2021-05-15 12:59:59 +08:00
$targetUser->updateWithModComment($update, $modCommentText);
do_log("user: $uid, $modCommentText, update: " . nexus_json_encode($update));
2022-07-30 15:06:51 +08:00
$this->clearCache($targetUser);
2021-05-14 02:11:57 +08:00
return true;
}
2021-05-14 20:41:43 +08:00
public function getInviteInfo($id)
{
$user = User::query()->findOrFail($id, ['id']);
return $user->invitee_code()->with('inviter_user')->first();
}
public function getModComment($id)
{
$user = User::query()->findOrFail($id, ['modcomment']);
return $user->modcomment;
}
2022-01-19 23:54:55 +08:00
public function incrementDecrement(User $operator, $uid, $action, $field, $value, $reason = ''): bool
{
$fieldMap = [
'uploaded' => 'uploaded',
'downloaded' => 'downloaded',
'seedbonus' => 'seedbonus',
'invites' => 'invites',
'attendance_card' => 'attendance_card',
];
if (!isset($fieldMap[$field])) {
throw new \InvalidArgumentException("Invalid field: $field, only support: " . implode(', ', array_keys($fieldMap)));
}
$sourceField = $fieldMap[$field];
$targetUser = User::query()->findOrFail($uid, User::$commonFields);
2022-07-23 23:35:43 +08:00
$this->checkPermission($operator, $targetUser);
$old = $targetUser->{$sourceField};
$valueAtomic = $value;
$formatSize = false;
if (in_array($field, ['uploaded', 'downloaded'])) {
//Frontend unit: GB
$valueAtomic = $value * 1024 * 1024 * 1024;
$formatSize = true;
}
if ($action == 'Increment') {
$new = $old + abs($valueAtomic);
} elseif ($action == 'Decrement') {
$new = $old - abs($valueAtomic);
} else {
throw new \InvalidArgumentException("Invalid action: $action.");
}
if ($new < 0) {
throw new NexusException("New value($new) lte 0");
}
//for administrator, use english
$modCommentText = nexus_trans('message.field_value_change_message_body', [
'field' => nexus_trans("user.labels.$sourceField", [], 'en'),
'operator' => $operator->username,
'old' => $formatSize ? mksize($old) : $old,
'new' => $formatSize ? mksize($new) : $new,
'reason' => $reason,
], 'en');
$modCommentText = date('Y-m-d') . " - $modCommentText";
do_log("user: $uid, $modCommentText", 'alert');
$update = [
$sourceField => $new,
'modcomment' => NexusDB::raw("if(modcomment = '', '$modCommentText', concat_ws('\n', '$modCommentText', modcomment))"),
];
$locale = $targetUser->locale;
$fieldLabel = nexus_trans("user.labels.$sourceField", [], $locale);
$msg = nexus_trans('message.field_value_change_message_body', [
'field' => $fieldLabel,
'operator' => $operator->username,
'old' => $formatSize ? mksize($old) : $old,
'new' => $formatSize ? mksize($new) : $new,
'reason' => $reason,
], $locale);
$message = [
'sender' => 0,
'receiver' => $targetUser->id,
'subject' => nexus_trans("message.field_value_change_message_subject", ['field' => $fieldLabel], $locale),
'msg' => $msg,
'added' => Carbon::now(),
];
NexusDB::transaction(function () use ($uid, $sourceField, $old, $new, $update, $message) {
$affectedRows = User::query()
->where('id', $uid)
->where($sourceField, $old)
->update($update)
;
if ($affectedRows != 1) {
throw new \RuntimeException("Change fail, affected rows != 1($affectedRows)");
}
Message::query()->insert($message);
});
2022-07-30 15:06:51 +08:00
$this->clearCache($targetUser);
return true;
}
2022-05-13 15:56:09 +08:00
public function removeLeechWarn($operator, $uid): bool
{
2022-07-23 23:35:43 +08:00
$operator = $this->getUser($operator);
2022-05-13 15:56:09 +08:00
$user = User::query()->findOrFail($uid, User::$commonFields);
2022-07-23 23:35:43 +08:00
$this->checkPermission($operator, $user);
2022-07-30 15:06:51 +08:00
$this->clearCache($user);
2022-05-13 15:56:09 +08:00
$user->leechwarn = 'no';
$user->leechwarnuntil = null;
return $user->save();
}
2022-05-13 17:55:49 +08:00
public function removeTwoStepAuthentication($operator, $uid): bool
{
if (!$operator->canAccessAdmin()) {
throw new \RuntimeException("No permission.");
}
$user = User::query()->findOrFail($uid, User::$commonFields);
2022-07-23 23:35:43 +08:00
$this->checkPermission($operator, $user);
2022-07-30 15:06:51 +08:00
$this->clearCache($user);
2022-05-13 17:55:49 +08:00
$user->two_step_secret = '';
return $user->save();
}
2022-07-23 23:35:43 +08:00
2022-07-30 15:06:51 +08:00
public function updateDownloadPrivileges($operator, $user, $status)
2022-07-23 23:35:43 +08:00
{
2022-07-30 15:06:51 +08:00
if (!in_array($status, ['yes', 'no'])) {
throw new \InvalidArgumentException("Invalid status: $status");
}
$targetUser = $this->getUser($user);
2022-07-23 23:35:43 +08:00
$operator = $this->getUser($operator);
2022-07-30 15:06:51 +08:00
$operatorUsername = 'System';
if ($operator) {
$operatorUsername = $operator->username;
$this->checkPermission($operator, $targetUser);
}
2022-07-23 23:35:43 +08:00
$message = [
'added' => now(),
'receiver' => $targetUser->id,
];
2022-07-30 15:06:51 +08:00
if ($status == 'no') {
2022-07-23 23:35:43 +08:00
$update = ['downloadpos' => 'no'];
2022-07-30 15:06:51 +08:00
$modComment = date('Y-m-d') . " - Download disable by " . $operatorUsername;
2022-07-23 23:35:43 +08:00
$message['subject'] = nexus_trans('message.download_disable.subject', [], $targetUser->locale);
2022-07-30 15:06:51 +08:00
$message['msg'] = nexus_trans('message.download_disable.body', ['operator' => $operatorUsername], $targetUser->locale);
2022-07-23 23:35:43 +08:00
} else {
$update = ['downloadpos' => 'yes'];
2022-07-30 15:06:51 +08:00
$modComment = date('Y-m-d') . " - Download enable by " . $operatorUsername;
2022-07-23 23:35:43 +08:00
$message['subject'] = nexus_trans('message.download_enable.subject', [], $targetUser->locale);
2022-07-30 15:06:51 +08:00
$message['msg'] = nexus_trans('message.download_enable.body', ['operator' => $operatorUsername], $targetUser->locale);
2022-07-23 23:35:43 +08:00
}
return NexusDB::transaction(function () use ($targetUser, $update, $modComment, $message) {
Message::add($message);
2022-07-30 15:06:51 +08:00
$this->clearCache($targetUser);
2022-07-23 23:35:43 +08:00
return $targetUser->updateWithModComment($update, $modComment);
});
}
private function checkPermission($operator, User $user, $minAuthClass = 'authority.prfmanage')
2022-05-13 17:55:49 +08:00
{
2022-07-23 23:35:43 +08:00
$operator = $this->getUser($operator);
2022-08-10 23:38:10 +08:00
if ($operator->id == $user->id) {
return;
}
2022-07-23 23:35:43 +08:00
$classRequire = Setting::get($minAuthClass);
if ($operator->class < $classRequire || $operator->class <= $user->class) {
throw new InsufficientPermissionException();
2022-05-13 17:55:49 +08:00
}
}
2022-07-30 15:06:51 +08:00
private function clearCache(User $user)
{
2022-08-10 17:38:05 +08:00
clear_user_cache($user->id, $user->passkey);
2022-07-30 15:06:51 +08:00
}
2022-08-10 17:38:05 +08:00
public function listMetas($uid, $metaKeys = [], $valid = true)
{
$query = UserMeta::query()->where('uid', $uid);
if (!empty($metaKeys)) {
$query->whereIn('meta_key', Arr::wrap($metaKeys));
}
if ($valid) {
$query->where('status', 0)->where(function (Builder $query) {
$query->whereNull('deadline')->orWhere('deadline', '>=', now());
});
}
return $query->get()->groupBy('meta_key');
}
public function consumeBenefit($uid, array $params): bool
{
$metaKey = $params['meta_key'];
$records = $this->listMetas($uid, $metaKey);
if (!$records->has($metaKey)) {
throw new \RuntimeException("User do not has this metaKey: $metaKey");
}
/** @var UserMeta $meta */
$meta = $records->get($metaKey)->first();
$user = User::query()->findOrFail($uid, User::$commonFields);
if ($metaKey == UserMeta::META_KEY_CHANGE_USERNAME) {
NexusDB::transaction(function () use ($user, $meta, $params) {
2022-08-10 23:38:10 +08:00
$this->changeUsername($user, UsernameChangeLog::CHANGE_TYPE_USER, $user, $params['username']);
2022-08-10 17:38:05 +08:00
$meta->delete();
clear_user_cache($user->id, $user->passkey);
});
return true;
}
throw new \InvalidArgumentException("Invalid meta_key: $metaKey");
}
2022-08-10 23:38:10 +08:00
private function changeUsername($operator, $changeType, $targetUser, $newUsername): bool
2022-08-10 17:38:05 +08:00
{
2022-08-10 23:38:10 +08:00
$operator = $this->getUser($operator);
$targetUser = $this->getUser($targetUser);
$this->checkPermission($operator, $targetUser);
if ($targetUser->username == $newUsername) {
2022-08-10 17:38:05 +08:00
throw new \RuntimeException("New username can not be the same with current username !");
}
2022-08-10 23:38:10 +08:00
$strWidth = mb_strwidth($newUsername);
if ($strWidth < 4 || $strWidth > 20) {
throw new \InvalidArgumentException("Invalid username, maybe too long or too short");
2022-08-10 17:38:05 +08:00
}
2022-08-10 23:38:10 +08:00
if (User::query()->where('username', $newUsername)->where('id', '!=', $targetUser->id)->exists()) {
2022-08-10 17:38:05 +08:00
throw new \RuntimeException("Username: $newUsername already exists !");
}
2022-08-10 23:38:10 +08:00
$changeLog = [
'uid' => $targetUser->id,
'operator' => $operator->username,
'change_type' => $changeType,
'username_old' => $targetUser->username,
'username_new' => $newUsername
];
NexusDB::transaction(function () use ($operator, $changeType,$targetUser, $changeLog) {
$targetUser->usernameChangeLogs()->create($changeLog);
$targetUser->username = $changeLog['username_new'];
$targetUser->save();
2022-08-10 17:38:05 +08:00
});
return true;
}
2022-01-19 23:54:55 +08:00
2022-08-11 17:12:36 +08:00
public function addMeta($user, array $metaData, array $keyExistsUpdates = [])
{
$user = $this->getUser($user);
$metaKey = $metaData['meta_key'];
$allowMultiple = UserMeta::$metaKeys[$metaKey]['multiple'];
if ($allowMultiple) {
//Allow multiple, just insert
$result = $user->metas()->create($metaData);
} else {
$metaExists = $user->metas()->where('meta_key', $metaKey)->first();
if (!$metaExists) {
$result = $user->metas()->create($metaData);
} else {
if (empty($keyExistsUpdates)) {
$keyExistsUpdates = ['updated_at' => now()];
}
$result = $metaExists->update($keyExistsUpdates);
}
}
if ($result) {
clear_user_cache($user->id, $user->passkey);
}
return $result;
}
2022-01-19 23:54:55 +08:00
2021-04-17 19:01:33 +08:00
}