PHP code example of muradcade / secureauth

1. Go to this page and download the library: Download muradcade/secureauth library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

muradcade / secureauth example snippets


use SecureAuth\Security\Csrf;
use SecureAuth\Validation\Validator;
use SecureAuth\Validation\ValidatorMessages;

// Create Validator instance
$validator = new Validator();
// custom validation message
 $customErrorMessage = new ValidatorMessages($validator);
 // if there is no csrf token generate one   = Csrf::generateToken();
$token = Csrf::getToken(); // get the generated session


// Data to validate
$data = [
    'email' => '[email protected]',
    'password' => 'StrongPass123!',
    'csrf_token' => $token
];

// Validation rules
$rules = [
    'email' => '

use SecureAuth\Repository\BaseRepository;

// Pass a MySQLi connection
$repository = new BaseRepository($connection);

// Insert a new user
$repository->query(
    'INSERT INTO users(fullname,email,password) VALUES (?, ?, ?)',
    'sss',
    $data['fullname'],
    $data['email'],
    password_hash($data['password'], PASSWORD_DEFAULT)
);

use SecureAuth\Auth\Auth;
use SecureAuth\Auth\SessionHelper;
use SecureAuth\Repository\BaseRepository;

// Fetch user record
$result = $repository
    ->query('SELECT * FROM users WHERE email = ?', 's', $data['email'])
    ->fetchOne();

// Authenticate user
if (Auth::authenticateUser($result, $data['email'], $data['password'])) {
    SessionHelper::setUserSession($result['fullname'], $result['email'], $result['userrole'], $result['id']);
    header('Location: dashboard.php');
    exit();
}

use SecureAuth\Auth\Authorization;
use SecureAuth\Auth\SessionHelper;

$auth = new Authorization();

// Redirect if user is logged in (e.g., login page)
$auth->Islogedin(SessionHelper::getSessionVariable('username'), 'dashboard.php');

// Redirect if user is not logged in
$auth->Isnotlogedin(SessionHelper::getSessionVariable('username'), 'index.php');

// Authorize specific user roles
$auth->AuthorizedUser(SessionHelper::getSessionVariable('userrole'), 'admin', 'index.php');

use SecureAuth\Jobs\WorkerJob;
use SecureAuth\Jobs\EmailJob;

$mailContent = [
    'recipient' => '[email protected]',
    'subject' => 'Test Email',
    'body' => '<h1>Hello World</h1>',
    'attachment' => __DIR__ . '/files/test.txt' // optional
];

// Dispatch job (emailjobclass) , $config comes from env file and mailcontent is array above
$result = WorkerJob::run(EmailJob::class, $config, $mailContent);

use SecureAuth\Security\RememberMeToken;
use SecureAuth\Auth\Authorization;
use SecureAuth\Auth\SessionHelper;

$tokenManager = new RememberMeToken();

// Generate token and set cookie
$tokenManager->generateRememberMeToken()->setCookie();
// create instance of authorization class
$auth = new Authorization();
// Check if session missing but token exists
if ($auth->shouldRotateToken(SessionHelper::getSessionVariable('userid'), $tokenManager->getTokenContent())) {
    $tokenManager->rotateTokenContent();
    SessionHelper::setUserSession('Username', '[email protected]', 'role', 2);
} else {
    $auth->redirectIfNotLoggedIn(SessionHelper::getSessionVariable('userid'), 'index.php', $tokenManager->getTokenContent());
}

// Get current token
$currentToken = $tokenManager->getTokenContent();

$config = [
    'DATABASE' => [
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'dbname' => 'secureauth'
    ],
    'MAIL' => [
        'GOOGLE_EMAIL' => '[email protected]',
        'GOOGLE_SECRET_KEY' => '',
        'PROJECT_NAME' => 'TEST',
        'Email_Verification_Url' => 'http://localhost/secureauth/'
    ]
];

use SecureAuth\Security\RateLimiter;

// Get client IP
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';

// 1. Store failed attempt
$baserepo->query(
    'INSERT INTO login_attempts(ip, email) VALUES(?, ?)',
    'ss',
    $ip,
    $email
);

// 2. Check if too many attempts
if ($rateLimiter->tooManyAttempts($ip, $email)) {
    $retryAfter = $rateLimiter->getRetryAfterSeconds($ip, $email);
    header('Retry-After: ' . $retryAfter);

    // Optionally send correct HTTP code (for APIs)
    // http_response_code(429);

    // Store error in session (for UI feedback)
    SessionHelper::flash('error', 'Too many login attempts. Please wait ' . $retryAfter . ' seconds.');

    header('location:index.php');
    exit();
}

 if ($msg = SessionHelper::getFlash('error')): 

if ($rateLimiter->tooManyAttempts($ip, $email)) {
    $retryAfter = $rateLimiter->getRetryAfterSeconds($ip, $email);
    SessionHelper::flash('error', "Too many login attempts. Please wait {$retryAfter} seconds.");
    header('location:index.php');
    exit();
}

$result = $baserepo->query(
    'SELECT * FROM users WHERE email = ?',
    's',
    $email
)->fetchOne();

if ($result && Auth::AuthenticateUser($result, $email, $password)) {
    $baserepo->query('DELETE FROM login_attempts WHERE email = ?', 's', $email);
    // set session, regenerate CSRF, handle Remember Me, redirect
} else {
    $baserepo->query('INSERT INTO login_attempts(ip, email) VALUES(?, ?)', 'ss', $ip, $email);
    SessionHelper::flash('error', 'Invalid email or password');
    header('location:index.php');
    exit();
}
n