@@ -4,8 +4,10 @@ import CommonCrypto
44fileprivate let CHANGE_EVENT_NAME = " onTotpUpdate "
55
66public class ExpoTotpModule : Module {
7+
78 private var timer : Timer ?
89
10+
911 public func definition( ) -> ModuleDefinition {
1012 Name ( " ExpoTotp " )
1113
@@ -23,19 +25,30 @@ public class ExpoTotpModule: Module {
2325
2426 }
2527
26- private func getTotp ( secretKey : String , options : TotpOptions ? ) -> [ String : Any ] ? {
27- let secretBase64 = Data ( secretKey . utf8 ) . base64EncodedString ( )
28+
29+ private func getTotp ( secretKey : String , options : TotpOptions ? ) throws -> [ String : Any ] {
2830 let finalOptions = options ?? TotpOptions ( )
31+ let secretBase64 = Data ( secretKey. utf8) . base64EncodedString ( )
2932
30- return computeTotp ( secretBase64: secretBase64, options: finalOptions)
33+ guard let totpInfo = try ? computeTotp ( secretBase64: secretBase64, options: finalOptions) else {
34+ throw Exceptions . InvalidSecretKey ( )
35+ }
36+ return totpInfo
3137 }
3238
33- private func startUpdates( secretKey: String , options: TotpOptions ? ) {
39+
40+ private func startUpdates( secretKey: String , options: TotpOptions ? ) throws {
41+
3442 stopUpdates ( )
3543
44+ let finalOptions = options ?? TotpOptions ( )
45+
3646 let secretBase64 = Data ( secretKey. utf8) . base64EncodedString ( )
3747
38- let finalOptions = options ?? TotpOptions ( )
48+ guard let totpInfo = computeTotp ( secretBase64: secretBase64, options: finalOptions) else {
49+ throw Exceptions . InvalidSecretKey ( )
50+ }
51+ sendEvent ( CHANGE_EVENT_NAME, totpInfo)
3952
4053 DispatchQueue . main. async { [ weak self] in
4154 guard let self else { return }
@@ -47,21 +60,26 @@ public class ExpoTotpModule: Module {
4760 sendEvent ( CHANGE_EVENT_NAME, totpInfo)
4861 }
4962 }
63+
5064 }
5165
66+
5267 private func stopUpdates( ) {
68+
5369 timer? . invalidate ( )
5470 timer = nil
71+
5572 }
5673
74+
5775 private func computeTotp( secretBase64: String , options: TotpOptions ) -> [ String : Any ] ? {
76+
5877 let currentTime = Int ( Date ( ) . timeIntervalSince1970)
5978 let remainingTime = options. interval - currentTime % options. interval
6079 let currentInterval = currentTime / options. interval
6180
6281 guard let keyData = Data ( base64Encoded: secretBase64) else {
63- NSLog ( " Invalid secret provided " )
64- return nil
82+ return nil
6583 }
6684
6785 // Create message for HMAC
@@ -92,5 +110,7 @@ public class ExpoTotpModule: Module {
92110 " remainingTime " : remainingTime,
93111 " progress " : ( Double ( remainingTime) / Double( options. interval) ) * 100
94112 ]
113+
95114 }
115+
96116}
0 commit comments