/** * @param UploadAvatar $command * @return \Flarum\Core\Users\User * @throws \Flarum\Core\Exceptions\PermissionDeniedException */ public function handle(UploadAvatar $command) { $actor = $command->actor; $user = $this->users->findOrFail($command->userId); // Make sure the current user is allowed to edit the user profile. // This will let admins and the user themselves pass through, and // throw an exception otherwise. if ($actor->id !== $user->id) { $user->assertCan($actor, 'edit'); } $tmpFile = tempnam(sys_get_temp_dir(), 'avatar'); $command->file->moveTo($tmpFile); $manager = new ImageManager(); $manager->make($tmpFile)->fit(100, 100)->save(); event(new AvatarWillBeSaved($user, $actor, $tmpFile)); $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => $this->uploadDir]); if ($user->avatar_path && $mount->has($file = "target://{$user->avatar_path}")) { $mount->delete($file); } $uploadName = Str::lower(Str::quickRandom()) . '.jpg'; $user->changeAvatarPath($uploadName); $mount->move("source://" . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}"); $user->save(); $this->dispatchEventsFor($user); return $user; }
public static function addId($tag, UserRepository $users) { if ($id = $users->getIdForUsername(rawurlencode($tag->getAttribute('username')))) { $tag->setAttribute('id', $id); return true; } }
/** * Get a single user, ready to be serialized and assigned to the JsonApi * response. * * @param JsonApiRequest $request * @param Document $document * @return \Flarum\Core\Users\User */ protected function data(JsonApiRequest $request, Document $document) { $id = $request->get('id'); if (!is_numeric($id)) { $id = $this->users->getIdForUsername($id); } return $this->users->findOrFail($id, $request->actor); }
/** * @param EditUser $command * @return User * @throws \Flarum\Core\Exceptions\PermissionDeniedException */ public function handle(EditUser $command) { $actor = $command->actor; $data = $command->data; $user = $this->users->findOrFail($command->userId, $actor); $isSelf = $actor->id === $user->id; $attributes = array_get($data, 'attributes', []); $relationships = array_get($data, 'relationships', []); if (isset($attributes['username'])) { $user->assertCan($actor, 'edit'); $user->rename($attributes['username']); } if (isset($attributes['email'])) { if ($isSelf) { $user->requestEmailChange($attributes['email']); } else { $user->assertCan($actor, 'edit'); $user->changeEmail($attributes['email']); } } if (isset($attributes['password'])) { $user->assertCan($actor, 'edit'); $user->changePassword($attributes['password']); } if (isset($attributes['bio'])) { if (!$isSelf) { $user->assertCan($actor, 'edit'); } $user->changeBio($attributes['bio']); } if (!empty($attributes['readTime'])) { $this->assert($isSelf); $user->markAllAsRead(); } if (!empty($attributes['preferences'])) { $this->assert($isSelf); foreach ($attributes['preferences'] as $k => $v) { $user->setPreference($k, $v); } } if (isset($relationships['groups']['data']) && is_array($relationships['groups']['data'])) { $user->assertCan($actor, 'edit'); $newGroupIds = []; foreach ($relationships['groups']['data'] as $group) { if ($id = array_get($group, 'id')) { $newGroupIds[] = $id; } } $user->raise(new UserGroupsWereChanged($user, $user->groups()->get()->all())); User::saved(function ($user) use($newGroupIds) { $user->groups()->sync($newGroupIds); }); } event(new UserWillBeSaved($user, $actor, $data)); $user->save(); $this->dispatchEventsFor($user); return $user; }
/** * {@inheritdoc} */ protected function conditions(Search $search, array $matches, $negate) { if (!$search instanceof DiscussionSearch) { throw new LogicException('This gambit can only be applied on a DiscussionSearch'); } $username = trim($matches[1], '"'); $id = $this->users->getIdForUsername($username); $search->getQuery()->where('start_user_id', $negate ? '!=' : '=', $id); }
/** * @param DeleteUser $command * @return User * @throws \Flarum\Core\Exceptions\PermissionDeniedException */ public function handle(DeleteUser $command) { $actor = $command->actor; $user = $this->users->findOrFail($command->userId, $actor); $user->assertCan($actor, 'delete'); event(new UserWillBeDeleted($user, $actor, $command->data)); $user->delete(); $this->dispatchEventsFor($user); return $user; }
/** * @param Request $request * @param array $routeParams * @return JsonResponse|EmptyResponse */ public function handle(Request $request, array $routeParams = []) { $params = array_only($request->getAttributes(), ['identification', 'password']); $data = $this->apiClient->send(app('flarum.actor'), 'Flarum\\Api\\Actions\\TokenAction', $params)->getBody(); // TODO: The client needs to pass through exceptions(?) or the whole // response so we can look at the response code. For now if there isn't // any useful data we just assume it's a 401. if (isset($data->userId)) { // Extend the token's expiry to 2 weeks so that we can set a // remember cookie AccessToken::where('id', $data->token)->update(['expires_at' => new DateTime('+2 weeks')]); event(new UserLoggedIn($this->users->findOrFail($data->userId), $data->token)); return $this->withRememberCookie(new JsonResponse($data), $data->token); } else { return new EmptyResponse(401); } }
/** * @param RequestPasswordReset $command * @return \Flarum\Core\Users\User * @throws ModelNotFoundException */ public function handle(RequestPasswordReset $command) { $user = $this->users->findByEmail($command->email); if (!$user) { throw new ModelNotFoundException(); } $token = PasswordToken::generate($user->id); $token->save(); // TODO: Need to use UrlGenerator, but since this is part of core we // don't know that the forum routes will be loaded. Should the reset // password route be part of core?? $data = ['username' => $user->username, 'url' => Core::url() . '/reset/' . $token->id, 'forumTitle' => $this->settings->get('forum_title')]; $this->mailer->send(['text' => 'flarum::emails.resetPassword'], $data, function (Message $message) use($user) { $message->to($user->email); $message->subject('Reset Your Password'); }); return $user; }
/** * @param DeleteAvatar $command * @return \Flarum\Core\Users\User */ public function handle(DeleteAvatar $command) { $actor = $command->actor; $user = $this->users->findOrFail($command->userId); // Make sure the current user is allowed to edit the user profile. // This will let admins and the user themselves pass through, and // throw an exception otherwise. if ($actor->id !== $user->id) { $user->assertCan($actor, 'edit'); } $avatarPath = $user->avatar_path; $user->changeAvatarPath(null); event(new AvatarWillBeDeleted($user, $actor)); if ($this->uploadDir->has($avatarPath)) { $this->uploadDir->delete($avatarPath); } $user->save(); $this->dispatchEventsFor($user); return $user; }
/** * @param SearchCriteria $criteria * @param int|null $limit * @param int $offset * @param array $load An array of relationships to load on the results. * @return SearchResults */ public function search(SearchCriteria $criteria, $limit = null, $offset = 0, array $load = []) { $actor = $criteria->actor; $query = $this->users->query()->whereVisibleTo($actor); // Construct an object which represents this search for users. // Apply gambits to it, sort, and paging criteria. Also give extensions // an opportunity to modify it. $search = new UserSearch($query->getQuery(), $actor); $this->gambits->apply($search, $criteria->query); $this->applySort($search, $criteria->sort); $this->applyOffset($search, $offset); $this->applyLimit($search, $limit + 1); event(new UserSearchWillBePerformed($search, $criteria)); // Execute the search query and retrieve the results. We get one more // results than the user asked for, so that we can say if there are more // results. If there are, we will get rid of that extra result. $users = $query->get(); if ($areMoreResults = $limit > 0 && $users->count() > $limit) { $users->pop(); } $users->load($load); return new SearchResults($users, $areMoreResults); }
/** * {@inheritdoc} */ public function apply(Search $search, $bit) { $users = $this->users->getIdsForUsername($bit, $search->getActor()); $search->getQuery()->whereIn('id', $users); $search->setDefaultSort(['id' => $users]); }