Add OTP email login to business portal
Replace default password login with email-based OTP flow. User enters email, receives 6-digit code, enters it to log in. Password login retained as fallback via link. On dev, magic OTP code is shown directly for easy testing. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
parent
77fb8b9780
commit
db90d9911a
4 changed files with 577 additions and 38 deletions
|
|
@ -103,6 +103,8 @@ if (len(request._api_path)) {
|
||||||
if (findNoCase("/api/auth/verifyOTP.cfm", request._api_path)) request._api_isPublic = true;
|
if (findNoCase("/api/auth/verifyOTP.cfm", request._api_path)) request._api_isPublic = true;
|
||||||
if (findNoCase("/api/auth/loginOTP.cfm", request._api_path)) request._api_isPublic = true;
|
if (findNoCase("/api/auth/loginOTP.cfm", request._api_path)) request._api_isPublic = true;
|
||||||
if (findNoCase("/api/auth/verifyLoginOTP.cfm", request._api_path)) request._api_isPublic = true;
|
if (findNoCase("/api/auth/verifyLoginOTP.cfm", request._api_path)) request._api_isPublic = true;
|
||||||
|
if (findNoCase("/api/auth/sendLoginOTP.cfm", request._api_path)) request._api_isPublic = true;
|
||||||
|
if (findNoCase("/api/auth/verifyEmailOTP.cfm", request._api_path)) request._api_isPublic = true;
|
||||||
if (findNoCase("/api/auth/completeProfile.cfm", request._api_path)) request._api_isPublic = true;
|
if (findNoCase("/api/auth/completeProfile.cfm", request._api_path)) request._api_isPublic = true;
|
||||||
|
|
||||||
if (findNoCase("/api/businesses/list.cfm", request._api_path)) request._api_isPublic = true;
|
if (findNoCase("/api/businesses/list.cfm", request._api_path)) request._api_isPublic = true;
|
||||||
|
|
|
||||||
129
api/auth/sendLoginOTP.cfm
Normal file
129
api/auth/sendLoginOTP.cfm
Normal file
|
|
@ -0,0 +1,129 @@
|
||||||
|
<cfsetting showdebugoutput="false">
|
||||||
|
<cfsetting enablecfoutputonly="true">
|
||||||
|
<cfcontent type="application/json; charset=utf-8" reset="true">
|
||||||
|
<cfheader name="Cache-Control" value="no-store">
|
||||||
|
|
||||||
|
<cfscript>
|
||||||
|
/*
|
||||||
|
Send OTP Code for Portal Login
|
||||||
|
POST: { "Email": "user@example.com" }
|
||||||
|
Returns: { OK: true } always (don't reveal if email exists)
|
||||||
|
*/
|
||||||
|
|
||||||
|
function apiAbort(required struct payload) {
|
||||||
|
writeOutput(serializeJSON(payload));
|
||||||
|
abort;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readJsonBody() {
|
||||||
|
var raw = getHttpRequestData().content;
|
||||||
|
if (isNull(raw)) raw = "";
|
||||||
|
if (!len(trim(raw))) return {};
|
||||||
|
try {
|
||||||
|
var data = deserializeJSON(raw);
|
||||||
|
if (isStruct(data)) return data;
|
||||||
|
} catch (any e) {}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
data = readJsonBody();
|
||||||
|
email = trim(data.Email ?: "");
|
||||||
|
|
||||||
|
if (!len(email)) {
|
||||||
|
apiAbort({ "OK": false, "ERROR": "missing_email", "MESSAGE": "Email is required" });
|
||||||
|
}
|
||||||
|
|
||||||
|
genericResponse = { "OK": true, "MESSAGE": "If an account exists, a code has been sent." };
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Look up user by email
|
||||||
|
qUser = queryExecute("
|
||||||
|
SELECT ID, FirstName
|
||||||
|
FROM Users
|
||||||
|
WHERE EmailAddress = :email
|
||||||
|
AND IsActive = 1
|
||||||
|
LIMIT 1
|
||||||
|
", {
|
||||||
|
email: { value: email, cfsqltype: "cf_sql_varchar" }
|
||||||
|
}, { datasource: "payfrit" });
|
||||||
|
|
||||||
|
// Always return OK to not reveal if email exists
|
||||||
|
if (qUser.recordCount == 0) {
|
||||||
|
writeOutput(serializeJSON(genericResponse));
|
||||||
|
abort;
|
||||||
|
}
|
||||||
|
|
||||||
|
userId = qUser.ID;
|
||||||
|
|
||||||
|
// Rate limit: max 3 codes per user in last 10 minutes
|
||||||
|
qRateCheck = queryExecute("
|
||||||
|
SELECT COUNT(*) AS cnt
|
||||||
|
FROM OTPCodes
|
||||||
|
WHERE UserID = :userId
|
||||||
|
AND CreatedAt > DATE_SUB(NOW(), INTERVAL 10 MINUTE)
|
||||||
|
", {
|
||||||
|
userId: { value: userId, cfsqltype: "cf_sql_integer" }
|
||||||
|
}, { datasource: "payfrit" });
|
||||||
|
|
||||||
|
if (qRateCheck.cnt >= 3) {
|
||||||
|
writeOutput(serializeJSON(genericResponse));
|
||||||
|
abort;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate 6-digit code (or use magic code on dev)
|
||||||
|
code = randRange(100000, 999999);
|
||||||
|
isDev = findNoCase("dev.payfrit.com", cgi.SERVER_NAME) > 0
|
||||||
|
|| findNoCase("localhost", cgi.SERVER_NAME) > 0;
|
||||||
|
|
||||||
|
if (isDev && structKeyExists(application, "MAGIC_OTP_ENABLED") && application.MAGIC_OTP_ENABLED
|
||||||
|
&& structKeyExists(application, "MAGIC_OTP_CODE") && len(application.MAGIC_OTP_CODE)) {
|
||||||
|
code = application.MAGIC_OTP_CODE;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store in DB with 10-minute expiry
|
||||||
|
queryExecute("
|
||||||
|
INSERT INTO OTPCodes (UserID, Code, ExpiresAt)
|
||||||
|
VALUES (:userId, :code, DATE_ADD(NOW(), INTERVAL 10 MINUTE))
|
||||||
|
", {
|
||||||
|
userId: { value: userId, cfsqltype: "cf_sql_integer" },
|
||||||
|
code: { value: code, cfsqltype: "cf_sql_varchar" }
|
||||||
|
}, { datasource: "payfrit" });
|
||||||
|
|
||||||
|
// Send email (skip on dev if magic OTP is enabled)
|
||||||
|
if (!isDev) {
|
||||||
|
try {
|
||||||
|
mailService = new mail();
|
||||||
|
mailService.setTo(email);
|
||||||
|
mailService.setFrom("admin@payfrit.com");
|
||||||
|
mailService.setSubject("Your Payfrit login code");
|
||||||
|
mailService.setType("html");
|
||||||
|
|
||||||
|
emailBody = "
|
||||||
|
<div style='font-family: -apple-system, BlinkMacSystemFont, sans-serif; max-width: 400px; margin: 0 auto; padding: 20px;'>
|
||||||
|
<h2 style='color: ##333; margin-bottom: 8px;'>Your login code</h2>
|
||||||
|
<p style='color: ##666; margin-bottom: 20px;'>Hi #encodeForHTML(qUser.FirstName)#, use this code to sign in to Payfrit:</p>
|
||||||
|
<div style='background: ##f5f5f5; border-radius: 8px; padding: 20px; text-align: center; margin-bottom: 20px;'>
|
||||||
|
<span style='font-size: 32px; font-weight: 700; letter-spacing: 6px; color: ##111;'>#code#</span>
|
||||||
|
</div>
|
||||||
|
<p style='color: ##999; font-size: 13px;'>This code expires in 10 minutes. If you didn't request this, you can safely ignore it.</p>
|
||||||
|
</div>
|
||||||
|
";
|
||||||
|
|
||||||
|
mailService.send(body=emailBody);
|
||||||
|
} catch (any mailErr) {
|
||||||
|
writeLog(file="otp_errors", text="Email send failed for user #userId#: #mailErr.message#");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// On dev, include the code in response for easy testing
|
||||||
|
resp = duplicate(genericResponse);
|
||||||
|
if (isDev) {
|
||||||
|
resp["DEV_OTP"] = code;
|
||||||
|
}
|
||||||
|
writeOutput(serializeJSON(resp));
|
||||||
|
|
||||||
|
} catch (any e) {
|
||||||
|
writeLog(file="otp_errors", text="sendLoginOTP error for #email#: #e.message#");
|
||||||
|
writeOutput(serializeJSON(genericResponse));
|
||||||
|
}
|
||||||
|
</cfscript>
|
||||||
116
api/auth/verifyEmailOTP.cfm
Normal file
116
api/auth/verifyEmailOTP.cfm
Normal file
|
|
@ -0,0 +1,116 @@
|
||||||
|
<cfsetting showdebugoutput="false">
|
||||||
|
<cfsetting enablecfoutputonly="true">
|
||||||
|
<cfcontent type="application/json; charset=utf-8" reset="true">
|
||||||
|
<cfheader name="Cache-Control" value="no-store">
|
||||||
|
|
||||||
|
<cfscript>
|
||||||
|
/*
|
||||||
|
Verify Email OTP Code for Portal Login
|
||||||
|
POST: { "Email": "user@example.com", "Code": "123456" }
|
||||||
|
Returns: { OK: true, UserID, FirstName, Token } or { OK: false, ERROR: "invalid_code" }
|
||||||
|
*/
|
||||||
|
|
||||||
|
function apiAbort(required struct payload) {
|
||||||
|
writeOutput(serializeJSON(payload));
|
||||||
|
abort;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readJsonBody() {
|
||||||
|
var raw = getHttpRequestData().content;
|
||||||
|
if (isNull(raw)) raw = "";
|
||||||
|
if (!len(trim(raw))) return {};
|
||||||
|
try {
|
||||||
|
var data = deserializeJSON(raw);
|
||||||
|
if (isStruct(data)) return data;
|
||||||
|
} catch (any e) {}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
data = readJsonBody();
|
||||||
|
email = trim(data.Email ?: "");
|
||||||
|
code = trim(data.Code ?: "");
|
||||||
|
|
||||||
|
if (!len(email) || !len(code)) {
|
||||||
|
apiAbort({ "OK": false, "ERROR": "missing_fields", "MESSAGE": "Email and code are required" });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Look up user by email
|
||||||
|
qUser = queryExecute("
|
||||||
|
SELECT ID, FirstName
|
||||||
|
FROM Users
|
||||||
|
WHERE EmailAddress = :email
|
||||||
|
AND IsActive = 1
|
||||||
|
LIMIT 1
|
||||||
|
", {
|
||||||
|
email: { value: email, cfsqltype: "cf_sql_varchar" }
|
||||||
|
}, { datasource: "payfrit" });
|
||||||
|
|
||||||
|
if (qUser.recordCount == 0) {
|
||||||
|
apiAbort({ "OK": false, "ERROR": "invalid_code", "MESSAGE": "Invalid or expired code" });
|
||||||
|
}
|
||||||
|
|
||||||
|
userId = qUser.ID;
|
||||||
|
|
||||||
|
// Check for valid OTP in OTPCodes table
|
||||||
|
qOTP = queryExecute("
|
||||||
|
SELECT ID
|
||||||
|
FROM OTPCodes
|
||||||
|
WHERE UserID = :userId
|
||||||
|
AND Code = :code
|
||||||
|
AND ExpiresAt > NOW()
|
||||||
|
AND UsedAt IS NULL
|
||||||
|
ORDER BY CreatedAt DESC
|
||||||
|
LIMIT 1
|
||||||
|
", {
|
||||||
|
userId: { value: userId, cfsqltype: "cf_sql_integer" },
|
||||||
|
code: { value: code, cfsqltype: "cf_sql_varchar" }
|
||||||
|
}, { datasource: "payfrit" });
|
||||||
|
|
||||||
|
if (qOTP.recordCount == 0) {
|
||||||
|
apiAbort({ "OK": false, "ERROR": "invalid_code", "MESSAGE": "Invalid or expired code" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mark OTP as used
|
||||||
|
queryExecute("
|
||||||
|
UPDATE OTPCodes
|
||||||
|
SET UsedAt = NOW()
|
||||||
|
WHERE ID = :otpId
|
||||||
|
", {
|
||||||
|
otpId: { value: qOTP.ID, cfsqltype: "cf_sql_integer" }
|
||||||
|
}, { datasource: "payfrit" });
|
||||||
|
|
||||||
|
// Create auth token (same as login.cfm)
|
||||||
|
token = replace(createUUID(), "-", "", "all");
|
||||||
|
|
||||||
|
queryExecute(
|
||||||
|
"INSERT INTO UserTokens (UserID, Token) VALUES (?, ?)",
|
||||||
|
[
|
||||||
|
{ value: userId, cfsqltype: "cf_sql_integer" },
|
||||||
|
{ value: token, cfsqltype: "cf_sql_varchar" }
|
||||||
|
],
|
||||||
|
{ datasource: "payfrit" }
|
||||||
|
);
|
||||||
|
|
||||||
|
// Set session
|
||||||
|
lock timeout="15" throwontimeout="yes" type="exclusive" scope="session" {
|
||||||
|
session.UserID = userId;
|
||||||
|
}
|
||||||
|
request.UserID = userId;
|
||||||
|
|
||||||
|
writeOutput(serializeJSON({
|
||||||
|
"OK": true,
|
||||||
|
"ERROR": "",
|
||||||
|
"UserID": userId,
|
||||||
|
"FirstName": qUser.FirstName,
|
||||||
|
"Token": token
|
||||||
|
}));
|
||||||
|
|
||||||
|
} catch (any e) {
|
||||||
|
apiAbort({
|
||||||
|
"OK": false,
|
||||||
|
"ERROR": "server_error",
|
||||||
|
"MESSAGE": e.message
|
||||||
|
});
|
||||||
|
}
|
||||||
|
</cfscript>
|
||||||
|
|
@ -134,6 +134,20 @@
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.login-success {
|
||||||
|
background: rgba(0, 255, 136, 0.1);
|
||||||
|
border: 1px solid rgba(0, 255, 136, 0.3);
|
||||||
|
color: var(--primary);
|
||||||
|
padding: 12px 16px;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 14px;
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-success.show {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
.login-footer {
|
.login-footer {
|
||||||
text-align: center;
|
text-align: center;
|
||||||
margin-top: 24px;
|
margin-top: 24px;
|
||||||
|
|
@ -182,6 +196,46 @@
|
||||||
.step.active {
|
.step.active {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.otp-input {
|
||||||
|
text-align: center;
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 8px;
|
||||||
|
padding: 14px 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.switch-link {
|
||||||
|
color: var(--text-muted);
|
||||||
|
text-decoration: none;
|
||||||
|
font-size: 13px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.switch-link:hover {
|
||||||
|
color: var(--primary);
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
.resend-link {
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-size: 13px;
|
||||||
|
cursor: pointer;
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
padding: 0;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.resend-link:hover {
|
||||||
|
color: var(--primary);
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
.resend-link:disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|
@ -190,11 +244,49 @@
|
||||||
<div class="login-header">
|
<div class="login-header">
|
||||||
<div class="login-logo">P</div>
|
<div class="login-logo">P</div>
|
||||||
<h1>Business Portal</h1>
|
<h1>Business Portal</h1>
|
||||||
<p>Sign in or enter your phone number to create an account</p>
|
<p id="loginSubtitle">Sign in with your email</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Step 1: Login -->
|
<!-- Step 1: OTP - Enter Email -->
|
||||||
<div class="step" id="step-login">
|
<div class="step" id="step-otp-email">
|
||||||
|
<form class="login-form" id="otpEmailForm">
|
||||||
|
<div class="login-error" id="otpEmailError"></div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="otpEmail">Email Address</label>
|
||||||
|
<input type="email" id="otpEmail" name="email" placeholder="Enter your email" required>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="submit" class="login-btn" id="sendCodeBtn">Send Login Code</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div class="login-footer">
|
||||||
|
<a href="#" class="switch-link" onclick="PortalLogin.showStep('password'); return false;">Sign in with password instead</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Step 2: OTP - Enter Code -->
|
||||||
|
<div class="step" id="step-otp-code">
|
||||||
|
<form class="login-form" id="otpCodeForm">
|
||||||
|
<div class="login-error" id="otpCodeError"></div>
|
||||||
|
<div class="login-success" id="otpCodeSuccess">A 6-digit code has been sent to your email.</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="otpCode">Enter 6-Digit Code</label>
|
||||||
|
<input type="text" id="otpCode" name="code" class="otp-input" placeholder="000000" maxlength="6" pattern="[0-9]{6}" inputmode="numeric" autocomplete="one-time-code" required>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="submit" class="login-btn" id="verifyCodeBtn">Verify Code</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div class="login-footer" style="display: flex; justify-content: space-between; align-items: center;">
|
||||||
|
<a href="#" class="switch-link" onclick="PortalLogin.showStep('otp-email'); return false;">Change email</a>
|
||||||
|
<button class="resend-link" id="resendBtn" onclick="PortalLogin.resendCode()">Resend code</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Step 3: Password Login (fallback) -->
|
||||||
|
<div class="step" id="step-password">
|
||||||
<form class="login-form" id="loginForm">
|
<form class="login-form" id="loginForm">
|
||||||
<div class="login-error" id="loginError"></div>
|
<div class="login-error" id="loginError"></div>
|
||||||
|
|
||||||
|
|
@ -212,11 +304,11 @@
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<div class="login-footer">
|
<div class="login-footer">
|
||||||
<a href="/index.cfm?mode=forgot">Forgot password?</a>
|
<a href="#" class="switch-link" onclick="PortalLogin.showStep('otp-email'); return false;">Sign in with email code instead</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Step 2: Select Business -->
|
<!-- Step 4: Select Business -->
|
||||||
<div class="step" id="step-business">
|
<div class="step" id="step-business">
|
||||||
<div class="login-form">
|
<div class="login-form">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
|
|
@ -231,7 +323,6 @@
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
// Detect base path for API calls (handles local dev at /biz.payfrit.com/)
|
|
||||||
const BASE_PATH = (() => {
|
const BASE_PATH = (() => {
|
||||||
const path = window.location.pathname;
|
const path = window.location.pathname;
|
||||||
const portalIndex = path.indexOf('/portal/');
|
const portalIndex = path.indexOf('/portal/');
|
||||||
|
|
@ -245,6 +336,8 @@
|
||||||
userToken: null,
|
userToken: null,
|
||||||
userId: null,
|
userId: null,
|
||||||
businesses: [],
|
businesses: [],
|
||||||
|
otpEmail: null,
|
||||||
|
resendCooldown: false,
|
||||||
|
|
||||||
init() {
|
init() {
|
||||||
const card = document.querySelector('.login-card');
|
const card = document.querySelector('.login-card');
|
||||||
|
|
@ -253,13 +346,11 @@
|
||||||
const savedUserId = localStorage.getItem('payfrit_portal_userid');
|
const savedUserId = localStorage.getItem('payfrit_portal_userid');
|
||||||
|
|
||||||
if (savedToken && savedBusiness) {
|
if (savedToken && savedBusiness) {
|
||||||
// Already logged in with a business - redirect to portal (stay hidden)
|
|
||||||
this.verifyAndRedirect(savedToken, savedBusiness);
|
this.verifyAndRedirect(savedToken, savedBusiness);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (savedToken && savedUserId) {
|
if (savedToken && savedUserId) {
|
||||||
// Has token but no business selected - skip login, show business selection
|
|
||||||
this.userToken = savedToken;
|
this.userToken = savedToken;
|
||||||
this.userId = parseInt(savedUserId);
|
this.userId = parseInt(savedUserId);
|
||||||
this.showStep('business');
|
this.showStep('business');
|
||||||
|
|
@ -268,38 +359,237 @@
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// No saved session - show login form
|
// Default: show OTP email step
|
||||||
this.showStep('login');
|
this.showStep('otp-email');
|
||||||
card.classList.add('ready');
|
card.classList.add('ready');
|
||||||
|
|
||||||
|
// OTP email form
|
||||||
|
document.getElementById('otpEmailForm').addEventListener('submit', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
this.sendOTP();
|
||||||
|
});
|
||||||
|
|
||||||
|
// OTP code form
|
||||||
|
document.getElementById('otpCodeForm').addEventListener('submit', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
this.verifyOTP();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Password login form
|
||||||
document.getElementById('loginForm').addEventListener('submit', (e) => {
|
document.getElementById('loginForm').addEventListener('submit', (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
this.login();
|
this.login();
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
// Load businesses and show selection (for switching businesses)
|
|
||||||
async loadBusinessesAndShow() {
|
async loadBusinessesAndShow() {
|
||||||
await this.loadBusinesses();
|
await this.loadBusinesses();
|
||||||
|
|
||||||
if (this.businesses.length === 0) {
|
if (this.businesses.length === 0) {
|
||||||
// No businesses - go directly to wizard
|
|
||||||
this.startNewRestaurant();
|
this.startNewRestaurant();
|
||||||
} else if (this.businesses.length === 1) {
|
} else if (this.businesses.length === 1) {
|
||||||
// Single business - auto-login to it
|
|
||||||
this.selectBusinessById(this.businesses[0].BusinessID);
|
this.selectBusinessById(this.businesses[0].BusinessID);
|
||||||
} else {
|
} else {
|
||||||
// Multiple businesses - show selection
|
|
||||||
this.showStep('business');
|
this.showStep('business');
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
async verifyAndRedirect(token, businessId) {
|
async verifyAndRedirect(token, businessId) {
|
||||||
// Save business ID to localStorage and redirect
|
|
||||||
localStorage.setItem('payfrit_portal_business', businessId);
|
localStorage.setItem('payfrit_portal_business', businessId);
|
||||||
window.location.href = BASE_PATH + '/portal/index.html';
|
window.location.href = BASE_PATH + '/portal/index.html';
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// --- OTP Flow ---
|
||||||
|
|
||||||
|
async sendOTP() {
|
||||||
|
const email = document.getElementById('otpEmail').value.trim();
|
||||||
|
const errorEl = document.getElementById('otpEmailError');
|
||||||
|
const btn = document.getElementById('sendCodeBtn');
|
||||||
|
|
||||||
|
if (!email) return;
|
||||||
|
|
||||||
|
errorEl.classList.remove('show');
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.textContent = 'Sending...';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(BASE_PATH + '/api/auth/sendLoginOTP.cfm', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ Email: email })
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = await response.text();
|
||||||
|
let data;
|
||||||
|
try {
|
||||||
|
data = JSON.parse(text);
|
||||||
|
} catch (parseErr) {
|
||||||
|
console.error('[OTP] JSON parse error:', parseErr);
|
||||||
|
errorEl.textContent = 'Server error. Please try again.';
|
||||||
|
errorEl.classList.add('show');
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = 'Send Login Code';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.OK) {
|
||||||
|
this.otpEmail = email;
|
||||||
|
|
||||||
|
// On dev, show the code for testing
|
||||||
|
if (data.DEV_OTP) {
|
||||||
|
console.log('[OTP] Dev code:', data.DEV_OTP);
|
||||||
|
document.getElementById('otpCodeSuccess').textContent =
|
||||||
|
'Dev mode - your code is: ' + data.DEV_OTP;
|
||||||
|
} else {
|
||||||
|
document.getElementById('otpCodeSuccess').textContent =
|
||||||
|
'A 6-digit code has been sent to ' + email;
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('otpCodeSuccess').classList.add('show');
|
||||||
|
this.showStep('otp-code');
|
||||||
|
document.getElementById('otpCode').focus();
|
||||||
|
} else {
|
||||||
|
errorEl.textContent = data.MESSAGE || data.ERROR || 'Could not send code. Please try again.';
|
||||||
|
errorEl.classList.add('show');
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[OTP] Send error:', err);
|
||||||
|
errorEl.textContent = 'Connection error. Please try again.';
|
||||||
|
errorEl.classList.add('show');
|
||||||
|
}
|
||||||
|
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = 'Send Login Code';
|
||||||
|
},
|
||||||
|
|
||||||
|
async verifyOTP() {
|
||||||
|
const code = document.getElementById('otpCode').value.trim();
|
||||||
|
const errorEl = document.getElementById('otpCodeError');
|
||||||
|
const btn = document.getElementById('verifyCodeBtn');
|
||||||
|
|
||||||
|
if (!code || code.length !== 6) {
|
||||||
|
errorEl.textContent = 'Please enter the 6-digit code.';
|
||||||
|
errorEl.classList.add('show');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
errorEl.classList.remove('show');
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.textContent = 'Verifying...';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(BASE_PATH + '/api/auth/verifyEmailOTP.cfm', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ Email: this.otpEmail, Code: code })
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = await response.text();
|
||||||
|
let data;
|
||||||
|
try {
|
||||||
|
data = JSON.parse(text);
|
||||||
|
} catch (parseErr) {
|
||||||
|
console.error('[OTP] Verify parse error:', parseErr);
|
||||||
|
errorEl.textContent = 'Server error. Please try again.';
|
||||||
|
errorEl.classList.add('show');
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = 'Verify Code';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.OK && data.TOKEN) {
|
||||||
|
// Normalize key casing
|
||||||
|
const token = data.TOKEN || data.Token;
|
||||||
|
const userId = data.USERID || data.UserID;
|
||||||
|
|
||||||
|
this.userToken = token;
|
||||||
|
this.userId = userId;
|
||||||
|
|
||||||
|
localStorage.setItem('payfrit_portal_token', token);
|
||||||
|
localStorage.setItem('payfrit_portal_userid', userId);
|
||||||
|
|
||||||
|
await this.loadBusinesses();
|
||||||
|
|
||||||
|
const card = document.querySelector('.login-card');
|
||||||
|
if (this.businesses.length === 0) {
|
||||||
|
this.startNewRestaurant();
|
||||||
|
} else if (this.businesses.length === 1) {
|
||||||
|
this.selectBusinessById(this.businesses[0].BusinessID);
|
||||||
|
} else {
|
||||||
|
this.showStep('business');
|
||||||
|
card.classList.add('ready');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const friendlyErrors = {
|
||||||
|
'invalid_code': 'Invalid or expired code. Please try again.',
|
||||||
|
'expired': 'Code has expired. Please request a new one.',
|
||||||
|
'user_not_found': 'No account found with that email.'
|
||||||
|
};
|
||||||
|
errorEl.textContent = friendlyErrors[data.ERROR] || data.MESSAGE || 'Invalid code. Please try again.';
|
||||||
|
errorEl.classList.add('show');
|
||||||
|
document.getElementById('otpCode').value = '';
|
||||||
|
document.getElementById('otpCode').focus();
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[OTP] Verify error:', err);
|
||||||
|
errorEl.textContent = 'Connection error. Please try again.';
|
||||||
|
errorEl.classList.add('show');
|
||||||
|
}
|
||||||
|
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = 'Verify Code';
|
||||||
|
},
|
||||||
|
|
||||||
|
async resendCode() {
|
||||||
|
if (this.resendCooldown) return;
|
||||||
|
|
||||||
|
const btn = document.getElementById('resendBtn');
|
||||||
|
this.resendCooldown = true;
|
||||||
|
btn.disabled = true;
|
||||||
|
|
||||||
|
// Re-send OTP
|
||||||
|
try {
|
||||||
|
const response = await fetch(BASE_PATH + '/api/auth/sendLoginOTP.cfm', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ Email: this.otpEmail })
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = await response.text();
|
||||||
|
let data;
|
||||||
|
try { data = JSON.parse(text); } catch (e) { data = {}; }
|
||||||
|
|
||||||
|
const successEl = document.getElementById('otpCodeSuccess');
|
||||||
|
if (data.OK) {
|
||||||
|
if (data.DEV_OTP) {
|
||||||
|
successEl.textContent = 'Dev mode - new code: ' + data.DEV_OTP;
|
||||||
|
} else {
|
||||||
|
successEl.textContent = 'A new code has been sent to ' + this.otpEmail;
|
||||||
|
}
|
||||||
|
successEl.classList.add('show');
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[OTP] Resend error:', err);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 30-second cooldown
|
||||||
|
let seconds = 30;
|
||||||
|
btn.textContent = 'Resend (' + seconds + 's)';
|
||||||
|
const interval = setInterval(() => {
|
||||||
|
seconds--;
|
||||||
|
if (seconds <= 0) {
|
||||||
|
clearInterval(interval);
|
||||||
|
btn.textContent = 'Resend code';
|
||||||
|
btn.disabled = false;
|
||||||
|
this.resendCooldown = false;
|
||||||
|
} else {
|
||||||
|
btn.textContent = 'Resend (' + seconds + 's)';
|
||||||
|
}
|
||||||
|
}, 1000);
|
||||||
|
},
|
||||||
|
|
||||||
|
// --- Password Login (fallback) ---
|
||||||
|
|
||||||
async login() {
|
async login() {
|
||||||
const username = document.getElementById('username').value.trim();
|
const username = document.getElementById('username').value.trim();
|
||||||
const password = document.getElementById('password').value;
|
const password = document.getElementById('password').value;
|
||||||
|
|
@ -317,9 +607,7 @@
|
||||||
body: JSON.stringify({ username, password })
|
body: JSON.stringify({ username, password })
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log("[Login] Response status:", response.status);
|
|
||||||
const text = await response.text();
|
const text = await response.text();
|
||||||
console.log("[Login] Raw response:", text.substring(0, 500));
|
|
||||||
let data;
|
let data;
|
||||||
try {
|
try {
|
||||||
data = JSON.parse(text);
|
data = JSON.parse(text);
|
||||||
|
|
@ -332,26 +620,24 @@
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (data.OK && data.Token) {
|
if (data.OK && (data.Token || data.TOKEN)) {
|
||||||
this.userToken = data.Token;
|
const token = data.Token || data.TOKEN;
|
||||||
this.userId = data.UserID;
|
const userId = data.UserID || data.USERID;
|
||||||
|
|
||||||
// Save token
|
this.userToken = token;
|
||||||
localStorage.setItem('payfrit_portal_token', data.Token);
|
this.userId = userId;
|
||||||
localStorage.setItem('payfrit_portal_userid', data.UserID);
|
|
||||||
|
localStorage.setItem('payfrit_portal_token', token);
|
||||||
|
localStorage.setItem('payfrit_portal_userid', userId);
|
||||||
|
|
||||||
// Load user's businesses
|
|
||||||
await this.loadBusinesses();
|
await this.loadBusinesses();
|
||||||
|
|
||||||
const card = document.querySelector('.login-card');
|
const card = document.querySelector('.login-card');
|
||||||
if (this.businesses.length === 0) {
|
if (this.businesses.length === 0) {
|
||||||
// No businesses - go directly to wizard
|
|
||||||
this.startNewRestaurant();
|
this.startNewRestaurant();
|
||||||
} else if (this.businesses.length === 1) {
|
} else if (this.businesses.length === 1) {
|
||||||
// Single business - auto-login to it
|
|
||||||
this.selectBusinessById(this.businesses[0].BusinessID);
|
this.selectBusinessById(this.businesses[0].BusinessID);
|
||||||
} else {
|
} else {
|
||||||
// Multiple businesses - show selection
|
|
||||||
this.showStep('business');
|
this.showStep('business');
|
||||||
card.classList.add('ready');
|
card.classList.add('ready');
|
||||||
}
|
}
|
||||||
|
|
@ -374,6 +660,8 @@
|
||||||
btn.textContent = 'Sign In';
|
btn.textContent = 'Sign In';
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// --- Business Selection ---
|
||||||
|
|
||||||
async loadBusinesses() {
|
async loadBusinesses() {
|
||||||
try {
|
try {
|
||||||
console.log('[Login] Loading businesses for UserID:', this.userId);
|
console.log('[Login] Loading businesses for UserID:', this.userId);
|
||||||
|
|
@ -386,10 +674,7 @@
|
||||||
body: JSON.stringify({ UserID: this.userId })
|
body: JSON.stringify({ UserID: this.userId })
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log("[Login] Businesses response status:", bizResponse.status);
|
|
||||||
const bizText = await bizResponse.text();
|
const bizText = await bizResponse.text();
|
||||||
console.log("[Login] Businesses raw response:", bizText.substring(0, 500));
|
|
||||||
|
|
||||||
let bizData;
|
let bizData;
|
||||||
try {
|
try {
|
||||||
bizData = JSON.parse(bizText);
|
bizData = JSON.parse(bizText);
|
||||||
|
|
@ -414,11 +699,10 @@
|
||||||
const select = document.getElementById('businessSelect');
|
const select = document.getElementById('businessSelect');
|
||||||
|
|
||||||
if (this.businesses.length === 0) {
|
if (this.businesses.length === 0) {
|
||||||
// No businesses - add wizard option only
|
|
||||||
select.innerHTML = '<option value="">No businesses yet</option>';
|
select.innerHTML = '<option value="">No businesses yet</option>';
|
||||||
const wizardOption = document.createElement('option');
|
const wizardOption = document.createElement('option');
|
||||||
wizardOption.value = 'NEW_WIZARD';
|
wizardOption.value = 'NEW_WIZARD';
|
||||||
wizardOption.textContent = '✨ Create New Business';
|
wizardOption.textContent = 'Create New Business';
|
||||||
select.appendChild(wizardOption);
|
select.appendChild(wizardOption);
|
||||||
} else {
|
} else {
|
||||||
select.innerHTML = '<option value="">Choose a business...</option>';
|
select.innerHTML = '<option value="">Choose a business...</option>';
|
||||||
|
|
@ -430,17 +714,27 @@
|
||||||
select.appendChild(option);
|
select.appendChild(option);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Add "New Business Wizard" option at the end
|
|
||||||
const wizardOption = document.createElement('option');
|
const wizardOption = document.createElement('option');
|
||||||
wizardOption.value = 'NEW_WIZARD';
|
wizardOption.value = 'NEW_WIZARD';
|
||||||
wizardOption.textContent = '✨ New Business Wizard';
|
wizardOption.textContent = 'New Business Wizard';
|
||||||
select.appendChild(wizardOption);
|
select.appendChild(wizardOption);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
showStep(step) {
|
showStep(step) {
|
||||||
document.querySelectorAll('.step').forEach(s => s.classList.remove('active'));
|
document.querySelectorAll('.step').forEach(s => s.classList.remove('active'));
|
||||||
document.getElementById(`step-${step}`).classList.add('active');
|
const el = document.getElementById('step-' + step);
|
||||||
|
if (el) el.classList.add('active');
|
||||||
|
|
||||||
|
// Update subtitle
|
||||||
|
const subtitle = document.getElementById('loginSubtitle');
|
||||||
|
if (step === 'otp-email') subtitle.textContent = 'Sign in with your email';
|
||||||
|
else if (step === 'otp-code') subtitle.textContent = 'Enter your verification code';
|
||||||
|
else if (step === 'password') subtitle.textContent = 'Sign in with your password';
|
||||||
|
else if (step === 'business') subtitle.textContent = 'Select your business';
|
||||||
|
|
||||||
|
// Clear errors when switching
|
||||||
|
document.querySelectorAll('.login-error').forEach(e => e.classList.remove('show'));
|
||||||
},
|
},
|
||||||
|
|
||||||
selectBusiness() {
|
selectBusiness() {
|
||||||
|
|
@ -458,10 +752,8 @@
|
||||||
},
|
},
|
||||||
|
|
||||||
startNewRestaurant() {
|
startNewRestaurant() {
|
||||||
// Clear any existing business selection
|
|
||||||
localStorage.removeItem('payfrit_portal_business');
|
localStorage.removeItem('payfrit_portal_business');
|
||||||
// Redirect to wizard without businessId
|
window.location.href = BASE_PATH + '/portal/setup-wizard.html';
|
||||||
window.location.href = BASE_PATH + `/portal/setup-wizard.html`;
|
|
||||||
},
|
},
|
||||||
|
|
||||||
logout() {
|
logout() {
|
||||||
|
|
|
||||||
Reference in a new issue