chartboard/app/Controllers/ProfileController.php
2026-03-30 09:51:33 +05:30

94 lines
3.2 KiB
PHP

<?php
namespace App\Controllers;
use App\Models\UserModel;
class ProfileController extends BaseController
{
public function index()
{
$userId = (int) $this->session->get('user_id');
$userModel = new UserModel();
$user = $userModel->find($userId);
return view('profile/index', [
'title' => 'Profile | Chart-Board',
'user' => $user,
'plainApiToken' => session()->getFlashdata('plain_api_token'),
]);
}
public function update()
{
$userId = (int) $this->session->get('user_id');
$rules = [
'name' => 'required|min_length[3]|max_length[150]',
'avatar' => 'permit_empty|uploaded[avatar]|max_size[avatar,2048]|is_image[avatar]|mime_in[avatar,image/jpg,image/jpeg,image/png,image/webp]',
];
$isAvatarUpload = $this->request->getFile('avatar') && $this->request->getFile('avatar')->isValid();
if (! $isAvatarUpload) {
unset($rules['avatar']);
}
if (! $this->validate($rules)) {
return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
}
$updateData = [
'name' => strip_tags((string) $this->request->getPost('name')),
];
if ($isAvatarUpload) {
$avatar = $this->request->getFile('avatar');
$avatarName = $avatar->getRandomName();
$avatar->move(WRITEPATH . 'uploads/avatars', $avatarName);
$updateData['avatar'] = 'writable/uploads/avatars/' . $avatarName;
}
$userModel = new UserModel();
$userModel->update($userId, $updateData);
$this->session->set('name', $updateData['name']);
return redirect()->to('/profile')->with('success', 'Profile updated.');
}
public function changePassword()
{
$rules = [
'current_password' => 'required|min_length[8]|max_length[255]',
'new_password' => 'required|min_length[8]|max_length[255]',
'confirm_password' => 'required|matches[new_password]',
];
if (! $this->validate($rules)) {
return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
}
$userId = (int) $this->session->get('user_id');
$userModel = new UserModel();
$user = $userModel->find($userId);
if (! $user || ! password_verify((string) $this->request->getPost('current_password'), (string) $user['password'])) {
return redirect()->back()->with('error', 'Current password is incorrect.');
}
$userModel->update($userId, ['password' => (string) $this->request->getPost('new_password')]);
return redirect()->to('/profile')->with('success', 'Password changed successfully.');
}
public function generateApiToken()
{
$userId = (int) $this->session->get('user_id');
$plainToken = bin2hex(random_bytes(32));
$hashedToken = hash('sha256', $plainToken);
$userModel = new UserModel();
$userModel->update($userId, ['api_token' => $hashedToken]);
return redirect()->to('/profile')->with('success', 'API token regenerated. Copy it now.')
->with('plain_api_token', $plainToken);
}
}