> ## Documentation Index
> Fetch the complete documentation index at: https://docs.strikebet.app/llms.txt
> Use this file to discover all available pages before exploring further.

# User Management

> Understanding user lifecycle and profile management in Strike Auth Service

## Overview

Strike Auth Service provides comprehensive user management capabilities, handling the complete user lifecycle from registration to deletion. The service manages user profiles, authentication credentials, and metadata while ensuring security and compliance.

## User Lifecycle

<Steps>
  <Step title="Registration">
    Users register with email/phone and password, or through OAuth providers
  </Step>

  <Step title="Verification">
    Email or phone verification confirms user identity
  </Step>

  <Step title="Authentication">
    Users sign in to receive access tokens for API access
  </Step>

  <Step title="Profile Management">
    Users can update their profile information and preferences
  </Step>

  <Step title="Account Maintenance">
    Password changes, email updates, and security settings
  </Step>

  <Step title="Deactivation/Deletion">
    Account suspension or permanent deletion when needed
  </Step>
</Steps>

## User Data Structure

### Core User Fields

```json
{
  "id": "123e4567-e89b-12d3-a456-426614174000",
  "aud": "authenticated",
  "role": "authenticated",
  "email": "user@example.com",
  "phone": "+1234567890",
  "email_confirmed_at": "2023-01-01T00:00:00Z",
  "phone_confirmed_at": "2023-01-01T00:00:00Z",
  "last_sign_in_at": "2023-01-01T12:00:00Z",
  "created_at": "2023-01-01T00:00:00Z",
  "updated_at": "2023-01-01T12:00:00Z"
}
```

### Metadata Types

<Tabs>
  <Tab title="App Metadata">
    System-managed metadata that applications can read but users cannot modify.

    ```json
    {
      "app_metadata": {
        "provider": "email",
        "providers": ["email", "google"],
        "roles": ["user"],
        "subscription_tier": "premium",
        "last_login_ip": "192.168.1.1"
      }
    }
    ```
  </Tab>

  <Tab title="User Metadata">
    User-controlled metadata for profile information and preferences.

    ```json
    {
      "user_metadata": {
        "first_name": "John",
        "last_name": "Doe",
        "avatar_url": "https://example.com/avatar.jpg",
        "preferences": {
          "theme": "dark",
          "notifications": true
        }
      }
    }
    ```
  </Tab>
</Tabs>

## User Roles and Permissions

### Default Roles

| Role            | Description     | Capabilities                |
| --------------- | --------------- | --------------------------- |
| `authenticated` | Standard user   | Access to user endpoints    |
| `admin`         | Administrator   | Full system access          |
| `service_role`  | Service account | Server-to-server operations |

### Custom Roles

You can define custom roles in the `app_metadata`:

```json
{
  "app_metadata": {
    "roles": ["moderator", "premium_user"],
    "permissions": ["read:posts", "write:comments"]
  }
}
```

## Registration Methods

### Email/Password Registration

Traditional registration with email verification:

```javascript
const user = await authService.signup({
  email: 'user@example.com',
  password: 'securepassword123',
  data: {
    first_name: 'John',
    last_name: 'Doe'
  }
});
```

### Phone/Password Registration

Registration with SMS verification:

```javascript
const user = await authService.signup({
  phone: '+1234567890',
  password: 'securepassword123',
  data: {
    first_name: 'John',
    last_name: 'Doe'
  }
});
```

### OAuth Registration

Registration through external providers:

```javascript
// Redirect to OAuth provider
window.location.href = '/authorize?provider=google&redirect_to=/dashboard';
```

## Profile Management

### Updating User Information

Users can update their profile information:

```javascript
const updatedUser = await authService.updateUser({
  data: {
    first_name: 'Jane',
    avatar_url: 'https://example.com/new-avatar.jpg',
    preferences: {
      theme: 'light',
      notifications: false
    }
  }
});
```

### Changing Email

Email changes require verification:

```javascript
// Request email change
await authService.updateUser({
  email: 'newemail@example.com'
});

// User receives confirmation email
// After clicking link, email is updated
```

### Changing Password

Password changes require current password:

```javascript
await authService.updateUser({
  password: 'newsecurepassword123'
});
```

## Admin User Management

### Creating Users (Admin)

Administrators can create users with specific settings:

```javascript
const newUser = await authService.admin.createUser({
  email: 'admin-created@example.com',
  password: 'temporarypassword',
  email_confirm: true, // Skip email verification
  user_metadata: {
    role: 'manager',
    department: 'sales'
  },
  app_metadata: {
    roles: ['manager'],
    created_by: 'admin'
  }
});
```

### Updating Users (Admin)

Admins can update any user's information:

```javascript
const updatedUser = await authService.admin.updateUser(userId, {
  email_confirm: true,
  ban_duration: 'none', // Unban user
  app_metadata: {
    roles: ['admin'],
    last_admin_action: new Date().toISOString()
  }
});
```

### User Invitations

Send invitations to new users:

```javascript
const invitation = await authService.admin.inviteUser({
  email: 'invited@example.com',
  data: {
    invited_by: 'admin@example.com',
    role: 'editor'
  },
  redirect_to: 'https://yourapp.com/welcome'
});
```

## User States

### Account Status

Users can be in various states:

* **Active**: Normal user with full access
* **Unconfirmed**: Registered but email/phone not verified
* **Banned**: Temporarily or permanently suspended
* **Deleted**: Account marked for deletion

### Confirmation Status

Track verification status:

```javascript
// Check if user needs verification
if (!user.email_confirmed_at) {
  // Show email verification prompt
  await authService.resend({
    type: 'signup',
    email: user.email
  });
}
```

## Security Features

### Password Security

* **Hashing**: Passwords are hashed using bcrypt
* **Complexity**: Configurable password requirements
* **History**: Prevent password reuse
* **Expiration**: Optional password expiration policies

### Account Protection

* **Rate Limiting**: Prevent brute force attacks
* **Account Lockout**: Temporary lockout after failed attempts
* **Audit Logging**: Track all user actions
* **Session Management**: Control active sessions

### Data Privacy

* **GDPR Compliance**: Support for data export and deletion
* **Data Minimization**: Only collect necessary information
* **Encryption**: Sensitive data encrypted at rest
* **Access Controls**: Role-based access to user data

## Best Practices

<AccordionGroup>
  <Accordion title="User Registration">
    * Implement email/phone verification
    * Use strong password requirements
    * Collect minimal required information
    * Provide clear privacy policy
  </Accordion>

  <Accordion title="Profile Management">
    * Allow users to control their data
    * Implement proper validation
    * Provide data export functionality
    * Support account deletion
  </Accordion>

  <Accordion title="Admin Operations">
    * Require admin authentication
    * Log all admin actions
    * Implement approval workflows
    * Use principle of least privilege
  </Accordion>

  <Accordion title="Security">
    * Regular security audits
    * Monitor for suspicious activity
    * Implement proper session management
    * Keep user data encrypted
  </Accordion>
</AccordionGroup>

## Integration Examples

### React User Profile Component

```jsx
import { useState, useEffect } from 'react';
import { useAuth } from './auth-context';

function UserProfile() {
  const { user, updateUser } = useAuth();
  const [profile, setProfile] = useState(user?.user_metadata || {});

  const handleSave = async () => {
    try {
      await updateUser({ data: profile });
      alert('Profile updated successfully!');
    } catch (error) {
      alert('Failed to update profile');
    }
  };

  return (
    <div>
      <h2>User Profile</h2>
      <input
        type="text"
        placeholder="First Name"
        value={profile.first_name || ''}
        onChange={(e) => setProfile({
          ...profile,
          first_name: e.target.value
        })}
      />
      <input
        type="text"
        placeholder="Last Name"
        value={profile.last_name || ''}
        onChange={(e) => setProfile({
          ...profile,
          last_name: e.target.value
        })}
      />
      <button onClick={handleSave}>Save Profile</button>
    </div>
  );
}
```

### Node.js Admin Dashboard

```javascript
const express = require('express');
const { createClient } = require('@supabase/supabase-js');

const app = express();
const supabase = createClient(url, serviceRoleKey);

// Get all users (admin only)
app.get('/admin/users', async (req, res) => {
  try {
    const { data: users, error } = await supabase.auth.admin.listUsers();
    if (error) throw error;
    res.json(users);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Update user (admin only)
app.put('/admin/users/:id', async (req, res) => {
  try {
    const { data: user, error } = await supabase.auth.admin.updateUserById(
      req.params.id,
      req.body
    );
    if (error) throw error;
    res.json(user);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});
```

## Related Topics

<CardGroup cols={2}>
  <Card title="Authentication" icon="key" href="/authentication">
    Learn about authentication methods and token management
  </Card>

  <Card title="Security" icon="shield-check" href="/concepts/security">
    Understand security features and best practices
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/user/get-profile">
    Detailed API documentation for user endpoints
  </Card>

  <Card title="Admin Operations" icon="user-gear" href="/guides/admin-operations">
    Guide to administrative user management
  </Card>
</CardGroup>
