Login , Register ,and onboarding

This commit is contained in:
Thanakorn S
2026-04-28 11:59:49 +07:00
parent d8c55d278a
commit d8fd30c961
25 changed files with 2394 additions and 110 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
<?php
session_start();
require '../../../session.php';
require '../../../assets/utils/db_auth.php';
+1 -2
View File
@@ -1,6 +1,5 @@
<?php
session_start();
require '../../../session.php';
require '../../../config.php';
require '../../../preset.php';
require '../../../assets/utils/db_auth.php';
+85 -30
View File
@@ -1,6 +1,5 @@
<?php
session_start();
require '../../../session.php';
require '../../../config.php';
require '../../../preset.php';
require '../../../assets/utils/db_auth.php';
@@ -39,8 +38,57 @@
exit(json_encode($answer));
}
if( $r["status"] == "not activated" ){
$answer["message"] = "Cannot Login: This user is not activated!?!";
// ── Block unverified accounts — resend verification email ───
if ($r["status"] === "pending") {
// generate fresh token
$token = bin2hex(random_bytes(32));
$expires_at = date('Y-m-d H:i:s', strtotime('+30 days'));
$sth = $pdo1->prepare("UPDATE user SET verify_token = :token, verify_expires_at = :expires WHERE user_id = :id");
$sth->execute([':token' => $token, ':expires' => $expires_at, ':id' => $r['user_id']]);
// build verify URL
$base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http')
. '://' . $_SERVER['HTTP_HOST'] . rtrim($server_url, '/');
$verify_url = $base_url . '/login/verify.php?token=' . $token;
// send email — silently ignore if it fails, don't expose error to user
try {
require_once $include_url . 'assets/utils/module/mailer.php';
$mailer = new mailer(['pdo1' => $pdo1]);
$mailer->send_email([
'company_id' => 0,
'smtp' => $SMTP,
'to' => $r['email'],
'subject' => 'Verify your email — WMS',
'message' => implode("
", [
"Hi {$r['name']},",
"",
"You attempted to login but your email is not yet verified.",
"Please verify your email address by clicking the button below:",
"",
"<a href='{$verify_url}' style='display:inline-block;padding:12px 28px;background:#E66239;color:#ffffff;text-decoration:none;border-radius:6px;font-weight:600;'>Verify Email Address</a>",
"",
"Or copy and paste this link into your browser:",
"<a href='{$verify_url}'>{$verify_url}</a>",
"",
"This link will expire in 30 days.",
]),
'channel_name' => 'WMS',
'key' => $pinkey,
]);
} catch (Exception $e) {
error_log('[resend_verify] ' . $e->getMessage());
}
$answer["message"] = "Your email is not verified. We've sent a new verification link to your inbox — please check your email.";
exit(json_encode($answer));
}
if ($r["status"] === "not activated") {
$answer["message"] = "Your account has been deactivated. Please contact your administrator.";
exit(json_encode($answer));
}
@@ -143,44 +191,51 @@
$reference_number = numberToLetters(generateOTP($otp));
/**
* Sent Email With OTP
*/
require "../../../assets/utils/module/mailer.php";
// ── Look up company SMTP using user's default_company ───────
$smtp_config = null;
$default_company = (int)($r["default_company"] ?? 0);
// send email
if(true){
if($default_company > 0) {
$sth = $pdo1->prepare("SELECT * FROM company_smtp WHERE company_id = :cid LIMIT 1");
$sth->execute([":cid" => $default_company]);
$smtp_row = $sth->fetch(PDO::FETCH_ASSOC);
if(!empty($smtp_row)) {
$smtp_config = $smtp_row;
}
}
$mailer = new mailer(["pdo1"=>$pdo1,"pdo2"=>$pdo2]);
// ── SMTP found → send OTP email ──────────────────────────────
if(!empty($smtp_config)) {
require "../../../assets/utils/module/mailer.php";
$mailer = new mailer(["pdo1"=>$pdo1,"pdo2"=>$pdo2]);
$mailer->send_email([
"company_id" => 0,
"smtp" => $SMTP,
"subject" => "One Time Password (OTP) For reference number ".$reference_number,
"message" => "Your OTP is ".$otp." for reference number ".$reference_number,
"channel_name" => "WMS LOGIN OTP ",
"to" => $user_email,
"key" => $pinkey,
"company_id" => $default_company,
"smtp" => $smtp_config,
"subject" => "One Time Password (OTP) For reference number ".$reference_number,
"message" => "Your OTP is ".$otp." for reference number ".$reference_number,
"channel_name" => "WMS LOGIN OTP",
"to" => $user_email,
"key" => $pinkey,
]);
}
$_SESSION = [];
$_SESSION["login_data"] = $data; // store variables
$_SESSION["otp"] = $otp;
$_SESSION["otpTime"] = $otpTime;
$_SESSION["reference"] = $reference_number;
$_SESSION["user_email"] = $user_email;
$_SESSION["login_data"] = $data;
$_SESSION["otp"] = $otp;
$_SESSION["otpTime"] = $otpTime;
$_SESSION["reference"] = $reference_number;
$_SESSION["user_email"] = $user_email;
$_SESSION["login_user_id"] = $user_id;
$_SESSION["no_smtp"] = empty($smtp_config); // flag for login_confirm
$answer["success"] = 1;
$answer["message"] = "Login Complete!";
$answer["success"] = 1;
$answer["skip_otp"] = empty($smtp_config);
$answer["message"] = "Login Complete!";
exit(json_encode($answer));
}
else
+174
View File
@@ -0,0 +1,174 @@
<?php
require '../../../session.php';
require '../../../config.php';
require '../../../dbconn.php';
require '../../../assets/utils/db_helpers.php';
header('Content-Type: application/json; charset=utf-8');
$answer = ['success' => 0, 'message' => ''];
// ─── Must come from onboarding session ───────────────────────
if (empty($_SESSION['onboarding_user_id'])) {
$answer['message'] = 'Invalid session. Please verify your email first.';
http_response_code(403);
exit(json_encode($answer));
}
$user_id = (int)$_SESSION['onboarding_user_id'];
// ─── CSRF ─────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$csrf = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
if (empty($csrf) || $csrf !== ($_SESSION['csrf_token'] ?? '')) {
http_response_code(403);
exit(json_encode(['message' => 'Invalid request.']));
}
}
$data = json_decode($_POST['json'] ?? '{}', true) ?: [];
try {
$company_name = trim($data['company_name'] ?? '');
$company_name2 = trim($data['company_name2'] ?? '');
$channel_name = strtolower(preg_replace('/[^a-z0-9\-_]/', '', $data['channel_name'] ?? ''));
$branch = trim($data['branch'] ?? 'สำนักงานใหญ่');
$branch_no = trim($data['branch_no'] ?? '00000');
$email = trim($data['email'] ?? '');
$phone = trim($data['phone'] ?? '');
if (!$company_name || !$channel_name) {
$answer['message'] = 'Company name and channel name are required.';
http_response_code(422);
exit(json_encode($answer));
}
// ── SMTP fields required ──────────────────────────────────
$smtp_host = trim($data['smtp_host'] ?? '');
$smtp_username = trim($data['smtp_username'] ?? '');
$smtp_password = $data['smtp_password'] ?? '';
if (!$smtp_host || !$smtp_username || !$smtp_password) {
$answer['message'] = 'SMTP configuration is required. Please fill in all SMTP fields.';
http_response_code(422);
exit(json_encode($answer));
}
$smtp_port = trim($data['smtp_port'] ?? '587');
$smtp_encryption = trim($data['smtp_encryption'] ?? 'tls');
if (!in_array($smtp_port, ['25', '465', '587'], true)) $smtp_port = '587';
if (!in_array($smtp_encryption, ['tls', 'ssl', 'none'], true)) $smtp_encryption = 'tls';
// ── Silent SMTP test — before touching the DB ─────────────
// Build a temporary config using the encrypted password
$encrypted_pass = openssl_encrypt($smtp_password, $method, $pinkey, 0, $iv);
$smtp_config = [
'server' => $smtp_host,
'port' => $smtp_port,
'username' => $smtp_username,
'password' => $encrypted_pass,
'from_name' => $company_name ?: $smtp_username,
'from_email' => $email ?: $smtp_username,
'encryption' => $smtp_encryption,
];
require_once $include_url . 'assets/utils/module/mailer.php';
$mailer = new mailer(['pdo1' => $pdo1]);
$mailer->send_email([
'company_id' => 0,
'smtp' => $smtp_config,
'to' => $_SESSION['onboarding_email'] ?? $smtp_username,
'subject' => 'WMS — SMTP Verification',
'message' => "Your SMTP is working correctly.\n\nSetup is now complete.",
'channel_name' => $company_name ?: 'WMS',
'key' => $pinkey,
]);
// if mailer fails it exits with its own error JSON — nothing below runs
// ── Duplicate channel name ────────────────────────────────
$sth = $pdo1->prepare('SELECT company_id FROM company_list WHERE channel_name = :c LIMIT 1');
$sth->execute([':c' => $channel_name]);
db_check($sth, $answer);
if ($sth->fetchColumn()) {
$answer['message'] = 'Channel name is already taken. Please choose another.';
http_response_code(409);
exit(json_encode($answer));
}
// ── Insert company ────────────────────────────────────────
$sth = $pdo1->prepare("
INSERT INTO company_list
(channel_name, company_name, company_name2, branch, branch_no, email, phone, fx)
VALUES
(:channel_name, :company_name, :company_name2, :branch, :branch_no, :email, :phone, 'thb')
");
$sth->execute([
':channel_name' => $channel_name,
':company_name' => $company_name,
':company_name2' => $company_name2,
':branch' => $branch,
':branch_no' => $branch_no,
':email' => $email,
':phone' => $phone,
]);
db_check($sth, $answer);
$company_id = (int)$pdo1->lastInsertId();
// ── Map user as owner ─────────────────────────────────────
$sth = $pdo1->prepare("
INSERT INTO company_map_user (company_id, user_id, role, created_at)
VALUES (:company_id, :user_id, 'owner', NOW())
");
$sth->execute([':company_id' => $company_id, ':user_id' => $user_id]);
db_check($sth, $answer);
// ── Set as default company for this user ──────────────────
$sth = $pdo1->prepare("UPDATE user SET default_company = :c, `status` = 'active' WHERE user_id = :u");
$sth->execute([':c' => $company_id, ':u' => $user_id]);
db_check($sth, $answer);
// ── Save SMTP ─────────────────────────────────────────────
$sth = $pdo1->prepare("
INSERT INTO company_smtp
(company_id, server, port, username, password,
from_name, from_email, encryption, updated_at)
VALUES
(:company_id, :server, :port, :username, :password,
:from_name, :from_email, :encryption, NOW())
");
$sth->execute([
':company_id' => $company_id,
':server' => $smtp_host,
':port' => $smtp_port,
':username' => $smtp_username,
':password' => $encrypted_pass,
':from_name' => $company_name,
':from_email' => $email ?: $smtp_username,
':encryption' => $smtp_encryption,
]);
db_check($sth, $answer);
// ── Clear onboarding session ──────────────────────────────
unset(
$_SESSION['onboarding_user_id'],
$_SESSION['onboarding_name'],
$_SESSION['onboarding_email']
);
$answer['success'] = 1;
$answer['message'] = 'Setup complete.';
} catch (Exception $e) {
error_log('[onboarding] ' . $e->getMessage());
$answer['message'] = 'Setup failed. Please try again.';
http_response_code(500);
}
exit(json_encode($answer));
?>
+156
View File
@@ -0,0 +1,156 @@
<?php
require '../../../session.php';
require '../../../config.php';
require '../../../dbconn.php';
require '../../../assets/utils/db_helpers.php';
require '../../../assets/utils/classes/PasswordManager.php';
header('Content-Type: application/json; charset=utf-8');
$answer = ['success' => 0, 'message' => ''];
// ─── CSRF ─────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$csrf = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
if (empty($csrf) || $csrf !== ($_SESSION['csrf_token'] ?? '')) {
http_response_code(403);
exit(json_encode(['message' => 'Invalid request.']));
}
}
$data = json_decode($_POST['json'] ?? '{}', true) ?: [];
try {
$name = trim($data['name'] ?? '');
$surname = trim($data['surname'] ?? '');
$username = strtolower(trim($data['username'] ?? ''));
$email = strtolower(trim($data['email'] ?? ''));
$password = $data['password'] ?? '';
$confirm = $data['confirm_password'] ?? '';
// ── Required fields ───────────────────────────────────────
if (!$name || !$surname || !$username || !$email || !$password || !$confirm) {
$answer['message'] = 'All fields are required.';
http_response_code(422);
exit(json_encode($answer));
}
// ── Username format ───────────────────────────────────────
if (!preg_match('/^[a-z0-9_]+$/', $username)) {
$answer['message'] = 'Username may only contain lowercase letters, numbers and underscores.';
http_response_code(422);
exit(json_encode($answer));
}
// ── Email format ──────────────────────────────────────────
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$answer['message'] = 'Invalid email address.';
http_response_code(422);
exit(json_encode($answer));
}
// ── Password match ────────────────────────────────────────
if ($password !== $confirm) {
$answer['message'] = 'Passwords do not match.';
http_response_code(422);
exit(json_encode($answer));
}
// ── Duplicate username ────────────────────────────────────
$sth = $pdo1->prepare('SELECT user_id FROM user WHERE username = :u LIMIT 1');
$sth->execute([':u' => $username]);
db_check($sth, $answer);
if ($sth->fetchColumn()) {
$answer['message'] = 'Username is already taken.';
http_response_code(409);
exit(json_encode($answer));
}
// ── Duplicate email ───────────────────────────────────────
$sth = $pdo1->prepare('SELECT user_id FROM user WHERE email = :e LIMIT 1');
$sth->execute([':e' => $email]);
db_check($sth, $answer);
if ($sth->fetchColumn()) {
$answer['message'] = 'An account with that email already exists.';
http_response_code(409);
exit(json_encode($answer));
}
// ── Password strength ─────────────────────────────────────
$pm = new PasswordManager($pdo1, $include_url);
$result = $pm->checkStrength($password, [$name, $surname, $username, $email]);
if ($result['score'] < PasswordManager::MIN_SCORE) {
$msg = $result['warning'] ?: ($result['suggestions'][0] ?? 'Please choose a stronger password.');
$answer['message'] = 'Password is too weak. ' . $msg;
http_response_code(422);
exit(json_encode($answer));
}
// ── Insert user with status=pending ───────────────────────
$hashed = password_hash($password, PASSWORD_BCRYPT);
$token = bin2hex(random_bytes(32));
$expires_at = date('Y-m-d H:i:s', strtotime('+30 days'));
$sth = $pdo1->prepare("
INSERT INTO user
(username, name, surname, email, password, status, profile_picture, verify_token, verify_expires_at)
VALUES
(:username, :name, :surname, :email, :password, 'pending', '', :token, :expires)
");
$sth->execute([
':username' => $username,
':name' => $name,
':surname' => $surname,
':email' => $email,
':password' => $hashed,
':token' => $token,
':expires' => $expires_at,
]);
db_check($sth, $answer);
// ── Send verification email via default SMTP ──────────────
// Build absolute URL
$base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http')
. '://' . $_SERVER['HTTP_HOST']
. rtrim($server_url, '/');
$verify_url = $base_url . '/login/verify.php?token=' . $token;
require_once $include_url . 'assets/utils/module/mailer.php';
$mailer = new mailer(['pdo1' => $pdo1]);
$mailer->send_email([
'company_id' => 0,
'smtp' => $SMTP,
'to' => $email,
'subject' => 'Verify your email — WMS',
'message' => implode("\n", [
"Hi {$name},",
"",
"Thanks for registering. Please verify your email address by clicking the button below:",
"",
"<a href=\"{$verify_url}\" style=\"display:inline-block;padding:12px 28px;background:#E66239;color:#ffffff;text-decoration:none;border-radius:6px;font-weight:600;\">Verify Email Address</a>",
"",
"Or copy and paste this link into your browser:",
"<a href=\"{$verify_url}\">{$verify_url}</a>",
"",
"This link will expire in 30 days.",
"",
"If you did not create an account, you can ignore this email.",
]),
'channel_name' => 'WMS',
'key' => $pinkey,
]);
$answer['success'] = 1;
$answer['message'] = 'Account created! Please check your email to verify your account.';
} catch (Exception $e) {
error_log('[register] ' . $e->getMessage());
$answer['message'] = 'Registration failed. Please try again.';
http_response_code(500);
}
exit(json_encode($answer));
?>
+2 -3
View File
@@ -1,6 +1,5 @@
<?php
session_start();
require '../../../session.php';
require '../../../config.php';
require '../../../preset.php';
require '../../../assets/utils/db_auth.php';
@@ -66,7 +65,7 @@
// send email
if(true){
$mailer = new mailer(["pdo1"=>$pdo1,"pdo2"=>$pdo2]);
$mailer = new mailer(["pdo1"=>$pdo1]);
$mailer->send_email([
"company_id" => 0,