user_app.py
Overview
The user_app.py file is a Flask-based module that handles user authentication, registration, profile management, and tenant-related operations within the InfiniFlow platform. It provides RESTful endpoints for user login (including OAuth via multiple channels), logout, registration, user settings updates, and retrieving user and tenant information.
This file integrates tightly with the database services managing users and tenants, authentication clients for OAuth providers, and utility functions for request validation, response construction, and secure password handling. It also supports multi-tenant architecture by exposing tenant info endpoints.
Detailed Documentation
Flask Blueprint
The file registers routes on a Flask manager blueprint (assumed to be defined elsewhere in the application).
All routes are decorated with HTTP methods and some with
@login_requiredto enforce authentication.
Routes and Their Functions
1. login()
Endpoint:
/loginMethods: POST, GET
Purpose: Authenticate users using email and password.
Parameters: JSON body containing:
email(string): User's email.password(string): Encrypted password.
Returns:
Success: JSON with user info, auth token, welcome message.
Failure: JSON with error message and status code 401 or 500.
Flow:
Validate JSON request.
Query user by email.
Decrypt password and verify.
If valid, generate an access token, update user last login time, and perform Flask-Login
login_user.Return user data and auth token.
Example:
curl -X POST /login -d '{"email":"[email protected]","password":"encrypted_pwd"}' -H "Content-Type: application/json"
2. get_login_channels()
Endpoint:
/login/channelsMethods: GET
Purpose: Retrieve all supported OAuth login channels.
Returns: JSON list of available OAuth channels with display name and icon.
Usage: Frontend can call this to display login options dynamically.
3. oauth_login(channel)
Endpoint:
/login/<channel>Methods: GET
Purpose: Initiate OAuth login flow for a specified channel (e.g., GitHub, Feishu).
Parameters:
channel(string): Name of OAuth provider.
Flow:
Validates channel.
Creates auth client.
Generates OAuth state token and stores in session.
Redirects user to provider’s authorization URL.
4. oauth_callback(channel)
Endpoint:
/oauth/callback/<channel>Methods: GET
Purpose: Handle OAuth callback, exchange code for token, fetch user info, login or register the user.
Flow:
Validate state parameter against session.
Exchange authorization code for access token.
Fetch user info from provider.
If user not registered, register new user.
Log user in and redirect with authentication token.
Error Handling: Redirects with error messages on failure.
Supports: Multiple OAuth channels configured in settings.
5. github_callback()
Endpoint:
/github_callbackMethods: GET
Purpose: Deprecated GitHub OAuth callback implementation.
Note: Use
/oauth/callback/githubinstead.Flow: Similar to
oauth_callback, but GitHub-specific logic.Recommendation: Transition to new callback route.
6. feishu_callback()
Endpoint:
/feishu_callbackMethods: GET
Purpose: OAuth callback for Feishu login.
Flow: Fetches app token, exchanges user code for token, fetches user info, registers or logs in user.
Note: Similar pattern to other OAuth callbacks.
7. log_out()
Endpoint:
/logoutMethods: GET
Purpose: Logs out the current user.
Decorators:
@login_requiredFlow:
Invalidates user’s access token.
Calls Flask-Login
logout_user.Returns JSON success response.
8. setting_user()
Endpoint:
/settingMethods: POST
Purpose: Update user profile/settings.
Decorators:
@login_requiredParameters: JSON body with user fields to update, including optional password change.
Flow:
Validates current password if changing password.
Updates allowed user fields.
Calls database service to update user.
Returns success or error JSON.
Security: Prevents changes to restricted fields like
is_superuser.
9. user_profile()
Endpoint:
/infoMethods: GET
Purpose: Retrieve current user profile data.
Decorators:
@login_requiredReturns: JSON with user ID, nickname, email, etc.
10. rollback_user_registration(user_id)
Purpose: Cleanup function to delete partially registered user and related tenant data on registration failure.
Parameters:
user_id(string): User identifier.
Flow: Attempts to delete user, tenant, user-tenant relationships, and tenant LLM records.
11. user_register(user_id, user)
Purpose: Register a new user with associated tenant and default files.
Parameters:
user_id(string): Unique ID for the user.user(dict): User data including email, nickname, access token, etc.
Flow:
Create tenant record with default models.
Create user-tenant relationship.
Create root folder for user.
Initialize tenant LLM models.
Save user to database.
Returns: List of user records if successful, None otherwise.
12. user_add()
Endpoint:
/registerMethods: POST
Purpose: Register a new user via email/password.
Decorators:
@validate_requestfor required fields:nickname,email,password.Flow:
Checks if registration is enabled.
Validates email format.
Checks for existing user with email.
Decrypts password.
Calls
user_register.Logs in new user.
Returns success or error JSON.
Example:
curl -X POST /register -d '{"nickname": "John", "email": "[email protected]", "password": "encrypted_pwd"}' -H "Content-Type: application/json"
13. tenant_info()
Endpoint:
/tenant_infoMethods: GET
Purpose: Retrieve tenant information associated with the current user.
Decorators:
@login_requiredReturns: JSON with tenant details like tenant_id, name, LLM IDs, embedding model ID, etc.
14. set_tenant_info()
Endpoint:
/set_tenant_infoMethods: POST
Purpose: Update tenant information.
Decorators:
@login_required,@validate_requestfor required tenant fields.Flow: Updates tenant record by tenant_id and returns success or error JSON.
15. Utility Functions for OAuth User Info Retrieval
user_info_from_feishu(access_token)Fetches user info from Feishu API using access token.
Returns a dictionary of user details including email and avatar.
user_info_from_github(access_token)Fetches user info and primary email from GitHub API.
Returns a dictionary with user details.
Important Implementation Details and Algorithms
Password Handling: Passwords are handled encrypted on the client side and decrypted server-side using
decrypt(). Passwords are hashed usingwerkzeug.security.generate_password_hashbefore storage and verified withcheck_password_hash.OAuth Flow: Uses OAuth 2.0 authorization code grant flow, including state parameter for CSRF protection.
Multi-Tenant Support: Each user is associated with a tenant (a logical workspace), with default LLM and embedding models configured at registration.
Session Management: Uses Flask-Login for session management and user authentication state.
Error Handling: Most endpoints return JSON responses with standardized result codes from
settings.RetCode.Rollback Strategy: On failures during user registration, partially created records are rolled back to maintain data integrity.
Dynamic OAuth Channel Support: Uses a configuration-driven approach to support multiple OAuth providers dynamically.
Interactions with Other Parts of the System
Database Services: Interacts with
UserService,TenantService,UserTenantService,TenantLLMService,FileServicefor CRUD operations.Auth Clients: Uses
get_auth_client()to instantiate OAuth clients per channel.Settings Module: Uses constants and configurations from
settings(OAuth configs, model IDs, registration flags, return codes).Utilities: Uses various utility functions for UUID generation, timestamp formatting, encryption/decryption, image downloading, and API response construction.
Flask Login: Integrates with Flask-Login for session and user state management.
Visual Diagram
classDiagram
class user_app {
+login()
+get_login_channels()
+oauth_login(channel)
+oauth_callback(channel)
+github_callback()
+feishu_callback()
+log_out()
+setting_user()
+user_profile()
+rollback_user_registration(user_id)
+user_register(user_id, user)
+user_add()
+tenant_info()
+set_tenant_info()
+user_info_from_feishu(access_token)
+user_info_from_github(access_token)
}
%% Relationships
user_app ..> UserService : uses
user_app ..> TenantService : uses
user_app ..> UserTenantService : uses
user_app ..> TenantLLMService : uses
user_app ..> FileService : uses
user_app ..> get_auth_client : uses
user_app ..> settings : uses
user_app ..> flask_login : uses
Summary
user_app.py is a comprehensive user management module in the InfiniFlow backend, providing user authentication (traditional and OAuth), registration, profile and tenant management APIs. It follows secure authentication best practices, supports multi-tenancy, and is designed for extensibility with various OAuth providers. The file relies on multiple service layers and utility modules to abstract core business logic and database interactions.