better image uploading & user roles
Some checks failed
Docker / build (push) Has been cancelled

This commit is contained in:
yuriko 🦊 2025-08-09 23:01:27 -04:00
parent 21e59d775a
commit f60ae41bf6
26 changed files with 741 additions and 70 deletions

33
app/Enums/RolesEnum.php Normal file
View file

@ -0,0 +1,33 @@
<?php
namespace App\Enums;
enum RolesEnum: string
{
case RESTRICTED = 'restricted';
case MEMBER = 'member';
case MODERATOR = 'moderator';
case ADMIN = 'admin';
public function label(): string
{
return match ($this)
{
RolesEnum::RESTRICTED => 'Restricted',
RolesEnum::MEMBER => 'Member',
RolesEnum::MODERATOR => 'Moderator',
RolesEnum::ADMIN => 'Admin',
};
}
public function variant(): string
{
return match ($this)
{
RolesEnum::RESTRICTED => 'danger',
RolesEnum::MEMBER => 'neutral',
RolesEnum::MODERATOR => 'success',
RolesEnum::ADMIN => 'brand',
};
}
}

View file

@ -2,6 +2,7 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Enums\RolesEnum;
use App\Models\User; use App\Models\User;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite; use Laravel\Socialite\Facades\Socialite;
@ -17,9 +18,15 @@ class AuthController extends Controller
{ {
$user = Socialite::driver('authentik')->user(); $user = Socialite::driver('authentik')->user();
$authUser = User::updateOrCreate( $authUser = User::where('email', $user->getEmail())->first();
[ 'email' => $user->getEmail() ], if ($authUser == null)
); {
$authUser = User::create([
'email' => $user->getEmail(),
'name' => $user->getName(),
]);
// $authUser->assignRole(RolesEnum::MEMBER);
}
if ($authUser) if ($authUser)
{ {

46
app/Livewire/App/Role.php Normal file
View file

@ -0,0 +1,46 @@
<?php
namespace App\Livewire\App;
use App\Enums\RolesEnum;
use App\Models\User;
use Livewire\Component;
class Role extends Component
{
public User $user;
public string $size = 'small';
protected string $variant = 'neutral';
protected string $name = '';
public function mount(User $user)
{
$this->user = $user;
if ($user->hasRole(RolesEnum::RESTRICTED))
{
$this->variant = RolesEnum::RESTRICTED->variant();
$this->name = RolesEnum::RESTRICTED->label();
}
if ($user->hasRole(RolesEnum::MEMBER))
{
$this->variant = RolesEnum::MEMBER->variant();
$this->name = RolesEnum::MEMBER->label();
}
if ($user->hasRole(RolesEnum::MODERATOR))
{
$this->variant = RolesEnum::MODERATOR->variant();
$this->name = RolesEnum::MODERATOR->label();
}
if ($user->hasRole(RolesEnum::ADMIN))
{
$this->variant = RolesEnum::ADMIN->variant();
$this->name = RolesEnum::ADMIN->label();
}
}
public function render()
{
return view('livewire.app.role');
}
}

View file

@ -15,8 +15,8 @@ class Upload extends Component
{ {
use WithFileUploads; use WithFileUploads;
#[Validate('image|max:65536')] #[Validate(['files.*' => 'required|image|max:65536'])]
public $file; public $files = [];
#[Validate('required|in:safe,suggestive,explicit')] #[Validate('required|in:safe,suggestive,explicit')]
public $rating = 'safe'; public $rating = 'safe';
@ -32,11 +32,14 @@ class Upload extends Component
$this->validate(); $this->validate();
$author = Auth::user(); $author = Auth::user();
if ($this->file) foreach ($this->files as $file)
{
if ($file)
{ {
$post = Post::create([ $post = Post::create([
'extension' => $this->file->getClientOriginalExtension(), 'extension' => $file->getClientOriginalExtension(),
'rating' => $this->rating, 'rating' => $this->rating,
'hash' => $file->hashName(),
]); ]);
if ($post) if ($post)
@ -44,7 +47,7 @@ class Upload extends Component
$author->posts()->save($post); $author->posts()->save($post);
// Save the full image // Save the full image
$this->file->storeAs("posts/$post->id", 'full'); $file->storeAs("posts/$post->id", 'full');
$fullImg = Storage::get("posts/$post->id/full"); $fullImg = Storage::get("posts/$post->id/full");
// Create thumbnail preview // Create thumbnail preview
@ -54,11 +57,10 @@ class Upload extends Component
// Create smaller preview image // Create smaller preview image
$preview = Image::read($fullImg)->scaleDown(width: 1280, height: 720); $preview = Image::read($fullImg)->scaleDown(width: 1280, height: 720);
Storage::put("posts/$post->id/preview", $preview->encodeByMediaType()); Storage::put("posts/$post->id/preview", $preview->encodeByMediaType());
}
return $this->redirect("/posts/$post->id");
} }
} }
return $this->redirect('/upload'); return $this->redirect('/posts');
} }
} }

View file

@ -8,6 +8,7 @@ use Livewire\Component;
class PostFeature extends Component class PostFeature extends Component
{ {
public ?Post $post = null; public ?Post $post = null;
public $tags = null;
public function mount() public function mount()
{ {
@ -18,6 +19,7 @@ class PostFeature extends Component
['$sample' => ['size' => 1]] ['$sample' => ['size' => 1]]
]); ]);
})->first(); })->first();
$this->tags = $this->post->tags()->take(5)->get();
} }
public function placeholder() public function placeholder()
@ -36,7 +38,6 @@ HTML;
{ {
if ($this->post == null) if ($this->post == null)
{ {
$href = route('posts.home');
return view('livewire.post-feature-empty'); return view('livewire.post-feature-empty');
} }
return view('livewire.post-feature'); return view('livewire.post-feature');

View file

@ -3,9 +3,7 @@
namespace App\Livewire\Posts; namespace App\Livewire\Posts;
use App\Models\Post; use App\Models\Post;
use App\Models\Tag;
use Livewire\Attributes\Title; use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component; use Livewire\Component;
use Livewire\WithPagination; use Livewire\WithPagination;
@ -13,11 +11,20 @@ class Index extends Component
{ {
use WithPagination; use WithPagination;
public $posts = [];
public function mount()
{
$this->posts = Post::orderBy('created_at', 'desc')->get();
}
#[Title('Posts')] #[Title('Posts')]
public function render() public function render()
{ {
return view('livewire.posts.index', [ if ($this->posts->count() == 0)
'posts' => Post::orderBy('created_at', 'desc')->paginate(25), {
]); return view('livewire.posts.index-empty');
}
return view('livewire.posts.index');
} }
} }

View file

@ -2,10 +2,28 @@
namespace App\Livewire\Tags; namespace App\Livewire\Tags;
use App\Models\Post;
use App\Models\Tag;
use Livewire\Component; use Livewire\Component;
class View extends Component class View extends Component
{ {
public ?Tag $tag = null;
public $posts = [];
public function mount(?Tag $tag)
{
$this->tag = $tag;
if ($tag)
{
$this->posts = $tag->posts;
}
else
{
$this->posts = Post::doesntHave('tags')->get();
}
}
public function render() public function render()
{ {
return view('livewire.tags.view'); return view('livewire.tags.view');

View file

@ -16,7 +16,7 @@ class Post extends Model
{ {
use SoftDeletes, Favoriteable; use SoftDeletes, Favoriteable;
protected $fillable = [ 'rating', 'extension', 'featured' ]; protected $fillable = [ 'rating', 'extension', 'hash', 'featured' ];
public function user(): BelongsTo public function user(): BelongsTo
{ {

View file

@ -9,13 +9,14 @@ use Laravel\Sanctum\HasApiTokens;
use MongoDB\Laravel\Auth\User as Authenticatable; use MongoDB\Laravel\Auth\User as Authenticatable;
use MongoDB\Laravel\Relations\HasMany; use MongoDB\Laravel\Relations\HasMany;
use Overtrue\LaravelFavorite\Traits\Favoriter; use Overtrue\LaravelFavorite\Traits\Favoriter;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable class User extends Authenticatable
{ {
protected $connection = 'mongodb'; protected $connection = 'mongodb';
protected $table = 'users'; protected $table = 'users';
use HasApiTokens, HasFactory, Notifiable, Favoriter; use HasApiTokens, HasFactory, Notifiable, Favoriter, HasRoles;
protected $fillable = [ protected $fillable = [
'name', 'name',

View file

@ -4,6 +4,7 @@ namespace App\Providers;
use App\Models\PersonalAccessToken; use App\Models\PersonalAccessToken;
use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
use Laravel\Sanctum\Sanctum; use Laravel\Sanctum\Sanctum;
use SocialiteProviders\Authentik\Provider as AuthentikProvider; use SocialiteProviders\Authentik\Provider as AuthentikProvider;
@ -24,6 +25,12 @@ class AppServiceProvider extends ServiceProvider
*/ */
public function boot(): void public function boot(): void
{ {
// Setup admin role access
Gate::before(function ($user, $ability)
{
return $user->hasRole('admin') ? true : null;
});
Sanctum::usePersonalAccessTokenModel(PersonalAccessToken::class); Sanctum::usePersonalAccessTokenModel(PersonalAccessToken::class);
// Authentik // Authentik

View file

@ -24,6 +24,7 @@
"overtrue/laravel-favorite": "^5.3", "overtrue/laravel-favorite": "^5.3",
"predis/predis": "^3.0", "predis/predis": "^3.0",
"socialiteproviders/authentik": "^5.2", "socialiteproviders/authentik": "^5.2",
"spatie/laravel-permission": "^6.21",
"spatie/laravel-searchable": "^1.13" "spatie/laravel-searchable": "^1.13"
}, },
"require-dev": { "require-dev": {

85
composer.lock generated
View file

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "5f2425ade7fd4df888b45f1bbc48bdf1", "content-hash": "5e6c845747a0b798e6b592c32bdccdfe",
"packages": [ "packages": [
{ {
"name": "brick/math", "name": "brick/math",
@ -4874,6 +4874,89 @@
}, },
"time": "2025-02-24T19:33:30+00:00" "time": "2025-02-24T19:33:30+00:00"
}, },
{
"name": "spatie/laravel-permission",
"version": "6.21.0",
"source": {
"type": "git",
"url": "https://github.com/spatie/laravel-permission.git",
"reference": "6a118e8855dfffcd90403aab77bbf35a03db51b3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/spatie/laravel-permission/zipball/6a118e8855dfffcd90403aab77bbf35a03db51b3",
"reference": "6a118e8855dfffcd90403aab77bbf35a03db51b3",
"shasum": ""
},
"require": {
"illuminate/auth": "^8.12|^9.0|^10.0|^11.0|^12.0",
"illuminate/container": "^8.12|^9.0|^10.0|^11.0|^12.0",
"illuminate/contracts": "^8.12|^9.0|^10.0|^11.0|^12.0",
"illuminate/database": "^8.12|^9.0|^10.0|^11.0|^12.0",
"php": "^8.0"
},
"require-dev": {
"laravel/passport": "^11.0|^12.0",
"laravel/pint": "^1.0",
"orchestra/testbench": "^6.23|^7.0|^8.0|^9.0|^10.0",
"phpunit/phpunit": "^9.4|^10.1|^11.5"
},
"type": "library",
"extra": {
"laravel": {
"providers": [
"Spatie\\Permission\\PermissionServiceProvider"
]
},
"branch-alias": {
"dev-main": "6.x-dev",
"dev-master": "6.x-dev"
}
},
"autoload": {
"files": [
"src/helpers.php"
],
"psr-4": {
"Spatie\\Permission\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Freek Van der Herten",
"email": "freek@spatie.be",
"homepage": "https://spatie.be",
"role": "Developer"
}
],
"description": "Permission handling for Laravel 8.0 and up",
"homepage": "https://github.com/spatie/laravel-permission",
"keywords": [
"acl",
"laravel",
"permission",
"permissions",
"rbac",
"roles",
"security",
"spatie"
],
"support": {
"issues": "https://github.com/spatie/laravel-permission/issues",
"source": "https://github.com/spatie/laravel-permission/tree/6.21.0"
},
"funding": [
{
"url": "https://github.com/spatie",
"type": "github"
}
],
"time": "2025-07-23T16:08:05+00:00"
},
{ {
"name": "spatie/laravel-searchable", "name": "spatie/laravel-searchable",
"version": "1.13.0", "version": "1.13.0",

202
config/permission.php Normal file
View file

@ -0,0 +1,202 @@
<?php
return [
'models' => [
/*
* When using the "HasPermissions" trait from this package, we need to know which
* Eloquent model should be used to retrieve your permissions. Of course, it
* is often just the "Permission" model but you may use whatever you like.
*
* The model you want to use as a Permission model needs to implement the
* `Spatie\Permission\Contracts\Permission` contract.
*/
'permission' => Spatie\Permission\Models\Permission::class,
/*
* When using the "HasRoles" trait from this package, we need to know which
* Eloquent model should be used to retrieve your roles. Of course, it
* is often just the "Role" model but you may use whatever you like.
*
* The model you want to use as a Role model needs to implement the
* `Spatie\Permission\Contracts\Role` contract.
*/
'role' => Spatie\Permission\Models\Role::class,
],
'table_names' => [
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your roles. We have chosen a basic
* default value but you may easily change it to any table you like.
*/
'roles' => 'roles',
/*
* When using the "HasPermissions" trait from this package, we need to know which
* table should be used to retrieve your permissions. We have chosen a basic
* default value but you may easily change it to any table you like.
*/
'permissions' => 'permissions',
/*
* When using the "HasPermissions" trait from this package, we need to know which
* table should be used to retrieve your models permissions. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'model_has_permissions' => 'model_has_permissions',
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your models roles. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'model_has_roles' => 'model_has_roles',
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your roles permissions. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'role_has_permissions' => 'role_has_permissions',
],
'column_names' => [
/*
* Change this if you want to name the related pivots other than defaults
*/
'role_pivot_key' => null, // default 'role_id',
'permission_pivot_key' => null, // default 'permission_id',
/*
* Change this if you want to name the related model primary key other than
* `model_id`.
*
* For example, this would be nice if your primary keys are all UUIDs. In
* that case, name this `model_uuid`.
*/
'model_morph_key' => 'model_id',
/*
* Change this if you want to use the teams feature and your related model's
* foreign key is other than `team_id`.
*/
'team_foreign_key' => 'team_id',
],
/*
* When set to true, the method for checking permissions will be registered on the gate.
* Set this to false if you want to implement custom logic for checking permissions.
*/
'register_permission_check_method' => true,
/*
* When set to true, Laravel\Octane\Events\OperationTerminated event listener will be registered
* this will refresh permissions on every TickTerminated, TaskTerminated and RequestTerminated
* NOTE: This should not be needed in most cases, but an Octane/Vapor combination benefited from it.
*/
'register_octane_reset_listener' => false,
/*
* Events will fire when a role or permission is assigned/unassigned:
* \Spatie\Permission\Events\RoleAttached
* \Spatie\Permission\Events\RoleDetached
* \Spatie\Permission\Events\PermissionAttached
* \Spatie\Permission\Events\PermissionDetached
*
* To enable, set to true, and then create listeners to watch these events.
*/
'events_enabled' => false,
/*
* Teams Feature.
* When set to true the package implements teams using the 'team_foreign_key'.
* If you want the migrations to register the 'team_foreign_key', you must
* set this to true before doing the migration.
* If you already did the migration then you must make a new migration to also
* add 'team_foreign_key' to 'roles', 'model_has_roles', and 'model_has_permissions'
* (view the latest version of this package's migration file)
*/
'teams' => false,
/*
* The class to use to resolve the permissions team id
*/
'team_resolver' => \Spatie\Permission\DefaultTeamResolver::class,
/*
* Passport Client Credentials Grant
* When set to true the package will use Passports Client to check permissions
*/
'use_passport_client_credentials' => false,
/*
* When set to true, the required permission names are added to exception messages.
* This could be considered an information leak in some contexts, so the default
* setting is false here for optimum safety.
*/
'display_permission_in_exception' => false,
/*
* When set to true, the required role names are added to exception messages.
* This could be considered an information leak in some contexts, so the default
* setting is false here for optimum safety.
*/
'display_role_in_exception' => false,
/*
* By default wildcard permission lookups are disabled.
* See documentation to understand supported syntax.
*/
'enable_wildcard_permission' => false,
/*
* The class to use for interpreting wildcard permissions.
* If you need to modify delimiters, override the class and specify its name here.
*/
// 'wildcard_permission' => Spatie\Permission\WildcardPermission::class,
/* Cache-specific settings */
'cache' => [
/*
* By default all permissions are cached for 24 hours to speed up performance.
* When permissions or roles are updated the cache is flushed automatically.
*/
'expiration_time' => \DateInterval::createFromDateString('24 hours'),
/*
* The cache key used to store all permissions.
*/
'key' => 'spatie.permission.cache',
/*
* You may optionally indicate a specific cache driver to use for permission and
* role caching using any of the `store` drivers listed in the cache.php config
* file. Using 'default' here means to use the `default` set in cache.php.
*/
'store' => 'default',
],
];

View file

@ -15,6 +15,7 @@ return new class extends Migration
$table->id(); $table->id();
$table->enum('rating', ['unknown', 'safe', 'suggestive', 'explicit'])->default('unknown'); $table->enum('rating', ['unknown', 'safe', 'suggestive', 'explicit'])->default('unknown');
$table->string('extension')->nullable(); $table->string('extension')->nullable();
$table->string('hash')->unique();
$table->boolean('featured')->default(false); $table->boolean('featured')->default(false);
$table->timestamps(); $table->timestamps();
$table->softDeletes(); $table->softDeletes();

View file

@ -0,0 +1,136 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
$teams = config('permission.teams');
$tableNames = config('permission.table_names');
$columnNames = config('permission.column_names');
$pivotRole = $columnNames['role_pivot_key'] ?? 'role_id';
$pivotPermission = $columnNames['permission_pivot_key'] ?? 'permission_id';
throw_if(empty($tableNames), new Exception('Error: config/permission.php not loaded. Run [php artisan config:clear] and try again.'));
throw_if($teams && empty($columnNames['team_foreign_key'] ?? null), new Exception('Error: team_foreign_key on config/permission.php not loaded. Run [php artisan config:clear] and try again.'));
Schema::create($tableNames['permissions'], static function (Blueprint $table) {
// $table->engine('InnoDB');
$table->bigIncrements('id'); // permission id
$table->string('name'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format)
$table->string('guard_name'); // For MyISAM use string('guard_name', 25);
$table->timestamps();
$table->unique(['name', 'guard_name']);
});
Schema::create($tableNames['roles'], static function (Blueprint $table) use ($teams, $columnNames) {
// $table->engine('InnoDB');
$table->bigIncrements('id'); // role id
if ($teams || config('permission.testing')) { // permission.testing is a fix for sqlite testing
$table->unsignedBigInteger($columnNames['team_foreign_key'])->nullable();
$table->index($columnNames['team_foreign_key'], 'roles_team_foreign_key_index');
}
$table->string('name'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format)
$table->string('guard_name'); // For MyISAM use string('guard_name', 25);
$table->timestamps();
if ($teams || config('permission.testing')) {
$table->unique([$columnNames['team_foreign_key'], 'name', 'guard_name']);
} else {
$table->unique(['name', 'guard_name']);
}
});
Schema::create($tableNames['model_has_permissions'], static function (Blueprint $table) use ($tableNames, $columnNames, $pivotPermission, $teams) {
$table->unsignedBigInteger($pivotPermission);
$table->string('model_type');
$table->unsignedBigInteger($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_permissions_model_id_model_type_index');
$table->foreign($pivotPermission)
->references('id') // permission id
->on($tableNames['permissions'])
->onDelete('cascade');
if ($teams) {
$table->unsignedBigInteger($columnNames['team_foreign_key']);
$table->index($columnNames['team_foreign_key'], 'model_has_permissions_team_foreign_key_index');
$table->primary([$columnNames['team_foreign_key'], $pivotPermission, $columnNames['model_morph_key'], 'model_type'],
'model_has_permissions_permission_model_type_primary');
} else {
$table->primary([$pivotPermission, $columnNames['model_morph_key'], 'model_type'],
'model_has_permissions_permission_model_type_primary');
}
});
Schema::create($tableNames['model_has_roles'], static function (Blueprint $table) use ($tableNames, $columnNames, $pivotRole, $teams) {
$table->unsignedBigInteger($pivotRole);
$table->string('model_type');
$table->unsignedBigInteger($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_roles_model_id_model_type_index');
$table->foreign($pivotRole)
->references('id') // role id
->on($tableNames['roles'])
->onDelete('cascade');
if ($teams) {
$table->unsignedBigInteger($columnNames['team_foreign_key']);
$table->index($columnNames['team_foreign_key'], 'model_has_roles_team_foreign_key_index');
$table->primary([$columnNames['team_foreign_key'], $pivotRole, $columnNames['model_morph_key'], 'model_type'],
'model_has_roles_role_model_type_primary');
} else {
$table->primary([$pivotRole, $columnNames['model_morph_key'], 'model_type'],
'model_has_roles_role_model_type_primary');
}
});
Schema::create($tableNames['role_has_permissions'], static function (Blueprint $table) use ($tableNames, $pivotRole, $pivotPermission) {
$table->unsignedBigInteger($pivotPermission);
$table->unsignedBigInteger($pivotRole);
$table->foreign($pivotPermission)
->references('id') // permission id
->on($tableNames['permissions'])
->onDelete('cascade');
$table->foreign($pivotRole)
->references('id') // role id
->on($tableNames['roles'])
->onDelete('cascade');
$table->primary([$pivotPermission, $pivotRole], 'role_has_permissions_permission_id_role_id_primary');
});
app('cache')
->store(config('permission.cache.store') != 'default' ? config('permission.cache.store') : null)
->forget(config('permission.cache.key'));
}
/**
* Reverse the migrations.
*/
public function down(): void
{
$tableNames = config('permission.table_names');
if (empty($tableNames)) {
throw new \Exception('Error: config/permission.php not found and defaults could not be merged. Please publish the package configuration before proceeding, or drop the tables manually.');
}
Schema::drop($tableNames['role_has_permissions']);
Schema::drop($tableNames['model_has_roles']);
Schema::drop($tableNames['model_has_permissions']);
Schema::drop($tableNames['roles']);
Schema::drop($tableNames['permissions']);
}
};

View file

@ -2,9 +2,11 @@
namespace Database\Seeders; namespace Database\Seeders;
use App\Models\User; use App\Enums\RolesEnum;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents; // use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder; use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
class DatabaseSeeder extends Seeder class DatabaseSeeder extends Seeder
{ {
@ -13,11 +15,84 @@ class DatabaseSeeder extends Seeder
*/ */
public function run(): void public function run(): void
{ {
// User::factory(10)->create(); // -- Create permissions
User::factory()->create([ // -- auth
'name' => 'Test User', $auth_login = Permission::create(['name' => 'auth.login']); // allow logging in to the site
'email' => 'test@example.com',
// -- user
$user_read = Permission::create(['name' => 'user.read']); // allow viewing user profiles
$user_write = Permission::create(['name' => 'user.write']); // allow updating user profiles
$user_delete = Permission::create(['name' => 'user.delete']); // allow deleting user profiles
// -- post
$post_read = Permission::create(['name' => 'post.read']); // allow viewing posts
$post_write = Permission::create(['name' => 'post.write']); // allow creating/updating posts
$post_delete = Permission::create(['name' => 'post.delete']); // allow deleting posts
// -- comment
$comment_read = Permission::create(['name' => 'comment.read']); // allow viewing comments
$comment_write = Permission::create(['name' => 'comment.write']); // allow creating/updating comments
$comment_delete = Permission::create(['name' => 'comment.delete']); // allow deleting comments
// -- tag
$tag_read = Permission::create(['name' => 'tag.read']); // allow viewing tags
$tag_write = Permission::create(['name' => 'tag.write']); // allow creating/updating tags
$tag_delete = Permission::create(['name' => 'tag.delete']); // allow deleting tags
// -- tag group
$tag_group_read = Permission::create(['name' => 'tag_group.read']); // allow viewing tag groups
$tag_group_write = Permission::create(['name' => 'tag_group.write']); // allow creating/updating tag groups
$tag_group_delete = Permission::create(['name' => 'tag_group.delete']); // allow deleting tag groups
// -- Create roles
// -- restricted
$restricted_role = app(Role::class)->findOrCreate(RolesEnum::RESTRICTED->value, 'web');
$restricted_role->syncPermissions([
$auth_login,
$user_read,
$post_read,
$comment_read,
$tag_read,
$tag_group_read,
]); ]);
// -- member
$member_role = app(Role::class)->findOrCreate(RolesEnum::MEMBER->value, 'web');
$member_role->syncPermissions([
$auth_login,
$user_read,
$post_read,
$post_write,
$comment_read,
$comment_write,
$tag_read,
$tag_write,
$tag_group_read,
]);
// -- moderator
$mod_role = app(Role::class)->findOrCreate(RolesEnum::MODERATOR->value, 'web');
$mod_role->syncPermissions([
$auth_login,
$user_read,
$post_read,
$post_write,
$post_delete,
$comment_read,
$comment_write,
$comment_delete,
$tag_read,
$tag_write,
$tag_delete,
$tag_group_read,
$tag_group_write,
$tag_group_delete,
]);
// -- admin
app(Role::class)->findOrCreate(RolesEnum::ADMIN->value, 'web');
} }
} }

View file

@ -1,5 +1,5 @@
<!doctype html> <!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" class="wa-theme-tailspin wa-palette-elegant wa-brand-pink wa-neutral-gray wa-success-green wa-warning-yellow wa-danger-red wa-dark"> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}" class="wa-theme-tailspin wa-palette-elegant wa-brand-indigo wa-neutral-gray wa-success-green wa-warning-yellow wa-danger-red wa-dark">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">

View file

@ -0,0 +1 @@
<wa-tag size="{{ $size }}" variant="{{ $variant }}" pill>{{ $name }}</wa-tag>

View file

@ -25,12 +25,18 @@
<wa-card> <wa-card>
<div class="wa-stack wa-gap-l"> <div class="wa-stack wa-gap-l">
<div class="wa-stack"> <div class="wa-stack">
<span class="wa-heading-m">Profile picture</span> <span class="wa-heading-s">Profile picture</span>
<input type="file" wire:model.live="avatar" wire:loading.attr="disabled" /> <label for="avatar" class="wa-cluster wa-placeholder">
<livewire:app.icon name="image-user" class="wa-caption-l" style="font-size: var(--wa-font-size-3xl)" />
<div class="wa-stack wa-gap-3xs">
<span class="wa-heading-m">Click to upload a new profile picture.</span>
@error('avatar') @error('avatar')
<span class="wa-caption-m">{{ $message }}</span> <span class="wa-caption-m">{{ $message }}</span>
@enderror @enderror
</div> </div>
<input id="avatar" type="file" wire:model.live="avatar" wire:loading.attr="disabled" style="opacity: 0;" />
</label>
</div>
<wa-divider></wa-divider> <wa-divider></wa-divider>

View file

@ -4,13 +4,29 @@
<wa-breadcrumb-item>upload</wa-breadcrumb-item> <wa-breadcrumb-item>upload</wa-breadcrumb-item>
</wa-breadcrumb> </wa-breadcrumb>
<form wire:submit="createPost" class="wa-stack wa-gap-xl"> <form wire:submit="createPost">
<wa-card class="wa-stack"> <div class="wa-stack wa-gap-xl"
<input wire:model="file" type="file" label="file" placeholder="Select a file to upload." /> x-data="{ uploading: false, progress: 0 }"
@error('file') x-on:livewire-upload-start="uploading = true"
<span class="wa-caption-m">{{ $message }}</span> x-on:livewire-upload-finish="uploading = false"
x-on:livewire-upload-cancel="uploading = false"
x-on:livewire-upload-error="uploading = false"
x-on:livewire-upload-progress="progress = $event.detail.progress"
>
<label for="files" class="wa-cluster wa-placeholder wa-link-plain">
<livewire:app.icon name="file-image" class="wa-caption-l" style="font-size: var(--wa-font-size-3xl)" />
<div class="wa-stack wa-gap-3xs" wire:loading.remove>
<span class="wa-heading-m">Click to select files to upload.</span>
@error('files.*')
<span class="wa-caption-l">{{ $message }}</span>
@enderror @enderror
</wa-card> </div>
<div class="wa-stack wa-gap-3xs" wire:loading>
<span class="wa-heading-m">Uploading files...</span>
<wa-progress-bar x-show="uploading" x-bind.value="progress" style="--track-height: 6px;"></wa-progress-bar>
</div>
<input id="files" wire:model="files" type="file" style="opacity: 0;" multiple />
</label>
<wa-select wire:model="rating" label="Rating" value="safe" hint="Select a content rating that matches the file."> <wa-select wire:model="rating" label="Rating" value="safe" hint="Select a content rating that matches the file.">
<wa-option value="safe">Safe</wa-option> <wa-option value="safe">Safe</wa-option>
@ -22,5 +38,6 @@
<livewire:app.icon slot="prefix" name="arrow-up-from-bracket" /> <livewire:app.icon slot="prefix" name="arrow-up-from-bracket" />
Upload Upload
</wa-button> </wa-button>
</div>
</form> </form>
</div> </div>

View file

@ -21,8 +21,10 @@
</div> </div>
<div class="wa-cluster wa-gap-xs"> <div class="wa-cluster wa-gap-xs">
<livewire:app.icon name="hashtag" /> <livewire:app.icon name="tags" />
<a href="{{ url("posts/$post->id") }}" wire:navigate.hover>{{ $post->id }}</a> @foreach($tags as $tag)
<a href="{{ route('tags.view', $tag) }}" style="color: {{ $tag->tagGroup->color }};" wire:navigate.hover>{{ $tag->name }}</a>
@endforeach
</div> </div>
</div> </div>
</div> </div>

View file

@ -0,0 +1,11 @@
<div class="wa-stack wa-gap-3xl">
<wa-breadcrumb class="wa-heading-l">
<wa-breadcrumb-item href="{{ route('home') }}" wire:navigate.hover>{{ config('app.name') }}</wa-breadcrumb-item>
<wa-breadcrumb-item>posts</wa-breadcrumb-item>
</wa-breadcrumb>
<a class="wa-stack wa-align-items-center wa-placeholder wa-link-plain" href="{{ route('upload') }}" wire:navigate.hover>
<livewire:app.icon name="image-slash" class="wa-caption-l" style="font-size: var(--wa-font-size-3xl)" />
<span class="wa-heading-m">No posts available</span>
<p class="wa-caption-l">Click here to start uploading!</p>
</a>
</div>

View file

@ -8,5 +8,4 @@
<livewire:posts.thumbnail :$post lazy /> <livewire:posts.thumbnail :$post lazy />
@endforeach @endforeach
</div> </div>
{{ $posts->links('livewire.app.pagination') }}
</div> </div>

View file

@ -19,7 +19,7 @@
<tbody> <tbody>
{{-- Untagged posts --}} {{-- Untagged posts --}}
<tr> <tr>
<td>Untagged</td> <td><a href="{{ route('tags.view-untagged') }}" wire:navigate.hover>Untagged</a></td>
<td></td> <td></td>
<td><wa-format-number value="{{ $untaggedPosts->count() }}"></wa-format-number> {{ Str::plural('post', $untaggedPosts->count()) }}</td> <td><wa-format-number value="{{ $untaggedPosts->count() }}"></wa-format-number> {{ Str::plural('post', $untaggedPosts->count()) }}</td>
<td></td> <td></td>
@ -27,7 +27,7 @@
@foreach ($tags as $tag) @foreach ($tags as $tag)
<tr> <tr>
<td style="color: {{ $tag->tagGroup->color }}">{{ $tag->name }}</td> <td><a href="{{ route('tags.view', $tag) }}" style="color: {{ $tag->tagGroup->color }}" wire:navigate.hover>{{ $tag->name }}</a></td>
<td> <td>
@if ($tag->implies) @if ($tag->implies)
@foreach ($tag->implies as $impliesTagId) @foreach ($tag->implies as $impliesTagId)
@ -51,12 +51,17 @@
<wa-input wire:model="name" type="text" label="Tag name" @error('name') hint="{{ $message }}" @enderror></wa-input> <wa-input wire:model="name" type="text" label="Tag name" @error('name') hint="{{ $message }}" @enderror></wa-input>
<wa-select wire:model="group" label="Tag group" @error('group') hint="{{ $message }}" @enderror> <wa-select wire:model="group" label="Tag group" @error('group') hint="{{ $message }}" @enderror>
@foreach ($tagGroups as $tagGroup) @foreach ($tagGroups as $tagGroup)
<wa-option value="{{ $tagGroup->id }}" style="color: {{ $tagGroup->color }};">{{ $tagGroup->name }}</wa-option> <wa-option value="{{ $tagGroup->id }}">{{ $tagGroup->name }}</wa-option>
@endforeach @endforeach
</wa-select> </wa-select>
<wa-select wire:model="implies" label="Implied tags" multiple clearable @error('implies') hint="{{ $message }}" @enderror> <wa-select wire:model="implies" label="Implied tags" multiple clearable @error('implies') hint="{{ $message }}" @enderror>
@foreach ($tags->all() as $tagToImply) @foreach ($tags->all() as $tagToImply)
<wa-option value="{{ $tagToImply->id }}" style="color: {{ $tagToImply->tagGroup->color }};">{{ $tagToImply->name }}</wa-option> <wa-option value="{{ $tagToImply->id }}">
<div class="wa-split">
<span>{{ $tagToImply->name }}</span>
<span class="wa-caption-s">{{ $tagToImply->tagGroup->name }}</span>
</div>
</wa-option>
@endforeach @endforeach
</wa-select> </wa-select>
<wa-button type="submit" variant="brand" appearance="outlined"> <wa-button type="submit" variant="brand" appearance="outlined">

View file

@ -1,3 +1,12 @@
<div> <div class="wa-stack wa-gap-3xl">
{{-- To attain knowledge, add things every day; To attain wisdom, subtract things every day. --}} <wa-breadcrumb class="wa-heading-l">
<wa-breadcrumb-item href="{{ route('home') }}" wire:navigate.hover>{{ config('app.name') }}</wa-breadcrumb-item>
<wa-breadcrumb-item href="{{ route('tags.home') }}" wire:navigate.hover>tags</wa-breadcrumb-item>
<wa-breadcrumb-item>{{ $tag->name ?? "Untagged" }}</wa-breadcrumb-item>
</wa-breadcrumb>
<div class="wa-cluster wa-gap-s">
@foreach ($posts as $post)
<livewire:posts.thumbnail wire:key="{{ $post->id }}" :$post lazy />
@endforeach
</div>
</div> </div>

View file

@ -38,6 +38,7 @@ Route::middleware('auth')->prefix('posts')->group(function () {
// Tag routes // Tag routes
Route::middleware('auth')->prefix('tags')->group(function () { Route::middleware('auth')->prefix('tags')->group(function () {
Route::get('/', TagsIndexPage::class)->name('tags.home'); Route::get('/', TagsIndexPage::class)->name('tags.home');
Route::get('/view', TagViewPage::class)->name('tags.view-untagged');
Route::get('/view/{tag}', TagViewPage::class)->name('tags.view'); Route::get('/view/{tag}', TagViewPage::class)->name('tags.view');
Route::get('/groups', TagGroupsPage::class)->name('tags.groups'); Route::get('/groups', TagGroupsPage::class)->name('tags.groups');
}); });