1
+ 'use client' ;
2
+
3
+ import { useEffect , useState } from 'react' ;
4
+ import * as fcl from '@onflow/fcl' ;
5
+ import { event } from '@site/src/utils/gtags.client' ;
6
+
7
+ interface FlowUser {
8
+ addr : string | null ;
9
+ loggedIn : boolean ;
10
+ }
11
+
12
+ interface UseCurrentUserReturn {
13
+ user : FlowUser ;
14
+ logIn : ( ) => Promise < void > ;
15
+ logOut : ( ) => void ;
16
+ }
17
+
18
+ async function hashAddress ( address : string ) : Promise < string > {
19
+ const encoder = new TextEncoder ( ) ;
20
+ const data = encoder . encode ( address ) ;
21
+ const hashBuffer = await crypto . subtle . digest ( 'SHA-256' , data ) ;
22
+ const hashArray = Array . from ( new Uint8Array ( hashBuffer ) ) ;
23
+ const hashHex = hashArray
24
+ . map ( ( byte ) => byte . toString ( 16 ) . padStart ( 2 , '0' ) )
25
+ . join ( '' ) ;
26
+ return hashHex ;
27
+ }
28
+
29
+ export function useCurrentUser ( ) : UseCurrentUserReturn {
30
+ const [ user , setUser ] = useState < FlowUser > ( { addr : null , loggedIn : false } ) ;
31
+
32
+ useEffect ( ( ) => {
33
+ const unsubscribe = fcl . currentUser . subscribe ( setUser ) ;
34
+ return ( ) => unsubscribe ( ) ;
35
+ } , [ ] ) ;
36
+
37
+ const logIn = async ( ) : Promise < void > => {
38
+ try {
39
+ await fcl . authenticate ( ) ;
40
+
41
+ const snapshot = await fcl . currentUser . snapshot ( ) ;
42
+ const userAddrSnapshot = snapshot ?. addr ;
43
+
44
+ if ( userAddrSnapshot ) {
45
+ const hashedAddr = await hashAddress ( userAddrSnapshot ) ;
46
+
47
+ event ( {
48
+ category : 'auth' ,
49
+ action : 'login' ,
50
+ label : `user_${ hashedAddr } ` ,
51
+ value : 1 ,
52
+ } ) ;
53
+ } else {
54
+ event ( {
55
+ category : 'auth' ,
56
+ action : 'login' ,
57
+ label : 'unknown_user' ,
58
+ value : 1 ,
59
+ } ) ;
60
+ }
61
+ } catch ( error ) {
62
+ console . error ( 'Error during login:' , error ) ;
63
+ }
64
+ } ;
65
+
66
+ const logOut = ( ) : void => {
67
+ fcl . unauthenticate ( ) ;
68
+ } ;
69
+
70
+ return {
71
+ user,
72
+ logIn,
73
+ logOut,
74
+ } ;
75
+ }
0 commit comments