### Frontend API Service Examples - TypeScript Source: https://context7.com/fish2018/yprompt/llms.txt Demonstrates usage of the unified API service for saving, retrieving, and managing prompts. Includes examples for pagination, filtering, toggling favorites, recording usage, deletion, and error handling with automatic token refresh. ```typescript // src/services/apiService.ts usage examples import * as api from '@/services/apiService' // Save a new prompt const promptData: api.SavePromptData = { title: 'Data Analysis Assistant', description: 'Analyzes datasets and provides insights', final_prompt: 'You are a data analysis expert...', language: 'en', prompt_type: 'system', tags: ['data', 'analysis'] } try { const result = await api.savePrompt(promptData) console.log('Prompt saved:', result) } catch (error) { console.error('Save failed:', error) } // Get paginated prompts with filters const response = await api.getPrompts({ page: 1, limit: 20, is_favorite: true, tags: ['code', 'review'], search: 'assistant' }) console.log('Total prompts:', response.data.total) response.data.items.forEach(prompt => { console.log(`${prompt.title} - v${prompt.current_version}`) }) // Toggle favorite status await api.toggleFavorite(42, true) // Record prompt usage await api.recordPromptUse(42) // Delete prompt await api.deletePrompt(42) // Error handling with automatic token refresh try { const userInfo = await api.get('/api/auth/userinfo') console.log(userInfo) } catch (error) { if (error.message === '未授权,请重新登录') { // Token expired, redirect to login router.push('/login') } } ``` -------------------------------- ### Versions - Get Version History Source: https://context7.com/fish2018/yprompt/llms.txt Retrieve a paginated list of all versions for a specific prompt, with filtering options by tag. ```APIDOC ## GET /api/versions/{prompt_id}/versions ### Description Retrieve paginated list of all versions for a specific prompt. ### Method GET ### Endpoint `/api/versions/{prompt_id}/versions` ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number for pagination. - **limit** (integer) - Optional - The number of items per page. - **tag** (string) - Optional - Filter versions by tag (e.g., "stable"). ### Request Example ```bash curl -X GET "http://localhost:8888/api/versions/42/versions?page=1&limit=20&tag=stable" \ -H "Authorization: Bearer TOKEN" ``` ### Response #### Success Response (200) - **total** (integer) - Total number of versions. - **page** (integer) - Current page number. - **limit** (integer) - Items per page. - **items** (array) - Array of version objects. - **id** (integer) - Version ID. - **prompt_id** (integer) - ID of the prompt. - **version_number** (string) - Version number (e.g., "1.2.0"). - **version_type** (string) - Type of version (e.g., "manual"). - **version_tag** (string) - Tag for the version (e.g., "stable"). - **title** (string) - Title of the version. - **final_prompt** (string) - The prompt content for this version. - **change_summary** (string) - Summary of changes for this version. - **change_log** (string) - Detailed change log. - **use_count** (integer) - Number of times this version has been used. - **rollback_count** (integer) - Number of rollbacks to this version. - **create_time** (string) - Timestamp of creation. #### Response Example ```json { "code": 200, "data": { "total": 5, "page": 1, "limit": 20, "items": [ { "id": 15, "prompt_id": 42, "version_number": "1.2.0", "version_type": "manual", "version_tag": "stable", "title": "Code Review Assistant", "final_prompt": "You are an expert code review assistant...", "change_summary": "添加了安全检查和性能优化建议", "change_log": "- 新增:SQL注入检测...", "use_count": 3, "rollback_count": 0, "create_time": "2025-01-05 14:30:00" }, { "id": 14, "version_number": "1.1.0", "version_tag": "stable", "change_summary": "优化代码质量检查逻辑", "use_count": 5, "create_time": "2025-01-03 09:15:00" } ] } } ``` ``` -------------------------------- ### Backend Database Adapter Pattern - Python Source: https://context7.com/fish2018/yprompt/llms.txt Illustrates the use of a unified database interface that supports both SQLite and MySQL. Demonstrates initialization for both databases, performing CRUD operations (get, query, insert, update), executing raw SQL, and managing transactions. ```python # apps/utils/db_adapter.py usage examples from apps.utils.db_adapter import create_database_adapter # Initialize SQLite (auto-creates database and tables) sqlite_config = {'path': '../data/yprompt.db'} db = await create_database_adapter('sqlite', sqlite_config, app.config) # Initialize MySQL mysql_config = { 'host': 'localhost', 'database': 'yprompt', 'user': 'root', 'password': 'password', 'port': 3306, 'minsize': 3, 'maxsize': 10 } db = await create_database_adapter('mysql', mysql_config) # Query single record (both databases use same interface) user = await db.get( "SELECT * FROM users WHERE username = ?", ['admin'] ) # Query multiple records prompts = await db.query( "SELECT * FROM prompts WHERE user_id = ? AND is_favorite = ?", [user_id, 1] ) # Insert data prompt_id = await db.table_insert('prompts', { 'user_id': 1, 'title': 'Test Prompt', 'final_prompt': 'You are a test assistant', 'language': 'zh', 'prompt_type': 'system' }) # Update data await db.table_update( 'prompts', {'is_favorite': 1, 'view_count': 10}, f"id = {prompt_id}" ) # Execute raw SQL await db.execute( "UPDATE users SET last_login_time = ? WHERE id = ?", [datetime.now(), user_id] ) # Transaction support async with db.transaction(): await db.execute("UPDATE prompts SET use_count = use_count + 1 WHERE id = ?", [prompt_id]) await db.execute("INSERT INTO prompt_logs (prompt_id, action) VALUES (?, ?)", [prompt_id, 'used']) # Close connection (important for cleanup) await db.close() ``` -------------------------------- ### API: Get Version History for a Prompt (Bash) Source: https://context7.com/fish2018/yprompt/llms.txt Retrieves a paginated list of all versions for a specific prompt. Requires prompt ID, page number, limit, and an optional tag. An Authorization header is necessary. ```bash curl -X GET "http://localhost:8888/api/versions/42/versions?page=1&limit=20&tag=stable" \ -H "Authorization: Bearer TOKEN" ``` -------------------------------- ### Get Auth Configuration Source: https://context7.com/fish2018/yprompt/llms.txt Retrieves the current authentication settings and enabled methods for the frontend to configure login options. ```APIDOC ## GET /api/auth/config ### Description Fetches the authentication configuration, including details about enabled authentication methods (Linux.do OAuth and local) and their respective settings. ### Method GET ### Endpoint `/api/auth/config` ### Parameters None ### Response #### Success Response (200) - **code** (integer) - The HTTP status code, 200 for success. - **data** (object) - An object containing the authentication configuration. - **linux_do_enabled** (boolean) - Indicates if Linux.do OAuth login is enabled. - **linux_do_client_id** (string) - The client ID for Linux.do OAuth. - **linux_do_redirect_uri** (string) - The redirect URI for Linux.do OAuth. - **local_auth_enabled** (boolean) - Indicates if local username/password authentication is enabled. - **registration_enabled** (boolean) - Indicates if user registration for local accounts is enabled. #### Response Example ```json { "code": 200, "data": { "linux_do_enabled": true, "linux_do_client_id": "your_client_id", "linux_do_redirect_uri": "http://localhost:5173/auth/callback", "local_auth_enabled": true, "registration_enabled": false } } ``` ``` -------------------------------- ### Frontend: Authentication Store Management (TypeScript/Vue Pinia) Source: https://context7.com/fish2018/yprompt/llms.txt Example usage of a Vue Pinia store for managing authentication state. It supports dual authentication methods (OAuth and password), automatic configuration loading, user registration, login status checks, and logout functionality. ```typescript // src/stores/authStore.ts usage example import { useAuthStore } from '@/stores/authStore' // Initialize auth store const authStore = useAuthStore() // Check authentication configuration const config = await authStore.getAuthConfig() if (config?.linux_do_enabled) { // Show Linux.do OAuth button const authUrl = `https://connect.linux.do/oauth/authorize?client_id=${config.linux_do_client_id}&redirect_uri=${config.linux_do_redirect_uri}&response_type=code` window.location.href = authUrl } // Handle OAuth callback const code = new URLSearchParams(window.location.search).get('code') if (code) { const success = await authStore.loginWithLinuxDo(code) if (success) { router.push('/') } } // Local login const loginSuccess = await authStore.loginWithPassword('admin', 'admin123') if (loginSuccess) { console.log('User:', authStore.user) console.log('Token:', authStore.token) } // Register new user const result = await authStore.register('newuser', 'Password123', 'New User') if (result.success) { // Auto login after registration await authStore.loginWithPassword('newuser', 'Password123') } // Check login status if (authStore.isLoggedIn) { console.log('Logged in as:', authStore.user?.name) } // Logout await authStore.logout() // Clears all local data and redirects to login ``` -------------------------------- ### Get Authentication Configuration API Call Source: https://context7.com/fish2018/yprompt/llms.txt Retrieves the current authentication configuration settings for the YPrompt platform. This includes whether Linux.do OAuth and local authentication are enabled, along with relevant client IDs and redirect URIs. ```bash curl -X GET http://localhost:8888/api/auth/config # Response { "code": 200, "data": { "linux_do_enabled": true, "linux_do_client_id": "your_client_id", "linux_do_redirect_uri": "http://localhost:5173/auth/callback", "local_auth_enabled": true, "registration_enabled": false } } ``` -------------------------------- ### Get User Info Source: https://context7.com/fish2018/yprompt/llms.txt Retrieves detailed information about the currently logged-in user using their authentication token. ```APIDOC ## GET /api/auth/userinfo ### Description Fetches detailed information about the currently authenticated user based on the provided JWT token in the Authorization header. ### Method GET ### Endpoint `/api/auth/userinfo` ### Parameters #### Headers - **Authorization** (string) - Required - The Bearer token of the current valid JWT. ### Request Example ```bash curl -X GET http://localhost:8888/api/auth/userinfo \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` ### Response (The response structure is expected to be the same as the `data.user` object in the authentication responses) #### Success Response (200) - **id** (integer) - The unique identifier for the user. - **name** (string) - The user's display name. - **username** (string) - The user's unique username. - **avatar** (string) - URL to the user's avatar image. - **auth_type** (string) - The authentication method used (e.g., "linux_do", "local"). - **is_admin** (integer) - Flag indicating if the user is an administrator (0 for no, 1 for yes). - **last_login_time** (string) - Timestamp of the user's last login. #### Response Example ```json { "id": 1, "name": "张三", "username": "zhangsan", "avatar": "https://example.com/avatar.jpg", "auth_type": "linux_do", "is_admin": 0, "last_login_time": "2025-01-10 10:30:00" } ``` ``` -------------------------------- ### Get User Information API Call Source: https://context7.com/fish2018/yprompt/llms.txt Retrieves detailed information about the currently authenticated user. Requires a valid JWT token to be provided in the Authorization header. Returns user profile data, including ID, name, username, and authentication type. ```bash curl -X GET http://localhost:8888/api/auth/userinfo \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` -------------------------------- ### Local Username/Password Login API Call Source: https://context7.com/fish2018/yprompt/llms.txt Authenticates users using local credentials (username and password) for private YPrompt deployments. Returns a JWT token and user details upon successful login. Includes example for successful login and error handling for incorrect credentials. ```bash curl -X POST http://localhost:8888/api/auth/local/login \ -H "Content-Type: application/json" \ -d '{ "username": "admin", "password": "admin123" }' # Response { "code": 200, "message": "登录成功", "data": { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "user": { "id": 1, "name": "管理员", "username": "admin", "avatar": "", "auth_type": "local", "is_admin": 1, "last_login_time": "2025-01-10 10:35:00" } } } # Error handling { "code": 400, "message": "用户名或密码错误" } ``` -------------------------------- ### Configuration Loading and Application Update (Python) Source: https://context7.com/fish2018/yprompt/llms.txt This snippet demonstrates how to load configuration settings dynamically based on the environment and update the application's configuration. It utilizes a `get_config` function to auto-select the appropriate configuration and then merges these settings into the application's config object. ```python from config.settings import get_config config = get_config() # Auto-selects based on ENV app.config.update(config.__dict__) ``` -------------------------------- ### User Registration Source: https://context7.com/fish2018/yprompt/llms.txt Allows new users to create a local account, enforcing password complexity and username format rules. ```APIDOC ## POST /api/auth/local/register ### Description Creates a new local user account with username, password, and name. Includes validation for password length and username format. ### Method POST ### Endpoint `/api/auth/local/register` ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new account. Must start with a letter. - **password** (string) - Required - The user's password. Must be at least 8 characters long. - **name** (string) - Required - The full name of the user. ### Request Example ```json { "username": "john_doe", "password": "SecurePass123", "name": "John Doe" } ``` ### Response #### Success Response (200) - **code** (integer) - The HTTP status code, 200 for success. - **message** (string) - A confirmation message, e.g., "注册成功". - **data** (object) - Information about the newly created user. - **id** (integer) - The unique identifier for the new user. - **username** (string) - The username of the new account. - **name** (string) - The name of the new user. #### Response Example ```json { "code": 200, "message": "注册成功", "data": { "id": 5, "username": "john_doe", "name": "John Doe" } } ``` #### Error Response (400) - **code** (integer) - The HTTP status code, 400 for bad request (e.g., validation errors). - **message** (string) - An error message indicating the validation failure (e.g., "密码长度至少8个字符", "用户名必须以字母开头"). #### Error Example ```json { "code": 400, "message": "密码长度至少8个字符" } ``` ``` -------------------------------- ### Versions - Compare Versions Source: https://context7.com/fish2018/yprompt/llms.txt Compare the differences between two specified versions of a prompt. ```APIDOC ## GET /api/versions/{prompt_id}/versions/compare ### Description Compare differences between two versions to understand changes. ### Method GET ### Endpoint `/api/versions/{prompt_id}/versions/compare` ### Parameters #### Path Parameters - **prompt_id** (integer) - Required - The ID of the prompt. #### Query Parameters - **from** (integer) - Required - The ID of the starting version for comparison. - **to** (integer) - Required - The ID of the ending version for comparison. ### Request Example ```bash curl -X GET "http://localhost:8888/api/versions/42/versions/compare?from=14&to=15" \ -H "Authorization: Bearer TOKEN" ``` ### Response #### Success Response (200) - **from_version** (object) - Details of the starting version. - **id** (integer) - Version ID. - **version_number** (string) - Version number. - **final_prompt** (string) - Prompt content. - **create_time** (string) - Creation timestamp. - **to_version** (object) - Details of the ending version. - **id** (integer) - Version ID. - **version_number** (string) - Version number. - **final_prompt** (string) - Prompt content. - **create_time** (string) - Creation timestamp. - **differences** (object) - Object indicating which fields have changed. - **title_changed** (boolean) - True if the title changed. - **prompt_changed** (boolean) - True if the prompt content changed. - **tags_changed** (boolean) - True if the tags changed. #### Response Example ```json { "code": 200, "data": { "from_version": { "id": 14, "version_number": "1.1.0", "final_prompt": "You are a code review assistant...", "create_time": "2025-01-03 09:15:00" }, "to_version": { "id": 15, "version_number": "1.2.0", "final_prompt": "You are an expert code review assistant...", "create_time": "2025-01-05 14:30:00" }, "differences": { "title_changed": false, "prompt_changed": true, "tags_changed": false } } } ``` ``` -------------------------------- ### API: Compare Differences Between Two Prompt Versions (Bash) Source: https://context7.com/fish2018/yprompt/llms.txt Compares the differences between two specified versions of a prompt. Requires prompt ID and the 'from' and 'to' version IDs. An Authorization header is necessary. ```bash curl -X GET "http://localhost:8888/api/versions/42/versions/compare?from=14&to=15" \ -H "Authorization: Bearer TOKEN" ``` -------------------------------- ### Versions - Rollback to Version Source: https://context7.com/fish2018/yprompt/llms.txt Revert a prompt to a previous version, creating a new rollback version entry. ```APIDOC ## POST /api/versions/{prompt_id}/versions/{version_id}/rollback ### Description Revert prompt to a previous version, creating a new rollback version entry. ### Method POST ### Endpoint `/api/versions/{prompt_id}/versions/{version_id}/rollback` ### Parameters #### Path Parameters - **prompt_id** (integer) - Required - The ID of the prompt to rollback. - **version_id** (integer) - Required - The ID of the version to rollback to. #### Request Body - **change_summary** (string) - Required - A summary of why the rollback is being performed. ### Request Example ```bash curl -X POST http://localhost:8888/api/versions/42/versions/14/rollback \ -H "Authorization: Bearer TOKEN" \ -H "Content-Type: application/json" \ -d '{ "change_summary": "回滚到1.1.0版本,因为1.2.0存在bug" }' ``` ### Response #### Success Response (200) - **version_id** (integer) - The ID of the newly created rollback version. - **version_number** (string) - The version number of the new rollback version. - **rollback_to_version** (string) - The version number that was rolled back to. #### Response Example ```json { "code": 200, "message": "回滚成功", "data": { "version_id": 16, "version_number": "1.3.0", "rollback_to_version": "1.1.0" } } ``` ``` -------------------------------- ### Base and Development Configuration (Python) Source: https://context7.com/fish2018/yprompt/llms.txt Defines base application configuration settings, including database type and connection details, JWT secret key, and OAuth parameters. The development configuration extends the base, enabling debug mode and registration. ```python # config/base.py - Base configuration class BaseConfig: # Database configuration DB_TYPE = 'sqlite' # 'sqlite' or 'mysql' # SQLite (default - zero configuration) SQLITE_DB_PATH = '../data/yprompt.db' # MySQL (optional) DB_HOST = 'localhost' DB_USER = 'root' DB_PASS = 'password' DB_NAME = 'yprompt' DB_PORT = 3306 # JWT configuration SECRET_KEY = 'your-secret-key-change-in-production' JWT_EXPIRE_HOURS = 24 * 7 # 7 days # Linux.do OAuth (optional - leave empty to disable) LINUX_DO_CLIENT_ID = '' LINUX_DO_CLIENT_SECRET = '' LINUX_DO_REDIRECT_URI = 'http://localhost:5173/auth/callback' # Default admin account (auto-created/synced on startup) DEFAULT_ADMIN_USERNAME = 'admin' DEFAULT_ADMIN_PASSWORD = 'admin123' DEFAULT_ADMIN_NAME = '管理员' # Registration REGISTRATION_ENABLED = False # Set to True to allow registration # config/dev.py - Development overrides from .base import BaseConfig class DevConfig(BaseConfig): DEBUG = True REGISTRATION_ENABLED = True ``` -------------------------------- ### Frontend - Authentication Store (Vue Pinia) Source: https://context7.com/fish2018/yprompt/llms.txt Client-side authentication state management using Vue Pinia, supporting dual authentication methods and automatic configuration loading. ```APIDOC ## Frontend Authentication (Vue Pinia) ### Description Centralized authentication state management with dual auth support and automatic config loading. ### Usage Example ```typescript // src/stores/authStore.ts usage example import { useAuthStore } from '@/stores/authStore' // Initialize auth store const authStore = useAuthStore() // Check authentication configuration const config = await authStore.getAuthConfig() if (config?.linux_do_enabled) { // Show Linux.do OAuth button const authUrl = `https://connect.linux.do/oauth/authorize?client_id=${config.linux_do_client_id}&redirect_uri=${config.linux_do_redirect_uri}&response_type=code` window.location.href = authUrl } // Handle OAuth callback const code = new URLSearchParams(window.location.search).get('code') if (code) { const success = await authStore.loginWithLinuxDo(code) if (success) { router.push('/') } } // Local login const loginSuccess = await authStore.loginWithPassword('admin', 'admin123') if (loginSuccess) { console.log('User:', authStore.user) console.log('Token:', authStore.token) } // Register new user const result = await authStore.register('newuser', 'Password123', 'New User') if (result.success) { // Auto login after registration await authStore.loginWithPassword('newuser', 'Password123') } // Check login status if (authStore.isLoggedIn) { console.log('Logged in as:', authStore.user?.name) } // Logout await authStore.logout() // Clears all local data and redirects to login ``` ``` -------------------------------- ### Linux.do OAuth Login API Call Source: https://context7.com/fish2018/yprompt/llms.txt Authenticates users via Linux.do OAuth by exchanging an authorization code for a JWT token and user information. Requires a client ID and redirect URI for the initial authorization request. The backend then handles the code exchange. ```bash # Client-side flow: Redirect user to Linux.do authorization page GET https://connect.linux.do/oauth/authorize?client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&response_type=code # After user authorizes, Linux.do redirects back with code # Backend receives the code and exchanges for user info curl -X POST http://localhost:8888/api/auth/linux-do/login \ -H "Content-Type: application/json" \ -d '{ "code": "auth_code_from_linux_do_callback" }' # Response { "code": 200, "message": "登录成功", "data": { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "user": { "id": 1, "name": "张三", "username": "zhangsan", "avatar": "https://example.com/avatar.jpg", "auth_type": "linux_do", "is_admin": 0, "last_login_time": "2025-01-10 10:30:00" } } } ``` -------------------------------- ### Local User Registration API Call Source: https://context7.com/fish2018/yprompt/llms.txt Creates a new local user account for private YPrompt deployments. Requires username, password, and name. Includes validation for password length and username format, returning success or specific validation error messages. ```bash curl -X POST http://localhost:8888/api/auth/local/register \ -H "Content-Type: application/json" \ -d '{ "username": "john_doe", "password": "SecurePass123", "name": "John Doe" }' # Response { "code": 200, "message": "注册成功", "data": { "id": 5, "username": "john_doe", "name": "John Doe" } } # Validation errors { "code": 400, "message": "密码长度至少8个字符" } { "code": 400, "message": "用户名必须以字母开头" } ``` -------------------------------- ### API: Rollback Prompt to a Previous Version (Bash) Source: https://context7.com/fish2018/yprompt/llms.txt Reverts a prompt to a specified previous version, creating a new rollback version entry. Requires prompt ID, the target version ID, and a JSON payload with a change summary. An Authorization header is also needed. ```bash curl -X POST http://localhost:8888/api/versions/42/versions/14/rollback \ -H "Authorization: Bearer TOKEN" \ -H "Content-Type: application/json" \ -d '{ "change_summary": "回滚到1.1.0版本,因为1.2.0存在bug" }' ``` -------------------------------- ### Local Username/Password Login Source: https://context7.com/fish2018/yprompt/llms.txt Authenticates users using local username and password credentials, suitable for private deployments. ```APIDOC ## POST /api/auth/local/login ### Description Authenticates users with local credentials (username and password) for private deployments. ### Method POST ### Endpoint `/api/auth/local/login` ### Parameters #### Request Body - **username** (string) - Required - The user's username. - **password** (string) - Required - The user's password. ### Request Example ```json { "username": "admin", "password": "admin123" } ``` ### Response #### Success Response (200) - **code** (integer) - The HTTP status code, 200 for success. - **message** (string) - A confirmation message, e.g., "登录成功". - **data** (object) - Contains the JWT token and user information (similar structure to Linux.do OAuth login response). - **token** (string) - The JWT token for subsequent authenticated requests. - **user** (object) - Information about the authenticated user. #### Response Example ```json { "code": 200, "message": "登录成功", "data": { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "user": { "id": 1, "name": "管理员", "username": "admin", "avatar": "", "auth_type": "local", "is_admin": 1, "last_login_time": "2025-01-10 10:35:00" } } } ``` #### Error Response (400) - **code** (integer) - The HTTP status code, 400 for bad request (e.g., invalid credentials). - **message** (string) - An error message, e.g., "用户名或密码错误". #### Error Example ```json { "code": 400, "message": "用户名或密码错误" } ``` ``` -------------------------------- ### Backend Password Utilities - Python Source: https://context7.com/fish2018/yprompt/llms.txt Provides utilities for secure password management using bcrypt. Includes functions for hashing, verifying passwords, validating password strength, validating usernames, and generating random passwords. ```python # apps/utils/password_utils.py usage examples from apps.utils.password_utils import PasswordUtil, UsernameUtil # Hash a password for storage password = "SecurePass123" hashed = PasswordUtil.hash_password(password) # hashed: "$2b$12$vK8ZlGxXz9..." # Store hashed password in database await db.table_insert('users', { 'username': 'john_doe', 'password_hash': hashed, 'name': 'John Doe', 'auth_type': 'local' }) # Verify password during login stored_hash = user['password_hash'] is_valid = PasswordUtil.verify_password('SecurePass123', stored_hash) if is_valid: # Generate JWT token token = JWTUtil.generate_token(user['id'], user['username']) else: return json({'code': 400, 'message': '密码错误'}) # Validate password strength before registration is_valid, error_msg = PasswordUtil.validate_password_strength('weak') # Returns: (False, "密码长度至少8个字符") is_valid, error_msg = PasswordUtil.validate_password_strength('NoDigits') # Returns: (False, "密码必须包含数字") is_valid, error_msg = PasswordUtil.validate_password_strength('SecurePass123') # Returns: (True, "") # Validate username format is_valid, error_msg = UsernameUtil.validate_username('123invalid') # Returns: (False, "用户名必须以字母开头") is_valid, error_msg = UsernameUtil.validate_username('valid_user123') # Returns: (True, "") # Generate random password random_pwd = PasswordUtil.generate_random_password(length=16) # Returns: "aB3dE5fG9hJ1kL7m" ``` -------------------------------- ### Linux.do OAuth Login Source: https://context7.com/fish2018/yprompt/llms.txt Authenticates users via Linux.do OAuth. The backend exchanges the authorization code received from the frontend for a JWT token and user information. ```APIDOC ## POST /api/auth/linux-do/login ### Description Authenticates users via Linux.do OAuth by exchanging an authorization code for a JWT token and user details. ### Method POST ### Endpoint `/api/auth/linux-do/login` ### Parameters #### Request Body - **code** (string) - Required - The authorization code obtained from the Linux.do OAuth callback. ### Request Example ```json { "code": "auth_code_from_linux_do_callback" } ``` ### Response #### Success Response (200) - **code** (integer) - The HTTP status code, 200 for success. - **message** (string) - A confirmation message, e.g., "登录成功". - **data** (object) - Contains the JWT token and user information. - **token** (string) - The JWT token for subsequent authenticated requests. - **user** (object) - Information about the authenticated user. - **id** (integer) - The unique identifier for the user. - **name** (string) - The user's display name. - **username** (string) - The user's unique username. - **avatar** (string) - URL to the user's avatar image. - **auth_type** (string) - The authentication method used (e.g., "linux_do"). - **is_admin** (integer) - Flag indicating if the user is an administrator (0 for no, 1 for yes). - **last_login_time** (string) - Timestamp of the user's last login. #### Response Example ```json { "code": 200, "message": "登录成功", "data": { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "user": { "id": 1, "name": "张三", "username": "zhangsan", "avatar": "https://example.com/avatar.jpg", "auth_type": "linux_do", "is_admin": 0, "last_login_time": "2025-01-10 10:30:00" } } } ``` ``` -------------------------------- ### Service Layer for Business Logic (Python/Sanic) Source: https://context7.com/fish2018/yprompt/llms.txt Implements a service layer pattern to separate business logic from request handlers. The `PromptService` class handles operations like saving prompts, including creating new ones or updating existing ones, with versioning logic. ```python # apps/modules/prompts/services.py usage example from apps.modules.prompts.services import PromptService class PromptService: def __init__(self, db): self.db = db async def save_prompt(self, user_id, data): """ Unified save: auto-detect create vs update Create version if requested """ prompt_id = data.get('id') create_version = data.get('create_version', True) if prompt_id: # Update existing prompt existing = await self.db.get( "SELECT * FROM prompts WHERE id = ? AND user_id = ?", [prompt_id, user_id] ) if not existing: raise PermissionError('无权限修改此提示词') await self.db.table_update('prompts', { 'title': data['title'], 'final_prompt': data['final_prompt'], 'tags': ','.join(data.get('tags', [])) }, f"id = {prompt_id}") # Create version if requested if create_version: await self._create_version(prompt_id, data.get('change_summary')) return {'action': 'updated', 'id': prompt_id} else: # Create new prompt prompt_id = await self.db.table_insert('prompts', { 'user_id': user_id, 'title': data['title'], 'final_prompt': data['final_prompt'], 'language': data.get('language', 'zh'), 'prompt_type': data.get('prompt_type', 'system') }) # Create initial version await self._create_version(prompt_id, 'Initial version') return {'action': 'created', 'id': prompt_id, 'version': '1.0.0'} # Usage in views.py from apps.modules.prompts.services import PromptService @prompts_bp.post('/') @auth_required async def save_prompt(request): user_id = request.ctx.user_id data = request.json service = PromptService(request.app.ctx.db) result = await service.save_prompt(user_id, data) return json({'code': 200, 'data': result}) ``` -------------------------------- ### Production Configuration Override (Python) Source: https://context7.com/fish2018/yprompt/llms.txt This snippet defines production-specific configuration settings for the YPrompt application by overriding base configurations. It sets debug mode to false, specifies a MySQL database type, and defines a complex secret key for security. ```python from .base import BaseConfig class PrdConfig(BaseConfig): DEBUG = False DB_TYPE = 'mysql' SECRET_KEY = 'complex-production-secret-key' ``` -------------------------------- ### User Prompts API Source: https://context7.com/fish2018/yprompt/llms.txt Endpoints for retrieving and creating user-specific prompts. These endpoints are protected and require a valid JWT token for authentication. ```APIDOC ## GET /api/prompts/ ### Description Retrieves a list of prompts associated with the authenticated user. ### Method GET ### Endpoint /api/prompts/ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **code** (integer) - HTTP status code. - **data** (array) - An array of prompt objects. #### Response Example ```json { "code": 200, "data": [ { "id": 1, "user_id": 123, "title": "Example Prompt", "final_prompt": "This is the content of the prompt." } ] } ``` ``` ```APIDOC ## POST /api/prompts/ ### Description Creates a new prompt for the authenticated user. ### Method POST ### Endpoint /api/prompts/ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **title** (string) - Required - The title of the prompt. - **final_prompt** (string) - Required - The content of the prompt. ### Request Example ```json { "title": "New Feature Idea", "final_prompt": "Generate ideas for a new feature." } ``` ### Response #### Success Response (200) - **code** (integer) - HTTP status code. - **data** (object) - An object containing the ID of the newly created prompt. - **id** (integer) - The unique identifier of the created prompt. #### Response Example ```json { "code": 200, "data": { "id": 101 } } ``` ``` -------------------------------- ### Prompt Service API (Internal) Source: https://context7.com/fish2018/yprompt/llms.txt Internal service endpoint for saving prompts, handling both creation and updates, and managing prompt versions. This endpoint is typically called from within the application and is protected by authentication. ```APIDOC ## POST /api/prompts/ ### Description Saves a prompt, which can be either a new creation or an update to an existing prompt. It also handles versioning if requested. ### Method POST ### Endpoint /api/prompts/ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **id** (integer) - Optional - The ID of the prompt to update. If not provided, a new prompt will be created. - **title** (string) - Required - The title of the prompt. - **final_prompt** (string) - Required - The content of the prompt. - **tags** (array of strings) - Optional - Tags associated with the prompt (used for updates). - **language** (string) - Optional - The language of the prompt (used for creation, defaults to 'zh'). - **prompt_type** (string) - Optional - The type of the prompt (used for creation, defaults to 'system'). - **create_version** (boolean) - Optional - Whether to create a new version of the prompt (defaults to true). - **change_summary** (string) - Optional - A summary of changes for the new version. ### Request Example ```json { "id": 101, "title": "Updated Prompt Title", "final_prompt": "This is the updated content.", "tags": ["api", "update"], "create_version": true, "change_summary": "Improved clarity and added tags." } ``` ### Response #### Success Response (200) - **code** (integer) - HTTP status code. - **data** (object) - An object indicating the result of the save operation. - **action** (string) - "created" or "updated". - **id** (integer) - The ID of the prompt. - **version** (string) - The version number, only present if a new prompt was created. #### Response Example ```json { "code": 200, "data": { "action": "updated", "id": 101 } } ``` ``` -------------------------------- ### Secure API Endpoints with Auth Middleware (Python/Sanic) Source: https://context7.com/fish2018/yprompt/llms.txt Demonstrates how to protect API endpoints using the `auth_required` middleware. This middleware automatically validates JWT tokens, injects user IDs, and handles unauthorized access. It's used for endpoints that require user authentication. ```python from sanic import Blueprint from sanic.response import json from apps.utils.auth_middleware import auth_required prompts_bp = Blueprint('prompts', url_prefix='/api/prompts') @prompts_bp.get('/') @auth_required # Requires valid JWT token async def get_user_prompts(request): """ @auth_required automatically: 1. Validates JWT token from Authorization header 2. Injects user_id into request.ctx.user_id 3. Returns 401 if token is invalid/expired """ user_id = request.ctx.user_id # Auto-injected by middleware # Query user's prompts prompts = await request.app.ctx.db.query( "SELECT * FROM prompts WHERE user_id = ?", [user_id] ) return json({'code': 200, 'data': prompts}) @prompts_bp.post('/') @auth_required async def create_prompt(request): user_id = request.ctx.user_id data = request.json # Create prompt for authenticated user prompt_id = await request.app.ctx.db.table_insert('prompts', { 'user_id': user_id, 'title': data['title'], 'final_prompt': data['final_prompt'] }) return json({'code': 200, 'data': {'id': prompt_id}}) # Public endpoints don't need @auth_required @prompts_bp.get('/public') async def get_public_prompts(request): # No authentication required prompts = await request.app.ctx.db.query( "SELECT * FROM prompts WHERE is_public = 1" ) return json({'code': 200, 'data': prompts}) ``` -------------------------------- ### Public Prompts API Source: https://context7.com/fish2018/yprompt/llms.txt Endpoint for retrieving publicly available prompts. This endpoint does not require authentication. ```APIDOC ## GET /api/prompts/public ### Description Retrieves a list of all public prompts. ### Method GET ### Endpoint /api/prompts/public ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **code** (integer) - HTTP status code. - **data** (array) - An array of public prompt objects. #### Response Example ```json { "code": 200, "data": [ { "id": 5, "user_id": 456, "title": "Publicly Shared Prompt", "final_prompt": "This is a prompt shared with everyone.", "is_public": 1 } ] } ``` ``` -------------------------------- ### Refresh Token Source: https://context7.com/fish2018/yprompt/llms.txt Allows clients to obtain a new JWT token by presenting a valid existing token, extending the user's session. ```APIDOC ## POST /api/auth/refresh ### Description Renews the user's authentication token by sending a valid existing JWT. This is used to extend the session without requiring the user to re-authenticate. ### Method POST ### Endpoint `/api/auth/refresh` ### Parameters #### Headers - **Authorization** (string) - Required - The Bearer token of the current valid JWT. - **Content-Type** (string) - Required - Must be `application/json`. ### Request Example ```bash curl -X POST http://localhost:8888/api/auth/refresh \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \ -H "Content-Type: application/json" ``` ### Response #### Success Response (200) - **code** (integer) - The HTTP status code, 200 for success. - **message** (string) - A confirmation message, e.g., "刷新成功". - **data** (object) - **token** (string) - The new, refreshed JWT token. #### Response Example ```json { "code": 200, "message": "刷新成功", "data": { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.new_token..." } } ``` ```