Skip to content

Commit

Permalink
Add authentication logging and fix useEffect dependency
Browse files Browse the repository at this point in the history
  • Loading branch information
b3hr4d committed Apr 4, 2024
1 parent 1541d02 commit 1935427
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 8 deletions.
11 changes: 8 additions & 3 deletions packages/core/src/classes/agent/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-console */
import { HttpAgent } from "@dfinity/agent"
import { createStoreWithOptionalDevtools } from "../../utils/helper"
import { AuthClient } from "@dfinity/auth-client"
Expand Down Expand Up @@ -150,12 +151,14 @@ export class AgentManager {
}

public authenticate = async () => {
console.log(
`Authenticating on ${this.getIsLocal() ? "local" : "ic"} network`
)
this.updateAuthState({ authenticating: true }, "authenticating")

try {
this._auth = await AuthClient.create()
const authenticated = await this._auth.isAuthenticated()

const identity = this._auth.getIdentity()

this._agent.replaceIdentity(identity)
Expand Down Expand Up @@ -195,9 +198,11 @@ export class AgentManager {
? LOCAL_INTERNET_IDENTITY_PROVIDER
: IC_INTERNET_IDENTITY_PROVIDER,
...options,
onSuccess: async (msg) => {
await this.authenticate()
options?.onSuccess?.(msg)
},
})

await this.authenticate()
}

public logout = async (options?: { returnTo?: string }) => {
Expand Down
6 changes: 2 additions & 4 deletions packages/react/src/helpers/authHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,12 +137,10 @@ export const authHooks = (agentManager: AgentManager): AuthHooksReturnType => {
)

React.useEffect(() => {
const authClient = getAuth()

if (!authClient && !authenticating) {
if (!authenticating && !authenticated) {
authenticate()
}
}, [authenticating])
}, [])

return {
authenticated,
Expand Down
9 changes: 8 additions & 1 deletion packages/react/test/__snapshots__/context.spec.tsx.snap
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,14 @@ exports[`createReactor should query 2`] = `

exports[`createReactor should query 3`] = `
<div>
Fetching canister...
<button
onClick={[Function]}
>
Get Version
</button>
<span>
Ready To call
</span>
</div>
`;

Expand Down

0 comments on commit 1935427

Please sign in to comment.