# Login Implementation

## How It Works

The Deva SDK provides the `useDeva` hook that handles the entire authentication flow. When you call the `login` function, it automatically initiates the secure OAuth login process.

***

## Implementation

```tsx
import { useDeva } from "@bitplanet/deva-sdk";

function LoginButton() {
  const { login, isAuthenticated, isReady } = useDeva();

  if (!isReady) {
    return <div>Loading...</div>;
  }

  if (isAuthenticated) {
    return <div>Already logged in</div>;
  }

  return <button onClick={login}>Login with Deva</button>;
}
```

***

## What Happens When User Clicks Login

1. **Clear Previous State** - Any existing authentication state is cleared
2. **Generate PKCE Challenge** - SDK creates a secure code verifier and challenge
3. **Redirect to Deva** - User is taken to Deva's login page with authentication parameters
4. **User Authenticates** - User logs in and grants permissions
5. **Return to App** - User is redirected back with an authorization code
6. **Token Exchange** - SDK automatically exchanges the code for access tokens
7. **Authenticated** - User is now logged in and `isAuthenticated` becomes `true`

This entire process is handled automatically by the SDK. Learn more about the [OAuth Authorization](https://sdkdocs.deva.me/oauth-integration#authorization-flow) flow.

***

## useDeva Hook Properties

```tsx
const {
  login,           // Function to initiate login
  isAuthenticated, // Boolean - true if user is logged in
  isReady,        // Boolean - true when SDK is initialized
  user,           // User profile data (null if not logged in)
  accessToken     // Access token for API calls (null if not logged in)
} = useDeva();
```

***

## Best Practices

**Check isReady** Always check `isReady` before rendering login UI to avoid showing the button before the SDK is initialized.

**Handle Loading States** Show a loading indicator while `isReady` is false.

**Conditional Rendering** Only show the login button when `isAuthenticated` is false.

***

## Related Documentation

* [Deva SSO](https://sdkdocs.deva.me/authentication/deva-sso) - Why use Deva authentication
* [OAuth Integration](https://sdkdocs.deva.me/authentication/oauth-integration) - Technical OAuth flow details
* [Authentication Flow](https://sdkdocs.deva.me/core-concepts/authentication-flow) - How authentication works
* [Logout Handling](https://sdkdocs.deva.me/authentication/logout-handling) - Implement logout functionality
* [Token Management](https://sdkdocs.deva.me/authentication/token-management) - Understand token lifecycle
