# 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?**
