donation/app/Controllers/Authentication.php
2023-12-14 17:38:07 +05:30

336 lines
15 KiB
PHP

<?php
namespace App\Controllers;
use App\Models\AuthenticationModel;
## Authentication Controllers only for Login,Logout,forgotpassword,confirmationpassword,resetpassword,session,cookie,lock-screen Modules
class Authentication extends BaseController
{
## Load Login Page
public function index()
{
// Retrieve flashed session data
$successMessage = session()->getFlashdata('success');
$validationErrors = session()->getFlashdata('error');
// Load and display the form view with the above data
// Here, we'll use the default View class for demonstration purposes
$alerts = [
'successMessage' => $successMessage,
'validationErrors' => $validationErrors,
];
return view('auth_login', $alerts);
}
## Authenticate the users and Redirect to Dashboard
public function authenticate()
{
$auth_model = new AuthenticationModel();
$rules = [
'username' => 'required',
'password' => 'required',
];
if ($this->validate($rules)) {
$username = $this->request->getPost('username');
$password = $this->request->getPost('password');
$user = $auth_model->where(['email'=>$username,'isactive'=>1])->first();
// $this->logger->info("Authenticate: Function Called.");
if (is_null($user)) {
$this->logger->error('User does not exist');
return redirect()->back()->withInput()->with('error', 'User does not exist');
}
$pwd_verify = password_verify((string)$password, $user['password']);
if (!$pwd_verify) {
$this->logger->error('Invalid Password');
return redirect()->back()->withInput()->with('error', 'Invalid Password.');
}
// You can implement your authentication logic here
// For example, check against a database, validate credentials, etc.
if ($username === $user['email'] && $pwd_verify) {
// Redirect to a dashboard or other protected area
helper('session');
set_logged_user_id($user['user_id']);
set_logged_name($user['first_name'] . " " . $user['last_name']);
set_user_role($user['role']);
set_business_id($user['business_id']);
return redirect()->to('dashboard');
// $cookie = \Config\Services::cookie();
// $cookie->setCookie('remember_username', 'Sri Harsha', 3600); // Cookie expires in 1 hour
} else {
// Invalid credentials, display error message
// return redirect()->back()->with('error', 'Invalid username or password.');
$this->logger->error('Invalid username or password.');
return redirect()->back()->withInput()->with('error', 'Invalid username or password.');
}
} else {
// Validation failed, display errors
// return redirect()->back()->withInput()->with('validation', $validation);
$this->logger->error('Username or password Required.');
return redirect()->back()->withInput()->with('error', 'Username or password Required.');
}
}
## Load Forgot password Confirmation Alert
public function auth_confirm_mail()
{
// Get the email address from the request
$mail_id = $this->request->getGet('email');
$url_domain = base_url();
// Validate the email address
$validation_rules = [
'email' => 'required|valid_email',
];
if (!$this->validate($validation_rules)) {
$this->logger->error('enter correct mail to reset your Password');
return redirect()->back()->withInput()->with('error', 'Enter correct E-mail to reset your password');
}
// Check if the email exists in the database
$auth_model = new AuthenticationModel();
// $user = $auth_model->where('email', $mail_id)->first();
$where = ['email' => $mail_id, 'isactive' => 1];
$user = $auth_model->where($where)->first();
if (!$user) {
$this->logger->error('There is no user enteries against given mail');
return redirect()->back()->withInput()->with('error', 'There is no user enteries against given mail');
} else {
$data['mail_id'] = $mail_id;
// Generate a unique token for password reset
$token = bin2hex(random_bytes(32));
$content = "Click the link below to reset your password : " . $url_domain . "auth_reset_password?email=" . $mail_id . "&token=" . $token;
$email = \Config\Services::email();
// $recipient = 'venbalap08@gmail.com';
$recipient = $mail_id;
// Compose the email
$email->setTo($recipient);
$email->setFrom('no-reply@tripapprovaltool.com', 'BB-VBP');
$email->setSubject('Email Notification');
// $email->setMessage('This is a notification email from CodeIgniter.');
$email->setMessage($content);
$update_token['reset_link'] = $token;
$auth_model->update($user['user_id'], $update_token);
$data['link'] = $url_domain . "auth_reset_password?email=" . $mail_id . "&token=" . $token;
// Retrieve flashed session data
$successMessage = session()->getFlashdata('success');
$validationErrors = session()->getFlashdata('error');
// Load and display the form view with the above data
// Here, we'll use the default View class for demonstration purposes
$data['successMessage'] = $successMessage;
$data['validationErrors'] = $validationErrors;
// return view('auth_confirm_mail', $data);
if ($email->send()) {
// Email sent successfully
return view('auth_confirm_mail', $data);
} else {
$this->logger->error('Email Not Sended,Try Again');
return redirect()->back()->withInput()->with('error', 'Email Not Sended,Try Again');
}
}
}
## Load Reset password Page
public function auth_reset_password()
{
$email = $this->request->getGet('email');
$token = $this->request->getGet('token');
$auth_model = new AuthenticationModel();
$where = ['email' => $email, 'reset_link' => $token, 'isactive' => 1];
$user = $auth_model->where($where)->first();
if (!$user) {
$this->logger->error('Invaild link for this Email');
return redirect()->back()->withInput()->with('error', 'Invaild link for this Email');
//return back page is auth_login
} else {
$update_token['reset_link'] = NULL;
$auth_model->update($user['user_id'], $update_token);
$data['email'] = $email;
// Retrieve flashed session data
$successMessage = session()->getFlashdata('success');
$validationErrors = session()->getFlashdata('error');
// Load and display the form view with the above data
// Here, we'll use the default View class for demonstration purposes
$data['successMessage'] = $successMessage;
$data['validationErrors'] = $validationErrors;
return view('auth_reset_password', $data);
}
}
## Save Resetted password. and Redirect to login
public function auth_reset_password_save()
{
$auth_model = new AuthenticationModel();
$rules = [
'password1' => 'required',
'password2' => 'required',
];
if ($this->validate($rules)) {
// echo "try";die;
$email = $this->request->getVar('email');
$password = $this->request->getVar('password1');
$confirmation = $this->request->getVar('password2');
$hash_password = password_hash($password, PASSWORD_DEFAULT);
// try {
// code for password confirmation
if ($password === $confirmation) {
$auth_model = new AuthenticationModel();
$user_details = $auth_model->where(['email' => $email, 'isactive' => 1])->first();
if ($user_details) {
$update_user_details = ['email' => $email, 'password' => $hash_password];
$auth_model->update($user_details['user_id'], $update_user_details);
}
// Retrieve flashed session data
$successMessage = session()->getFlashdata('success');
$validationErrors = session()->getFlashdata('error');
// Load and display the form view with the above data
// Here, we'll use the default View class for demonstration purposes
$data['successMessage'] = $successMessage;
$data['validationErrors'] = $validationErrors;
return view('auth_login', $data);
} else {
// Password confirmation failed
$this->logger->error('Password confirmation failed');
return redirect()->back()->withInput()->with('error', 'Password confirmation failed');
}
// } catch (\Exception $e) {
// $error = "Exception Errno returned" . $e->getCode() . " <br/>";
// $error_msg = $e->getMessage();
// $this->logger->error($error . '(' . $error_msg . ')');
// return redirect()->back()->withInput()->with('error', $error . '(' . $error_msg . ')');
// }
} else {
// Validation failed, display errors
$this->logger->error('Password And Confirmation Password are Required.');
return redirect()->back()->withInput()->with('error', 'Password And Confirmation Password are Required.');
}
}
## Logout With destory Session Details
public function logout()
{
// Clear session and cookies
$session = session();
// Regenerate the session ID
$session->regenerate();
// Clear session data and perform logout logic
$session->destroy();
// $cookie = \Config\Services::cookie();
// $cookie->delete('ci_session');
// $remembered_username = $cookie->getCookie('remember_username');
// $cookie->delete('remember_username');
// Redirect to a logout confirmation page or login page
// return redirect()->to('/login'); // Replace with your login route
$this->response->setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0');
$this->response->setHeader('Pragma', 'no-cache');
$this->response->setHeader('Expires', 'Fri, 01 Jan 1990 00:00:00 GMT');
$data = [];
return redirect()->route('login');
// return view('auth_logout', $data);
}
## Lock Screen - holded
public function lockscreen()
{
// Load the session library
helper('session');
$session_uid = get_logged_user_id();
$session_uname = get_logged_name();
$auth_model = new AuthenticationModel();
$details = $auth_model->getheringDetailsForHeader($session_uid);
$data['loggedin_person'] = $session_uname;
$data['loggedin_person_role'] = $details[0]['role'];
$data['favicon'] = !empty($details[0]['favicon']) && file_exists(FCPATH."public/uploads/".$details[0]['favicon']) ? base_url("public/uploads/".$details[0]['favicon']) : base_url("public/uploads/default.ico");
$data['profile_picture'] = !empty($details[0]['profile_picture']) && file_exists(FCPATH."public/uploads/".$details[0]['profile_picture']) ? base_url("public/uploads/" . $details[0]['profile_picture']) : base_url("public/assets/images/users/avatar-9.jpg");
$data['company_logo_small'] = !empty($details[0]['company_logo_small']) && file_exists(FCPATH."public/uploads/".$details[0]['company_logo_small']) ? base_url("public/uploads/" . $details[0]['company_logo_small']) : base_url("public/uploads/default_logo.png");
$data['company_logo_large'] = !empty($details[0]['company_logo_large']) && file_exists(FCPATH."public/uploads/".$details[0]['company_logo_large']) ? base_url("public/uploads/" . $details[0]['company_logo_large']) : base_url("public/uploads/default.png");
$successMessage = session()->getFlashdata('success');
$validationErrors = session()->getFlashdata('error');
// Load and display the form view with the above data
// Here, we'll use the default View class for demonstration purposes
// Check if the session is locked
if (get_session_locked()) {
$data['successMessage'] = $successMessage;
$data['validationErrors'] = $validationErrors;
// Load the lock screen view
return view('auth_lock_screen', $data);
} else {
// Redirect the user to their previous page or dashboard
return redirect()->to('dashboard'); // Replace with appropriate URL
}
}
## Lock Screen
public function lock()
{
// Load the session library
helper('session');
// Set the session_locked flag
set_session_locked(true);
// Redirect the user to the lock screen
return redirect()->to('lockscreen'); // Replace with your lock screen URL
}
## Unlock Screen - holded
public function unlock()
{
// Load the session library
helper('session');
// Check password logic
$password = $this->request->getVar('password');
if ($this->checkPassword($password)) {
// Unlock the session
remove_session_locked();
return redirect()->to('dashboard'); // Redirect to dashboard
} else {
// Incorrect password, show error
return redirect()->back()->withInput()->with('error', 'Incorrect password.');
}
}
## Unlock Screen
private function checkPassword($password)
{
// Implement your password validation logic here
// For example, compare against a stored hash
// return $password === 'correct_password';
helper('session');
$session_uid = get_logged_user_id();
$auth_model = new AuthenticationModel();
$user = $auth_model->where('user_id', $session_uid)->first();
$pwd_verify = password_verify((string)$password, $user['password']);
return $pwd_verify ;
}
}