The Google driver allows you to authenticate users via Google OAuth2. It supports fetching user profile information such as name, email, and profile picture. You can initiate a redirect to Google's authorization page and handle the callback to retrieve the user's profile.
Redirecting to Google
To start the authentication process, use ally.use('google').redirect(). You can customize the requested scopes within the redirect callback.
Handling the Callback
In your callback route, you should check for common OAuth errors like access denial, state mismatch, or other errors before attempting to fetch the user profile.
Fetching the User
Once the callback is successful, use google.user() to retrieve the user's profile and access token, or google.userFromToken(token) if you already have an access token.
// 1. Redirect to Google
router.get('/google/redirect', ({ ally }) => {
return ally.use('google').redirect((request) => {
request.scopes(['userinfo.email', 'userinfo.profile', 'calendar.readonly'])
})
})
// 2. Handle Callback
router.get('/google/callback', async ({ ally }) => {
const google = ally.use('google')
if (google.accessDenied()) {
return 'Access was denied'
}
if (google.stateMisMatch()) {
return 'State mismatch error'
}
if (google.hasError()) {
return google.getError()
}
const user = await google.user()
return user
})