Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/main' into 328-be-refactor-stude…
Browse files Browse the repository at this point in the history
…ntlanguageupdate-endpoint

# Conflicts:
#	routes/api/v1.php
  • Loading branch information
StephaneCarteaux committed Oct 16, 2024
2 parents 34a679e + 13c0563 commit caddaef
Show file tree
Hide file tree
Showing 14 changed files with 172 additions and 347 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class UpdateStudentProjectAnnotation
{
/**
* @OA\Put(
* path="/student/{studentId}/resume/projects/{projectId}",
* path="/student/{student}/resume/projects/{projectId}",
* operationId="updateStudentProject",
* tags={"Student -> Resume"},
* summary="Update a project for a student",
Expand All @@ -17,7 +17,7 @@ class UpdateStudentProjectAnnotation
* {"bearerAuth": {}}
* },
* @OA\Parameter(
* name="studentId",
* name="student",
* in="path",
* description="Student ID",
* required=true,
Expand All @@ -27,7 +27,7 @@ class UpdateStudentProjectAnnotation
* )
* ),
* @OA\Parameter(
* name="projectId",
* name="project",
* in="path",
* description="Project ID",
* required=true,
Expand Down Expand Up @@ -97,12 +97,12 @@ class UpdateStudentProjectAnnotation
* @OA\Property(
* property="message",
* type="string",
* example="Student not found"
* example="No query results for model [App\\Models\\Student] invalid_student_id']"
* ),
* @OA\Property(
* property="message2",
* type="string",
* example="Project not found"
* example="No query results for model [App\\Models\\Project] invalid_project_id'"
* )
* )
* ),
Expand All @@ -113,7 +113,7 @@ class UpdateStudentProjectAnnotation
* @OA\Property(
* property="message",
* type="string",
* example="Unauthorized"
* example="This action is unauthorized."
* )
* )
* ),
Expand All @@ -130,7 +130,5 @@ class UpdateStudentProjectAnnotation
* )
* )
*/
public function __invoke()
{
}
public function __invoke() {}
}
62 changes: 17 additions & 45 deletions app/Http/Controllers/api/Student/UpdateStudentImageController.php
Original file line number Diff line number Diff line change
@@ -1,63 +1,35 @@
<?php

declare(strict_types=1);

namespace App\Http\Controllers\api\Student;

use Illuminate\Http\{
JsonResponse,
Request
};
use Illuminate\Support\Facades\{
Log
};

use App\Models\Student;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Exceptions\StudentNotFoundException;
use App\Service\Student\UpdateStudentImageService;
use Illuminate\Support\Facades\Storage;
use App\Http\Requests\UpdateImageStudentRequest;


class UpdateStudentImageController extends Controller
{
private UpdateStudentImageService $updateStudentImageService;
private string $photo_infix = '.profile_photo.';
private string $photos_path = 'public/photos/';

public function __construct(UpdateStudentImageService $updateStudentImageService)
public function __invoke(UpdateImageStudentRequest $request, Student $student): JsonResponse
{
$this->updateStudentImageService = $updateStudentImageService;
}

public function __invoke(UpdateImageStudentRequest $request, string $studentID): JsonResponse
{

try {
$file = $request->file('photo');

$file = $request->file('photo');
$filename = $this->updateStudentImageService->createImageNameByStudentIDAndFileHash($studentID, $file->hashName());
$this->updateStudentImageService->storePhotoInStorageByFileName($file, $filename);
$this->updateStudentImageService->updateStudentImagePathInDatabaseByStudentID($studentID, $filename);
$filename = time() . '.' . $student->id . $this->photo_infix . $file->hashName();

if ($student->photo) {
Storage::delete($this->photos_path . $student->photo);
}

return response()->json([
'profile' => "La foto del perfil de l'estudiant s'actualitzat correctament"
], 200);
$file->storeAs($this->photos_path, $filename);

$student->photo = $filename;
$student->save();

} catch (StudentNotFoundException $e) {

Log::error('Exception:', [
'exception' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
return response()->json($e->getMessage(), 404);

} catch (\Exception $e) {

Log::error('Exception:', [
'exception' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
return response()->json('La foto del perfil de l\'estudiant no s\'ha pogut actualitzar, per favor intenteu-ho de nou', 500);

}
}
return response()->json(['message' => 'La imatge s\'ha actualitzat']);
}
}
49 changes: 13 additions & 36 deletions app/Http/Controllers/api/Student/UpdateStudentProjectController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,51 +4,28 @@

namespace App\Http\Controllers\api\Student;

use Exception;
use App\Http\Controllers\Controller;
use App\Service\Student\UpdateStudentProjectService;
use Illuminate\Http\JsonResponse;
use App\Http\Requests\UpdateStudentProjectRequest;
use App\Service\Student\StudentService;
use App\Models\Project;
use App\Models\Student;

class UpdateStudentProjectController extends Controller
{
private UpdateStudentProjectService $updateStudentProjectService;
public function __invoke(UpdateStudentProjectRequest $request, Student $student, Project $project): JsonResponse
{
$this->authorize('update', $project);

private StudentService $studentService;
$data = $request->validated();

public function __construct(UpdateStudentProjectService $updateStudentProjectService, StudentService $studentService)
{
$this->updateStudentProjectService = $updateStudentProjectService;
$this->studentService = $studentService;
}
$project->update($data);

public function __invoke(UpdateStudentProjectRequest $request, $studentId, $projectId): JsonResponse
{
try {
$userProfile = $this->studentService->findUserByStudentID($studentId);

$data = $request->all();
$this->updateStudentProjectService->execute($studentId, $projectId, $data);
return response()->json(['message' => 'El projecte s\'ha actualitzat'], 200);
} catch (Exception $e) {
// Catch any exceptions and return a consistent JSON response
$status = $e->getCode() ?: 500;
$message = $e->getMessage();

// Handle specific exceptions for clearer messages
if ($message === 'Student not found') {
return response()->json(['message' => 'Student not found'], 404);
}
if ($message === 'Project not found') {
return response()->json(['message' => 'Project not found'], 404);
}
if ($message === 'No tienes permiso para actualizar este proyecto.') {
return response()->json(['message' => 'Unauthorized'], 403);
}

// Generic error message
return response()->json(['message' => $message], $status);
if (isset($data['tags'])) {
$project->tags()->sync($data['tags']);
}

return response()->json([
'message' => 'El projecte s\'ha actualitzat',
], 200);
}
}
12 changes: 0 additions & 12 deletions app/Http/Requests/UpdateImageStudentRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class UpdateImageStudentRequest extends FormRequest
{
Expand All @@ -28,14 +26,4 @@ public function rules(): array
];

}

/**
* If validator fails returns the exception in json form
*
* @return array
*/
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json(['errors' => $validator->errors()], 422));
}
}
20 changes: 0 additions & 20 deletions app/Http/Requests/UpdateStudentProjectRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,15 @@

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class UpdateStudentProjectRequest 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 [
Expand All @@ -32,14 +22,4 @@ public function rules(): array
'project_url' => 'string|url|max:60|nullable',
];
}

/**
* If validator fails returns the exception in json form
*
* @return array
*/
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json(['errors' => $validator->errors()], 422));
}
}
17 changes: 1 addition & 16 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,6 @@ class User extends Authenticatable
* @var array<int, string>
*/
protected $guarded = ['id'];
protected $fillable = [
'username', 'dni', 'email', 'password',
];

/**
* The attributes that should be hidden for serialization.
*
Expand All @@ -52,22 +48,11 @@ class User extends Authenticatable
'password' => 'hashed',
];

// RIGHT NOW THERE ARE NO ADMINS OR RECRUITERS
// public function admin()
// {
// return $this->hasOne(Admin::class);
// }

// public function recruiter()
// {
// return $this->hasOne(Recruiter::class);
// }

public function student():HasOne
{
return $this->hasOne(Student::class);
}

public function resume():HasOne
{
return $this->hasOne(Resume::class);
Expand Down
23 changes: 23 additions & 0 deletions app/Policies/ProjectPolicy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

namespace App\Policies;

use App\Models\Project;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Auth\Access\Response;

class ProjectPolicy
{
use HandlesAuthorization;

public function update(User $user, Project $project): Response
{
if ($user->student->resume->projects->contains($project)) {
return Response::allow();
}
return Response::deny('This action is unauthorized.', 403);
}
}
13 changes: 3 additions & 10 deletions app/Providers/AuthServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,16 @@

namespace App\Providers;

// use Illuminate\Support\Facades\Gate;
use App\Models\Project;
use App\Policies\ProjectPolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
/**
* The model to policy mappings for the application.
*
* @var array<class-string, class-string>
*/
protected $policies = [
//
Project::class => ProjectPolicy::class,
];

/**
* Register any authentication / authorization services.
*/
public function boot(): void
{
$this->registerPolicies();
Expand Down
Loading

0 comments on commit caddaef

Please sign in to comment.