forked from jsnbuchanan/crowd-funder-for-time-pwa
- Enhance JWT extraction with unified path handling and validation - Add debouncing to prevent duplicate scans - Improve error handling and logging throughout QR flow - Add proper TypeScript interfaces for QR scan results - Implement mobile app lifecycle handlers (pause/resume) - Enhance logging with structured data and consistent levels - Clean up scanner resources properly on component destroy - Split contact handling into separate method for better organization - Add proper type for UserNameDialog ref This commit improves the reliability and maintainability of the QR code scanning functionality while adding better error handling and logging.
614 lines
17 KiB
Vue
614 lines
17 KiB
Vue
<template>
|
|
<QuickNav selected="Profile" />
|
|
<!-- CONTENT -->
|
|
<section id="Content" class="p-6 pb-24 max-w-3xl mx-auto">
|
|
<!-- Breadcrumb -->
|
|
<div class="mb-8">
|
|
<!-- Back -->
|
|
<div class="relative px-7">
|
|
<h1
|
|
class="text-lg text-center font-light px-2 py-1 absolute -left-2 -top-1"
|
|
@click="$router.back()"
|
|
>
|
|
<font-awesome icon="chevron-left" class="fa-fw" />
|
|
</h1>
|
|
</div>
|
|
|
|
<!-- Heading -->
|
|
<h1 id="ViewHeading" class="text-4xl text-center font-light pt-4">
|
|
Your Contact Info
|
|
</h1>
|
|
<p
|
|
v-if="!givenName"
|
|
class="bg-amber-200 rounded-md overflow-hidden text-center px-4 py-3 mb-4"
|
|
>
|
|
<span class="text-red">Beware!</span>
|
|
You aren't sharing your name, so quickly
|
|
<br />
|
|
<span
|
|
class="bg-gradient-to-b from-blue-400 to-blue-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-1.5 py-1 rounded-md"
|
|
@click="openUserNameDialog"
|
|
>
|
|
click here to set it for them.
|
|
</span>
|
|
</p>
|
|
</div>
|
|
<UserNameDialog ref="userNameDialog" />
|
|
|
|
<div
|
|
v-if="activeDid && activeDid.startsWith(ETHR_DID_PREFIX)"
|
|
class="text-center"
|
|
@click="onCopyUrlToClipboard()"
|
|
>
|
|
<!--
|
|
Play with display options: https://qr-code-styling.com/
|
|
See docs: https://www.npmjs.com/package/qr-code-generator-vue3
|
|
-->
|
|
<QRCodeVue3
|
|
:value="qrValue"
|
|
:corners-square-options="{ type: 'extra-rounded' }"
|
|
:dots-options="{ type: 'square' }"
|
|
class="flex justify-center"
|
|
/>
|
|
<span>
|
|
Click the QR code to copy your contact info to your clipboard.
|
|
</span>
|
|
</div>
|
|
<div v-else-if="activeDid" class="text-center">
|
|
<!-- Not an ETHR DID so force them to paste it. (Passkey Peer DIDs are too big.) -->
|
|
<span class="text-blue-500" @click="onCopyDidToClipboard()">
|
|
Click here to copy your DID to your clipboard.
|
|
</span>
|
|
<span>
|
|
Then give it to them so they can paste it in their list of People.
|
|
</span>
|
|
</div>
|
|
<div v-else class="text-center">
|
|
You have no identitifiers yet, so
|
|
<router-link
|
|
:to="{ name: 'start' }"
|
|
class="bg-blue-500 text-white px-1.5 py-1 rounded-md"
|
|
>
|
|
create your identifier.
|
|
</router-link>
|
|
<br />
|
|
If you don't that first, these contacts won't see your activity.
|
|
</div>
|
|
|
|
<div class="text-center">
|
|
<h1 class="text-4xl text-center font-light pt-6">Scan Contact Info</h1>
|
|
<div v-if="isScanning" class="relative aspect-square">
|
|
<div
|
|
class="absolute inset-0 border-2 border-blue-500 opacity-50 pointer-events-none"
|
|
></div>
|
|
</div>
|
|
<div v-else>
|
|
<button
|
|
class="bg-blue-500 text-white px-4 py-2 rounded-md mt-4"
|
|
@click="startScanning"
|
|
>
|
|
Start Scanning
|
|
</button>
|
|
</div>
|
|
<span v-if="error" class="text-red-500 block mt-2">{{ error }}</span>
|
|
<span v-else class="block mt-2">
|
|
If you do not see a scanning camera window here, check your camera
|
|
permissions.
|
|
</span>
|
|
</div>
|
|
</section>
|
|
</template>
|
|
|
|
<script lang="ts">
|
|
import { AxiosError } from "axios";
|
|
import QRCodeVue3 from "qr-code-generator-vue3";
|
|
import { Component, Vue } from "vue-facing-decorator";
|
|
import { useClipboard } from "@vueuse/core";
|
|
|
|
import QuickNav from "../components/QuickNav.vue";
|
|
import UserNameDialog from "../components/UserNameDialog.vue";
|
|
import { NotificationIface } from "../constants/app";
|
|
import { db, retrieveSettingsForActiveAccount } from "../db/index";
|
|
import { Contact } from "../db/tables/contacts";
|
|
import { MASTER_SETTINGS_KEY } from "../db/tables/settings";
|
|
import { getContactJwtFromJwtUrl } from "../libs/crypto";
|
|
import {
|
|
generateEndorserJwtUrlForAccount,
|
|
isDid,
|
|
register,
|
|
setVisibilityUtil,
|
|
} from "../libs/endorserServer";
|
|
import { decodeEndorserJwt, ETHR_DID_PREFIX } from "../libs/crypto/vc";
|
|
import { retrieveAccountMetadata } from "../libs/util";
|
|
import { Router } from "vue-router";
|
|
import { logger } from "../utils/logger";
|
|
import { QRScannerFactory } from "../services/QRScanner/QRScannerFactory";
|
|
|
|
interface QRScanResult {
|
|
rawValue?: string;
|
|
barcode?: string;
|
|
}
|
|
|
|
interface IUserNameDialog {
|
|
open: (callback: (name: string) => void) => void;
|
|
}
|
|
|
|
@Component({
|
|
components: {
|
|
QRCodeVue3,
|
|
QuickNav,
|
|
UserNameDialog,
|
|
},
|
|
})
|
|
export default class ContactQRScanShow extends Vue {
|
|
$notify!: (notification: NotificationIface, timeout?: number) => void;
|
|
$router!: Router;
|
|
|
|
activeDid = "";
|
|
apiServer = "";
|
|
givenName = "";
|
|
hideRegisterPromptOnNewContact = false;
|
|
isRegistered = false;
|
|
qrValue = "";
|
|
isScanning = false;
|
|
error: string | null = null;
|
|
|
|
ETHR_DID_PREFIX = ETHR_DID_PREFIX;
|
|
|
|
// Add new properties to track scanning state
|
|
private lastScannedValue: string = "";
|
|
private lastScanTime: number = 0;
|
|
private readonly SCAN_DEBOUNCE_MS = 2000; // Prevent duplicate scans within 2 seconds
|
|
|
|
async created() {
|
|
const settings = await retrieveSettingsForActiveAccount();
|
|
this.activeDid = settings.activeDid || "";
|
|
this.apiServer = settings.apiServer || "";
|
|
this.givenName = settings.firstName || "";
|
|
this.hideRegisterPromptOnNewContact =
|
|
!!settings.hideRegisterPromptOnNewContact;
|
|
this.isRegistered = !!settings.isRegistered;
|
|
|
|
const account = await retrieveAccountMetadata(this.activeDid);
|
|
if (account) {
|
|
const name =
|
|
(settings.firstName || "") +
|
|
(settings.lastName ? ` ${settings.lastName}` : ""); // lastName is deprecated, pre v 0.1.3
|
|
|
|
this.qrValue = await generateEndorserJwtUrlForAccount(
|
|
account,
|
|
!!settings.isRegistered,
|
|
name,
|
|
settings.profileImageUrl || "",
|
|
false,
|
|
);
|
|
}
|
|
}
|
|
|
|
async startScanning() {
|
|
try {
|
|
this.error = null;
|
|
this.isScanning = true;
|
|
this.lastScannedValue = "";
|
|
this.lastScanTime = 0;
|
|
|
|
const scanner = QRScannerFactory.getInstance();
|
|
|
|
// Check permissions first
|
|
if (!(await scanner.checkPermissions())) {
|
|
const granted = await scanner.requestPermissions();
|
|
if (!granted) {
|
|
this.error = "Camera permission denied";
|
|
this.isScanning = false;
|
|
return;
|
|
}
|
|
}
|
|
|
|
// Add scan listener
|
|
scanner.addListener({
|
|
onScan: this.onScanDetect,
|
|
onError: this.onScanError,
|
|
});
|
|
|
|
// Start scanning
|
|
await scanner.startScan();
|
|
} catch (error) {
|
|
this.error = error instanceof Error ? error.message : String(error);
|
|
this.isScanning = false;
|
|
logger.error("Error starting scan:", error);
|
|
}
|
|
}
|
|
|
|
async stopScanning() {
|
|
try {
|
|
const scanner = QRScannerFactory.getInstance();
|
|
await scanner.stopScan();
|
|
this.isScanning = false;
|
|
this.lastScannedValue = "";
|
|
this.lastScanTime = 0;
|
|
} catch (error) {
|
|
logger.error("Error stopping scan:", error);
|
|
}
|
|
}
|
|
|
|
danger(message: string, title: string = "Error", timeout = 5000) {
|
|
this.$notify(
|
|
{
|
|
group: "alert",
|
|
type: "danger",
|
|
title: title,
|
|
text: message,
|
|
},
|
|
timeout,
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Handle QR code scan result with debouncing to prevent duplicate scans
|
|
*/
|
|
async onScanDetect(result: string | QRScanResult) {
|
|
try {
|
|
// Extract raw value from different possible formats
|
|
const rawValue = typeof result === 'string' ? result : (result?.rawValue || result?.barcode);
|
|
if (!rawValue) {
|
|
logger.warn("Invalid scan result - no value found:", result);
|
|
return;
|
|
}
|
|
|
|
// Debounce duplicate scans
|
|
const now = Date.now();
|
|
if (
|
|
rawValue === this.lastScannedValue &&
|
|
now - this.lastScanTime < this.SCAN_DEBOUNCE_MS
|
|
) {
|
|
logger.info("Ignoring duplicate scan:", rawValue);
|
|
return;
|
|
}
|
|
|
|
// Update scan tracking
|
|
this.lastScannedValue = rawValue;
|
|
this.lastScanTime = now;
|
|
|
|
logger.info("Processing QR code scan result:", rawValue);
|
|
|
|
// Extract JWT
|
|
const jwt = getContactJwtFromJwtUrl(rawValue);
|
|
if (!jwt) {
|
|
logger.warn("Invalid QR code format - no JWT found in URL");
|
|
this.$notify({
|
|
group: "alert",
|
|
type: "danger",
|
|
title: "Invalid QR Code",
|
|
text: "This QR code does not contain valid contact information. Please scan a TimeSafari contact QR code.",
|
|
});
|
|
return;
|
|
}
|
|
|
|
// Process JWT and contact info
|
|
logger.info("Decoding JWT payload from QR code");
|
|
const decodedJwt = await decodeEndorserJwt(jwt);
|
|
if (!decodedJwt?.payload?.own) {
|
|
logger.warn("Invalid JWT payload - missing 'own' field");
|
|
this.$notify({
|
|
group: "alert",
|
|
type: "danger",
|
|
title: "Invalid Contact Info",
|
|
text: "The contact information is incomplete or invalid.",
|
|
});
|
|
return;
|
|
}
|
|
|
|
const contactInfo = decodedJwt.payload.own;
|
|
if (!contactInfo.did) {
|
|
logger.warn("Invalid contact info - missing DID");
|
|
this.$notify({
|
|
group: "alert",
|
|
type: "danger",
|
|
title: "Invalid Contact",
|
|
text: "The contact DID is missing.",
|
|
});
|
|
return;
|
|
}
|
|
|
|
// Create contact object
|
|
const contact = {
|
|
did: contactInfo.did,
|
|
name: contactInfo.name || "",
|
|
email: contactInfo.email || "",
|
|
phone: contactInfo.phone || "",
|
|
company: contactInfo.company || "",
|
|
title: contactInfo.title || "",
|
|
notes: contactInfo.notes || "",
|
|
};
|
|
|
|
// Add contact and stop scanning
|
|
logger.info("Adding new contact to database:", {
|
|
did: contact.did,
|
|
name: contact.name,
|
|
});
|
|
await this.addNewContact(contact);
|
|
await this.stopScanning();
|
|
} catch (error) {
|
|
logger.error("Error processing contact QR code:", {
|
|
error: error instanceof Error ? error.message : String(error),
|
|
stack: error instanceof Error ? error.stack : undefined,
|
|
});
|
|
this.$notify({
|
|
group: "alert",
|
|
type: "danger",
|
|
title: "Error",
|
|
text:
|
|
error instanceof Error
|
|
? error.message
|
|
: "Could not process QR code. Please try again.",
|
|
});
|
|
}
|
|
}
|
|
|
|
async setVisibility(contact: Contact, visibility: boolean) {
|
|
const result = await setVisibilityUtil(
|
|
this.activeDid,
|
|
this.apiServer,
|
|
this.axios,
|
|
db,
|
|
contact,
|
|
visibility,
|
|
);
|
|
if (result.error) {
|
|
this.danger(result.error as string, "Error Setting Visibility");
|
|
} else if (!result.success) {
|
|
logger.warn("Unexpected result from setting visibility:", result);
|
|
}
|
|
}
|
|
|
|
async register(contact: Contact) {
|
|
logger.info("Submitting contact registration", {
|
|
did: contact.did,
|
|
name: contact.name,
|
|
});
|
|
this.$notify(
|
|
{
|
|
group: "alert",
|
|
type: "toast",
|
|
text: "",
|
|
title: "Registration submitted...",
|
|
},
|
|
1000,
|
|
);
|
|
|
|
try {
|
|
const regResult = await register(
|
|
this.activeDid,
|
|
this.apiServer,
|
|
this.axios,
|
|
contact,
|
|
);
|
|
if (regResult.success) {
|
|
contact.registered = true;
|
|
db.contacts.update(contact.did, { registered: true });
|
|
logger.info("Contact registration successful", { did: contact.did });
|
|
|
|
this.$notify(
|
|
{
|
|
group: "alert",
|
|
type: "success",
|
|
title: "Registration Success",
|
|
text:
|
|
(contact.name || "That unnamed person") + " has been registered.",
|
|
},
|
|
5000,
|
|
);
|
|
} else {
|
|
this.$notify(
|
|
{
|
|
group: "alert",
|
|
type: "danger",
|
|
title: "Registration Error",
|
|
text:
|
|
(regResult.error as string) ||
|
|
"Something went wrong during registration.",
|
|
},
|
|
5000,
|
|
);
|
|
}
|
|
} catch (error) {
|
|
logger.error("Error registering contact:", {
|
|
did: contact.did,
|
|
error: error instanceof Error ? error.message : String(error),
|
|
stack: error instanceof Error ? error.stack : undefined,
|
|
});
|
|
let userMessage = "There was an error.";
|
|
const serverError = error as AxiosError;
|
|
if (serverError) {
|
|
if (
|
|
serverError.response?.data &&
|
|
typeof serverError.response.data === "object" &&
|
|
"message" in serverError.response.data
|
|
) {
|
|
userMessage = (serverError.response.data as { message: string })
|
|
.message;
|
|
} else if (serverError.message) {
|
|
userMessage = serverError.message; // Info for the user
|
|
} else {
|
|
userMessage = JSON.stringify(serverError.toJSON());
|
|
}
|
|
} else {
|
|
userMessage = error as string;
|
|
}
|
|
// Now set that error for the user to see.
|
|
this.$notify(
|
|
{
|
|
group: "alert",
|
|
type: "danger",
|
|
title: "Registration Error",
|
|
text: userMessage,
|
|
},
|
|
5000,
|
|
);
|
|
}
|
|
}
|
|
|
|
onScanError(error: Error) {
|
|
this.error = error.message;
|
|
logger.error("QR code scan error:", {
|
|
error: error.message,
|
|
stack: error.stack,
|
|
});
|
|
}
|
|
|
|
onCopyUrlToClipboard() {
|
|
//this.onScanDetect([{ rawValue: this.qrValue }]); // good for testing
|
|
useClipboard()
|
|
.copy(this.qrValue)
|
|
.then(() => {
|
|
// console.log("Contact URL:", this.qrValue);
|
|
this.$notify(
|
|
{
|
|
group: "alert",
|
|
type: "toast",
|
|
title: "Copied",
|
|
text: "Contact URL was copied to clipboard.",
|
|
},
|
|
2000,
|
|
);
|
|
});
|
|
}
|
|
|
|
onCopyDidToClipboard() {
|
|
//this.onScanDetect([{ rawValue: this.qrValue }]); // good for testing
|
|
useClipboard()
|
|
.copy(this.activeDid)
|
|
.then(() => {
|
|
this.$notify(
|
|
{
|
|
group: "alert",
|
|
type: "info",
|
|
title: "Copied",
|
|
text: "Your DID was copied to the clipboard. Have them paste it in the box on their 'People' screen to add you.",
|
|
},
|
|
5000,
|
|
);
|
|
});
|
|
}
|
|
|
|
openUserNameDialog() {
|
|
(this.$refs.userNameDialog as IUserNameDialog).open((name: string) => {
|
|
this.givenName = name;
|
|
});
|
|
}
|
|
|
|
beforeDestroy() {
|
|
logger.info("Cleaning up QR scanner resources");
|
|
this.stopScanning(); // Ensure scanner is stopped
|
|
QRScannerFactory.cleanup();
|
|
}
|
|
|
|
async addNewContact(contact: Contact) {
|
|
try {
|
|
logger.info("Opening database connection for new contact");
|
|
await db.open();
|
|
await db.contacts.add(contact);
|
|
|
|
if (this.activeDid) {
|
|
logger.info("Setting contact visibility", { did: contact.did });
|
|
await this.setVisibility(contact, true);
|
|
contact.seesMe = true;
|
|
}
|
|
|
|
this.$notify(
|
|
{
|
|
group: "alert",
|
|
type: "success",
|
|
title: "Contact Added",
|
|
text: this.activeDid
|
|
? "They were added, and your activity is visible to them."
|
|
: "They were added.",
|
|
},
|
|
3000,
|
|
);
|
|
|
|
if (
|
|
this.isRegistered &&
|
|
!this.hideRegisterPromptOnNewContact &&
|
|
!contact.registered
|
|
) {
|
|
setTimeout(() => {
|
|
this.$notify(
|
|
{
|
|
group: "modal",
|
|
type: "confirm",
|
|
title: "Register",
|
|
text: "Do you want to register them?",
|
|
onCancel: async (stopAsking?: boolean) => {
|
|
if (stopAsking) {
|
|
await db.settings.update(MASTER_SETTINGS_KEY, {
|
|
hideRegisterPromptOnNewContact: stopAsking,
|
|
});
|
|
this.hideRegisterPromptOnNewContact = stopAsking;
|
|
}
|
|
},
|
|
onNo: async (stopAsking?: boolean) => {
|
|
if (stopAsking) {
|
|
await db.settings.update(MASTER_SETTINGS_KEY, {
|
|
hideRegisterPromptOnNewContact: stopAsking,
|
|
});
|
|
this.hideRegisterPromptOnNewContact = stopAsking;
|
|
}
|
|
},
|
|
onYes: async () => {
|
|
await this.register(contact);
|
|
},
|
|
promptToStopAsking: true,
|
|
},
|
|
-1,
|
|
);
|
|
}, 500);
|
|
}
|
|
} catch (error) {
|
|
logger.error("Error saving contact to database:", {
|
|
did: contact.did,
|
|
error: error instanceof Error ? error.message : String(error),
|
|
stack: error instanceof Error ? error.stack : undefined,
|
|
});
|
|
this.$notify(
|
|
{
|
|
group: "alert",
|
|
type: "danger",
|
|
title: "Contact Error",
|
|
text: "Could not save contact. Check if it already exists.",
|
|
},
|
|
5000,
|
|
);
|
|
}
|
|
}
|
|
|
|
// Add pause/resume handlers for mobile
|
|
mounted() {
|
|
document.addEventListener("pause", this.handleAppPause);
|
|
document.addEventListener("resume", this.handleAppResume);
|
|
}
|
|
|
|
beforeUnmount() {
|
|
document.removeEventListener("pause", this.handleAppPause);
|
|
document.removeEventListener("resume", this.handleAppResume);
|
|
}
|
|
|
|
handleAppPause() {
|
|
logger.info("App paused, stopping scanner");
|
|
this.stopScanning();
|
|
}
|
|
|
|
handleAppResume() {
|
|
logger.info("App resumed, scanner can be restarted by user");
|
|
// Don't auto-restart scanning - let user initiate it
|
|
this.isScanning = false;
|
|
}
|
|
}
|
|
</script>
|
|
|
|
<style scoped>
|
|
.aspect-square {
|
|
aspect-ratio: 1 / 1;
|
|
}
|
|
</style>
|