diff --git a/AGENTS.md b/AGENTS.md index 0e1fe7ac..1913b13e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -44,6 +44,37 @@ custom classes must fully style the input - Focus on **delightful details** like hover effects, loading states, and smooth page transitions + +## Authentication + +- **Always** handle authentication flow at the router level with proper redirects +- **Always** be mindful of where to place routes. `phx.gen.auth` creates multiple router plugs: + - A plug `:fetch_current_scope_for_user` that is included in the default browser pipeline + - A plug `:require_authenticated_user` that redirects to the log in page when the user is not authenticated + - In both cases, a `@current_scope` is assigned to the Plug connection + - A plug `redirect_if_user_is_authenticated` that redirects to a default path in case the user is authenticated - useful for a registration page that should only be shown to unauthenticated users +- **Always let the user know in which router scopes and pipeline you are placing the route, AND SAY WHY** +- `phx.gen.auth` assigns the `current_scope` assign - it **does not assign a `current_user` assign** +- Always pass the assign `current_scope` to context modules as first argument. When performing queries, use `current_scope.user` to filter the query results +- To derive/access `current_user` in templates, **always use the `@current_scope.user`**, never use **`@current_user`** in templates +- Anytime you hit `current_scope` errors or the logged in session isn't displaying the right content, **always double check the router and ensure you are using the correct plug as described below** + +### Routes that require authentication + +Controller routes must be placed in a scope that sets the `:require_authenticated_user` plug: + + scope "/", AppWeb do + pipe_through [:browser, :require_authenticated_user] + + get "/", MyControllerThatRequiresAuth, :index + end + +### Routes that work with or without authentication + +Controllers automatically have the `current_scope` available if they use the `:browser` pipeline. + + + diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md new file mode 100644 index 00000000..50f2b1b6 --- /dev/null +++ b/IMPLEMENTATION_PLAN.md @@ -0,0 +1,403 @@ +# TowerOps - Network Monitoring & Alerting Platform +## Implementation Plan + +## Overview +Multi-tenant network monitoring and alerting application for tracking network equipment health via ping monitoring. + +## Core Requirements +1. User accounts (email as username) +2. Organizations (multi-tenant) +3. Organization membership with permission levels +4. Site hierarchy +5. Equipment management (IP-based) +6. Automated ping monitoring (5-minute intervals) +7. Alerting system + +--- + +## Data Model Design + +### Users +- `id` (binary_id, PK) +- `email` (string, unique, username) +- `hashed_password` (string) +- `confirmed_at` (utc_datetime, nullable) +- `inserted_at` / `updated_at` (utc_datetime) + +### Organizations +- `id` (binary_id, PK) +- `name` (string) +- `slug` (string, unique) - for URLs +- `inserted_at` / `updated_at` (utc_datetime) + +### OrganizationMemberships +- `id` (binary_id, PK) +- `organization_id` (binary_id, FK -> organizations) +- `user_id` (binary_id, FK -> users) +- `role` (enum: owner, admin, member, viewer) +- `inserted_at` / `updated_at` (utc_datetime) +- Unique constraint on (organization_id, user_id) + +**Permission Levels:** +- `owner` - Full control, can delete org, manage all settings +- `admin` - Can manage users, sites, equipment, view all +- `member` - Can add/edit equipment, view sites +- `viewer` - Read-only access + +### Sites +- `id` (binary_id, PK) +- `organization_id` (binary_id, FK -> organizations) +- `parent_site_id` (binary_id, FK -> sites, nullable) - for hierarchy +- `name` (string) +- `description` (text, nullable) +- `location` (string, nullable) +- `inserted_at` / `updated_at` (utc_datetime) + +### Equipment +- `id` (binary_id, PK) +- `site_id` (binary_id, FK -> sites) +- `name` (string) +- `ip_address` (string) +- `description` (text, nullable) +- `status` (enum: up, down, unknown) +- `last_checked_at` (utc_datetime, nullable) +- `last_status_change_at` (utc_datetime, nullable) +- `monitoring_enabled` (boolean, default: true) +- `check_interval_seconds` (integer, default: 300) - 5 minutes +- `inserted_at` / `updated_at` (utc_datetime) + +### MonitoringChecks (historical log) +- `id` (binary_id, PK) +- `equipment_id` (binary_id, FK -> equipment) +- `status` (enum: success, failure) +- `response_time_ms` (integer, nullable) +- `checked_at` (utc_datetime) +- Index on (equipment_id, checked_at) + +### Alerts +- `id` (binary_id, PK) +- `equipment_id` (binary_id, FK -> equipment) +- `alert_type` (enum: equipment_down, equipment_up) +- `triggered_at` (utc_datetime) +- `acknowledged_at` (utc_datetime, nullable) +- `acknowledged_by_id` (binary_id, FK -> users, nullable) +- `resolved_at` (utc_datetime, nullable) +- `email_sent_at` (utc_datetime, nullable) +- `inserted_at` / `updated_at` (utc_datetime) + +### OrganizationInvitations +- `id` (binary_id, PK) +- `organization_id` (binary_id, FK -> organizations) +- `email` (string) +- `role` (enum: admin, member, viewer) - cannot invite as owner +- `token` (string, unique) - secure random token for invite link +- `invited_by_id` (binary_id, FK -> users) +- `accepted_at` (utc_datetime, nullable) +- `accepted_by_id` (binary_id, FK -> users, nullable) +- `expires_at` (utc_datetime) - invites expire after 7 days +- `inserted_at` / `updated_at` (utc_datetime) + +--- + +## Architecture Components + +### 1. Authentication & Authorization + +**Use Phoenix.LiveView built-in patterns:** +- Email/password authentication +- Session-based auth with LiveView +- Password reset via email + +**Authorization Strategy:** +- Context-based permissions (organization-scoped) +- Plugs for organization membership verification +- LiveView mount hooks for permission checks +- Helper functions: `can?(user, :action, resource)` + +### 2. Multi-Tenancy + +**Organization Scoping:** +- All queries scoped by current_organization +- LiveView assigns: `@current_user`, `@current_organization`, `@current_membership` +- Router organization switcher for users in multiple orgs +- URL structure: `/orgs/:org_slug/sites`, `/orgs/:org_slug/equipment` + +### 3. Monitoring System + +**Background Job Architecture:** +- Use GenServer or DynamicSupervisor for monitoring workers +- One worker per equipment (or batched by site) +- Quantum or similar for scheduling (or custom OTP solution) +- Use `:gen_icmp` or System.cmd("ping") for ping checks + +**Monitoring Flow:** +1. Worker wakes up every N seconds (configurable per equipment) +2. Pings equipment IP address +3. Records result in monitoring_checks table +4. Updates equipment status if changed +5. Creates alert if status transitions (up->down or down->up) +6. Broadcasts status change via PubSub for real-time UI updates + +### 4. Real-Time Updates + +**Phoenix PubSub Topics:** +- `organization:#{org_id}:equipment:#{equipment_id}` - Equipment status +- `organization:#{org_id}:alerts` - New alerts +- `organization:#{org_id}:sites` - Site changes + +**LiveView Integration:** +- Subscribe to relevant topics on mount +- Handle PubSub messages to update assigns +- Stream-based updates for lists + +### 5. UI Structure + +**LiveView Pages:** +- `/login`, `/register` - Authentication +- `/orgs` - Organization list/switcher +- `/orgs/:slug/dashboard` - Overview, active alerts, recent changes +- `/orgs/:slug/sites` - Site hierarchy tree view +- `/orgs/:slug/sites/:id` - Site detail with equipment list +- `/orgs/:slug/equipment` - All equipment list +- `/orgs/:slug/equipment/:id` - Equipment detail with check history +- `/orgs/:slug/alerts` - Alert history +- `/orgs/:slug/settings` - Org settings, members + +**Components:** +- Organization switcher (header) +- Site tree navigator +- Equipment status badge +- Alert list/feed +- Permission-based action buttons + +--- + +## Implementation Stages + +### Stage 1: Foundation & Authentication +**Goal**: User authentication and basic org structure +**Success Criteria**: +- Users can register/login with email +- Users can create organizations +- Users can switch between organizations +- Basic navigation structure +- Tests passing + +**Detailed Tasks**: + +#### 1.1 User Authentication +- [ ] Run `mix phx.gen.auth Accounts User users` to scaffold auth system +- [ ] Review and customize generated code (email as username) +- [ ] Update user registration to create first organization +- [ ] Add tests for auth flows + +**Files Created**: +- `lib/towerops/accounts.ex` - User context +- `lib/towerops/accounts/user.ex` - User schema +- `lib/towerops/accounts/user_token.ex` - Session tokens +- `lib/towerops_web/user_auth.ex` - Auth plugs +- `lib/towerops_web/controllers/user_session_controller.ex` +- `lib/towerops_web/controllers/user_registration_controller.ex` +- `lib/towerops_web/controllers/user_reset_password_controller.ex` +- `lib/towerops_web/controllers/user_settings_controller.ex` +- Migrations for users and user_tokens tables + +#### 1.2 Organizations & Memberships +- [ ] Create migration: `mix ecto.gen.migration create_organizations` +- [ ] Create migration: `mix ecto.gen.migration create_organization_memberships` +- [ ] Create migration: `mix ecto.gen.migration create_organization_invitations` +- [ ] Create `lib/towerops/organizations.ex` context +- [ ] Create `lib/towerops/organizations/organization.ex` schema +- [ ] Create `lib/towerops/organizations/membership.ex` schema +- [ ] Create `lib/towerops/organizations/invitation.ex` schema +- [ ] Add slug generation for organizations (use Ecto changeset) +- [ ] Add tests for organizations context + +**Migration Details**: +```elixir +# organizations table +create table(:organizations, primary_key: false) do + add :id, :binary_id, primary_key: true + add :name, :string, null: false + add :slug, :string, null: false + timestamps(type: :utc_datetime) +end +create unique_index(:organizations, [:slug]) + +# organization_memberships table +create table(:organization_memberships, primary_key: false) do + add :id, :binary_id, primary_key: true + add :organization_id, references(:organizations, type: :binary_id, on_delete: :delete_all) + add :user_id, references(:users, type: :binary_id, on_delete: :delete_all) + add :role, :string, null: false + timestamps(type: :utc_datetime) +end +create unique_index(:organization_memberships, [:organization_id, :user_id]) +create index(:organization_memberships, [:user_id]) +``` + +#### 1.3 Multi-Org Navigation +- [ ] Create organization switcher LiveView component +- [ ] Add current_organization plug to router +- [ ] Create `/orgs` LiveView (list user's organizations) +- [ ] Create `/orgs/new` LiveView (create organization) +- [ ] Update router with organization-scoped routes +- [ ] Add breadcrumb navigation component +- [ ] Add tests for organization switching + +**Router Structure**: +```elixir +scope "/", ToweropsWeb do + pipe_through [:browser, :require_authenticated_user] + + live "/orgs", OrgLive.Index + live "/orgs/new", OrgLive.New +end + +scope "/orgs/:org_slug", ToweropsWeb do + pipe_through [:browser, :require_authenticated_user, :load_current_organization] + + live "/", DashboardLive + # Future: sites, equipment, etc. +end +``` + +#### 1.4 Authorization System +- [ ] Create `lib/towerops/organizations/policy.ex` for permission checks +- [ ] Add `can?/3` helper function +- [ ] Create `:load_current_organization` plug +- [ ] Add permission checks to LiveView mount callbacks +- [ ] Add tests for authorization + +**Permission Matrix**: +| Action | Owner | Admin | Member | Viewer | +|--------|-------|-------|--------|--------| +| View org | ✓ | ✓ | ✓ | ✓ | +| Edit org settings | ✓ | ✓ | ✗ | ✗ | +| Delete org | ✓ | ✗ | ✗ | ✗ | +| Manage members | ✓ | ✓ | ✗ | ✗ | +| Add/edit equipment | ✓ | ✓ | ✓ | ✗ | +| View equipment | ✓ | ✓ | ✓ | ✓ | + +#### 1.5 Basic UI & Layouts +- [ ] Update `layouts.ex` to include org switcher in header +- [ ] Create organization badge component +- [ ] Style navigation with Tailwind +- [ ] Add flash message styling +- [ ] Ensure responsive design + +### Stage 2: Sites & Equipment Management +**Goal**: CRUD for sites and equipment +**Success Criteria**: +- Users can create/edit/delete sites +- Sites can have parent sites (hierarchy) +- Users can add equipment to sites +- Equipment has IP address and basic info + +**Tasks**: +1. Generate sites schema and LiveViews +2. Build site hierarchy tree component +3. Generate equipment schema and LiveViews +4. Add IP address validation +5. Permission checks on all actions + +### Stage 3: Monitoring System +**Goal**: Automated ping monitoring +**Success Criteria**: +- Equipment is pinged every 5 minutes +- Status updates in real-time +- Monitoring checks are logged + +**Tasks**: +1. Design monitoring worker architecture +2. Implement ping functionality +3. Create monitoring_checks schema +4. Build GenServer workers for monitoring +5. Add PubSub broadcasting +6. Update LiveView to receive real-time updates + +### Stage 4: Alerting +**Goal**: Alert generation and management +**Success Criteria**: +- Alerts created on status changes +- Users can view alert history +- Users can acknowledge alerts + +**Tasks**: +1. Create alerts schema +2. Build alert creation logic in monitoring workers +3. Create alert LiveView pages +4. Add alert acknowledgment +5. Alert notifications in UI + +### Stage 5: Polish & Production +**Goal**: Production-ready application +**Success Criteria**: +- All tests passing +- Polished UI with Tailwind +- Email notifications configured +- Production deployment ready + +**Tasks**: +1. Comprehensive test coverage +2. UI/UX improvements +3. Email alert notifications +4. Performance optimization +5. Documentation + +--- + +## Technical Decisions + +### Database +- PostgreSQL with Ecto +- Use binary_id (UUID) for all primary keys (already configured) +- Indexes on foreign keys and frequently queried fields + +### Background Jobs +**Options:** +1. Custom OTP solution with GenServer + Process.send_after +2. Quantum scheduler +3. Oban (more heavyweight but robust) + +**Recommendation**: Start with custom OTP, migrate to Oban if needed + +### Real-time Communication +- Phoenix PubSub for server-side messaging +- LiveView for UI updates +- No WebSocket client code needed + +### Ping Implementation +**Options:** +1. `:gen_icmp` library (requires raw sockets, might need permissions) +2. System.cmd("ping") - simpler, cross-platform +3. HTTP health checks (future enhancement) + +**Recommendation**: System.cmd("ping") for MVP, abstract for future protocols + +--- + +## Decisions Made + +1. **Email notifications**: ✓ Yes - Users receive email alerts on status changes +2. **Multi-org users**: ✓ Yes - Users can belong to multiple organizations +3. **Invite system**: ✓ Email invitation system (secure token-based invites) +4. **Check intervals**: ✓ Customizable per equipment (stored in equipment.check_interval_seconds) + +## Additional Schema Needed + +Based on decisions: +- **OrganizationInvitations** table for email invite workflow +- **email_sent_at** field in Alerts for tracking email delivery + +## Open Questions + +1. **Alert escalation**: Any escalation policies (e.g., page admin if down > X minutes)? +2. **Retention**: How long to keep monitoring_checks history? +3. **Equipment types**: Just ping for now, or plan for SNMP, HTTP, etc.? +4. **Site hierarchy depth**: Any limit on site nesting levels? + +--- + +## Status: Planning Phase - Ready to Begin Stage 1 +Last updated: 2025-12-21 diff --git a/config/config.exs b/config/config.exs index 3f7a0951..d413e955 100644 --- a/config/config.exs +++ b/config/config.exs @@ -56,6 +56,19 @@ config :towerops, ToweropsWeb.Endpoint, pubsub_server: Towerops.PubSub, live_view: [signing_salt: "Uh1ABfdI"] +config :towerops, :scopes, + user: [ + default: true, + module: Towerops.Accounts.Scope, + assign_key: :current_scope, + access_path: [:user, :id], + schema_key: :user_id, + schema_type: :binary_id, + schema_table: :users, + test_data_fixture: Towerops.AccountsFixtures, + test_setup_helper: :register_and_log_in_user + ] + # Import environment specific config. This must remain at the bottom # of this file so it overrides the configuration defined above. config :towerops, diff --git a/config/test.exs b/config/test.exs index bcbd9ccc..62382d20 100644 --- a/config/test.exs +++ b/config/test.exs @@ -1,5 +1,8 @@ import Config +# Only in tests, remove the complexity from the password hashing algorithm +config :bcrypt_elixir, :log_rounds, 1 + # Print only warnings and errors during test config :logger, level: :warning diff --git a/lib/towerops/accounts.ex b/lib/towerops/accounts.ex new file mode 100644 index 00000000..3cb20101 --- /dev/null +++ b/lib/towerops/accounts.ex @@ -0,0 +1,330 @@ +defmodule Towerops.Accounts do + @moduledoc """ + The Accounts context. + """ + + import Ecto.Query, warn: false + + alias Towerops.Accounts.User + alias Towerops.Accounts.UserNotifier + alias Towerops.Accounts.UserToken + alias Towerops.Repo + + ## Database getters + + @doc """ + Gets a user by email. + + ## Examples + + iex> get_user_by_email("foo@example.com") + %User{} + + iex> get_user_by_email("unknown@example.com") + nil + + """ + def get_user_by_email(email) when is_binary(email) do + Repo.get_by(User, email: email) + end + + @doc """ + Gets a user by email and password. + + ## Examples + + iex> get_user_by_email_and_password("foo@example.com", "correct_password") + %User{} + + iex> get_user_by_email_and_password("foo@example.com", "invalid_password") + nil + + """ + def get_user_by_email_and_password(email, password) when is_binary(email) and is_binary(password) do + user = Repo.get_by(User, email: email) + if User.valid_password?(user, password), do: user + end + + @doc """ + Gets a single user. + + Raises `Ecto.NoResultsError` if the User does not exist. + + ## Examples + + iex> get_user!(123) + %User{} + + iex> get_user!(456) + ** (Ecto.NoResultsError) + + """ + def get_user!(id), do: Repo.get!(User, id) + + ## User registration + + @doc """ + Registers a user. + + ## Examples + + iex> register_user(%{field: value}) + {:ok, %User{}} + + iex> register_user(%{field: bad_value}) + {:error, %Ecto.Changeset{}} + + """ + def register_user(attrs) do + %User{} + |> User.email_changeset(attrs) + |> Repo.insert() + end + + @doc """ + Registers a user and creates a default organization. + + ## Examples + + iex> register_user_with_organization(%{field: value}) + {:ok, %User{}} + + iex> register_user_with_organization(%{field: bad_value}) + {:error, %Ecto.Changeset{}} + + """ + def register_user_with_organization(attrs) do + Ecto.Multi.new() + |> Ecto.Multi.insert(:user, fn _ -> + User.email_changeset(%User{}, attrs) + end) + |> Ecto.Multi.run(:organization, fn _repo, %{user: user} -> + org_name = attrs["organization_name"] || "#{user.email}'s Organization" + + Towerops.Organizations.create_organization( + %{name: org_name}, + user.id + ) + end) + |> Repo.transaction() + |> case do + {:ok, %{user: user}} -> {:ok, user} + {:error, :user, changeset, _} -> {:error, changeset} + {:error, :organization, changeset, _} -> {:error, changeset} + end + end + + ## Settings + + @doc """ + Checks whether the user is in sudo mode. + + The user is in sudo mode when the last authentication was done no further + than 20 minutes ago. The limit can be given as second argument in minutes. + """ + def sudo_mode?(user, minutes \\ -20) + + def sudo_mode?(%User{authenticated_at: ts}, minutes) when is_struct(ts, DateTime) do + DateTime.after?(ts, DateTime.add(DateTime.utc_now(), minutes, :minute)) + end + + def sudo_mode?(_user, _minutes), do: false + + @doc """ + Returns an `%Ecto.Changeset{}` for changing the user email. + + See `Towerops.Accounts.User.email_changeset/3` for a list of supported options. + + ## Examples + + iex> change_user_email(user) + %Ecto.Changeset{data: %User{}} + + """ + def change_user_email(user, attrs \\ %{}, opts \\ []) do + User.email_changeset(user, attrs, opts) + end + + @doc """ + Updates the user email using the given token. + + If the token matches, the user email is updated and the token is deleted. + """ + def update_user_email(user, token) do + context = "change:#{user.email}" + + Repo.transact(fn -> + with {:ok, query} <- UserToken.verify_change_email_token_query(token, context), + %UserToken{sent_to: email} <- Repo.one(query), + {:ok, user} <- Repo.update(User.email_changeset(user, %{email: email})), + {_count, _result} <- + Repo.delete_all(from(UserToken, where: [user_id: ^user.id, context: ^context])) do + {:ok, user} + else + _ -> {:error, :transaction_aborted} + end + end) + end + + @doc """ + Returns an `%Ecto.Changeset{}` for changing the user password. + + See `Towerops.Accounts.User.password_changeset/3` for a list of supported options. + + ## Examples + + iex> change_user_password(user) + %Ecto.Changeset{data: %User{}} + + """ + def change_user_password(user, attrs \\ %{}, opts \\ []) do + User.password_changeset(user, attrs, opts) + end + + @doc """ + Updates the user password. + + Returns a tuple with the updated user, as well as a list of expired tokens. + + ## Examples + + iex> update_user_password(user, %{password: ...}) + {:ok, {%User{}, [...]}} + + iex> update_user_password(user, %{password: "too short"}) + {:error, %Ecto.Changeset{}} + + """ + def update_user_password(user, attrs) do + user + |> User.password_changeset(attrs) + |> update_user_and_delete_all_tokens() + end + + ## Session + + @doc """ + Generates a session token. + """ + def generate_user_session_token(user) do + {token, user_token} = UserToken.build_session_token(user) + Repo.insert!(user_token) + token + end + + @doc """ + Gets the user with the given signed token. + + If the token is valid `{user, token_inserted_at}` is returned, otherwise `nil` is returned. + """ + def get_user_by_session_token(token) do + {:ok, query} = UserToken.verify_session_token_query(token) + Repo.one(query) + end + + @doc """ + Gets the user with the given magic link token. + """ + def get_user_by_magic_link_token(token) do + with {:ok, query} <- UserToken.verify_magic_link_token_query(token), + {user, _token} <- Repo.one(query) do + user + else + _ -> nil + end + end + + @doc """ + Logs the user in by magic link. + + There are three cases to consider: + + 1. The user has already confirmed their email. They are logged in + and the magic link is expired. + + 2. The user has not confirmed their email and no password is set. + In this case, the user gets confirmed, logged in, and all tokens - + including session ones - are expired. In theory, no other tokens + exist but we delete all of them for best security practices. + + 3. The user has not confirmed their email but a password is set. + This cannot happen in the default implementation but may be the + source of security pitfalls. See the "Mixing magic link and password registration" section of + `mix help phx.gen.auth`. + """ + def login_user_by_magic_link(token) do + {:ok, query} = UserToken.verify_magic_link_token_query(token) + + case Repo.one(query) do + # Prevent session fixation attacks by disallowing magic links for unconfirmed users with password + {%User{confirmed_at: nil, hashed_password: hash}, _token} when not is_nil(hash) -> + raise """ + magic link log in is not allowed for unconfirmed users with a password set! + + This cannot happen with the default implementation, which indicates that you + might have adapted the code to a different use case. Please make sure to read the + "Mixing magic link and password registration" section of `mix help phx.gen.auth`. + """ + + {%User{confirmed_at: nil} = user, _token} -> + user + |> User.confirm_changeset() + |> update_user_and_delete_all_tokens() + + {user, token} -> + Repo.delete!(token) + {:ok, {user, []}} + + nil -> + {:error, :not_found} + end + end + + @doc ~S""" + Delivers the update email instructions to the given user. + + ## Examples + + iex> deliver_user_update_email_instructions(user, current_email, &url(~p"/users/settings/confirm-email/#{&1}")) + {:ok, %{to: ..., body: ...}} + + """ + def deliver_user_update_email_instructions(%User{} = user, current_email, update_email_url_fun) + when is_function(update_email_url_fun, 1) do + {encoded_token, user_token} = UserToken.build_email_token(user, "change:#{current_email}") + + Repo.insert!(user_token) + UserNotifier.deliver_update_email_instructions(user, update_email_url_fun.(encoded_token)) + end + + @doc """ + Delivers the magic link login instructions to the given user. + """ + def deliver_login_instructions(%User{} = user, magic_link_url_fun) when is_function(magic_link_url_fun, 1) do + {encoded_token, user_token} = UserToken.build_email_token(user, "login") + Repo.insert!(user_token) + UserNotifier.deliver_login_instructions(user, magic_link_url_fun.(encoded_token)) + end + + @doc """ + Deletes the signed token with the given context. + """ + def delete_user_session_token(token) do + Repo.delete_all(from(UserToken, where: [token: ^token, context: "session"])) + :ok + end + + ## Token helper + + defp update_user_and_delete_all_tokens(changeset) do + Repo.transact(fn -> + with {:ok, user} <- Repo.update(changeset) do + tokens_to_expire = Repo.all_by(UserToken, user_id: user.id) + + Repo.delete_all(from(t in UserToken, where: t.id in ^Enum.map(tokens_to_expire, & &1.id))) + + {:ok, {user, tokens_to_expire}} + end + end) + end +end diff --git a/lib/towerops/accounts/scope.ex b/lib/towerops/accounts/scope.ex new file mode 100644 index 00000000..3358e1fb --- /dev/null +++ b/lib/towerops/accounts/scope.ex @@ -0,0 +1,33 @@ +defmodule Towerops.Accounts.Scope do + @moduledoc """ + Defines the scope of the caller to be used throughout the app. + + The `Towerops.Accounts.Scope` allows public interfaces to receive + information about the caller, such as if the call is initiated from an + end-user, and if so, which user. Additionally, such a scope can carry fields + such as "super user" or other privileges for use as authorization, or to + ensure specific code paths can only be access for a given scope. + + It is useful for logging as well as for scoping pubsub subscriptions and + broadcasts when a caller subscribes to an interface or performs a particular + action. + + Feel free to extend the fields on this struct to fit the needs of + growing application requirements. + """ + + alias Towerops.Accounts.User + + defstruct user: nil + + @doc """ + Creates a scope for the given user. + + Returns nil if no user is given. + """ + def for_user(%User{} = user) do + %__MODULE__{user: user} + end + + def for_user(nil), do: nil +end diff --git a/lib/towerops/accounts/user.ex b/lib/towerops/accounts/user.ex new file mode 100644 index 00000000..08418170 --- /dev/null +++ b/lib/towerops/accounts/user.ex @@ -0,0 +1,137 @@ +defmodule Towerops.Accounts.User do + @moduledoc false + use Ecto.Schema + + import Ecto.Changeset + + @primary_key {:id, :binary_id, autogenerate: true} + @foreign_key_type :binary_id + schema "users" do + field :email, :string + field :password, :string, virtual: true, redact: true + field :hashed_password, :string, redact: true + field :confirmed_at, :utc_datetime + field :authenticated_at, :utc_datetime, virtual: true + + has_many :memberships, Towerops.Organizations.Membership + has_many :organizations, through: [:memberships, :organization] + + timestamps(type: :utc_datetime) + end + + @doc """ + A user changeset for registering or changing the email. + + It requires the email to change otherwise an error is added. + + ## Options + + * `:validate_unique` - Set to false if you don't want to validate the + uniqueness of the email, useful when displaying live validations. + Defaults to `true`. + """ + def email_changeset(user, attrs, opts \\ []) do + user + |> cast(attrs, [:email]) + |> validate_email(opts) + end + + defp validate_email(changeset, opts) do + changeset = + changeset + |> validate_required([:email]) + |> validate_format(:email, ~r/^[^@,;\s]+@[^@,;\s]+$/, message: "must have the @ sign and no spaces") + |> validate_length(:email, max: 160) + + if Keyword.get(opts, :validate_unique, true) do + changeset + |> unsafe_validate_unique(:email, Towerops.Repo) + |> unique_constraint(:email) + |> validate_email_changed() + else + changeset + end + end + + defp validate_email_changed(changeset) do + if get_field(changeset, :email) && get_change(changeset, :email) == nil do + add_error(changeset, :email, "did not change") + else + changeset + end + end + + @doc """ + A user changeset for changing the password. + + It is important to validate the length of the password, as long passwords may + be very expensive to hash for certain algorithms. + + ## Options + + * `:hash_password` - Hashes the password so it can be stored securely + in the database and ensures the password field is cleared to prevent + leaks in the logs. If password hashing is not needed and clearing the + password field is not desired (like when using this changeset for + validations on a LiveView form), this option can be set to `false`. + Defaults to `true`. + """ + def password_changeset(user, attrs, opts \\ []) do + user + |> cast(attrs, [:password]) + |> validate_confirmation(:password, message: "does not match password") + |> validate_password(opts) + end + + defp validate_password(changeset, opts) do + changeset + |> validate_required([:password]) + |> validate_length(:password, min: 12, max: 72) + # Examples of additional password validation: + # |> validate_format(:password, ~r/[a-z]/, message: "at least one lower case character") + # |> validate_format(:password, ~r/[A-Z]/, message: "at least one upper case character") + # |> validate_format(:password, ~r/[!?@#$%^&*_0-9]/, message: "at least one digit or punctuation character") + |> maybe_hash_password(opts) + end + + defp maybe_hash_password(changeset, opts) do + hash_password? = Keyword.get(opts, :hash_password, true) + password = get_change(changeset, :password) + + if hash_password? && password && changeset.valid? do + changeset + # If using Bcrypt, then further validate it is at most 72 bytes long + |> validate_length(:password, max: 72, count: :bytes) + # Hashing could be done with `Ecto.Changeset.prepare_changes/2`, but that + # would keep the database transaction open longer and hurt performance. + |> put_change(:hashed_password, Bcrypt.hash_pwd_salt(password)) + |> delete_change(:password) + else + changeset + end + end + + @doc """ + Confirms the account by setting `confirmed_at`. + """ + def confirm_changeset(user) do + now = DateTime.utc_now(:second) + change(user, confirmed_at: now) + end + + @doc """ + Verifies the password. + + If there is no user or the user doesn't have a password, we call + `Bcrypt.no_user_verify/0` to avoid timing attacks. + """ + def valid_password?(%Towerops.Accounts.User{hashed_password: hashed_password}, password) + when is_binary(hashed_password) and byte_size(password) > 0 do + Bcrypt.verify_pass(password, hashed_password) + end + + def valid_password?(_, _) do + Bcrypt.no_user_verify() + false + end +end diff --git a/lib/towerops/accounts/user_notifier.ex b/lib/towerops/accounts/user_notifier.ex new file mode 100644 index 00000000..f5a061ae --- /dev/null +++ b/lib/towerops/accounts/user_notifier.ex @@ -0,0 +1,85 @@ +defmodule Towerops.Accounts.UserNotifier do + @moduledoc false + import Swoosh.Email + + alias Towerops.Accounts.User + alias Towerops.Mailer + + # Delivers the email using the application mailer. + defp deliver(recipient, subject, body) do + email = + new() + |> to(recipient) + |> from({"Towerops", "contact@example.com"}) + |> subject(subject) + |> text_body(body) + + with {:ok, _metadata} <- Mailer.deliver(email) do + {:ok, email} + end + end + + @doc """ + Deliver instructions to update a user email. + """ + def deliver_update_email_instructions(user, url) do + deliver(user.email, "Update email instructions", """ + + ============================== + + Hi #{user.email}, + + You can change your email by visiting the URL below: + + #{url} + + If you didn't request this change, please ignore this. + + ============================== + """) + end + + @doc """ + Deliver instructions to log in with a magic link. + """ + def deliver_login_instructions(user, url) do + case user do + %User{confirmed_at: nil} -> deliver_confirmation_instructions(user, url) + _ -> deliver_magic_link_instructions(user, url) + end + end + + defp deliver_magic_link_instructions(user, url) do + deliver(user.email, "Log in instructions", """ + + ============================== + + Hi #{user.email}, + + You can log into your account by visiting the URL below: + + #{url} + + If you didn't request this email, please ignore this. + + ============================== + """) + end + + defp deliver_confirmation_instructions(user, url) do + deliver(user.email, "Confirmation instructions", """ + + ============================== + + Hi #{user.email}, + + You can confirm your account by visiting the URL below: + + #{url} + + If you didn't create an account with us, please ignore this. + + ============================== + """) + end +end diff --git a/lib/towerops/accounts/user_token.ex b/lib/towerops/accounts/user_token.ex new file mode 100644 index 00000000..0ddbe315 --- /dev/null +++ b/lib/towerops/accounts/user_token.ex @@ -0,0 +1,161 @@ +defmodule Towerops.Accounts.UserToken do + @moduledoc false + use Ecto.Schema + + import Ecto.Query + + alias Towerops.Accounts.UserToken + + @hash_algorithm :sha256 + @rand_size 32 + + # It is very important to keep the magic link token expiry short, + # since someone with access to the email may take over the account. + @magic_link_validity_in_minutes 15 + @change_email_validity_in_days 7 + @session_validity_in_days 14 + + @primary_key {:id, :binary_id, autogenerate: true} + @foreign_key_type :binary_id + schema "users_tokens" do + field :token, :binary + field :context, :string + field :sent_to, :string + field :authenticated_at, :utc_datetime + belongs_to :user, Towerops.Accounts.User + + timestamps(type: :utc_datetime, updated_at: false) + end + + @doc """ + Generates a token that will be stored in a signed place, + such as session or cookie. As they are signed, those + tokens do not need to be hashed. + + The reason why we store session tokens in the database, even + though Phoenix already provides a session cookie, is because + Phoenix's default session cookies are not persisted, they are + simply signed and potentially encrypted. This means they are + valid indefinitely, unless you change the signing/encryption + salt. + + Therefore, storing them allows individual user + sessions to be expired. The token system can also be extended + to store additional data, such as the device used for logging in. + You could then use this information to display all valid sessions + and devices in the UI and allow users to explicitly expire any + session they deem invalid. + """ + def build_session_token(user) do + token = :crypto.strong_rand_bytes(@rand_size) + dt = user.authenticated_at || DateTime.utc_now(:second) + {token, %UserToken{token: token, context: "session", user_id: user.id, authenticated_at: dt}} + end + + @doc """ + Checks if the token is valid and returns its underlying lookup query. + + The query returns the user found by the token, if any, along with the token's creation time. + + The token is valid if it matches the value in the database and it has + not expired (after @session_validity_in_days). + """ + def verify_session_token_query(token) do + query = + from token in by_token_and_context_query(token, "session"), + join: user in assoc(token, :user), + where: token.inserted_at > ago(@session_validity_in_days, "day"), + select: {%{user | authenticated_at: token.authenticated_at}, token.inserted_at} + + {:ok, query} + end + + @doc """ + Builds a token and its hash to be delivered to the user's email. + + The non-hashed token is sent to the user email while the + hashed part is stored in the database. The original token cannot be reconstructed, + which means anyone with read-only access to the database cannot directly use + the token in the application to gain access. Furthermore, if the user changes + their email in the system, the tokens sent to the previous email are no longer + valid. + + Users can easily adapt the existing code to provide other types of delivery methods, + for example, by phone numbers. + """ + def build_email_token(user, context) do + build_hashed_token(user, context, user.email) + end + + defp build_hashed_token(user, context, sent_to) do + token = :crypto.strong_rand_bytes(@rand_size) + hashed_token = :crypto.hash(@hash_algorithm, token) + + {Base.url_encode64(token, padding: false), + %UserToken{ + token: hashed_token, + context: context, + sent_to: sent_to, + user_id: user.id + }} + end + + @doc """ + Checks if the token is valid and returns its underlying lookup query. + + If found, the query returns a tuple of the form `{user, token}`. + + The given token is valid if it matches its hashed counterpart in the + database. This function also checks if the token is being used within + 15 minutes. The context of a magic link token is always "login". + """ + def verify_magic_link_token_query(token) do + case Base.url_decode64(token, padding: false) do + {:ok, decoded_token} -> + hashed_token = :crypto.hash(@hash_algorithm, decoded_token) + + query = + from token in by_token_and_context_query(hashed_token, "login"), + join: user in assoc(token, :user), + where: token.inserted_at > ago(^@magic_link_validity_in_minutes, "minute"), + where: token.sent_to == user.email, + select: {user, token} + + {:ok, query} + + :error -> + :error + end + end + + @doc """ + Checks if the token is valid and returns its underlying lookup query. + + The query returns the user_token found by the token, if any. + + This is used to validate requests to change the user + email. + The given token is valid if it matches its hashed counterpart in the + database and if it has not expired (after @change_email_validity_in_days). + The context must always start with "change:". + """ + def verify_change_email_token_query(token, "change:" <> _ = context) do + case Base.url_decode64(token, padding: false) do + {:ok, decoded_token} -> + hashed_token = :crypto.hash(@hash_algorithm, decoded_token) + + query = + from token in by_token_and_context_query(hashed_token, context), + where: token.inserted_at > ago(@change_email_validity_in_days, "day") + + {:ok, query} + + :error -> + :error + end + end + + defp by_token_and_context_query(token, context) do + from UserToken, where: [token: ^token, context: ^context] + end +end diff --git a/lib/towerops/organizations.ex b/lib/towerops/organizations.ex new file mode 100644 index 00000000..aa939eff --- /dev/null +++ b/lib/towerops/organizations.ex @@ -0,0 +1,228 @@ +defmodule Towerops.Organizations do + @moduledoc """ + The Organizations context. + """ + + import Ecto.Query + + alias Towerops.Organizations.Invitation + alias Towerops.Organizations.Membership + alias Towerops.Organizations.Organization + alias Towerops.Organizations.Policy + alias Towerops.Repo + + ## Organizations + + @doc """ + Returns the list of organizations for a user. + """ + def list_user_organizations(user_id) do + Repo.all( + from(o in Organization, + join: m in Membership, + on: m.organization_id == o.id, + where: m.user_id == ^user_id, + order_by: [desc: m.inserted_at], + preload: [memberships: m] + ) + ) + end + + @doc """ + Gets a single organization by ID. + """ + def get_organization!(id), do: Repo.get!(Organization, id) + + @doc """ + Gets a single organization by slug. + """ + def get_organization_by_slug!(slug) do + Repo.get_by!(Organization, slug: slug) + end + + @doc """ + Creates an organization and adds the creator as owner. + """ + def create_organization(attrs, user_id) do + Ecto.Multi.new() + |> Ecto.Multi.insert(:organization, Organization.changeset(%Organization{}, attrs)) + |> Ecto.Multi.insert(:membership, fn %{organization: organization} -> + Membership.changeset(%Membership{}, %{ + organization_id: organization.id, + user_id: user_id, + role: :owner + }) + end) + |> Repo.transaction() + |> case do + {:ok, %{organization: organization}} -> {:ok, organization} + {:error, :organization, changeset, _} -> {:error, changeset} + {:error, :membership, changeset, _} -> {:error, changeset} + end + end + + @doc """ + Updates an organization. + """ + def update_organization(%Organization{} = organization, attrs) do + organization + |> Organization.changeset(attrs) + |> Repo.update() + end + + @doc """ + Deletes an organization. + """ + def delete_organization(%Organization{} = organization) do + Repo.delete(organization) + end + + @doc """ + Returns an `%Ecto.Changeset{}` for tracking organization changes. + """ + def change_organization(%Organization{} = organization, attrs \\ %{}) do + Organization.changeset(organization, attrs) + end + + ## Memberships + + @doc """ + Gets a user's membership for an organization. + """ + def get_membership(organization_id, user_id) do + Repo.get_by(Membership, organization_id: organization_id, user_id: user_id) + end + + @doc """ + Gets a user's membership for an organization, raises if not found. + """ + def get_membership!(organization_id, user_id) do + Repo.get_by!(Membership, organization_id: organization_id, user_id: user_id) + end + + @doc """ + Lists all memberships for an organization. + """ + def list_organization_memberships(organization_id) do + Repo.all( + from(m in Membership, + where: m.organization_id == ^organization_id, + preload: [:user], + order_by: [asc: m.inserted_at] + ) + ) + end + + @doc """ + Creates a membership (adds a user to an organization). + """ + def create_membership(attrs) do + %Membership{} + |> Membership.changeset(attrs) + |> Repo.insert() + end + + @doc """ + Updates a membership (changes a user's role). + """ + def update_membership(%Membership{} = membership, attrs) do + membership + |> Membership.changeset(attrs) + |> Repo.update() + end + + @doc """ + Deletes a membership (removes a user from an organization). + """ + def delete_membership(%Membership{} = membership) do + Repo.delete(membership) + end + + ## Invitations + + @doc """ + Lists pending invitations for an organization. + """ + def list_pending_invitations(organization_id) do + now = DateTime.utc_now() + + Repo.all( + from(i in Invitation, + where: i.organization_id == ^organization_id, + where: is_nil(i.accepted_at), + where: i.expires_at > ^now, + preload: [:invited_by], + order_by: [desc: i.inserted_at] + ) + ) + end + + @doc """ + Creates an invitation. + """ + def create_invitation(attrs) do + %Invitation{} + |> Invitation.changeset(attrs) + |> Repo.insert() + end + + @doc """ + Gets an invitation by token. + """ + def get_invitation_by_token(token) do + now = DateTime.utc_now() + + Repo.one( + from(i in Invitation, + where: i.token == ^token, + where: is_nil(i.accepted_at), + where: i.expires_at > ^now, + preload: [:organization] + ) + ) + end + + @doc """ + Accepts an invitation and creates a membership. + """ + def accept_invitation(invitation, user_id) do + Ecto.Multi.new() + |> Ecto.Multi.update(:invitation, fn _ -> + Ecto.Changeset.change(invitation, %{accepted_at: DateTime.utc_now(), accepted_by_id: user_id}) + end) + |> Ecto.Multi.insert(:membership, fn _ -> + Membership.changeset(%Membership{}, %{ + organization_id: invitation.organization_id, + user_id: user_id, + role: invitation.role + }) + end) + |> Repo.transaction() + |> case do + {:ok, %{membership: membership}} -> {:ok, membership} + {:error, _failed_operation, changeset, _changes_so_far} -> {:error, changeset} + end + end + + @doc """ + Deletes an invitation. + """ + def delete_invitation(%Invitation{} = invitation) do + Repo.delete(invitation) + end + + ## Authorization + + @doc """ + Checks if a membership has permission to perform an action on a resource. + + ## Examples + + iex> can?(membership, :edit, :equipment) + true + + iex> can?(membership, :delete, :organization) + false + """ + defdelegate can?(membership, action, resource), to: Policy +end diff --git a/lib/towerops/organizations/invitation.ex b/lib/towerops/organizations/invitation.ex new file mode 100644 index 00000000..45a0a70c --- /dev/null +++ b/lib/towerops/organizations/invitation.ex @@ -0,0 +1,48 @@ +defmodule Towerops.Organizations.Invitation do + @moduledoc false + use Ecto.Schema + + import Ecto.Changeset + + alias Towerops.Accounts.User + + @primary_key {:id, :binary_id, autogenerate: true} + @foreign_key_type :binary_id + schema "organization_invitations" do + field :email, :string + field :role, Ecto.Enum, values: [:admin, :member, :viewer] + field :token, :string + field :accepted_at, :utc_datetime + field :expires_at, :utc_datetime + + belongs_to :organization, Towerops.Organizations.Organization + belongs_to :invited_by, User + belongs_to :accepted_by, User + + timestamps(type: :utc_datetime) + end + + @doc false + def changeset(invitation, attrs) do + invitation + |> cast(attrs, [:email, :role, :organization_id, :invited_by_id]) + |> validate_required([:email, :role, :organization_id, :invited_by_id]) + |> validate_format(:email, ~r/^[^\s]+@[^\s]+\.[^\s]+$/) + |> generate_token() + |> set_expires_at() + |> validate_required([:token, :expires_at]) + |> unique_constraint(:token) + |> foreign_key_constraint(:organization_id) + |> foreign_key_constraint(:invited_by_id) + end + + defp generate_token(changeset) do + token = 32 |> :crypto.strong_rand_bytes() |> Base.url_encode64(padding: false) + put_change(changeset, :token, token) + end + + defp set_expires_at(changeset) do + expires_at = DateTime.add(DateTime.utc_now(), 7, :day) + put_change(changeset, :expires_at, expires_at) + end +end diff --git a/lib/towerops/organizations/membership.ex b/lib/towerops/organizations/membership.ex new file mode 100644 index 00000000..5d111ecb --- /dev/null +++ b/lib/towerops/organizations/membership.ex @@ -0,0 +1,29 @@ +defmodule Towerops.Organizations.Membership do + @moduledoc false + use Ecto.Schema + + import Ecto.Changeset + + @primary_key {:id, :binary_id, autogenerate: true} + @foreign_key_type :binary_id + schema "organization_memberships" do + field :role, Ecto.Enum, values: [:owner, :admin, :member, :viewer] + + belongs_to :organization, Towerops.Organizations.Organization + belongs_to :user, Towerops.Accounts.User + + timestamps(type: :utc_datetime) + end + + @doc false + def changeset(membership, attrs) do + membership + |> cast(attrs, [:role, :organization_id, :user_id]) + |> validate_required([:role, :organization_id, :user_id]) + |> foreign_key_constraint(:organization_id) + |> foreign_key_constraint(:user_id) + |> unique_constraint([:organization_id, :user_id], + name: :organization_memberships_organization_id_user_id_index + ) + end +end diff --git a/lib/towerops/organizations/organization.ex b/lib/towerops/organizations/organization.ex new file mode 100644 index 00000000..f09552ad --- /dev/null +++ b/lib/towerops/organizations/organization.ex @@ -0,0 +1,50 @@ +defmodule Towerops.Organizations.Organization do + @moduledoc false + use Ecto.Schema + + import Ecto.Changeset + + @primary_key {:id, :binary_id, autogenerate: true} + @foreign_key_type :binary_id + schema "organizations" do + field :name, :string + field :slug, :string + + has_many :memberships, Towerops.Organizations.Membership + has_many :users, through: [:memberships, :user] + has_many :invitations, Towerops.Organizations.Invitation + + timestamps(type: :utc_datetime) + end + + @doc false + def changeset(organization, attrs) do + organization + |> cast(attrs, [:name]) + |> validate_required([:name]) + |> validate_length(:name, min: 2, max: 100) + |> generate_slug() + |> validate_required([:slug]) + |> unique_constraint(:slug) + end + + defp generate_slug(changeset) do + case get_change(changeset, :name) do + nil -> + changeset + + name -> + slug = + name + |> String.downcase() + |> String.replace(~r/[^a-z0-9\s-]/, "") + |> String.replace(~r/\s+/, "-") + |> String.replace(~r/-+/, "-") + |> String.trim("-") + + # Add random suffix to ensure uniqueness + slug_with_suffix = "#{slug}-#{:rand.uniform(9999)}" + put_change(changeset, :slug, slug_with_suffix) + end + end +end diff --git a/lib/towerops/organizations/policy.ex b/lib/towerops/organizations/policy.ex new file mode 100644 index 00000000..1eb1993c --- /dev/null +++ b/lib/towerops/organizations/policy.ex @@ -0,0 +1,46 @@ +defmodule Towerops.Organizations.Policy do + @moduledoc """ + Authorization policy for organization resources. + """ + + alias Towerops.Organizations.Membership + + @doc """ + Checks if a user can perform an action on a resource within an organization. + + ## Examples + + iex> can?(%Membership{role: :owner}, :delete, :organization) + true + + iex> can?(%Membership{role: :viewer}, :edit, :equipment) + false + """ + def can?(%Membership{role: role}, action, resource) do + check_permission(role, action, resource) + end + + def can?(nil, _action, _resource), do: false + + # Owner permissions - can do everything + defp check_permission(:owner, _action, _resource), do: true + + # Admin permissions + defp check_permission(:admin, :delete, :organization), do: false + defp check_permission(:admin, _action, _resource), do: true + + # Member permissions + defp check_permission(:member, action, :organization) when action in [:view, :list], do: true + + defp check_permission(:member, :delete, _resource), do: false + defp check_permission(:member, action, :membership) when action in [:create, :edit], do: false + defp check_permission(:member, action, :invitation) when action in [:create, :delete], do: false + + defp check_permission(:member, action, resource) + when action in [:view, :list, :create, :edit] and resource in [:site, :equipment, :alert], do: true + + # Viewer permissions - read-only + defp check_permission(:viewer, action, _resource) when action in [:view, :list], do: true + defp check_permission(:viewer, :acknowledge, :alert), do: true + defp check_permission(:viewer, _action, _resource), do: false +end diff --git a/lib/towerops_web/components/layouts/root.html.heex b/lib/towerops_web/components/layouts/root.html.heex index 38d762cf..5e425fe3 100644 --- a/lib/towerops_web/components/layouts/root.html.heex +++ b/lib/towerops_web/components/layouts/root.html.heex @@ -31,6 +31,26 @@
+ {@inner_content}