承接 muradcade/secureauth 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

muradcade/secureauth

Composer 安装命令:

composer require muradcade/secureauth

包简介

SecureAuth is a lightweight PHP package designed to simplify common web application security and authentication tasks, including validation, CSRF protection, authentication, authorization, email sending, and “remember me” functionality.

README 文档

README

SecureAuth is a lightweight PHP package designed to simplify common web application security and authentication tasks, including validation, CSRF protection, authentication, authorization, email sending, and “remember me” functionality.

Table of Contents

  1. Installation
  2. Validation
  3. BaseRepository
  4. Authentication
  5. Authorization
  6. Email Jobs
  7. RememberMe Token
  8. Rate Limiter
  9. Environment Configuration
  10. Example Workflow
  11. SecureAuth PHP Package License

Installation

Install via Composer:

composer require muradcade/secureauth

Validation

SecureAuth wraps Laravel’s validation components for simple and robust validation.

Validation Usage

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' => 'test@example.com',
    'password' => 'StrongPass123!',
    'csrf_token' => $token
];

// Validation rules
$rules = [
    'email' => 'required|email',
    'password' => 'required|min:8|strong_password',
    'csrf_token' => 'required|verify_csrftoken'
];

// Validate and handle errors
if (!$validator->validate($data, $rules, $customErrorMessage->validationMessage())) {
    var_dump($validator->errors()[0]);
}

Validation Rules

Rule Description
required Field must not be empty
email Must be a valid email format
min:8 Minimum 8 characters
strong_password Must include uppercase, lowercase, numbers, and symbols
verify_csrftoken Validates that the CSRF token is valid

BaseRepository

Provides database interaction using prepared statements with MySQLi.

BaseRepository Usage

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)
);
  • Supports SELECT, INSERT, UPDATE, DELETE operations.

Authentication

Authenticate users with database data and manage sessions.

Authentication Usage

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();
}

Authorization

Check user login status and role-based access.

Authorization Usage

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');

Email Jobs

Supports sending emails with or without attachments using a worker-job system.

Job Structure

  • JobInterface – Defines rules for processing email jobs.
  • EmailJob – Handles sending emails.
  • WorkerJob – Dispatches email jobs.

Email Jobs Usage

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

$mailContent = [
    'recipient' => 'recipient@example.com',
    '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);

RememberMe Token

Manages persistent login tokens stored in cookies.

RememberMe Token Usage

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@example.com', 'role', 2);
} else {
    $auth->redirectIfNotLoggedIn(SessionHelper::getSessionVariable('userid'), 'index.php', $tokenManager->getTokenContent());
}

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

Environment Configuration

$config = [
    'DATABASE' => [
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'dbname' => 'secureauth'
    ],
    'MAIL' => [
        'GOOGLE_EMAIL' => 'john@example.com',
        'GOOGLE_SECRET_KEY' => '',
        'PROJECT_NAME' => 'TEST',
        'Email_Verification_Url' => 'http://localhost/secureauth/'
    ]
];

Rate Limiter

The Rate Limiter is responsible for preventing brute-force login attacks by limiting the number of failed login attempts a user can make within a specified timeframe. It works by storing failed attempts in a database table and checking whether the threshold has been exceeded before processing further login requests.

Database Schema

Before using the Rate Limiter, create the login_attempts table:

CREATE TABLE login_attempts (
    id INT(4) PRIMARY KEY AUTO_INCREMENT,
    ip VARCHAR(45) NOT NULL,
    email VARCHAR(255) NOT NULL,
    attempt_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

How It Works

  1. Store Failed Attempts : Every time a login attempt fails (invalid email or password), an entry is stored in the login_attempts table.
  2. Check Attempt Limits:Before processing a new login, the RateLimiter checks if the IP/email combination has exceeded the maximum allowed attempts in the defined interval.
  3. Block Excessive Attempts: If the limit is reached, the login is denied. The user must wait until the retry window has expired before attempting again.
  4. Reset After Success:On successful login, all attempts for that user/email are cleared.

Example Usage

Below is how you integrate the RateLimiter inside your login controller or login handler:

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();
}

Example Workflow

Here’s how everything ties together in a login flow:
Login Page (index.php)

<?php if ($msg = SessionHelper::getFlash('error')): ?>
    <p style="color:red"><?= htmlspecialchars($msg); ?></p>
<?php endif; ?>

<form method="POST">
    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($token, ENT_QUOTES, 'UTF-8') ?>">
    <input type="text" name="email" placeholder="email">
    <br><br>
    <input type="password" name="password" placeholder="password">
    <br><br>
    <label>
        <input type="checkbox" name="remember_me"> Remember Me
    </label>
    <br><br>
    <button type="submit" name="submit">Login</button>
</form>

Login Logic

This file handles:

  1. Input validation
  2. CSRF token generation & validation
  3. Rate limiting
  4. User authentication
  5. Remember Me functionality
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

SecureAuth PHP Package License

Copyright (c) 2025 Muradcade

Permission is granted to anyone to use, copy, and distribute this software for any purpose, including personal and commercial use.

You are free to:

  • View the source code.
  • Use it in your own projects.
  • Fork it for personal use.

You are not allowed to:

  • Modify the official repository.
  • Claim ownership of the official codebase.
  • Merge changes into the official repository.

The original author (Muradcade) retains the exclusive right to update and maintain the official repository.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT ANY WARRANTY.
USE IT AT YOUR OWN RISK. The author is not responsible for any damages, data loss, or other issues arising from the use of this software.

muradcade/secureauth 适用场景与选型建议

muradcade/secureauth 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 8 次下载、GitHub Stars 达 1, 最近一次更新时间为 2025 年 09 月 07 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「authorization」 「Authentication」 「validation」 「csrf」 「rate-limit」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 muradcade/secureauth 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 muradcade/secureauth 我们能提供哪些服务?
定制开发 / 二次开发

基于 muradcade/secureauth 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 8
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 29
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-09-07