wstrange / GoogleAuth

Google Authenticator Server side code
BSD 3-Clause "New" or "Revised" License
1.05k stars 328 forks source link

Get time remaining #81

Open joshstrange opened 5 years ago

joshstrange commented 5 years ago

I'm going to look to see if there is another way to calculate this (I'm sure there is) but it would be nice if there was a public method on GoogleAuthenticator to return the time that a pin generated would be valid for.

Like I said I'm sure I can do some math but I'm using this as a client and I would like to be able to display a countdown to the user. Yes I know the window size means the number will be larger but I also want to show the new code as soon as it becomes valid.

joshstrange commented 5 years ago

It looks like this should be as simple as:

120 - (Math.round((new GregorianCalendar()).getTimeInMillis() / 1000) % 120)

Where 120 is the second you make it valid:

.setTimeStepSizeInMillis(TimeUnit.SECONDS.toMillis(120))

Of course your window size will probably make it valid for LONGER but for the purposes of UI this gives me an accurate countdown. In the end since this is for a web app I'll probably just do the calculation in javascript on the front end:

console.log(120 - Math.round(new Date() / 1000) % 120)

Yes, the web front end is acting like a TOTP generator for another device, I know it sounds weird but trust me, it's what I want for the project I'm working on.