Skip to content

Commit 463c19f

Browse files
committed
docs: Adds Google OAuth authentication
Adds Google OAuth authentication to enable users to register and log in using their Google accounts. This includes: - Documentation for Google Cloud setup - Configuration options for `nuxt.config.ts` - Database migration instructions - Usage examples for the `NUsersGoogleLoginButton` component - Details on the OAuth flow, user account linking, security features, and error handling. Fixes #17
1 parent e830872 commit 463c19f

File tree

1 file changed

+181
-0
lines changed

1 file changed

+181
-0
lines changed

docs/user-guide/authentication.md

Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -666,6 +666,186 @@ For accessing the current user in client-side components, see the [`getCurrentUs
666666

667667
For error handling with the `useAuthentication` composable, refer to the [Composables documentation](/user-guide/composables.md#useauthentication).
668668

669+
## Google OAuth Authentication
670+
671+
The module provides built-in support for Google OAuth authentication, allowing users to register and login using their Google accounts.
672+
673+
### Google Cloud Setup
674+
675+
Before implementing Google OAuth, you need to set up a project in Google Cloud Console:
676+
677+
1. **Create a Google Cloud Project**:
678+
- Go to [Google Cloud Console](https://console.cloud.google.com/)
679+
- Create a new project or select an existing one
680+
681+
2. **Enable Google+ API**:
682+
- Navigate to "APIs & Services" > "Library"
683+
- Search for "Google+ API" or "People API"
684+
- Click "Enable"
685+
686+
3. **Create OAuth 2.0 Credentials**:
687+
- Go to "APIs & Services" > "Credentials"
688+
- Click "Create Credentials" > "OAuth 2.0 Client ID"
689+
- Choose "Web application"
690+
- Add your callback URL: `https://yourdomain.com/api/nuxt-users/auth/google/callback`
691+
- Save your Client ID and Client Secret
692+
693+
### Configuration
694+
695+
Add Google OAuth configuration to your `nuxt.config.ts`:
696+
697+
```ts
698+
export default defineNuxtConfig({
699+
modules: ['nuxt-users'],
700+
nuxtUsers: {
701+
auth: {
702+
google: {
703+
clientId: process.env.GOOGLE_CLIENT_ID!,
704+
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
705+
// Optional: customize URLs and scopes
706+
callbackUrl: '/api/nuxt-users/auth/google/callback',
707+
successRedirect: '/dashboard',
708+
errorRedirect: '/login?error=oauth_failed',
709+
scopes: ['openid', 'profile', 'email']
710+
}
711+
}
712+
}
713+
})
714+
```
715+
716+
### Environment Variables
717+
718+
Add your Google OAuth credentials to your environment variables:
719+
720+
```bash
721+
# .env
722+
GOOGLE_CLIENT_ID=your_google_client_id_here
723+
GOOGLE_CLIENT_SECRET=your_google_client_secret_here
724+
```
725+
726+
### Database Migration
727+
728+
For existing databases, run the migration to add Google OAuth fields:
729+
730+
```bash
731+
# Add google_id and profile_picture columns to users table
732+
npx nuxt-users add-google-oauth-fields
733+
```
734+
735+
For new installations, the fields are automatically included when creating the users table.
736+
737+
### Using the Google Login Button
738+
739+
The module provides a ready-to-use `NUsersGoogleLoginButton` component:
740+
741+
```vue
742+
<template>
743+
<div class="login-page">
744+
<h1>Sign In</h1>
745+
746+
<!-- Traditional login form -->
747+
<NUsersLoginForm @success="handleLoginSuccess" />
748+
749+
<!-- Divider -->
750+
<div class="divider">
751+
<span>or</span>
752+
</div>
753+
754+
<!-- Google OAuth button -->
755+
<NUsersGoogleLoginButton
756+
@click="handleGoogleLogin"
757+
button-text="Sign in with Google"
758+
class="google-login-btn"
759+
/>
760+
</div>
761+
</template>
762+
763+
<script setup>
764+
const handleLoginSuccess = (user) => {
765+
console.log('Login successful:', user)
766+
await navigateTo('/dashboard')
767+
}
768+
769+
const handleGoogleLogin = () => {
770+
console.log('Starting Google OAuth flow')
771+
}
772+
</script>
773+
```
774+
775+
### Component Props
776+
777+
The `NUsersGoogleLoginButton` component accepts these props:
778+
779+
- **`buttonText`** (string): Button text (default: "Continue with Google")
780+
- **`showLogo`** (boolean): Show Google logo (default: true)
781+
- **`redirectEndpoint`** (string): Custom OAuth redirect endpoint
782+
- **`class`** (string): Custom CSS class
783+
784+
### OAuth Flow
785+
786+
The Google OAuth authentication flow works as follows:
787+
788+
1. **User clicks Google login button** → Redirects to `/api/nuxt-users/auth/google/redirect`
789+
2. **Redirect to Google** → User is sent to Google's OAuth consent screen
790+
3. **User grants permission** → Google redirects back to `/api/nuxt-users/auth/google/callback`
791+
4. **Process OAuth response** → Module exchanges code for user info
792+
5. **Create or link account** → User is created or existing account is linked
793+
6. **Set authentication cookie** → User is logged in with persistent session
794+
7. **Redirect to success page** → User is redirected to configured success URL
795+
796+
### User Account Linking
797+
798+
The module intelligently handles user account linking:
799+
800+
- **New Google user**: Creates a new account with secure random password
801+
- **Existing email**: Links Google account to existing user account
802+
- **Returning Google user**: Logs in existing user and updates profile picture
803+
804+
### Security Features
805+
806+
- **Secure password generation**: OAuth users get cryptographically secure random passwords
807+
- **Email verification**: Only verified Google emails are accepted
808+
- **Account activation**: Inactive accounts are blocked from OAuth login
809+
- **Profile picture sync**: User profile pictures are automatically updated
810+
- **Token management**: Uses the same secure token system as password authentication
811+
812+
### Error Handling
813+
814+
The OAuth flow handles various error scenarios:
815+
816+
- **OAuth denied**: User cancels Google consent → redirects to error page
817+
- **Invalid configuration**: Missing client ID/secret → shows configuration error
818+
- **Account inactive**: Inactive user attempts login → redirects with error message
819+
- **API errors**: Google API failures → logs error and redirects safely
820+
821+
### Customization
822+
823+
You can customize the OAuth behavior:
824+
825+
```ts
826+
// nuxt.config.ts
827+
export default defineNuxtConfig({
828+
nuxtUsers: {
829+
auth: {
830+
google: {
831+
clientId: process.env.GOOGLE_CLIENT_ID!,
832+
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
833+
834+
// Customize redirect URLs
835+
successRedirect: '/welcome', // After successful login
836+
errorRedirect: '/login?error=google_failed', // After failed login
837+
838+
// Request additional permissions
839+
scopes: ['openid', 'profile', 'email', 'https://www.googleapis.com/auth/user.birthday.read'],
840+
841+
// Custom callback URL (must match Google Cloud Console)
842+
callbackUrl: '/api/nuxt-users/auth/google/callback'
843+
}
844+
}
845+
}
846+
})
847+
```
848+
669849
## Security Best Practices
670850

671851
1. **Use HTTPS**: Always use HTTPS in production to protect credentials in transit
@@ -677,6 +857,7 @@ For error handling with the `useAuthentication` composable, refer to the [Compos
677857
7. **Error messages**: Don't reveal too much information in error messages
678858
8. **Monitoring**: Monitor authentication attempts and failures
679859
9. **Regular updates**: Keep the module and dependencies updated
860+
10. **OAuth security**: Keep your Google Client Secret secure and never expose it to the client
680861

681862
## Next Steps
682863

0 commit comments

Comments
 (0)