oauth.py
Overview
The oauth.py file provides a lightweight, reusable OAuth 2.0 client implementation designed to facilitate user authentication and authorization flows within the InfiniFlow system. It encapsulates the process of generating OAuth authorization URLs, exchanging authorization codes for access tokens, and fetching normalized user profile information from OAuth providers.
This file primarily contains two classes:
UserInfo: A simple data container for normalized user profile attributes.
OAuthClient: Manages OAuth 2.0 interactions including URL generation, token exchange, and user info retrieval.
The module leverages the requests library for HTTP communication and urllib.parse for URL parameter encoding. It is intended to be integrated into authentication components of the larger application, enabling secure and standardized OAuth-based user login and data retrieval from external providers.
Classes and Methods
Class: UserInfo
Represents normalized user profile information retrieved from an OAuth provider.
Attributes
Attribute | Type | Description |
|---|---|---|
| str | User's email address |
| str | Username identifier |
| str | User's display nickname |
| str | URL to the user's avatar or profile picture |
Methods
init(self, email, username, nickname, avatar_url)Initializes a
UserInfoinstance with provided user attributes.user = UserInfo( email="[email protected]", username="user123", nickname="User", avatar_url="https://example.com/avatar.png" )to_dict(self) -> dictReturns a dictionary representation of the user information.
Returns:
dict— Keys are attribute names (email,username,nickname,avatar_url), values are corresponding attribute values.user_dict = user.to_dict() # Example output: # { # "email": "[email protected]", # "username": "user123", # "nickname": "User", # "avatar_url": "https://example.com/avatar.png" # }
Class: OAuthClient
Handles OAuth 2.0 authorization flows and user info retrieval.
Initialization
oauth_client = OAuthClient(config)
Parameters:
Parameter
Type
Description
configdict
Configuration dictionary with keys:
client_id(str): OAuth client identifier
client_secret(str): OAuth client secret
authorization_url(str): URL to redirect users for authorization
token_url(str): URL to exchange code for access token
userinfo_url(str): URL to fetch user profile information
redirect_uri(str): Redirect URI registered with OAuth provider
scope(str, optional): OAuth scope string
Example:
config = { "client_id": "abc123", "client_secret": "secretXYZ", "authorization_url": "https://provider.com/oauth/authorize", "token_url": "https://provider.com/oauth/token", "userinfo_url": "https://provider.com/api/userinfo", "redirect_uri": "https://myapp.com/oauth/callback", "scope": "profile email" } oauth_client = OAuthClient(config)
Methods
get_authorization_url(self, state=None) -> strConstructs the OAuth authorization URL to which users are redirected to log in.
Parameters:
state(str, optional): An opaque value to maintain state between request and callback (e.g., CSRF token).
Returns:
str— Complete authorization URL with query parameters.Usage Example:
auth_url = oauth_client.get_authorization_url(state="xyz123") # Redirect user to auth_url for loginImplementation Details:
Uses URL parameters:
client_id,redirect_uri,response_type=code.Adds optional
scopeandstateparameters if provided.URL parameters are encoded for safe HTTP transmission.
exchange_code_for_token(self, code) -> dictExchanges the OAuth authorization code obtained from the callback for an access token.
Parameters:
code(str): Authorization code received from the OAuth provider after user consent.
Returns:
dict— JSON response parsed as a dictionary, typically containingaccess_token,token_type,expires_in, and optionallyrefresh_token.Raises:
ValueErrorif the HTTP request fails or the response is invalid.Usage Example:
token_response = oauth_client.exchange_code_for_token("auth_code_123") access_token = token_response.get("access_token")Implementation Details:
Sends a POST request to the token endpoint with required parameters:
client_id,client_secret,code,redirect_uri,grant_type=authorization_code.Uses a 7-second HTTP request timeout.
Handles HTTP exceptions and raises a
ValueErrorwith descriptive message.
fetch_user_info(self, access_token, **kwargs) -> UserInfoRetrieves user profile information from the OAuth provider using the access token.
Parameters:
access_token(str): OAuth 2.0 access token.**kwargs: Additional optional parameters (currently unused but reserved for extensibility).
Returns:
UserInfo— Instance containing normalized user profile details.Raises:
ValueErrorif the HTTP request fails or the response is invalid.Usage Example:
user_info = oauth_client.fetch_user_info(access_token) print(user_info.to_dict())Implementation Details:
Sends a GET request to the
userinfo_urlwithAuthorization: Bearer <token>header.Parses JSON response and passes it to
normalize_user_infomethod.Handles HTTP exceptions gracefully by raising
ValueError.
normalize_user_info(self, user_info: dict) -> UserInfoNormalizes raw user info dictionary from the OAuth provider into a
UserInfoinstance.Parameters:
user_info(dict): Raw user profile data returned from the provider.
Returns:
UserInfo— Normalized user profile object.Usage Example:
normalized_user = oauth_client.normalize_user_info(raw_user_info)Implementation Details:
Extracts
email,username,nickname, andavatar_urlfields.Defaults:
usernamedefaults to the portion of email before '@' if missing.nicknamedefaults tousernameif missing.avatar_urltriesavatar_urlkey or falls back topicturekey or empty string.
Ensures consistent user info representation across different OAuth providers.
Important Implementation Details
Timeout Handling:
All HTTP requests use a fixed 7-second timeout (self.http_request_timeout) to avoid hanging requests.Error Handling:
Network or HTTP errors during token exchange and user info fetching raiseValueErrorwith descriptive messages, which should be handled by the caller for user feedback or retries.Normalization:
Different OAuth providers may return user profile data with varying field names; this implementation normalizes key user attributes for consistent consumption.Stateless Authorization URL Generation:
Theget_authorization_urlmethod allows optionalstateparameter to mitigate CSRF attacks by maintaining client state.
Interaction with Other System Components
Authentication Workflows:
This file would be used by authentication controllers or middleware components responsible for user login flows using OAuth 2.0.Configuration Management:
Theconfigdictionary passed toOAuthClienttypically comes from the system's centralized configuration management, allowing easy switching between OAuth providers.User Session Management:
After obtaining user info via this client, the system can create or update user sessions, permissions, and profiles accordingly.HTTP Requests:
Relies on therequestslibrary for external HTTP communication with OAuth providers' endpoints.URL Routing:
The redirect URI and authorization URL generated here are critical for routing users to/from the OAuth provider during login.
Visual Diagram
classDiagram
class UserInfo {
+email: str
+username: str
+nickname: str
+avatar_url: str
+to_dict() dict
}
class OAuthClient {
-client_id: str
-client_secret: str
-authorization_url: str
-token_url: str
-userinfo_url: str
-redirect_uri: str
-scope: str
-http_request_timeout: int
+get_authorization_url(state=None) str
+exchange_code_for_token(code) dict
+fetch_user_info(access_token, **kwargs) UserInfo
+normalize_user_info(user_info) UserInfo
}
OAuthClient o-- UserInfo : uses
Summary
The oauth.py file is a core utility module that encapsulates OAuth 2.0 client functionality, simplifying the integration of third-party OAuth providers for user authentication and profile retrieval. Its design focuses on clean abstraction, error handling, and normalization to support robust and flexible authentication workflows within the InfiniFlow platform.