fisrt_commit

main
elmer-20 2 months ago
parent 14d4fef898
commit 0925fa4575

@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[compose.yaml]
indent_size = 4

@ -0,0 +1,65 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:wEHrK9znRe1M/jdkBIM7b+TihyUtHygp8hKeqE57eB4=
APP_DEBUG=true
APP_URL=http://localhost:8000
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
# APP_MAINTENANCE_STORE=database
# PHP_CLI_SERVER_WORKERS=4
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=admision_2026
DB_USERNAME=root
DB_PASSWORD=
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
CACHE_STORE=database
# CACHE_PREFIX=
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=log
MAIL_SCHEME=null
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}"

@ -0,0 +1,11 @@
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore

24
back/.gitignore vendored

@ -0,0 +1,24 @@
*.log
.DS_Store
.env
.env.backup
.env.production
.phpactor.json
.phpunit.result.cache
/.fleet
/.idea
/.nova
/.phpunit.cache
/.vscode
/.zed
/auth.json
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/storage/pail
/vendor
Homestead.json
Homestead.yaml
Thumbs.db

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

@ -0,0 +1,28 @@
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use Illuminate\Auth\AuthenticationException; // <- importante importarlo
class Handler extends ExceptionHandler
{
// ... otras propiedades y métodos
/**
* Convert an authentication exception into a response.
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
// Si la petición espera JSON (API)
if ($request->expectsJson()) {
return response()->json(['error' => 'No autenticado.'], 401);
}
// Para web (redirección normal)
return redirect()->guest(route('login'));
}
// ... otros métodos
}

@ -0,0 +1,245 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class AuthController extends Controller
{
/**
* Registro de usuario
*/
public function register(Request $request)
{
try {
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255|regex:/^[\pL\s\-]+$/u',
'email' => 'required|email|unique:users,email|max:255',
'password' => [
'required',
'string',
'min:8',
'confirmed',
'regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/'
],
], [
'password.regex' => 'La contraseña debe contener al menos una mayúscula, una minúscula, un número y un carácter especial.',
'name.regex' => 'El nombre solo puede contener letras y espacios.',
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'errors' => $validator->errors()
], 422);
}
$user = User::create([
'name' => strip_tags(trim($request->name)),
'email' => strtolower(trim($request->email)),
'password' => Hash::make($request->password),
'email_verified_at' => null, // Para implementar verificación de email después
]);
$user->assignRole('administrador');
// Registrar actividad
Log::info('Usuario registrado', ['user_id' => $user->id, 'email' => $user->email]);
// Crear token de acceso
$token = $user->createToken('api_token', ['*'], now()->addHours(12))->plainTextToken;
return response()->json([
'success' => true,
'message' => 'Usuario registrado exitosamente',
'user' => [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
'roles' => $user->getRoleNames(),
'permissions' => $user->getAllPermissions()->pluck('name')
],
'token' => $token,
'token_type' => 'Bearer',
'expires_in' => 12 * 60 * 60 // 12 horas en segundos
], 201);
} catch (\Exception $e) {
Log::error('Error en registro', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return response()->json([
'success' => false,
'message' => 'Error en el servidor. Por favor, intente más tarde.'
], 500);
}
}
/**
* Login de usuario
*/
public function login(Request $request)
{
try {
$validator = Validator::make($request->all(), [
'email' => 'required|email|max:255',
'password' => 'required|string',
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'errors' => $validator->errors()
], 422);
}
$credentials = [
'email' => strtolower(trim($request->email)),
'password' => $request->password
];
// Intentar autenticación
if (!Auth::attempt($credentials)) {
// Registrar intento fallido
Log::warning('Intento de login fallido', ['email' => $request->email]);
return response()->json([
'success' => false,
'message' => 'Credenciales inválidas'
], 401);
}
$user = User::where('email', $credentials['email'])->firstOrFail();
// Verificar si el usuario está activo (puedes agregar un campo 'is_active' después)
// if (!$user->is_active) {
// return response()->json(['error' => 'Cuenta desactivada'], 403);
// }
// Revocar tokens anteriores (opcional, para seguridad)
$user->tokens()->delete();
// Crear nuevo token con expiración
$token = $user->createToken('api_token', ['*'], now()->addHours(12))->plainTextToken;
// Registrar login exitoso
Log::info('Login exitoso', ['user_id' => $user->id]);
return response()->json([
'success' => true,
'message' => 'Login exitoso',
'user' => [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
'roles' => $user->getRoleNames(),
'permissions' => $user->getAllPermissions()->pluck('name')
],
'token' => $token,
'token_type' => 'Bearer',
'expires_in' => 12 * 60 * 60
]);
} catch (\Exception $e) {
Log::error('Error en login', [
'error' => $e->getMessage(),
'email' => $request->email
]);
return response()->json([
'success' => false,
'message' => 'Error en el servidor. Por favor, intente más tarde.'
], 500);
}
}
/**
* Logout de usuario
*/
public function logout(Request $request)
{
try {
if ($request->user()) {
// Registrar logout
Log::info('Logout exitoso', ['user_id' => $request->user()->id]);
// Revocar todos los tokens del usuario
$request->user()->tokens()->delete();
}
return response()->json([
'success' => true,
'message' => 'Sesión cerrada correctamente'
]);
} catch (\Exception $e) {
Log::error('Error en logout', ['error' => $e->getMessage()]);
return response()->json([
'success' => false,
'message' => 'Error al cerrar sesión'
], 500);
}
}
/**
* Obtener usuario actual
*/
public function me(Request $request)
{
try {
$user = $request->user();
if (!$user) {
return response()->json([
'success' => false,
'message' => 'Usuario no autenticado'
], 401);
}
return response()->json([
'success' => true,
'user' => [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
'roles' => $user->getRoleNames(),
'permissions' => $user->getAllPermissions()->pluck('name')
]
]);
} catch (\Exception $e) {
Log::error('Error obteniendo usuario', ['error' => $e->getMessage()]);
return response()->json([
'success' => false,
'message' => 'Error obteniendo información del usuario'
], 500);
}
}
/**
* Refrescar token (opcional para implementar después)
*/
public function refresh(Request $request)
{
$user = $request->user();
$user->tokens()->delete();
$token = $user->createToken('api_token', ['*'], now()->addHours(12))->plainTextToken;
return response()->json([
'success' => true,
'token' => $token,
'token_type' => 'Bearer',
'expires_in' => 12 * 60 * 60
]);
}
}

@ -0,0 +1,8 @@
<?php
namespace App\Http\Controllers;
abstract class Controller
{
//
}

@ -0,0 +1,59 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* Global HTTP middleware stack.
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Http\Middleware\HandleCors::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\Illuminate\Foundation\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*/
protected $middlewareGroups = [
'web' => [
\Illuminate\Cookie\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* Route middleware aliases.
*/
protected $middlewareAliases = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'precognitive' => \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
// 🔥 SPATIE (ESTO ES LO IMPORTANTE)
'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,
'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
];
}

@ -0,0 +1,38 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Auth;
class CheckRole
{
/**
* Handle an incoming request.
*/
public function handle(Request $request, Closure $next, ...$roles): Response
{
$user = Auth::user();
if (!$user) {
return response()->json([
'success' => false,
'message' => 'No autenticado'
], 401);
}
// Verificar si el usuario tiene alguno de los roles requeridos
foreach ($roles as $role) {
if ($user->hasRole($role)) {
return $next($request);
}
}
return response()->json([
'success' => false,
'message' => 'No autorizado para esta acción'
], 403);
}
}

@ -0,0 +1,20 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureTokenIsValid
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
return $next($request);
}
}

@ -0,0 +1,72 @@
<?php
namespace App\Models;
use Laravel\Sanctum\HasApiTokens;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
use App\Models\Academia;
use App\Models\IntentoExamen;
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasApiTokens, HasFactory, Notifiable, HasRoles;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
// 👇 RELACIÓN CLAVE
public function academias()
{
return $this->belongsToMany(
Academia::class,
'academia_user',
'user_id',
'academia_id'
)->withTimestamps();
}
public function intentosExamen()
{
return $this->hasMany(IntentoExamen::class, 'user_id', 'id');
}
public function academia()
{
return $this->hasOne(Academia::class, 'superadmin_id');
}
}

@ -0,0 +1,24 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
}
}

@ -0,0 +1,18 @@
#!/usr/bin/env php
<?php
use Illuminate\Foundation\Application;
use Symfony\Component\Console\Input\ArgvInput;
define('LARAVEL_START', microtime(true));
// Register the Composer autoloader...
require __DIR__.'/vendor/autoload.php';
// Bootstrap Laravel and handle the command...
/** @var Application $app */
$app = require_once __DIR__.'/bootstrap/app.php';
$status = $app->handleCommand(new ArgvInput);
exit($status);

@ -0,0 +1,29 @@
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Spatie\Permission\Middleware\RoleMiddleware;
use Spatie\Permission\Middleware\PermissionMiddleware;
use Spatie\Permission\Middleware\RoleOrPermissionMiddleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
// ✅ ALIAS DE MIDDLEWARE (REEMPLAZA Kernel)
$middleware->alias([
'role' => RoleMiddleware::class,
'permission' => PermissionMiddleware::class,
'role_or_permission' => RoleOrPermissionMiddleware::class,
]);
})
->withExceptions(function (Exceptions $exceptions) {
//
})
->create();

@ -0,0 +1,2 @@
*
!.gitignore

@ -0,0 +1,5 @@
<?php
return [
App\Providers\AppServiceProvider::class,
];

@ -0,0 +1,92 @@
{
"$schema": "https://getcomposer.org/schema.json",
"name": "laravel/laravel",
"type": "project",
"description": "The skeleton application for the Laravel framework.",
"keywords": [
"laravel",
"framework"
],
"license": "MIT",
"require": {
"php": "^8.2",
"laravel/framework": "^12.0",
"laravel/sanctum": "^4.2",
"laravel/tinker": "^2.10.1",
"simplesoftwareio/simple-qrcode": "^4.2",
"spatie/laravel-permission": "^6.24"
},
"require-dev": {
"fakerphp/faker": "^1.23",
"laravel/pail": "^1.2.2",
"laravel/pint": "^1.24",
"laravel/sail": "^1.41",
"mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.6",
"phpunit/phpunit": "^11.5.3"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"setup": [
"composer install",
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\"",
"@php artisan key:generate",
"@php artisan migrate --force",
"npm install",
"npm run build"
],
"dev": [
"Composer\\Config::disableProcessTimeout",
"npx concurrently -c \"#93c5fd,#c4b5fd,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1\" \"npm run dev\" --names='server,queue,vite'"
],
"test": [
"@php artisan config:clear --ansi",
"@php artisan test"
],
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi",
"@php -r \"file_exists('database/database.sqlite') || touch('database/database.sqlite');\"",
"@php artisan migrate --graceful --ansi"
],
"pre-package-uninstall": [
"Illuminate\\Foundation\\ComposerScripts::prePackageUninstall"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true,
"php-http/discovery": true
}
},
"minimum-stability": "stable",
"prefer-stable": true
}

8691
back/composer.lock generated

File diff suppressed because it is too large Load Diff

@ -0,0 +1,126 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application, which will be used when the
| framework needs to place the application's name in a notification or
| other UI elements where an application name needs to be displayed.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| the application so that it's available within Artisan commands.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. The timezone
| is set to "UTC" by default as it is suitable for most use cases.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by Laravel's translation / localization methods. This option can be
| set to any locale for which you plan to have translation strings.
|
*/
'locale' => env('APP_LOCALE', 'en'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is utilized by Laravel's encryption services and should be set
| to a random, 32 character string to ensure that all encrypted values
| are secure. You should do this prior to deploying the application.
|
*/
'cipher' => 'AES-256-CBC',
'key' => env('APP_KEY'),
'previous_keys' => [
...array_filter(
explode(',', (string) env('APP_PREVIOUS_KEYS', ''))
),
],
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => env('APP_MAINTENANCE_DRIVER', 'file'),
'store' => env('APP_MAINTENANCE_STORE', 'database'),
],
];

@ -0,0 +1,115 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option defines the default authentication "guard" and password
| reset "broker" for your application. You may change these values
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => env('AUTH_GUARD', 'web'),
'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| which utilizes session storage plus the Eloquent user provider.
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| If you have multiple user tables or models you may configure multiple
| providers to represent the model / table. These providers may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', App\Models\User::class),
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| These configuration options specify the behavior of Laravel's password
| reset functionality, including the table utilized for token storage
| and the user provider that is invoked to actually retrieve users.
|
| The expiry time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the number of seconds before a password confirmation
| window expires and users are asked to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
];

@ -0,0 +1,117 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache store that will be used by the
| framework. This connection is utilized if another isn't explicitly
| specified when running a cache operation inside the application.
|
*/
'default' => env('CACHE_STORE', 'database'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "array", "database", "file", "memcached",
| "redis", "dynamodb", "octane",
| "failover", "null"
|
*/
'stores' => [
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'connection' => env('DB_CACHE_CONNECTION'),
'table' => env('DB_CACHE_TABLE', 'cache'),
'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'),
'lock_table' => env('DB_CACHE_LOCK_TABLE'),
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
'lock_path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_CACHE_CONNECTION', 'cache'),
'lock_connection' => env('REDIS_CACHE_LOCK_CONNECTION', 'default'),
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
'octane' => [
'driver' => 'octane',
],
'failover' => [
'driver' => 'failover',
'stores' => [
'database',
'array',
],
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, and DynamoDB cache
| stores, there might be other applications using the same cache. For
| that reason, you may prefix every cache key to avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-cache-'),
];

@ -0,0 +1,183 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for database operations. This is
| the connection which will be utilized unless another connection
| is explicitly specified when you execute a query / statement.
|
*/
'default' => env('DB_CONNECTION', 'sqlite'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Below are all of the database connections defined for your application.
| An example configuration is provided for each database system which
| is supported by Laravel. You're free to add / remove connections.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DB_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
'busy_timeout' => null,
'journal_mode' => null,
'synchronous' => null,
'transaction_mode' => 'DEFERRED',
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
(PHP_VERSION_ID >= 80500 ? \Pdo\Mysql::ATTR_SSL_CA : \PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'mariadb' => [
'driver' => 'mariadb',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
(PHP_VERSION_ID >= 80500 ? \Pdo\Mysql::ATTR_SSL_CA : \PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => env('DB_SSLMODE', 'prefer'),
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DB_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run on the database.
|
*/
'migrations' => [
'table' => 'migrations',
'update_date_on_publish' => true,
],
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as Memcached. You may define your connection settings here.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
'persistent' => env('REDIS_PERSISTENT', false),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
],
];

@ -0,0 +1,80 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application for file storage.
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Below you may configure as many filesystem disks as necessary, and you
| may even configure multiple disks for the same driver. Examples for
| most supported storage drivers are configured here for reference.
|
| Supported drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app/private'),
'serve' => true,
'throw' => false,
'report' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => rtrim(env('APP_URL', 'http://localhost'), '/').'/storage',
'visibility' => 'public',
'throw' => false,
'report' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
'report' => false,
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];

@ -0,0 +1,132 @@
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that is utilized to write
| messages to your logs. The value provided here should match one of
| the channels present in the list of "channels" configured below.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => env('LOG_DEPRECATIONS_TRACE', false),
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Laravel
| utilizes the Monolog PHP logging library, which includes a variety
| of powerful log handlers and formatters that you're free to use.
|
| Available drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog", "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => explode(',', (string) env('LOG_STACK', 'single')),
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => env('LOG_DAILY_DAYS', 14),
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => env('LOG_SLACK_USERNAME', 'Laravel Log'),
'emoji' => env('LOG_SLACK_EMOJI', ':boom:'),
'level' => env('LOG_LEVEL', 'critical'),
'replace_placeholders' => true,
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
'processors' => [PsrLogMessageProcessor::class],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'handler_with' => [
'stream' => 'php://stderr',
],
'formatter' => env('LOG_STDERR_FORMATTER'),
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER),
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];

@ -0,0 +1,118 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send all email
| messages unless another mailer is explicitly specified when sending
| the message. All additional mailers can be configured within the
| "mailers" array. Examples of each type of mailer are provided.
|
*/
'default' => env('MAIL_MAILER', 'log'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers that can be used
| when delivering an email. You may specify which one you're using for
| your mailers below. You may also add additional mailers if needed.
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
| "postmark", "resend", "log", "array",
| "failover", "roundrobin"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'scheme' => env('MAIL_SCHEME'),
'url' => env('MAIL_URL'),
'host' => env('MAIL_HOST', '127.0.0.1'),
'port' => env('MAIL_PORT', 2525),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url((string) env('APP_URL', 'http://localhost'), PHP_URL_HOST)),
],
'ses' => [
'transport' => 'ses',
],
'postmark' => [
'transport' => 'postmark',
// 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'),
// 'client' => [
// 'timeout' => 5,
// ],
],
'resend' => [
'transport' => 'resend',
],
'sendmail' => [
'transport' => 'sendmail',
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
'failover' => [
'transport' => 'failover',
'mailers' => [
'smtp',
'log',
],
'retry_after' => 60,
],
'roundrobin' => [
'transport' => 'roundrobin',
'mailers' => [
'ses',
'postmark',
],
'retry_after' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all emails sent by your application to be sent from
| the same address. Here you may specify a name and address that is
| used globally for all emails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
];

@ -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',
],
];

@ -0,0 +1,129 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue supports a variety of backends via a single, unified
| API, giving you convenient access to each backend using identical
| syntax for each. The default queue connection is defined below.
|
*/
'default' => env('QUEUE_CONNECTION', 'database'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection options for every queue backend
| used by your application. An example configuration is provided for
| each backend supported by Laravel. You're also free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis",
| "deferred", "background", "failover", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'connection' => env('DB_QUEUE_CONNECTION'),
'table' => env('DB_QUEUE_TABLE', 'jobs'),
'queue' => env('DB_QUEUE', 'default'),
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'),
'queue' => env('BEANSTALKD_QUEUE', 'default'),
'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90),
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
'block_for' => null,
'after_commit' => false,
],
'deferred' => [
'driver' => 'deferred',
],
'background' => [
'driver' => 'background',
],
'failover' => [
'driver' => 'failover',
'connections' => [
'database',
'deferred',
],
],
],
/*
|--------------------------------------------------------------------------
| Job Batching
|--------------------------------------------------------------------------
|
| The following options configure the database and table that store job
| batching information. These options can be updated to any database
| connection and table which has been defined by your application.
|
*/
'batching' => [
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'job_batches',
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control how and where failed jobs are stored. Laravel ships with
| support for storing failed jobs in a simple file or in a database.
|
| Supported drivers: "database-uuids", "dynamodb", "file", "null"
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'failed_jobs',
],
];

@ -0,0 +1,84 @@
<?php
use Laravel\Sanctum\Sanctum;
return [
/*
|--------------------------------------------------------------------------
| Stateful Domains
|--------------------------------------------------------------------------
|
| Requests from the following domains / hosts will receive stateful API
| authentication cookies. Typically, these should include your local
| and production domains which access your API via a frontend SPA.
|
*/
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
Sanctum::currentApplicationUrlWithPort(),
// Sanctum::currentRequestHost(),
))),
/*
|--------------------------------------------------------------------------
| Sanctum Guards
|--------------------------------------------------------------------------
|
| This array contains the authentication guards that will be checked when
| Sanctum is trying to authenticate a request. If none of these guards
| are able to authenticate the request, Sanctum will use the bearer
| token that's present on an incoming request for authentication.
|
*/
'guard' => ['web'],
/*
|--------------------------------------------------------------------------
| Expiration Minutes
|--------------------------------------------------------------------------
|
| This value controls the number of minutes until an issued token will be
| considered expired. This will override any values set in the token's
| "expires_at" attribute, but first-party sessions are not affected.
|
*/
'expiration' => null,
/*
|--------------------------------------------------------------------------
| Token Prefix
|--------------------------------------------------------------------------
|
| Sanctum can prefix new tokens in order to take advantage of numerous
| security scanning initiatives maintained by open source platforms
| that notify developers if they commit tokens into repositories.
|
| See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning
|
*/
'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),
/*
|--------------------------------------------------------------------------
| Sanctum Middleware
|--------------------------------------------------------------------------
|
| When authenticating your first-party SPA with Sanctum you may need to
| customize some of the middleware Sanctum uses while processing the
| request. You may change the middleware listed below as required.
|
*/
'middleware' => [
'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class,
'encrypt_cookies' => Illuminate\Cookie\Middleware\EncryptCookies::class,
'validate_csrf_token' => Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
],
];

@ -0,0 +1,38 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'postmark' => [
'key' => env('POSTMARK_API_KEY'),
],
'resend' => [
'key' => env('RESEND_API_KEY'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'slack' => [
'notifications' => [
'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'),
],
],
];

@ -0,0 +1,217 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option determines the default session driver that is utilized for
| incoming requests. Laravel supports a variety of storage options to
| persist session data. Database storage is a great default choice.
|
| Supported: "file", "cookie", "database", "memcached",
| "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'database'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to expire immediately when the browser is closed then you may
| indicate that via the expire_on_close configuration option.
|
*/
'lifetime' => (int) env('SESSION_LIFETIME', 120),
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it's stored. All encryption is performed
| automatically by Laravel and you may use the session like normal.
|
*/
'encrypt' => env('SESSION_ENCRYPT', false),
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When utilizing the "file" session driver, the session files are placed
| on disk. The default storage location is defined here; however, you
| are free to provide another location where they should be stored.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table to
| be used to store sessions. Of course, a sensible default is defined
| for you; however, you're welcome to change this to another table.
|
*/
'table' => env('SESSION_TABLE', 'sessions'),
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using one of the framework's cache driven session backends, you may
| define the cache store which should be used to store the session data
| between requests. This must match one of your defined cache stores.
|
| Affects: "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the session cookie that is created by
| the framework. Typically, you should not need to change this value
| since doing so does not grant a meaningful security improvement.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug((string) env('APP_NAME', 'laravel')).'-session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application, but you're free to change this when necessary.
|
*/
'path' => env('SESSION_PATH', '/'),
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| This value determines the domain and subdomains the session cookie is
| available to. By default, the cookie will be available to the root
| domain without subdomains. Typically, this shouldn't be changed.
|
*/
'domain' => env('SESSION_DOMAIN'),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. It's unlikely you should disable this option.
|
*/
'http_only' => env('SESSION_HTTP_ONLY', true),
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" to permit secure cross-site requests.
|
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => env('SESSION_SAME_SITE', 'lax'),
/*
|--------------------------------------------------------------------------
| Partitioned Cookies
|--------------------------------------------------------------------------
|
| Setting this value to true will tie the cookie to the top-level site for
| a cross-site context. Partitioned cookies are accepted by the browser
| when flagged "secure" and the Same-Site attribute is set to "none".
|
*/
'partitioned' => env('SESSION_PARTITIONED_COOKIE', false),
];

@ -0,0 +1 @@
*.sqlite*

@ -0,0 +1,44 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}

@ -0,0 +1,49 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
Schema::dropIfExists('password_reset_tokens');
Schema::dropIfExists('sessions');
}
};

@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('cache', function (Blueprint $table) {
$table->string('key')->primary();
$table->mediumText('value');
$table->integer('expiration')->index();
});
Schema::create('cache_locks', function (Blueprint $table) {
$table->string('key')->primary();
$table->string('owner');
$table->integer('expiration')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('cache');
Schema::dropIfExists('cache_locks');
}
};

@ -0,0 +1,57 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('jobs', function (Blueprint $table) {
$table->id();
$table->string('queue')->index();
$table->longText('payload');
$table->unsignedTinyInteger('attempts');
$table->unsignedInteger('reserved_at')->nullable();
$table->unsignedInteger('available_at');
$table->unsignedInteger('created_at');
});
Schema::create('job_batches', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('name');
$table->integer('total_jobs');
$table->integer('pending_jobs');
$table->integer('failed_jobs');
$table->longText('failed_job_ids');
$table->mediumText('options')->nullable();
$table->integer('cancelled_at')->nullable();
$table->integer('created_at');
$table->integer('finished_at')->nullable();
});
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('jobs');
Schema::dropIfExists('job_batches');
Schema::dropIfExists('failed_jobs');
}
};

@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('personal_access_tokens', function (Blueprint $table) {
$table->id();
$table->morphs('tokenable');
$table->text('name');
$table->string('token', 64)->unique();
$table->text('abilities')->nullable();
$table->timestamp('last_used_at')->nullable();
$table->timestamp('expires_at')->nullable()->index();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('personal_access_tokens');
}
};

@ -0,0 +1,134 @@
<?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), Exception::class, 'Error: config/permission.php not loaded. Run [php artisan config:clear] and try again.');
throw_if($teams && empty($columnNames['team_foreign_key'] ?? null), Exception::class, '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');
throw_if(empty($tableNames), Exception::class, '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']);
}
};

@ -0,0 +1,27 @@
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
use WithoutModelEvents;
/**
* Seed the application's database.
*/
public function run(): void
{
// User::factory(10)->create();
$this->call([
RoleSeeder::class,
]);
User::factory()->create([
'name' => 'Test User',
'email' => 'test@example.com',
]);
}
}

@ -0,0 +1,31 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Illuminate\Support\Facades\Schema;
class RoleSeeder extends Seeder
{
public function run(): void
{
// Evita problemas si se vuelve a ejecutar
app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();
// Roles base
$roles = [
'usuario',
'administrador',
'superadmin',
];
foreach ($roles as $role) {
Role::firstOrCreate([
'name' => $role,
'guard_name' => 'web',
]);
}
}
}

3532
back/package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -0,0 +1,17 @@
{
"$schema": "https://www.schemastore.org/package.json",
"private": true,
"type": "module",
"scripts": {
"build": "vite build",
"dev": "vite"
},
"devDependencies": {
"@tailwindcss/vite": "^4.0.0",
"axios": "^1.11.0",
"concurrently": "^9.0.1",
"laravel-vite-plugin": "^2.0.0",
"tailwindcss": "^4.0.0",
"vite": "^7.0.7"
}
}

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Unit">
<directory>tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory>tests/Feature</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>app</directory>
</include>
</source>
<php>
<env name="APP_ENV" value="testing"/>
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="BROADCAST_CONNECTION" value="null"/>
<env name="CACHE_STORE" value="array"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="MAIL_MAILER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="PULSE_ENABLED" value="false"/>
<env name="TELESCOPE_ENABLED" value="false"/>
<env name="NIGHTWATCH_ENABLED" value="false"/>
</php>
</phpunit>

@ -0,0 +1,25 @@
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Handle X-XSRF-Token Header
RewriteCond %{HTTP:x-xsrf-token} .
RewriteRule .* - [E=HTTP_X_XSRF_TOKEN:%{HTTP:X-XSRF-Token}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

@ -0,0 +1,20 @@
<?php
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
define('LARAVEL_START', microtime(true));
// Determine if the application is in maintenance mode...
if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
require $maintenance;
}
// Register the Composer autoloader...
require __DIR__.'/../vendor/autoload.php';
// Bootstrap Laravel and handle the request...
/** @var Application $app */
$app = require_once __DIR__.'/../bootstrap/app.php';
$app->handleRequest(Request::capture());

@ -0,0 +1,2 @@
User-agent: *
Disallow:

@ -0,0 +1,11 @@
@import 'tailwindcss';
@source '../../vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php';
@source '../../storage/framework/views/*.php';
@source '../**/*.blade.php';
@source '../**/*.js';
@theme {
--font-sans: 'Instrument Sans', ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji',
'Segoe UI Symbol', 'Noto Color Emoji';
}

@ -0,0 +1 @@
import './bootstrap';

@ -0,0 +1,4 @@
import axios from 'axios';
window.axios = axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

File diff suppressed because one or more lines are too long

@ -0,0 +1,34 @@
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\AcademiaController;
use App\Http\Controllers\VinculacionController;
use App\Http\Controllers\Administracion\AdminAcademiaController;
use App\Http\Controllers\Administracion\ExamenesController;
use App\Http\Controllers\Administracion\PreguntasController;
use App\Http\Controllers\Administracion\AreaController;
use App\Http\Controllers\SuperAdminController;
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:sanctum');
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);
// Rutas protegidas
Route::middleware('auth:sanctum')->group(function () {
Route::post('/logout', [AuthController::class, 'logout']);
Route::get('/me', [AuthController::class, 'me']);
Route::post('/refresh-token', [AuthController::class, 'refresh']);
});

@ -0,0 +1,8 @@
<?php
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');

@ -0,0 +1,7 @@
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});

@ -0,0 +1,4 @@
*
!private/
!public/
!.gitignore

@ -0,0 +1,2 @@
*
!.gitignore

@ -0,0 +1,2 @@
*
!.gitignore

@ -0,0 +1,9 @@
compiled.php
config.php
down
events.scanned.php
maintenance.php
routes.php
routes.scanned.php
schedule-*
services.json

@ -0,0 +1,3 @@
*
!data/
!.gitignore

@ -0,0 +1,2 @@
*
!.gitignore

@ -0,0 +1,2 @@
*
!.gitignore

@ -0,0 +1,2 @@
*
!.gitignore

@ -0,0 +1,2 @@
*
!.gitignore

@ -0,0 +1,19 @@
<?php
namespace Tests\Feature;
// use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*/
public function test_the_application_returns_a_successful_response(): void
{
$response = $this->get('/');
$response->assertStatus(200);
}
}

@ -0,0 +1,10 @@
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
//
}

@ -0,0 +1,16 @@
<?php
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*/
public function test_that_true_is_true(): void
{
$this->assertTrue(true);
}
}

@ -0,0 +1,18 @@
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import tailwindcss from '@tailwindcss/vite';
export default defineConfig({
plugins: [
laravel({
input: ['resources/css/app.css', 'resources/js/app.js'],
refresh: true,
}),
tailwindcss(),
],
server: {
watch: {
ignored: ['**/storage/framework/views/**'],
},
},
});

@ -0,0 +1 @@
VITE_API_URL=http://127.0.0.1:8000/api

24
front/.gitignore vendored

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

@ -0,0 +1,3 @@
{
"recommendations": ["Vue.volar"]
}

@ -0,0 +1,5 @@
# Vue 3 + Vite
This template should help get you started developing with Vue 3 in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
Learn more about IDE Support for Vue in the [Vue Docs Scaling up Guide](https://vuejs.org/guide/scaling-up/tooling.html#ide-support).

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>frontend</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>

2396
front/package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -0,0 +1,26 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"ant-design-vue": "^4.2.6",
"axios": "^1.13.3",
"chart.js": "^4.5.1",
"dayjs": "^1.11.19",
"pinia": "^3.0.4",
"vue": "^3.5.24",
"vue-chartjs": "^5.3.3",
"vue-qrcode": "^2.2.2",
"vue-router": "^4.6.4"
},
"devDependencies": {
"@vitejs/plugin-vue": "^6.0.1",
"vite": "^7.2.4"
}
}

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

@ -0,0 +1,6 @@
<template>
<router-view />
</template>
<script setup>
</script>

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>

After

Width:  |  Height:  |  Size: 496 B

@ -0,0 +1,59 @@
import axios from 'axios'
import router from './router'
const api = axios.create({
baseURL: import.meta.env.VITE_API_URL,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
}
});
// Request interceptor
api.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
},
(error) => {
return Promise.reject(error)
}
)
// Response interceptor
api.interceptors.response.use(
(response) => {
return response
},
async (error) => {
const originalRequest = error.config
// Si el error es 401 y no es un intento de re-autenticación
if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true
// Limpiar autenticación
localStorage.removeItem('token')
localStorage.removeItem('user')
// Redirigir a login
router.push('/login')
return Promise.reject(error)
}
// Manejar otros errores
if (error.response?.status === 403) {
router.push('/unauthorized')
}
return Promise.reject(error)
}
)
export default api

File diff suppressed because it is too large Load Diff

@ -0,0 +1,615 @@
<!-- components/Postulante/VinculacionAcademia.vue -->
<template>
<div class="vinculacion-modal">
<div class="modal-content">
<!-- Paso 1: Ingresar código -->
<div class="step-ingreso" v-if="paso === 1">
<div class="step-header">
<div class="step-number active">1</div>
<div class="step-info">
<h3>Ingresa el código de academia</h3>
<p>Pide el código a tu profesor o coordinador</p>
</div>
</div>
<a-form
:model="formState"
layout="vertical"
@finish="validarCodigo"
class="codigo-form"
>
<a-form-item
label="Código de Academia"
:rules="[
{ required: true, message: 'Ingresa el código' },
{ pattern: /^[A-Z0-9\-]+$/, message: 'Solo letras mayúsculas, números y guiones' }
]"
>
<a-input
v-model:value="formState.codigo"
placeholder="Ej: AC001-2024"
size="large"
:disabled="vinculacionStore.isLoading"
@input="formatearCodigo"
>
<template #prefix>
<KeyOutlined style="color: #666" />
</template>
<template #suffix>
<a-tooltip title="¿Cómo obtener el código?">
<QuestionCircleOutlined
@click="mostrarAyuda"
style="cursor: pointer; color: #666"
/>
</a-tooltip>
</template>
</a-input>
</a-form-item>
<a-form-item>
<a-button
type="primary"
html-type="submit"
size="large"
:loading="vinculacionStore.isLoading"
block
>
Validar Código
</a-button>
</a-form-item>
</a-form>
<!-- Códigos recientes -->
<div class="codigos-recientes" v-if="codigosRecientes.length > 0">
<h4>Códigos recientes</h4>
<a-space :size="8" wrap>
<a-tag
v-for="codigo in codigosRecientes"
:key="codigo"
color="blue"
style="cursor: pointer"
@click="usarCodigoReciente(codigo)"
>
{{ codigo }}
<CloseOutlined @click.stop="eliminarCodigoReciente(codigo)" />
</a-tag>
</a-space>
</div>
<!-- Ayuda QR -->
<div class="qr-section">
<p class="qr-title">
<QrcodeOutlined /> También puedes usar QR
</p>
<div class="qr-actions">
<a-button @click="escanearQR">
<CameraOutlined />
Escanear QR
</a-button>
<a-button @click="mostrarEjemploQR">
<EyeOutlined />
Ver ejemplo
</a-button>
</div>
</div>
</div>
<!-- Paso 2: Confirmar vinculación -->
<div class="step-confirmacion" v-else-if="paso === 2 && vinculacionStore.codigoValidado">
<div class="step-header">
<div class="step-number active">2</div>
<div class="step-info">
<h3>Confirmar vinculación</h3>
<p>Revisa los detalles antes de vincular</p>
</div>
</div>
<a-card class="academia-info-card">
<a-space direction="vertical" size="large" style="width: 100%">
<!-- Información de la academia -->
<div class="academia-details">
<div class="academia-header">
<a-avatar :size="48" :style="{ backgroundColor: stringToColor(vinculacionStore.codigoValidado.nombre) }">
{{ vinculacionStore.codigoValidado.nombre.charAt(0).toUpperCase() }}
</a-avatar>
<div class="academia-titulo">
<h3 style="margin: 0">{{ vinculacionStore.codigoValidado.nombre }}</h3>
<p style="margin: 0; color: #666">
Código: <strong>{{ vinculacionStore.codigoValidado.codigo }}</strong>
</p>
</div>
</div>
<a-divider style="margin: 16px 0" />
<!-- Estadísticas -->
<a-row :gutter="16" class="academia-stats">
<a-col :span="12">
<div class="stat-item">
<TeamOutlined style="color: #1890ff; font-size: 20px" />
<div class="stat-info">
<div class="stat-value">{{ vinculacionStore.codigoValidado.estudiantes_activos }}</div>
<div class="stat-label">Estudiantes</div>
</div>
</div>
</a-col>
<a-col :span="12">
<div class="stat-item">
<FileTextOutlined style="color: #52c41a; font-size: 20px" />
<div class="stat-info">
<div class="stat-value">+{{ examenesCount }}</div>
<div class="stat-label">Exámenes</div>
</div>
</div>
</a-col>
</a-row>
<!-- Límite de estudiantes -->
<a-alert
v-if="vinculacionStore.codigoValidado.estudiantes_activos >= vinculacionStore.codigoValidado.limite_estudiantes * 0.9"
type="warning"
message="Cupo casi lleno"
:description="`${vinculacionStore.codigoValidado.estudiantes_activos}/${vinculacionStore.codigoValidado.limite_estudiantes} estudiantes`"
show-icon
style="margin-top: 16px"
/>
<!-- Estado -->
<div class="academia-status">
<a-tag :color="vinculacionStore.codigoValidado.activa ? 'green' : 'red'">
{{ vinculacionStore.codigoValidado.activa ? 'Activa' : 'Inactiva' }}
</a-tag>
<span v-if="vinculacionStore.codigoValidado.ya_vinculado" class="ya-vinculado">
<CheckCircleOutlined /> Ya estás vinculado
</span>
</div>
</div>
<!-- Acciones -->
<div class="acciones-confirmacion">
<a-space :size="16" style="width: 100%">
<a-button
@click="paso = 1"
:disabled="vinculacionStore.isLoading"
block
>
<LeftOutlined />
Volver
</a-button>
<a-button
type="primary"
@click="confirmarVinculacion"
:loading="vinculacionStore.isLoading"
:disabled="
vinculacionStore.codigoValidado.ya_vinculado ||
!vinculacionStore.codigoValidado.activa ||
vinculacionStore.codigoValidado.estudiantes_activos >= vinculacionStore.codigoValidado.limite_estudiantes
"
block
>
<template v-if="vinculacionStore.codigoValidado.ya_vinculado">
Ya vinculado
</template>
<template v-else>
<LinkOutlined />
Vincularme
</template>
</a-button>
</a-space>
</div>
</a-space>
</a-card>
</div>
<!-- Paso 3: Éxito -->
<div class="step-exito" v-else-if="paso === 3">
<div class="exito-content">
<div class="exito-icon">
<CheckCircleOutlined style="font-size: 64px; color: #52c41a" />
</div>
<h2>¡Vinculación exitosa!</h2>
<p>Ahora formas parte de <strong>{{ academiaVinculada?.nombre }}</strong></p>
<div class="exito-details">
<a-card size="small">
<a-list size="small">
<a-list-item>
<template #actions>
<a-tag color="blue">{{ academiaVinculada?.codigo }}</a-tag>
</template>
<a-list-item-meta>
<template #title>
Código de academia
</template>
</a-list-item-meta>
</a-list-item>
<a-list-item>
<template #actions>
<span>{{ examenesDisponibles }} disponibles</span>
</template>
<a-list-item-meta>
<template #title>
Exámenes
</template>
</a-list-item-meta>
</a-list-item>
</a-list>
</a-card>
</div>
<div class="exito-acciones">
<a-space :size="16" style="width: 100%">
<a-button @click="cerrarModal" block>
Continuar
</a-button>
<a-button type="primary" @click="irAExamenes" block>
<EyeOutlined />
Ver exámenes
</a-button>
</a-space>
</div>
</div>
</div>
<!-- Error -->
<div class="step-error" v-else-if="paso === 'error'">
<div class="error-content">
<div class="error-icon">
<CloseCircleOutlined style="font-size: 64px; color: #ff4d4f" />
</div>
<h2>Error en la vinculación</h2>
<p>{{ errorMensaje }}</p>
<div class="error-sugerencias">
<a-alert
type="info"
message="Sugerencias:"
description="1. Verifica que el código sea correcto
2. Asegúrate de que la academia esté activa
3. Contacta al administrador de la academia"
show-icon
/>
</div>
<div class="error-acciones">
<a-space :size="16" style="width: 100%">
<a-button @click="reiniciarProceso" type="primary" block>
<ReloadOutlined />
Intentar nuevamente
</a-button>
<a-button @click="cerrarModal" block>
Cancelar
</a-button>
</a-space>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { useVinculacionStore } from '../../store/vinculacion'
import {
KeyOutlined,
QuestionCircleOutlined,
CloseOutlined,
QrcodeOutlined,
CameraOutlined,
EyeOutlined,
TeamOutlined,
FileTextOutlined,
LeftOutlined,
LinkOutlined,
CheckCircleOutlined,
CloseCircleOutlined,
ReloadOutlined
} from '@ant-design/icons-vue'
const vinculacionStore = useVinculacionStore()
const emit = defineEmits(['cerrar'])
const paso = ref(1)
const formState = reactive({
codigo: ''
})
const codigosRecientes = ref([])
const academiaVinculada = ref(null)
const errorMensaje = ref('')
const examenesCount = ref(15) // Esto vendría del backend
onMounted(() => {
cargarCodigosRecientes()
})
const cargarCodigosRecientes = () => {
const codigos = localStorage.getItem('codigos_recientes')
if (codigos) {
codigosRecientes.value = JSON.parse(codigos)
}
}
const guardarCodigoReciente = (codigo) => {
const codigos = new Set([codigo, ...codigosRecientes.value])
codigosRecientes.value = Array.from(codigos).slice(0, 5)
localStorage.setItem('codigos_recientes', JSON.stringify(codigosRecientes.value))
}
const eliminarCodigoReciente = (codigo) => {
codigosRecientes.value = codigosRecientes.value.filter(c => c !== codigo)
localStorage.setItem('codigos_recientes', JSON.stringify(codigosRecientes.value))
}
const usarCodigoReciente = (codigo) => {
formState.codigo = codigo
validarCodigo()
}
const formatearCodigo = () => {
formState.codigo = formState.codigo.toUpperCase().replace(/[^A-Z0-9\-]/g, '')
}
const validarCodigo = async () => {
if (!formState.codigo.trim()) {
message.error('Ingresa un código válido')
return
}
try {
await vinculacionStore.validarCodigo(formState.codigo)
guardarCodigoReciente(formState.codigo)
paso.value = 2
} catch (error) {
// Error manejado en el store
}
}
const confirmarVinculacion = async () => {
try {
const resultado = await vinculacionStore.vincularAcademia(formState.codigo)
academiaVinculada.value = resultado.academia
paso.value = 3
} catch (error) {
paso.value = 'error'
errorMensaje.value = vinculacionStore.getError || 'Error al vincular con la academia'
}
}
const mostrarAyuda = () => {
message.info('El código te lo debe proporcionar tu profesor o coordinador de la academia')
}
const escanearQR = () => {
message.info('Función de escaneo de QR en desarrollo')
}
const mostrarEjemploQR = () => {
message.info('El QR contiene el código de la academia para escanear')
}
const stringToColor = (str) => {
let hash = 0
for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash)
}
const colors = ['#1890ff', '#52c41a', '#722ed1', '#fa8c16', '#f5222d']
return colors[Math.abs(hash) % colors.length]
}
const cerrarModal = () => {
vinculacionStore.hideModalVinculacion()
reiniciarProceso()
}
const irAExamenes = () => {
cerrarModal()
// Navegar a exámenes
router.push('/postulante/examenes')
}
const reiniciarProceso = () => {
paso.value = 1
formState.codigo = ''
academiaVinculada.value = null
errorMensaje.value = ''
}
const examenesDisponibles = ref(3) // Esto vendría del backend
</script>
<style scoped>
.vinculacion-modal {
padding: 24px;
}
.modal-content {
max-width: 500px;
margin: 0 auto;
}
/* Pasos */
.step-header {
display: flex;
align-items: flex-start;
gap: 16px;
margin-bottom: 24px;
}
.step-number {
width: 32px;
height: 32px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-weight: 600;
background: #f0f0f0;
color: #999;
}
.step-number.active {
background: #1890ff;
color: white;
}
.step-info h3 {
margin: 0 0 4px 0;
font-size: 18px;
}
.step-info p {
margin: 0;
color: #666;
font-size: 14px;
}
/* Formulario */
.codigo-form {
margin-bottom: 24px;
}
/* Códigos recientes */
.codigos-recientes {
margin-bottom: 24px;
}
.codigos-recientes h4 {
margin: 0 0 8px 0;
font-size: 14px;
color: #666;
}
/* QR Section */
.qr-section {
background: #fafafa;
border-radius: 8px;
padding: 16px;
text-align: center;
}
.qr-title {
margin: 0 0 12px 0;
font-weight: 500;
}
.qr-actions {
display: flex;
gap: 8px;
justify-content: center;
}
/* Academia Info Card */
.academia-info-card {
margin-bottom: 24px;
}
.academia-header {
display: flex;
align-items: center;
gap: 16px;
margin-bottom: 16px;
}
.academia-titulo {
flex: 1;
}
.academia-stats {
margin: 16px 0;
}
.stat-item {
display: flex;
align-items: center;
gap: 12px;
}
.stat-value {
font-size: 20px;
font-weight: 600;
line-height: 1;
}
.stat-label {
font-size: 12px;
color: #666;
margin-top: 2px;
}
.academia-status {
display: flex;
align-items: center;
gap: 8px;
margin-top: 16px;
}
.ya-vinculado {
color: #52c41a;
font-size: 14px;
}
/* Éxito y Error */
.exito-content,
.error-content {
text-align: center;
padding: 24px 0;
}
.exito-icon,
.error-icon {
margin-bottom: 24px;
}
.exito-content h2,
.error-content h2 {
margin: 0 0 8px 0;
color: #333;
}
.exito-content p,
.error-content p {
margin: 0 0 24px 0;
color: #666;
}
.exito-details,
.error-sugerencias {
margin-bottom: 24px;
}
.exito-acciones,
.error-acciones {
max-width: 400px;
margin: 0 auto;
}
/* Responsive */
@media (max-width: 576px) {
.vinculacion-modal {
padding: 16px;
}
.step-header {
flex-direction: column;
gap: 8px;
text-align: center;
}
.step-number {
align-self: center;
}
.qr-actions {
flex-direction: column;
}
.academia-header {
flex-direction: column;
text-align: center;
gap: 12px;
}
}
</style>

@ -0,0 +1,307 @@
<!-- components/SuperAdmin/AcademiasList.vue -->
<template>
<div class="academias-list">
<a-card title="Gestión de Academias" class="mb-4">
<template #extra>
<a-space>
<a-input-search
v-model:value="searchText"
placeholder="Buscar academias..."
style="width: 250px"
@search="handleSearch"
/>
<a-button type="primary" @click="showModal = true">
<template #icon><plus-outlined /></template>
Nueva Academia
</a-button>
</a-space>
</template>
<a-table
:columns="columns"
:data-source="academiaStore.getAcademias"
:loading="academiaStore.isLoading"
:pagination="academiaStore.getPagination"
@change="handleTableChange"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'codigo'">
<a-tag color="blue">{{ record.codigo }}</a-tag>
</template>
<template v-if="column.key === 'estado'">
<a-tag :color="record.activa ? 'green' : 'red'">
{{ record.activa ? 'Activa' : 'Inactiva' }}
</a-tag>
</template>
<template v-if="column.key === 'estudiantes'">
<span>{{ record.estudiantes_activos }} / {{ record.limite_estudiantes }}</span>
</template>
<template v-if="column.key === 'admin'">
<span>{{ record.admin_academia?.name || 'No asignado' }}</span>
</template>
<template v-if="column.key === 'acciones'">
<a-space>
<a-button type="link" size="small" @click="verDetalles(record)">
<eye-outlined />
</a-button>
<a-button type="link" size="small" @click="editarAcademia(record)">
<edit-outlined />
</a-button>
<a-popconfirm
title="¿Estás seguro de eliminar esta academia?"
@confirm="eliminarAcademia(record.id)"
>
<a-button type="link" danger size="small">
<delete-outlined />
</a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</a-table>
</a-card>
<!-- Modal para crear/editar academia -->
<a-modal
v-model:open="showModal"
:title="modalTitle"
width="600px"
@ok="handleModalOk"
@cancel="handleModalCancel"
>
<a-form
ref="formRef"
:model="formState"
:rules="rules"
layout="vertical"
@finish="handleSubmit"
>
<a-form-item label="Nombre" name="nombre">
<a-input
v-model:value="formState.nombre"
placeholder="Nombre de la academia"
/>
</a-form-item>
<a-form-item label="Descripción" name="descripcion">
<a-textarea
v-model:value="formState.descripcion"
placeholder="Descripción de la academia"
:rows="3"
/>
</a-form-item>
<a-form-item label="Límite de Estudiantes" name="limite_estudiantes">
<a-input-number
v-model:value="formState.limite_estudiantes"
:min="1"
:max="10000"
style="width: 100%"
/>
</a-form-item>
<a-form-item label="Administrador" name="admin_academia_id" required>
<a-select
v-model:value="formState.admin_academia_id"
placeholder="Seleccionar administrador"
:loading="loadingAdmins"
show-search
option-filter-prop="label"
>
<a-select-option
v-for="admin in administradores"
:key="admin.id"
:value="admin.id"
:label="admin.name"
>
{{ admin.name }} ({{ admin.email }})
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="Estado" name="activa">
<a-switch
v-model:checked="formState.activa"
checked-children="Activa"
un-checked-children="Inactiva"
/>
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
PlusOutlined,
EyeOutlined,
EditOutlined,
DeleteOutlined
} from '@ant-design/icons-vue'
import { useAcademiaStore } from '../../stores/academia'
import { useUserStore } from '../../stores/user'
const academiaStore = useAcademiaStore()
const userStore = useUserStore()
const searchText = ref('')
const showModal = ref(false)
const formRef = ref()
const loadingAdmins = ref(false)
const administradores = ref([])
const editingId = ref(null)
const columns = [
{
title: 'Código',
dataIndex: 'codigo',
key: 'codigo',
width: 150
},
{
title: 'Nombre',
dataIndex: 'nombre',
key: 'nombre',
ellipsis: true
},
{
title: 'Estado',
key: 'estado',
width: 100
},
{
title: 'Estudiantes',
key: 'estudiantes',
width: 150
},
{
title: 'Administrador',
key: 'admin',
ellipsis: true
},
{
title: 'Creada',
dataIndex: 'created_at',
key: 'created_at',
width: 150,
customRender: ({ text }) => new Date(text).toLocaleDateString()
},
{
title: 'Acciones',
key: 'acciones',
width: 150
}
]
const formState = reactive({
nombre: '',
descripcion: '',
limite_estudiantes: 100,
admin_academia_id: null,
activa: true
})
const rules = {
nombre: [
{ required: true, message: 'Por favor ingresa el nombre' },
{ max: 255, message: 'Máximo 255 caracteres' }
],
admin_academia_id: [
{ required: true, message: 'Por favor selecciona un administrador' }
]
}
const modalTitle = computed(() =>
editingId.value ? 'Editar Academia' : 'Nueva Academia'
)
onMounted(() => {
academiaStore.fetchAcademias()
cargarAdministradores()
})
const cargarAdministradores = async () => {
try {
loadingAdmins.value = true
// Aquí deberías implementar un endpoint para obtener usuarios con rol AdminAcademia
const response = await api.get('/usuarios?role=AdminAcademia')
administradores.value = response.data
} catch (error) {
message.error('Error al cargar administradores')
} finally {
loadingAdmins.value = false
}
}
const handleSearch = () => {
academiaStore.setFiltros({ search: searchText.value })
}
const handleTableChange = (pagination) => {
academiaStore.setPagination({
current: pagination.current,
pageSize: pagination.pageSize
})
}
const verDetalles = (academia) => {
// Navegar a la vista de detalles
router.push(`/admin/academias/${academia.id}`)
}
const editarAcademia = (academia) => {
editingId.value = academia.id
Object.assign(formState, {
nombre: academia.nombre,
descripcion: academia.descripcion,
limite_estudiantes: academia.limite_estudiantes,
admin_academia_id: academia.admin_academia_id,
activa: academia.activa
})
showModal.value = true
}
const eliminarAcademia = async (id) => {
await academiaStore.deleteAcademia(id)
}
const handleModalOk = () => {
formRef.value.validateFields().then(async () => {
if (editingId.value) {
await academiaStore.updateAcademia(editingId.value, formState)
} else {
await academiaStore.createAcademia(formState)
}
showModal.value = false
resetForm()
})
}
const handleModalCancel = () => {
resetForm()
}
const resetForm = () => {
formRef.value?.resetFields()
editingId.value = null
Object.assign(formState, {
nombre: '',
descripcion: '',
limite_estudiantes: 100,
admin_academia_id: null,
activa: true
})
}
</script>
<style scoped>
.academias-list {
padding: 20px;
}
</style>

@ -0,0 +1,21 @@
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { createPinia } from 'pinia'
import { useUserStore } from './store/user'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/reset.css'
const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
const userStore = useUserStore()
await userStore.initialize()
app.use(router)
app.use(Antd)
app.mount('#app')

@ -0,0 +1,72 @@
import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Hello from '../components/HelloWorld.vue'
import { useUserStore } from '../store/user'
const routes = [
{
path: '/',
component: Hello
},
{
path: '/login',
component: Login,
meta: { guest: true }
},
{
path: '/usuario/dashboard',
name: 'dashboard',
component: () => import('../views/usuario/Dashboard.vue'),
meta: { requiresAuth: true, role: 'usuario' }
},
{
path: '/admin/dashboard',
name: 'admin-dashboard',
component: () => import('../views/administrador/Dashboard.vue'),
meta: { requiresAuth: true, role: 'administrador' }
},
{
path: '/superadmin/dashboard',
name: 'superadmin-dashboard',
component: () => import('../views/superadmin/Dashboard.vue'),
meta: { requiresAuth: true, role: 'superadmin' }
},
{
path: '/403',
name: 'forbidden',
component: () => import('../views/403.vue')
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
router.beforeEach((to, from, next) => {
const userStore = useUserStore()
// 🚫 No autenticado
if (to.meta.requiresAuth && !userStore.isAuth) {
return next('/login')
}
// 🚫 Autenticado intentando ir a login
if (to.meta.guest && userStore.isAuth) {
userStore.redirectByRole()
return
}
// 🚫 Rol requerido incorrecto
if (to.meta.role && !userStore.hasRole(to.meta.role)) {
return next('/403')
}
next()
})
export default router

@ -0,0 +1,164 @@
import { defineStore } from 'pinia'
import api from '../axios'
import router from '../router'
export const useUserStore = defineStore('user', {
state: () => ({
user: JSON.parse(localStorage.getItem('user')) || null,
token: localStorage.getItem('token') || null,
loading: false,
error: null
}),
actions: {
async initialize() {
if (this.token) {
try {
await this.fetchUser()
} catch (error) {
this.clearAuth()
}
}
},
async register(payload) {
this.loading = true
this.error = null
try {
const response = await api.post('/register', payload)
if (response.data.success) {
this.user = response.data.user
this.token = response.data.token
localStorage.setItem('token', this.token)
localStorage.setItem('user', JSON.stringify(this.user))
api.defaults.headers.common['Authorization'] = `Bearer ${this.token}`
}
return response.data
} catch (error) {
this.error =
error.response?.data?.errors ||
error.response?.data?.message ||
'Error en el registro'
throw error
} finally {
this.loading = false
}
},
async login(email, password) {
this.loading = true
this.error = null
try {
const response = await api.post('/login', { email, password })
if (response.data.success) {
this.user = response.data.user
this.token = response.data.token
localStorage.setItem('token', this.token)
localStorage.setItem('user', JSON.stringify(this.user))
api.defaults.headers.common['Authorization'] = `Bearer ${this.token}`
// Refresca usuario (roles / permisos)
await this.fetchUser()
// Redirección según rol
this.redirectByRole()
}
return response.data
} catch (error) {
this.error = error.response?.data?.message || 'Error en el login'
throw error
} finally {
this.loading = false
}
},
async fetchUser() {
try {
const response = await api.get('/me')
if (response.data.success) {
this.user = response.data.user
localStorage.setItem('user', JSON.stringify(this.user))
}
} catch (error) {
this.clearAuth()
throw error
}
},
async logout() {
try {
if (this.token) {
await api.post('/logout')
}
} catch (error) {
console.error('Error en logout:', error)
} finally {
this.clearAuth()
router.push('/login')
}
},
clearAuth() {
this.user = null
this.token = null
this.error = null
localStorage.removeItem('token')
localStorage.removeItem('user')
delete api.defaults.headers.common['Authorization']
},
updateUser(updates) {
this.user = { ...this.user, ...updates }
localStorage.setItem('user', JSON.stringify(this.user))
},
redirectByRole() {
if (!this.user || !this.user.roles?.length) {
router.push('/login')
return
}
if (this.user.roles.includes('superadmin')) {
router.push('/superadmin/dashboard')
} else if (this.user.roles.includes('administrador')) {
router.push('/admin/dashboard')
} else {
router.push('/usuario/dashboard') // usuario normal
}
}
},
getters: {
isAuth: (state) => !!state.token && !!state.user,
isSuperAdmin: (state) =>
state.user?.roles?.includes('superadmin') || false,
isAdministrador: (state) =>
state.user?.roles?.includes('administrador') || false,
isUsuario: (state) =>
state.user?.roles?.includes('usuario') || false,
hasRole: (state) => (role) =>
state.user?.roles?.includes(role) || false,
hasPermission: (state) => (permission) =>
state.user?.permissions?.includes(permission) || false,
isLoading: (state) => state.loading,
getError: (state) => state.error
}
})

@ -0,0 +1,79 @@
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
.card {
padding: 2em;
}
#app {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

@ -0,0 +1,3 @@
<template>
<h1>error</h1>
</template>

@ -0,0 +1,438 @@
<template>
<div class="login-container">
<div class="login-card">
<!-- Logo y título -->
<div class="login-header">
<div class="logo">
<!-- <img src="/logo.png" alt="Logo" /> -->
</div>
<h2>{{ isRegister ? 'Crear Cuenta' : 'Iniciar Sesión' }}</h2>
<p class="subtitle">
{{ isRegister
? 'Complete el formulario para registrarse'
: 'Ingrese sus credenciales para continuar'
}}
</p>
</div>
<!-- Formulario -->
<a-form
ref="formRef"
:model="formState"
:rules="rules"
@finish="handleSubmit"
layout="vertical"
class="login-form"
>
<!-- Nombre (solo registro) -->
<a-form-item
v-if="isRegister"
label="Nombre completo"
name="name"
>
<a-input
v-model:value="formState.name"
placeholder="Ingrese su nombre"
size="large"
>
<template #prefix>
<UserOutlined />
</template>
</a-input>
</a-form-item>
<!-- Email -->
<a-form-item label="Correo electrónico" name="email">
<a-input
v-model:value="formState.email"
placeholder="ejemplo@correo.com"
size="large"
>
<template #prefix>
<MailOutlined />
</template>
</a-input>
</a-form-item>
<!-- Contraseña -->
<a-form-item label="Contraseña" name="password">
<a-input-password
v-model:value="formState.password"
placeholder="Ingrese su contraseña"
size="large"
>
<template #prefix>
<LockOutlined />
</template>
</a-input-password>
</a-form-item>
<!-- Confirmar contraseña (solo registro) -->
<a-form-item
v-if="isRegister"
label="Confirmar contraseña"
name="password_confirmation"
>
<a-input-password
v-model:value="formState.password_confirmation"
placeholder="Confirme su contraseña"
size="large"
>
<template #prefix>
<LockOutlined />
</template>
</a-input-password>
</a-form-item>
<!-- Recordarme (solo login) -->
<div v-if="!isRegister" class="remember-forgot">
<a-checkbox v-model:checked="rememberMe">
Recordarme
</a-checkbox>
<a-button type="link" size="small" @click="handleForgotPassword">
¿Olvidó su contraseña?
</a-button>
</div>
<!-- Botón principal -->
<a-form-item>
<a-button
type="primary"
html-type="submit"
:loading="loading"
block
size="large"
class="submit-btn"
>
{{ isRegister ? 'Registrarse' : 'Iniciar Sesión' }}
</a-button>
</a-form-item>
<!-- Cambiar modo -->
<div class="toggle-mode">
<span>
{{ isRegister
? '¿Ya tiene una cuenta?'
: '¿No tiene una cuenta?'
}}
</span>
<a-button type="link" @click="toggleMode">
{{ isRegister ? 'Iniciar sesión' : 'Registrarse' }}
</a-button>
</div>
<!-- Términos (solo registro) -->
<div v-if="isRegister" class="terms">
<p>
Al registrarse, acepta nuestros
<a href="#">Términos</a> y
<a href="#">Política de privacidad</a>
</p>
</div>
</a-form>
</div>
</div>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../store/user'
import { UserOutlined, MailOutlined, LockOutlined } from '@ant-design/icons-vue'
import { notification } from 'ant-design-vue'
const router = useRouter()
const userStore = useUserStore()
const formRef = ref()
const isRegister = ref(false)
const loading = ref(false)
const rememberMe = ref(false)
const formState = reactive({
name: '',
email: '',
password: '',
password_confirmation: ''
})
// Configurar notificación para que aparezca en el centro superior
notification.config({
placement: 'top',
duration: 2,
maxCount: 1,
})
// Función para mostrar toast/notification
const showToast = (type, message, description = '') => {
const config = {
message,
description,
duration: 2, // 2 segundos
placement: 'top',
}
switch (type) {
case 'success':
notification.success(config)
break
case 'error':
notification.error(config)
break
case 'warning':
notification.warning(config)
break
case 'info':
notification.info(config)
break
default:
notification.open(config)
}
}
// Reglas de validación
const rules = {
name: [
{
required: isRegister.value,
message: 'Ingrese su nombre',
trigger: 'blur'
}
],
email: [
{
required: true,
message: 'Ingrese su correo',
trigger: 'blur'
},
{
type: 'email',
message: 'Correo inválido',
trigger: 'blur'
}
],
password: [
{
required: true,
message: 'Ingrese su contraseña',
trigger: 'blur'
},
{
min: 6,
message: 'Mínimo 6 caracteres',
trigger: 'blur'
}
],
password_confirmation: [
{
required: isRegister.value,
message: 'Confirme su contraseña',
trigger: 'blur'
},
({ getFieldValue }) => ({
validator(_, value) {
if (!value || getFieldValue('password') === value) {
return Promise.resolve()
}
return Promise.reject('Las contraseñas no coinciden')
}
})
]
}
// Cambiar entre login/registro
const toggleMode = () => {
isRegister.value = !isRegister.value
formRef.value?.resetFields()
}
// Olvidó contraseña
const handleForgotPassword = () => {
showToast('info', 'Recuperación de contraseña', 'Contacte al administrador del sistema')
}
// Enviar formulario
const handleSubmit = async () => {
try {
loading.value = true
if (isRegister.value) {
await userStore.register(formState)
showToast('success',
'¡Registro exitoso!',
'Tu cuenta ha sido creada correctamente'
)
toggleMode() // Cambiar a login
} else {
await userStore.login(formState.email, formState.password)
showToast('success', '¡Bienvenido!', 'Inicio de sesión exitoso')
}
} catch (error) {
console.error('Error:', error)
// Extraer mensaje de error del backend
let errorMessage = 'Ocurrió un error inesperado'
let errorDetails = ''
if (error.response) {
const status = error.response.status
const data = error.response.data
switch (status) {
case 400:
errorMessage = 'Error en la solicitud'
if (data.errors) {
const firstError = Object.values(data.errors)[0]
errorDetails = Array.isArray(firstError) ? firstError[0] : firstError
} else if (data.message) {
errorDetails = data.message
}
break
case 401:
errorMessage = 'Credenciales incorrectas'
errorDetails = 'Verifique su correo electrónico y contraseña'
break
case 403:
errorMessage = 'Acceso denegado'
errorDetails = 'No tiene permisos para acceder'
break
case 422:
errorMessage = 'Error de validación'
if (data.errors) {
const firstError = Object.values(data.errors)[0]
errorDetails = Array.isArray(firstError) ? firstError[0] : firstError
} else if (data.message) {
errorDetails = data.message
}
break
case 500:
errorMessage = 'Error del servidor'
errorDetails = 'Por favor, intente más tarde'
break
default:
errorMessage = `Error ${status}`
if (data.message) {
errorDetails = data.message
}
}
} else if (error.message) {
errorMessage = 'Error de conexión'
errorDetails = 'Verifique su conexión a internet'
}
// Mostrar error en toast
showToast('error', errorMessage, errorDetails)
} finally {
loading.value = false
}
}
</script>
<style scoped>
.login-container {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
background-color: #f8f9fa;
position: relative;
}
.login-card {
width: 100%;
max-width: 420px;
background: white;
border-radius: 8px;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
padding: 40px;
z-index: 1;
}
.login-header {
text-align: center;
margin-bottom: 32px;
}
.logo {
margin-bottom: 16px;
}
.logo img {
height: 48px;
width: auto;
}
.login-header h2 {
margin: 0 0 8px 0;
color: #262626;
font-weight: 500;
}
.subtitle {
margin: 0;
color: #8c8c8c;
font-size: 14px;
}
.login-form {
margin-bottom: 16px;
}
.remember-forgot {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 24px;
}
.submit-btn {
height: 44px;
font-weight: 500;
margin-top: 8px;
}
.toggle-mode {
text-align: center;
margin-top: 24px;
padding-top: 24px;
border-top: 1px solid #f0f0f0;
color: #595959;
font-size: 14px;
}
.toggle-mode span {
margin-right: 8px;
}
.terms {
margin-top: 24px;
text-align: center;
font-size: 12px;
color: #8c8c8c;
}
.terms a {
color: #1890ff;
text-decoration: none;
}
.terms a:hover {
text-decoration: underline;
}
@media (max-width: 480px) {
.login-card {
padding: 24px;
box-shadow: none;
border: 1px solid #f0f0f0;
}
.remember-forgot {
flex-direction: column;
align-items: flex-start;
gap: 12px;
}
}
</style>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -0,0 +1,16 @@
<template>
<div style="padding: 24px;">
<a-result
status="403"
title="403"
sub-title="superadmin"
>
</a-result>
</div>
</template>
<script setup>
import { useUserStore } from '../../store/user'
</script>

@ -0,0 +1,17 @@
<!-- views/Dashboard.vue -->
<template>
<div style="padding: 24px;">
<a-result
status="403"
title="403"
sub-title="usuario"
>
</a-result>
</div>
</template>
<script setup>
import { useUserStore } from '../../store/user'
</script>

@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vite.dev/config/
export default defineConfig({
plugins: [vue()],
})
Loading…
Cancel
Save