<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>React &#8211; hackanooga</title>
	<atom:link href="/tag/react/feed/" rel="self" type="application/rss+xml" />
	<link>/</link>
	<description>Confessions of a homelab hacker</description>
	<lastBuildDate>Wed, 13 Mar 2024 16:14:24 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.6.2</generator>

<image>
	<url>/wp-content/uploads/2024/03/cropped-cropped-avatar-32x32.png</url>
	<title>React &#8211; hackanooga</title>
	<link>/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Roll your own authenticator app with KeystoneJS and React &#8211; pt 3</title>
		<link>/roll-your-own-authenticator-app-with-keystonejs-and-react-pt-3/</link>
		
		<dc:creator><![CDATA[mikeconrad]]></dc:creator>
		<pubDate>Wed, 17 Jan 2024 17:11:00 +0000</pubDate>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Authentication]]></category>
		<category><![CDATA[Blog Post]]></category>
		<category><![CDATA[React]]></category>
		<category><![CDATA[TypeScript]]></category>
		<guid isPermaLink="false">/?p=546</guid>

					<description><![CDATA[In our previous post we got to the point of displaying an OTP in our card component. Now it is time to refactor a bit and implement a countdown functionality to see when this token will expire. For now we will go ahead and add this logic into our Card component. In order to figure [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>In our previous post we got to the point of displaying an OTP in our card component.  Now it is time to refactor a bit and implement a countdown functionality to see when this token will expire.  For now we will go ahead and add this logic into our Card component.  In order to figure out how to build this countdown timer we first need to understand how the TOTP counter is calculated.</p>



<p>In other words, we know that at TOTP token is derived from a secret key and the current time.  If we dig into the spec some we can find that time is a reference to Linux epoch time or the number of seconds that have elapsed since January 1st 1970.  For a little more clarification check out this Stackexchange <a href="https://crypto.stackexchange.com/questions/72558/what-time-is-used-in-a-totp-counter">article</a>.</p>



<p>So if we know that the time is based on epoch time, we also need to know that most TOTP tokens have a validity period of either 30 seconds or 60 seconds.  30 seconds is the most common standard so we will use that for our implementation.  If we put all that together then basically all we need is 2 variables:</p>



<ol class="wp-block-list">
<li>Number of seconds since epoch</li>



<li>How many seconds until this token expires</li>
</ol>



<p>The first one is easy:</p>



<pre class="wp-block-code"><code>let secondsSinceEpoch;
secondsSinceEpoch = Math.ceil(Date.now() / 1000) - 1;

# This gives us a time like so: 1710338609</code></pre>



<p>For the second one we will need to do a little math but it&#8217;s pretty straightforward.  We need to divide <code>secondsSinceEpoch</code> by 30 seconds and then subtract this number from 30.  Here is what that looks like:</p>



<pre class="wp-block-code"><code>let secondsSinceEpoch;
let secondsRemaining;
const period = 30;

secondsSinceEpoch = Math.ceil(Date.now() / 1000) - 1;
secondsRemaining = period - (secondsSinceEpoch % period);</code></pre>



<p>Now let&#8217;s put all of that together into a function that we can test out to make sure we are getting the results we expect.</p>



<pre class="wp-block-code"><code>const timer = setInterval(() => {
  countdown()
}, 1000)

function countdown() {
  let secondsSinceEpoch;
  let secondsRemaining;

  const period = 30;
  secondsSinceEpoch = Math.ceil(Date.now() / 1000) - 1;

  secondsRemaining = period - (secondsSinceEpoch % period);
  console.log(secondsSinceEpoch, secondsRemaining)
  if (secondsRemaining == 1) {
    console.log("timer done")
    clearInterval(timer)
  }
}
</code></pre>



<p>Running this function should give you output similar to the following.  In this example we are stopping the timer once it hits 1 second just to show that everything is working as we expect.  In our application we will want this time to keep going forever:</p>



<pre class="wp-block-code"><code>1710339348, 12
1710339349, 11
1710339350, 10
1710339351, 9
1710339352, 8
1710339353, 7
1710339354, 6
1710339355, 5
1710339356, 4
1710339357, 3
1710339358, 2
1710339359, 1
"timer done"</code></pre>



<p>Here is a JSfiddle that shows it in action: https://jsfiddle.net/561vg3k7/</p>



<p>We can go ahead and add this function to our Card component and get it wired up.  I am going to skip ahead a bit and add a progress bar to our card that is synced with our countdown timer and changes colors as it drops below 10 seconds.  For now we will be using a <code>setInterval</code> function to accomplish this. </p>



<p>Here is what my updated <code>src/Components/Card.tsx</code> looks like:</p>



<pre class="wp-block-code"><code>import { useState } from "react";
import { IToken } from "../App"
import { TOTP } from 'totp-generator';


function Card({ token }: { token: IToken }) {
  const { otp } = TOTP.generate(token.token);
  const &#91;timerStyle, setTimerStyle] = useState("");
  const &#91;timerWidth, setTimerWidth] = useState("");


  function countdown() {
    let secondsSinceEpoch: number;
    let secondsRemaining: number = 30;
    const period = 30;
    secondsSinceEpoch = Math.ceil(Date.now() / 1000) - 1;
    secondsRemaining = period - (secondsSinceEpoch % period);
    setTimerWidth(`${100 - (100 / 30 * (30 - secondsRemaining))}%`)
    setTimerStyle(secondsRemaining &lt; 10 ? "salmon" : "lightgreen")
  }
  setInterval(() => {
    countdown();
  }, 250);
  return (
    &lt;>
      &lt;div className='card'>
        &lt;div className='progressBar'style={{ width: timerWidth, backgroundColor: timerStyle}}>&lt;/div>
        &lt;span>{token.issuer}&lt;/span>
        &lt;span>{token.account}&lt;/span>
        &lt;span >{otp}&lt;/span>
      &lt;/div>
    &lt;/>

  )
}
export default Card</code></pre>



<p>Pretty straightforward.  I also updated my <code>src/index.css</code> and added a style for our progress bar:</p>



<pre class="wp-block-code"><code>.progressBar {
  height: 10px;
  position: absolute;
  top: 0;
  left: 0;
  right: inherit;
}
// Also be sure to add position:relative to .card which is the parent of this.</code></pre>



<p>Here is what it all looks like in action:</p>



<figure class="wp-block-video"><video controls src="/wp-content/uploads/2024/03/otp-countdown.mp4"></video></figure>



<p>If you look closely you will notice a few interesting things.  First is that the color of the progress bar changes from green to red.  This is handled by our <code>timerStyle</code> variable.  That part is pretty simple, if the timer is less than 10 seconds we set the background color as salmon otherwise we use light green.  The width of the progress bar is controlled by `${100 &#8211; (100 / 30 * (30 &#8211; secondsRemaining))}%`</p>



<p>The other interesting thing to note is that when the timer runs out it automatically restarts at 30 seconds with a new OTP.  This is due to the fact that this component is re-rendering every 1/4 second and every time it re-renders it is running the entire function body including: <code>const { otp } = TOTP.generate(token.token);</code>.  </p>



<p>This is to be expected since we are using React and we are just using a setInterval.  It may be a little unexpected though if you aren&#8217;t as familiar with React render cycles.  For our purposes this will work just fine for now.  Stay tuned for pt 4 of this series where we wire up the backend API.</p>
]]></content:encoded>
					
		
		<enclosure url="/wp-content/uploads/2024/03/otp-countdown.mp4" length="29730" type="video/mp4" />

			</item>
	</channel>
</rss>
