Compare commits

..

12 commits

17 changed files with 484 additions and 129 deletions

2
.gitignore vendored
View file

@ -18,8 +18,10 @@
/public/storage
/storage/*.key
/storage/pail
/storage/dbbackups
/vendor
Homestead.json
Homestead.yaml
Thumbs.db
CLAUDE.md
.junie

View file

@ -1,59 +1,8 @@
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
## Movie Night API
<p align="center">
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
</p>
## About Laravel
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
Laravel is accessible, powerful, and provides tools required for large, robust applications.
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework. You can also check out [Laravel Learn](https://laravel.com/learn), where you will be guided through building a modern Laravel application.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains thousands of video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
## Laravel Sponsors
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the [Laravel Partners program](https://partners.laravel.com).
### Premium Partners
- **[Vehikl](https://vehikl.com)**
- **[Tighten Co.](https://tighten.co)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Curotec](https://www.curotec.com/services/technologies/laravel)**
- **[DevSquad](https://devsquad.com/hire-laravel-developers)**
- **[Redberry](https://redberry.international/laravel-development)**
- **[Active Logic](https://activelogic.com)**
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
Backend API for [Movie Night](https://github.com/tiradoe/movie-night-web)
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).
The Movie Night API is open-sourced software licensed under
the [AGPL License](https://opensource.org/licenses/agpl-3-0).

View file

@ -0,0 +1,226 @@
<?php
namespace App\Console\Commands;
use App\Models\Movie;
use App\Models\MovieList;
use App\Models\Schedule;
use App\Models\Showing;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class DjangoImport extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mn:django_import';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Imports data from Django version of Movie Night from exported table CSVs. Nobody else should need this.';
private $csvPath = 'dbbackups/';
/**
* Execute the console command.
*/
public function handle()
{
$this->wipeTables();
$this->importMovies();
$this->importMovielists();
$this->importMovieListMovies();
$this->importSchedules();
$this->importShowings();
}
private function wipeTables()
{
$this->info('Truncating tables...');
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
DB::table('movie_movie_list')->truncate();
DB::table('movies')->truncate();
DB::table('movie_lists')->truncate();
DB::table('schedules')->truncate();
DB::table('showings')->truncate();
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
}
private function importMovies($fileName = 'moviemanager_movies.csv'): void
{
$this->info('Importing movies...');
$file = fopen(storage_path($this->csvPath.$fileName), 'r');
if (! $file) {
$this->error('File not found: '.$fileName);
return;
}
// Skip the header row
fgetcsv($file);
while (($row = fgetcsv($file)) !== false) {
Movie::forceCreate([
'id' => $row[0],
'title' => $row[1],
'imdb_id' => $row[2],
'year' => $row[3],
'director' => $row[4],
'actors' => $row[5],
'plot' => $row[6],
'genre' => $row[7],
'mpaa_rating' => $row[8],
'critic_scores' => $this->parsePythonList($row[9]),
'poster' => $row[10],
'added_by' => $row[11],
]);
}
fclose($file);
}
/**
* Convert a Python-style list string (single-quoted) to a PHP array.
*
* @return array<int, array<string, string>>
*/
private function parsePythonList(string $value): array
{
if (empty($value) || $value === '[]') {
return [];
}
$json = str_replace("'", '"', $value);
if (str_starts_with($json, '{')) {
// Fixes incorrect key for Source in some older data
$json = str_replace('Score', 'Source', $json);
$json = '['.$json.']';
}
$decoded = json_decode($json, true);
if (is_array($decoded)) {
return $decoded;
} elseif (is_string($decoded)) {
return [$decoded];
}
return [];
}
private function importMovielists($fileName = 'moviemanager_movielist.csv'): void
{
$this->info('Importing Movie Lists...');
$file = fopen(storage_path($this->csvPath.$fileName), 'r');
if (! $file) {
$this->error('File not found: '.$fileName);
return;
}
// Skip the header row
fgetcsv($file);
while (($row = fgetcsv($file)) !== false) {
MovieList::create([
'name' => $row[1],
'is_public' => $row[2] === 't' ? true : false,
'slug' => Str::slug($row[1]),
'owner' => $row[3],
]);
}
fclose($file);
}
private function importMovieListMovies($fileName = 'moviemanager_movielist_movies.csv'): void
{
$this->info('Importing movie_list_movies...');
$file = fopen(storage_path($this->csvPath.$fileName), 'r');
if (! $file) {
$this->error('File not found: '.$fileName);
return;
}
// Skip the header row
fgetcsv($file);
while (($row = fgetcsv($file)) !== false) {
$movieList = MovieList::find($row[1]);
$movie = Movie::find($row[2]);
if ($movieList && $movie) {
$movieList->movies()->attach($movie);
} else {
$this->error('Movie or MovieList not found. Movie ID: '.$row[2].', MovieList ID: '.$row[1]);
}
}
fclose($file);
}
private function importSchedules($fileName = 'moviemanager_schedule.csv'): void
{
$this->info('Importing schedules...');
$file = fopen(storage_path($this->csvPath.$fileName), 'r');
if (! $file) {
$this->error('File not found: '.$fileName);
return;
}
// Skip the header row
fgetcsv($file);
while (($row = fgetcsv($file)) !== false) {
Schedule::create([
'name' => $row[1],
'is_public' => $row[2] === 't' ? true : false,
'slug' => $row[3],
'owner' => $row[4],
]);
}
fclose($file);
}
private function importShowings($fileName = 'moviemanager_showing.csv'): void
{
$this->info('Importing showings...');
$file = fopen(storage_path($this->csvPath.$fileName), 'r');
if (! $file) {
$this->error('File not found: '.$fileName);
return;
}
// Skip the header row
fgetcsv($file);
while (($row = fgetcsv($file)) !== false) {
Showing::create([
'is_public' => $row[1] === 't' ? true : false,
'showtime' => Carbon::parse($row[2]),
'movie_id' => $row[3],
'owner_id' => $row[4],
'schedule_id' => $row[5],
]);
}
fclose($file);
}
}

View file

@ -4,6 +4,7 @@ namespace App\Http\Controllers;
use App\Http\Requests\LoginRequest;
use App\Http\Requests\PasswordResetRequest;
use App\Http\Requests\PasswordResetWithTokenRequest;
use App\Http\Requests\RegisterRequest;
use App\Models\Invitation;
use App\Models\Role;
@ -11,6 +12,7 @@ use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
class AuthController extends Controller
@ -54,6 +56,24 @@ class AuthController extends Controller
}
public function resetPassword(PasswordResetRequest $request)
{
$user = Auth::user();
$validatedData = $request->validated();
if (! Hash::check($request->current_password, $user->password)) {
return response()->json(['message' => 'Current password is incorrect.'], 422);
}
try {
$user->forceFill(['password' => $validatedData['password']])->save();
} catch (\Exception $e) {
return response()->json(['message' => 'Password reset failed.'], 400);
}
return response()->json(['message' => 'Password reset successful.']);
}
public function resetPasswordWithToken(PasswordResetWithTokenRequest $request)
{
$updatedUser = null;

View file

@ -8,7 +8,6 @@ use App\Http\Resources\MovieListResource;
use App\Interfaces\MovieDbInterface;
use App\Models\Movie;
use App\Models\MovieList;
use App\Models\Role;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
@ -34,18 +33,18 @@ class MovieListController extends Controller
/**
* Store a newly created resource in storage.
*/
public function store(CreateMovieListRequest $request)
public function store(CreateMovieListRequest $request): MovieListResource
{
$this->authorize('create', MovieList::class);
$validated = $request->validated();
$movieList = MovieList::create([
...$validated,
'owner' => auth()->id(),
'owner' => Auth::user()->id,
'slug' => Str::slug($validated['name']),
]);
return response()->json($movieList, 201);
return MovieListResource::make($movieList);
}
/**
@ -77,12 +76,13 @@ class MovieListController extends Controller
$this->authorize('delete', $movieList);
$movieList->delete();
return response()->json(['message', 'Movie list deleted successfully'], 204);
return response()->json(['message' => 'Movie list deleted successfully'], 204);
}
public function addMovie(MovieDbInterface $movieDb, Request $request, MovieList $movieList): MovieListResource
{
$this->authorize('update', $movieList);
$this->authorize('editMovies', $movieList);
$movieResult = $movieDb->find($request->input('movie')['imdbId'], ['type' => 'imdb']);
$movie = Movie::where('imdb_id', $movieResult->imdbId)->first();
@ -94,7 +94,7 @@ class MovieListController extends Controller
public function removeMovie(MovieList $movieList, Movie $movie): MovieListResource
{
$this->authorize('update', $movieList);
$this->authorize('editMovies', $movieList);
$movieList->movies()->detach($movie);
$movieList->load('movies');
@ -104,13 +104,13 @@ class MovieListController extends Controller
public function updateCollaboratorRole(Request $request, MovieList $movieList, User $collaborator): MovieListResource|JsonResponse
{
$this->authorize('update', $movieList);
$request->validate([
'role_id' => 'required|exists:roles,id',
]);
$adminRole = Role::query()->where('name', 'ADMIN')->first()?->id;
if (Auth::id() !== $movieList->owner && ! Auth::user()->hasRole($movieList, $adminRole)) {
return response()->json(['message' => 'Unauthorized'], 403);
if (Auth::id() === $collaborator->getKey()) {
return response()->json(['message' => 'Cannot edit own role'], 422);
}
$movieList->collaborators()->updateExistingPivot($collaborator->getKey(), [

View file

@ -24,8 +24,7 @@ class PasswordResetRequest extends FormRequest
return [
'password' => 'required|string|min:8|confirmed',
'password_confirmation' => 'string',
'token' => 'required|string',
'email' => 'required|email|exists:users,email',
'current_password' => 'required|string',
];
}
}

View file

@ -0,0 +1,31 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class PasswordResetWithTokenRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'password' => 'required|string|min:8|confirmed',
'password_confirmation' => 'string',
'token' => 'required|string',
'email' => 'required|email|exists:users,email',
];
}
}

View file

@ -27,7 +27,7 @@ class MovieList extends Model
return $this->belongsToMany(Movie::class);
}
public function getUserRole($userId): string
public function getUserRole($userId): ?string
{
$roleId = $this->collaborators()
->where('user_id', $userId)

15
app/Models/Schedule.php Normal file
View file

@ -0,0 +1,15 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Schedule extends Model
{
protected $fillable = [
'name',
'is_public',
'slug',
'owner',
];
}

16
app/Models/Showing.php Normal file
View file

@ -0,0 +1,16 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Showing extends Model
{
protected $fillable = [
'is_public',
'showtime',
'movie_id',
'owner_id',
'schedule_id',
];
}

View file

@ -15,6 +15,10 @@ class User extends Authenticatable
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable;
private static $adminRoleId = null;
private static $editorRoleId = null;
/**
* The attributes that are mass assignable.
*
@ -45,10 +49,33 @@ class User extends Authenticatable
return $this->hasMany(MovieList::class, 'owner');
}
public function hasRole(MovieList $movieList, int $role): bool
public function isListEditor(MovieList $movieList): bool
{
self::$editorRoleId = Role::query()
->where('name', 'EDITOR')
->value('id');
return $this->isListAdmin($movieList) || $this->hasRole($movieList->getKey(), self::$editorRoleId);
}
public function isListAdmin(MovieList $movieList): bool
{
self::$adminRoleId = Role::query()
->where('name', 'ADMIN')
->value('id');
return $this->isListOwner($movieList) || $this->hasRole($movieList->getKey(), self::$adminRoleId);
}
public function isListOwner(MovieList $movieList): bool
{
return $this->getKey() === $movieList->owner;
}
public function hasRole(int $movieListId, int $role): bool
{
return $this->sharedLists()
->wherePivot('movie_list_id', $movieList->id)
->wherePivot('movie_list_id', $movieListId)
->wherePivot('role_id', $role)
->exists();
}
@ -60,6 +87,13 @@ class User extends Authenticatable
->withTimestamps();
}
public function roles(): BelongsToMany
{
return $this->belongsToMany(Role::class, 'movie_list_user')
->withPivot('role_id')
->withTimestamps();
}
/**
* Get the attributes that should be cast.
*

View file

@ -22,29 +22,23 @@ class MovieListPolicy
public function view(User $user, MovieList $movieList): bool
{
if ($movieList->owner === $user->getKey() || $movieList->isPublic || $user->sharedLists->contains($movieList)) {
return true;
}
return false;
}
public function update(User $user, MovieList $movieList): bool
{
if ($movieList->owner === $user->getKey()) {
return true;
}
return false;
return $movieList->is_public
|| $user->isListOwner($movieList)
|| $user->sharedLists->contains($movieList);
}
public function delete(User $user, MovieList $movieList): bool
{
if ($movieList->owner === $user->getKey()) {
return true;
return $user->isListOwner($movieList);
}
return false;
public function editMovies(User $user, MovieList $movieList): bool
{
return $user->isListEditor($movieList);
}
public function update(User $user, MovieList $movieList): bool
{
return $user->isListAdmin($movieList);
}
}

View file

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('schedules', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->boolean('is_public')->default(false);
$table->string('slug');
$table->foreignId('owner')->constrained('users')->cascadeOnDelete();
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('schedules');
}
};

View file

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('showings', function (Blueprint $table) {
$table->id();
$table->dateTime('showtime');
$table->boolean('is_public')->default(false);
$table->foreignId('movie_id')->constrained('movies')->cascadeOnDelete();
$table->foreignId('owner_id')->constrained('users')->cascadeOnDelete();
$table->foreignId('schedule_id')->constrained('schedules')->cascadeOnDelete();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('showings');
}
};

View file

@ -10,14 +10,15 @@ use Illuminate\Support\Facades\Route;
// Public auth routes
Route::post('/register', [AuthController::class, 'register'])->name('auth.register');
Route::post('/login', [AuthController::class, 'login'])->name('auth.login');
Route::post('/reset-password', [AuthController::class, 'resetPassword'])->name('auth.reset-password');
Route::post('/forgot-password', [AuthController::class, 'forgotPassword'])->name('auth.forgot-password');
Route::post('/reset-password-token', [AuthController::class, 'resetPasswordWithToken'])->name('auth.reset-password-with-token');
Route::get('/invitations/{token}/accept', [InvitationController::class, 'accept'])->name('invitations.accept');
Route::get('/invitations/{token}/decline', [InvitationController::class, 'decline'])->name('invitations.decline');
// Authenticated routes
Route::middleware('auth:sanctum')->group(function () {
Route::post('/logout', [AuthController::class, 'logout'])->name('auth.logout');
Route::post('/reset-password', [AuthController::class, 'resetPassword'])->name('auth.reset-password');
// Invitations
Route::post('/invitations', [InvitationController::class, 'store'])->name('invitations.store');

View file

@ -16,8 +16,6 @@ class AuthTest extends TestCase
->postJson('/api/register', [
'username' => 'johndoe',
'email' => 'john@example.com',
'password' => 'password123',
'password_confirmation' => 'password123',
]);
$response->assertStatus(201)
@ -31,12 +29,10 @@ class AuthTest extends TestCase
$response = $this->postJson('/api/register', [
'username' => '',
'email' => 'not-an-email',
'password' => 'short',
'password_confirmation' => 'mismatch',
]);
$response->assertStatus(422)
->assertJsonValidationErrors(['username', 'email', 'password']);
->assertJsonValidationErrors(['username', 'email']);
}
public function test_registration_fails_with_duplicate_email(): void
@ -46,8 +42,6 @@ class AuthTest extends TestCase
$response = $this->postJson('/api/register', [
'username' => 'johndoe',
'email' => 'john@example.com',
'password' => 'password123',
'password_confirmation' => 'password123',
]);
$response->assertStatus(422)
@ -61,8 +55,6 @@ class AuthTest extends TestCase
$response = $this->postJson('/api/register', [
'username' => 'johndoe',
'email' => 'john@example.com',
'password' => 'password123',
'password_confirmation' => 'password123',
]);
$response->assertStatus(422)
@ -111,18 +103,8 @@ class AuthTest extends TestCase
public function test_unauthenticated_user_cannot_access_protected_routes(): void
{
$response = $this->getJson('/api/user');
$response = $this->getJson('/api/roles');
$response->assertStatus(401);
}
public function test_authenticated_user_can_access_user_endpoint(): void
{
$user = User::factory()->create();
$response = $this->actingAs($user)->getJson('/api/user');
$response->assertOk()
->assertJsonFragment(['email' => $user->email]);
}
}

View file

@ -14,28 +14,11 @@ class UpdateCollaboratorRoleTest extends TestCase
use RefreshDatabase;
private Role $adminRole;
private Role $editorRole;
private Role $viewerRole;
protected function setUp(): void
{
parent::setUp();
$this->seed(DatabaseSeeder::class);
$this->adminRole = Role::where('name', 'ADMIN')->first();
$this->editorRole = Role::where('name', 'EDITOR')->first();
$this->viewerRole = Role::where('name', 'VIEWER')->first();
}
private function makeList(User $owner): MovieList
{
return MovieList::create([
'name' => 'Test List',
'owner' => $owner->getKey(),
'slug' => 'test-list',
]);
}
public function test_role_id_is_required(): void
{
$owner = User::factory()->create();
@ -50,6 +33,15 @@ class UpdateCollaboratorRoleTest extends TestCase
->assertJsonValidationErrors(['role_id']);
}
private function makeList(User $owner): MovieList
{
return MovieList::create([
'name' => 'Test List',
'owner' => $owner->getKey(),
'slug' => 'test-list',
]);
}
public function test_role_id_must_exist_in_roles_table(): void
{
$owner = User::factory()->create();
@ -125,6 +117,26 @@ class UpdateCollaboratorRoleTest extends TestCase
$response->assertForbidden();
}
public function test_admin_collaborator_cannot_update_own_role(): void
{
$owner = User::factory()->create();
$admin = User::factory()->create();
$movieList = $this->makeList($owner);
$movieList->collaborators()->attach($admin, ['role_id' => $this->adminRole->getKey()]);
$response = $this->actingAs($admin)
->patchJson("/api/movielists/{$movieList->getKey()}/collaborators/{$admin->getKey()}", [
'role_id' => $this->editorRole->getKey(),
]);
$response->assertUnprocessable();
$this->assertDatabaseHas('movie_list_user', [
'movie_list_id' => $movieList->getKey(),
'user_id' => $admin->getKey(),
'role_id' => $this->adminRole->getKey(),
]);
}
public function test_unrelated_user_cannot_update_collaborator_role(): void
{
$owner = User::factory()->create();
@ -140,4 +152,14 @@ class UpdateCollaboratorRoleTest extends TestCase
$response->assertForbidden();
}
protected function setUp(): void
{
parent::setUp();
$this->seed(DatabaseSeeder::class);
$this->adminRole = Role::where('name', 'ADMIN')->first();
$this->editorRole = Role::where('name', 'EDITOR')->first();
$this->viewerRole = Role::where('name', 'VIEWER')->first();
}
}