How to fetch user picture and store it in DB while using Google OAuth2? #1386
Replies: 3 comments 4 replies
-
I don't save images/avatars to the database myself. If you have successfully bound google oauth. You can do this. ref https://fastapi-users.github.io/fastapi-users/latest/usage/current-user/ https://github.com/frankie567/httpx-oauth/blob/master/httpx_oauth/clients/google.py#L35 from httpx_oauth.clients.google import PROFILE_ENDPOINT, GoogleOAuth2
class MyGoogleOAuth2(GoogleOAuth2):
async def get_photos(self, token: str) -> str:
async with self.get_httpx_client() as client:
response = await client.get(
PROFILE_ENDPOINT,
params={'personFields': 'photos'},
headers={
**self.request_headers,
'Authorization': f'Bearer {token}',
},
)
if response.status_code >= 400:
# Show Error
raise
data = response.json()
photos_url = next(photo['url'] for photo in data['photos'])
return photos_url
google_oauth_client = MyGoogleOAuth2(client_id=..., client_secret=...)
@app.get('/oauth-google-photos')
async def oauth_google_photos(
user: UserModel = Depends(current_active_verified_user),
) -> dict[str, str]:
google = next(
(
oauth
for oauth in user.oauth_accounts
if oauth.oauth_name == 'google'
),
None,
)
url = await google_oauth_client.get_photos(token=google.access_token)
return {'url': url} You can get
If you want to change the size, set |
Beta Was this translation helpful? Give feedback.
-
FastAPI Users only fetch the ID and the email from the external OAuth provider. If you need more, you'll need to implement it yourself. The easiest way is probably to do it in the There, you have access to the user; so you can very well retrieve the Google's access token from the OAuthAccount table and make all the API requests you need to do, and save the response. If you want to do it all at once, you can override the fastapi-users/fastapi_users/router/oauth.py Lines 110 to 112 in 61dba26 You can replace it with a custom API call to Google to retrieve all the data you need. |
Beta Was this translation helpful? Give feedback.
-
So I've to override the function. Thanks @hgalytoby @frankie567 🙏🏻 |
Beta Was this translation helpful? Give feedback.
-
Hi 👋🏻
I'm following the official guide and everything seems file. However, Logged in user picture/avatar is missing from my DB I inspected a lot but couldn't find how to implement it, Can somebody help?
Thanks 😇
Beta Was this translation helpful? Give feedback.
All reactions