有效管理使用者帳戶對於任何 Web 應用程式都至關重要。 CodeIgniter 4 Shield 憑藉其強大的身份驗證和授權工具簡化了此任務。在這篇文章中,我們將探討使用 CodeIgniter 4 Shield 的使用者設定檔管理、密碼重設和復原以及帳戶已啟動和停用。
建立使用者設定檔檢視和表單
要管理使用者設定文件,您需要建立允許使用者查看和更新其資訊的視圖和表單。讓我們從建立基本的個人資料視圖和表單開始。
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
class Profile extends Controller
{
public function index()
{
$userModel = model('UserModel');
$userId = auth()->id(); // Get current user ID
$data['user'] = $userModel->find($userId);
return view('profile_view', $data);
}
public function update()
{
$userModel = model('UserModel');
$userId = auth()->id(); // Get current user ID
$userModel->update($userId, [
'username' => $this->request->getPost('username'),
'email' => $this->request->getPost('email'),
]);
return redirect()->to('/profile')->with('success', 'Profile updated successfully.');
}
public function resetPassword()
{
$email = $this->request->getPost('email');
$userModel = model('UserModel');
$user = $userModel->where('email', $email)->first();
if ($user) {
// Send reset link via email (implement email sending)
// For simplicity, we just log a message here
log_message('info', 'Password reset link sent to ' . $email);
}
return redirect()->to('/')->with('message', 'If the email is registered, a reset link will be sent.');
}
public function reset()
{
$token = $this->request->getPost('token');
$newPassword = $this->request->getPost('new_password');
$userModel = model('UserModel');
// Validate token and reset password
// For simplicity, token validation is skipped here
$user = $userModel->where('reset_token', $token)->first();
if ($user) {
$userModel->update($user['id'], [
'password' => password_hash($newPassword, PASSWORD_DEFAULT),
'reset_token' => null // Clear reset token
]);
return redirect()->to('/login')->with('success', 'Password reset successfully.');
}
return redirect()->to('/')->with('error', 'Invalid token.');
}
public function activate($token)
{
$userModel = model('UserModel');
$user = $userModel->where('activation_token', $token)->first();
if ($user) {
$userModel->update($user['id'], [
'is_active' => true,
'activation_token' => null // Clear activation token
]);
return redirect()->to('/login')->with('success', 'Account activated successfully.');
}
return redirect()->to('/')->with('error', 'Invalid activation token.');
}
public function deactivate()
{
$userId = auth()->id(); // Get current user ID
$userModel = model('UserModel');
$userModel->update($userId, [
'is_active' => false
]);
return redirect()->to('/login')->with('success', 'Account deactivated. Please contact support to reactivate.');
}
}