Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ add friend checkin to api #2717

Merged
merged 42 commits into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from 26 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
3ac8dd6
no message
MrKrisKrisu Jun 28, 2024
999061e
Merge branch 'develop' into dev-ks/friend-checkin
MrKrisKrisu Jul 1, 2024
ef2e57a
add policy and tests
MrKrisKrisu Jul 1, 2024
ab5c343
improve api docs
MrKrisKrisu Jul 1, 2024
de4f78e
no message
MrKrisKrisu Jul 1, 2024
41bba53
no message
MrKrisKrisu Jul 1, 2024
3513671
:white_check_mark: Adding tests.
MrKrisKrisu Jul 1, 2024
4f8833b
fix notification selection
MrKrisKrisu Jul 1, 2024
cf5ed27
add endpoints for trusted users
MrKrisKrisu Jul 1, 2024
886fde7
Merge branch 'develop' into dev-ks/friend-checkin
MrKrisKrisu Jul 1, 2024
e0f7836
add expire date
MrKrisKrisu Jul 2, 2024
730254f
Merge remote-tracking branch 'origin/dev-ks/friend-checkin' into dev-…
MrKrisKrisu Jul 2, 2024
f2996d5
pagination test (failing)
MrKrisKrisu Jul 2, 2024
62b109d
Merge branch 'refs/heads/develop' into dev-ks/friend-checkin
MrKrisKrisu Jul 5, 2024
5b772a1
fix docs
MrKrisKrisu Jul 5, 2024
dff6835
improve validator with max array attributes
MrKrisKrisu Jul 5, 2024
12f9e48
add operationId to api docs
MrKrisKrisu Jul 5, 2024
53d441f
fix api attribute
MrKrisKrisu Jul 5, 2024
5e6e0fc
add self api attribute
MrKrisKrisu Jul 5, 2024
7284573
Merge branch 'refs/heads/develop' into dev-ks/friend-checkin
MrKrisKrisu Jul 7, 2024
6ad92d2
add operationId
MrKrisKrisu Jul 7, 2024
f610b0c
fix http response
MrKrisKrisu Jul 7, 2024
914a895
fix parameter
MrKrisKrisu Jul 7, 2024
c237d80
fix parameter
MrKrisKrisu Jul 7, 2024
d159ba0
fix parameter
MrKrisKrisu Jul 7, 2024
8c754bb
generate docs
MrKrisKrisu Jul 7, 2024
0a2e96d
Update app/Http/Controllers/API/v1/TrustedUserController.php
MrKrisKrisu Jul 13, 2024
336c4ac
Update app/Http/Controllers/API/v1/TrustedUserController.php
MrKrisKrisu Jul 13, 2024
2d324cc
Update app/Http/Controllers/API/v1/TrustedUserController.php
MrKrisKrisu Jul 13, 2024
ef35152
Merge remote-tracking branch 'origin/develop' into dev-ks/friend-checkin
HerrLevin Jul 28, 2024
e062656
Adapt with hydrator
HerrLevin Jul 30, 2024
8045273
fix tests
HerrLevin Jul 30, 2024
fb246ee
fix "fix tests"
MrKrisKrisu Jul 31, 2024
f641419
Merge branch 'develop' into dev-ks/friend-checkin
MrKrisKrisu Jul 31, 2024
10cf410
Merge branch 'develop' into dev-ks/friend-checkin
MrKrisKrisu Aug 1, 2024
3924e34
:test_tube: add failing test
MrKrisKrisu Aug 2, 2024
97f1b9d
:white_check_mark: test follow relationships
MrKrisKrisu Aug 2, 2024
4f0bd01
rename api attributes
MrKrisKrisu Aug 2, 2024
bb2edcf
rename api attributes
MrKrisKrisu Aug 2, 2024
d74d42b
add 403 docs
MrKrisKrisu Aug 2, 2024
5e546ef
Merge branch 'develop' into dev-ks/friend-checkin
MrKrisKrisu Aug 2, 2024
41f654a
update 403 docs
MrKrisKrisu Aug 2, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/Console/Commands/DatabaseCleaner/DatabaseCleaner.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public function handle(): int {
$this->call(Polylines::class);
$this->call(PolylinesBrouter::class);
$this->call(User::class);
$this->call(TrustedUser::class);
$this->call(Trips::class);

$this->call('queue-monitor:purge', ['--beforeDays' => 7]);
Expand Down
18 changes: 18 additions & 0 deletions app/Console/Commands/DatabaseCleaner/TrustedUser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace App\Console\Commands\DatabaseCleaner;

use App\Models\TrustedUser as TrustedUserModel;
use Illuminate\Console\Command;

class TrustedUser extends Command
{
protected $signature = 'app:clean-db:trusted-user';
protected $description = 'Find and delete expired trusted users from database';

public function handle(): int {
$affectedRows = TrustedUserModel::where('expires_at', '<', now())->delete();
$this->info($affectedRows . ' expired trusted users deleted.');
return 0;
}
}
20 changes: 20 additions & 0 deletions app/Enum/User/FriendCheckinSetting.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);

namespace App\Enum\User;

/**
* @OA\Schema(
* title="FriendCheckinSetting",
* type="string",
* enum={"forbidden", "friends", "list"},
* example="forbidden",
* )
*/
enum FriendCheckinSetting: string
{
case FORBIDDEN = 'forbidden'; // default
case FRIENDS = 'friends'; // user who are following each other
case LIST = 'list'; // specific list of users
}

9 changes: 9 additions & 0 deletions app/Http/Controllers/API/v1/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace App\Http\Controllers\API\v1;

use App\Models\OAuthClient;
use App\Models\User;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Throwable;
Expand Down Expand Up @@ -133,4 +135,11 @@ public static function getCurrentOAuthClient(): OAuthClient|null {
return null;
}
}

protected function getUserOrSelf(string|int $userIdOrSelf): Authenticatable {
if ($userIdOrSelf === 'self') {
return auth()->user();
}
return User::findOrFail($userIdOrSelf);
}
}
139 changes: 62 additions & 77 deletions app/Http/Controllers/API/v1/SettingsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use App\Enum\MapProvider;
use App\Enum\MastodonVisibility;
use App\Enum\StatusVisibility;
use App\Enum\User\FriendCheckinSetting;
use App\Exceptions\RateLimitExceededException;
use App\Http\Controllers\Backend\SettingsController as BackendSettingsController;
use App\Http\Resources\UserProfileSettingsResource;
Expand Down Expand Up @@ -62,6 +63,67 @@ public function updateMail(Request $request): UserProfileSettingsResource|JsonRe
}
}

/**
* @OA\Put(
* path="/settings/profile",
MrKrisKrisu marked this conversation as resolved.
Show resolved Hide resolved
* operationId="putProfileSettings",
* tags={"Settings"},
* summary="Update the current user's profile settings",
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* @OA\Property(property="username", type="string", example="Gertrud123", maxLength=25),
* @OA\Property(property="displayName", type="string", example="Gertrud", maxLength=50),
* @OA\Property(property="privateProfile", type="boolean", example=false, nullable=true),
* @OA\Property(property="preventIndex", type="boolean", example=false, nullable=true),
* @OA\Property(property="privacyHideDays", type="integer", example=1, nullable=true),
* @OA\Property(property="defaultStatusVisibility", type="integer", nullable=true, @OA\Schema(ref="#/components/schemas/StatusVisibility")),
* @OA\Property(property="mastodonVisibility", type="integer", nullable=true, @OA\Schema(ref="#/components/schemas/MastodonVisibility")),
* @OA\Property(property="mapProvider", type="string", nullable=true, @OA\Schema(ref="#/components/schemas/MapProvider"), example="cargo"),
* @OA\Property(property="friendCheckin", type="string", nullable=true, @OA\Schema(ref="#/components/schemas/FriendCheckinSetting"), example="forbidden")
* )
* ),
* @OA\Response(
* response=200,
* description="Success",
* @OA\JsonContent(
* @OA\Property(property="data", type="object", ref="#/components/schemas/UserProfileSettings")
* )
* ),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=422, description="Unprocessable Entity"),
* @OA\Response(response=400, description="Bad Request"),
* security={{"passport": {"write-settings"}}, {"token": {}}}
* )
*/
public function updateSettings(Request $request): UserProfileSettingsResource|JsonResponse {
$validated = $request->validate([
'username' => [
'required', 'string', 'max:25', 'regex:/^[a-zA-Z0-9_]*$/'
],
'displayName' => ['required', 'string', 'max:50'],
'privateProfile' => ['boolean', 'nullable'],
'preventIndex' => ['boolean', 'nullable'],
'privacyHideDays' => ['integer', 'nullable', 'gte:1'],
'defaultStatusVisibility' => [
'nullable',
new Enum(StatusVisibility::class),
],
'mastodonVisibility' => [
'nullable',
new Enum(MastodonVisibility::class),
],
'mapProvider' => ['nullable', new Enum(MapProvider::class)],
'friendCheckin' => ['nullable', new Enum(FriendCheckinSetting::class)]
MrKrisKrisu marked this conversation as resolved.
Show resolved Hide resolved
]);

try {
return new UserProfileSettingsResource(BackendSettingsController::updateSettings($validated));
} catch (RateLimitExceededException) {
return $this->sendError(error: __('email.verification.too-many-requests'), code: 400);
}
}

public function resendMail(): void {
try {
auth()->user()->sendEmailVerificationNotification();
Expand Down Expand Up @@ -95,83 +157,6 @@ public function updatePassword(Request $request): UserProfileSettingsResource|Js
}
}

/**
* @OA\Put(
* path="/settings/profile",
* tags={"Settings"},
* summary="Update the current user's profile settings",
* description="Update the current user's profile settings",
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* @OA\Property(property="username", type="string", example="gertrud123", maxLength=25),
* @OA\Property(property="displayName", type="string", example="Gertrud", maxLength=50),
* @OA\Property(property="privateProfile", type="boolean", example=false, nullable=true),
* @OA\Property(property="preventIndex", type="boolean", example=false, nullable=true),
* @OA\Property(property="privacyHideDays", type="integer", example=1, nullable=true),
* @OA\Property(
* property="defaultStatusVisibility",
* type="integer",
* nullable=true,
* @OA\Schema(ref="#/components/schemas/StatusVisibility")
* ),
* @OA\Property(
* property="mastodonVisibility",
* type="integer",
* nullable=true,
* @OA\Schema(ref="#/components/schemas/MastodonVisibility")
* ),
* @OA\Property(
* property="mapProvider",
* type="string",
* nullable=true,
* @OA\Schema(ref="#/components/schemas/MapProvider")
* )
* )
* ),
* @OA\Response(
* response=200,
* description="Success",
* @OA\JsonContent(
* @OA\Property(property="data", type="object", ref="#/components/schemas/UserProfileSettings")
* )
* ),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=422, description="Unprocessable Entity"),
* @OA\Response(response=400, description="Bad Request"),
* security={
* {"passport": {"write-settings"}}, {"token": {}}
* }
* )
*/
public function updateSettings(Request $request): UserProfileSettingsResource|JsonResponse {
$validated = $request->validate([
'username' => ['required',
'string',
'max:25',
'regex:/^[a-zA-Z0-9_]*$/'],
'displayName' => ['required', 'string', 'max:50'],
'privateProfile' => ['boolean', 'nullable'],
'preventIndex' => ['boolean', 'nullable'],
'privacyHideDays' => ['integer', 'nullable', 'gte:1'],
'defaultStatusVisibility' => [
'nullable',
new Enum(StatusVisibility::class),
],
'mastodonVisibility' => [
'nullable',
new Enum(MastodonVisibility::class),
],
'mapProvider' => ['nullable', new Enum(MapProvider::class)],
]);

try {
return new UserProfileSettingsResource(BackendSettingsController::updateSettings($validated));
} catch (RateLimitExceededException) {
return $this->sendError(error: __('email.verification.too-many-requests'), code: 400);
}
}

/**
* Undocumented and unofficial API Endpoint
*
Expand Down
54 changes: 43 additions & 11 deletions app/Http/Controllers/API/v1/TransportController.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
use App\Exceptions\HafasException;
use App\Exceptions\NotConnectedException;
use App\Exceptions\StationNotOnTripException;
use App\Http\Controllers\Backend\Transport\HomeController;
use App\Http\Controllers\Backend\Transport\StationController;
use App\Http\Controllers\Backend\Transport\TrainCheckinController;
use App\Http\Controllers\HafasController;
Expand All @@ -21,6 +20,8 @@
use App\Http\Resources\TripResource;
use App\Models\Event;
use App\Models\Station;
use App\Models\User;
use App\Notifications\YouHaveBeenCheckedIn;
use Carbon\Carbon;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
Expand Down Expand Up @@ -329,9 +330,9 @@ public function getNextStationByCoordinates(Request $request): JsonResponse {
/**
* @OA\Post(
* path="/trains/checkin",
* operationId="createTrainCheckin",
* operationId="createCheckin",
* tags={"Checkin"},
* summary="Create a checkin",
* summary="Check in to a trip.",
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(ref="#/components/schemas/CheckinRequestBody")
Expand All @@ -342,11 +343,11 @@ public function getNextStationByCoordinates(Request $request): JsonResponse {
* @OA\JsonContent(ref="#/components/schemas/CheckinResponse")
* ),
* @OA\Response(response=400, description="Bad request"),
* @OA\Response(response=409, description="Checkin collision"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Forbidden"),
* @OA\Response(response=409, description="Checkin collision"),
* security={
* {"passport": {"create-statuses"}}, {"token": {}}
*
* }
* )
*
Expand All @@ -370,25 +371,40 @@ public function create(Request $request): JsonResponse {
'destination' => ['required', 'numeric'],
'departure' => ['required', 'date'],
'arrival' => ['required', 'date'],
'force' => ['nullable', 'boolean']
'force' => ['nullable', 'boolean'],
'with' => ['nullable', 'array', 'max:10'],
]);
if (isset($validated['with'])) {
$withUsers = User::whereIn('id', $validated['with'])->get();
foreach ($withUsers as $user) {
if (!Auth::user()?->can('checkin', $user)) {
return $this->sendError('You are not allowed to checkin for the given user.', 403);
HerrLevin marked this conversation as resolved.
Show resolved Hide resolved
}
}
}

try {
$searchKey = empty($validated['ibnr']) ? 'id' : 'ibnr';
$trip = HafasController::getHafasTrip($validated['tripId'], $validated['lineName']);
MrKrisKrisu marked this conversation as resolved.
Show resolved Hide resolved
$originStation = Station::where($searchKey, $validated['start'])->first();
$departure = Carbon::parse($validated['departure']);
$destinationStation = Station::where($searchKey, $validated['destination'])->first();
$arrival = Carbon::parse($validated['arrival']);
$travelReason = Business::tryFrom($validated['business'] ?? Business::PRIVATE->value);
$event = isset($validated['eventId']) ? Event::find($validated['eventId']) : null;

// check in the authenticated user
HerrLevin marked this conversation as resolved.
Show resolved Hide resolved
$checkinResponse = TrainCheckinController::checkin(
MrKrisKrisu marked this conversation as resolved.
Show resolved Hide resolved
user: Auth::user(),
trip: HafasController::getHafasTrip($validated['tripId'], $validated['lineName']),
trip: $trip,
origin: $originStation,
departure: Carbon::parse($validated['departure']),
departure: $departure,
destination: $destinationStation,
arrival: Carbon::parse($validated['arrival']),
travelReason: Business::tryFrom($validated['business'] ?? Business::PRIVATE->value),
arrival: $arrival,
travelReason: $travelReason,
visibility: StatusVisibility::tryFrom($validated['visibility'] ?? StatusVisibility::PUBLIC->value),
body: $validated['body'] ?? null,
event: isset($validated['eventId']) ? Event::find($validated['eventId']) : null,
event: $event,
force: isset($validated['force']) && $validated['force'],
postOnMastodon: isset($validated['toot']) && $validated['toot'],
shouldChain: isset($validated['chainPost']) && $validated['chainPost']
Expand All @@ -408,6 +424,22 @@ public function create(Request $request): JsonResponse {
'additional' => null, //unused old attribute (not removed so this isn't breaking)
];

// if isset, check in the other users with their default values
foreach ($withUsers ?? [] as $user) {
$checkin = TrainCheckinController::checkin(
HerrLevin marked this conversation as resolved.
Show resolved Hide resolved
user: $user,
trip: $trip,
origin: $originStation,
departure: $departure,
destination: $destinationStation,
arrival: $arrival,
travelReason: $travelReason,
visibility: $user->default_status_visibility,
event: $event,
);
$user->notify(new YouHaveBeenCheckedIn($checkin['status'], auth()->user()));
}

return $this->sendResponse($checkinResponse, 201); //ToDo: Check if documented structure has changed
} catch (CheckInCollisionException $exception) {
return $this->sendError([
Expand Down
Loading
Loading