laconic-deploy/qwrk-docs/project-docs/authentication/user-project-management.md
icld e1c2a8ce2c refactor: consolidate project documentation and routing strategy
This commit introduces a comprehensive documentation strategy for the project, focusing on:

- Centralizing routing configuration
- Adding detailed documentation for frontend architecture
- Creating standards for component documentation
- Implementing a feature building process template
- Removing legacy documentation files

Key changes include:
- Added routing strategy and implementation documents
- Created project-wide documentation standards
- Introduced new documentation structure in qwrk-docs
- Removed redundant README and documentation files
- Enhanced routing and layout documentation
2025-03-02 06:14:24 -08:00

7.3 KiB

User Project Authentication and Management

Overview

This document explains how users authenticate with the system and how their projects are managed and counted. The process begins with wallet authentication and extends to GitHub integration for project access and creation.

Authentication Flow

Users in the system are identified primarily by their wallet address, but to create or access projects, they must authenticate with GitHub. This dual authentication approach ensures secure access to both blockchain and version control resources.

Wallet Authentication

Wallet authentication is handled through an iframe-based mechanism that:

  1. Requests the user's wallet address
  2. Generates a Sign-In With Ethereum (SIWE) message
  3. Asks the user to sign this message to prove wallet ownership
  4. Verifies the signature on the backend
  5. Creates or retrieves the user account based on the Ethereum address

GitHub Authentication

After wallet authentication, GitHub authentication is required to:

  1. Access repositories for project creation
  2. Deploy projects with proper permissions
  3. Link project changes to the appropriate GitHub account

When a user connects their GitHub account:

  • A GitHub OAuth flow is initiated
  • The received GitHub token is stored in the user record
  • The user can now access their GitHub repositories through the platform

Project-User Relationships

Projects in the system have two types of relationships with users:

  1. Direct Ownership: The user who created the project is designated as the owner
  2. Project Membership: Users can be added as members with specific permissions (View, Edit)

This dual relationship structure allows for collaborative project management while maintaining clear ownership.

Database Structure

The key entities involved in user project management:

  • User: Stores wallet address, GitHub token, and other user information
  • Project: Contains project details including repository, framework, and deployment settings
  • ProjectMember: Junction table that links users to projects with specific permissions
  • Organization: Groups projects and provides team-level management

Counting User Projects

To count a user's projects, the system:

  1. Retrieves the user's ID from their wallet authentication
  2. Identifies the organization(s) the user belongs to
  3. Queries projects where either:
    • The user is the project owner, OR
    • The user is linked via the ProjectMember table
  4. Returns the combined list of projects the user has access to

The query used looks similar to:

SELECT projects.*
FROM projects
LEFT JOIN project_members ON projects.id = project_members.project_id
LEFT JOIN organizations ON projects.organization_id = organizations.id
WHERE (projects.owner_id = :userId OR project_members.user_id = :userId)
AND organizations.slug = :organizationSlug

Sequence Diagram

sequenceDiagram
    participant User
    participant Frontend
    participant WalletIframe
    participant Backend
    participant GitHub
    participant Database

    %% Wallet Authentication
    User->>Frontend: Visits platform
    Frontend->>WalletIframe: Loads wallet authentication iframe
    WalletIframe->>User: Requests wallet connection
    User->>WalletIframe: Connects wallet
    WalletIframe->>Frontend: Message event with wallet address
    Frontend->>User: Requests signature of SIWE message
    User->>Frontend: Signs message
    Frontend->>Backend: Validate signature
    Backend->>Database: Create/Retrieve user account
    Database->>Backend: User account details
    Backend->>Frontend: Authentication successful

    %% GitHub Authentication
    Frontend->>User: Prompts for GitHub authentication
    User->>GitHub: Authorizes application
    GitHub->>Frontend: Returns OAuth code
    Frontend->>Backend: Exchange code for token
    Backend->>GitHub: Validate token
    GitHub->>Backend: Token validation response
    Backend->>Database: Store GitHub token with user
    Database->>Backend: Update confirmation
    Backend->>Frontend: GitHub connection successful

    %% Project Access
    User->>Frontend: Request projects list
    Frontend->>Backend: getProjectsInOrganization(orgSlug)
    Backend->>Database: Query for owned & member projects
    Database->>Backend: Projects data
    Backend->>Frontend: Projects list
    Frontend->>User: Display projects count and list

Entity Relationship Diagram

erDiagram
    User ||--o{ Project : owns
    User ||--o{ ProjectMember : has
    Project ||--o{ ProjectMember : includes
    Organization ||--o{ Project : contains
    User ||--o{ UserOrganization : belongs_to
    Organization ||--o{ UserOrganization : has_members

    User {
        string id PK
        string ethAddress
        string name
        string email
        string gitHubToken
        boolean isVerified
        datetime createdAt
        datetime updatedAt
        string subOrgId
        string turnkeyWalletId
    }

    Project {
        string id PK
        string ownerId FK
        string name
        string repository
        string prodBranch
        string description
        string framework
        string organizationId FK
        datetime createdAt
        datetime updatedAt
    }

    ProjectMember {
        string id PK
        string userId FK
        string projectId FK
        string[] permissions
        boolean isPending
        datetime createdAt
        datetime updatedAt
    }

    Organization {
        string id PK
        string name
        string slug
        datetime createdAt
        datetime updatedAt
    }

    UserOrganization {
        string id PK
        string userId FK
        string organizationId FK
        string role
        datetime createdAt
        datetime updatedAt
    }
</mermaid>

## Implementation Details

### Frontend Components

Key components involved in project management:

- **WalletContextProvider**: Manages wallet connection state and authentication
- **OctokitProvider**: Handles GitHub authentication and API access
- **ProjectSearchLayout**: Retrieves and displays user projects

### Backend Services

- **AuthService**: Handles SIWE validation and session management
- **Service.getProjectsInOrganization**: Retrieves projects for a user in an organization
- **Database.getProjectsInOrganization**: Performs the actual database query

## API Endpoints

### GraphQL Queries

- `getProjectsInOrganization(organizationSlug: String!)`: Returns all projects a user has access to in an organization
- `projectMembers(projectId: String!)`: Returns all members of a specific project
- `getUser()`: Returns the authenticated user's information

## Future Considerations

1. **Performance Optimization**: For users with many projects, pagination or optimized queries may be needed
2. **Permission Caching**: Consider caching project access for frequently accessed projects
3. **Multi-Wallet Support**: Plan for supporting multiple wallet connections per user
4. **Cross-Organization Projects**: Consider how to handle projects that span multiple organizations

## References

- **WalletContextProvider.tsx**: Main wallet authentication logic
- **OctokitContext.tsx**: GitHub authentication management
- **service.ts**: Service layer with project retrieval methods
- **database.ts**: Database queries for project access
- **User.ts** and **ProjectMember.ts**: Entity definitions showing relationships