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
View File
@@ -43,6 +43,7 @@ build/Release
# Dependency directories
node_modules/
ignores/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
BIN
View File
Binary file not shown.
+54 -70
View File
@@ -11,44 +11,36 @@ class mailer{
if( empty($_db["pdo1"]) ){
exit(json_encode(["success"=>0, "message"=>"Error {$this->new_line}Developer need to define pdo1 - class ap"]));
exit(json_encode(["success"=>0, "message"=>"Error: Developer need to define pdo1 - class mailer"]));
}
if( empty($_db["pdo2"]) ){
exit(json_encode(["success"=>0, "message"=>"Error {$this->new_line}Developer need to define pdo2 - class ap"]));
}
$this->pdo1 = $_db["pdo1"];
$this->pdo2 = $_db["pdo2"];
$this->pdo1 = $_db["pdo1"];
}
public function get_authen($input = array()){
$revise = [];
$revise["company_id"] = $input["company_id"];
if(count($input["smtp"]) > 0){
$revise = [];
$revise["company_id"] = $input["company_id"];
// If SMTP config passed directly, use it (e.g. system default from config.php)
if( !empty($input["smtp"]) && count($input["smtp"]) > 0 ){
return $input["smtp"];
}
$sql = "SELECT * FROM smtp_setting WHERE company_id = :company_id ";
$sth = $this->pdo2->prepare("$sql");
$sth->execute([
":company_id" => $revise["company_id"]
]);
// Otherwise read from company_smtp on pdo1 (wms)
$sth = $this->pdo1->prepare("SELECT * FROM company_smtp WHERE company_id = :company_id");
$sth->execute([":company_id" => $revise["company_id"]]);
$res = $sth->fetch(PDO::FETCH_ASSOC);
if( empty($res) ){
$answer = [];
$answer["success"] = 0;
$answer["message"] = "<b>Error: </b> You haven't set SMTP Server yet<br>----------<br>กรุณาตั้งค่า SMTP Server ก่อนส่ง Email";
$answer["message"] = "<b>Error:</b> You haven't set SMTP Server yet<br>----------<br>กรุณาตั้งค่า SMTP Server ก่อนส่ง Email";
exit(json_encode($answer));
}
return $res;
}
@@ -62,7 +54,6 @@ class mailer{
$revise["require"] = $input["require"];
$revise["input"] = $input["input"];
foreach ($revise["require"] as $key => $item) {
if( !isset($revise["input"][$item]) ){
@@ -75,7 +66,7 @@ class mailer{
private function decrypt($input){
$this->check_required_fields([
"class" => "trdb",
"class" => "mailer",
"function" => "decrypt",
"require" => ["key","data"],
"input" => $input
@@ -87,15 +78,13 @@ class mailer{
public function send_email($input = array()){
$this->check_required_fields([
"class" => "trdb",
"class" => "mailer",
"function" => "send_email",
"require" => ["subject","message","company_id"],
"input" => $input
]);
$revise = [];
$revise["subject"] = $input["subject"];
$revise["message"] = $input["message"];
@@ -106,73 +95,68 @@ class mailer{
$authen = $this->get_authen($input);
require_once dirname(__FILE__).'/phpmailer/vendor/autoload.php';
require_once dirname(__FILE__).'/phpmailer/vendor/autoload.php';
$mail = new PHPMailer(true);
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = false;
$mail->isSMTP();
$mail->CharSet = "UTF-8";
$mail->Host = $authen["server"];
$mail->SMTPAuth = true;
$mail->Timeout = 20;
$mail->Username = $authen["username"];
$mail->Password = $this->decrypt(["data"=>$authen["password"],"key"=>$revise["key"]]);
try {
$mail->SMTPDebug = false;
$mail->isSMTP();
$mail->CharSet = "UTF-8";
$mail->Host = $authen["server"];
$mail->SMTPAuth = true;
$mail->Timeout = 20;
$mail->Username = $authen["username"];
$mail->Password = $this->decrypt(["data"=>$authen["password"],"key"=>$revise["key"]]);
if ($authen["port"] === "465") {
$port = (string)$authen["port"];
if ($port === "465") {
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
} elseif ($authen["port"] === "587" || $authen["port"] === "25") {
} elseif ($port === "587" || $port === "25") {
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
} else {
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // default fallback
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
}
$mail->Port = $authen["port"];
$mail->Port = $authen["port"];
if(true){
$mail->SMTPOptions = [
'socket' => ['bindto' => '0.0.0.0:0']
];
$mail->SMTPOptions = [
'socket' => ['bindto' => '0.0.0.0:0']
];
// Sender
$from_email = !empty($authen["from_email"]) ? $authen["from_email"] : $authen["username"];
$from_name = !empty($revise["channel_name"]) ? $revise["channel_name"]
: (!empty($authen["from_name"]) ? $authen["from_name"] : $authen["username"]);
$mail->setFrom($from_email, $from_name);
$des = explode(",", $revise["to"]);
foreach ($des as $key => $value) {
$mail->addAddress(trim($value));
}
//Recipients
$mail->setFrom($authen["username"], $revise["channel_name"]);
$des = explode(",", $revise["to"]);
foreach ($des as $key => $value) {
$mail->addAddress(trim($value));
}
//Content
$mail->isHTML(true);
$mail->Subject = $revise["subject"];
$mail->Body = nl2br($revise["message"]);
$mail->AltBody = $revise["message"];
$mail->send();
}
catch (phpmailerException $e) {
$mail->isHTML(true);
$mail->Subject = $revise["subject"];
$mail->Body = nl2br($revise["message"]);
$mail->AltBody = $revise["message"];
$mail->send();
}
catch (phpmailerException $e) {
$answer = [];
$answer["success"] = 0;
$answer["message"] = "<b>Error1</b>: ".nl2br($e->errorMessage());
exit(json_encode($answer));
}
catch (Exception $e) {
catch (Exception $e) {
$answer = [];
$answer["success"] = 0;
$answer["message"] = "<b>Error2</b>: ".nl2br($mail->ErrorInfo);
exit(json_encode($answer));
}
}
}
}
?>
?>
-2
View File
@@ -31,8 +31,6 @@ class db_statement extends PDOStatement {
// Perform logging here. PDO object is accessible
// from $this->pdo.
echo $this->pdo->last_query();
if (!is_array($args)) {
$args = func_get_args();
}else{
+14 -1
View File
@@ -3,7 +3,7 @@
?>
<!-- SIDEBAR -->
<aside id="sidebar" class="sidebar overflow-y-auto">
<aside id="sidebar" class="sidebar overflow-y-auto d-flex flex-column">
<div class="logo-area">
<a href="<?php echo $server_url?>index.php" class="d-inline-flex">
<img
@@ -56,5 +56,18 @@
</a>
</li>
<!-- Back -->
<li class="nav-text-space mt-2">
<small class="nav-text text-muted">Navigation</small>
</li>
<li>
<a class="nav-link" href="<?php echo $server_url?>dashboard/index.php">
<i class="ti ti-arrow-left"></i>
<span class="nav-text">Back to App</span>
</a>
</li>
</ul>
</aside>
BIN
View File
Binary file not shown.
+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;?>
+13
View File
@@ -0,0 +1,13 @@
<?php
// app/session.php
if (session_status() === PHP_SESSION_NONE) {
session_set_cookie_params([
'lifetime' => 0,
'path' => '/wms/',
'domain' => '',
'secure' => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on',
'httponly' => true,
'samesite' => 'Lax',
]);
session_start();
}
+144
View File
@@ -0,0 +1,144 @@
<?php
session_start();
require '../../../assets/utils/db_auth.php';
// ─── Role guard: only owner/admin ────────────────────────────────────────
$sth = $pdo1->prepare("
SELECT role FROM company_map_user
WHERE company_id = :company_id AND user_id = :user_id
LIMIT 1
");
$sth->execute([':company_id' => $company_id, ':user_id' => $user_id]);
db_check($sth, $answer);
if (!in_array($sth->fetchColumn(), ['owner', 'admin'], true)) {
$answer['message'] = 'You do not have permission to change SMTP settings.';
http_response_code(403);
exit(json_encode($answer));
}
// ─── Encrypt password — same method/key/iv as config.php ─────────────────
function encrypt_password(string $plain): string {
global $pinkey, $method, $iv;
return openssl_encrypt($plain, $method, $pinkey, 0, $iv);
}
try {
$server = trim($data['smtp_host'] ?? '');
$port = trim($data['smtp_port'] ?? '587');
$username = trim($data['smtp_username'] ?? '');
$raw_pass = $data['smtp_password'] ?? ''; // blank = keep current
$from_name = trim($data['smtp_from_name'] ?? '');
$from_email = trim($data['smtp_from_email'] ?? '');
$encryption = trim($data['smtp_encryption'] ?? 'tls');
if (!$server || !$username) {
$answer['message'] = 'SMTP host and username are required.';
http_response_code(422);
exit(json_encode($answer));
}
if (!in_array($port, ['25', '465', '587'], true)) $port = '587';
if (!in_array($encryption, ['tls', 'ssl', 'none'], true)) $encryption = 'tls';
// Check if row already exists (uses pdo1 — company_smtp lives in wms2)
$sth = $pdo1->prepare("
SELECT smtp_id FROM company_smtp
WHERE company_id = :company_id LIMIT 1
");
$sth->execute([':company_id' => $company_id]);
db_check($sth, $answer);
$existing_id = $sth->fetchColumn();
if ($existing_id) {
if ($raw_pass !== '') {
$sth = $pdo1->prepare("
UPDATE company_smtp SET
server = :server,
port = :port,
username = :username,
password = :password,
from_name = :from_name,
from_email = :from_email,
encryption = :encryption,
updated_at = NOW()
WHERE smtp_id = :smtp_id
");
$sth->execute([
':server' => $server,
':port' => $port,
':username' => $username,
':password' => encrypt_password($raw_pass),
':from_name' => $from_name,
':from_email' => $from_email,
':encryption' => $encryption,
':smtp_id' => $existing_id,
]);
} else {
// Keep existing password — don't touch it
$sth = $pdo1->prepare("
UPDATE company_smtp SET
server = :server,
port = :port,
username = :username,
from_name = :from_name,
from_email = :from_email,
encryption = :encryption,
updated_at = NOW()
WHERE smtp_id = :smtp_id
");
$sth->execute([
':server' => $server,
':port' => $port,
':username' => $username,
':from_name' => $from_name,
':from_email' => $from_email,
':encryption' => $encryption,
':smtp_id' => $existing_id,
]);
}
} else {
// New record — password required
if ($raw_pass === '') {
$answer['message'] = 'Password is required for a new SMTP configuration.';
http_response_code(422);
exit(json_encode($answer));
}
$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' => $server,
':port' => $port,
':username' => $username,
':password' => encrypt_password($raw_pass),
':from_name' => $from_name,
':from_email' => $from_email,
':encryption' => $encryption,
]);
}
db_check($sth, $answer);
$answer['success'] = 1;
$answer['message'] = 'SMTP settings saved.';
} catch (Exception $e) {
$answer['message'] = 'Failed to save SMTP settings.';
http_response_code(500);
}
exit(json_encode($answer));
?>
+214
View File
@@ -0,0 +1,214 @@
<?php
session_start();
require '../../../assets/utils/db_auth.php';
// ─── Role guard: only owner/admin can manage users ────────────────────────
$sth = $pdo1->prepare("
SELECT role FROM company_map_user
WHERE company_id = :company_id AND user_id = :user_id
LIMIT 1
");
$sth->execute([':company_id' => $company_id, ':user_id' => $user_id]);
db_check($sth, $answer);
$caller_role = $sth->fetchColumn();
if (!in_array($caller_role, ['owner', 'admin'], true)) {
$answer['message'] = 'You do not have permission to manage users.';
http_response_code(403);
exit(json_encode($answer));
}
$action = $data['action'] ?? '';
try {
// ══════════════════════════════════════════════════════════════════════
// CREATE — invite a user by email
// ══════════════════════════════════════════════════════════════════════
if ($action === 'create') {
$invite_email = strtolower(trim($data['invite_email'] ?? ''));
$invite_role = trim($data['invite_role'] ?? '');
if (!filter_var($invite_email, FILTER_VALIDATE_EMAIL)) {
$answer['message'] = 'Invalid email address.';
http_response_code(422);
exit(json_encode($answer));
}
$allowed_roles = ['admin', 'staff', 'viewer'];
if (!in_array($invite_role, $allowed_roles, true)) {
$answer['message'] = 'Invalid role selected.';
http_response_code(422);
exit(json_encode($answer));
}
// Look up user by email
$sth = $pdo1->prepare("SELECT user_id, email FROM user WHERE email = :email LIMIT 1");
$sth->execute([':email' => $invite_email]);
db_check($sth, $answer);
$target = $sth->fetch(PDO::FETCH_ASSOC);
if (!$target) {
$answer['message'] = 'No registered account found with that email address.';
http_response_code(404);
exit(json_encode($answer));
}
$target_user_id = (int)$target['user_id'];
// Prevent inviting self
if ($target_user_id === (int)$user_id) {
$answer['message'] = 'You cannot invite yourself.';
http_response_code(422);
exit(json_encode($answer));
}
// Check if already mapped to this company
$sth = $pdo1->prepare("
SELECT map_id FROM company_map_user
WHERE company_id = :company_id AND user_id = :user_id
LIMIT 1
");
$sth->execute([':company_id' => $company_id, ':user_id' => $target_user_id]);
db_check($sth, $answer);
$existing = $sth->fetch(PDO::FETCH_ASSOC);
if ($existing) {
$answer['message'] = 'This user is already a member of your company.';
http_response_code(409);
exit(json_encode($answer));
}
$sth = $pdo1->prepare("
INSERT INTO company_map_user
(company_id, user_id, role, created_at)
VALUES
(:company_id, :user_id, :role, NOW())
");
$sth->execute([
':company_id' => $company_id,
':user_id' => $target_user_id,
':role' => $invite_role,
]);
db_check($sth, $answer);
$answer['success'] = 1;
$answer['message'] = htmlspecialchars($target['email']) . ' has been added to your company.';
// ══════════════════════════════════════════════════════════════════════
// UPDATE — change a user's role
// ══════════════════════════════════════════════════════════════════════
} elseif ($action === 'update') {
$map_id = (int)($data['map_id'] ?? 0);
$new_role = trim($data['role'] ?? '');
$allowed_roles = ['admin', 'staff', 'viewer'];
if (!$map_id || !in_array($new_role, $allowed_roles, true)) {
$answer['message'] = 'Invalid request.';
http_response_code(422);
exit(json_encode($answer));
}
// Verify map belongs to this company and is not the owner
$sth = $pdo1->prepare("
SELECT role FROM company_map_user
WHERE map_id = :map_id AND company_id = :company_id
LIMIT 1
");
$sth->execute([':map_id' => $map_id, ':company_id' => $company_id]);
db_check($sth, $answer);
$target_role = $sth->fetchColumn();
if ($target_role === false) {
$answer['message'] = 'User not found.';
http_response_code(404);
exit(json_encode($answer));
}
if ($target_role === 'owner') {
$answer['message'] = 'Owner role cannot be changed.';
http_response_code(403);
exit(json_encode($answer));
}
$sth = $pdo1->prepare("
UPDATE company_map_user
SET role = :role
WHERE map_id = :map_id AND company_id = :company_id
");
$sth->execute([
':role' => $new_role,
':map_id' => $map_id,
':company_id' => $company_id,
]);
db_check($sth, $answer);
$answer['success'] = 1;
$answer['message'] = 'Role updated successfully.';
// ══════════════════════════════════════════════════════════════════════
// DELETE — remove user from company
// ══════════════════════════════════════════════════════════════════════
} elseif ($action === 'delete') {
$map_id = (int)($data['map_id'] ?? 0);
if (!$map_id) {
$answer['message'] = 'Invalid request.';
http_response_code(422);
exit(json_encode($answer));
}
// Verify map belongs to this company, and isn't the owner
$sth = $pdo1->prepare("
SELECT role, user_id FROM company_map_user
WHERE map_id = :map_id AND company_id = :company_id
LIMIT 1
");
$sth->execute([':map_id' => $map_id, ':company_id' => $company_id]);
db_check($sth, $answer);
$row = $sth->fetch(PDO::FETCH_ASSOC);
if (!$row) {
$answer['message'] = 'User not found.';
http_response_code(404);
exit(json_encode($answer));
}
if ($row['role'] === 'owner') {
$answer['message'] = 'The owner cannot be removed.';
http_response_code(403);
exit(json_encode($answer));
}
// Prevent removing yourself
if ((int)$row['user_id'] === (int)$user_id) {
$answer['message'] = 'You cannot remove yourself.';
http_response_code(403);
exit(json_encode($answer));
}
// Hard delete — just remove the row
$sth = $pdo1->prepare("
DELETE FROM company_map_user
WHERE map_id = :map_id AND company_id = :company_id
");
$sth->execute([':map_id' => $map_id, ':company_id' => $company_id]);
db_check($sth, $answer);
$answer['success'] = 1;
$answer['message'] = 'User has been removed from this company.';
} else {
$answer['message'] = 'Unknown action.';
http_response_code(400);
}
} catch (Exception $e) {
$answer['message'] = 'An error occurred. Please try again.';
http_response_code(500);
}
exit(json_encode($answer));
?>
+33
View File
@@ -0,0 +1,33 @@
<?php
session_start();
require '../../../assets/utils/db_auth.php';
try {
$sth = $pdo1->prepare("
SELECT
server,
port,
username,
from_name,
from_email,
encryption
FROM company_smtp
WHERE company_id = :company_id
LIMIT 1
");
$sth->execute([':company_id' => $company_id]);
db_check($sth, $answer);
$row = $sth->fetch(PDO::FETCH_ASSOC);
$answer['success'] = 1;
$answer['output'] = $row ?: null; // null = not configured yet
} catch (Exception $e) {
$answer['message'] = $e->getMessage();
http_response_code(500);
}
exit(json_encode($answer));
?>
+38
View File
@@ -0,0 +1,38 @@
<?php
session_start();
require '../../../assets/utils/db_auth.php';
try {
// Fetch all users mapped to this company, joined with user profile
$sth = $pdo1->prepare("
SELECT
m.map_id,
m.role,
m.created_at,
u.user_id,
u.username,
u.name,
u.surname,
u.email,
u.profile_picture
FROM company_map_user m
JOIN user u ON u.user_id = m.user_id
WHERE m.company_id = :company_id
ORDER BY
FIELD(m.role, 'owner', 'admin', 'staff', 'viewer'),
u.name ASC
");
$sth->execute([':company_id' => $company_id]);
db_check($sth, $answer);
$answer['success'] = 1;
$answer['output'] = $sth->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
$answer['message'] = 'Failed to load users.';
http_response_code(500);
}
exit(json_encode($answer));
?>
+50
View File
@@ -0,0 +1,50 @@
<?php
session_start();
require '../../../assets/utils/db_auth.php';
try {
$keyword = trim($data['keyword'] ?? '');
if ($keyword === '') {
$answer['success'] = 1;
$answer['result'] = [];
exit(json_encode($answer));
}
$like = '%' . $keyword . '%';
// Search users by email NOT already active/pending in this company
$sth = $pdo1->prepare("
SELECT
u.user_id,
u.username,
u.name,
u.surname,
u.email
FROM user u
WHERE
u.email LIKE :kw
AND u.user_id NOT IN (
SELECT user_id FROM company_map_user
WHERE company_id = :company_id
)
ORDER BY u.email ASC
LIMIT 10
");
$sth->execute([
':kw' => $like,
':company_id' => $company_id,
]);
db_check($sth, $answer);
$answer['success'] = 1;
$answer['result'] = $sth->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
$answer['message'] = 'Search failed.';
http_response_code(500);
}
exit(json_encode($answer));
?>
+55
View File
@@ -0,0 +1,55 @@
<?php
session_start();
require '../../../assets/utils/db_auth.php';
try {
$to = trim($data['test_email'] ?? '');
if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
$answer['message'] = 'Invalid recipient email address.';
http_response_code(422);
exit(json_encode($answer));
}
// Fetch from_name / channel_name for the sender display
$sth = $pdo1->prepare("
SELECT from_name FROM company_smtp
WHERE company_id = :company_id LIMIT 1
");
$sth->execute([':company_id' => $company_id]);
db_check($sth, $answer);
$row = $sth->fetch(PDO::FETCH_ASSOC);
if (!$row) {
$answer['message'] = 'No SMTP configuration found. Please save your settings first.';
http_response_code(422);
exit(json_encode($answer));
}
$channel_name = $row['from_name'] ?: 'WMS System';
// Use existing mailer — it reads company_smtp via pdo1 automatically
require_once $include_url . 'assets/utils/module/mailer.php';
$mailer = new mailer(['pdo1' => $pdo1]);
$mailer->send_email([
'company_id' => $company_id,
'smtp' => [], // empty = mailer reads from company_smtp
'to' => $to,
'subject' => 'SMTP Test — WMS',
'message' => "This is a test email from your WMS SMTP configuration.\n\nIf you received this, your SMTP settings are working correctly.",
'channel_name' => $channel_name,
'key' => $pinkey,
]);
$answer['success'] = 1;
$answer['message'] = 'Test email sent to ' . htmlspecialchars($to) . '.';
} catch (Exception $e) {
$answer['message'] = 'Failed to send test email: ' . $e->getMessage();
http_response_code(500);
}
exit(json_encode($answer));
?>
+286
View File
@@ -0,0 +1,286 @@
<?php
session_start();
require '../config.php';
require '../include_header.php';
?>
<body>
<?php require '../include_topbar.php'; ?>
<?php require '../include_setting_sidebar.php'; ?>
<main id="content" class="content py-15">
<div class="container-fluid">
<!-- Page header -->
<div class="row">
<div class="col-12">
<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-6 gap-3">
<div>
<h1 class="fs-3 mb-1">SMTP Setting</h1>
<p class="mb-0">Configure outgoing email server for your company</p>
</div>
</div>
</div>
</div>
<div class="row g-5">
<!-- LEFT: info panel -->
<div class="col-lg-3 col-12">
<div class="card">
<div class="card-body p-6">
<div class="text-center mb-4">
<span class="d-inline-flex align-items-center justify-content-center rounded-circle bg-label-primary mb-3"
style="width:56px;height:56px;">
<i class="ti ti-mail-cog fs-3"></i>
</span>
<h6 class="mb-1">Email Server</h6>
<p class="text-muted small mb-0">Used for system notifications and invitations</p>
</div>
<hr class="my-4">
<div id="smtp_status_panel">
<div class="d-flex align-items-center gap-2 mb-2">
<span id="status_dot" class="rounded-circle d-inline-block" style="width:10px;height:10px;background:#adb5bd;flex-shrink:0;"></span>
<span id="status_label" class="small fw-semibold text-muted">Not configured</span>
</div>
<div class="small text-muted" id="status_host">—</div>
</div>
<hr class="my-4">
<div class="small text-muted">
<div class="fw-semibold mb-2">Common SMTP hosts</div>
<div class="mb-1"><i class="ti ti-brand-gmail me-1"></i>smtp.gmail.com : 587</div>
<div class="mb-1"><i class="ti ti-brand-office me-1"></i>smtp.office365.com : 587</div>
<div class="mb-1"><i class="ti ti-mail me-1"></i>smtp.mail.yahoo.com : 587</div>
</div>
</div>
</div>
</div>
<!-- RIGHT: form -->
<div class="col-lg-9 col-12">
<div class="card">
<div class="card-body p-6">
<h2 class="fs-5 mb-4">Server Configuration</h2>
<div class="row">
<div class="col-md-8 mb-3">
<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 mb-3">
<label class="form-label">Port <span class="text-danger">*</span></label>
<select class="form-select" id="smtp_port">
<option value="587">587 — TLS (recommended)</option>
<option value="465">465 — SSL</option>
<option value="25">25 — Plain</option>
</select>
</div>
<div class="col-md-6 mb-3">
<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 mb-3">
<label class="form-label">Password</label>
<div class="input-group">
<input type="password" class="form-control" id="smtp_password"
placeholder="Leave blank to keep current">
<button class="btn btn-outline-secondary toggle-pw" type="button"
data-target="smtp_password">
<i class="ti ti-eye"></i>
</button>
</div>
<div class="form-text">Leave blank to keep the existing password.</div>
</div>
<div class="col-md-6 mb-3">
<label class="form-label">Sender Name</label>
<input type="text" class="form-control" id="smtp_from_name"
placeholder="e.g. My Company">
</div>
<div class="col-md-6 mb-3">
<label class="form-label">Sender Email</label>
<input type="email" class="form-control" id="smtp_from_email"
placeholder="noreply@company.com">
</div>
<div class="col-12 mb-3">
<label class="form-label">Encryption</label>
<div class="d-flex gap-4 mt-1">
<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>
<!-- Test connection -->
<div class="border rounded p-4 mb-4 bg-light">
<div class="fw-semibold mb-2"><i class="ti ti-plug-connected me-1"></i>Test Connection</div>
<p class="text-muted small mb-3">Send a test email to verify your SMTP settings before saving.</p>
<div class="d-flex gap-2 align-items-center flex-wrap">
<input type="email" class="form-control form-control-sm"
id="test_email" placeholder="Send test to…"
style="max-width:260px;">
<button class="btn btn-sm btn-outline-primary" onclick="test_smtp()">
<i class="ti ti-send me-1"></i>Send Test
</button>
<span id="test_result" class="small ms-1"></span>
</div>
</div>
</div>
<div class="card-footer d-flex justify-content-end gap-2">
<button class="btn btn-ghost-secondary" onclick="load_smtp()">
<i class="ti ti-refresh me-1"></i>Reset
</button>
<button class="btn btn-primary" onclick="save_smtp()">
<i class="ti ti-device-floppy me-1"></i>Save Changes
</button>
</div>
</div>
</div>
</div>
</div>
<?php require '../include_ending.php'; ?>
</main>
<script>
// ═══════════════════════════════════════════════
// State
// ═══════════════════════════════════════════════
const api = '<?php echo $server_url?>setting/api/engine/';
// ═══════════════════════════════════════════════
// On load
// ═══════════════════════════════════════════════
$(function () {
load_smtp();
// Toggle show/hide password
$(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');
});
});
// ═══════════════════════════════════════════════
// Load
// ═══════════════════════════════════════════════
function load_smtp() {
return ajax_request({
url: api + 'retrieve_smtp.php',
autoPrepare: true,
checkRequired: 0,
action: 'read',
onSuccess: function (r) {
const s = r.output;
if (!s) return; // no config yet — leave form blank
$('#smtp_host').val(s.server || '');
$('#smtp_port').val(s.port || '587');
$('#smtp_username').val(s.username || '');
$('#smtp_password').val(''); // never prefill password
$('#smtp_from_name').val(s.from_name || '');
$('#smtp_from_email').val(s.from_email || '');
$(`input[name="smtp_encryption"][value="${s.encryption || 'tls'}"]`).prop('checked', true);
update_status_panel(s);
},
});
}
// ═══════════════════════════════════════════════
// Save
// ═══════════════════════════════════════════════
function save_smtp() {
const encryption = $('input[name="smtp_encryption"]:checked').val();
ajax_request({
url: api + 'manage_smtp.php',
autoPrepare: true,
checkRequired: 0,
action: 'manage',
data: { smtp_encryption: encryption },
onSuccess: function (r) {
bootbox.alert('SMTP settings saved.');
load_smtp();
},
});
}
// ═══════════════════════════════════════════════
// Test connection
// ═══════════════════════════════════════════════
function test_smtp() {
const to = $('#test_email').val().trim();
if (!to) {
$('#test_result').html('<span class="text-danger">Enter a recipient email.</span>');
return;
}
$('#test_result').html('<span class="text-muted"><i class="ti ti-loader-2 me-1"></i>Sending…</span>');
ajax_request({
url: api + 'test_smtp.php',
autoPrepare: true,
checkRequired: 0,
action: 'read',
data: { test_email: to },
onSuccess: function (r) {
$('#test_result').html('<span class="text-success"><i class="ti ti-circle-check me-1"></i>' + (r.message || 'Test email sent!') + '</span>');
},
onError: function (r) {
$('#test_result').html('<span class="text-danger"><i class="ti ti-circle-x me-1"></i>' + (r.message || 'Failed.') + '</span>');
},
});
}
// ═══════════════════════════════════════════════
// Status panel
// ═══════════════════════════════════════════════
function update_status_panel(s) {
if (s && s.server) {
$('#status_dot').css('background', '#198754');
$('#status_label').text('Configured').removeClass('text-muted').addClass('text-success');
$('#status_host').text(s.server + ' : ' + (s.port || '587'));
} else {
$('#status_dot').css('background', '#adb5bd');
$('#status_label').text('Not configured').addClass('text-muted').removeClass('text-success');
$('#status_host').text('—');
}
}
</script>
</body>
</html>
+424
View File
@@ -0,0 +1,424 @@
<?php
session_start();
require '../config.php';
require '../include_header.php';
?>
<body>
<?php require '../include_topbar.php'; ?>
<?php require '../include_setting_sidebar.php'; ?>
<main id="content" class="content py-15">
<div class="container-fluid">
<!-- Page header -->
<div class="row">
<div class="col-12">
<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-6 gap-3">
<div>
<h1 class="fs-3 mb-1">Users Access</h1>
<p class="mb-0">Manage team members and their roles in your company</p>
</div>
<div class="d-flex gap-2">
<button class="btn btn-primary" onclick="open_invite_modal()">
<i class="ti ti-user-plus me-1"></i>Add User
</button>
</div>
</div>
</div>
</div>
<!-- Users table card -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body p-0">
<!-- Toolbar -->
<div class="d-flex align-items-center gap-3 px-4 py-3 border-bottom">
<div class="flex-grow-1" style="max-width:320px;">
<div class="input-group input-group-sm">
<span class="input-group-text bg-transparent border-end-0">
<i class="ti ti-search text-muted"></i>
</span>
<input type="text" id="search_input" class="form-control border-start-0 ps-0"
placeholder="Search by name or email…" oninput="filter_table()">
</div>
</div>
<div>
<select id="filter_role" class="form-select form-select-sm" onchange="filter_table()" style="min-width:130px;">
<option value="">All roles</option>
<option value="owner">Owner</option>
<option value="admin">Admin</option>
<option value="staff">Staff</option>
<option value="viewer">Viewer</option>
</select>
</div>
</div>
<!-- Table -->
<div class="table-responsive">
<table class="table table-hover align-middle mb-0" id="users_table">
<thead class="table-light">
<tr>
<th class="ps-4">User</th>
<th>Email</th>
<th>Role</th>
<th>Joined</th>
<th class="text-end pe-4">Actions</th>
</tr>
</thead>
<tbody id="users_tbody">
<tr>
<td colspan="5" class="text-center py-5 text-muted">
<i class="ti ti-loader-2 fs-2 d-block mb-2"></i>Loading…
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<?php require '../include_ending.php'; ?>
</main>
<!-- ═══════════════════════════════════════════════
INVITE MODAL
═══════════════════════════════════════════════ -->
<div class="modal fade" id="inviteModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><i class="ti ti-user-plus me-2"></i>Add User</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label class="form-label">Email Address <span class="text-danger">*</span></label>
<input type="email" class="form-control" id="invite_email"
placeholder="user@example.com">
<div class="form-text">Enter the email address of a registered user.</div>
</div>
<div class="mb-3">
<label class="form-label">Role <span class="text-danger">*</span></label>
<select class="form-select" id="invite_role" required>
<option value="">— Select role —</option>
<option value="admin">Admin — full access except billing</option>
<option value="staff">Staff — manage inventory &amp; orders</option>
<option value="viewer">Viewer — read-only access</option>
</select>
</div>
<div class="alert alert-light border small mb-0">
<div class="fw-semibold mb-1">Role permissions</div>
<ul class="mb-0 ps-3">
<li><strong>Admin</strong> — manage users, settings, all modules</li>
<li><strong>Staff</strong> — manage inventory, ICS, orders</li>
<li><strong>Viewer</strong> — view-only access across all modules</li>
</ul>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-ghost-secondary" data-bs-dismiss="modal">Cancel</button>
<button class="btn btn-primary" onclick="send_invite()">
<i class="ti ti-user-plus me-1"></i>Add User
</button>
</div>
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════════
EDIT ROLE MODAL
═══════════════════════════════════════════════ -->
<div class="modal fade" id="editRoleModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><i class="ti ti-shield-half me-2"></i>Change Role</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<input type="hidden" id="edit_map_id">
<div class="d-flex align-items-center gap-3 mb-4">
<img id="edit_avatar" src="" alt=""
class="rounded-circle border" style="width:48px;height:48px;object-fit:cover;">
<div>
<div class="fw-semibold" id="edit_username">—</div>
<div class="text-muted small" id="edit_email_display">—</div>
</div>
</div>
<div class="mb-3">
<label class="form-label">Role</label>
<select class="form-select" id="edit_role">
<option value="admin">Admin</option>
<option value="staff">Staff</option>
<option value="viewer">Viewer</option>
</select>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-ghost-secondary" data-bs-dismiss="modal">Cancel</button>
<button class="btn btn-primary" onclick="save_role()">
<i class="ti ti-device-floppy me-1"></i>Save
</button>
</div>
</div>
</div>
</div>
<script>
// ═══════════════════════════════════════════════
// State
// ═══════════════════════════════════════════════
const api = '<?php echo $server_url?>setting/api/engine/';
const img_base = '<?php echo $server_url?>uploads/profile/';
const avatar_ph = '<?php echo $server_url?>assets/images/logo.svg';
let _users_data = []; // full list from server
// ═══════════════════════════════════════════════
// On load
// ═══════════════════════════════════════════════
$(function () {
load_users();
});
// ═══════════════════════════════════════════════
// Load users
// ═══════════════════════════════════════════════
function load_users() {
return ajax_request({
url: api + 'retrieve_users.php',
autoPrepare: true,
checkRequired: 0,
action: 'read',
onSuccess: function (r) {
_users_data = r.output || [];
render_table(_users_data);
},
});
}
// ═══════════════════════════════════════════════
// Render table
// ═══════════════════════════════════════════════
function render_table(rows) {
const tbody = $('#users_tbody');
if (!rows.length) {
tbody.html(`
<tr>
<td colspan="5" class="text-center py-5 text-muted">
<i class="ti ti-users-group fs-2 d-block mb-2"></i>No users found.
</td>
</tr>`);
return;
}
const html = rows.map(u => {
const avatar = u.profile_picture
? `<img src="${img_base}${u.profile_picture}" class="rounded-circle border" style="width:36px;height:36px;object-fit:cover;" alt="">`
: `<span class="avatar-initials rounded-circle d-inline-flex align-items-center justify-content-center bg-light border fw-semibold text-secondary"
style="width:36px;height:36px;font-size:13px;">${initials(u.name, u.surname)}</span>`;
const role_badge = role_html(u.role);
const joined = u.created_at
? new Date(u.created_at).toLocaleDateString('en-GB', {day:'2-digit', month:'short', year:'numeric'})
: '—';
// Build action buttons — owner cannot be edited or removed
let actions = '';
if (u.role !== 'owner') {
actions += `
<button class="btn btn-sm btn-ghost-secondary" title="Change role"
onclick="open_edit_modal(${u.map_id})">
<i class="ti ti-shield-half"></i>
</button>`;
actions += `
<button class="btn btn-sm btn-ghost-danger" title="Remove user"
onclick="remove_user(${u.map_id}, '${esc(u.name)} ${esc(u.surname)}')">
<i class="ti ti-user-minus"></i>
</button>`;
}
return `
<tr data-role="${u.role}"
data-search="${esc(u.name)} ${esc(u.surname)} ${esc(u.email)}">
<td class="ps-4">
<div class="d-flex align-items-center gap-3">
${avatar}
<div>
<div class="fw-semibold lh-sm">${esc(u.name)} ${esc(u.surname)}</div>
<div class="small" style="color:#6c757d;">@${esc(u.username)}</div>
</div>
</div>
</td>
<td style="color:#495057;">${esc(u.email)}</td>
<td>${role_badge}</td>
<td style="color:#495057;">${joined}</td>
<td class="text-end pe-4">
<div class="d-flex justify-content-end gap-1">${actions}</div>
</td>
</tr>`;
}).join('');
tbody.html(html);
}
// ═══════════════════════════════════════════════
// Filter (client-side)
// ═══════════════════════════════════════════════
function filter_table() {
const kw = $('#search_input').val().toLowerCase();
const role = $('#filter_role').val();
const filtered = _users_data.filter(u => {
const haystack = `${u.name} ${u.surname} ${u.email}`.toLowerCase();
return (!kw || haystack.includes(kw))
&& (!role || u.role === role);
});
render_table(filtered);
}
// ═══════════════════════════════════════════════
// Invite
// ═══════════════════════════════════════════════
function open_invite_modal() {
$('#invite_email').val('').removeClass('is-invalid is-valid');
$('#invite_role').val('').removeClass('is-invalid');
new bootstrap.Modal('#inviteModal').show();
}
function send_invite() {
const email = $('#invite_email').val().trim();
const role = $('#invite_role').val();
let valid = true;
if (!email) {
$('#invite_email').addClass('is-invalid');
valid = false;
} else {
$('#invite_email').removeClass('is-invalid');
}
if (!role) {
$('#invite_role').addClass('is-invalid');
valid = false;
} else {
$('#invite_role').removeClass('is-invalid');
}
if (!valid) return;
ajax_request({
url: api + 'manage_users.php',
autoPrepare: true,
checkRequired: 0,
action: 'create',
data: { invite_email: email, invite_role: role },
onSuccess: function (r) {
bootstrap.Modal.getInstance('#inviteModal')?.hide();
bootbox.alert(r.message || 'Invitation sent.');
load_users();
},
});
}
// ═══════════════════════════════════════════════
// Edit role
// ═══════════════════════════════════════════════
function open_edit_modal(map_id) {
const u = _users_data.find(x => x.map_id == map_id);
if (!u) return;
$('#edit_map_id').val(map_id);
$('#edit_username').text(`${u.name} ${u.surname}`);
$('#edit_email_display').text(u.email);
$('#edit_role').val(u.role);
$('#edit_avatar').attr('src', u.profile_picture ? img_base + u.profile_picture : avatar_ph);
new bootstrap.Modal('#editRoleModal').show();
}
function save_role() {
ajax_request({
url: api + 'manage_users.php',
autoPrepare: true,
checkRequired: 0,
action: 'update',
data: { map_id: $('#edit_map_id').val(), role: $('#edit_role').val() },
onSuccess: function (r) {
bootstrap.Modal.getInstance('#editRoleModal')?.hide();
bootbox.alert(r.message || 'Role updated.');
load_users();
},
});
}
// ═══════════════════════════════════════════════
// Remove user
// ═══════════════════════════════════════════════
function remove_user(map_id, display_name) {
bootbox.confirm(`Remove <strong>${display_name}</strong> from this company?`, function (ok) {
if (!ok) return;
ajax_request({
url: api + 'manage_users.php',
autoPrepare: true,
checkRequired: 0,
action: 'delete',
data: { map_id: map_id },
onSuccess: function (r) {
bootbox.alert(r.message || 'User removed.');
load_users();
},
});
});
}
// ═══════════════════════════════════════════════
// Helpers
// ═══════════════════════════════════════════════
function initials(name, surname) {
return ((name?.[0] || '') + (surname?.[0] || '')).toUpperCase() || '?';
}
function esc(str) {
if (!str) return '';
return String(str)
.replace(/&/g,'&amp;').replace(/</g,'&lt;')
.replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
function role_html(role) {
const map = {
owner: ['bg-dark', 'ti-crown', 'Owner'],
admin: ['bg-primary', 'ti-shield-check','Admin'],
staff: ['bg-info', 'ti-tool', 'Staff'],
viewer: ['bg-secondary','ti-eye', 'Viewer'],
};
const [cls, icon, label] = map[role] || ['bg-label-secondary','ti-user','Unknown'];
return `<span class="badge ${cls}"><i class="ti ${icon} me-1"></i>${label}</span>`;
}
</script>
</body>
</html>