├── public ├── favicon.ico ├── robots.txt ├── .htaccess └── index.php ├── resources ├── css │ └── app.css ├── js │ ├── app.js │ └── bootstrap.js └── views │ └── welcome.blade.php ├── database ├── .gitignore ├── seeders │ ├── DatabaseSeeder.php │ ├── UsersSeeder.php │ └── RoleSeeder.php ├── migrations │ ├── 2022_05_17_181447_create_roles_table.php │ ├── 2014_10_12_100000_create_password_resets_table.php │ ├── 2024_01_07_095037_add_expires_at_to_personal_access_token_table.php │ ├── 2022_05_17_181456_create_user_roles_table.php │ ├── 2014_10_12_000000_create_users_table.php │ ├── 2019_08_19_000000_create_failed_jobs_table.php │ └── 2019_12_14_000001_create_personal_access_tokens_table.php └── factories │ └── UserFactory.php ├── bootstrap ├── cache │ └── .gitignore └── app.php ├── storage ├── logs │ └── .gitignore ├── app │ ├── public │ │ └── .gitignore │ └── .gitignore └── framework │ ├── testing │ └── .gitignore │ ├── views │ └── .gitignore │ ├── cache │ ├── data │ │ └── .gitignore │ └── .gitignore │ ├── sessions │ └── .gitignore │ └── .gitignore ├── .gitattributes ├── tests ├── TestCase.php ├── Unit │ └── ExampleTest.php ├── CreatesApplication.php └── Feature │ ├── HelloHydraTest.php │ ├── AdminLoginTest.php │ ├── UserTest.php │ ├── RoleTest.php │ └── UserRoleTest.php ├── .styleci.yml ├── .gitignore ├── app ├── Models │ ├── UserRole.php │ ├── Role.php │ └── User.php ├── Http │ ├── Middleware │ │ ├── EncryptCookies.php │ │ ├── VerifyCsrfToken.php │ │ ├── TrustHosts.php │ │ ├── PreventRequestsDuringMaintenance.php │ │ ├── TrimStrings.php │ │ ├── Authenticate.php │ │ ├── TrustProxies.php │ │ ├── RedirectIfAuthenticated.php │ │ └── HydraLog.php │ ├── Controllers │ │ ├── Controller.php │ │ ├── HydraController.php │ │ ├── UserRoleController.php │ │ ├── RoleController.php │ │ └── UserController.php │ └── Kernel.php ├── Providers │ ├── BroadcastServiceProvider.php │ ├── AppServiceProvider.php │ ├── AuthServiceProvider.php │ ├── EventServiceProvider.php │ └── RouteServiceProvider.php ├── Console │ └── Kernel.php └── Exceptions │ └── Handler.php ├── .editorconfig ├── package.json ├── routes ├── web.php ├── channels.php ├── console.php └── api.php ├── lang └── en │ ├── pagination.php │ ├── auth.php │ ├── passwords.php │ └── validation.php ├── webpack.mix.js ├── config ├── cors.php ├── services.php ├── view.php ├── hydra.php ├── hashing.php ├── broadcasting.php ├── sanctum.php ├── filesystems.php ├── queue.php ├── cache.php ├── mail.php ├── auth.php ├── logging.php ├── database.php ├── session.php └── app.php ├── pint.json ├── LICENSE ├── phpunit.xml ├── phpunit.xml.bak ├── .env.example ├── artisan ├── composer.json ├── docker-compose.yml └── README.md /public/favicon.ico: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /resources/css/app.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /database/.gitignore: -------------------------------------------------------------------------------- 1 | *.sqlite* 2 | -------------------------------------------------------------------------------- /bootstrap/cache/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /storage/logs/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | User-agent: * 2 | Disallow: 3 | -------------------------------------------------------------------------------- /resources/js/app.js: -------------------------------------------------------------------------------- 1 | require('./bootstrap'); 2 | 3 | -------------------------------------------------------------------------------- /storage/app/public/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /storage/app/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !public/ 3 | !.gitignore 4 | -------------------------------------------------------------------------------- /storage/framework/testing/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /storage/framework/views/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /storage/framework/cache/data/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /storage/framework/sessions/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /storage/framework/cache/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !data/ 3 | !.gitignore 4 | -------------------------------------------------------------------------------- /storage/framework/.gitignore: -------------------------------------------------------------------------------- 1 | compiled.php 2 | config.php 3 | down 4 | events.scanned.php 5 | maintenance.php 6 | routes.php 7 | routes.scanned.php 8 | schedule-* 9 | services.json 10 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto 2 | 3 | *.blade.php diff=html 4 | *.css diff=css 5 | *.html diff=html 6 | *.md diff=markdown 7 | *.php diff=php 8 | 9 | /.github export-ignore 10 | CHANGELOG.md export-ignore 11 | -------------------------------------------------------------------------------- /tests/TestCase.php: -------------------------------------------------------------------------------- 1 | assertTrue(true); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /app/Http/Middleware/EncryptCookies.php: -------------------------------------------------------------------------------- 1 | 12 | */ 13 | protected $except = [ 14 | // 15 | ]; 16 | } 17 | -------------------------------------------------------------------------------- /app/Http/Middleware/VerifyCsrfToken.php: -------------------------------------------------------------------------------- 1 | 12 | */ 13 | protected $except = [ 14 | // 15 | ]; 16 | } 17 | -------------------------------------------------------------------------------- /app/Http/Controllers/Controller.php: -------------------------------------------------------------------------------- 1 | 12 | */ 13 | public function hosts() { 14 | return [ 15 | $this->allSubdomainsOfApplicationUrl(), 16 | ]; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /app/Http/Middleware/PreventRequestsDuringMaintenance.php: -------------------------------------------------------------------------------- 1 | 12 | */ 13 | protected $except = [ 14 | // 15 | ]; 16 | } 17 | -------------------------------------------------------------------------------- /app/Http/Middleware/TrimStrings.php: -------------------------------------------------------------------------------- 1 | 12 | */ 13 | protected $except = [ 14 | 'current_password', 15 | 'password', 16 | 'password_confirmation', 17 | ]; 18 | } 19 | -------------------------------------------------------------------------------- /tests/CreatesApplication.php: -------------------------------------------------------------------------------- 1 | make(Kernel::class)->bootstrap(); 17 | 18 | return $app; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /app/Providers/BroadcastServiceProvider.php: -------------------------------------------------------------------------------- 1 | belongsToMany(User::class, 'user_roles'); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "scripts": { 4 | "dev": "npm run development", 5 | "development": "mix", 6 | "watch": "mix watch", 7 | "watch-poll": "mix watch -- --watch-options-poll=1000", 8 | "hot": "mix watch --hot", 9 | "prod": "npm run production", 10 | "production": "mix --production" 11 | }, 12 | "devDependencies": { 13 | "axios": "^1.6", 14 | "laravel-mix": "^6.0.49", 15 | "lodash": "^4.17.21", 16 | "postcss": "^8.4.33" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /app/Http/Middleware/Authenticate.php: -------------------------------------------------------------------------------- 1 | expectsJson()) { 16 | return route('login'); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /routes/web.php: -------------------------------------------------------------------------------- 1 | '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.', 9 | ]); 10 | } 11 | 12 | public function version() { 13 | return response([ 14 | 'version' => config('hydra.version'), 15 | ]); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /lang/en/pagination.php: -------------------------------------------------------------------------------- 1 | '« Previous', 17 | 'next' => 'Next »', 18 | 19 | ]; 20 | -------------------------------------------------------------------------------- /webpack.mix.js: -------------------------------------------------------------------------------- 1 | const mix = require('laravel-mix'); 2 | 3 | /* 4 | |-------------------------------------------------------------------------- 5 | | Mix Asset Management 6 | |-------------------------------------------------------------------------- 7 | | 8 | | Mix provides a clean, fluent API for defining some Webpack build steps 9 | | for your Laravel applications. By default, we are compiling the CSS 10 | | file for the application as well as bundling up all the JS files. 11 | | 12 | */ 13 | 14 | mix.js('resources/js/app.js', 'public/js') 15 | .postCss('resources/css/app.css', 'public/css', [ 16 | // 17 | ]); 18 | -------------------------------------------------------------------------------- /routes/channels.php: -------------------------------------------------------------------------------- 1 | id === (int) $id; 18 | }); 19 | -------------------------------------------------------------------------------- /database/seeders/DatabaseSeeder.php: -------------------------------------------------------------------------------- 1 | create(); 15 | 16 | // \App\Models\User::factory()->create([ 17 | // 'name' => 'Test User', 18 | // 'email' => 'test@example.com', 19 | // ]); 20 | $this->call([ 21 | RoleSeeder::class, 22 | UsersSeeder::class, 23 | ]); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /routes/console.php: -------------------------------------------------------------------------------- 1 | comment(Inspiring::quote()); 19 | })->purpose('Display an inspiring quote'); 20 | -------------------------------------------------------------------------------- /public/.htaccess: -------------------------------------------------------------------------------- 1 | 2 | 3 | Options -MultiViews -Indexes 4 | 5 | 6 | RewriteEngine On 7 | 8 | # Handle Authorization Header 9 | RewriteCond %{HTTP:Authorization} . 10 | RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] 11 | 12 | # Redirect Trailing Slashes If Not A Folder... 13 | RewriteCond %{REQUEST_FILENAME} !-d 14 | RewriteCond %{REQUEST_URI} (.+)/$ 15 | RewriteRule ^ %1 [L,R=301] 16 | 17 | # Send Requests To Front Controller... 18 | RewriteCond %{REQUEST_FILENAME} !-d 19 | RewriteCond %{REQUEST_FILENAME} !-f 20 | RewriteRule ^ index.php [L] 21 | 22 | -------------------------------------------------------------------------------- /app/Providers/AuthServiceProvider.php: -------------------------------------------------------------------------------- 1 | 12 | */ 13 | protected $policies = [ 14 | // 'App\Models\Model' => 'App\Policies\ModelPolicy', 15 | ]; 16 | 17 | /** 18 | * Register any authentication / authorization services. 19 | * 20 | * @return void 21 | */ 22 | public function boot() { 23 | $this->registerPolicies(); 24 | 25 | // 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /app/Console/Kernel.php: -------------------------------------------------------------------------------- 1 | command('inspire')->hourly(); 16 | } 17 | 18 | /** 19 | * Register the commands for the application. 20 | * 21 | * @return void 22 | */ 23 | protected function commands() { 24 | $this->load(__DIR__.'/Commands'); 25 | 26 | require base_path('routes/console.php'); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /lang/en/auth.php: -------------------------------------------------------------------------------- 1 | 'These credentials do not match our records.', 17 | 'password' => 'The provided password is incorrect.', 18 | 'throttle' => 'Too many login attempts. Please try again in :seconds seconds.', 19 | 20 | ]; 21 | -------------------------------------------------------------------------------- /app/Http/Middleware/TrustProxies.php: -------------------------------------------------------------------------------- 1 | |string|null 13 | */ 14 | protected $proxies; 15 | 16 | /** 17 | * The headers that should be used to detect proxies. 18 | * 19 | * @var int 20 | */ 21 | protected $headers = 22 | Request::HEADER_X_FORWARDED_FOR | 23 | Request::HEADER_X_FORWARDED_HOST | 24 | Request::HEADER_X_FORWARDED_PORT | 25 | Request::HEADER_X_FORWARDED_PROTO | 26 | Request::HEADER_X_FORWARDED_AWS_ELB; 27 | } 28 | -------------------------------------------------------------------------------- /tests/Feature/HelloHydraTest.php: -------------------------------------------------------------------------------- 1 | get('/api/hydra'); 15 | 16 | $response 17 | ->assertStatus(200) 18 | ->assertJson([ 19 | 'message' => true, 20 | ]); 21 | } 22 | 23 | public function test_hydra_version() { 24 | $response = $this->get('/api/hydra/version'); 25 | 26 | $response 27 | ->assertStatus(200) 28 | ->assertJson([ 29 | 'version' => true, 30 | ]); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /database/migrations/2022_05_17_181447_create_roles_table.php: -------------------------------------------------------------------------------- 1 | id(); 16 | $table->string('name'); 17 | $table->string('slug')->index(); 18 | $table->timestamps(); 19 | }); 20 | } 21 | 22 | /** 23 | * Reverse the migrations. 24 | * 25 | * @return void 26 | */ 27 | public function down() { 28 | Schema::dropIfExists('roles'); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /database/migrations/2014_10_12_100000_create_password_resets_table.php: -------------------------------------------------------------------------------- 1 | string('email')->index(); 16 | $table->string('token'); 17 | $table->timestamp('created_at')->nullable(); 18 | }); 19 | } 20 | 21 | /** 22 | * Reverse the migrations. 23 | * 24 | * @return void 25 | */ 26 | public function down() { 27 | Schema::dropIfExists('password_resets'); 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /lang/en/passwords.php: -------------------------------------------------------------------------------- 1 | 'Your password has been reset!', 17 | 'sent' => 'We have emailed your password reset link!', 18 | 'throttled' => 'Please wait before retrying.', 19 | 'token' => 'This password reset token is invalid.', 20 | 'user' => "We can't find a user with that email address.", 21 | 22 | ]; 23 | -------------------------------------------------------------------------------- /database/migrations/2024_01_07_095037_add_expires_at_to_personal_access_token_table.php: -------------------------------------------------------------------------------- 1 | timestamp('expires_at')->nullable()->after('last_used_at'); 16 | }); 17 | } 18 | 19 | /** 20 | * Reverse the migrations. 21 | * 22 | * @return void 23 | */ 24 | public function down() { 25 | Schema::table('personal_access_tokens', function (Blueprint $table) { 26 | $table->dropColumn('expires_at'); 27 | }); 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /database/seeders/UsersSeeder.php: -------------------------------------------------------------------------------- 1 | truncate(); 21 | Schema::enableForeignKeyConstraints(); 22 | 23 | $user = User::create([ 24 | 'email' => 'admin@hydra.project', 25 | 'password' => Hash::make('hydra'), 26 | 'name' => 'Hydra Admin', 27 | ]); 28 | $user->roles()->attach(Role::where('slug', 'admin')->first()); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /database/migrations/2022_05_17_181456_create_user_roles_table.php: -------------------------------------------------------------------------------- 1 | id(); 16 | $table->foreignId('user_id')->constrained()->cascadeOnDelete(); 17 | $table->foreignId('role_id')->constrained()->cascadeOnDelete(); 18 | $table->unique(['user_id', 'role_id']); 19 | $table->timestamps(); 20 | }); 21 | } 22 | 23 | /** 24 | * Reverse the migrations. 25 | * 26 | * @return void 27 | */ 28 | public function down() { 29 | Schema::dropIfExists('user_roles'); 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /database/migrations/2014_10_12_000000_create_users_table.php: -------------------------------------------------------------------------------- 1 | id(); 16 | $table->string('name'); 17 | $table->string('email')->unique(); 18 | $table->timestamp('email_verified_at')->nullable(); 19 | $table->string('password'); 20 | $table->rememberToken(); 21 | $table->timestamps(); 22 | }); 23 | } 24 | 25 | /** 26 | * Reverse the migrations. 27 | * 28 | * @return void 29 | */ 30 | public function down() { 31 | Schema::dropIfExists('users'); 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /app/Http/Middleware/RedirectIfAuthenticated.php: -------------------------------------------------------------------------------- 1 | check()) { 23 | return redirect(RouteServiceProvider::HOME); 24 | } 25 | } 26 | 27 | return $next($request); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /config/cors.php: -------------------------------------------------------------------------------- 1 | ['api/*', 'sanctum/csrf-cookie'], 19 | 20 | 'allowed_methods' => ['*'], 21 | 22 | 'allowed_origins' => ['*'], 23 | 24 | 'allowed_origins_patterns' => [], 25 | 26 | 'allowed_headers' => ['*'], 27 | 28 | 'exposed_headers' => [], 29 | 30 | 'max_age' => 0, 31 | 32 | 'supports_credentials' => false, 33 | 34 | ]; 35 | -------------------------------------------------------------------------------- /database/migrations/2019_08_19_000000_create_failed_jobs_table.php: -------------------------------------------------------------------------------- 1 | id(); 16 | $table->string('uuid')->unique(); 17 | $table->text('connection'); 18 | $table->text('queue'); 19 | $table->longText('payload'); 20 | $table->longText('exception'); 21 | $table->timestamp('failed_at')->useCurrent(); 22 | }); 23 | } 24 | 25 | /** 26 | * Reverse the migrations. 27 | * 28 | * @return void 29 | */ 30 | public function down() { 31 | Schema::dropIfExists('failed_jobs'); 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php: -------------------------------------------------------------------------------- 1 | id(); 16 | $table->morphs('tokenable'); 17 | $table->string('name'); 18 | $table->string('token', 64)->unique(); 19 | $table->text('abilities')->nullable(); 20 | $table->timestamp('last_used_at')->nullable(); 21 | $table->timestamps(); 22 | }); 23 | } 24 | 25 | /** 26 | * Reverse the migrations. 27 | * 28 | * @return void 29 | */ 30 | public function down() { 31 | Schema::dropIfExists('personal_access_tokens'); 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /resources/js/bootstrap.js: -------------------------------------------------------------------------------- 1 | window._ = require('lodash'); 2 | 3 | /** 4 | * We'll load the axios HTTP library which allows us to easily issue requests 5 | * to our Laravel back-end. This library automatically handles sending the 6 | * CSRF token as a header based on the value of the "XSRF" token cookie. 7 | */ 8 | 9 | window.axios = require('axios'); 10 | // window.axios.defaults.withCredentials = true; 11 | window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; 12 | 13 | /** 14 | * Echo exposes an expressive API for subscribing to channels and listening 15 | * for events that are broadcast by Laravel. Echo and event broadcasting 16 | * allows your team to easily build robust real-time web applications. 17 | */ 18 | 19 | // import Echo from 'laravel-echo'; 20 | 21 | // window.Pusher = require('pusher-js'); 22 | 23 | // window.Echo = new Echo({ 24 | // broadcaster: 'pusher', 25 | // key: process.env.MIX_PUSHER_APP_KEY, 26 | // cluster: process.env.MIX_PUSHER_APP_CLUSTER, 27 | // forceTLS: true 28 | // }); 29 | -------------------------------------------------------------------------------- /app/Http/Middleware/HydraLog.php: -------------------------------------------------------------------------------- 1 | $request->route()]); 23 | Log::debug('app.headers', ['headers' => $request->headers]); 24 | Log::debug('app.requests', ['request' => $request->all()]); 25 | Log::debug('app.response', ['response' => $response]); 26 | Log::info("\n\n".str_repeat('=', 100)."\n\n"); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /database/seeders/RoleSeeder.php: -------------------------------------------------------------------------------- 1 | truncate(); 19 | Schema::enableForeignKeyConstraints(); 20 | 21 | $roles = [ 22 | ['name' => 'Administrator', 'slug' => 'admin'], 23 | ['name' => 'User', 'slug' => 'user'], 24 | ['name' => 'Customer', 'slug' => 'customer'], 25 | ['name' => 'Editor', 'slug' => 'editor'], 26 | ['name' => 'All', 'slug' => '*'], 27 | ['name' => 'Super Admin', 'slug' => 'super-admin'], 28 | ]; 29 | 30 | collect($roles)->each(function ($role) { 31 | Role::create($role); 32 | }); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /pint.json: -------------------------------------------------------------------------------- 1 | { 2 | "preset": "laravel", 3 | "rules": { 4 | "simplified_null_return": true, 5 | "braces": { 6 | "allow_single_line_anonymous_class_with_empty_body": true, 7 | "allow_single_line_closure": true, 8 | "position_after_control_structures": "same", 9 | "position_after_functions_and_oop_constructs": "same", 10 | "position_after_anonymous_constructs": "same" 11 | }, 12 | "curly_braces_position": { 13 | "control_structures_opening_brace": "same_line", 14 | "functions_opening_brace": "same_line", 15 | "anonymous_functions_opening_brace": "same_line", 16 | "classes_opening_brace": "same_line", 17 | "anonymous_classes_opening_brace": "same_line", 18 | "allow_single_line_empty_anonymous_classes": true, 19 | "allow_single_line_anonymous_functions": true 20 | }, 21 | "new_with_braces": { 22 | "anonymous_class": false, 23 | "named_class": false 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/Providers/EventServiceProvider.php: -------------------------------------------------------------------------------- 1 | > 15 | */ 16 | protected $listen = [ 17 | Registered::class => [ 18 | SendEmailVerificationNotification::class, 19 | ], 20 | ]; 21 | 22 | /** 23 | * Register any events for your application. 24 | * 25 | * @return void 26 | */ 27 | public function boot() { 28 | // 29 | } 30 | 31 | /** 32 | * Determine if events and listeners should be automatically discovered. 33 | * 34 | * @return bool 35 | */ 36 | public function shouldDiscoverEvents() { 37 | return false; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /config/services.php: -------------------------------------------------------------------------------- 1 | [ 18 | 'domain' => env('MAILGUN_DOMAIN'), 19 | 'secret' => env('MAILGUN_SECRET'), 20 | 'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'), 21 | 'scheme' => 'https', 22 | ], 23 | 24 | 'postmark' => [ 25 | 'token' => env('POSTMARK_TOKEN'), 26 | ], 27 | 28 | 'ses' => [ 29 | 'key' => env('AWS_ACCESS_KEY_ID'), 30 | 'secret' => env('AWS_SECRET_ACCESS_KEY'), 31 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), 32 | ], 33 | 34 | ]; 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Hasin Hayder 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /tests/Feature/AdminLoginTest.php: -------------------------------------------------------------------------------- 1 | postJson('/api/login', [ 16 | 'email' => 'admin@hydra.project', 17 | 'password' => 'hydra', 18 | ]); 19 | 20 | $response 21 | ->assertJson(fn (AssertableJson $json) => $json->where('error', 0) 22 | ->has('token') 23 | ->etc() 24 | ); 25 | } 26 | 27 | public function test_admin_login_fail() { 28 | $response = $this->postJson('/api/login', [ 29 | 'email' => 'admin@hydra.project', 30 | 'password' => 'hydrax', 31 | ]); 32 | 33 | $response 34 | ->assertJson(fn (AssertableJson $json) => $json->where('error', 1) 35 | ->missing('token') 36 | ->has('message') 37 | ); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | ./tests/Unit 6 | 7 | 8 | ./tests/Feature 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | ./app 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /database/factories/UserFactory.php: -------------------------------------------------------------------------------- 1 | 10 | */ 11 | class UserFactory extends Factory { 12 | /** 13 | * Define the model's default state. 14 | * 15 | * @return array 16 | */ 17 | public function definition() { 18 | return [ 19 | 'name' => $this->faker->name(), 20 | 'email' => $this->faker->unique()->safeEmail(), 21 | 'email_verified_at' => now(), 22 | 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password 23 | 'remember_token' => Str::random(10), 24 | ]; 25 | } 26 | 27 | /** 28 | * Indicate that the model's email address should be unverified. 29 | * 30 | * @return static 31 | */ 32 | public function unverified() { 33 | return $this->state(function (array $attributes) { 34 | return [ 35 | 'email_verified_at' => null, 36 | ]; 37 | }); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /config/view.php: -------------------------------------------------------------------------------- 1 | [ 17 | resource_path('views'), 18 | ], 19 | 20 | /* 21 | |-------------------------------------------------------------------------- 22 | | Compiled View Path 23 | |-------------------------------------------------------------------------- 24 | | 25 | | This option determines where all the compiled Blade templates will be 26 | | stored for your application. Typically, this is within the storage 27 | | directory. However, as usual, you are free to change this value. 28 | | 29 | */ 30 | 31 | 'compiled' => env( 32 | 'VIEW_COMPILED_PATH', 33 | realpath(storage_path('framework/views')) 34 | ), 35 | 36 | ]; 37 | -------------------------------------------------------------------------------- /app/Models/User.php: -------------------------------------------------------------------------------- 1 | 17 | */ 18 | protected $fillable = [ 19 | 'name', 20 | 'email', 21 | 'password', 22 | ]; 23 | 24 | /** 25 | * The attributes that should be hidden for serialization. 26 | * 27 | * @var array 28 | */ 29 | protected $hidden = [ 30 | 'password', 31 | 'remember_token', 32 | 'created_at', 33 | 'updated_at', 34 | 'email_verified_at', 35 | ]; 36 | 37 | /** 38 | * The attributes that should be cast. 39 | * 40 | * @var array 41 | */ 42 | protected $casts = [ 43 | 'email_verified_at' => 'datetime', 44 | ]; 45 | 46 | public function roles() { 47 | return $this->belongsToMany(Role::class, 'user_roles'); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /app/Http/Controllers/UserRoleController.php: -------------------------------------------------------------------------------- 1 | load('roles'); 17 | } 18 | 19 | /** 20 | * Store a newly created resource in storage. 21 | * 22 | * @return \App\Models\User $user 23 | */ 24 | public function store(Request $request, User $user) { 25 | $data = $request->validate([ 26 | 'role_id' => 'required|integer', 27 | ]); 28 | $role = Role::find($data['role_id']); 29 | if (! $user->roles()->find($data['role_id'])) { 30 | $user->roles()->attach($role); 31 | } 32 | 33 | return $user->load('roles'); 34 | } 35 | 36 | /** 37 | * Remove the specified resource from storage. 38 | * 39 | * @return \App\Models\User $user 40 | */ 41 | public function destroy(User $user, Role $role) { 42 | $user->roles()->detach($role); 43 | 44 | return $user->load('roles'); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /phpunit.xml.bak: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | ./tests/Unit 10 | 11 | 12 | ./tests/Feature 13 | 14 | 15 | 16 | 17 | ./app 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | APP_NAME=Laravel 2 | APP_ENV=local 3 | APP_KEY= 4 | APP_VERSION=1.1.0 5 | APP_DEBUG=true 6 | APP_URL=http://localhost 7 | 8 | LOG_CHANNEL=stack 9 | LOG_DEPRECATIONS_CHANNEL=null 10 | LOG_LEVEL=debug 11 | 12 | DB_CONNECTION=sqlite 13 | DB_HOST=127.0.0.1 14 | DB_PORT=3306 15 | DB_DATABASE=hydra.sqlite 16 | DB_USERNAME=root 17 | DB_PASSWORD= 18 | 19 | BROADCAST_DRIVER=log 20 | CACHE_DRIVER=file 21 | FILESYSTEM_DISK=local 22 | QUEUE_CONNECTION=sync 23 | SESSION_DRIVER=file 24 | SESSION_LIFETIME=120 25 | 26 | MEMCACHED_HOST=127.0.0.1 27 | 28 | REDIS_HOST=127.0.0.1 29 | REDIS_PASSWORD=null 30 | REDIS_PORT=6379 31 | 32 | MAIL_MAILER=smtp 33 | MAIL_HOST=mailhog 34 | MAIL_PORT=1025 35 | MAIL_USERNAME=null 36 | MAIL_PASSWORD=null 37 | MAIL_ENCRYPTION=null 38 | MAIL_FROM_ADDRESS="hello@example.com" 39 | MAIL_FROM_NAME="${APP_NAME}" 40 | 41 | AWS_ACCESS_KEY_ID= 42 | AWS_SECRET_ACCESS_KEY= 43 | AWS_DEFAULT_REGION=us-east-1 44 | AWS_BUCKET= 45 | AWS_USE_PATH_STYLE_ENDPOINT=false 46 | 47 | PUSHER_APP_ID= 48 | PUSHER_APP_KEY= 49 | PUSHER_APP_SECRET= 50 | PUSHER_APP_CLUSTER=mt1 51 | 52 | MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}" 53 | MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}" 54 | 55 | SANCTUM_STATEFUL_DOMAINS="localhost,localhost:3000,localhost:8000,127.0.0.1,127.0.0.1:8000,::1" 56 | 57 | DEFAULT_ROLE_SLUG=user 58 | DELETE_PREVIOUS_ACCESS_TOKENS_ON_LOGIN=false 59 | -------------------------------------------------------------------------------- /config/hydra.php: -------------------------------------------------------------------------------- 1 | env('APP_VERSION', '1.2.0'), 15 | 16 | /* 17 | |-------------------------------------------------------------------------- 18 | | Default user role 19 | |-------------------------------------------------------------------------- 20 | | 21 | | This value is the default user role id that will be assigned to new users 22 | | when they register. 23 | | 24 | | admin = Admin role, user = User role, customer = Customer Role - Check RoleSeeder for more 25 | | 26 | */ 27 | 28 | 'default_user_role_slug' => env('DEFAULT_ROLE_SLUG', 'user'), 29 | 30 | /* 31 | |-------------------------------------------------------------------------- 32 | | Delete old access tokens when logged in 33 | |-------------------------------------------------------------------------- 34 | | 35 | | This value determines whether or not to delete old access tokens when 36 | | the users are logged in. 37 | | 38 | */ 39 | 40 | 'delete_previous_access_tokens_on_login' => env('DELETE_PREVIOUS_ACCESS_TOKENS_ON_LOGIN', false), 41 | ]; 42 | -------------------------------------------------------------------------------- /app/Providers/RouteServiceProvider.php: -------------------------------------------------------------------------------- 1 | configureRateLimiting(); 28 | 29 | $this->routes(function () { 30 | Route::middleware('api') 31 | ->prefix('api') 32 | ->group(base_path('routes/api.php')); 33 | 34 | Route::middleware('web') 35 | ->group(base_path('routes/web.php')); 36 | }); 37 | } 38 | 39 | /** 40 | * Configure the rate limiters for the application. 41 | * 42 | * @return void 43 | */ 44 | protected function configureRateLimiting() { 45 | RateLimiter::for('api', function (Request $request) { 46 | return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip()); 47 | }); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /config/hashing.php: -------------------------------------------------------------------------------- 1 | 'bcrypt', 19 | 20 | /* 21 | |-------------------------------------------------------------------------- 22 | | Bcrypt Options 23 | |-------------------------------------------------------------------------- 24 | | 25 | | Here you may specify the configuration options that should be used when 26 | | passwords are hashed using the Bcrypt algorithm. This will allow you 27 | | to control the amount of time it takes to hash the given password. 28 | | 29 | */ 30 | 31 | 'bcrypt' => [ 32 | 'rounds' => env('BCRYPT_ROUNDS', 10), 33 | ], 34 | 35 | /* 36 | |-------------------------------------------------------------------------- 37 | | Argon Options 38 | |-------------------------------------------------------------------------- 39 | | 40 | | Here you may specify the configuration options that should be used when 41 | | passwords are hashed using the Argon algorithm. These will allow you 42 | | to control the amount of time it takes to hash the given password. 43 | | 44 | */ 45 | 46 | 'argon' => [ 47 | 'memory' => 65536, 48 | 'threads' => 1, 49 | 'time' => 4, 50 | ], 51 | 52 | ]; 53 | -------------------------------------------------------------------------------- /bootstrap/app.php: -------------------------------------------------------------------------------- 1 | singleton( 30 | Illuminate\Contracts\Http\Kernel::class, 31 | App\Http\Kernel::class 32 | ); 33 | 34 | $app->singleton( 35 | Illuminate\Contracts\Console\Kernel::class, 36 | App\Console\Kernel::class 37 | ); 38 | 39 | $app->singleton( 40 | Illuminate\Contracts\Debug\ExceptionHandler::class, 41 | App\Exceptions\Handler::class 42 | ); 43 | 44 | /* 45 | |-------------------------------------------------------------------------- 46 | | Return The Application 47 | |-------------------------------------------------------------------------- 48 | | 49 | | This script returns the application instance. The instance is given to 50 | | the calling script so we can separate the building of the instances 51 | | from the actual running of the application and sending responses. 52 | | 53 | */ 54 | 55 | return $app; 56 | -------------------------------------------------------------------------------- /artisan: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env php 2 | make(Illuminate\Contracts\Console\Kernel::class); 34 | 35 | $status = $kernel->handle( 36 | $input = new Symfony\Component\Console\Input\ArgvInput, 37 | new Symfony\Component\Console\Output\ConsoleOutput 38 | ); 39 | 40 | /* 41 | |-------------------------------------------------------------------------- 42 | | Shutdown The Application 43 | |-------------------------------------------------------------------------- 44 | | 45 | | Once Artisan has finished running, we will fire off the shutdown events 46 | | so that any final work may be done by the application before we shut 47 | | down the process. This is the last thing to happen to the request. 48 | | 49 | */ 50 | 51 | $kernel->terminate($input, $status); 52 | 53 | exit($status); 54 | -------------------------------------------------------------------------------- /public/index.php: -------------------------------------------------------------------------------- 1 | make(Kernel::class); 50 | 51 | $response = $kernel->handle( 52 | $request = Request::capture() 53 | )->send(); 54 | 55 | $kernel->terminate($request, $response); 56 | -------------------------------------------------------------------------------- /app/Exceptions/Handler.php: -------------------------------------------------------------------------------- 1 | , \Psr\Log\LogLevel::*> 15 | */ 16 | protected $levels = [ 17 | // 18 | ]; 19 | 20 | /** 21 | * A list of the exception types that are not reported. 22 | * 23 | * @var array> 24 | */ 25 | protected $dontReport = [ 26 | // 27 | ]; 28 | 29 | /** 30 | * A list of the inputs that are never flashed to the session on validation exceptions. 31 | * 32 | * @var array 33 | */ 34 | protected $dontFlash = [ 35 | 'current_password', 36 | 'password', 37 | 'password_confirmation', 38 | ]; 39 | 40 | /** 41 | * Register the exception handling callbacks for the application. 42 | * 43 | * @return void 44 | */ 45 | public function register() { 46 | $this->reportable(function (Throwable $e) { 47 | // 48 | }); 49 | } 50 | 51 | public function render($request, Throwable $exception) { 52 | if ($exception instanceof ModelNotFoundException) { 53 | return response([ 54 | 'error' => 1, 55 | 'message' => $exception->getMessage(), 56 | ], 404); 57 | } 58 | 59 | if ($exception instanceof MissingAbilityException) { 60 | return response([ 61 | 'error' => 1, 62 | 'message' => 'Not authorized', 63 | ], 409); 64 | } 65 | 66 | return parent::render($request, $exception); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "laravel/laravel", 3 | "type": "project", 4 | "description": "The Laravel Framework.", 5 | "keywords": [ 6 | "framework", 7 | "laravel" 8 | ], 9 | "license": "MIT", 10 | "require": { 11 | "php": "^8.1", 12 | "guzzlehttp/guzzle": "^7.4.4", 13 | "laravel/framework": "^10.0", 14 | "laravel/sanctum": "^3.2", 15 | "laravel/tinker": "^2.7" 16 | }, 17 | "require-dev": { 18 | "fakerphp/faker": "^1.9.1", 19 | "laravel/pint": "^1.1.0", 20 | "laravel/sail": "^1.15", 21 | "mockery/mockery": "^1.4.4", 22 | "nunomaduro/collision": "^7.0", 23 | "phpunit/phpunit": "^10.0", 24 | "spatie/laravel-ignition": "^2.0" 25 | }, 26 | "autoload": { 27 | "psr-4": { 28 | "App\\": "app/", 29 | "Database\\Factories\\": "database/factories/", 30 | "Database\\Seeders\\": "database/seeders/" 31 | } 32 | }, 33 | "autoload-dev": { 34 | "psr-4": { 35 | "Tests\\": "tests/" 36 | } 37 | }, 38 | "scripts": { 39 | "post-autoload-dump": [ 40 | "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump", 41 | "@php artisan package:discover --ansi" 42 | ], 43 | "post-update-cmd": [ 44 | "@php artisan vendor:publish --tag=laravel-assets --ansi --force" 45 | ], 46 | "post-root-package-install": [ 47 | "@php -r \"file_exists('.env') || copy('.env.example', '.env');\"" 48 | ], 49 | "post-create-project-cmd": [ 50 | "@php artisan key:generate --ansi" 51 | ] 52 | }, 53 | "extra": { 54 | "laravel": { 55 | "dont-discover": [] 56 | } 57 | }, 58 | "config": { 59 | "optimize-autoloader": true, 60 | "preferred-install": "dist", 61 | "sort-packages": true 62 | }, 63 | "minimum-stability": "stable", 64 | "prefer-stable": true 65 | } 66 | -------------------------------------------------------------------------------- /routes/api.php: -------------------------------------------------------------------------------- 1 | except(['edit', 'create', 'store', 'update'])->middleware(['auth:sanctum', 'ability:admin,super-admin']); 27 | Route::post('users', [UserController::class, 'store']); 28 | Route::put('users/{user}', [UserController::class, 'update'])->middleware(['auth:sanctum', 'ability:admin,super-admin,user']); 29 | Route::post('users/{user}', [UserController::class, 'update'])->middleware(['auth:sanctum', 'ability:admin,super-admin,user']); 30 | Route::patch('users/{user}', [UserController::class, 'update'])->middleware(['auth:sanctum', 'ability:admin,super-admin,user']); 31 | Route::get('me', [UserController::class, 'me'])->middleware('auth:sanctum'); 32 | Route::post('login', [UserController::class, 'login']); 33 | 34 | Route::apiResource('roles', RoleController::class)->except(['create', 'edit'])->middleware(['auth:sanctum', 'ability:admin,super-admin,user']); 35 | Route::apiResource('users.roles', UserRoleController::class)->except(['create', 'edit', 'show', 'update'])->middleware(['auth:sanctum', 'ability:admin,super-admin']); 36 | -------------------------------------------------------------------------------- /config/broadcasting.php: -------------------------------------------------------------------------------- 1 | env('BROADCAST_DRIVER', 'null'), 19 | 20 | /* 21 | |-------------------------------------------------------------------------- 22 | | Broadcast Connections 23 | |-------------------------------------------------------------------------- 24 | | 25 | | Here you may define all of the broadcast connections that will be used 26 | | to broadcast events to other systems or over websockets. Samples of 27 | | each available type of connection are provided inside this array. 28 | | 29 | */ 30 | 31 | 'connections' => [ 32 | 33 | 'pusher' => [ 34 | 'driver' => 'pusher', 35 | 'key' => env('PUSHER_APP_KEY'), 36 | 'secret' => env('PUSHER_APP_SECRET'), 37 | 'app_id' => env('PUSHER_APP_ID'), 38 | 'options' => [ 39 | 'cluster' => env('PUSHER_APP_CLUSTER'), 40 | 'useTLS' => true, 41 | ], 42 | 'client_options' => [ 43 | // Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html 44 | ], 45 | ], 46 | 47 | 'ably' => [ 48 | 'driver' => 'ably', 49 | 'key' => env('ABLY_KEY'), 50 | ], 51 | 52 | 'redis' => [ 53 | 'driver' => 'redis', 54 | 'connection' => 'default', 55 | ], 56 | 57 | 'log' => [ 58 | 'driver' => 'log', 59 | ], 60 | 61 | 'null' => [ 62 | 'driver' => 'null', 63 | ], 64 | 65 | ], 66 | 67 | ]; 68 | -------------------------------------------------------------------------------- /config/sanctum.php: -------------------------------------------------------------------------------- 1 | explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf( 19 | '%s%s', 20 | 'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1', 21 | Sanctum::currentApplicationUrlWithPort() 22 | ))), 23 | 24 | /* 25 | |-------------------------------------------------------------------------- 26 | | Sanctum Guards 27 | |-------------------------------------------------------------------------- 28 | | 29 | | This array contains the authentication guards that will be checked when 30 | | Sanctum is trying to authenticate a request. If none of these guards 31 | | are able to authenticate the request, Sanctum will use the bearer 32 | | token that's present on an incoming request for authentication. 33 | | 34 | */ 35 | 36 | 'guard' => ['web'], 37 | 38 | /* 39 | |-------------------------------------------------------------------------- 40 | | Expiration Minutes 41 | |-------------------------------------------------------------------------- 42 | | 43 | | This value controls the number of minutes until an issued token will be 44 | | considered expired. If this value is null, personal access tokens do 45 | | not expire. This won't tweak the lifetime of first-party sessions. 46 | | 47 | */ 48 | 49 | 'expiration' => null, 50 | 51 | /* 52 | |-------------------------------------------------------------------------- 53 | | Sanctum Middleware 54 | |-------------------------------------------------------------------------- 55 | | 56 | | When authenticating your first-party SPA with Sanctum you may need to 57 | | customize some of the middleware Sanctum uses while processing the 58 | | request. You may change the middleware listed below as required. 59 | | 60 | */ 61 | 62 | 'middleware' => [ 63 | 'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class, 64 | 'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class, 65 | ], 66 | 67 | ]; 68 | -------------------------------------------------------------------------------- /config/filesystems.php: -------------------------------------------------------------------------------- 1 | env('FILESYSTEM_DISK', 'local'), 17 | 18 | /* 19 | |-------------------------------------------------------------------------- 20 | | Filesystem Disks 21 | |-------------------------------------------------------------------------- 22 | | 23 | | Here you may configure as many filesystem "disks" as you wish, and you 24 | | may even configure multiple disks of the same driver. Defaults have 25 | | been set up for each driver as an example of the required values. 26 | | 27 | | Supported Drivers: "local", "ftp", "sftp", "s3" 28 | | 29 | */ 30 | 31 | 'disks' => [ 32 | 33 | 'local' => [ 34 | 'driver' => 'local', 35 | 'root' => storage_path('app'), 36 | 'throw' => false, 37 | ], 38 | 39 | 'public' => [ 40 | 'driver' => 'local', 41 | 'root' => storage_path('app/public'), 42 | 'url' => env('APP_URL').'/storage', 43 | 'visibility' => 'public', 44 | 'throw' => false, 45 | ], 46 | 47 | 's3' => [ 48 | 'driver' => 's3', 49 | 'key' => env('AWS_ACCESS_KEY_ID'), 50 | 'secret' => env('AWS_SECRET_ACCESS_KEY'), 51 | 'region' => env('AWS_DEFAULT_REGION'), 52 | 'bucket' => env('AWS_BUCKET'), 53 | 'url' => env('AWS_URL'), 54 | 'endpoint' => env('AWS_ENDPOINT'), 55 | 'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false), 56 | 'throw' => false, 57 | ], 58 | 59 | ], 60 | 61 | /* 62 | |-------------------------------------------------------------------------- 63 | | Symbolic Links 64 | |-------------------------------------------------------------------------- 65 | | 66 | | Here you may configure the symbolic links that will be created when the 67 | | `storage:link` Artisan command is executed. The array keys should be 68 | | the locations of the links and the values should be their targets. 69 | | 70 | */ 71 | 72 | 'links' => [ 73 | public_path('storage') => storage_path('app/public'), 74 | ], 75 | 76 | ]; 77 | -------------------------------------------------------------------------------- /app/Http/Controllers/RoleController.php: -------------------------------------------------------------------------------- 1 | validate([ 25 | 'name' => 'required', 26 | 'slug' => 'required', 27 | ]); 28 | 29 | $existing = Role::where('slug', $data['slug'])->first(); 30 | 31 | if (! $existing) { 32 | $role = Role::create([ 33 | 'name' => $data['name'], 34 | 'slug' => $data['slug'], 35 | ]); 36 | 37 | return $role; 38 | } 39 | 40 | return response(['error' => 1, 'message' => 'role already exists'], 409); 41 | } 42 | 43 | /** 44 | * Display the specified resource. 45 | * 46 | * @return \App\Models\Role $role 47 | */ 48 | public function show(Role $role) { 49 | return $role; 50 | } 51 | 52 | /** 53 | * Update the specified resource in storage. 54 | * 55 | * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response|Role 56 | */ 57 | public function update(Request $request, ?Role $role = null) { 58 | if (! $role) { 59 | return response(['error' => 1, 'message' => 'role doesn\'t exist'], 404); 60 | } 61 | 62 | $role->name = $request->name ?? $role->name; 63 | 64 | if ($request->slug) { 65 | if ($role->slug != 'admin' && $role->slug != 'super-admin') { 66 | //don't allow changing the admin slug, because it will make the routes inaccessbile due to faile ability check 67 | $role->slug = $request->slug; 68 | } 69 | } 70 | 71 | $role->update(); 72 | 73 | return $role; 74 | } 75 | 76 | /** 77 | * Remove the specified resource from storage. 78 | * 79 | * @return \Illuminate\Http\Response 80 | */ 81 | public function destroy(Role $role) { 82 | if ($role->slug != 'admin' && $role->slug != 'super-admin') { 83 | //don't allow changing the admin slug, because it will make the routes inaccessbile due to faile ability check 84 | $role->delete(); 85 | 86 | return response(['error' => 0, 'message' => 'role has been deleted']); 87 | } 88 | 89 | return response(['error' => 1, 'message' => 'you cannot delete this role'], 422); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /app/Http/Kernel.php: -------------------------------------------------------------------------------- 1 | 14 | */ 15 | protected $middleware = [ 16 | // \App\Http\Middleware\TrustHosts::class, 17 | \App\Http\Middleware\TrustProxies::class, 18 | \Illuminate\Http\Middleware\HandleCors::class, 19 | \App\Http\Middleware\PreventRequestsDuringMaintenance::class, 20 | \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, 21 | \App\Http\Middleware\TrimStrings::class, 22 | \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, 23 | ]; 24 | 25 | /** 26 | * The application's route middleware groups. 27 | * 28 | * @var array> 29 | */ 30 | protected $middlewareGroups = [ 31 | 'web' => [ 32 | \App\Http\Middleware\EncryptCookies::class, 33 | \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, 34 | \Illuminate\Session\Middleware\StartSession::class, 35 | \Illuminate\View\Middleware\ShareErrorsFromSession::class, 36 | \App\Http\Middleware\VerifyCsrfToken::class, 37 | \Illuminate\Routing\Middleware\SubstituteBindings::class, 38 | ], 39 | 40 | 'api' => [ 41 | \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, 42 | 'throttle:api', 43 | \Illuminate\Routing\Middleware\SubstituteBindings::class, 44 | ], 45 | ]; 46 | 47 | /** 48 | * The application's route middleware. 49 | * 50 | * These middleware may be assigned to groups or used individually. 51 | * 52 | * @var array 53 | */ 54 | protected $routeMiddleware = [ 55 | 'auth' => \App\Http\Middleware\Authenticate::class, 56 | 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 57 | 'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class, 58 | 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, 59 | 'can' => \Illuminate\Auth\Middleware\Authorize::class, 60 | 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 61 | 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class, 62 | 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, 63 | 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 64 | 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, 65 | 'abilities' => \Laravel\Sanctum\Http\Middleware\CheckAbilities::class, 66 | 'ability' => \Laravel\Sanctum\Http\Middleware\CheckForAnyAbility::class, 67 | 'hydra.log' => \App\Http\Middleware\HydraLog::class, 68 | ]; 69 | } 70 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | # For more information: https://laravel.com/docs/sail 2 | version: '3' 3 | services: 4 | laravel.test: 5 | build: 6 | context: ./vendor/laravel/sail/runtimes/8.1 7 | dockerfile: Dockerfile 8 | args: 9 | WWWGROUP: '${WWWGROUP}' 10 | image: sail-8.1/app 11 | extra_hosts: 12 | - 'host.docker.internal:host-gateway' 13 | ports: 14 | - '${APP_PORT:-80}:80' 15 | - '${HMR_PORT:-8080}:8080' 16 | environment: 17 | WWWUSER: '${WWWUSER}' 18 | LARAVEL_SAIL: 1 19 | XDEBUG_MODE: '${SAIL_XDEBUG_MODE:-off}' 20 | XDEBUG_CONFIG: '${SAIL_XDEBUG_CONFIG:-client_host=host.docker.internal}' 21 | volumes: 22 | - '.:/var/www/html' 23 | networks: 24 | - sail 25 | depends_on: 26 | - mysql 27 | - redis 28 | - minio 29 | mysql: 30 | image: 'mysql/mysql-server:8.0' 31 | ports: 32 | - '${FORWARD_DB_PORT:-3306}:3306' 33 | environment: 34 | MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}' 35 | MYSQL_ROOT_HOST: "%" 36 | MYSQL_DATABASE: '${DB_DATABASE}' 37 | MYSQL_USER: '${DB_USERNAME}' 38 | MYSQL_PASSWORD: '${DB_PASSWORD}' 39 | MYSQL_ALLOW_EMPTY_PASSWORD: 1 40 | volumes: 41 | - 'sail-mysql:/var/lib/mysql' 42 | - './vendor/laravel/sail/database/mysql/create-testing-database.sh:/docker-entrypoint-initdb.d/10-create-testing-database.sh' 43 | networks: 44 | - sail 45 | healthcheck: 46 | test: ["CMD", "mysqladmin", "ping", "-p${DB_PASSWORD}"] 47 | retries: 3 48 | timeout: 5s 49 | redis: 50 | image: 'redis:alpine' 51 | ports: 52 | - '${FORWARD_REDIS_PORT:-6379}:6379' 53 | volumes: 54 | - 'sail-redis:/data' 55 | networks: 56 | - sail 57 | healthcheck: 58 | test: ["CMD", "redis-cli", "ping"] 59 | retries: 3 60 | timeout: 5s 61 | minio: 62 | image: 'minio/minio:latest' 63 | ports: 64 | - '${FORWARD_MINIO_PORT:-9000}:9000' 65 | - '${FORWARD_MINIO_CONSOLE_PORT:-8900}:8900' 66 | environment: 67 | MINIO_ROOT_USER: 'sail' 68 | MINIO_ROOT_PASSWORD: 'password' 69 | volumes: 70 | - 'sail-minio:/data/minio' 71 | networks: 72 | - sail 73 | command: minio server /data/minio --console-address ":8900" 74 | healthcheck: 75 | test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"] 76 | retries: 3 77 | timeout: 5s 78 | mailhog: 79 | image: 'mailhog/mailhog:latest' 80 | ports: 81 | - '${FORWARD_MAILHOG_PORT:-1025}:1025' 82 | - '${FORWARD_MAILHOG_DASHBOARD_PORT:-8025}:8025' 83 | networks: 84 | - sail 85 | networks: 86 | sail: 87 | driver: bridge 88 | volumes: 89 | sail-mysql: 90 | driver: local 91 | sail-redis: 92 | driver: local 93 | sail-minio: 94 | driver: local 95 | -------------------------------------------------------------------------------- /config/queue.php: -------------------------------------------------------------------------------- 1 | env('QUEUE_CONNECTION', 'sync'), 17 | 18 | /* 19 | |-------------------------------------------------------------------------- 20 | | Queue Connections 21 | |-------------------------------------------------------------------------- 22 | | 23 | | Here you may configure the connection information for each server that 24 | | is used by your application. A default configuration has been added 25 | | for each back-end shipped with Laravel. You are free to add more. 26 | | 27 | | Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null" 28 | | 29 | */ 30 | 31 | 'connections' => [ 32 | 33 | 'sync' => [ 34 | 'driver' => 'sync', 35 | ], 36 | 37 | 'database' => [ 38 | 'driver' => 'database', 39 | 'table' => 'jobs', 40 | 'queue' => 'default', 41 | 'retry_after' => 90, 42 | 'after_commit' => false, 43 | ], 44 | 45 | 'beanstalkd' => [ 46 | 'driver' => 'beanstalkd', 47 | 'host' => 'localhost', 48 | 'queue' => 'default', 49 | 'retry_after' => 90, 50 | 'block_for' => 0, 51 | 'after_commit' => false, 52 | ], 53 | 54 | 'sqs' => [ 55 | 'driver' => 'sqs', 56 | 'key' => env('AWS_ACCESS_KEY_ID'), 57 | 'secret' => env('AWS_SECRET_ACCESS_KEY'), 58 | 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'), 59 | 'queue' => env('SQS_QUEUE', 'default'), 60 | 'suffix' => env('SQS_SUFFIX'), 61 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), 62 | 'after_commit' => false, 63 | ], 64 | 65 | 'redis' => [ 66 | 'driver' => 'redis', 67 | 'connection' => 'default', 68 | 'queue' => env('REDIS_QUEUE', 'default'), 69 | 'retry_after' => 90, 70 | 'block_for' => null, 71 | 'after_commit' => false, 72 | ], 73 | 74 | ], 75 | 76 | /* 77 | |-------------------------------------------------------------------------- 78 | | Failed Queue Jobs 79 | |-------------------------------------------------------------------------- 80 | | 81 | | These options configure the behavior of failed queue job logging so you 82 | | can control which database and table are used to store the jobs that 83 | | have failed. You may change them to any database / table you wish. 84 | | 85 | */ 86 | 87 | 'failed' => [ 88 | 'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'), 89 | 'database' => env('DB_CONNECTION', 'mysql'), 90 | 'table' => 'failed_jobs', 91 | ], 92 | 93 | ]; 94 | -------------------------------------------------------------------------------- /config/cache.php: -------------------------------------------------------------------------------- 1 | env('CACHE_DRIVER', 'file'), 19 | 20 | /* 21 | |-------------------------------------------------------------------------- 22 | | Cache Stores 23 | |-------------------------------------------------------------------------- 24 | | 25 | | Here you may define all of the cache "stores" for your application as 26 | | well as their drivers. You may even define multiple stores for the 27 | | same cache driver to group types of items stored in your caches. 28 | | 29 | | Supported drivers: "apc", "array", "database", "file", 30 | | "memcached", "redis", "dynamodb", "octane", "null" 31 | | 32 | */ 33 | 34 | 'stores' => [ 35 | 36 | 'apc' => [ 37 | 'driver' => 'apc', 38 | ], 39 | 40 | 'array' => [ 41 | 'driver' => 'array', 42 | 'serialize' => false, 43 | ], 44 | 45 | 'database' => [ 46 | 'driver' => 'database', 47 | 'table' => 'cache', 48 | 'connection' => null, 49 | 'lock_connection' => null, 50 | ], 51 | 52 | 'file' => [ 53 | 'driver' => 'file', 54 | 'path' => storage_path('framework/cache/data'), 55 | ], 56 | 57 | 'memcached' => [ 58 | 'driver' => 'memcached', 59 | 'persistent_id' => env('MEMCACHED_PERSISTENT_ID'), 60 | 'sasl' => [ 61 | env('MEMCACHED_USERNAME'), 62 | env('MEMCACHED_PASSWORD'), 63 | ], 64 | 'options' => [ 65 | // Memcached::OPT_CONNECT_TIMEOUT => 2000, 66 | ], 67 | 'servers' => [ 68 | [ 69 | 'host' => env('MEMCACHED_HOST', '127.0.0.1'), 70 | 'port' => env('MEMCACHED_PORT', 11211), 71 | 'weight' => 100, 72 | ], 73 | ], 74 | ], 75 | 76 | 'redis' => [ 77 | 'driver' => 'redis', 78 | 'connection' => 'cache', 79 | 'lock_connection' => 'default', 80 | ], 81 | 82 | 'dynamodb' => [ 83 | 'driver' => 'dynamodb', 84 | 'key' => env('AWS_ACCESS_KEY_ID'), 85 | 'secret' => env('AWS_SECRET_ACCESS_KEY'), 86 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), 87 | 'table' => env('DYNAMODB_CACHE_TABLE', 'cache'), 88 | 'endpoint' => env('DYNAMODB_ENDPOINT'), 89 | ], 90 | 91 | 'octane' => [ 92 | 'driver' => 'octane', 93 | ], 94 | 95 | ], 96 | 97 | /* 98 | |-------------------------------------------------------------------------- 99 | | Cache Key Prefix 100 | |-------------------------------------------------------------------------- 101 | | 102 | | When utilizing the APC, database, memcached, Redis, or DynamoDB cache 103 | | stores there might be other applications using the same cache. For 104 | | that reason, you may prefix every cache key to avoid collisions. 105 | | 106 | */ 107 | 108 | 'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache_'), 109 | 110 | ]; 111 | -------------------------------------------------------------------------------- /config/mail.php: -------------------------------------------------------------------------------- 1 | env('MAIL_MAILER', 'smtp'), 17 | 18 | /* 19 | |-------------------------------------------------------------------------- 20 | | Mailer Configurations 21 | |-------------------------------------------------------------------------- 22 | | 23 | | Here you may configure all of the mailers used by your application plus 24 | | their respective settings. Several examples have been configured for 25 | | you and you are free to add your own as your application requires. 26 | | 27 | | Laravel supports a variety of mail "transport" drivers to be used while 28 | | sending an e-mail. You will specify which one you are using for your 29 | | mailers below. You are free to add additional mailers as required. 30 | | 31 | | Supported: "smtp", "sendmail", "mailgun", "ses", 32 | | "postmark", "log", "array", "failover" 33 | | 34 | */ 35 | 36 | 'mailers' => [ 37 | 'smtp' => [ 38 | 'transport' => 'smtp', 39 | 'host' => env('MAIL_HOST', 'smtp.mailgun.org'), 40 | 'port' => env('MAIL_PORT', 587), 41 | 'encryption' => env('MAIL_ENCRYPTION', 'tls'), 42 | 'username' => env('MAIL_USERNAME'), 43 | 'password' => env('MAIL_PASSWORD'), 44 | 'timeout' => null, 45 | 'local_domain' => env('MAIL_EHLO_DOMAIN'), 46 | ], 47 | 48 | 'ses' => [ 49 | 'transport' => 'ses', 50 | ], 51 | 52 | 'mailgun' => [ 53 | 'transport' => 'mailgun', 54 | ], 55 | 56 | 'postmark' => [ 57 | 'transport' => 'postmark', 58 | ], 59 | 60 | 'sendmail' => [ 61 | 'transport' => 'sendmail', 62 | 'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'), 63 | ], 64 | 65 | 'log' => [ 66 | 'transport' => 'log', 67 | 'channel' => env('MAIL_LOG_CHANNEL'), 68 | ], 69 | 70 | 'array' => [ 71 | 'transport' => 'array', 72 | ], 73 | 74 | 'failover' => [ 75 | 'transport' => 'failover', 76 | 'mailers' => [ 77 | 'smtp', 78 | 'log', 79 | ], 80 | ], 81 | ], 82 | 83 | /* 84 | |-------------------------------------------------------------------------- 85 | | Global "From" Address 86 | |-------------------------------------------------------------------------- 87 | | 88 | | You may wish for all e-mails sent by your application to be sent from 89 | | the same address. Here, you may specify a name and address that is 90 | | used globally for all e-mails that are sent by your application. 91 | | 92 | */ 93 | 94 | 'from' => [ 95 | 'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'), 96 | 'name' => env('MAIL_FROM_NAME', 'Example'), 97 | ], 98 | 99 | /* 100 | |-------------------------------------------------------------------------- 101 | | Markdown Mail Settings 102 | |-------------------------------------------------------------------------- 103 | | 104 | | If you are using Markdown based email rendering, you may configure your 105 | | theme and component paths here, allowing you to customize the design 106 | | of the emails. Or, you may simply stick with the Laravel defaults! 107 | | 108 | */ 109 | 110 | 'markdown' => [ 111 | 'theme' => 'default', 112 | 113 | 'paths' => [ 114 | resource_path('views/vendor/mail'), 115 | ], 116 | ], 117 | 118 | ]; 119 | -------------------------------------------------------------------------------- /config/auth.php: -------------------------------------------------------------------------------- 1 | [ 17 | 'guard' => 'web', 18 | 'passwords' => 'users', 19 | ], 20 | 21 | /* 22 | |-------------------------------------------------------------------------- 23 | | Authentication Guards 24 | |-------------------------------------------------------------------------- 25 | | 26 | | Next, you may define every authentication guard for your application. 27 | | Of course, a great default configuration has been defined for you 28 | | here which uses session storage and the Eloquent user provider. 29 | | 30 | | All authentication drivers have a user provider. This defines how the 31 | | users are actually retrieved out of your database or other storage 32 | | mechanisms used by this application to persist your user's data. 33 | | 34 | | Supported: "session" 35 | | 36 | */ 37 | 38 | 'guards' => [ 39 | 'web' => [ 40 | 'driver' => 'session', 41 | 'provider' => 'users', 42 | ], 43 | ], 44 | 45 | /* 46 | |-------------------------------------------------------------------------- 47 | | User Providers 48 | |-------------------------------------------------------------------------- 49 | | 50 | | All authentication drivers have a user provider. This defines how the 51 | | users are actually retrieved out of your database or other storage 52 | | mechanisms used by this application to persist your user's data. 53 | | 54 | | If you have multiple user tables or models you may configure multiple 55 | | sources which represent each model / table. These sources may then 56 | | be assigned to any extra authentication guards you have defined. 57 | | 58 | | Supported: "database", "eloquent" 59 | | 60 | */ 61 | 62 | 'providers' => [ 63 | 'users' => [ 64 | 'driver' => 'eloquent', 65 | 'model' => App\Models\User::class, 66 | ], 67 | 68 | // 'users' => [ 69 | // 'driver' => 'database', 70 | // 'table' => 'users', 71 | // ], 72 | ], 73 | 74 | /* 75 | |-------------------------------------------------------------------------- 76 | | Resetting Passwords 77 | |-------------------------------------------------------------------------- 78 | | 79 | | You may specify multiple password reset configurations if you have more 80 | | than one user table or model in the application and you want to have 81 | | separate password reset settings based on the specific user types. 82 | | 83 | | The expire time is the number of minutes that each reset token will be 84 | | considered valid. This security feature keeps tokens short-lived so 85 | | they have less time to be guessed. You may change this as needed. 86 | | 87 | */ 88 | 89 | 'passwords' => [ 90 | 'users' => [ 91 | 'provider' => 'users', 92 | 'table' => 'password_resets', 93 | 'expire' => 60, 94 | 'throttle' => 60, 95 | ], 96 | ], 97 | 98 | /* 99 | |-------------------------------------------------------------------------- 100 | | Password Confirmation Timeout 101 | |-------------------------------------------------------------------------- 102 | | 103 | | Here you may define the amount of seconds before a password confirmation 104 | | times out and the user is prompted to re-enter their password via the 105 | | confirmation screen. By default, the timeout lasts for three hours. 106 | | 107 | */ 108 | 109 | 'password_timeout' => 10800, 110 | 111 | ]; 112 | -------------------------------------------------------------------------------- /config/logging.php: -------------------------------------------------------------------------------- 1 | env('LOG_CHANNEL', 'stack'), 21 | 22 | /* 23 | |-------------------------------------------------------------------------- 24 | | Deprecations Log Channel 25 | |-------------------------------------------------------------------------- 26 | | 27 | | This option controls the log channel that should be used to log warnings 28 | | regarding deprecated PHP and library features. This allows you to get 29 | | your application ready for upcoming major versions of dependencies. 30 | | 31 | */ 32 | 33 | 'deprecations' => [ 34 | 'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'), 35 | 'trace' => false, 36 | ], 37 | 38 | /* 39 | |-------------------------------------------------------------------------- 40 | | Log Channels 41 | |-------------------------------------------------------------------------- 42 | | 43 | | Here you may configure the log channels for your application. Out of 44 | | the box, Laravel uses the Monolog PHP logging library. This gives 45 | | you a variety of powerful log handlers / formatters to utilize. 46 | | 47 | | Available Drivers: "single", "daily", "slack", "syslog", 48 | | "errorlog", "monolog", 49 | | "custom", "stack" 50 | | 51 | */ 52 | 53 | 'channels' => [ 54 | 'stack' => [ 55 | 'driver' => 'stack', 56 | 'channels' => ['single'], 57 | 'ignore_exceptions' => false, 58 | ], 59 | 60 | 'single' => [ 61 | 'driver' => 'single', 62 | 'path' => storage_path('logs/laravel.log'), 63 | 'level' => env('LOG_LEVEL', 'debug'), 64 | ], 65 | 66 | 'daily' => [ 67 | 'driver' => 'daily', 68 | 'path' => storage_path('logs/laravel.log'), 69 | 'level' => env('LOG_LEVEL', 'debug'), 70 | 'days' => 14, 71 | ], 72 | 73 | 'slack' => [ 74 | 'driver' => 'slack', 75 | 'url' => env('LOG_SLACK_WEBHOOK_URL'), 76 | 'username' => 'Laravel Log', 77 | 'emoji' => ':boom:', 78 | 'level' => env('LOG_LEVEL', 'critical'), 79 | ], 80 | 81 | 'papertrail' => [ 82 | 'driver' => 'monolog', 83 | 'level' => env('LOG_LEVEL', 'debug'), 84 | 'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class), 85 | 'handler_with' => [ 86 | 'host' => env('PAPERTRAIL_URL'), 87 | 'port' => env('PAPERTRAIL_PORT'), 88 | 'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'), 89 | ], 90 | ], 91 | 92 | 'stderr' => [ 93 | 'driver' => 'monolog', 94 | 'level' => env('LOG_LEVEL', 'debug'), 95 | 'handler' => StreamHandler::class, 96 | 'formatter' => env('LOG_STDERR_FORMATTER'), 97 | 'with' => [ 98 | 'stream' => 'php://stderr', 99 | ], 100 | ], 101 | 102 | 'syslog' => [ 103 | 'driver' => 'syslog', 104 | 'level' => env('LOG_LEVEL', 'debug'), 105 | ], 106 | 107 | 'errorlog' => [ 108 | 'driver' => 'errorlog', 109 | 'level' => env('LOG_LEVEL', 'debug'), 110 | ], 111 | 112 | 'null' => [ 113 | 'driver' => 'monolog', 114 | 'handler' => NullHandler::class, 115 | ], 116 | 117 | 'emergency' => [ 118 | 'path' => storage_path('logs/laravel.log'), 119 | ], 120 | ], 121 | 122 | ]; 123 | -------------------------------------------------------------------------------- /app/Http/Controllers/UserController.php: -------------------------------------------------------------------------------- 1 | validate([ 28 | 'email' => 'required|email', 29 | 'password' => 'required', 30 | 'name' => 'nullable|string', 31 | ]); 32 | 33 | $user = User::where('email', $creds['email'])->first(); 34 | if ($user) { 35 | return response(['error' => 1, 'message' => 'user already exists'], 409); 36 | } 37 | 38 | $user = User::create([ 39 | 'email' => $creds['email'], 40 | 'password' => Hash::make($creds['password']), 41 | 'name' => $creds['name'], 42 | ]); 43 | 44 | $defaultRoleSlug = config('hydra.default_user_role_slug', 'user'); 45 | $user->roles()->attach(Role::where('slug', $defaultRoleSlug)->first()); 46 | 47 | return $user; 48 | } 49 | 50 | /** 51 | * Authenticate an user and dispatch token. 52 | * 53 | * @return \Illuminate\Http\Response 54 | */ 55 | public function login(Request $request) { 56 | $creds = $request->validate([ 57 | 'email' => 'required|email', 58 | 'password' => 'required', 59 | ]); 60 | 61 | $user = User::where('email', $creds['email'])->first(); 62 | if (! $user || ! Hash::check($request->password, $user->password)) { 63 | return response(['error' => 1, 'message' => 'invalid credentials'], 401); 64 | } 65 | 66 | if (config('hydra.delete_previous_access_tokens_on_login', false)) { 67 | $user->tokens()->delete(); 68 | } 69 | 70 | $roles = $user->roles->pluck('slug')->all(); 71 | 72 | $plainTextToken = $user->createToken('hydra-api-token', $roles)->plainTextToken; 73 | 74 | return response(['error' => 0, 'id' => $user->id, 'name' => $user->name, 'token' => $plainTextToken], 200); 75 | } 76 | 77 | /** 78 | * Display the specified resource. 79 | * 80 | * @return \App\Models\User $user 81 | */ 82 | public function show(User $user) { 83 | return $user; 84 | } 85 | 86 | /** 87 | * Update the specified resource in storage. 88 | * 89 | * @return User 90 | * 91 | * @throws MissingAbilityException 92 | */ 93 | public function update(Request $request, User $user) { 94 | $user->name = $request->name ?? $user->name; 95 | $user->email = $request->email ?? $user->email; 96 | $user->password = $request->password ? Hash::make($request->password) : $user->password; 97 | $user->email_verified_at = $request->email_verified_at ?? $user->email_verified_at; 98 | 99 | //check if the logged in user is updating it's own record 100 | 101 | $loggedInUser = $request->user(); 102 | if ($loggedInUser->id == $user->id) { 103 | $user->update(); 104 | } elseif ($loggedInUser->tokenCan('admin') || $loggedInUser->tokenCan('super-admin')) { 105 | $user->update(); 106 | } else { 107 | throw new MissingAbilityException('Not Authorized'); 108 | } 109 | 110 | return $user; 111 | } 112 | 113 | /** 114 | * Remove the specified resource from storage. 115 | * 116 | * @return \Illuminate\Http\Response 117 | */ 118 | public function destroy(User $user) { 119 | $adminRole = Role::where('slug', 'admin')->first(); 120 | $userRoles = $user->roles; 121 | 122 | if ($userRoles->contains($adminRole)) { 123 | //the current user is admin, then if there is only one admin - don't delete 124 | $numberOfAdmins = Role::where('slug', 'admin')->first()->users()->count(); 125 | if ($numberOfAdmins == 1) { 126 | return response(['error' => 1, 'message' => 'Create another admin before deleting this only admin user'], 409); 127 | } 128 | } 129 | 130 | $user->delete(); 131 | 132 | return response(['error' => 0, 'message' => 'user deleted']); 133 | } 134 | 135 | /** 136 | * Return Auth user 137 | * 138 | * @return mixed 139 | */ 140 | public function me(Request $request) { 141 | return $request->user(); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /config/database.php: -------------------------------------------------------------------------------- 1 | env('DB_CONNECTION', 'mysql'), 19 | 20 | /* 21 | |-------------------------------------------------------------------------- 22 | | Database Connections 23 | |-------------------------------------------------------------------------- 24 | | 25 | | Here are each of the database connections setup for your application. 26 | | Of course, examples of configuring each database platform that is 27 | | supported by Laravel is shown below to make development simple. 28 | | 29 | | 30 | | All database work in Laravel is done through the PHP PDO facilities 31 | | so make sure you have the driver for your particular database of 32 | | choice installed on your machine before you begin development. 33 | | 34 | */ 35 | 36 | 'connections' => [ 37 | 38 | 'sqlite' => [ 39 | 'driver' => 'sqlite', 40 | 'url' => env('DATABASE_URL'), 41 | 'database' => database_path(env('DB_DATABASE', 'database.sqlite')), 42 | 'prefix' => '', 43 | 'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true), 44 | ], 45 | 46 | 'mysql' => [ 47 | 'driver' => 'mysql', 48 | 'url' => env('DATABASE_URL'), 49 | 'host' => env('DB_HOST', '127.0.0.1'), 50 | 'port' => env('DB_PORT', '3306'), 51 | 'database' => env('DB_DATABASE', 'forge'), 52 | 'username' => env('DB_USERNAME', 'forge'), 53 | 'password' => env('DB_PASSWORD', ''), 54 | 'unix_socket' => env('DB_SOCKET', ''), 55 | 'charset' => 'utf8mb4', 56 | 'collation' => 'utf8mb4_unicode_ci', 57 | 'prefix' => '', 58 | 'prefix_indexes' => true, 59 | 'strict' => true, 60 | 'engine' => null, 61 | 'options' => extension_loaded('pdo_mysql') ? array_filter([ 62 | PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), 63 | ]) : [], 64 | ], 65 | 66 | 'pgsql' => [ 67 | 'driver' => 'pgsql', 68 | 'url' => env('DATABASE_URL'), 69 | 'host' => env('DB_HOST', '127.0.0.1'), 70 | 'port' => env('DB_PORT', '5432'), 71 | 'database' => env('DB_DATABASE', 'forge'), 72 | 'username' => env('DB_USERNAME', 'forge'), 73 | 'password' => env('DB_PASSWORD', ''), 74 | 'charset' => 'utf8', 75 | 'prefix' => '', 76 | 'prefix_indexes' => true, 77 | 'search_path' => 'public', 78 | 'sslmode' => 'prefer', 79 | ], 80 | 81 | 'sqlsrv' => [ 82 | 'driver' => 'sqlsrv', 83 | 'url' => env('DATABASE_URL'), 84 | 'host' => env('DB_HOST', 'localhost'), 85 | 'port' => env('DB_PORT', '1433'), 86 | 'database' => env('DB_DATABASE', 'forge'), 87 | 'username' => env('DB_USERNAME', 'forge'), 88 | 'password' => env('DB_PASSWORD', ''), 89 | 'charset' => 'utf8', 90 | 'prefix' => '', 91 | 'prefix_indexes' => true, 92 | // 'encrypt' => env('DB_ENCRYPT', 'yes'), 93 | // 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'), 94 | ], 95 | 96 | ], 97 | 98 | /* 99 | |-------------------------------------------------------------------------- 100 | | Migration Repository Table 101 | |-------------------------------------------------------------------------- 102 | | 103 | | This table keeps track of all the migrations that have already run for 104 | | your application. Using this information, we can determine which of 105 | | the migrations on disk haven't actually been run in the database. 106 | | 107 | */ 108 | 109 | 'migrations' => 'migrations', 110 | 111 | /* 112 | |-------------------------------------------------------------------------- 113 | | Redis Databases 114 | |-------------------------------------------------------------------------- 115 | | 116 | | Redis is an open source, fast, and advanced key-value store that also 117 | | provides a richer body of commands than a typical key-value system 118 | | such as APC or Memcached. Laravel makes it easy to dig right in. 119 | | 120 | */ 121 | 122 | 'redis' => [ 123 | 124 | 'client' => env('REDIS_CLIENT', 'phpredis'), 125 | 126 | 'options' => [ 127 | 'cluster' => env('REDIS_CLUSTER', 'redis'), 128 | 'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'), 129 | ], 130 | 131 | 'default' => [ 132 | 'url' => env('REDIS_URL'), 133 | 'host' => env('REDIS_HOST', '127.0.0.1'), 134 | 'username' => env('REDIS_USERNAME'), 135 | 'password' => env('REDIS_PASSWORD'), 136 | 'port' => env('REDIS_PORT', '6379'), 137 | 'database' => env('REDIS_DB', '0'), 138 | ], 139 | 140 | 'cache' => [ 141 | 'url' => env('REDIS_URL'), 142 | 'host' => env('REDIS_HOST', '127.0.0.1'), 143 | 'username' => env('REDIS_USERNAME'), 144 | 'password' => env('REDIS_PASSWORD'), 145 | 'port' => env('REDIS_PORT', '6379'), 146 | 'database' => env('REDIS_CACHE_DB', '1'), 147 | ], 148 | 149 | ], 150 | 151 | ]; 152 | -------------------------------------------------------------------------------- /tests/Feature/UserTest.php: -------------------------------------------------------------------------------- 1 | postJson('/api/users', [ 23 | 'name' => 'Test User', 24 | 'email' => 'test@test.com', 25 | 'password' => 'test', 26 | ]); 27 | 28 | $response 29 | ->assertJson( 30 | fn (AssertableJson $json) => $json->where('email', 'test@test.com') 31 | ->where('name', 'Test User') 32 | ->etc() 33 | ); 34 | } 35 | 36 | public function test_existing_email_registration_fail() { 37 | $response = $this->postJson('/api/users', [ 38 | 'name' => 'Test User', 39 | 'email' => 'test@test.com', 40 | 'password' => 'test', 41 | ]); 42 | 43 | $response 44 | ->assertJson( 45 | fn (AssertableJson $json) => $json->where('error', 1) 46 | ->where('message', 'user already exists') 47 | ); 48 | } 49 | 50 | public function test_new_user_login() { 51 | $response = $this->postJson('/api/login', [ 52 | 'email' => 'test@test.com', 53 | 'password' => 'test', 54 | ]); 55 | 56 | $data = json_decode($response->getContent()); 57 | $this->token = $data->token; 58 | $this->user_id = $data->id; 59 | 60 | $response 61 | ->assertJson( 62 | fn (AssertableJson $json) => $json->where('error', 0) 63 | ->has('name') 64 | ->has('token') 65 | ->has('id') 66 | ); 67 | } 68 | 69 | public function test_new_user_failed_login() { 70 | $response = $this->postJson('/api/login', [ 71 | 'email' => 'test@test.com', 72 | 'password' => 'testX', 73 | ]); 74 | 75 | $response 76 | ->assertJson( 77 | fn (AssertableJson $json) => $json->where('error', 1) 78 | ->has('message') 79 | ); 80 | } 81 | 82 | public function test_new_user_name_update_with_user_token() { 83 | $response = $this->postJson('/api/login', [ 84 | 'email' => 'test@test.com', 85 | 'password' => 'test', 86 | ]); 87 | 88 | $data = json_decode($response->getContent()); 89 | $this->token = $data->token; 90 | $this->user_id = $data->id; 91 | 92 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 93 | ->put("/api/users/{$this->user_id}", [ 94 | 'name' => 'Mini Me', 95 | ]); 96 | 97 | $response 98 | ->assertJson( 99 | fn (AssertableJson $json) => $json->where('name', 'Mini Me') 100 | ->etc() 101 | ); 102 | } 103 | 104 | public function test_new_user_name_update_with_admin_token() { 105 | $response = $this->postJson('/api/login', [ 106 | 'email' => 'admin@hydra.project', 107 | 'password' => 'hydra', 108 | ]); 109 | 110 | $data = json_decode($response->getContent()); 111 | $this->token = $data->token; 112 | $this->user_id = $data->id; 113 | 114 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 115 | ->put("/api/users/{$this->user_id}", [ 116 | 'name' => 'Mini Me', 117 | ]); 118 | 119 | $response 120 | ->assertJson( 121 | fn (AssertableJson $json) => $json->where('name', 'Mini Me') 122 | ->etc() 123 | ); 124 | } 125 | 126 | public function test_new_user_destroy_as_user_should_fail() { 127 | $response = $this->postJson('/api/login', [ 128 | 'email' => 'test@test.com', 129 | 'password' => 'test', 130 | ]); 131 | 132 | $data = json_decode($response->getContent()); 133 | $this->token = $data->token; 134 | $this->user_id = $data->id; 135 | 136 | $target = User::where('email', 'test@test.com')->first(); 137 | 138 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 139 | ->delete("/api/users/{$target->id}"); 140 | 141 | $response 142 | ->assertJson( 143 | fn (AssertableJson $json) => $json->where('error', 1) 144 | ->has('message') 145 | ); 146 | } 147 | 148 | public function test_new_user_destroy_as_admin() { 149 | $response = $this->postJson('/api/login', [ 150 | 'email' => 'admin@hydra.project', 151 | 'password' => 'hydra', 152 | ]); 153 | 154 | $data = json_decode($response->getContent()); 155 | $this->token = $data->token; 156 | $this->user_id = $data->id; 157 | 158 | $target = User::where('email', 'test@test.com')->first(); 159 | 160 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 161 | ->delete("/api/users/{$target->id}"); 162 | 163 | $response 164 | ->assertJson( 165 | fn (AssertableJson $json) => $json->where('error', 0) 166 | ->where('message', 'user deleted') 167 | ); 168 | } 169 | 170 | public function test_delete_admin_user_if_multiple_admins_are_present() { 171 | $newAdminUser = User::create([ 172 | 'name' => 'Test Admin', 173 | 'password' => Hash::make('abcd'), 174 | 'email' => 'testadmin@test.com', 175 | ]); 176 | 177 | $adminRole = Role::find(1); 178 | 179 | $newAdminUser->roles()->attach($adminRole); 180 | 181 | $response = $this->postJson('/api/login', [ 182 | 'email' => 'admin@hydra.project', 183 | 'password' => 'hydra', 184 | ]); 185 | 186 | $data = json_decode($response->getContent()); 187 | $this->token = $data->token; 188 | $this->user_id = $data->id; 189 | 190 | $target = User::where('email', 'testadmin@test.com')->first(); 191 | 192 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 193 | ->delete("/api/users/{$target->id}"); 194 | 195 | $response 196 | ->assertJson( 197 | fn (AssertableJson $json) => $json->where('error', 0) 198 | ->where('message', 'user deleted') 199 | ); 200 | } 201 | } 202 | -------------------------------------------------------------------------------- /config/session.php: -------------------------------------------------------------------------------- 1 | env('SESSION_DRIVER', 'file'), 22 | 23 | /* 24 | |-------------------------------------------------------------------------- 25 | | Session Lifetime 26 | |-------------------------------------------------------------------------- 27 | | 28 | | Here you may specify the number of minutes that you wish the session 29 | | to be allowed to remain idle before it expires. If you want them 30 | | to immediately expire on the browser closing, set that option. 31 | | 32 | */ 33 | 34 | 'lifetime' => env('SESSION_LIFETIME', 120), 35 | 36 | 'expire_on_close' => false, 37 | 38 | /* 39 | |-------------------------------------------------------------------------- 40 | | Session Encryption 41 | |-------------------------------------------------------------------------- 42 | | 43 | | This option allows you to easily specify that all of your session data 44 | | should be encrypted before it is stored. All encryption will be run 45 | | automatically by Laravel and you can use the Session like normal. 46 | | 47 | */ 48 | 49 | 'encrypt' => false, 50 | 51 | /* 52 | |-------------------------------------------------------------------------- 53 | | Session File Location 54 | |-------------------------------------------------------------------------- 55 | | 56 | | When using the native session driver, we need a location where session 57 | | files may be stored. A default has been set for you but a different 58 | | location may be specified. This is only needed for file sessions. 59 | | 60 | */ 61 | 62 | 'files' => storage_path('framework/sessions'), 63 | 64 | /* 65 | |-------------------------------------------------------------------------- 66 | | Session Database Connection 67 | |-------------------------------------------------------------------------- 68 | | 69 | | When using the "database" or "redis" session drivers, you may specify a 70 | | connection that should be used to manage these sessions. This should 71 | | correspond to a connection in your database configuration options. 72 | | 73 | */ 74 | 75 | 'connection' => env('SESSION_CONNECTION'), 76 | 77 | /* 78 | |-------------------------------------------------------------------------- 79 | | Session Database Table 80 | |-------------------------------------------------------------------------- 81 | | 82 | | When using the "database" session driver, you may specify the table we 83 | | should use to manage the sessions. Of course, a sensible default is 84 | | provided for you; however, you are free to change this as needed. 85 | | 86 | */ 87 | 88 | 'table' => 'sessions', 89 | 90 | /* 91 | |-------------------------------------------------------------------------- 92 | | Session Cache Store 93 | |-------------------------------------------------------------------------- 94 | | 95 | | While using one of the framework's cache driven session backends you may 96 | | list a cache store that should be used for these sessions. This value 97 | | must match with one of the application's configured cache "stores". 98 | | 99 | | Affects: "apc", "dynamodb", "memcached", "redis" 100 | | 101 | */ 102 | 103 | 'store' => env('SESSION_STORE'), 104 | 105 | /* 106 | |-------------------------------------------------------------------------- 107 | | Session Sweeping Lottery 108 | |-------------------------------------------------------------------------- 109 | | 110 | | Some session drivers must manually sweep their storage location to get 111 | | rid of old sessions from storage. Here are the chances that it will 112 | | happen on a given request. By default, the odds are 2 out of 100. 113 | | 114 | */ 115 | 116 | 'lottery' => [2, 100], 117 | 118 | /* 119 | |-------------------------------------------------------------------------- 120 | | Session Cookie Name 121 | |-------------------------------------------------------------------------- 122 | | 123 | | Here you may change the name of the cookie used to identify a session 124 | | instance by ID. The name specified here will get used every time a 125 | | new session cookie is created by the framework for every driver. 126 | | 127 | */ 128 | 129 | 'cookie' => env( 130 | 'SESSION_COOKIE', 131 | Str::slug(env('APP_NAME', 'laravel'), '_').'_session' 132 | ), 133 | 134 | /* 135 | |-------------------------------------------------------------------------- 136 | | Session Cookie Path 137 | |-------------------------------------------------------------------------- 138 | | 139 | | The session cookie path determines the path for which the cookie will 140 | | be regarded as available. Typically, this will be the root path of 141 | | your application but you are free to change this when necessary. 142 | | 143 | */ 144 | 145 | 'path' => '/', 146 | 147 | /* 148 | |-------------------------------------------------------------------------- 149 | | Session Cookie Domain 150 | |-------------------------------------------------------------------------- 151 | | 152 | | Here you may change the domain of the cookie used to identify a session 153 | | in your application. This will determine which domains the cookie is 154 | | available to in your application. A sensible default has been set. 155 | | 156 | */ 157 | 158 | 'domain' => env('SESSION_DOMAIN'), 159 | 160 | /* 161 | |-------------------------------------------------------------------------- 162 | | HTTPS Only Cookies 163 | |-------------------------------------------------------------------------- 164 | | 165 | | By setting this option to true, session cookies will only be sent back 166 | | to the server if the browser has a HTTPS connection. This will keep 167 | | the cookie from being sent to you when it can't be done securely. 168 | | 169 | */ 170 | 171 | 'secure' => env('SESSION_SECURE_COOKIE'), 172 | 173 | /* 174 | |-------------------------------------------------------------------------- 175 | | HTTP Access Only 176 | |-------------------------------------------------------------------------- 177 | | 178 | | Setting this value to true will prevent JavaScript from accessing the 179 | | value of the cookie and the cookie will only be accessible through 180 | | the HTTP protocol. You are free to modify this option if needed. 181 | | 182 | */ 183 | 184 | 'http_only' => true, 185 | 186 | /* 187 | |-------------------------------------------------------------------------- 188 | | Same-Site Cookies 189 | |-------------------------------------------------------------------------- 190 | | 191 | | This option determines how your cookies behave when cross-site requests 192 | | take place, and can be used to mitigate CSRF attacks. By default, we 193 | | will set this value to "lax" since this is a secure default value. 194 | | 195 | | Supported: "lax", "strict", "none", null 196 | | 197 | */ 198 | 199 | 'same_site' => 'lax', 200 | 201 | ]; 202 | -------------------------------------------------------------------------------- /tests/Feature/RoleTest.php: -------------------------------------------------------------------------------- 1 | postJson('/api/login', [ 17 | 'email' => 'admin@hydra.project', 18 | 'password' => 'hydra', 19 | ]); 20 | 21 | $data = json_decode($response->getContent()); 22 | $this->token = $data->token; 23 | $this->user_id = $data->id; 24 | 25 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 26 | ->get('/api/roles'); 27 | 28 | $response 29 | ->assertJson( 30 | fn (AssertableJson $json) => $json->has(6) 31 | ->first( 32 | fn ($json) => $json->where('id', 1) 33 | ->where('name', 'Administrator') 34 | ->where('slug', 'admin') 35 | ->etc() 36 | ) 37 | ); 38 | } 39 | 40 | public function test_update_role_name_as_admin() { 41 | $response = $this->postJson('/api/login', [ 42 | 'email' => 'admin@hydra.project', 43 | 'password' => 'hydra', 44 | ]); 45 | 46 | $data = json_decode($response->getContent()); 47 | $this->token = $data->token; 48 | $this->user_id = $data->id; 49 | 50 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 51 | ->put('/api/roles/4', [ 52 | 'name' => 'Chief Editor', 53 | ]); 54 | 55 | $response 56 | ->assertJson( 57 | fn (AssertableJson $json) => $json->where('name', 'Chief Editor') 58 | ->missing('error') 59 | ->etc() 60 | ); 61 | } 62 | 63 | public function test_update_role_slug_as_admin() { 64 | $response = $this->postJson('/api/login', [ 65 | 'email' => 'admin@hydra.project', 66 | 'password' => 'hydra', 67 | ]); 68 | 69 | $data = json_decode($response->getContent()); 70 | $this->token = $data->token; 71 | $this->user_id = $data->id; 72 | 73 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 74 | ->put('/api/roles/4', [ 75 | 'slug' => 'chief-editor', 76 | ]); 77 | 78 | $response 79 | ->assertJson( 80 | fn (AssertableJson $json) => $json->where('slug', 'chief-editor') 81 | ->missing('error') 82 | ->etc() 83 | ); 84 | } 85 | 86 | public function test_update_role_namd_and_slug_as_admin() { 87 | $response = $this->postJson('/api/login', [ 88 | 'email' => 'admin@hydra.project', 89 | 'password' => 'hydra', 90 | ]); 91 | 92 | $data = json_decode($response->getContent()); 93 | $this->token = $data->token; 94 | $this->user_id = $data->id; 95 | 96 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 97 | ->put('/api/roles/4', [ 98 | 'name' => 'Editor X', 99 | 'slug' => 'editor-x', 100 | ]); 101 | 102 | $response 103 | ->assertJson( 104 | fn (AssertableJson $json) => $json->where('name', 'Editor X') 105 | ->where('slug', 'editor-x') 106 | ->missing('error') 107 | ->etc() 108 | ); 109 | } 110 | 111 | public function test_update_admin_slug_as_admin_should_fail() { 112 | $response = $this->postJson('/api/login', [ 113 | 'email' => 'admin@hydra.project', 114 | 'password' => 'hydra', 115 | ]); 116 | 117 | $data = json_decode($response->getContent()); 118 | $this->token = $data->token; 119 | $this->user_id = $data->id; 120 | 121 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 122 | ->put('/api/roles/1', [ 123 | 'slug' => 'admin-x', 124 | ]); 125 | 126 | $response 127 | ->assertJson( 128 | fn (AssertableJson $json) => $json 129 | ->where('slug', 'admin') 130 | ->etc() 131 | ); 132 | } 133 | 134 | public function test_create_new_role_as_admin() { 135 | $response = $this->postJson('/api/login', [ 136 | 'email' => 'admin@hydra.project', 137 | 'password' => 'hydra', 138 | ]); 139 | 140 | $data = json_decode($response->getContent()); 141 | $this->token = $data->token; 142 | $this->user_id = $data->id; 143 | 144 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 145 | ->post('/api/roles', [ 146 | 'name' => 'New Role', 147 | 'slug' => 'new-role', 148 | ]); 149 | 150 | $response 151 | ->assertJson( 152 | fn (AssertableJson $json) => $json->where('name', 'New Role') 153 | ->where('slug', 'new-role') 154 | ->missing('error') 155 | ->etc() 156 | ); 157 | } 158 | 159 | public function test_duplicate_role_will_not_be_created() { 160 | $response = $this->postJson('/api/login', [ 161 | 'email' => 'admin@hydra.project', 162 | 'password' => 'hydra', 163 | ]); 164 | 165 | $data = json_decode($response->getContent()); 166 | $this->token = $data->token; 167 | $this->user_id = $data->id; 168 | 169 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 170 | ->post('/api/roles', [ 171 | 'name' => 'New Role', 172 | 'slug' => 'new-role', 173 | ]); 174 | 175 | $response 176 | ->assertJson( 177 | fn (AssertableJson $json) => $json->where('error', 1) 178 | ->etc() 179 | ); 180 | } 181 | 182 | public function test_delete_role_as_admin() { 183 | $response = $this->postJson('/api/login', [ 184 | 'email' => 'admin@hydra.project', 185 | 'password' => 'hydra', 186 | ]); 187 | 188 | $data = json_decode($response->getContent()); 189 | $this->token = $data->token; 190 | $this->user_id = $data->id; 191 | 192 | $newRole = Role::where('slug', 'new-role')->first(); 193 | 194 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 195 | ->delete("/api/roles/{$newRole->id}"); 196 | 197 | $response 198 | ->assertJson( 199 | fn (AssertableJson $json) => $json->where('error', 0) 200 | ->has('message') 201 | ); 202 | } 203 | 204 | public function test_delete_admin_role_should_fail() { 205 | $response = $this->postJson('/api/login', [ 206 | 'email' => 'admin@hydra.project', 207 | 'password' => 'hydra', 208 | ]); 209 | 210 | $data = json_decode($response->getContent()); 211 | $this->token = $data->token; 212 | $this->user_id = $data->id; 213 | 214 | $newRole = Role::where('slug', 'admin')->first(); 215 | 216 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 217 | ->delete("/api/roles/{$newRole->id}"); 218 | 219 | $response 220 | ->assertJson( 221 | fn (AssertableJson $json) => $json->where('error', 1) 222 | ->has('message') 223 | ); 224 | } 225 | } 226 | -------------------------------------------------------------------------------- /tests/Feature/UserRoleTest.php: -------------------------------------------------------------------------------- 1 | postJson('/api/login', [ 13 | 'email' => 'admin@hydra.project', 14 | 'password' => 'hydra', 15 | ]); 16 | 17 | $data = json_decode($response->getContent()); 18 | $this->token = $data->token; 19 | $this->user_id = $data->id; 20 | 21 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 22 | ->get('/api/users/1/roles'); 23 | 24 | $response 25 | ->assertJson( 26 | fn (AssertableJson $json) => $json->has( 27 | 'roles.0', 28 | fn ($json) => $json->where('id', 1) 29 | ->where('name', 'Administrator') 30 | ->where('slug', 'admin') 31 | ->etc() 32 | )->etc() 33 | ); 34 | } 35 | 36 | public function test_assign_role_to_a_user() { 37 | $newUser = User::create([ 38 | 'name' => 'Test User', 39 | 'password' => Hash::make('abcd'), 40 | 'email' => 'testuser@hydra.project', 41 | ]); 42 | 43 | $response = $this->postJson('/api/login', [ 44 | 'email' => 'admin@hydra.project', 45 | 'password' => 'hydra', 46 | ]); 47 | 48 | $data = json_decode($response->getContent()); 49 | $this->token = $data->token; 50 | $this->user_id = $data->id; 51 | 52 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 53 | ->post("/api/users/{$newUser->id}/roles", ['role_id' => 3]); //assign customer role 54 | 55 | $response 56 | ->assertJson( 57 | fn (AssertableJson $json) => $json->has( 58 | 'roles.0', 59 | fn ($json) => $json->where('id', 3) 60 | ->where('name', 'Customer') 61 | ->where('slug', 'customer') 62 | ->etc() 63 | )->etc() 64 | ); 65 | 66 | $newUser->delete(); 67 | } 68 | 69 | public function test_assign_role_multiple_times_to_a_user_should_fail() { 70 | $newUser = User::create([ 71 | 'name' => 'Test User', 72 | 'password' => Hash::make('abcd'), 73 | 'email' => 'testuser@hydra.project', 74 | ]); 75 | 76 | $response = $this->postJson('/api/login', [ 77 | 'email' => 'admin@hydra.project', 78 | 'password' => 'hydra', 79 | ]); 80 | 81 | $data = json_decode($response->getContent()); 82 | $this->token = $data->token; 83 | $this->user_id = $data->id; 84 | 85 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 86 | ->post("/api/users/{$newUser->id}/roles", ['role_id' => 3]); //assign customer role 87 | 88 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 89 | ->post("/api/users/{$newUser->id}/roles", ['role_id' => 3]); //again assign customer role 90 | 91 | $response 92 | ->assertJson( 93 | fn (AssertableJson $json) => $json->has( 94 | 'roles', 95 | fn ($json) => $json->has(1)->etc() //only one role 96 | )->etc() 97 | ); 98 | 99 | $newUser->delete(); 100 | } 101 | 102 | public function test_assign_multiple_roles_to_a_user() { 103 | $newUser = User::create([ 104 | 'name' => 'Test User', 105 | 'password' => Hash::make('abcd'), 106 | 'email' => 'testuser@hydra.project', 107 | ]); 108 | 109 | $response = $this->postJson('/api/login', [ 110 | 'email' => 'admin@hydra.project', 111 | 'password' => 'hydra', 112 | ]); 113 | 114 | $data = json_decode($response->getContent()); 115 | $this->token = $data->token; 116 | $this->user_id = $data->id; 117 | 118 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 119 | ->post("/api/users/{$newUser->id}/roles", ['role_id' => 2]); //assign customer role 120 | 121 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 122 | ->post("/api/users/{$newUser->id}/roles", ['role_id' => 3]); //again assign customer role 123 | 124 | $response 125 | ->assertJson( 126 | fn (AssertableJson $json) => $json->has( 127 | 'roles', 128 | fn ($json) => $json->has(2)->etc() //only one role 129 | )->etc() 130 | ); 131 | 132 | $newUser->delete(); 133 | } 134 | 135 | public function test_delete_role_from_a_user() { 136 | $newUser = User::create([ 137 | 'name' => 'Test User', 138 | 'password' => Hash::make('abcd'), 139 | 'email' => 'testuser@hydra.project', 140 | ]); 141 | 142 | $response = $this->postJson('/api/login', [ 143 | 'email' => 'admin@hydra.project', 144 | 'password' => 'hydra', 145 | ]); 146 | 147 | $data = json_decode($response->getContent()); 148 | $this->token = $data->token; 149 | $this->user_id = $data->id; 150 | 151 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 152 | ->post("/api/users/{$newUser->id}/roles", ['role_id' => 2]); //assign customer role 153 | 154 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 155 | ->post("/api/users/{$newUser->id}/roles", ['role_id' => 3]); //again assign customer role 156 | 157 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 158 | ->delete("/api/users/{$newUser->id}/roles/3"); //delete 159 | 160 | $response 161 | ->assertJson( 162 | fn (AssertableJson $json) => $json->has( 163 | 'roles', 164 | fn ($json) => $json->has(1)->etc() //only one role 165 | )->etc() 166 | ); 167 | 168 | $newUser->delete(); 169 | } 170 | 171 | public function test_delete_all_roles_from_a_user() { 172 | $newUser = User::create([ 173 | 'name' => 'Test User', 174 | 'password' => Hash::make('abcd'), 175 | 'email' => 'testuser@hydra.project', 176 | ]); 177 | 178 | $response = $this->postJson('/api/login', [ 179 | 'email' => 'admin@hydra.project', 180 | 'password' => 'hydra', 181 | ]); 182 | 183 | $data = json_decode($response->getContent()); 184 | $this->token = $data->token; 185 | $this->user_id = $data->id; 186 | 187 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 188 | ->post("/api/users/{$newUser->id}/roles", ['role_id' => 2]); //assign customer role 189 | 190 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 191 | ->post("/api/users/{$newUser->id}/roles", ['role_id' => 3]); //again assign customer role 192 | 193 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 194 | ->delete("/api/users/{$newUser->id}/roles/3"); //delete 195 | $response = $this->withHeader('Authorization', 'Bearer '.$this->token) 196 | ->delete("/api/users/{$newUser->id}/roles/2"); //delete 197 | 198 | $response 199 | ->assertJson( 200 | fn (AssertableJson $json) => $json->has( 201 | 'roles', 202 | fn ($json) => $json->has(0)->etc() //only one role 203 | )->etc() 204 | ); 205 | 206 | $newUser->delete(); 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /config/app.php: -------------------------------------------------------------------------------- 1 | env('APP_NAME', 'Laravel'), 19 | 20 | /* 21 | |-------------------------------------------------------------------------- 22 | | Application Environment 23 | |-------------------------------------------------------------------------- 24 | | 25 | | This value determines the "environment" your application is currently 26 | | running in. This may determine how you prefer to configure various 27 | | services the application utilizes. Set this in your ".env" file. 28 | | 29 | */ 30 | 31 | 'env' => env('APP_ENV', 'production'), 32 | 33 | /* 34 | |-------------------------------------------------------------------------- 35 | | Application Debug Mode 36 | |-------------------------------------------------------------------------- 37 | | 38 | | When your application is in debug mode, detailed error messages with 39 | | stack traces will be shown on every error that occurs within your 40 | | application. If disabled, a simple generic error page is shown. 41 | | 42 | */ 43 | 44 | 'debug' => (bool) env('APP_DEBUG', false), 45 | 46 | /* 47 | |-------------------------------------------------------------------------- 48 | | Application URL 49 | |-------------------------------------------------------------------------- 50 | | 51 | | This URL is used by the console to properly generate URLs when using 52 | | the Artisan command line tool. You should set this to the root of 53 | | your application so that it is used when running Artisan tasks. 54 | | 55 | */ 56 | 57 | 'url' => env('APP_URL', 'http://localhost'), 58 | 59 | 'asset_url' => env('ASSET_URL'), 60 | 61 | /* 62 | |-------------------------------------------------------------------------- 63 | | Application Timezone 64 | |-------------------------------------------------------------------------- 65 | | 66 | | Here you may specify the default timezone for your application, which 67 | | will be used by the PHP date and date-time functions. We have gone 68 | | ahead and set this to a sensible default for you out of the box. 69 | | 70 | */ 71 | 72 | 'timezone' => 'UTC', 73 | 74 | /* 75 | |-------------------------------------------------------------------------- 76 | | Application Locale Configuration 77 | |-------------------------------------------------------------------------- 78 | | 79 | | The application locale determines the default locale that will be used 80 | | by the translation service provider. You are free to set this value 81 | | to any of the locales which will be supported by the application. 82 | | 83 | */ 84 | 85 | 'locale' => 'en', 86 | 87 | /* 88 | |-------------------------------------------------------------------------- 89 | | Application Fallback Locale 90 | |-------------------------------------------------------------------------- 91 | | 92 | | The fallback locale determines the locale to use when the current one 93 | | is not available. You may change the value to correspond to any of 94 | | the language folders that are provided through your application. 95 | | 96 | */ 97 | 98 | 'fallback_locale' => 'en', 99 | 100 | /* 101 | |-------------------------------------------------------------------------- 102 | | Faker Locale 103 | |-------------------------------------------------------------------------- 104 | | 105 | | This locale will be used by the Faker PHP library when generating fake 106 | | data for your database seeds. For example, this will be used to get 107 | | localized telephone numbers, street address information and more. 108 | | 109 | */ 110 | 111 | 'faker_locale' => 'en_US', 112 | 113 | /* 114 | |-------------------------------------------------------------------------- 115 | | Encryption Key 116 | |-------------------------------------------------------------------------- 117 | | 118 | | This key is used by the Illuminate encrypter service and should be set 119 | | to a random, 32 character string, otherwise these encrypted strings 120 | | will not be safe. Please do this before deploying an application! 121 | | 122 | */ 123 | 124 | 'key' => env('APP_KEY'), 125 | 126 | 'cipher' => 'AES-256-CBC', 127 | 128 | /* 129 | |-------------------------------------------------------------------------- 130 | | Maintenance Mode Driver 131 | |-------------------------------------------------------------------------- 132 | | 133 | | These configuration options determine the driver used to determine and 134 | | manage Laravel's "maintenance mode" status. The "cache" driver will 135 | | allow maintenance mode to be controlled across multiple machines. 136 | | 137 | | Supported drivers: "file", "cache" 138 | | 139 | */ 140 | 141 | 'maintenance' => [ 142 | 'driver' => 'file', 143 | // 'store' => 'redis', 144 | ], 145 | 146 | /* 147 | |-------------------------------------------------------------------------- 148 | | Autoloaded Service Providers 149 | |-------------------------------------------------------------------------- 150 | | 151 | | The service providers listed here will be automatically loaded on the 152 | | request to your application. Feel free to add your own services to 153 | | this array to grant expanded functionality to your applications. 154 | | 155 | */ 156 | 157 | 'providers' => [ 158 | 159 | /* 160 | * Laravel Framework Service Providers... 161 | */ 162 | Illuminate\Auth\AuthServiceProvider::class, 163 | Illuminate\Broadcasting\BroadcastServiceProvider::class, 164 | Illuminate\Bus\BusServiceProvider::class, 165 | Illuminate\Cache\CacheServiceProvider::class, 166 | Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class, 167 | Illuminate\Cookie\CookieServiceProvider::class, 168 | Illuminate\Database\DatabaseServiceProvider::class, 169 | Illuminate\Encryption\EncryptionServiceProvider::class, 170 | Illuminate\Filesystem\FilesystemServiceProvider::class, 171 | Illuminate\Foundation\Providers\FoundationServiceProvider::class, 172 | Illuminate\Hashing\HashServiceProvider::class, 173 | Illuminate\Mail\MailServiceProvider::class, 174 | Illuminate\Notifications\NotificationServiceProvider::class, 175 | Illuminate\Pagination\PaginationServiceProvider::class, 176 | Illuminate\Pipeline\PipelineServiceProvider::class, 177 | Illuminate\Queue\QueueServiceProvider::class, 178 | Illuminate\Redis\RedisServiceProvider::class, 179 | Illuminate\Auth\Passwords\PasswordResetServiceProvider::class, 180 | Illuminate\Session\SessionServiceProvider::class, 181 | Illuminate\Translation\TranslationServiceProvider::class, 182 | Illuminate\Validation\ValidationServiceProvider::class, 183 | Illuminate\View\ViewServiceProvider::class, 184 | 185 | /* 186 | * Package Service Providers... 187 | */ 188 | 189 | /* 190 | * Application Service Providers... 191 | */ 192 | App\Providers\AppServiceProvider::class, 193 | App\Providers\AuthServiceProvider::class, 194 | // App\Providers\BroadcastServiceProvider::class, 195 | App\Providers\EventServiceProvider::class, 196 | App\Providers\RouteServiceProvider::class, 197 | 198 | ], 199 | 200 | /* 201 | |-------------------------------------------------------------------------- 202 | | Class Aliases 203 | |-------------------------------------------------------------------------- 204 | | 205 | | This array of class aliases will be registered when this application 206 | | is started. However, feel free to register as many as you wish as 207 | | the aliases are "lazy" loaded so they don't hinder performance. 208 | | 209 | */ 210 | 211 | 'aliases' => Facade::defaultAliases()->merge([ 212 | // 'ExampleClass' => App\Example\ExampleClass::class, 213 | ])->toArray(), 214 | 215 | ]; 216 | -------------------------------------------------------------------------------- /lang/en/validation.php: -------------------------------------------------------------------------------- 1 | 'The :attribute must be accepted.', 17 | 'accepted_if' => 'The :attribute must be accepted when :other is :value.', 18 | 'active_url' => 'The :attribute is not a valid URL.', 19 | 'after' => 'The :attribute must be a date after :date.', 20 | 'after_or_equal' => 'The :attribute must be a date after or equal to :date.', 21 | 'alpha' => 'The :attribute must only contain letters.', 22 | 'alpha_dash' => 'The :attribute must only contain letters, numbers, dashes and underscores.', 23 | 'alpha_num' => 'The :attribute must only contain letters and numbers.', 24 | 'array' => 'The :attribute must be an array.', 25 | 'before' => 'The :attribute must be a date before :date.', 26 | 'before_or_equal' => 'The :attribute must be a date before or equal to :date.', 27 | 'between' => [ 28 | 'array' => 'The :attribute must have between :min and :max items.', 29 | 'file' => 'The :attribute must be between :min and :max kilobytes.', 30 | 'numeric' => 'The :attribute must be between :min and :max.', 31 | 'string' => 'The :attribute must be between :min and :max characters.', 32 | ], 33 | 'boolean' => 'The :attribute field must be true or false.', 34 | 'confirmed' => 'The :attribute confirmation does not match.', 35 | 'current_password' => 'The password is incorrect.', 36 | 'date' => 'The :attribute is not a valid date.', 37 | 'date_equals' => 'The :attribute must be a date equal to :date.', 38 | 'date_format' => 'The :attribute does not match the format :format.', 39 | 'declined' => 'The :attribute must be declined.', 40 | 'declined_if' => 'The :attribute must be declined when :other is :value.', 41 | 'different' => 'The :attribute and :other must be different.', 42 | 'digits' => 'The :attribute must be :digits digits.', 43 | 'digits_between' => 'The :attribute must be between :min and :max digits.', 44 | 'dimensions' => 'The :attribute has invalid image dimensions.', 45 | 'distinct' => 'The :attribute field has a duplicate value.', 46 | 'email' => 'The :attribute must be a valid email address.', 47 | 'ends_with' => 'The :attribute must end with one of the following: :values.', 48 | 'enum' => 'The selected :attribute is invalid.', 49 | 'exists' => 'The selected :attribute is invalid.', 50 | 'file' => 'The :attribute must be a file.', 51 | 'filled' => 'The :attribute field must have a value.', 52 | 'gt' => [ 53 | 'array' => 'The :attribute must have more than :value items.', 54 | 'file' => 'The :attribute must be greater than :value kilobytes.', 55 | 'numeric' => 'The :attribute must be greater than :value.', 56 | 'string' => 'The :attribute must be greater than :value characters.', 57 | ], 58 | 'gte' => [ 59 | 'array' => 'The :attribute must have :value items or more.', 60 | 'file' => 'The :attribute must be greater than or equal to :value kilobytes.', 61 | 'numeric' => 'The :attribute must be greater than or equal to :value.', 62 | 'string' => 'The :attribute must be greater than or equal to :value characters.', 63 | ], 64 | 'image' => 'The :attribute must be an image.', 65 | 'in' => 'The selected :attribute is invalid.', 66 | 'in_array' => 'The :attribute field does not exist in :other.', 67 | 'integer' => 'The :attribute must be an integer.', 68 | 'ip' => 'The :attribute must be a valid IP address.', 69 | 'ipv4' => 'The :attribute must be a valid IPv4 address.', 70 | 'ipv6' => 'The :attribute must be a valid IPv6 address.', 71 | 'json' => 'The :attribute must be a valid JSON string.', 72 | 'lt' => [ 73 | 'array' => 'The :attribute must have less than :value items.', 74 | 'file' => 'The :attribute must be less than :value kilobytes.', 75 | 'numeric' => 'The :attribute must be less than :value.', 76 | 'string' => 'The :attribute must be less than :value characters.', 77 | ], 78 | 'lte' => [ 79 | 'array' => 'The :attribute must not have more than :value items.', 80 | 'file' => 'The :attribute must be less than or equal to :value kilobytes.', 81 | 'numeric' => 'The :attribute must be less than or equal to :value.', 82 | 'string' => 'The :attribute must be less than or equal to :value characters.', 83 | ], 84 | 'mac_address' => 'The :attribute must be a valid MAC address.', 85 | 'max' => [ 86 | 'array' => 'The :attribute must not have more than :max items.', 87 | 'file' => 'The :attribute must not be greater than :max kilobytes.', 88 | 'numeric' => 'The :attribute must not be greater than :max.', 89 | 'string' => 'The :attribute must not be greater than :max characters.', 90 | ], 91 | 'mimes' => 'The :attribute must be a file of type: :values.', 92 | 'mimetypes' => 'The :attribute must be a file of type: :values.', 93 | 'min' => [ 94 | 'array' => 'The :attribute must have at least :min items.', 95 | 'file' => 'The :attribute must be at least :min kilobytes.', 96 | 'numeric' => 'The :attribute must be at least :min.', 97 | 'string' => 'The :attribute must be at least :min characters.', 98 | ], 99 | 'multiple_of' => 'The :attribute must be a multiple of :value.', 100 | 'not_in' => 'The selected :attribute is invalid.', 101 | 'not_regex' => 'The :attribute format is invalid.', 102 | 'numeric' => 'The :attribute must be a number.', 103 | 'password' => [ 104 | 'letters' => 'The :attribute must contain at least one letter.', 105 | 'mixed' => 'The :attribute must contain at least one uppercase and one lowercase letter.', 106 | 'numbers' => 'The :attribute must contain at least one number.', 107 | 'symbols' => 'The :attribute must contain at least one symbol.', 108 | 'uncompromised' => 'The given :attribute has appeared in a data leak. Please choose a different :attribute.', 109 | ], 110 | 'present' => 'The :attribute field must be present.', 111 | 'prohibited' => 'The :attribute field is prohibited.', 112 | 'prohibited_if' => 'The :attribute field is prohibited when :other is :value.', 113 | 'prohibited_unless' => 'The :attribute field is prohibited unless :other is in :values.', 114 | 'prohibits' => 'The :attribute field prohibits :other from being present.', 115 | 'regex' => 'The :attribute format is invalid.', 116 | 'required' => 'The :attribute field is required.', 117 | 'required_array_keys' => 'The :attribute field must contain entries for: :values.', 118 | 'required_if' => 'The :attribute field is required when :other is :value.', 119 | 'required_unless' => 'The :attribute field is required unless :other is in :values.', 120 | 'required_with' => 'The :attribute field is required when :values is present.', 121 | 'required_with_all' => 'The :attribute field is required when :values are present.', 122 | 'required_without' => 'The :attribute field is required when :values is not present.', 123 | 'required_without_all' => 'The :attribute field is required when none of :values are present.', 124 | 'same' => 'The :attribute and :other must match.', 125 | 'size' => [ 126 | 'array' => 'The :attribute must contain :size items.', 127 | 'file' => 'The :attribute must be :size kilobytes.', 128 | 'numeric' => 'The :attribute must be :size.', 129 | 'string' => 'The :attribute must be :size characters.', 130 | ], 131 | 'starts_with' => 'The :attribute must start with one of the following: :values.', 132 | 'string' => 'The :attribute must be a string.', 133 | 'timezone' => 'The :attribute must be a valid timezone.', 134 | 'unique' => 'The :attribute has already been taken.', 135 | 'uploaded' => 'The :attribute failed to upload.', 136 | 'url' => 'The :attribute must be a valid URL.', 137 | 'uuid' => 'The :attribute must be a valid UUID.', 138 | 139 | /* 140 | |-------------------------------------------------------------------------- 141 | | Custom Validation Language Lines 142 | |-------------------------------------------------------------------------- 143 | | 144 | | Here you may specify custom validation messages for attributes using the 145 | | convention "attribute.rule" to name the lines. This makes it quick to 146 | | specify a specific custom language line for a given attribute rule. 147 | | 148 | */ 149 | 150 | 'custom' => [ 151 | 'attribute-name' => [ 152 | 'rule-name' => 'custom-message', 153 | ], 154 | ], 155 | 156 | /* 157 | |-------------------------------------------------------------------------- 158 | | Custom Validation Attributes 159 | |-------------------------------------------------------------------------- 160 | | 161 | | The following language lines are used to swap our attribute placeholder 162 | | with something more reader friendly such as "E-Mail Address" instead 163 | | of "email". This simply helps us make our message more expressive. 164 | | 165 | */ 166 | 167 | 'attributes' => [], 168 | 169 | ]; 170 | -------------------------------------------------------------------------------- /resources/views/welcome.blade.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Laravel 8 | 9 | 10 | 11 | 12 | 13 | 16 | 17 | 22 | 23 | 24 |
25 | @if (Route::has('login')) 26 | 37 | @endif 38 | 39 |
40 |
41 | 42 | 43 | 44 | 45 | 46 |
47 | 48 |
49 |
50 |
51 |
52 | 53 | 54 |
55 | 56 |
57 |
58 | Laravel has wonderful, thorough documentation covering every aspect of the framework. Whether you are new to the framework or have previous experience with Laravel, we recommend reading all of the documentation from beginning to end. 59 |
60 |
61 |
62 | 63 |
64 |
65 | 66 | 67 |
68 | 69 |
70 |
71 | Laracasts offers thousands of video tutorials on Laravel, PHP, and JavaScript development. Check them out, see for yourself, and massively level up your development skills in the process. 72 |
73 |
74 |
75 | 76 |
77 |
78 | 79 | 80 |
81 | 82 |
83 |
84 | Laravel News is a community driven portal and newsletter aggregating all of the latest and most important news in the Laravel ecosystem, including new package releases and tutorials. 85 |
86 |
87 |
88 | 89 |
90 |
91 | 92 |
Vibrant Ecosystem
93 |
94 | 95 |
96 |
97 | Laravel's robust library of first-party tools and libraries, such as Forge, Vapor, Nova, and Envoyer help you take your projects to the next level. Pair them with powerful open source libraries like Cashier, Dusk, Echo, Horizon, Sanctum, Telescope, and more. 98 |
99 |
100 |
101 |
102 |
103 | 104 |
105 |
106 |
107 | 108 | 109 | 110 | 111 | 112 | Shop 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | Sponsor 121 | 122 |
123 |
124 | 125 |
126 | Laravel v{{ Illuminate\Foundation\Application::VERSION }} (PHP v{{ PHP_VERSION }}) 127 |
128 |
129 |
130 |
131 | 132 | 133 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ![Hydra - Zero Config API Boilerplate with Laravel Sanctum](https://res.cloudinary.com/roxlox/image/upload/v1653133921/hydra/hydra-trnsparent_jcsl4l.png) 4 | 5 | # Hydra - Zero Config API Boilerplate with Laravel Sanctum 6 | ![GitHub](https://img.shields.io/github/license/hasinhayder/hydra?label=License&style=flat-square) 7 | 8 | Hydra is a zero-config API boilerplate with Laravel Sanctum and comes with excellent user and role management API out of the box. Start your next big API project with Hydra, focus on building business logic, and save countless hours of writing boring user and role management API again and again. 9 | 10 | Hydra works with Laravel 10.x and Sanctum 3.x. If you want to work with Laravel 9.x then checkout the 9.x branch. 11 | 12 | - [Hydra - Zero Config API Boilerplate with Laravel Sanctum](#hydra---zero-config-api-boilerplate-with-laravel-sanctum) 13 | - [Getting Started](#getting-started) 14 | - [Without Docker (Simple)](#without-docker-simple) 15 | - [Using Docker \& Laravel Sail](#using-docker--laravel-sail) 16 | - [Screencast](#screencast) 17 | - [Database Migration and Seeding](#database-migration-and-seeding) 18 | - [List of Default Routes](#list-of-default-routes) 19 | - [Default Roles](#default-roles) 20 | - [Routes Documentation](#routes-documentation) 21 | - [User Registration](#user-registration) 22 | - [User Authentication/Login (Admin)](#user-authenticationlogin-admin) 23 | - [User Authentication/Login (Other Roles)](#user-authenticationlogin-other-roles) 24 | - [List Users (Admin Ability Required)](#list-users-admin-ability-required) 25 | - [Update a User (User/Admin Ability Required)](#update-a-user-useradmin-ability-required) 26 | - [Delete a User (Admin Ability Required)](#delete-a-user-admin-ability-required) 27 | - [List Roles (Admin Ability Required)](#list-roles-admin-ability-required) 28 | - [Add a New Role (Admin Ability Required)](#add-a-new-role-admin-ability-required) 29 | - [Update a Role (Admin Ability Required)](#update-a-role-admin-ability-required) 30 | - [Delete a Role (Admin Ability Required)](#delete-a-role-admin-ability-required) 31 | - [List Available Roles of a User (Admin Ability Required)](#list-available-roles-of-a-user-admin-ability-required) 32 | - [Assign a Role to a User (Admin Ability Required)](#assign-a-role-to-a-user-admin-ability-required) 33 | - [Delete a Role from a User (Admin Ability Required)](#delete-a-role-from-a-user-admin-ability-required) 34 | - [Notes](#notes) 35 | - [Default Admin Username and Password](#default-admin-username-and-password) 36 | - [Default Role for New Users](#default-role-for-new-users) 37 | - [Single Session or Multiple Session](#single-session-or-multiple-session) 38 | - [Add `Accept: application/json` Header In Your API Calls (Important)](#add-accept-applicationjson-header-in-your-api-calls-important) 39 | - [Logging](#logging) 40 | - [Code Formatting](#code-formatting) 41 | - [Tutorial](#tutorial) 42 | - [Create a New API Controller](#create-a-new-api-controller) 43 | - [Add a Function](#add-a-function) 44 | - [Create Protected Routes](#create-protected-routes) 45 | - [Test Protected Routes](#test-protected-routes) 46 | - [Protect a Route with Laravel Sanctum's Ability and Abilities Middleware](#protect-a-route-with-laravel-sanctums-ability-and-abilities-middleware) 47 | 48 | ## Getting Started 49 | 50 | It's super easy to get Hydra up and running. 51 | 52 | First clone the project and change the directory 53 | 54 | ```shell 55 | git clone https://github.com/hasinhayder/hydra.git 56 | cd hydra 57 | ``` 58 | 59 | Then follow the process using either Docker or without Docker (simple). 60 | 61 | ### Without Docker (Simple) 62 | 63 | 1. Install the dependencies 64 | 65 | ```shell 66 | composer install 67 | ``` 68 | 69 | 2. Copy `.env.example` to `.env` 70 | 71 | ```shell 72 | cp .env.example .env 73 | ``` 74 | 75 | 3. Generate application key 76 | 77 | ```shell 78 | php artisan key:generate 79 | ``` 80 | 81 | 4. Start the webserver 82 | 83 | ```shell 84 | php artisan serve 85 | ``` 86 | 87 | That's mostly it! You have a fully running laravel installation with Sanctum, all configured. 88 | 89 | ### Using Docker & Laravel Sail 90 | 91 | 1. Install the dependencies 92 | 93 | ```shell 94 | docker run --rm \ 95 | -u "$(id -u):$(id -g)" \ 96 | -v $(pwd):/var/www/html \ 97 | -w /var/www/html \ 98 | laravelsail/php81-composer:latest \ 99 | composer install --ignore-platform-reqs 100 | ``` 101 | 102 | 2. Copy `.env.example` to `.env` 103 | 104 | ```shell 105 | cp .env.example .env 106 | ``` 107 | 108 | 3. Run the containers 109 | 110 | ```shell 111 | ./vendor/bin/sail up 112 | ``` 113 | 114 | 4. Generate application key 115 | 116 | ```shell 117 | ./vendor/bin/sail artisan key:generate 118 | ``` 119 | 120 | To learn more about Sail, visit the [official Doc](https://laravel.com/docs/9.x/sail). 121 | 122 | ### Screencast 123 | 124 | [![asciicast](https://asciinema.org/a/497775.svg)](https://asciinema.org/a/497775) 125 | 126 | ## Database Migration and Seeding 127 | 128 | Open your `.env` file and change the DATABASE options. You can start with SQLite by following these steps 129 | 130 | 1. Create a new SQLite database 131 | 132 | ```shell 133 | touch database/hydra.sqlite 134 | ``` 135 | 136 | Or simply create a new file as **hydra.sqlite** inside your **database** folder. 137 | 138 | 2. You can run both migrations and seeders together by simply running the following command 139 | 140 | ```shell 141 | php artisan migrate:fresh --seed 142 | ``` 143 | 144 | **OR** 145 | 146 | 147 | you can run them separately using the following commands 148 | 149 | 2. Run Migrations 150 | 151 | ```shell 152 | php artisan migrate:fresh 153 | ``` 154 | 155 | Now your database has essential tables for user and roles management. 156 | 157 | 3. Run Database Seeders 158 | 159 | Run `db:seed`, and you have your first admin user, some essential roles in the roles table, and the relationship correctly setup. 160 | 161 | ```shell 162 | php artisan db:seed 163 | ``` 164 | 165 | Please note that the default admin user is **admin@hydra.project** and the default password is **hydra**. You should create a new admin user before deploying to production and delete this default admin user. You can do that using the available Hydra user management API or any DB management tool. 166 | 167 | ## List of Default Routes 168 | 169 | Here is a list of default routes. Run the following artisan command to see this list in your terminal. 170 | 171 | ```shell 172 | php artisan route:list 173 | ``` 174 | 175 | ![Hydra - List of Default Routes](https://res.cloudinary.com/roxlox/image/upload/v1653131647/hydra/default-routes-hydra_fgn9oh.webp) 176 | 177 | ## Default Roles 178 | 179 | Hydra comes with these `super-admin`,`admin`,`editor`,`customer` & `user` roles out of the box. For details, open the roles table after database seeding, or open the laravel tinker and experiment with the `Role` model. 180 | 181 | ```shell 182 | php artisan tinker 183 | ``` 184 | 185 | run the following command 186 | 187 | ```php 188 | >>> Role::select(['id','slug','name'])->get() 189 | //or 190 | >>> Role::all(['id','name','slug']) 191 | //or 192 | >>> Role::all() 193 | ``` 194 | 195 | ## Routes Documentation 196 | 197 | Let's have a look at what Hydra has to offer. Before experimenting with the following API endpoints, run your Hydra project using `php artisan serve` command. For the next part of this documentation, we assumed that Hydra is listening at http://localhost:8000 198 | 199 | ### User Registration 200 | 201 | You can make an `HTTP POST` call to create/register a new user to the following endpoint. Newly created users will have the `user` role by default. 202 | 203 | ```shell 204 | http://localhost:8000/api/users 205 | ``` 206 | 207 | **API Payload & Response** 208 | 209 | You can send a Form Multipart payload or a JSON payload like this. 210 | 211 | ```json 212 | { 213 | "name":"Hydra User", 214 | "email":"user@hydra.project", 215 | "password":"Surprisingly A Good Password" 216 | } 217 | ``` 218 | 219 | Voila! Your user has been created and is now ready to log in! 220 | 221 | If this user already exists, then you will receive a 409 Response like this 222 | 223 | ```json 224 | { 225 | "error": 1, 226 | "message": "user already exists" 227 | } 228 | ``` 229 | 230 | ### User Authentication/Login (Admin) 231 | 232 | Remember Hydra comes with the default admin user? You can log in as an admin by making an HTTP POST call to the following route. 233 | 234 | ```shell 235 | http://localhost:8000/api/login 236 | ``` 237 | 238 | **API Payload & Response** 239 | 240 | You can send a Form Multipart or a JSON payload like this. 241 | 242 | ```json 243 | { 244 | "email":"admin@hydra.project", 245 | "password":"hydra" 246 | } 247 | ``` 248 | 249 | You will get a JSON response with user token. You need this admin token for making any call to other routes protected by admin ability. 250 | 251 | ```json 252 | { 253 | "error": 0, 254 | "token": "1|se9wkPKTxevv9jpVgXN8wS5tYKx53wuRLqvRuqCR" 255 | } 256 | ``` 257 | 258 | For any unsuccessful attempt, you will receive a 401 error response. 259 | 260 | ```json 261 | { 262 | "error": 1, 263 | "message": "invalid credentials" 264 | } 265 | ``` 266 | 267 | ### User Authentication/Login (Other Roles) 268 | 269 | You can log in as a user by making an HTTP POST call to the following route 270 | 271 | ```shell 272 | http://localhost:8000/api/login 273 | ``` 274 | 275 | **API Payload & Response** 276 | 277 | You can send a Form Multipart or a JSON payload like this 278 | 279 | ```json 280 | { 281 | "email":"user@hydra.project", 282 | "password":"Surprisingly A Good Password" 283 | } 284 | ``` 285 | 286 | You will get a JSON response with user token. You need this user token for making any calls to other routes protected by user ability. 287 | 288 | ```json 289 | { 290 | "error": 0, 291 | "token": "2|u0ZUNlNtXgdUmtQSACRU1KWBKAmcaX8Bkhd2xVIf" 292 | } 293 | ``` 294 | 295 | For any unsuccessful attempt, you will receive a 401 error response. 296 | 297 | ```json 298 | { 299 | "error": 1, 300 | "message": "invalid credentials" 301 | } 302 | ``` 303 | 304 | ### List Users (Admin Ability Required) 305 | 306 | To list the users, make an `HTTP GET` call to the following route, with Admin Token obtained from Admin Login. Add this token as a standard `Bearer Token` to your API call. 307 | 308 | ```shell 309 | http://localhost:8000/api/users 310 | ``` 311 | 312 | **API Payload & Response** 313 | 314 | No payload is required for this call. 315 | 316 | You will get a JSON response with all users available in your project. 317 | 318 | ```json 319 | [ 320 | { 321 | "id": 1, 322 | "name": "Hydra Admin", 323 | "email": "admin@hydra.project" 324 | }, 325 | { 326 | "id": 2, 327 | "name": "Test User", 328 | "email": "test@hydra.project" 329 | }, 330 | ] 331 | ``` 332 | 333 | For any unsuccessful attempt or wrong token, you will receive a 401 error response. 334 | 335 | ```json 336 | { 337 | "message": "Unauthenticated." 338 | } 339 | ``` 340 | 341 | ### Update a User (User/Admin Ability Required) 342 | 343 | Make an `HTTP PUT` request to the following route to update an existing user. Replace {userId} with actual user id. You must include a Bearer token obtained from User/Admin authentication. A bearer admin token can update any user. A bearer user token can only update the authenticated user by this token. 344 | 345 | ```shell 346 | http://localhost:8000/api/users/{userId} 347 | ``` 348 | 349 | For example, to update the user with id 3, use this endpoint `http://localhost:8000/api/users/3` 350 | 351 | **API Payload & Response** 352 | 353 | You can include `name` or `email`, or both in a URL Encoded Form Data or JSON payload, just like this 354 | 355 | ```json 356 | { 357 | "name":"Captain Cook", 358 | "email":"captaincook@hydra.project" 359 | } 360 | ``` 361 | 362 | You will receive the updated user if the bearer token is valid. 363 | 364 | ```json 365 | { 366 | "id": 3, 367 | "name": "Captain Cook", 368 | "email": "captaincook@hydra.project", 369 | } 370 | ``` 371 | 372 | For any unsuccessful attempt with an invalid token, you will receive a 401 error response. 373 | 374 | ```json 375 | { 376 | "error": 1, 377 | "message": "invalid credentials" 378 | } 379 | ``` 380 | 381 | If a bearer user token attempts to update any other user but itself, a 409 error response will be delivered 382 | 383 | ```json 384 | { 385 | "error": 1, 386 | "message": "Not authorized" 387 | } 388 | ``` 389 | 390 | For any unsuccessful attempt with an invalid `user id`, you will receive a 404 not found error response. For example, when you are trying to delete a non-existing user with id 16, you will receive the following response. 391 | 392 | ```json 393 | { 394 | "error": 1, 395 | "message": "No query results for model [App\\Models\\User] 16" 396 | } 397 | ``` 398 | 399 | ### Delete a User (Admin Ability Required) 400 | 401 | To delete an existing user, make a `HTTP DELETE` request to the following route. Replace {userId} with actual user id 402 | 403 | ```shell 404 | http://localhost:8000/api/users/{userId} 405 | ``` 406 | 407 | For example to delete the user with id 2, use this endpoint `http://localhost:8000/api/users/2` 408 | 409 | **API Payload & Response** 410 | 411 | No payload is required for this call. 412 | 413 | If the request is successful and the bearer token is valid, you will receive a JSON response like this 414 | 415 | ```json 416 | { 417 | "error": 0, 418 | "message": "user deleted" 419 | } 420 | ``` 421 | 422 | You will receive a 401 error response for any unsuccessful attempt with an invalid token. 423 | 424 | ```json 425 | { 426 | "error": 1, 427 | "message": "invalid credentials" 428 | } 429 | ``` 430 | 431 | For any unsuccessful attempt with an invalid `user id`, you will receive a 404 not found error response. For example, you will receive the following response when you try to delete a non-existing user with id 16. 432 | 433 | ```json 434 | { 435 | "error": 1, 436 | "message": "No query results for model [App\\Models\\User] 16" 437 | } 438 | ``` 439 | 440 | ### List Roles (Admin Ability Required) 441 | 442 | To list the roles, make an `HTTP GET` call to the following route, with Admin Token obtained from Admin Login. Add this token as a standard `Bearer Token` to your API call. 443 | 444 | ```shell 445 | http://localhost:8000/api/roles 446 | ``` 447 | 448 | **API Payload & Response** 449 | 450 | No payload is required for this call. 451 | 452 | You will get a JSON response with all the roles available in your project. 453 | 454 | ```json 455 | [ 456 | { 457 | "id": 1, 458 | "name": "Administrator", 459 | "slug": "admin" 460 | }, 461 | { 462 | "id": 2, 463 | "name": "User", 464 | "slug": "user" 465 | }, 466 | { 467 | "id": 3, 468 | "name": "Customer", 469 | "slug": "customer" 470 | }, 471 | { 472 | "id": 4, 473 | "name": "Editor", 474 | "slug": "editor" 475 | }, 476 | { 477 | "id": 5, 478 | "name": "All", 479 | "slug": "*" 480 | }, 481 | { 482 | "id": 6, 483 | "name": "Super Admin", 484 | "slug": "super-admin" 485 | } 486 | ] 487 | ``` 488 | 489 | For any unsuccessful attempt or wrong token, you will receive a 401 error response. 490 | 491 | ```json 492 | { 493 | "message": "Unauthenticated." 494 | } 495 | ``` 496 | 497 | ### Add a New Role (Admin Ability Required) 498 | 499 | To list the roles, make an `HTTP POST` call to the following route, with Admin Token obtained from Admin Login. Add this token as a standard `Bearer Token` to your API call. 500 | 501 | ```shell 502 | http://localhost:8000/api/roles 503 | ``` 504 | 505 | **API Payload & Response** 506 | 507 | You need to supply title of the role as `name`, role `slug` in your payload as Multipart Form or JSON data 508 | 509 | ```json 510 | { 511 | "name":"Manager", 512 | "slug":"manager" 513 | } 514 | ``` 515 | 516 | You will get a JSON response with this newly created role for successful execution. 517 | 518 | ```json 519 | { 520 | "name": "Manager", 521 | "slug": "manager", 522 | "id": 7 523 | } 524 | ``` 525 | 526 | If this role `slug` already exists, you will get a 409 error message like this 527 | 528 | ```json 529 | { 530 | "error": 1, 531 | "message": "role already exists" 532 | } 533 | ``` 534 | 535 | For any unsuccessful attempt or wrong token, you will receive a 401 error response. 536 | 537 | ```json 538 | { 539 | "message": "Unauthenticated." 540 | } 541 | ``` 542 | 543 | ### Update a Role (Admin Ability Required) 544 | 545 | To update a role, make an `HTTP PUT` or `HTTP PATCH` request to the following route, with Admin Token obtained from Admin Login. Add this token as a standard `Bearer Token` to your API call. 546 | 547 | ```shell 548 | http://localhost:8000/api/roles/{roleId} 549 | ``` 550 | 551 | For example to update the Customer role, use this endpoint `http://localhost:8000/api/roles/3` 552 | 553 | **API Payload & Response** 554 | 555 | You need to supply title of the role as `name`, and/or role `slug` in your payload as Multipart Form or JSON data 556 | 557 | ```json 558 | { 559 | "name":"Product Customer", 560 | "slug":"product-customer" 561 | } 562 | ``` 563 | 564 | You will get a JSON response with this updated role for successful execution. 565 | 566 | ```json 567 | { 568 | "id": 3, 569 | "name": "Product Customer", 570 | "slug": "product-customer" 571 | } 572 | ``` 573 | 574 | Please note that you cannot change a `super-admin` or `admin` role slug because many API routes in Hydra exclusively require this role to function correctly. 575 | 576 | For any unsuccessful attempt or wrong token, you will receive a 401 error response. 577 | 578 | ```json 579 | { 580 | "message": "Unauthenticated." 581 | } 582 | ``` 583 | 584 | ### Delete a Role (Admin Ability Required) 585 | 586 | To delete a role, make an `HTTP DELETE` request to the following route, with Admin Token obtained from Admin Login. Add this token as a standard `Bearer Token` to your API call. 587 | 588 | ```shell 589 | http://localhost:8000/api/roles/{roleId} 590 | ``` 591 | 592 | For example, to delete the Customer role, use this endpoint `http://localhost:8000/api/roles/3` 593 | 594 | **API Payload & Response** 595 | 596 | No payload is required for this endpoint. 597 | 598 | You will get a JSON response with this updated role for successful execution. 599 | 600 | ```json 601 | { 602 | "error": 0, 603 | "message": "role has been deleted" 604 | } 605 | ``` 606 | 607 | Please note that you cannot delete the `admin` role because many API routes in Hydra exclusively require this role to function correctly. 608 | 609 | If you try to delete the admin role, you will receive the following 422 error response. 610 | 611 | ```json 612 | { 613 | "error": 1, 614 | "message": "you cannot delete this role" 615 | } 616 | ``` 617 | 618 | For any unsuccessful attempt or wrong token, you will receive a 401 error response. 619 | 620 | ```json 621 | { 622 | "message": "Unauthenticated." 623 | } 624 | ``` 625 | 626 | ### List Available Roles of a User (Admin Ability Required) 627 | 628 | To list all available roles for a user, make an `HTTP GET` request to the following route, with Admin Token obtained from Admin Login. Add this token as a standard `Bearer Token` to your API call. Replace {userId} with an actual user id 629 | 630 | ```shell 631 | http://localhost:8000/api/users/{userId}/roles 632 | ``` 633 | 634 | For example to get all roles assigned to the user with id 2, use this endpoint `http://localhost:8000/api/users/2/roles` 635 | 636 | **API Payload & Response** 637 | 638 | No payload is required for this call. 639 | 640 | For successful execution, you will get a JSON response containing the user with all its assigned roles. 641 | 642 | ```json 643 | { 644 | "id": 2, 645 | "name": "Test User", 646 | "email": "test@hydra.project", 647 | "roles": [ 648 | { 649 | "id": 2, 650 | "name": "User", 651 | "slug": "user" 652 | }, 653 | { 654 | "id": 3, 655 | "name": "Customer", 656 | "slug": "customer" 657 | } 658 | ] 659 | } 660 | ``` 661 | 662 | For any unsuccessful attempt or wrong token, you will receive a 401 error response. 663 | 664 | ```json 665 | { 666 | "message": "Unauthenticated." 667 | } 668 | ``` 669 | 670 | ### Assign a Role to a User (Admin Ability Required) 671 | 672 | To assign a role to a user, make an `HTTP POST` request to the following route, with Admin Token obtained from Admin Login. Add this token as a standard `Bearer Token` to your API call. Replace {userId} with an actual user id 673 | 674 | ```shell 675 | http://localhost:8000/api/users/{userId}/roles 676 | ``` 677 | 678 | For example to assign a role to the user with id 2, use this endpoint `http://localhost:8000/api/users/2/roles` 679 | 680 | **API Payload & Response** 681 | 682 | You need to supply `role_id` in your payload as Multipart Form or JSON data 683 | 684 | ```json 685 | { 686 | "role_id":3 687 | } 688 | ``` 689 | 690 | For successful execution, you will get a JSON response containing the user with all its assigned roles. 691 | 692 | ```json 693 | { 694 | "id": 2, 695 | "name": "Test User", 696 | "email": "test@hydra.project", 697 | "roles": [ 698 | { 699 | "id": 2, 700 | "name": "User", 701 | "slug": "user" 702 | }, 703 | { 704 | "id": 3, 705 | "name": "Customer", 706 | "slug": "customer" 707 | } 708 | ] 709 | } 710 | ``` 711 | 712 | Notice that the user has a `Roles` array, and this newly assigned role is present in this array. 713 | 714 | Please note that it will have no effect if you assign the same `role` again to a user. 715 | 716 | For any unsuccessful attempt or wrong token, you will receive a 401 error response. 717 | 718 | ```json 719 | { 720 | "message": "Unauthenticated." 721 | } 722 | ``` 723 | 724 | ### Delete a Role from a User (Admin Ability Required) 725 | 726 | To delete a role from a user, make an `HTTP DELETE` request to the following route, with Admin Token obtained from Admin Login. Add this token as a standard `Bearer Token` to your API call. Replace `{userId}` with an actual user id, and `{role}` with an actual role id 727 | 728 | ```shell 729 | http://localhost:8000/api/users/{userId}/roles/{role} 730 | ``` 731 | 732 | For example, to delete a role with id 3 from the user with id 2, use this endpoint `http://localhost:8000/api/users/2/roles/3` 733 | 734 | **API Payload & Response** 735 | 736 | No payload is required for this call 737 | 738 | For successful execution, you will get a JSON response containing the user with all asigned roles to it. 739 | 740 | ```json 741 | { 742 | "id": 2, 743 | "name": "Test User", 744 | "email": "test@hydra.project", 745 | "roles": [ 746 | { 747 | "id": 2, 748 | "name": "User", 749 | "slug": "user" 750 | }, 751 | ] 752 | } 753 | ``` 754 | 755 | Notice that the user has a `Roles` array, and the role with id 3 is not present in this array. 756 | 757 | For any unsuccessful attempt or wrong token, you will receive a 401 error response. 758 | 759 | ```json 760 | { 761 | "message": "Unauthenticated." 762 | } 763 | ``` 764 | 765 | ## Notes 766 | 767 | ### Default Admin Username and Password 768 | 769 | When you run the database seeders, a default admin user is created with the username '**admin@hydra.project**' and the password '**hydra**'. You can login as this default admin user and use the bearer token on next API calls where admin ability is required. 770 | 771 | When you push your application to production, please remember to change this user's password, email or simply create a new admin user and delete the default one. 772 | ### Default Role for New Users 773 | 774 | The `user` role is assigned to them when a new user is created. To change this behavior, open your `.env` file and set the value of `DEFAULT_ROLE_SLUG` to any existing `role slug`. New users will have that role by default. For example, if you want your new users to have a `customer` role, set `DEFAULT_ROLE_SLUG=customer` in your `.env` file. 775 | 776 | There are five default role slugs in Hydra. 777 | | Role Slug | Role Name | 778 | |-------------|-------------| 779 | | admin | Admin | 780 | | user | User | 781 | | customer | Customer | 782 | | editor | Editor | 783 | | super-admin | Super Admin | 784 | 785 | 786 | This ENV variable is configured in in `config/hydra.php` as `default_user_role_slug`, and then used in `app/Http/Controllers/UserController.php` 787 | 788 | ### Single Session or Multiple Session 789 | 790 | Hydra doesn't invalidate the previously issued access tokens when a user authenticates. So, all access tokens, including the newly created one, will remain valid. If you want to change this behavior and delete all previous tokens when a user authenticates, set `DELETE_PREVIOUS_ACCESS_TOKENS_ON_LOGIN` to `true` in your `.env` file. The value of `DELETE_PREVIOUS_ACCESS_TOKENS_ON_LOGIN` is set to `false` by default. 791 | 792 | This ENV variable is configured in in `config/hydra.php`, and then used in `app/Http/Controllers/UserController.php` 793 | 794 | ### Add `Accept: application/json` Header In Your API Calls (Important) 795 | 796 | This is very important. To properly receive JSON responses, add the following header to your API requests. 797 | 798 | ```shell 799 | Accept: application/json 800 | ``` 801 | 802 | For example, if you are using `curl` you can make a call like this. 803 | 804 | ```shell 805 | curl --request GET \ 806 | --url http://localhost:8000/hydra/version \ 807 | --header 'Accept: application/json' \ 808 | --header 'Content-Type: application/x-www-form-urlencoded' \ 809 | --data = 810 | ``` 811 | 812 | ### Logging 813 | 814 | Hydra comes with an excellent logger to log request headers, parameters and response to help debugging and inspecting API calls. All you have to do is wrap the route with 'hydra.log' middleware, as shown below 815 | 816 | ```php 817 | Route::post('login', [UserController::class, 'login'])->middleware('hydra.log'); 818 | ``` 819 | 820 | or, like this 821 | 822 | ```php 823 | Route::put('users/{user}', [UserController::class, 'update'])->middleware(['hydra.log', 'auth:sanctum', 'ability:admin,super-admin,user']); 824 | 825 | ``` 826 | 827 | And then you can see the API call logs in `logs/laravel.log` file. 828 | 829 | ### Code Formatting 830 | 831 | Hydra comes with an excellent code formatter called [Laravel Pint](https://github.com/laravel/pint) out of the box, with an excellent configuration preset that you can find in `pint.json`. By default `pint` uses the [Allman style](https://en.wikipedia.org/wiki/Indentation_style#Allman_style) for the braces where the braces are placed in a new line after the function name. So we have changed it to [K&R style](https://en.wikipedia.org/wiki/Indentation_style#K&R_style) formatting where the brace stays on the same line of the function name. 832 | 833 | To format your code using `laravel pint`, you can run the following command any time from inside your project diretory. 834 | 835 | ```shell 836 | ./vendor/bin/pint 837 | ``` 838 | 839 | And that's all for formatting. To know more, check out laravel pint documentation at [https://github.com/laravel/pint](https://github.com/laravel/pint) 840 | 841 | ## Tutorial 842 | 843 | So you decided to give Hydra a try and create a new protected API endpoint; that's awesome; let's dive in. 844 | 845 | ### Create a New API Controller 846 | 847 | You can create a normal or a resourceful controller. To keep it simple, I am going with a standard controller. 848 | 849 | ```shell 850 | php artisan make:controller MessageController 851 | ``` 852 | 853 | This will create a new file called `app/Http/Controlers/MessageController.php` 854 | 855 | ### Add a Function 856 | 857 | We will add a simple function that will greet the authenticated user. Since this will be protected using Sanctum middleware, only a request with a valid bearer token will be able to access this endpoint. You don't need to worry about anything else. 858 | 859 | Open this file `app/Http/Controlers/MessageController.php` and add the following code 860 | 861 | ```php 862 | user(); 872 | 873 | $response = [ 874 | "name" => $user->name, 875 | "role" => $user->roles()->first()->name //or $user->roles()->first()->slug 876 | ]; 877 | 878 | return $response; 879 | 880 | } 881 | } 882 | 883 | ``` 884 | 885 | ### Create Protected Routes 886 | 887 | Let's create a protected route `http://localhost:8000/api/greet` to use this API 888 | 889 | Open your `routes/api.php` file and add the following line at the end. 890 | 891 | ```php 892 | Route::get('greet', [MessageController::class, 'greet'])->middleware(['auth:sanctum']); 893 | ``` 894 | 895 | Nice! Now we have a route `/api/greet` that is only accessible with a valid bearer token. 896 | 897 | ### Test Protected Routes 898 | 899 | If you have already created a user, you need his accessToken first. You can use the admin user or create a new user and then log in and note their bearer token. To create or authenticate a user, check the documentation in the beginning. 900 | 901 | To create a new user, you can place a curl request or use tools like Postman, Insomnia or HTTPie. Here is a quick example using curl. 902 | 903 | ```shell 904 | curl --request POST \ 905 | --url http://localhost:8000/api/users \ 906 | --header 'Accept: application/json' \ 907 | --header 'Content-Type: multipart/form-data; boundary=---011000010111000001101001' \ 908 | --form 'name=Hydra User' \ 909 | --form email=user@hydra.project \ 910 | --form 'password=Surprisingly A Good Password' 911 | ``` 912 | 913 | Great! Now we have our users. Let's login as this new user using curl (You can use tools like Postman, Insomnia, or HTTPie) 914 | 915 | ```shell 916 | curl --request POST \ 917 | --url http://localhost:8000/api/login \ 918 | --header 'Accept: aplication/json' \ 919 | --header 'Content-Type: application/json' \ 920 | --data '{ 921 | "email": "user@hydra.project", 922 | "password": "Surprisingly A Good Password" 923 | }' 924 | ``` 925 | 926 | Now you have this user's accessToken in the response, as shown below. Note it. 927 | 928 | ```javascript 929 | {"error":0,"id":2,"token":"5|gbiWdd7yJFYiTIgoK1jK3C7HZJtJUK1PnBIToBLN"} 930 | ``` 931 | 932 | The bearer token for this user is `5|gbiWdd7yJFYiTIgoK1jK3C7HZJtJUK1PnBIToBLN` 933 | 934 | Now let's test our protected route. Add this bearer token in your PostMan/Insomnia/HTTPie or Curl call and make a `HTTP GET` request to our newly created protected route `http://localhost:8000/api/greet`. Here's an example call with curl 935 | 936 | ```shell 937 | curl --request GET \ 938 | --url http://localhost:8000/api/greet \ 939 | --header 'Accept: application/json' \ 940 | --header 'Authorization: Bearer 5|gbiWdd7yJFYiTIgoK1jK3C7HZJtJUK1PnBIToBLN' 941 | ``` 942 | 943 | The response will be something like this. 944 | 945 | ```javascript 946 | { 947 | "name": "user@hydra.project", 948 | "role": "User" 949 | } 950 | ``` 951 | 952 | Great! you have learned how to create your protected API endpoint using Laravel Sanctum and Hydra! 953 | 954 | ### Protect a Route with Laravel Sanctum's Ability and Abilities Middleware 955 | 956 | Let's make our newly created API endpoint even more robust. Say, we want our route to be accessible by only admin users. Remember you added the following line in the `routes/api.php` file just a few minutes ago? Let's change it. 957 | 958 | ```php 959 | Route::get('greet', [MessageController::class, 'greet'])->middleware(['auth:sanctum']); 960 | ``` 961 | 962 | Change it like this 963 | 964 | ```php 965 | Route::get('greet', [MessageController::class, 'greet'])->middleware(['auth:sanctum', 'ability:admin']); 966 | ``` 967 | 968 | Only an `HTTP GET` call with a valid admin user's access token can access this route. 969 | If you want this route to be accessible by the users with `admin`, **OR** the `user` role, then modify it. 970 | 971 | ```php 972 | Route::get('greet', [MessageController::class, 'greet'])->middleware(['auth:sanctum', 'ability:admin,user']); 973 | ``` 974 | 975 | If you want this route to be accessible by the users with both `user`, **AND** the `customer` role, then modify it. 976 | 977 | ```php 978 | Route::get('greet', [MessageController::class, 'greet'])->middleware(['auth:sanctum', 'abilities:customer,user']); 979 | ``` 980 | 981 | Note that this time we have used the `abilities` keyword instead of `ability` 982 | 983 | Great, now you know everything to start creating your next big API project with Laravel & Laravel Sanctum using our powerful boilerplate project called Hydra. Enjoy! 984 | 985 | 986 | --------------------------------------------------------------------------------