Skip to content

Commit

Permalink
Merge pull request #39 from UselessStudio/hotfix/invalid-uri
Browse files Browse the repository at this point in the history
Check if url is invalid
  • Loading branch information
LowderPlay authored Jul 29, 2024
2 parents 67681a9 + 41f2bc6 commit 84f5abf
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 25 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "teleotp",
"private": true,
"version": "0.3.0",
"version": "0.3.1",
"type": "module",
"homepage": "https://github.com/UselessStudio/TeleOTP",
"scripts": {
Expand Down
51 changes: 29 additions & 22 deletions src/hooks/useAccount.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,37 @@
import {useEffect, useState} from "react";
import {HOTP, URI} from "otpauth";
import {HOTP, TOTP, URI} from "otpauth";

export default function useAccount(accountUri?: string): { code: string, period: number, progress: number } {
const [code, setCode] = useState("N/A");
const [period, setPeriod] = useState(30);
useEffect(() => {
if (!accountUri) return;
const otp = URI.parse(accountUri);
if (otp instanceof HOTP) {
throw new Error("HOTP is not supported");
}
const [code, setCode] = useState("N/A");
const [period, setPeriod] = useState(30);
useEffect(() => {
if (!accountUri) return;
let otp: HOTP | TOTP;
try {
otp = URI.parse(accountUri);
} catch (e) {
console.error("weird uri!", accountUri);
setCode("N/A");
return;
}
if (otp instanceof HOTP) {
throw new Error("HOTP is not supported");
}

setPeriod(otp.period);
let timeout: NodeJS.Timeout | null = null;
setPeriod(otp.period);
let timeout: NodeJS.Timeout | null = null;

function cycle() {
setCode(otp.generate());
const untilNext = period - (Math.floor(Date.now() / 1000) % period);
timeout = setTimeout(cycle, untilNext * 1000);
}
cycle();
function cycle() {
setCode(otp.generate());
const untilNext = period - (Math.floor(Date.now() / 1000) % period);
timeout = setTimeout(cycle, untilNext * 1000);
}
cycle();

return () => {
if (timeout) clearTimeout(timeout);
}
}, [accountUri, period]);
return () => {
if (timeout) clearTimeout(timeout);
}
}, [accountUri, period]);


const [progress, setProgress] = useState(0);
Expand All @@ -39,4 +46,4 @@ export default function useAccount(accountUri?: string): { code: string, period:
};
}, [accountUri, period]);
return {code, period, progress};
}
}

0 comments on commit 84f5abf

Please sign in to comment.