Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,8 @@ VITE_APP_NAME="${APP_NAME}"


ACTIVITY_LOGGER_ENABLED=true

SASHA_CLIENT_ID=""
SASHA_CLIENT_SECRET=""
SASHA_REDIRECT_URL=""
SASHA_URL=""
106 changes: 106 additions & 0 deletions app/Http/Controllers/SashaAuthController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<?php

namespace App\Http\Controllers;

use App\Enums\UserRol;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Spatie\Activitylog\Models\Activity;

class SashaAuthController extends Controller
{
public function redirectToSasha(string $guard, Request $request)
{
session(['guard' => $guard]);
$request->session()->put('state', $state = Str::random(40));
$scopes = [];

switch ($guard) {
case 'student':
$scopes = ["students:read", "teachers:read", "user", "email"];
break;
case 'teacher':
$scopes = ["students:read", "teachers:read", "user", "email"];
break;
case 'developer':
$scopes = ["students:read", "teachers:read", "user", "email"];
break;
default:
$scopes = ["students:read", "teachers:read", "user", "email"];
break;
}

// This is the query
$q = [
'client_id' => config('services.sasha.client_id'),
'redirect_uri' => config('services.sasha.redirect'),
'response_type' => 'code',
'scope' => implode(" ", $scopes),
'state' => $state,
// Custom HTTP
'guard' => $guard
];

// HTTP BUILD WITH QUERY
$query = http_build_query($q);


// Notify
Log::info("New user is attempt login in SASHA:");
Log::info($q);

return redirect(config('services.sasha.main_url') . '/oauth/authorize?' . $query);
}

public function handleCallback(Request $request)
{
$response = Http::asForm()->post(config('services.sasha.main_url') . '/oauth/token', [
'grant_type' => 'authorization_code',
'client_id' => config('services.sasha.client_id'),
'client_secret' => config('services.sasha.client_secret'),
'redirect_uri' => config('services.sasha.redirect'),
'code' => $request->code,
]);

if (!$response->successful()) {
return redirect('/')->withErrors('No se pudo autenticar con SASHA.');
}

$accessToken = $response->json('access_token');
session([
'sasha_access_token' => $accessToken,
]);

$userResponse = Http::withToken($accessToken)->get(config('services.sasha.main_url') . '/api/me')->json();
$sashaUser = $userResponse['data'];

$user = User::updateOrCreate([
'id' => $sashaUser['uuid'],
], [
'id' => $sashaUser['uuid'],
'name' => $sashaUser["name"],
'last_name' => $sashaUser["last_name"],
'email' => $sashaUser['email'],
'grade' => $sashaUser['grade'],
'fingerprint' => $sashaUser['fingerprint'],
'document' => $sashaUser['document'],
'document_type' => $sashaUser['document_type'],
'last_login_ip' => $sashaUser["last_login_ip"],
'last_login_at' => $sashaUser['last_login_at'],
'password' => Hash::make("somosoeistas"),
'rol' => UserRol::from($sashaUser["type"] ?? 'student'),
]);

Log::info("Se creo o actualizo un usuario");
Activity::all();

Auth::login($user);

return redirect('/');
}
}
14 changes: 13 additions & 1 deletion app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;

use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
Expand All @@ -13,17 +15,27 @@
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable, TwoFactorAuthenticatable;
use HasFactory, Notifiable, TwoFactorAuthenticatable, HasUuids;

/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'id',
'name',
'last_name',
'email',
'grade',
'fingerprint',
'uuid',
'document',
'document_type',
'last_login_ip',
'last_login_at',
'password',
'rol'
];

/**
Expand Down
7 changes: 7 additions & 0 deletions config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,11 @@
],
],

'sasha' => [
'client_id' => env('SASHA_CLIENT_ID'),
'client_secret' => env('SASHA_CLIENT_SECRET'),
'redirect' => env('SASHA_REDIRECT_URL'),
'main_url' => env('SASHA_URL', 'http://localhost:3500'),
],

];
2 changes: 1 addition & 1 deletion database/factories/UserFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,13 @@ public function definition(): array
{
return [
'name' => fake()->name(),
'last_name' => fake()->lastName(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
'grade' => '1104',
'fingerprint' => fake()->sha256(),
'UUID' => fake()->uuid(),
'document' => fake()->numberBetween(1000000000, 1999999999),
'document_type' => 'T.I',
'profile_photo_path' => null,
Expand Down
3 changes: 2 additions & 1 deletion database/migrations/0001_01_01_000000_create_users_table.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->uuid('id')->primary();
$table->string('name');
$table->string("last_name");
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public function up(): void
Schema::create('records', function (Blueprint $table) {
$table->id();

$table->unsignedBigInteger('user_id');
$table->uuid('user_id');
$table->dateTime("date");
$table->enum('record_type', RecordType::cases());
$table->unsignedBigInteger("journey_id");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public function up(): void
{
Schema::create('newnesses', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger("user_id");
$table->uuid("user_id");
$table->string("subject");
$table->text("text");
$table->string("slug");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ public function up(): void
$table->enum("rol", UserRol::cases())->nullable();
$table->string("grade")->nullable();
$table->string("fingerprint")->nullable();
$table->uuid("UUID")->nullable(); // Indentificadores universales
$table->integer("document")->unique()->nullable();
$table->string("document_type")->nullable();

Expand Down
15 changes: 11 additions & 4 deletions routes/auth.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

use App\Http\Controllers\Auth\VerifyEmailController;
use App\Http\Controllers\SashaAuthController;
use App\Livewire\Actions\Logout;
use App\Livewire\Auth\ForgotPassword;
use App\Livewire\Auth\Login;
Expand All @@ -10,10 +11,16 @@
use Illuminate\Support\Facades\Route;

Route::middleware('guest')->group(function () {
Route::get('login', Login::class)->name('login');
Route::get('register', Register::class)->name('register');
Route::get('forgot-password', ForgotPassword::class)->name('password.request');
Route::get('reset-password/{token}', ResetPassword::class)->name('password.reset');
Route::get(
'login/{guard}',
[SashaAuthController::class, 'redirectToSasha']
)->name('login');

Route::get('/auth/callback', [SashaAuthController::class, 'handleCallback']);

// Route::get('register', Register::class)->name('register');
// Route::get('forgot-password', ForgotPassword::class)->name('password.request');
// Route::get('reset-password/{token}', ResetPassword::class)->name('password.reset');
});

Route::middleware('auth')->group(function () {
Expand Down
Loading