diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index d8bc1d2..40d4dbf 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -5,16 +5,14 @@ namespace App\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; -class Kernel extends ConsoleKernel -{ +class Kernel extends ConsoleKernel { /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ - protected function schedule(Schedule $schedule) - { + protected function schedule(Schedule $schedule) { // $schedule->command('inspire')->hourly(); } @@ -23,8 +21,7 @@ class Kernel extends ConsoleKernel * * @return void */ - protected function commands() - { + protected function commands() { $this->load(__DIR__.'/Commands'); require base_path('routes/console.php'); diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index 8fc1c4a..5c8edbb 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -52,16 +52,17 @@ class Handler extends ExceptionHandler { if ($exception instanceof ModelNotFoundException) { return response([ 'error'=>1, - 'message'=>$exception->getMessage() - ],404); + 'message'=>$exception->getMessage(), + ], 404); } if ($exception instanceof MissingAbilityException) { return response([ 'error'=>1, - 'message'=>"Not authorized" - ],409); + 'message'=>'Not authorized', + ], 409); } + return parent::render($request, $exception); } } diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index a0a2a8a..5f1acc4 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -7,7 +7,6 @@ use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Routing\Controller as BaseController; -class Controller extends BaseController -{ +class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; } diff --git a/app/Http/Controllers/HydraController.php b/app/Http/Controllers/HydraController.php index 9f94df2..8459d79 100644 --- a/app/Http/Controllers/HydraController.php +++ b/app/Http/Controllers/HydraController.php @@ -2,19 +2,16 @@ namespace App\Http\Controllers; -use Illuminate\Http\Request; - -class HydraController extends Controller -{ - public function hydra(){ +class HydraController extends Controller { + public function hydra() { return response([ - "message"=>"Welcome to Hydra, the zero config API boilerplate with roles and abilities for Laravel Sanctum. Please visit https://hasinhayder.github.io/hydra to know more." + 'message'=>'Welcome to Hydra, the zero config API boilerplate with roles and abilities for Laravel Sanctum. Please visit https://hasinhayder.github.io/hydra to know more.', ]); } - public function version(){ + public function version() { return response([ - "version"=> config('hydra.version') + 'version'=> config('hydra.version'), ]); } } diff --git a/app/Http/Controllers/RoleController.php b/app/Http/Controllers/RoleController.php index b78b6be..c7d1ef3 100644 --- a/app/Http/Controllers/RoleController.php +++ b/app/Http/Controllers/RoleController.php @@ -24,16 +24,17 @@ class RoleController extends Controller { public function store(Request $request) { $data = $request->validate([ 'name' => 'required', - 'slug' => 'required' + 'slug' => 'required', ]); $existing = Role::where('slug', $data['slug'])->first(); - if (!$existing) { + if (! $existing) { $role = Role::create([ 'name' => $data['name'], - 'slug' => $data['slug'] + 'slug' => $data['slug'], ]); + return $role; } @@ -58,8 +59,7 @@ class RoleController extends Controller { * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response|Role */ public function update(Request $request, Role $role = null) { - - if (!$role) { + if (! $role) { return response(['error' => 1, 'message' => 'role doesn\'t exist'], 404); } @@ -87,6 +87,7 @@ class RoleController extends Controller { if ($role->slug != 'admin' && $role->slug != 'super-admin') { //don't allow changing the admin slug, because it will make the routes inaccessbile due to faile ability check $role->delete(); + return response(['error' => 0, 'message' => 'role has been deleted']); } diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php index 0b25cc9..9f07353 100644 --- a/app/Http/Controllers/UserController.php +++ b/app/Http/Controllers/UserController.php @@ -4,10 +4,8 @@ namespace App\Http\Controllers; use App\Models\Role; use App\Models\User; -use Illuminate\Validation\ValidationException; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; -use App\Models\UserRole; use Laravel\Sanctum\Exceptions\MissingAbilityException; class UserController extends Controller { @@ -30,7 +28,7 @@ class UserController extends Controller { $creds = $request->validate([ 'email' => 'required|email', 'password' => 'required', - 'name' => 'nullable|string' + 'name' => 'nullable|string', ]); $user = User::where('email', $creds['email'])->first(); @@ -41,7 +39,7 @@ class UserController extends Controller { $user = User::create([ 'email' => $creds['email'], 'password' => Hash::make($creds['password']), - 'name' => $creds['name'] + 'name' => $creds['name'], ]); $defaultRoleSlug = config('hydra.default_user_role_slug', 'user'); @@ -63,7 +61,7 @@ class UserController extends Controller { ]); $user = User::where('email', $creds['email'])->first(); - if (!$user || !Hash::check($request->password, $user->password)) { + if (! $user || ! Hash::check($request->password, $user->password)) { return response(['error' => 1, 'message' => 'invalid credentials'], 401); } @@ -71,9 +69,10 @@ class UserController extends Controller { $user->tokens()->delete(); } - $roles = $user->roles->pluck('slug')->all(); + $roles = $user->roles->pluck('slug')->all(); $plainTextToken = $user->createToken('hydra-api-token', $roles)->plainTextToken; + return response(['error' => 0, 'id' => $user->id, 'token' => $plainTextToken], 200); } @@ -90,27 +89,27 @@ class UserController extends Controller { /** * Update the specified resource in storage. * - * @param \Illuminate\Http\Request $request - * @param \App\Models\User $user + * @param \Illuminate\Http\Request $request + * @param \App\Models\User $user * @return User + * * @throws MissingAbilityException */ public function update(Request $request, User $user) { $user->name = $request->name ?? $user->name; $user->email = $request->email ?? $user->email; - $user->password = $request->password ? Hash::make($request->password) : $user->password; + $user->password = $request->password ? Hash::make($request->password) : $user->password; $user->email_verified_at = $request->email_verified_at ?? $user->email_verified_at; //check if the logged in user is updating it's own record - $loggedInUser = $request->user(); if ($loggedInUser->id == $user->id) { $user->update(); - } else if ($loggedInUser->tokenCan('admin') || $loggedInUser->tokenCan('super-admin')) { + } elseif ($loggedInUser->tokenCan('admin') || $loggedInUser->tokenCan('super-admin')) { $user->update(); } else { - throw new MissingAbilityException("Not Authorized"); + throw new MissingAbilityException('Not Authorized'); } return $user; @@ -123,13 +122,12 @@ class UserController extends Controller { * @return \Illuminate\Http\Response */ public function destroy(User $user) { - $adminRole = Role::where('slug', 'admin')->first(); $userRoles = $user->roles; if ($userRoles->contains($adminRole)) { //the current user is admin, then if there is only one admin - don't delete - $numberOfAdmins = Role::where('slug', 'admin')->first()->users()->count(); + $numberOfAdmins = Role::where('slug', 'admin')->first()->users()->count(); if (1 == $numberOfAdmins) { return response(['error' => 1, 'message' => 'Create another admin before deleting this only admin user'], 409); } @@ -143,7 +141,7 @@ class UserController extends Controller { /** * Return Auth user * - * @param Request $request + * @param Request $request * @return mixed */ public function me(Request $request) { diff --git a/app/Http/Controllers/UserRoleController.php b/app/Http/Controllers/UserRoleController.php index b3b9f0e..db5eb02 100644 --- a/app/Http/Controllers/UserRoleController.php +++ b/app/Http/Controllers/UserRoleController.php @@ -26,10 +26,10 @@ class UserRoleController extends Controller { */ public function store(Request $request, User $user) { $data = $request->validate([ - 'role_id' => 'required|integer' + 'role_id' => 'required|integer', ]); $role = Role::find($data['role_id']); - if (!$user->roles()->find($data['role_id'])) { + if (! $user->roles()->find($data['role_id'])) { $user->roles()->attach($role); } @@ -45,6 +45,7 @@ class UserRoleController extends Controller { */ public function destroy(User $user, Role $role) { $user->roles()->detach($role); + return $user->load('roles'); } } diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php index 704089a..d8770c4 100644 --- a/app/Http/Middleware/Authenticate.php +++ b/app/Http/Middleware/Authenticate.php @@ -4,16 +4,14 @@ namespace App\Http\Middleware; use Illuminate\Auth\Middleware\Authenticate as Middleware; -class Authenticate extends Middleware -{ +class Authenticate extends Middleware { /** * Get the path the user should be redirected to when they are not authenticated. * * @param \Illuminate\Http\Request $request * @return string|null */ - protected function redirectTo($request) - { + protected function redirectTo($request) { if (! $request->expectsJson()) { return route('login'); } diff --git a/app/Http/Middleware/EncryptCookies.php b/app/Http/Middleware/EncryptCookies.php index 867695b..b8f5743 100644 --- a/app/Http/Middleware/EncryptCookies.php +++ b/app/Http/Middleware/EncryptCookies.php @@ -4,8 +4,7 @@ namespace App\Http\Middleware; use Illuminate\Cookie\Middleware\EncryptCookies as Middleware; -class EncryptCookies extends Middleware -{ +class EncryptCookies extends Middleware { /** * The names of the cookies that should not be encrypted. * diff --git a/app/Http/Middleware/HydraLog.php b/app/Http/Middleware/HydraLog.php index c83a9cb..dd18e0a 100644 --- a/app/Http/Middleware/HydraLog.php +++ b/app/Http/Middleware/HydraLog.php @@ -6,8 +6,7 @@ use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; -class HydraLog -{ +class HydraLog { /** * Handle an incoming request. * @@ -15,18 +14,16 @@ class HydraLog * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse */ - public function handle(Request $request, Closure $next) - { + public function handle(Request $request, Closure $next) { return $next($request); } - public function terminate($request, $response) - { - Log::info("\n\n".str_repeat("=",100)."\n\n"); - Log::debug('app.route', ['route'=>$request->route()]); - Log::debug('app.headers', ['headers'=>$request->headers]); - Log::debug('app.requests', ['request' => $request->all()]); - Log::debug('app.response', ['response' => $response]); - Log::info("\n\n".str_repeat("=",100)."\n\n"); - } + public function terminate($request, $response) { + Log::info("\n\n".str_repeat('=', 100)."\n\n"); + Log::debug('app.route', ['route'=>$request->route()]); + Log::debug('app.headers', ['headers'=>$request->headers]); + Log::debug('app.requests', ['request' => $request->all()]); + Log::debug('app.response', ['response' => $response]); + Log::info("\n\n".str_repeat('=', 100)."\n\n"); + } } diff --git a/app/Http/Middleware/PreventRequestsDuringMaintenance.php b/app/Http/Middleware/PreventRequestsDuringMaintenance.php index 74cbd9a..fe31bf9 100644 --- a/app/Http/Middleware/PreventRequestsDuringMaintenance.php +++ b/app/Http/Middleware/PreventRequestsDuringMaintenance.php @@ -4,8 +4,7 @@ namespace App\Http\Middleware; use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware; -class PreventRequestsDuringMaintenance extends Middleware -{ +class PreventRequestsDuringMaintenance extends Middleware { /** * The URIs that should be reachable while maintenance mode is enabled. * diff --git a/app/Http/Middleware/RedirectIfAuthenticated.php b/app/Http/Middleware/RedirectIfAuthenticated.php index a2813a0..fbd3570 100644 --- a/app/Http/Middleware/RedirectIfAuthenticated.php +++ b/app/Http/Middleware/RedirectIfAuthenticated.php @@ -7,8 +7,7 @@ use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; -class RedirectIfAuthenticated -{ +class RedirectIfAuthenticated { /** * Handle an incoming request. * @@ -17,8 +16,7 @@ class RedirectIfAuthenticated * @param string|null ...$guards * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse */ - public function handle(Request $request, Closure $next, ...$guards) - { + public function handle(Request $request, Closure $next, ...$guards) { $guards = empty($guards) ? [null] : $guards; foreach ($guards as $guard) { diff --git a/app/Http/Middleware/TrimStrings.php b/app/Http/Middleware/TrimStrings.php index 88cadca..f9db2f9 100644 --- a/app/Http/Middleware/TrimStrings.php +++ b/app/Http/Middleware/TrimStrings.php @@ -4,8 +4,7 @@ namespace App\Http\Middleware; use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware; -class TrimStrings extends Middleware -{ +class TrimStrings extends Middleware { /** * The names of the attributes that should not be trimmed. * diff --git a/app/Http/Middleware/TrustHosts.php b/app/Http/Middleware/TrustHosts.php index 7186414..1e9d9a1 100644 --- a/app/Http/Middleware/TrustHosts.php +++ b/app/Http/Middleware/TrustHosts.php @@ -4,15 +4,13 @@ namespace App\Http\Middleware; use Illuminate\Http\Middleware\TrustHosts as Middleware; -class TrustHosts extends Middleware -{ +class TrustHosts extends Middleware { /** * Get the host patterns that should be trusted. * * @return array */ - public function hosts() - { + public function hosts() { return [ $this->allSubdomainsOfApplicationUrl(), ]; diff --git a/app/Http/Middleware/TrustProxies.php b/app/Http/Middleware/TrustProxies.php index 3391630..cb842aa 100644 --- a/app/Http/Middleware/TrustProxies.php +++ b/app/Http/Middleware/TrustProxies.php @@ -5,8 +5,7 @@ namespace App\Http\Middleware; use Illuminate\Http\Middleware\TrustProxies as Middleware; use Illuminate\Http\Request; -class TrustProxies extends Middleware -{ +class TrustProxies extends Middleware { /** * The trusted proxies for this application. * diff --git a/app/Http/Middleware/VerifyCsrfToken.php b/app/Http/Middleware/VerifyCsrfToken.php index 9e86521..5430966 100644 --- a/app/Http/Middleware/VerifyCsrfToken.php +++ b/app/Http/Middleware/VerifyCsrfToken.php @@ -4,8 +4,7 @@ namespace App\Http\Middleware; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware; -class VerifyCsrfToken extends Middleware -{ +class VerifyCsrfToken extends Middleware { /** * The URIs that should be excluded from CSRF verification. * diff --git a/app/Models/Role.php b/app/Models/Role.php index 991be4d..4c6bcf7 100644 --- a/app/Models/Role.php +++ b/app/Models/Role.php @@ -4,21 +4,21 @@ namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; -use App\Models\User; -class Role extends Model -{ +class Role extends Model { use HasFactory; + protected $fillable = [ - 'name','slug' + 'name', 'slug', ]; + protected $hidden = [ 'pivot', 'created_at', 'updated_at', ]; - public function users(){ - return $this->belongsToMany(User::class,'user_roles'); + public function users() { + return $this->belongsToMany(User::class, 'user_roles'); } } diff --git a/app/Models/User.php b/app/Models/User.php index b436307..df4eb34 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -2,15 +2,12 @@ namespace App\Models; -use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; -use App\Models\Role; -class User extends Authenticatable -{ +class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; /** @@ -34,7 +31,7 @@ class User extends Authenticatable 'remember_token', 'created_at', 'updated_at', - 'email_verified_at' + 'email_verified_at', ]; /** @@ -46,7 +43,7 @@ class User extends Authenticatable 'email_verified_at' => 'datetime', ]; - public function roles(){ - return $this->belongsToMany(Role::class,'user_roles'); + public function roles() { + return $this->belongsToMany(Role::class, 'user_roles'); } } diff --git a/app/Models/UserRole.php b/app/Models/UserRole.php index 4554f75..238f755 100644 --- a/app/Models/UserRole.php +++ b/app/Models/UserRole.php @@ -5,10 +5,10 @@ namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; -class UserRole extends Model -{ +class UserRole extends Model { use HasFactory; + protected $fillable = [ - 'user_id','role_id' + 'user_id', 'role_id', ]; } diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index ee8ca5b..5a7cf2f 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -4,15 +4,13 @@ namespace App\Providers; use Illuminate\Support\ServiceProvider; -class AppServiceProvider extends ServiceProvider -{ +class AppServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ - public function register() - { + public function register() { // } @@ -21,8 +19,7 @@ class AppServiceProvider extends ServiceProvider * * @return void */ - public function boot() - { + public function boot() { // } } diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index 51b351b..b1783f4 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -3,10 +3,8 @@ namespace App\Providers; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; -use Illuminate\Support\Facades\Gate; -class AuthServiceProvider extends ServiceProvider -{ +class AuthServiceProvider extends ServiceProvider { /** * The model to policy mappings for the application. * @@ -21,8 +19,7 @@ class AuthServiceProvider extends ServiceProvider * * @return void */ - public function boot() - { + public function boot() { $this->registerPolicies(); // diff --git a/app/Providers/BroadcastServiceProvider.php b/app/Providers/BroadcastServiceProvider.php index 395c518..26a236a 100644 --- a/app/Providers/BroadcastServiceProvider.php +++ b/app/Providers/BroadcastServiceProvider.php @@ -5,15 +5,13 @@ namespace App\Providers; use Illuminate\Support\Facades\Broadcast; use Illuminate\Support\ServiceProvider; -class BroadcastServiceProvider extends ServiceProvider -{ +class BroadcastServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ - public function boot() - { + public function boot() { Broadcast::routes(); require base_path('routes/channels.php'); diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index ab8b2cf..591e739 100644 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -7,8 +7,7 @@ use Illuminate\Auth\Listeners\SendEmailVerificationNotification; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; use Illuminate\Support\Facades\Event; -class EventServiceProvider extends ServiceProvider -{ +class EventServiceProvider extends ServiceProvider { /** * The event to listener mappings for the application. * @@ -25,8 +24,7 @@ class EventServiceProvider extends ServiceProvider * * @return void */ - public function boot() - { + public function boot() { // } @@ -35,8 +33,7 @@ class EventServiceProvider extends ServiceProvider * * @return bool */ - public function shouldDiscoverEvents() - { + public function shouldDiscoverEvents() { return false; } } diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php index ea87f2e..aea6e8e 100644 --- a/app/Providers/RouteServiceProvider.php +++ b/app/Providers/RouteServiceProvider.php @@ -8,8 +8,7 @@ use Illuminate\Http\Request; use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\Facades\Route; -class RouteServiceProvider extends ServiceProvider -{ +class RouteServiceProvider extends ServiceProvider { /** * The path to the "home" route for your application. * @@ -24,8 +23,7 @@ class RouteServiceProvider extends ServiceProvider * * @return void */ - public function boot() - { + public function boot() { $this->configureRateLimiting(); $this->routes(function () { @@ -43,8 +41,7 @@ class RouteServiceProvider extends ServiceProvider * * @return void */ - protected function configureRateLimiting() - { + protected function configureRateLimiting() { RateLimiter::for('api', function (Request $request) { return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip()); }); diff --git a/composer.json b/composer.json index 1d7d767..4914ac8 100644 --- a/composer.json +++ b/composer.json @@ -16,6 +16,7 @@ }, "require-dev": { "fakerphp/faker": "^1.9.1", + "laravel/pint": "^0.2.0", "laravel/sail": "^1.14", "mockery/mockery": "^1.4.4", "nunomaduro/collision": "^6.1", diff --git a/config/hydra.php b/config/hydra.php index 1036241..5155b17 100644 --- a/config/hydra.php +++ b/config/hydra.php @@ -13,7 +13,6 @@ return [ 'version' => env('APP_VERSION', '1.1.0'), - /* |-------------------------------------------------------------------------- | Default user role diff --git a/database/factories/UserFactory.php b/database/factories/UserFactory.php index 23b61d2..bc2f498 100644 --- a/database/factories/UserFactory.php +++ b/database/factories/UserFactory.php @@ -8,15 +8,13 @@ use Illuminate\Support\Str; /** * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User> */ -class UserFactory extends Factory -{ +class UserFactory extends Factory { /** * Define the model's default state. * * @return array */ - public function definition() - { + public function definition() { return [ 'name' => $this->faker->name(), 'email' => $this->faker->unique()->safeEmail(), @@ -31,8 +29,7 @@ class UserFactory extends Factory * * @return static */ - public function unverified() - { + public function unverified() { return $this->state(function (array $attributes) { return [ 'email_verified_at' => null, diff --git a/database/migrations/2014_10_12_000000_create_users_table.php b/database/migrations/2014_10_12_000000_create_users_table.php index cf6b776..545e2f7 100644 --- a/database/migrations/2014_10_12_000000_create_users_table.php +++ b/database/migrations/2014_10_12_000000_create_users_table.php @@ -4,15 +4,13 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * * @return void */ - public function up() - { + public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); @@ -29,8 +27,7 @@ return new class extends Migration * * @return void */ - public function down() - { + public function down() { Schema::dropIfExists('users'); } }; diff --git a/database/migrations/2014_10_12_100000_create_password_resets_table.php b/database/migrations/2014_10_12_100000_create_password_resets_table.php index fcacb80..7c0aa50 100644 --- a/database/migrations/2014_10_12_100000_create_password_resets_table.php +++ b/database/migrations/2014_10_12_100000_create_password_resets_table.php @@ -4,15 +4,13 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * * @return void */ - public function up() - { + public function up() { Schema::create('password_resets', function (Blueprint $table) { $table->string('email')->index(); $table->string('token'); @@ -25,8 +23,7 @@ return new class extends Migration * * @return void */ - public function down() - { + public function down() { Schema::dropIfExists('password_resets'); } }; diff --git a/database/migrations/2019_08_19_000000_create_failed_jobs_table.php b/database/migrations/2019_08_19_000000_create_failed_jobs_table.php index 1719198..3608f1e 100644 --- a/database/migrations/2019_08_19_000000_create_failed_jobs_table.php +++ b/database/migrations/2019_08_19_000000_create_failed_jobs_table.php @@ -4,15 +4,13 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * * @return void */ - public function up() - { + public function up() { Schema::create('failed_jobs', function (Blueprint $table) { $table->id(); $table->string('uuid')->unique(); @@ -29,8 +27,7 @@ return new class extends Migration * * @return void */ - public function down() - { + public function down() { Schema::dropIfExists('failed_jobs'); } }; diff --git a/database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php b/database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php index fd235f8..abf2ce9 100644 --- a/database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php +++ b/database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php @@ -4,15 +4,13 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * * @return void */ - public function up() - { + public function up() { Schema::create('personal_access_tokens', function (Blueprint $table) { $table->id(); $table->morphs('tokenable'); @@ -29,8 +27,7 @@ return new class extends Migration * * @return void */ - public function down() - { + public function down() { Schema::dropIfExists('personal_access_tokens'); } }; diff --git a/database/migrations/2022_05_17_181447_create_roles_table.php b/database/migrations/2022_05_17_181447_create_roles_table.php index ff43946..b7ccdf7 100644 --- a/database/migrations/2022_05_17_181447_create_roles_table.php +++ b/database/migrations/2022_05_17_181447_create_roles_table.php @@ -4,15 +4,13 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * * @return void */ - public function up() - { + public function up() { Schema::create('roles', function (Blueprint $table) { $table->id(); $table->string('name'); @@ -26,8 +24,7 @@ return new class extends Migration * * @return void */ - public function down() - { + public function down() { Schema::dropIfExists('roles'); } }; diff --git a/database/migrations/2022_05_17_181456_create_user_roles_table.php b/database/migrations/2022_05_17_181456_create_user_roles_table.php index 03bf56d..9616574 100644 --- a/database/migrations/2022_05_17_181456_create_user_roles_table.php +++ b/database/migrations/2022_05_17_181456_create_user_roles_table.php @@ -4,20 +4,18 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * * @return void */ - public function up() - { + public function up() { Schema::create('user_roles', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained()->cascadeOnDelete(); $table->foreignId('role_id')->constrained()->cascadeOnDelete(); - $table->unique(['user_id','role_id']); + $table->unique(['user_id', 'role_id']); $table->timestamps(); }); } @@ -27,8 +25,7 @@ return new class extends Migration * * @return void */ - public function down() - { + public function down() { Schema::dropIfExists('user_roles'); } }; diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index de71c2b..8ccf378 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -2,18 +2,15 @@ namespace Database\Seeders; -use Illuminate\Database\Console\Seeds\WithoutModelEvents; use Illuminate\Database\Seeder; -class DatabaseSeeder extends Seeder -{ +class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ - public function run() - { + public function run() { // \App\Models\User::factory(10)->create(); // \App\Models\User::factory()->create([ @@ -24,6 +21,5 @@ class DatabaseSeeder extends Seeder RoleSeeder::class, UsersSeeder::class, ]); - } } diff --git a/database/seeders/RoleSeeder.php b/database/seeders/RoleSeeder.php index 2387f92..5d35996 100644 --- a/database/seeders/RoleSeeder.php +++ b/database/seeders/RoleSeeder.php @@ -2,9 +2,8 @@ namespace Database\Seeders; -use Illuminate\Database\Console\Seeds\WithoutModelEvents; -use Illuminate\Database\Seeder; use App\Models\Role; +use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; @@ -28,7 +27,7 @@ class RoleSeeder extends Seeder { ['name' => 'Super Admin', 'slug' => 'super-admin'], ]; - collect($roles)->each(function($role){ + collect($roles)->each(function ($role) { Role::create($role); }); } diff --git a/database/seeders/UsersSeeder.php b/database/seeders/UsersSeeder.php index d8a024a..167f87a 100644 --- a/database/seeders/UsersSeeder.php +++ b/database/seeders/UsersSeeder.php @@ -4,22 +4,18 @@ namespace Database\Seeders; use App\Models\Role; use App\Models\User; -use Illuminate\Support\Str; use Illuminate\Database\Seeder; -use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Schema; -use Illuminate\Database\Console\Seeds\WithoutModelEvents; -class UsersSeeder extends Seeder -{ +class UsersSeeder extends Seeder { /** * Run the database seeds. * * @return void */ - public function run() - { + public function run() { Schema::disableForeignKeyConstraints(); DB::table('users')->truncate(); Schema::enableForeignKeyConstraints(); @@ -27,7 +23,7 @@ class UsersSeeder extends Seeder $user = User::create([ 'email'=>'admin@hydra.project', 'password'=>Hash::make('hydra'), - 'name'=>'Hydra Admin' + 'name'=>'Hydra Admin', ]); $user->roles()->attach(Role::where('slug', 'admin')->first()); } diff --git a/routes/api.php b/routes/api.php index 6a33f09..a4d8071 100644 --- a/routes/api.php +++ b/routes/api.php @@ -4,7 +4,6 @@ use App\Http\Controllers\HydraController; use App\Http\Controllers\RoleController; use App\Http\Controllers\UserController; use App\Http\Controllers\UserRoleController; -use App\Http\Middleware\HydraLog; use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; @@ -21,16 +20,16 @@ use Illuminate\Support\Facades\Route; //use the middleware 'hydra.log' with any request to get the detailed headers, request parameters and response logged in logs/laravel.log -Route::get('hydra',[HydraController::class,'hydra']); -Route::get('hydra/version',[HydraController::class,'version']); +Route::get('hydra', [HydraController::class, 'hydra']); +Route::get('hydra/version', [HydraController::class, 'version']); -Route::apiResource('users',UserController::class)->except(['edit','create','store','update'])->middleware(['auth:sanctum', 'ability:admin,super-admin']); -Route::post('users',[UserController::class,'store']); -Route::put('users/{user}',[UserController::class,'update'])->middleware(['auth:sanctum', 'ability:admin,super-admin,user']); -Route::post('users/{user}',[UserController::class,'update'])->middleware(['auth:sanctum', 'ability:admin,super-admin,user']); -Route::patch('users/{user}',[UserController::class,'update'])->middleware(['auth:sanctum', 'ability:admin,super-admin,user']); -Route::get('me',[UserController::class,'me'])->middleware('auth:sanctum'); -Route::post('login',[UserController::class,'login']); +Route::apiResource('users', UserController::class)->except(['edit', 'create', 'store', 'update'])->middleware(['auth:sanctum', 'ability:admin,super-admin']); +Route::post('users', [UserController::class, 'store']); +Route::put('users/{user}', [UserController::class, 'update'])->middleware(['auth:sanctum', 'ability:admin,super-admin,user']); +Route::post('users/{user}', [UserController::class, 'update'])->middleware(['auth:sanctum', 'ability:admin,super-admin,user']); +Route::patch('users/{user}', [UserController::class, 'update'])->middleware(['auth:sanctum', 'ability:admin,super-admin,user']); +Route::get('me', [UserController::class, 'me'])->middleware('auth:sanctum'); +Route::post('login', [UserController::class, 'login']); -Route::apiResource('roles',RoleController::class)->except(['create','edit'])->middleware(['auth:sanctum', 'ability:admin,super-admin,user']); -Route::apiResource('users.roles',UserRoleController::class)->except(['create','edit','show','update'])->middleware(['auth:sanctum', 'ability:admin,super-admin']); +Route::apiResource('roles', RoleController::class)->except(['create', 'edit'])->middleware(['auth:sanctum', 'ability:admin,super-admin,user']); +Route::apiResource('users.roles', UserRoleController::class)->except(['create', 'edit', 'show', 'update'])->middleware(['auth:sanctum', 'ability:admin,super-admin']); diff --git a/tests/CreatesApplication.php b/tests/CreatesApplication.php index 547152f..6795a74 100644 --- a/tests/CreatesApplication.php +++ b/tests/CreatesApplication.php @@ -4,15 +4,13 @@ namespace Tests; use Illuminate\Contracts\Console\Kernel; -trait CreatesApplication -{ +trait CreatesApplication { /** * Creates the application. * * @return \Illuminate\Foundation\Application */ - public function createApplication() - { + public function createApplication() { $app = require __DIR__.'/../bootstrap/app.php'; $app->make(Kernel::class)->bootstrap(); diff --git a/tests/Feature/AdminLoginTest.php b/tests/Feature/AdminLoginTest.php index 55a6003..40da9bc 100644 --- a/tests/Feature/AdminLoginTest.php +++ b/tests/Feature/AdminLoginTest.php @@ -2,44 +2,36 @@ namespace Tests\Feature; -use Illuminate\Foundation\Testing\RefreshDatabase; -use Illuminate\Foundation\Testing\WithFaker; -use Tests\TestCase; use Illuminate\Testing\Fluent\AssertableJson; +use Tests\TestCase; - -class AdminLoginTest extends TestCase -{ +class AdminLoginTest extends TestCase { /** * A basic feature test example. * * @return void */ - public function test_admin_login() - { - $response = $this->postJson('/api/login',[ + public function test_admin_login() { + $response = $this->postJson('/api/login', [ 'email'=>'admin@hydra.project', - 'password'=>'hydra' + 'password'=>'hydra', ]); $response - ->assertJson(fn (AssertableJson $json) => - $json->where('error', 0) + ->assertJson(fn (AssertableJson $json) => $json->where('error', 0) ->has('token') ->etc() ); } - public function test_admin_login_fail() - { - $response = $this->postJson('/api/login',[ + public function test_admin_login_fail() { + $response = $this->postJson('/api/login', [ 'email'=>'admin@hydra.project', - 'password'=>'hydrax' + 'password'=>'hydrax', ]); $response - ->assertJson(fn (AssertableJson $json) => - $json->where('error', 1) + ->assertJson(fn (AssertableJson $json) => $json->where('error', 1) ->missing('token') ->has('message') ); diff --git a/tests/Feature/HelloHydraTest.php b/tests/Feature/HelloHydraTest.php index 3c0e3c7..126cb8e 100644 --- a/tests/Feature/HelloHydraTest.php +++ b/tests/Feature/HelloHydraTest.php @@ -2,19 +2,15 @@ namespace Tests\Feature; -use Illuminate\Foundation\Testing\RefreshDatabase; -use Illuminate\Foundation\Testing\WithFaker; use Tests\TestCase; -class HelloHydraTest extends TestCase -{ +class HelloHydraTest extends TestCase { /** * A basic feature test example. * * @return void */ - public function test_hello_hydra() - { + public function test_hello_hydra() { $response = $this->get('/api/hydra'); $response @@ -24,8 +20,7 @@ class HelloHydraTest extends TestCase ]); } - public function test_hydra_version() - { + public function test_hydra_version() { $response = $this->get('/api/hydra/version'); $response diff --git a/tests/Feature/RoleTest.php b/tests/Feature/RoleTest.php index b494427..b56ee7e 100644 --- a/tests/Feature/RoleTest.php +++ b/tests/Feature/RoleTest.php @@ -2,11 +2,9 @@ namespace Tests\Feature; -use Illuminate\Foundation\Testing\RefreshDatabase; -use Illuminate\Foundation\Testing\WithFaker; -use Tests\TestCase; -use Illuminate\Testing\Fluent\AssertableJson; use App\Models\Role; +use Illuminate\Testing\Fluent\AssertableJson; +use Tests\TestCase; class RoleTest extends TestCase { /** @@ -17,26 +15,23 @@ class RoleTest extends TestCase { public function test_list_roles() { $response = $this->postJson('/api/login', [ 'email' => 'admin@hydra.project', - 'password' => 'hydra' + 'password' => 'hydra', ]); $data = json_decode($response->getContent()); $this->token = $data->token; $this->user_id = $data->id; - - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) - ->get("/api/roles"); + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) + ->get('/api/roles'); $response ->assertJson( - fn (AssertableJson $json) => - $json->has(6) + fn (AssertableJson $json) => $json->has(6) ->first( - fn ($json) => - $json->where('id', 1) + fn ($json) => $json->where('id', 1) ->where('name', 'Administrator') - ->where('slug','admin') + ->where('slug', 'admin') ->etc() ) ); @@ -45,23 +40,21 @@ class RoleTest extends TestCase { public function test_update_role_name_as_admin() { $response = $this->postJson('/api/login', [ 'email' => 'admin@hydra.project', - 'password' => 'hydra' + 'password' => 'hydra', ]); $data = json_decode($response->getContent()); $this->token = $data->token; $this->user_id = $data->id; - - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) - ->put("/api/roles/4",[ - "name"=>"Chief Editor" + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) + ->put('/api/roles/4', [ + 'name'=>'Chief Editor', ]); $response ->assertJson( - fn (AssertableJson $json) => - $json->where('name','Chief Editor') + fn (AssertableJson $json) => $json->where('name', 'Chief Editor') ->missing('error') ->etc() ); @@ -70,23 +63,21 @@ class RoleTest extends TestCase { public function test_update_role_slug_as_admin() { $response = $this->postJson('/api/login', [ 'email' => 'admin@hydra.project', - 'password' => 'hydra' + 'password' => 'hydra', ]); $data = json_decode($response->getContent()); $this->token = $data->token; $this->user_id = $data->id; - - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) - ->put("/api/roles/4",[ - "slug"=>"chief-editor" + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) + ->put('/api/roles/4', [ + 'slug'=>'chief-editor', ]); $response ->assertJson( - fn (AssertableJson $json) => - $json->where('slug','chief-editor') + fn (AssertableJson $json) => $json->where('slug', 'chief-editor') ->missing('error') ->etc() ); @@ -95,25 +86,23 @@ class RoleTest extends TestCase { public function test_update_role_namd_and_slug_as_admin() { $response = $this->postJson('/api/login', [ 'email' => 'admin@hydra.project', - 'password' => 'hydra' + 'password' => 'hydra', ]); $data = json_decode($response->getContent()); $this->token = $data->token; $this->user_id = $data->id; - - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) - ->put("/api/roles/4",[ - "name"=>"Editor X", - "slug"=>"editor-x" + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) + ->put('/api/roles/4', [ + 'name'=>'Editor X', + 'slug'=>'editor-x', ]); $response ->assertJson( - fn (AssertableJson $json) => - $json->where('name','Editor X') - ->where('slug','editor-x') + fn (AssertableJson $json) => $json->where('name', 'Editor X') + ->where('slug', 'editor-x') ->missing('error') ->etc() ); @@ -122,24 +111,22 @@ class RoleTest extends TestCase { public function test_update_admin_slug_as_admin_should_fail() { $response = $this->postJson('/api/login', [ 'email' => 'admin@hydra.project', - 'password' => 'hydra' + 'password' => 'hydra', ]); $data = json_decode($response->getContent()); $this->token = $data->token; $this->user_id = $data->id; - - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) - ->put("/api/roles/1",[ - "slug"=>"admin-x" + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) + ->put('/api/roles/1', [ + 'slug'=>'admin-x', ]); $response ->assertJson( - fn (AssertableJson $json) => - $json - ->where('slug','admin') + fn (AssertableJson $json) => $json + ->where('slug', 'admin') ->etc() ); } @@ -147,25 +134,23 @@ class RoleTest extends TestCase { public function test_create_new_role_as_admin() { $response = $this->postJson('/api/login', [ 'email' => 'admin@hydra.project', - 'password' => 'hydra' + 'password' => 'hydra', ]); $data = json_decode($response->getContent()); $this->token = $data->token; $this->user_id = $data->id; - - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) - ->post("/api/roles",[ - "name"=>"New Role", - "slug"=>"new-role" + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) + ->post('/api/roles', [ + 'name'=>'New Role', + 'slug'=>'new-role', ]); $response ->assertJson( - fn (AssertableJson $json) => - $json->where('name','New Role') - ->where('slug','new-role') + fn (AssertableJson $json) => $json->where('name', 'New Role') + ->where('slug', 'new-role') ->missing('error') ->etc() ); @@ -174,24 +159,22 @@ class RoleTest extends TestCase { public function test_duplicate_role_will_not_be_created() { $response = $this->postJson('/api/login', [ 'email' => 'admin@hydra.project', - 'password' => 'hydra' + 'password' => 'hydra', ]); $data = json_decode($response->getContent()); $this->token = $data->token; $this->user_id = $data->id; - - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) - ->post("/api/roles",[ - "name"=>"New Role", - "slug"=>"new-role" + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) + ->post('/api/roles', [ + 'name'=>'New Role', + 'slug'=>'new-role', ]); $response ->assertJson( - fn (AssertableJson $json) => - $json->where('error',1) + fn (AssertableJson $json) => $json->where('error', 1) ->etc() ); } @@ -199,23 +182,21 @@ class RoleTest extends TestCase { public function test_delete_role_as_admin() { $response = $this->postJson('/api/login', [ 'email' => 'admin@hydra.project', - 'password' => 'hydra' + 'password' => 'hydra', ]); $data = json_decode($response->getContent()); $this->token = $data->token; $this->user_id = $data->id; - $newRole = Role::where('slug','new-role')->first(); - + $newRole = Role::where('slug', 'new-role')->first(); - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) ->delete("/api/roles/{$newRole->id}"); $response ->assertJson( - fn (AssertableJson $json) => - $json->where('error',0) + fn (AssertableJson $json) => $json->where('error', 0) ->has('message') ); } @@ -223,23 +204,21 @@ class RoleTest extends TestCase { public function test_delete_admin_role_should_fail() { $response = $this->postJson('/api/login', [ 'email' => 'admin@hydra.project', - 'password' => 'hydra' + 'password' => 'hydra', ]); $data = json_decode($response->getContent()); $this->token = $data->token; $this->user_id = $data->id; - $newRole = Role::where('slug','admin')->first(); - + $newRole = Role::where('slug', 'admin')->first(); - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) ->delete("/api/roles/{$newRole->id}"); $response ->assertJson( - fn (AssertableJson $json) => - $json->where('error',1) + fn (AssertableJson $json) => $json->where('error', 1) ->has('message') ); } diff --git a/tests/Feature/UserRoleTest.php b/tests/Feature/UserRoleTest.php index 3bd51af..023950f 100644 --- a/tests/Feature/UserRoleTest.php +++ b/tests/Feature/UserRoleTest.php @@ -3,35 +3,29 @@ namespace Tests\Feature; use App\Models\User; -use Illuminate\Foundation\Testing\RefreshDatabase; -use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Support\Facades\Hash; use Illuminate\Testing\Fluent\AssertableJson; use Tests\TestCase; class UserRoleTest extends TestCase { - public function test_user_role_is_present() { $response = $this->postJson('/api/login', [ 'email' => 'admin@hydra.project', - 'password' => 'hydra' + 'password' => 'hydra', ]); $data = json_decode($response->getContent()); $this->token = $data->token; $this->user_id = $data->id; - - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) - ->get("/api/users/1/roles"); + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) + ->get('/api/users/1/roles'); $response ->assertJson( - fn (AssertableJson $json) => - $json->has( + fn (AssertableJson $json) => $json->has( 'roles.0', - fn ($json) => - $json->where('id', 1) + fn ($json) => $json->where('id', 1) ->where('name', 'Administrator') ->where('slug', 'admin') ->etc() @@ -40,34 +34,29 @@ class UserRoleTest extends TestCase { } public function test_assign_role_to_a_user() { - $newUser = User::create([ 'name' => 'Test User', 'password' => Hash::make('abcd'), - 'email' => 'testuser@hydra.project' + 'email' => 'testuser@hydra.project', ]); - $response = $this->postJson('/api/login', [ 'email' => 'admin@hydra.project', - 'password' => 'hydra' + 'password' => 'hydra', ]); $data = json_decode($response->getContent()); $this->token = $data->token; $this->user_id = $data->id; - - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) ->post("/api/users/{$newUser->id}/roles", ['role_id' => 3]); //assign customer role $response ->assertJson( - fn (AssertableJson $json) => - $json->has( + fn (AssertableJson $json) => $json->has( 'roles.0', - fn ($json) => - $json->where('id', 3) + fn ($json) => $json->where('id', 3) ->where('name', 'Customer') ->where('slug', 'customer') ->etc() @@ -78,37 +67,32 @@ class UserRoleTest extends TestCase { } public function test_assign_role_multiple_times_to_a_user_should_fail() { - $newUser = User::create([ 'name' => 'Test User', 'password' => Hash::make('abcd'), - 'email' => 'testuser@hydra.project' + 'email' => 'testuser@hydra.project', ]); - $response = $this->postJson('/api/login', [ 'email' => 'admin@hydra.project', - 'password' => 'hydra' + 'password' => 'hydra', ]); $data = json_decode($response->getContent()); $this->token = $data->token; $this->user_id = $data->id; - - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) ->post("/api/users/{$newUser->id}/roles", ['role_id' => 3]); //assign customer role - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) ->post("/api/users/{$newUser->id}/roles", ['role_id' => 3]); //again assign customer role $response ->assertJson( - fn (AssertableJson $json) => - $json->has( + fn (AssertableJson $json) => $json->has( 'roles', - fn ($json) => - $json->has(1)->etc() //only one role + fn ($json) => $json->has(1)->etc() //only one role )->etc() ); @@ -116,37 +100,32 @@ class UserRoleTest extends TestCase { } public function test_assign_multiple_roles_to_a_user() { - $newUser = User::create([ 'name' => 'Test User', 'password' => Hash::make('abcd'), - 'email' => 'testuser@hydra.project' + 'email' => 'testuser@hydra.project', ]); - $response = $this->postJson('/api/login', [ 'email' => 'admin@hydra.project', - 'password' => 'hydra' + 'password' => 'hydra', ]); $data = json_decode($response->getContent()); $this->token = $data->token; $this->user_id = $data->id; - - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) ->post("/api/users/{$newUser->id}/roles", ['role_id' => 2]); //assign customer role - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) ->post("/api/users/{$newUser->id}/roles", ['role_id' => 3]); //again assign customer role $response ->assertJson( - fn (AssertableJson $json) => - $json->has( + fn (AssertableJson $json) => $json->has( 'roles', - fn ($json) => - $json->has(2)->etc() //only one role + fn ($json) => $json->has(2)->etc() //only one role )->etc() ); @@ -154,40 +133,35 @@ class UserRoleTest extends TestCase { } public function test_delete_role_from_a_user() { - $newUser = User::create([ 'name' => 'Test User', 'password' => Hash::make('abcd'), - 'email' => 'testuser@hydra.project' + 'email' => 'testuser@hydra.project', ]); - $response = $this->postJson('/api/login', [ 'email' => 'admin@hydra.project', - 'password' => 'hydra' + 'password' => 'hydra', ]); $data = json_decode($response->getContent()); $this->token = $data->token; $this->user_id = $data->id; - - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) ->post("/api/users/{$newUser->id}/roles", ['role_id' => 2]); //assign customer role - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) ->post("/api/users/{$newUser->id}/roles", ['role_id' => 3]); //again assign customer role - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) ->delete("/api/users/{$newUser->id}/roles/3"); //delete $response ->assertJson( - fn (AssertableJson $json) => - $json->has( + fn (AssertableJson $json) => $json->has( 'roles', - fn ($json) => - $json->has(1)->etc() //only one role + fn ($json) => $json->has(1)->etc() //only one role )->etc() ); @@ -195,42 +169,37 @@ class UserRoleTest extends TestCase { } public function test_delete_all_roles_from_a_user() { - $newUser = User::create([ 'name' => 'Test User', 'password' => Hash::make('abcd'), - 'email' => 'testuser@hydra.project' + 'email' => 'testuser@hydra.project', ]); - $response = $this->postJson('/api/login', [ 'email' => 'admin@hydra.project', - 'password' => 'hydra' + 'password' => 'hydra', ]); $data = json_decode($response->getContent()); $this->token = $data->token; $this->user_id = $data->id; - - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) ->post("/api/users/{$newUser->id}/roles", ['role_id' => 2]); //assign customer role - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) ->post("/api/users/{$newUser->id}/roles", ['role_id' => 3]); //again assign customer role - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) ->delete("/api/users/{$newUser->id}/roles/3"); //delete - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) ->delete("/api/users/{$newUser->id}/roles/2"); //delete $response ->assertJson( - fn (AssertableJson $json) => - $json->has( + fn (AssertableJson $json) => $json->has( 'roles', - fn ($json) => - $json->has(0)->etc() //only one role + fn ($json) => $json->has(0)->etc() //only one role )->etc() ); diff --git a/tests/Feature/UserTest.php b/tests/Feature/UserTest.php index 1bc38f4..0da9197 100644 --- a/tests/Feature/UserTest.php +++ b/tests/Feature/UserTest.php @@ -3,12 +3,10 @@ namespace Tests\Feature; use App\Models\Role; -use Illuminate\Foundation\Testing\RefreshDatabase; -use Illuminate\Foundation\Testing\WithFaker; -use Tests\TestCase; -use Illuminate\Testing\Fluent\AssertableJson; use App\Models\User; use Illuminate\Support\Facades\Hash; +use Illuminate\Testing\Fluent\AssertableJson; +use Tests\TestCase; class UserTest extends TestCase { /** @@ -16,21 +14,20 @@ class UserTest extends TestCase { * * @return void */ - private $token; + private $user_id; public function test_new_user_registration() { $response = $this->postJson('/api/users', [ 'name' => 'Test User', 'email' => 'test@test.com', - 'password' => 'test' + 'password' => 'test', ]); $response ->assertJson( - fn (AssertableJson $json) => - $json->where('email', 'test@test.com') + fn (AssertableJson $json) => $json->where('email', 'test@test.com') ->where('name', 'Test User') ->etc() ); @@ -40,13 +37,12 @@ class UserTest extends TestCase { $response = $this->postJson('/api/users', [ 'name' => 'Test User', 'email' => 'test@test.com', - 'password' => 'test' + 'password' => 'test', ]); $response ->assertJson( - fn (AssertableJson $json) => - $json->where('error', 1) + fn (AssertableJson $json) => $json->where('error', 1) ->where('message', 'user already exists') ); } @@ -54,7 +50,7 @@ class UserTest extends TestCase { public function test_new_user_login() { $response = $this->postJson('/api/login', [ 'email' => 'test@test.com', - 'password' => 'test' + 'password' => 'test', ]); $data = json_decode($response->getContent()); @@ -63,8 +59,7 @@ class UserTest extends TestCase { $response ->assertJson( - fn (AssertableJson $json) => - $json->where('error', 0) + fn (AssertableJson $json) => $json->where('error', 0) ->has('token') ->has('id') ); @@ -73,70 +68,64 @@ class UserTest extends TestCase { public function test_new_user_failed_login() { $response = $this->postJson('/api/login', [ 'email' => 'test@test.com', - 'password' => 'testX' + 'password' => 'testX', ]); $response ->assertJson( - fn (AssertableJson $json) => - $json->where('error', 1) + fn (AssertableJson $json) => $json->where('error', 1) ->has('message') ); } public function test_new_user_name_update_with_user_token() { - $response = $this->postJson('/api/login', [ 'email' => 'test@test.com', - 'password' => 'test' + 'password' => 'test', ]); $data = json_decode($response->getContent()); $this->token = $data->token; $this->user_id = $data->id; - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) ->put("/api/users/{$this->user_id}", [ 'name' => 'Mini Me', ]); $response ->assertJson( - fn (AssertableJson $json) => - $json->where('name', "Mini Me") + fn (AssertableJson $json) => $json->where('name', 'Mini Me') ->etc() ); } public function test_new_user_name_update_with_admin_token() { - $response = $this->postJson('/api/login', [ 'email' => 'admin@hydra.project', - 'password' => 'hydra' + 'password' => 'hydra', ]); $data = json_decode($response->getContent()); $this->token = $data->token; $this->user_id = $data->id; - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) ->put("/api/users/{$this->user_id}", [ 'name' => 'Mini Me', ]); $response ->assertJson( - fn (AssertableJson $json) => - $json->where('name', "Mini Me") + fn (AssertableJson $json) => $json->where('name', 'Mini Me') ->etc() ); } public function test_new_user_destroy_as_user_should_fail() { - $response = $this->postJson('/api/login', [ 'email' => 'test@test.com', - 'password' => 'test' + 'password' => 'test', ]); $data = json_decode($response->getContent()); @@ -145,22 +134,20 @@ class UserTest extends TestCase { $target = User::where('email', 'test@test.com')->first(); - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) ->delete("/api/users/{$target->id}"); $response ->assertJson( - fn (AssertableJson $json) => - $json->where('error', 1) + fn (AssertableJson $json) => $json->where('error', 1) ->has('message') ); } public function test_new_user_destroy_as_admin() { - $response = $this->postJson('/api/login', [ 'email' => 'admin@hydra.project', - 'password' => 'hydra' + 'password' => 'hydra', ]); $data = json_decode($response->getContent()); @@ -169,23 +156,21 @@ class UserTest extends TestCase { $target = User::where('email', 'test@test.com')->first(); - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) ->delete("/api/users/{$target->id}"); $response ->assertJson( - fn (AssertableJson $json) => - $json->where('error', 0) + fn (AssertableJson $json) => $json->where('error', 0) ->where('message', 'user deleted') ); } public function test_delete_admin_user_if_multiple_admins_are_present() { - $newAdminUser = User::create([ 'name'=>'Test Admin', 'password'=>Hash::make('abcd'), - 'email'=>'testadmin@test.com' + 'email'=>'testadmin@test.com', ]); $adminRole = Role::find(1); @@ -194,7 +179,7 @@ class UserTest extends TestCase { $response = $this->postJson('/api/login', [ 'email' => 'admin@hydra.project', - 'password' => 'hydra' + 'password' => 'hydra', ]); $data = json_decode($response->getContent()); @@ -203,13 +188,12 @@ class UserTest extends TestCase { $target = User::where('email', 'testadmin@test.com')->first(); - $response = $this->withHeader('Authorization', 'Bearer ' . $this->token) + $response = $this->withHeader('Authorization', 'Bearer '.$this->token) ->delete("/api/users/{$target->id}"); $response ->assertJson( - fn (AssertableJson $json) => - $json->where('error', 0) + fn (AssertableJson $json) => $json->where('error', 0) ->where('message', 'user deleted') ); } diff --git a/tests/TestCase.php b/tests/TestCase.php index 2932d4a..74bf669 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -4,7 +4,6 @@ namespace Tests; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; -abstract class TestCase extends BaseTestCase -{ +abstract class TestCase extends BaseTestCase { use CreatesApplication; } diff --git a/tests/Unit/ExampleTest.php b/tests/Unit/ExampleTest.php index e5c5fef..f421239 100644 --- a/tests/Unit/ExampleTest.php +++ b/tests/Unit/ExampleTest.php @@ -4,15 +4,13 @@ namespace Tests\Unit; use PHPUnit\Framework\TestCase; -class ExampleTest extends TestCase -{ +class ExampleTest extends TestCase { /** * A basic test example. * * @return void */ - public function test_that_true_is_true() - { + public function test_that_true_is_true() { $this->assertTrue(true); } }