Skip to content

Commit

Permalink
Merge pull request #66 from OrifInformatique:update_azure_login
Browse files Browse the repository at this point in the history
Update azure login
  • Loading branch information
DidierViret committed Jun 28, 2024
2 parents b960636 + 738c695 commit 0cbfad9
Show file tree
Hide file tree
Showing 5 changed files with 169 additions and 45 deletions.
10 changes: 8 additions & 2 deletions orif/user/Config/Routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,16 @@
*/
use User\Controllers\Auth;
use User\Controllers\Profile;

$routes->add('user/auth/(:any)','\User\Controllers\Auth::$1');
$routes->add('user/admin/(:any)','\User\Controllers\Admin::$1');
$routes->add('user/auth/azure_login','Auth::azure_login',
['as' => 'azure_login']);
$routes->add('user/auth/azure_login','Auth::azure_login', ['as' => 'azure_login']);
$routes->add('user/profile/update','\User\Controllers\Profile::$1');
$routes->add('user/profile/(:any)','\User\Controllers\Profile::$1');

// Specific routes for unit tests
$routes->add('user/auth/verify_verification_code','Auth::verify_verification_code',
['as' => 'verify_verification_code']);
$routes->add('user/auth/handle_mail_form','Auth::handle_mail_form',
['as' => 'handle_mail_form']);
?>
47 changes: 21 additions & 26 deletions orif/user/Controllers/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,12 +157,10 @@ public function azure_login() {
$url .= "&approval_prompt=auto";
$url .= "&client_id=" . $client_id;
$url .= "&redirect_uri=" . urlencode($redirect_uri);


// Redirection to Microsoft's login page
return $this->response->redirect($url)->send();

// header("Location:" . $url); // Redirection to Microsoft's login page
// exit;

// Second stage of the authentication process
} elseif (isset($_GET["error"])) {

Expand Down Expand Up @@ -194,9 +192,8 @@ public function azure_login() {
} catch (\Exception $e) {
$data['title'] = 'Azure error';
$data['Exception'] = $e;
d('test debug Exception');

return $this->display_view('\User\errors\401error', $data);
exit();
};

if ($json === false){
Expand Down Expand Up @@ -303,9 +300,9 @@ public function prepare_mail_form(): string {
/**
* Prepares the mail form and checks if the Azure mail already registered in the DB
*
* @return ???
* @return html Display the form view to verify the expiration code.
*/
public function handle_mail_form() {
public function handle_mail_form(): string {

// Get user email from mail form
$_SESSION['form_email'] = $this->request->getPost('user_email');
Expand All @@ -325,11 +322,12 @@ public function handle_mail_form() {
}

/**
* Generates, starts the expiration time and sends the verification code via SMTP (mail) to the user
* Generates verification code, starts the expiration time and sends the verification code
* via SMTP (mail) to the user.
*
* @return ???
* @return html Display the form view to verify the expiration code.
*/
public function generate_send_verification_code($form_email) { // generate code and send mail
public function generate_send_verification_code($form_email): string { // generate code and send mail

// Random code generator
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
Expand Down Expand Up @@ -383,13 +381,17 @@ public function generate_send_verification_code($form_email) { // generate code
'timer_limit' => $_SESSION['timer_limit'],
'timer_end' => $_SESSION['timer_end'],
);

// echo doesn't work with unit tests

return $this->display_view('\User\auth\verification_code_form', $data);
}

public function verify_verification_code() {
// If verification code is not set, generate one and send it to user
if (!isset($_SESSION['verification_code']) || empty($_SESSION['verification_code'])){
return $this->generate_send_verification_code($_SESSION['form_email']);
}

// Get the verification code posted by the user
$user_verification_code = $this->request->getPost('user_verification_code');

if ($user_verification_code == $_SESSION['verification_code'] && time() < $_SESSION['timer_end']){
Expand All @@ -409,17 +411,11 @@ public function verify_verification_code() {
// insert this new user
$this->user_model->insert($new_user);

// Force user to change password on next 'normal' login

$_SESSION['logged_in'] = (bool)true;

// TODO: Afficher formulaire creation user avec infos pré-remplies (save_user)
// TODO : Route differente, remplacer after_login_redirect

} else {

// User already in DB => Update azure_mail in DB

$ci_user = $this->user_model->where('email', $_SESSION['form_email'])->first();

// Verification code matches
Expand All @@ -432,8 +428,11 @@ public function verify_verification_code() {
];

$this->user_model->update($ci_user['id'], $data);

$_SESSION['logged_in'] = (bool)true;

// Send the user to the redirection URL
return redirect()->to($_SESSION['after_login_redirect']);
}

} else { // Code is not valid for any reason (false and/or expired)
Expand All @@ -442,6 +441,7 @@ public function verify_verification_code() {

if ($_SESSION['verification_attempts'] <= 0) {
// No more attempts, keep default user access, reset some session variables and redirect to after_login_redirect
return $this->reset_session();
} else {
$output = array(
'title' => lang('user_lang.title_validation_code'),
Expand All @@ -457,10 +457,6 @@ public function verify_verification_code() {
);
}
}

// todo redirect to reset sessions method
return $this->reset_session();

}

public function register_user() {
Expand Down Expand Up @@ -512,11 +508,10 @@ public function reset_session() {
$_SESSION['timer_end'] = null;
$_SESSION['timer_limit'] = null;
$_SESSION['test'] = null;
$_SESSION['reset_password'] = null;
$_SESSION['reset_password'] = null;

// Send the user to the redirection URL
return redirect()->to($_SESSION['after_login_redirect']);
// return redirect()->to('/user/profile/test');
}

function errorhandler($data) {
Expand Down
9 changes: 6 additions & 3 deletions orif/user/Controllers/Profile.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,12 @@ public function initController(RequestInterface $request,
public function change_password(): Response|string|RedirectResponse {

// Get user from DB, redirect if user doesn't exist
$user = $this->user_model->withDeleted()->find($_SESSION['user_id']);
if (is_null($user)) return redirect()->to('/user/auth/login');
if(isset($_SESSION['user_id'])) {
$user = $this->user_model->withDeleted()->find($_SESSION['user_id']);
if (is_null($user)) return redirect()->to('/user/auth/login');
} else {
return redirect()->to('/user/auth/login');
}

// Empty errors message in output
$output['errors'] = [];
Expand Down Expand Up @@ -91,7 +95,6 @@ public function change_password(): Response|string|RedirectResponse {
$_SESSION['reset_password'] = $user['reset_password'];
$output['title'] = lang('user_lang.page_my_password_change');
return $this->display_view('\User\auth\change_password', $output);

}
}
?>
104 changes: 104 additions & 0 deletions tests/orif/user/Controllers/AuthHttpTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
<?php

namespace User\Controllers;

use CodeIgniter\Test\DatabaseTestTrait;
use CodeIgniter\Test\FeatureTestTrait;
use CodeIgniter\Test\CIUnitTestCase;

use User\Models\User_model;

class AuthHttpTest extends CIUnitTestCase
{
use DatabaseTestTrait;
use FeatureTestTrait;

protected $migrate = true;
protected $migrateOnce = false;
protected $refresh = true;
protected $namespace = null;

protected function setUp(): void
{
parent::setUp();
}

protected function tearDown(): void
{
parent::tearDown();
}

private function test_azure_login_begin(): void
{
$url = substr(url_to('Auth::azure_login_begin'), strlen(base_url()));
$result = $this->call('get', $url);
$redirectUrl = $result->getRedirectUrl();
$html = file_get_contents($redirectUrl, false);
dd($html);
}

public function test_azure_mail_with_correct_code_new_user(): void
{
$firstName = 'Firstname';
$lastName = 'Lastname';
$userName = "$firstName.$lastName";
$_POST['user_verification_code'] = 'correct';
$_SESSION['verification_code'] = 'correct';
$_SESSION['verification_attempts'] = 3;
$_SESSION['after_login_redirect'] = base_url();
$_SESSION['new_user'] = true;
$_SESSION['azure_mail'] = "$userName@azurefake.fake";
$_SESSION['form_email'] = "[email protected]";
$_SESSION['timer_end'] = time() + 300;
$url = substr(url_to('verify_verification_code'), strlen(site_url()));
$result = $this->withSession()->call('get', $url);
$userModel = model(User_model::class);
$name = $userModel->select('username')->where('username=', $userName)
->findAll()[0]['username'];
$this->assertEquals($userName, $name);
}

public function test_azure_mail_existed_user_variable_created(): void
{
$userId = 2;
$noAzureMail = '[email protected]';
$userModel = model(User_model::class);
$userModel->update($userId, ['email' => $noAzureMail]);

$_SESSION['after_login_redirect'] = base_url();
$_POST['user_email'] = $noAzureMail;

$azureMail = '[email protected]';
$_SESSION['azure_mail'] = $azureMail;

$url = substr(url_to('handle_mail_form'), strlen(site_url()));
$result = $this->withSession()->post($url);

$result->assertSee(lang('user_lang.user_validation_code'));
}

public function test_azure_mail_with_correct_code_existing_user(): void
{
$userId = 2;
$noAzureMail = '[email protected]';
$userModel = model(User_model::class);
$userModel->update($userId, ['email' => $noAzureMail]);

$_POST['user_verification_code'] = 'correct';
$_SESSION['verification_code'] = 'correct';
$_SESSION['verification_attempts'] = 3;
$_SESSION['after_login_redirect'] = base_url();
$_SESSION['new_user'] = false;
$_SESSION['form_email'] = $noAzureMail;
$_SESSION['timer_end'] = time() + 300;
$azureMail = '[email protected]';
$_SESSION['azure_mail'] = $azureMail;

$url = substr(url_to('verify_verification_code'), strlen(site_url()));
$result = $this->withSession()->call('get', $url);

$azureMailInDb = $userModel->select('azure_mail')
->find($userId)['azure_mail'];
$this->assertEquals($azureMail, $azureMailInDb);
}
}
44 changes: 30 additions & 14 deletions tests/orif/user/Controllers/AuthTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -608,9 +608,13 @@ public function test_azure_mail_without_code(): void
{
$_POST['user_verification_code'] = null;
$_SESSION['verification_code'] = null;
$form_email = '[email protected]';
$result = $this->controller(Auth::class)
->execute('generate_send_verification_code', $form_email);
$_SESSION['verification_attempts'] = 3;
$_SESSION['timer_end'] = time() + 300;
$_SESSION['new_user'] = true;
$_SESSION['azure_mail'] = "[email protected]";
$_SESSION['form_email'] = "[email protected]";
$_SESSION['after_login_redirect'] = base_url();
$result = $this->controller(Auth::class)->execute('verify_verification_code');
$result->assertSee(lang('user_lang.user_validation_code'));
}

Expand All @@ -624,11 +628,13 @@ public function test_azure_mail_with_fake_code(): void
{
$_POST['user_verification_code'] = 'fake1';
$_SESSION['verification_code'] = 'fake2';
$_SESSION['verification_attempts'] = 3; // 3 attempts left
$_SESSION['timer_end'] = time() + 300; // force timer_end to be greater than time()
$form_email = '[email protected]';
$result = $this->controller(Auth::class)
->execute('verify_verification_code', $form_email);
$_SESSION['verification_attempts'] = 3;
$_SESSION['timer_end'] = time() + 300;
$_SESSION['new_user'] = true;
$_SESSION['azure_mail'] = "[email protected]";
$_SESSION['form_email'] = "[email protected]";
$_SESSION['after_login_redirect'] = base_url();
$result = $this->controller(Auth::class)->execute('verify_verification_code');
$result->assertSee(lang('user_lang.msg_err_validation_code'));
}

Expand All @@ -637,11 +643,12 @@ public function test_azure_mail_with_fake_code_all_attemps_done(): void
$_POST['user_verification_code'] = 'fake1';
$_SESSION['verification_code'] = 'fake2';
$_SESSION['verification_attempts'] = 1;
$_SESSION['timer_end'] = time() - 300; // force timer_end to be expired
$_SESSION['timer_end'] = time() + 300;
$_SESSION['new_user'] = true;
$_SESSION['azure_mail'] = "[email protected]";
$_SESSION['form_email'] = "[email protected]";
$_SESSION['after_login_redirect'] = base_url();
$form_email = '[email protected]';
$result = $this->controller(Auth::class)
->execute('verify_verification_code', $form_email);
$result = $this->controller(Auth::class)->execute('verify_verification_code');
$this->assert_redirect($result);
}

Expand Down Expand Up @@ -711,15 +718,24 @@ public function test_azure_mail_with_correct_code_existing_user(): void
$_SESSION['timer_end'] = time() + 300; // force timer_end to be greater than time()
$_SESSION['after_login_redirect'] = base_url();
$_SESSION['new_user'] = false;
$_SESSION['azure_mail'] = "[email protected]";
$_SESSION['form_email'] = "[email protected]";
$_SESSION['azure_mail'] = "[email protected]";
$_SESSION['form_email'] = "[email protected]";
$redirect_url = $_SESSION['after_login_redirect'];

$result = $this->controller(Auth::class)
->execute('verify_verification_code');

/* Check that user's azure_mail has been updated in the DB */
$azureMailInDb = $userModel->select('azure_mail')
->find($userId)['azure_mail'];
$this->assertEquals($_SESSION['azure_mail'], $azureMailInDb);

/* Check that the user is logged in */
$result->assertSessionHas('logged_in', true);

/* Check if user has been redirected correctly */
$result->assertRedirect();
$result->assertRedirectTo($redirect_url);
}

/**
Expand Down

0 comments on commit 0cbfad9

Please sign in to comment.