Skip to contents

This file contains guidance targeted for this repository. Notes here should follow organization guidance (see here).

Repository Overview

artauth is the authentication and access control package for the Artalytics platform. It provides passwordless authentication via magic links, user account management, role-based access control (RBAC), and lead capture functionality for artist waiting lists and whitepaper downloads.

Purpose

  • Passwordless authentication via magic links sent through Resend API
  • User account management (create, update, role assignment)
  • Role-based access control (artist, collector, investor, admin roles)
  • Lead capture (artist waiting list, whitepaper downloads)
  • Session management and authentication state
  • Integration layer for artsend email delivery

Architecture Role

This is a Core layer package in the Artalytics platform architecture: - Depends on artcore (database, CDN, configuration) and artutils (shared utilities) - Provides authentication services to all application packages - No dependencies on domain-specific or UI packages - Critical security component - changes require thorough review

Key Functional Areas

User Account Management

  • create_user_account() - Create new user with role assignment
  • assign_role() - Add/modify user roles (artist, collector, investor, admin)
  • check_user_access() - Verify user has required role(s)
  • get_current_user() - Retrieve authenticated user from Shiny session
  • require_authentication() - Shiny middleware to enforce authentication
  • generate_magic_link() - Create secure, time-limited login token
  • verify_magic_link() - Validate token and authenticate user
  • invalidate_user_tokens() - Revoke all active tokens (logout)
  • Token security: SHA-256 hashing, 15-minute expiration, single-use

Waitlist & Lead Capture

Investor Access Management

  • grant_investor_access() - Assign investor role with access scopes
  • check_investor_scope() - Verify access to investor resources
  • list_investor_users() - Retrieve all users with investor access

Anonymous Session Tracking (Future)

  • create_anonymous_session() - Initialize anonymous user tracking
  • track_anonymous_activity() - Record page views and artwork viewing
  • convert_anonymous_to_user() - Link anonymous session to new account

Database Schema

Core Tables

  • user_accounts - Central user table with authentication state
  • user_roles - Many-to-many role assignments
  • user_artist_link - Links users to existing artist_index records
  • investor_access - Investor-specific access scopes
  • artist_waitlist - Pre-account signup for artists
  • whitepaper_downloads - Lead tracking for whitepaper downloads
  • anonymous_sessions - Anonymous user tracking (Phase 5)

Database Connection Pattern

All database functions follow the artcore connection pattern:

my_function <- function(user_id, cn = NULL) {
  if (is.null(cn)) {
    cn <- artcore::..dbc()
    on.exit(artcore::..dbd(cn))
  }

  # Database operations
  result <- DBI::dbGetQuery(cn, query, params)
  return(result)
}

Environment Configuration

Required Environment Variables

  • ART_USE_PG_CONF - Database configuration (inherited from artcore)
  • ART_RUN_AS_DEMO - Demo mode flag (inherited from artcore)

Optional Configuration

  • Magic link expiration time (default: 15 minutes)
  • Session cookie settings
  • Rate limiting parameters

Integration with artsend

Email delivery requires artsend package with ART_RESEND_KEY configured:

# Magic link email sent via artsend
artsend::send_magic_link_email(
  to = user_email,
  magic_link = magic_link_url,
  user_name = user_name,
  expires_in_minutes = 15
)

Security Considerations

Critical Security Patterns

  1. Token Security
    • Generate cryptographically secure tokens via uuid::UUIDgenerate()
    • Hash tokens with digest::sha256() before database storage
    • Set short expiration (15 minutes recommended)
    • Invalidate after single use
  2. Input Validation
    • Validate all UUID parameters
    • Sanitize email addresses
    • Use prepared statements for database queries
    • Validate role types against allowed values
  3. Session Management
    • Use secure, HTTP-only cookies
    • Regenerate session ID on login
    • Invalidate sessions on logout
    • Implement CSRF protection
  4. Password-Free Design
    • No password storage or hashing needed
    • No password reset flows
    • Reduced attack surface vs traditional auth

Email Security

  • Validate email format before sending
  • Rate limit magic link requests per email
  • Use HTTPS URLs in all emails
  • No secrets in email content

Testing Strategy

Unit Tests

  • Mock database connections for all database operations
  • Test token generation and validation logic
  • Validate email format checking
  • Test role assignment and checking
  • Test error conditions and edge cases

Integration Tests

  • Test magic link end-to-end flow (with mocked email)
  • Test waitlist conversion workflow
  • Test session management
  • Test access control patterns

Security Tests

  • Test token expiration handling
  • Test invalid token rejection
  • Test session invalidation
  • Test unauthorized access blocking
  • Test SQL injection prevention

Test Patterns

test_that("generate_magic_link creates valid token", {
  # Mock database connection
  local_mocked_bindings(
    ..dbc = function() list(),
    ..dbd = function(cn) invisible(NULL),
    .package = "artcore"
  )

  result <- generate_magic_link("test@example.com")
  expect_true(nchar(result$token) > 20)
  expect_match(result$magic_link, "^https://")
})

Common Development Tasks

Adding New Authentication Function

  1. Add function to appropriate R/*.R file
  2. Follow database connection pattern with optional cn
  3. Add comprehensive tests with mocked connections
  4. Document with security considerations
  5. Export if needed by applications

Adding New Email Type

  1. Define function signature in artauth
  2. Coordinate with artsend package for email template
  3. Add tests for email triggering logic
  4. Document integration requirements

Adding New User Role

  1. Update user_roles table allowed values
  2. Add role constant to package
  3. Update assign_role() validation
  4. Update check_user_access() logic
  5. Add tests for new role

Extending Access Control

  1. Add new permission check function
  2. Implement access scope logic
  3. Add database queries if needed
  4. Document permission structure
  5. Add comprehensive tests

Integration Patterns

Shiny Application Integration

# In Shiny server
server <- function(input, output, session) {
  # Require authentication
  user <- artauth::require_authentication(session)

  # Check role
  if (artauth::check_user_access(user$user_id, "artist")) {
    # Artist-only features
  }

  # Get current user
  current_user <- artauth::get_current_user(session)
}

artutils Integration

artutils should provide wrapper functions for common patterns:

# In artutils
get_current_user <- function(session) {
  artauth::get_current_user(session)
}

require_authentication <- function(session, required_roles = NULL) {
  artauth::require_authentication(session, required_roles)
}

Database Integration

When adding new artist with user account:

# 1. Create user account
user_id <- artauth::create_user_account(
  email = email,
  full_name = name,
  roles = "artist"
)

# 2. Create artist profile
artist_uuid <- artutils::addArtist(
  artist_name = name,
  user_id = user_id,  # New parameter
  ...
)

# Link is created automatically in user_artist_link table

Implementation Status

Phase 1: Lead Capture & Database Foundation (IN PROGRESS)

  • ✅ Database schema defined
  • ✅ Package structure created
  • ⏳ Waitlist functions (pending implementation)
  • ⏳ Whitepaper tracking (pending implementation)
  • ⏳ Integration with artsend (pending)

Phase 2: Core Authentication System (PLANNED)

  • ⏳ Magic link generation and verification
  • ⏳ User account management
  • ⏳ Role-based access control
  • ⏳ Session management

Phase 3+: Future Phases

See Authentication Implementation Plan for complete roadmap.

References

  • Implementation Plan: /Users/bobbyf/Projects/artalytics/_TASK/Pending/AUTHENTICATION_IMPLEMENTATION_PLAN.md
  • Organization Standards: ../../AGENTS.md and ../../CLAUDE.md
  • artcore Package: Foundational services (database, configuration)
  • artutils Package: Shared application utilities
  • artsend Package: Email delivery via Resend API

Repo Files

  • setup-env.sh - Minimal install script for package development environment
  • Dockerfile - Docker image for development and testing environment

Task Items

Current development tasks tracked in implementation plan sections: - Phase 1 Tasks (Lines 747-807 of implementation plan) - Phase 2 Tasks (Lines 820-891 of implementation plan)