README.md

# PhxAuthPlus

๐Ÿ” **Complete & Extensible Phoenix Authentication** - Full email + password authentication with future-proof extensibility using Igniter.

## โœจ Why PhxAuthPlus?

Phoenix v1.8 simplified authentication to magic links only. **PhxAuthPlus restores the complete email + password experience** while preparing your app for future authentication methods!

Built with [Igniter](https://hexdocs.pm/igniter) for smarter code generation and better project integration.

## ๐Ÿš€ Quick Start

### Installation

Add to your `mix.exs`:

```elixir
def deps do
  [
    {:phx_auth_plus, "~> 0.0.1", only: [:dev], runtime: false}
  ]
end
```

### Generate Authentication

```bash
# Install and generate in one command!
mix igniter.install phx_auth_plus

# Or generate manually
mix phx_auth_plus.gen.auth Accounts User users
```

## ๐ŸŽฏ Complete Feature Set

### ๐Ÿ” Core Authentication
- โœ… **Email + Password Registration** - Complete user signup with validation
- โœ… **Secure Login** - Email/password authentication with session management
- โœ… **Account Confirmation** - Email verification with token-based confirmation
- โœ… **Password Reset** - Forgot password flow with secure token reset
- โœ… **Email Changes** - Update email address with confirmation
- โœ… **Settings Management** - User profile and password management
- โœ… **"Remember Me"** - Persistent login with secure cookies
- โœ… **Session Tracking** - Track active sessions across devices

### ๐Ÿ›ก๏ธ Security Features
- โœ… **Password Hashing** - bcrypt/pbkdf2/argon2 support with configurable rounds
- โœ… **Session Tokens** - Secure token-based authentication
- โœ… **CSRF Protection** - Built-in Phoenix security integration
- โœ… **Timing Attack Protection** - Safe authentication checks
- โœ… **Session Invalidation** - Auto-invalidate on password change
- โœ… **Secure Cookies** - HttpOnly, SameSite, signed cookies
- โœ… **Rate Limiting Ready** - Easy to add rate limiting
- โœ… **Audit Trail Support** - Track authentication events

### ๐ŸŽจ User Experience
- โœ… **LiveView Support** - Modern reactive UI components
- โœ… **Controller Support** - Traditional MVC option
- โœ… **Responsive Design** - Mobile-friendly authentication pages
- โœ… **Accessibility** - WCAG compliant forms and navigation
- โœ… **Error Handling** - User-friendly error messages
- โœ… **Flash Messages** - Informative feedback system

### ๐Ÿ”ง Developer Experience
- โœ… **Igniter-Powered** - AST-based code generation
- โœ… **Smart Detection** - Automatic conflict detection
- โœ… **Interactive Setup** - Guided configuration wizard
- โœ… **Comprehensive Tests** - Full test suite included
- โœ… **Documentation** - Complete API and usage guides
- โœ… **Binary ID Support** - UUID primary keys option

### ๐Ÿš€ Extensibility (Future-Proof)
- ๐Ÿ”„ **Passwordless Auth** - Ready for magic link integration
- ๐Ÿ”„ **OAuth Providers** - Extensible for Google, GitHub, etc.
- ๐Ÿ”„ **Multi-Factor Auth** - Architecture ready for 2FA
- ๐Ÿ”„ **Social Login** - Prepare for SSO integration
- ๐Ÿ”„ **API Authentication** - Ready for token-based API auth

## ๐Ÿ“ฆ Installation Methods

### Method 1: Igniter (Recommended)
```bash
mix igniter.install phx_auth_plus
```

### Method 2: Manual
```bash
# Add to deps
{:phx_auth_plus, "~> 0.0.1", only: [:dev], runtime: false}

# Generate
mix deps.get
mix phx_auth_plus.gen.auth Accounts User users
```

## ๐Ÿ› ๏ธ Usage Options

### Basic Generation
```bash
mix phx_auth_plus.gen.auth Accounts User users
```

### With Options
```bash
# LiveView (default)
mix phx_auth_plus.gen.auth Accounts User users --live

# Controllers only  
mix phx_auth_plus.gen.auth Accounts User users --no-live

# Argon2 hashing (most secure)
mix phx_auth_plus.gen.auth Accounts User users --hashing-lib argon2

# Binary IDs (UUIDs)
mix phx_auth_plus.gen.auth Accounts User users --binary-id

# Custom table name
mix phx_auth_plus.gen.auth Accounts User users --table app_users

# Context app (umbrella projects)
mix phx_auth_plus.gen.auth Accounts User users --context-app my_app
```

## ๐Ÿ”„ After Generation

```bash
# Install dependencies
mix deps.get

# Run migrations  
mix ecto.migrate

# Start server
mix phx.server
```

Visit `http://localhost:4000` to see the complete authentication system!

## ๐Ÿ“ Generated Files

```
lib/
โ”œโ”€โ”€ my_app/accounts/
โ”‚   โ”œโ”€โ”€ user.ex                    # User schema with password fields
โ”‚   โ”œโ”€โ”€ user_token.ex              # Token management for sessions
โ”‚   โ””โ”€โ”€ user_notifier.ex           # Email notifications (Swoosh)
โ””โ”€โ”€ my_app_web/
    โ”œโ”€โ”€ auth/
    โ”‚   โ””โ”€โ”€ user_auth.ex           # Authentication plugs & functions
    โ””โ”€โ”€ user_auth/
        โ”œโ”€โ”€ registration_live.ex   # Signup LiveView
        โ”œโ”€โ”€ login_live.ex          # Login LiveView  
        โ”œโ”€โ”€ settings_live.ex       # Settings LiveView
        โ”œโ”€โ”€ reset_password_live.ex # Password reset LiveView
        โ””โ”€โ”€ confirmation_live.ex   # Email confirmation LiveView

priv/repo/migrations/
โ””โ”€โ”€ xxx_create_users_auth_tables.exs  # Users & tokens tables

test/
โ””โ”€โ”€ my_app_web/
    โ””โ”€โ”€ auth/
        โ””โ”€โ”€ user_auth_test.exs    # Complete authentication tests
```

## ๐Ÿ”— Available Routes

### Authentication Routes
- `/users/register` - Sign up with email + password
- `/users/log_in` - Login with email + password
- `/users/log_out` - Logout (clears all sessions)
- `/users/reset_password` - Forgot password
- `/users/reset_password/:token` - Password reset form
- `/users/confirm` - Resend confirmation
- `/users/confirm/:token` - Email confirmation

### Settings Routes  
- `/users/settings` - Account settings
- `/users/settings/confirm_email/:token` - Email change confirmation

## ๐ŸŽจ Authentication Flow

### 1. Registration
```
User enters email + password โ†’ 
Validation โ†’ 
Hash password โ†’ 
Save user โ†’ 
Send confirmation email โ†’ 
Redirect to login
```

### 2. Login
```
User enters email + password โ†’ 
Find user by email โ†’ 
Verify password โ†’ 
Create session token โ†’ 
Set secure cookie โ†’ 
Redirect to dashboard
```

### 3. Password Reset
```
User requests reset โ†’ 
Generate secure token โ†’ 
Send reset email โ†’ 
User clicks link โ†’ 
Verify token โ†’ 
Allow password change โ†’ 
Invalidate all sessions
```

## ๐Ÿ“Š Security Architecture

### Password Security
- **Hashing**: bcrypt (Unix) / pbkdf2 (Windows) / argon2 (optional)
- **Validation**: Min 12 chars, max 72 chars, complexity checks
- **Storage**: Only hashed passwords stored, never plain text

### Session Security  
- **Tokens**: Cryptographically secure session tokens
- **Cookies**: HttpOnly, SameSite, signed, configurable TTL
- **Tracking**: All sessions tracked in database
- **Invalidation**: Auto-invalidate on password change

### Email Security
- **Confirmation**: Required for account activation
- **Tokens**: Single-use, time-limited confirmation tokens
- **Rate Limiting**: Easy to add email rate limiting
- **Verification**: Secure email change process

## ๐Ÿ†š vs Standard Phoenix Auth

| Feature | Phoenix v1.8+ | PhxAuthPlus |
|---------|---------------|-------------|
| Email + Password | โŒ Removed | โœ… Full Support |
| Account Confirmation | โœ… Basic | โœ… Enhanced |
| Password Reset | โœ… Basic | โœ… Complete Flow |
| Remember Me | โŒ Removed | โœ… Secure Cookies |
| Session Tracking | โœ… Basic | โœ… Enhanced |
| LiveView Support | โœ… Basic | โœ… Complete |
| Smart Generation | โŒ Basic | โœ… AST-based |
| Future Extensibility | โŒ Limited | โœ… Ready |
| Documentation | โœ… Basic | โœ… Comprehensive |

## ๐Ÿ”ง Configuration

### Password Hashing
```elixir
# config/config.exs
config :phx_auth_plus, PhxAuthPlus.Vault,
  # bcrypt (default Unix)
  log_rounds: 12,
  
  # pbkdf2 (default Windows)  
  salt_len: 16,
  digest: :sha256,
  
  # argon2 (most secure)
  t_cost: 2,
  m_cost: 65536,
  parallelism: 4
```

### Session Configuration
```elixir
# config/config.exs  
config :phx_auth_plus, PhxAuthPlusWeb.Auth,
  session_timeout: :timer.hours(24),
  absolute_session_timeout: :timer.hours(72),
  remember_me_timeout: :timer.days(30),
  max_sessions_per_user: 5
```

### Email Configuration
```elixir
# config/dev.exs
config :my_app, MyApp.Mailer,
  adapter: Swoosh.Adapters.Local

# Visit /dev/mailbox to see emails during development
```

## ๐Ÿงช Testing

The generated test suite includes:

- **Registration Tests** - Valid/invalid data, duplicate emails
- **Login Tests** - Valid credentials, invalid attempts, session management
- **Password Reset Tests** - Token generation, validation, expiration
- **Confirmation Tests** - Email verification, token handling
- **Settings Tests** - Password changes, email updates
- **Security Tests** - Session invalidation, concurrent sessions

Run tests with:
```bash
mix test test/my_app_web/auth/user_auth_test.exs
```

## ๐ŸŽจ Customization

### Add Custom Fields to User
```elixir
# lib/my_app/accounts/user.ex
schema "users" do
  field :email, :string
  field :password, :string, virtual: true, redact: true
  field :hashed_password, :string, redact: true
  field :confirmed_at, :utc_datetime_usec
  
  # Custom fields
  field :first_name, :string
  field :last_name, :string
  field :avatar_url, :string
  field :role, :string, default: "user"
  
  timestamps()
end
```

### Add Role-Based Authorization
```elixir
# lib/my_app/accounts/authorization.ex
defmodule MyApp.Accounts.Authorization do
  def admin?(%User{role: "admin"}), do: true
  def admin?(_), do: false
  
  def can_access?(user, resource) do
    # Your authorization logic here
  end
end
```

### Customize LiveViews
```elixir
# lib/my_app_web/user_auth/registration_live.ex
defmodule MyAppWeb.UserAuth.RegistrationLive do
  use MyAppWeb, :live_view

  def render(assigns) do
    ~H"""
    <div class="mx-auto max-w-md">
      <.header class="text-center">
        Create your account
        <:subtitle>
          Join our community today
        </:subtitle>
      </.header>
      
      <!-- Your custom registration form -->
    </div>
    """
  end
end
```

## ๐Ÿ“š Documentation

- [Installation Guide](guides/installation.md)
- [Configuration Options](guides/configuration.md)  
- [Customization Guide](guides/customization.md)
- [Security Best Practices](guides/security.md)
- [Migration from Phoenix Auth](guides/migration.md)
- [Adding OAuth Providers](guides/oauth.md)
- [API Authentication](guides/api_auth.md)

## ๐Ÿš€ Roadmap

### v1.1.0 (Planned)
- ๐Ÿ”„ OAuth 2.0 providers (Google, GitHub, Facebook)
- ๐Ÿ”„ Magic link authentication
- ๐Ÿ”„ Two-factor authentication (TOTP)
- ๐Ÿ”„ Rate limiting middleware

### v1.2.0 (Future)
- ๐Ÿ”„ SSO/SAML support
- ๐Ÿ”„ LDAP integration
- ๐Ÿ”„ Biometric authentication
- ๐Ÿ”„ Advanced audit logging

### v2.0.0 (Long-term)
- ๐Ÿ”„ Multi-tenant authentication
- ๐Ÿ”„ GraphQL authentication
- ๐Ÿ”„ Advanced user management
- ๐Ÿ”„ Enterprise features

## ๐Ÿค Contributing

Contributions welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md).

### Development Setup
```bash
# Clone the repository
git clone https://github.com/your-username/phx_auth_plus.git
cd phx_auth_plus

# Install dependencies
mix deps.get

# Run tests
mix test

# Generate documentation
mix docs
```

## ๐Ÿ“„ License

MIT License - see [LICENSE.md](LICENSE.md) for details.

## ๐Ÿ”— Links

- **Hex Package**: https://hex.pm/packages/phx_auth_plus
- **Documentation**: https://hexdocs.pm/phx_auth_plus
- **GitHub**: https://github.com/your-username/phx_auth_plus
- **Issues & Support**: https://github.com/your-username/phx_auth_plus/issues
- **Phoenix Auth Docs**: https://hexdocs.pm/phoenix/mix_phx_gen_auth.html

## ๐ŸŽฏ Why "Plus"?

**PhxAuthPlus** is designed to be the **complete authentication solution** that grows with your application:

1. **Plus Features** - All the features Phoenix removed + more
2. **Plus Security** - Enhanced security with modern best practices  
3. **Plus Extensibility** - Ready for future authentication methods
4. **Plus Developer Experience** - Igniter-powered smart generation
5. **Plus Documentation** - Comprehensive guides and examples

Start with email + password today, add OAuth tomorrow, implement 2FA next week - **PhxAuthPlus scales with your needs**!

---

**Built with โค๏ธ using [Igniter](https://hexdocs.pm/igniter)** - The future of Elixir code generation!

๐Ÿš€ **Ready to build the complete authentication system your users deserve?**