Skip to content

Commit

Permalink
further refactoring of login process to separate out concerns and met…
Browse files Browse the repository at this point in the history
…hods
  • Loading branch information
fredbradley committed Apr 11, 2024
1 parent 5f3f030 commit 102eecb
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 66 deletions.
28 changes: 9 additions & 19 deletions app/Domains/SelfReflection/Http/LoginController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Validation\ValidationException;

class LoginController
{
Expand Down Expand Up @@ -43,32 +44,21 @@ public function callbackSuccess(Request $request): RedirectResponse
'ffauth_secret' => 'string|required',
]);

$secret = $request->get('ffauth_secret');

return $this->getUserData($secret);

return redirect()->route('selfreflection.home');
}

/**
* @throws RequestException
*/
public function getUserData(string $secret): RedirectResponse
{
$response = Http::get($this->url.'/login/api/sso', [
'ffauth_secret' => $secret,
$fireflyReponse = Http::get($this->url.'/login/api/sso', [
'ffauth_secret' => $request->get('ffauth_secret'),
'ffauth_device_id' => config('services.firefly.selfreflections.app'),
]);

return $this->findOrCreateUserAndLogin($response->throw()->body(), request());

return auth()->user();
return $this->findOrCreateUserAndLogin($fireflyReponse, $request);
}

public function callbackFailure(): RedirectResponse
/**
* @throws ValidationException
*/
public function callbackFailure(): \Symfony\Component\HttpFoundation\Response
{
session()->flash('alert-danger', 'There was an issue with the Firefly authentication. Please try again.');

return redirect()->route('selfreflection.login');
return $this->sendFailedLoginResponse(request());
}
}
78 changes: 48 additions & 30 deletions app/Http/Controllers/Auth/FireflyAuth.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
namespace App\Http\Controllers\Auth;

use App\Models\User;
use Exception;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\Client\Response;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
Expand All @@ -12,18 +16,6 @@ trait FireflyAuth
{
use AuthenticatesUsers;

private function getIdentifierItems(string $identifier): array
{
$parts = explode(':', $identifier);
$isamsId = end($parts);
$db = str_replace('iSAMS', '', $parts[3]);

return [
'table' => $db,
'id' => (int) $isamsId,
];
}

public function logout(Request $request): RedirectResponse
{
auth()->logout();
Expand All @@ -35,6 +27,29 @@ public function logout(Request $request): RedirectResponse
return redirect('/');
}

/**
* @throws RequestException
* @throws Exception
*/
private function findOrCreateUserAndLogin(Response $fireflyReponse, Request $request): RedirectResponse
{
$xmlString = $fireflyReponse->throw()->body();

$obj = $this->convertXmlToObject($xmlString);

$user = $this->getUserObject($obj->user->{'@attributes'});

// log them in
$this->guard()->login($user);
// Update db with login time
auth()->user()->update(['updated_at' => now()]);
// Fake request data (for the sendLoginResponse method work)
$request->merge(['email' => $user->email, 'username' => $user->email, 'password' => 'cranleigh12']);
session()->flash('alert-success', 'You have logged in as: ' . auth()->user()->name);

return $this->sendLoginResponse($request);
}

private function convertXmlToObject(string $xmlString): object
{
/**
Expand All @@ -47,29 +62,32 @@ private function convertXmlToObject(string $xmlString): object
return json_decode($json);
}

private function findOrCreateUserAndLogin(string $xmlString, Request $request): RedirectResponse
/**
* @throws Exception
*/
private function getUserObject(object $userData): User
{
$obj = $this->convertXmlToObject($xmlString);

$user = $obj->user->{'@attributes'};
$existingUser = User::query()->where('email', $user->email)->first();

$existingUser = User::query()->where('email', '=', $userData->email)->first();
if (is_null($existingUser)) {
// create a new user
$ssoData = $this->getIdentifierItems($user->identifier);
$existingUser = User::create($user->email, $ssoData['table'], $user->name, $user->username, $ssoData['id']);
$ssoData = $this->getIdentifierItems($userData->identifier);
$existingUser = User::create($userData->email, $ssoData['table'], $userData->name, $userData->username, $ssoData['id']);
}
if ($existingUser instanceof User) {
return $existingUser;
}
throw new Exception('User not found');
}

// log them in
$this->guard()->login($existingUser);
// Update db with login time
auth()->user()->update(['updated_at' => now()]);
// Fake request data
$request->merge(['email' => $user->email, 'username' => $user->email, 'password' => 'cranleigh12']);
session()->flash('alert-success', 'You have logged in as: '.auth()->user()->name);

return $this->sendLoginResponse($request);
private function getIdentifierItems(string $identifier): array
{
$parts = explode(':', $identifier);
$isamsId = end($parts);
$db = str_replace('iSAMS', '', $parts[3]);

// Let them know they've logged in
return [
'table' => $db,
'id' => (int)$isamsId,
];
}
}
32 changes: 15 additions & 17 deletions app/Http/Controllers/Auth/LoginController.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,31 +50,29 @@ public function showLoginForm(): View|RedirectResponse
*/
public function callbackSuccess(Request $request, string $school): RedirectResponse
{
if ($request->has('ffauth_secret')) {
$request->validate([
'ffauth_secret' => 'string|required',
]);

try {
$subdomain = match ($school) {
'senior' => 'cranleigh',
'prep' => 'cranprep'
};
$output = Http::get('https://'.$subdomain.'.fireflycloud.net/login/api/sso', [
$fireflyReponse = Http::get('https://' . $subdomain . '.fireflycloud.net/login/api/sso', [
'ffauth_device_id' => 'raiseaconcern-cranleigh',
'ffauth_secret' => $request->get('ffauth_secret'),
])->throw()->body();

return $this->findOrCreateUserAndLogin($output, $request);

return $this->sendLoginResponse($request);
return redirect('/submit');
}
]);

$debugarray = [
'school' => $school,
'request' => $request,
];
if (isset($user)) {
$debugarray['user'] = $user;
return $this->findOrCreateUserAndLogin($fireflyReponse, $request);
} catch (Exception $exception) {
$debugArr = [
'school' => $school,
'request' => $request,
];
Log::error($exception->getMessage(), $debugArr);
throw new Exception('Firefly Authentication Not Found', 400, $debugArr);
}
throw new Exception('Firefly Authentication Not Found', 400, $debugarray);
}

public function loginRedirect(string $school): RedirectResponse
Expand All @@ -95,6 +93,6 @@ public function loginRedirect(string $school): RedirectResponse

$url = route('raiseaconcern.firefly-success', $school);

return redirect('https://'.$subdomain.'.fireflycloud.net/login/api/webgettoken?app=raiseaconcern-cranleigh&successURL='.$url);
return redirect('https://' . $subdomain . '.fireflycloud.net/login/api/webgettoken?app=raiseaconcern-cranleigh&successURL=' . $url);
}
}

0 comments on commit 102eecb

Please sign in to comment.