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,
+20 -1
View File
@@ -1,5 +1,5 @@
<?php
session_start();
require '../session.php';
require '../config.php';
require '../include_header.php';
// successful login
@@ -16,6 +16,12 @@
<div class="card " style="max-width:420px; width:100%;">
<div class="card-body p-5">
<div class="text-center mb-3">
<?php if (!empty($_SESSION['verify_error'])): ?>
<div class="alert alert-danger small py-2 mb-3">
<i class="ti ti-alert-circle me-1"></i>
<?php echo htmlspecialchars($_SESSION['verify_error']); unset($_SESSION['verify_error']); ?>
</div>
<?php endif; ?>
<a href="index.html" class="mb-5 d-inline-block"><img
src="data:image/svg+xml,%3csvg%20width='62'%20height='67'%20viewBox='0%200%2062%2067'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M30.604%2066.378L0.00805664%2048.1582V35.7825L30.604%2054.0023V66.378Z'%20fill='%23302C4D'/%3e%3cpath%20d='M61.1996%2048.1582L30.604%2066.378V54.0023L61.1996%2035.7825V48.1582Z'%20fill='%23E66239'/%3e%3cpath%20d='M30.5955%200L0%2018.2198V30.5955L30.5955%2012.3757V0Z'%20fill='%23657E92'/%3e%3cpath%20d='M61.191%2018.2198L30.5955%200V12.3757L61.191%2030.5955V18.2198Z'%20fill='%23A3B2BE'/%3e%3cpath%20d='M30.604%2048.8457L0.00805664%2030.6259V18.2498L30.604%2036.47V48.8457Z'%20fill='%23302C4D'/%3e%3cpath%20d='M61.1996%2030.6259L30.604%2048.8457V36.47L61.1996%2018.2498V30.6259Z'%20fill='%23E66239'/%3e%3c/svg%3e"
alt="" width="36">
@@ -48,8 +54,18 @@
</div>
</div>
<button class="btn btn-primary w-100" onclick="login();">Sign in</button>
<p class="text-center text-muted small mt-3 mb-0">
Don't have an account?
<a href="<?php echo $server_url?>login/register.php" class="link-primary">Create one</a>
</p>
<?php }else{ ?>
<!-- second step login -->
<div class="alert alert-warning small py-2 mb-3">
<i class="ti ti-mail me-1"></i>
OTP is sent via your company's SMTP setting.
If no SMTP is configured, you will be signed in directly without OTP.
<a href="<?php echo $server_url?>setting/smtp.php" class="alert-link ms-1">Configure SMTP →</a>
</div>
<div class="mb-3">
<label for="otp" class="form-label d-flex justify-content-between">
<span>One Time Password</span>
@@ -96,6 +112,9 @@
// reqquest new otp function
function request_new_otp() {
+298
View File
@@ -0,0 +1,298 @@
<?php
require '../session.php';
require '../config.php';
require '../include_header.php';
// Must come from email verification
if (empty($_SESSION['onboarding_user_id'])) {
header('Location: ' . $server_url . 'login/index.php');
exit;
}
// Generate CSRF token if not already set
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$user_name = htmlspecialchars($_SESSION['onboarding_name'] ?? 'there');
?>
<body>
<div class="container py-5" style="max-width:680px;">
<!-- Header -->
<div class="text-center mb-5">
<a href="<?php echo $server_url?>login/index.php" class="d-inline-block mb-4">
<img src="data:image/svg+xml,%3csvg%20width='62'%20height='67'%20viewBox='0%200%2062%2067'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M30.604%2066.378L0.00805664%2048.1582V35.7825L30.604%2054.0023V66.378Z'%20fill='%23302C4D'/%3e%3cpath%20d='M61.1996%2048.1582L30.604%2066.378V54.0023L61.1996%2035.7825V48.1582Z'%20fill='%23E66239'/%3e%3cpath%20d='M30.5955%200L0%2018.2198V30.5955L30.5955%2012.3757V0Z'%20fill='%23657E92'/%3e%3cpath%20d='M61.191%2018.2198L30.5955%200V12.3757L61.191%2030.5955V18.2198Z'%20fill='%23A3B2BE'/%3e%3cpath%20d='M30.604%2048.8457L0.00805664%2030.6259V18.2498L30.604%2036.47V48.8457Z'%20fill='%23302C4D'/%3e%3cpath%20d='M61.1996%2030.6259L30.604%2048.8457V36.47L61.1996%2018.2498V30.6259Z'%20fill='%23E66239'/%3e%3c/svg%3e"
alt="" width="36">
<span class="ms-2"><img src="<?php echo $server_url?>assets/images/logo.svg" alt=""></span>
</a>
<h1 class="h4 mb-1">Welcome, <?php echo $user_name ?>! 👋</h1>
<p class="text-muted">Set up your company and email before you get started.</p>
</div>
<!-- Company Info Card -->
<div class="card mb-4">
<div class="card-body p-5">
<h2 class="fs-5 mb-1"><i class="ti ti-building me-2"></i>Company Information</h2>
<p class="text-muted small mb-4">This is how your company appears across the system.</p>
<div class="row g-3">
<div class="col-md-6">
<label class="form-label">Company Name (TH) <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="company_name" placeholder="ชื่อบริษัท" required>
</div>
<div class="col-md-6">
<label class="form-label">Company Name (EN)</label>
<input type="text" class="form-control" id="company_name2" placeholder="Company Name (English)">
</div>
<div class="col-md-6">
<label class="form-label">Channel Name <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="channel_name" placeholder="e.g. my-shop">
<div class="form-text">Unique identifier. Lowercase, no spaces.</div>
</div>
<div class="col-md-3">
<label class="form-label">Branch</label>
<input type="text" class="form-control" id="branch" placeholder="สำนักงานใหญ่">
</div>
<div class="col-md-3">
<label class="form-label">Branch No.</label>
<input type="text" class="form-control" id="branch_no" placeholder="00000">
</div>
<div class="col-md-6">
<label class="form-label">Email</label>
<input type="email" class="form-control" id="company_email" placeholder="company@example.com">
</div>
<div class="col-md-6">
<label class="form-label">Phone</label>
<input type="text" class="form-control" id="company_phone" placeholder="02-xxx-xxxx">
</div>
</div>
</div>
</div>
<!-- SMTP Card -->
<div class="card mb-4">
<div class="card-body p-5">
<div class="d-flex justify-content-between align-items-start mb-1">
<h2 class="fs-5 mb-0"><i class="ti ti-mail-cog me-2"></i>SMTP / Email Setting</h2>
<span class="badge bg-label-danger">Required</span>
</div>
<p class="text-muted small mb-3">
SMTP is required to send OTP during login.
A verification email will be sent when you finish setup.
</p>
<!-- SMTP User Guide (collapsible) -->
<div class="mb-4">
<a class="small link-primary text-decoration-none" data-bs-toggle="collapse" href="#smtp_guide" role="button">
<i class="ti ti-help-circle me-1"></i>How do I get SMTP settings?
</a>
<div class="collapse mt-3" id="smtp_guide">
<div class="border rounded p-4 bg-light small">
<!-- Gmail -->
<div class="mb-4">
<div class="fw-semibold mb-2">
<i class="ti ti-brand-gmail me-1 text-danger"></i>Gmail
</div>
<p class="text-muted mb-2">Gmail requires an <strong>App Password</strong> — your regular Gmail password will not work.</p>
<ol class="mb-2 ps-3">
<li>Go to <a href="https://myaccount.google.com/security" target="_blank">myaccount.google.com/security</a></li>
<li>Enable <strong>2-Step Verification</strong> if not already on</li>
<li>Search for <strong>App passwords</strong> in the search bar</li>
<li>Create a new app password — name it <em>WMS</em></li>
<li>Copy the 16-character password shown</li>
</ol>
<div class="bg-white border rounded p-2 font-monospace small">
Host: smtp.gmail.com &nbsp;|&nbsp; Port: 587 &nbsp;|&nbsp; Encryption: TLS
</div>
</div>
<hr class="my-3">
<!-- Outlook / Office 365 -->
<div class="mb-4">
<div class="fw-semibold mb-2">
<i class="ti ti-brand-office me-1 text-primary"></i>Outlook / Office 365
</div>
<p class="text-muted mb-2">Use your Microsoft 365 email and password directly. Make sure SMTP AUTH is enabled for your account.</p>
<ol class="mb-2 ps-3">
<li>Go to <a href="https://admin.microsoft.com" target="_blank">admin.microsoft.com</a></li>
<li>Under <strong>Users → Active users</strong>, select the account</li>
<li>Go to <strong>Mail → Manage email apps</strong></li>
<li>Enable <strong>Authenticated SMTP</strong></li>
</ol>
<div class="bg-white border rounded p-2 font-monospace small">
Host: smtp.office365.com &nbsp;|&nbsp; Port: 587 &nbsp;|&nbsp; Encryption: TLS
</div>
</div>
<hr class="my-3">
<!-- Yahoo -->
<div class="mb-4">
<div class="fw-semibold mb-2">
<i class="ti ti-mail me-1 text-warning"></i>Yahoo Mail
</div>
<p class="text-muted mb-2">Yahoo also requires an <strong>App Password</strong>.</p>
<ol class="mb-2 ps-3">
<li>Go to <a href="https://login.yahoo.com/account/security" target="_blank">Yahoo Account Security</a></li>
<li>Enable <strong>Two-step verification</strong></li>
<li>Click <strong>Generate app password</strong></li>
<li>Select <em>Other App</em>, name it <em>WMS</em>, copy the password</li>
</ol>
<div class="bg-white border rounded p-2 font-monospace small">
Host: smtp.mail.yahoo.com &nbsp;|&nbsp; Port: 587 &nbsp;|&nbsp; Encryption: TLS
</div>
</div>
<hr class="my-3">
<!-- Generic / cPanel -->
<div>
<div class="fw-semibold mb-2">
<i class="ti ti-server me-1 text-secondary"></i>Web Hosting / cPanel
</div>
<p class="text-muted mb-2">If your email is hosted with a web provider (e.g. Hostinger, GoDaddy, SiteGround):</p>
<ol class="mb-2 ps-3">
<li>Log in to your hosting <strong>cPanel</strong></li>
<li>Go to <strong>Email Accounts</strong> and create or select an account</li>
<li>Click <strong>Connect Devices</strong> to see SMTP details</li>
<li>Use those exact host, port and encryption settings</li>
</ol>
<div class="text-muted">
The host is usually <code>mail.yourdomain.com</code> and port is <code>587</code>.
</div>
</div>
</div>
</div>
</div>
<!-- SMTP Form -->
<div class="row g-3">
<div class="col-md-8">
<label class="form-label">SMTP Host <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="smtp_host" placeholder="e.g. smtp.gmail.com">
</div>
<div class="col-md-4">
<label class="form-label">Port <span class="text-danger">*</span></label>
<select class="form-select" id="smtp_port">
<option value="587">587 — TLS</option>
<option value="465">465 — SSL</option>
<option value="25">25 — Plain</option>
</select>
</div>
<div class="col-md-6">
<label class="form-label">Username / Email <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="smtp_username" placeholder="your@email.com">
</div>
<div class="col-md-6">
<label class="form-label">Password <span class="text-danger">*</span></label>
<div class="input-group">
<input type="password" class="form-control" id="smtp_password" placeholder="SMTP password">
<button class="btn btn-outline-secondary toggle-pw" type="button" data-target="smtp_password">
<i class="ti ti-eye"></i>
</button>
</div>
</div>
<div class="col-12">
<label class="form-label">Encryption</label>
<div class="d-flex gap-4">
<div class="form-check">
<input class="form-check-input" type="radio" name="smtp_encryption" id="enc_tls" value="tls" checked>
<label class="form-check-label" for="enc_tls">TLS</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="smtp_encryption" id="enc_ssl" value="ssl">
<label class="form-check-label" for="enc_ssl">SSL</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="smtp_encryption" id="enc_none" value="none">
<label class="form-check-label" for="enc_none">None</label>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Actions -->
<div class="d-flex justify-content-end align-items-center">
<button class="btn btn-primary px-5" id="btn_finish" onclick="finish_onboarding()">
<i class="ti ti-rocket me-1"></i>Finish Setup
</button>
</div>
</div>
<script>
$(function () {
$(document).on('click', '.toggle-pw', function () {
const $input = $('#' + $(this).data('target'));
const isText = $input.attr('type') === 'text';
$input.attr('type', isText ? 'password' : 'text');
$(this).find('i').toggleClass('ti-eye ti-eye-off');
});
});
function finish_onboarding() {
const company_name = $('#company_name').val().trim();
const channel_name = $('#channel_name').val().trim();
if (!company_name || !channel_name) {
bootbox.alert('Company name and channel name are required.');
return;
}
if (!$('#smtp_host').val().trim() || !$('#smtp_username').val().trim() || !$('#smtp_password').val()) {
bootbox.alert('SMTP host, username and password are required.');
return;
}
const $btn = $('#btn_finish');
$btn.prop('disabled', true).html('<i class="ti ti-loader-2 me-1"></i>Verifying SMTP…');
const encryption = $('input[name="smtp_encryption"]:checked').val();
ajax_request({
url: '<?php echo $server_url?>login/api/engine/onboarding.php',
autoPrepare: false,
data: { json: JSON.stringify({
action: 'create',
company_name: company_name,
company_name2: $('#company_name2').val().trim(),
channel_name: channel_name,
branch: $('#branch').val().trim() || 'สำนักงานใหญ่',
branch_no: $('#branch_no').val().trim() || '00000',
email: $('#company_email').val().trim(),
phone: $('#company_phone').val().trim(),
smtp_host: $('#smtp_host').val().trim(),
smtp_port: $('#smtp_port').val(),
smtp_username: $('#smtp_username').val().trim(),
smtp_password: $('#smtp_password').val(),
smtp_encryption: encryption,
})},
onSuccess: function (r) {
bootbox.alert('Setup complete! Please sign in to get started.', function () {
window.location.href = '<?php echo $server_url?>login/index.php';
});
},
onError: function (r) {
$btn.prop('disabled', false).html('<i class="ti ti-rocket me-1"></i>Finish Setup');
},
});
}
</script>
</body>
</html>
+260
View File
@@ -0,0 +1,260 @@
<?php
require '../session.php';
require '../config.php';
// Redirect if already logged in
if (!empty($_SESSION['login_status'])) {
header('Location: ' . $server_url . 'dashboard/index.php');
exit;
}
// Generate CSRF token for unauthenticated form
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
require '../include_header.php';
?>
<body>
<div class="container d-flex align-items-center justify-content-center min-vh-100 py-5">
<div class="card" style="max-width:520px; width:100%;">
<div class="card-body p-5">
<div class="text-center mb-4">
<a href="<?php echo $server_url?>login/index.php" class="mb-4 d-inline-block">
<img src="data:image/svg+xml,%3csvg%20width='62'%20height='67'%20viewBox='0%200%2062%2067'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M30.604%2066.378L0.00805664%2048.1582V35.7825L30.604%2054.0023V66.378Z'%20fill='%23302C4D'/%3e%3cpath%20d='M61.1996%2048.1582L30.604%2066.378V54.0023L61.1996%2035.7825V48.1582Z'%20fill='%23E66239'/%3e%3cpath%20d='M30.5955%200L0%2018.2198V30.5955L30.5955%2012.3757V0Z'%20fill='%23657E92'/%3e%3cpath%20d='M61.191%2018.2198L30.5955%200V12.3757L61.191%2030.5955V18.2198Z'%20fill='%23A3B2BE'/%3e%3cpath%20d='M30.604%2048.8457L0.00805664%2030.6259V18.2498L30.604%2036.47V48.8457Z'%20fill='%23302C4D'/%3e%3cpath%20d='M61.1996%2030.6259L30.604%2048.8457V36.47L61.1996%2018.2498V30.6259Z'%20fill='%23E66239'/%3e%3c/svg%3e"
alt="" width="36">
<span class="ms-2"><img src="<?php echo $server_url?>assets/images/logo.svg" alt=""></span>
</a>
<h1 class="h5 mb-1">Create your account</h1>
<p class="text-muted small mb-0">Fill in the details below to get started</p>
</div>
<!-- Name row -->
<div class="row g-3 mb-3">
<div class="col-6">
<label class="form-label">First Name <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="name" placeholder="First name" required>
</div>
<div class="col-6">
<label class="form-label">Last Name <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="surname" placeholder="Last name" required>
</div>
</div>
<!-- Username -->
<div class="mb-3">
<label class="form-label">Username <span class="text-danger">*</span></label>
<div class="input-group">
<span class="input-group-text"><i class="ti ti-at"></i></span>
<input type="text" class="form-control" id="username"
placeholder="Choose a username" required
oninput="this.value=this.value.toLowerCase().replace(/[^a-z0-9_]/g,'')">
</div>
<div class="form-text">Lowercase letters, numbers and underscores only.</div>
</div>
<!-- Email -->
<div class="mb-3">
<label class="form-label">Email <span class="text-danger">*</span></label>
<input type="email" class="form-control" id="email" placeholder="your@email.com" required>
</div>
<!-- Password -->
<div class="mb-3">
<label class="form-label">Password <span class="text-danger">*</span></label>
<div class="input-group">
<input type="password" class="form-control" id="password"
placeholder="Choose a strong password"
oninput="on_password_input(this.value)">
<button class="btn btn-outline-secondary toggle-pw" type="button" data-target="password">
<i class="ti ti-eye"></i>
</button>
</div>
<div class="mt-2">
<div class="progress" style="height:5px;">
<div id="pw_strength_bar" class="progress-bar"
style="width:0%;transition:width .25s,background-color .25s;border-radius:4px;"></div>
</div>
<div class="d-flex justify-content-between mt-1">
<small id="pw_strength_label" class="fw-semibold" style="white-space:nowrap;">—</small>
<small id="pw_feedback" class="text-muted text-end"></small>
</div>
</div>
</div>
<!-- Confirm password -->
<div class="mb-4">
<label class="form-label">Confirm Password <span class="text-danger">*</span></label>
<div class="input-group">
<input type="password" class="form-control" id="confirm_password"
placeholder="Repeat your password"
oninput="check_confirm_match()">
<button class="btn btn-outline-secondary toggle-pw" type="button" data-target="confirm_password">
<i class="ti ti-eye"></i>
</button>
</div>
<small id="pw_match_label" class="mt-1 d-block"></small>
</div>
<button class="btn btn-primary w-100 mb-3" id="btn_register" onclick="register()">
<i class="ti ti-user-plus me-1"></i>Create Account
</button>
<!-- Success state (hidden until submit) -->
<div id="success_panel" class="d-none text-center py-3">
<div class="mb-3">
<span class="d-inline-flex align-items-center justify-content-center rounded-circle bg-label-success"
style="width:56px;height:56px;">
<i class="ti ti-mail-check fs-3 text-success"></i>
</span>
</div>
<h6 class="mb-1">Check your inbox!</h6>
<p class="text-muted small mb-0">We've sent a verification link to your email address. Click it to activate your account.</p>
</div>
<p class="text-center text-muted small mb-0">
Already have an account?
<a href="<?php echo $server_url?>login/index.php" class="link-primary">Sign in</a>
</p>
</div>
</div>
</div>
<script>
// ═══════════════════════════════════════════════
// State
// ═══════════════════════════════════════════════
const STRENGTH_LEVELS = [
{ label: 'Very weak', color: '#dc3545', pct: 20 },
{ label: 'Weak', color: '#fd7e14', pct: 40 },
{ label: 'Fair', color: '#ffc107', pct: 60 },
{ label: 'Strong', color: '#198754', pct: 80 },
{ label: 'Very strong', color: '#0d6efd', pct: 100 },
];
var pw_score = -1;
var pw_debounce = null;
var pw_xhr = null;
// ═══════════════════════════════════════════════
// On load
// ═══════════════════════════════════════════════
$(function () {
$(document).on('click', '.toggle-pw', function () {
const $input = $('#' + $(this).data('target'));
const isText = $input.attr('type') === 'text';
$input.attr('type', isText ? 'password' : 'text');
$(this).find('i').toggleClass('ti-eye ti-eye-off');
});
});
// ═══════════════════════════════════════════════
// Password strength
// ═══════════════════════════════════════════════
function on_password_input(pw) {
clearTimeout(pw_debounce);
if (!pw) { reset_strength_ui(); check_confirm_match(); return; }
pw_debounce = setTimeout(() => check_strength(pw), 350);
}
function check_strength(pw) {
if (pw_xhr) pw_xhr.abort();
pw_xhr = $.ajax({
url: '<?php echo $server_url?>setting/api/engine/check_password.php',
type: 'POST',
dataType: 'json',
data: { json: JSON.stringify({
otp: '',
company_id: 0,
action: 'read',
password: pw,
})},
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
success: function (res) {
pw_score = res.score ?? -1;
if (pw_score < 0) { reset_strength_ui(); return; }
const lvl = STRENGTH_LEVELS[pw_score];
$('#pw_strength_bar').css({ width: lvl.pct + '%', backgroundColor: lvl.color });
$('#pw_strength_label').text(lvl.label).css('color', lvl.color);
$('#pw_feedback').text(res.feedback || '');
check_confirm_match();
}
});
}
function reset_strength_ui() {
pw_score = -1;
$('#pw_strength_bar').css({ width: '0%', backgroundColor: '' });
$('#pw_strength_label').text('—').css('color', '');
$('#pw_feedback').text('');
}
function check_confirm_match() {
const np = $('#password').val();
const cp = $('#confirm_password').val();
if (!cp) { $('#pw_match_label').text(''); return; }
if (np === cp) {
$('#pw_match_label').html('<span style="color:#198754;">&#10003; Passwords match</span>');
} else {
$('#pw_match_label').html('<span style="color:#dc3545;">&#10007; Passwords do not match</span>');
}
}
// ═══════════════════════════════════════════════
// Register
// ═══════════════════════════════════════════════
function register() {
const name = $('#name').val().trim();
const surname = $('#surname').val().trim();
const username = $('#username').val().trim();
const email = $('#email').val().trim();
const password = $('#password').val();
const confirm = $('#confirm_password').val();
if (!name || !surname || !username || !email || !password || !confirm) {
bootbox.alert('Please fill in all required fields.');
return;
}
if (password !== confirm) {
bootbox.alert('Passwords do not match.');
return;
}
if (pw_score < 3) {
bootbox.alert('Please choose a stronger password.');
return;
}
ajax_request({
url: '<?php echo $server_url?>login/api/engine/register.php',
autoPrepare: false,
data: { json: JSON.stringify({
otp: '',
company_id: 0,
action: 'create',
name: name,
surname: surname,
username: username,
email: email,
password: password,
confirm_password: confirm,
})},
onSuccess: function (r) {
// Hide form, show success panel
$('input, button, .row, .mb-3, .mb-4').hide();
$('#success_panel').removeClass('d-none');
},
});
}
</script>
</body>
</html>
+71
View File
@@ -0,0 +1,71 @@
<?php
require '../session.php';
require '../config.php';
require '../dbconn.php';
require '../assets/utils/db_helpers.php';
$answer = ['success' => 0, 'message' => ''];
$token = trim($_GET['token'] ?? '');
if (!$token) {
header('Location: ' . $server_url . 'login/index.php');
exit;
}
// ── Look up token ─────────────────────────────────────────────
$sth = $pdo1->prepare("
SELECT user_id, name, status, verify_expires_at
FROM user
WHERE verify_token = :token
LIMIT 1
");
$sth->execute([':token' => $token]);
$user = $sth->fetch(PDO::FETCH_ASSOC);
// ── Invalid token ─────────────────────────────────────────────
if (!$user) {
$_SESSION['verify_error'] = 'This verification link is invalid or has already been used.';
header('Location: ' . $server_url . 'login/index.php');
exit;
}
// ── Already verified — check if onboarding still needed ───────
if ($user['status'] === 'active') {
$sth = $pdo1->prepare("
SELECT default_company FROM user WHERE user_id = :id LIMIT 1
");
$sth->execute([':id' => $user['user_id']]);
$default_company = $sth->fetchColumn();
if (empty($default_company)) {
// Verified but never completed onboarding — resume it
$_SESSION['onboarding_user_id'] = (int)$user['user_id'];
$_SESSION['onboarding_name'] = $user['name'];
session_write_close();
header('Location: ' . $server_url . 'login/onboarding.php');
} else {
// Fully set up — just go to login
header('Location: ' . $server_url . 'login/index.php');
}
exit;
}
// ── Expired ───────────────────────────────────────────────────
if (strtotime($user['verify_expires_at']) < time()) {
// Delete the expired pending account
$sth = $pdo1->prepare("DELETE FROM user WHERE user_id = :id AND status = 'pending'");
$sth->execute([':id' => $user['user_id']]);
$_SESSION['verify_error'] = 'This verification link has expired. Please register again.';
header('Location: ' . $server_url . 'login/index.php');
exit;
}
// ── Store user_id in session for onboarding ───────────────────
$_SESSION['onboarding_user_id'] = (int)$user['user_id'];
$_SESSION['onboarding_name'] = $user['name'];
session_write_close();
header('Location: ' . $server_url . 'login/onboarding.php');
exit;?>