8000 feature: User adds avatar by mwoods79 · Pull Request #89 · huddlz-hq/huddlz · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .formatter.exs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
[
import_deps: [
:ash_oban,
:oban,
:ash_authentication,
:ash_authentication_phoenix,
:ash_postgres,
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,6 @@ npm-debug.log
.*.env

.playwright-mcp/

# User uploads (development only)
/priv/static/uploads/
1 change: 1 addition & 0 deletions Brewfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
brew "vips"
4 changes: 2 additions & 2 deletions CLAUDE.md
8BD0
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ custom classes must fully style the input
<!-- usage-rules-header -->
# Usage Rules

**IMPORTANT**: Consult these usage rules early and often when working with the packages listed below.
Before attempting to use any of these packages or to discover if you should use them, review their
**IMPORTANT**: Consult these usage rules early and often when working with the packages listed below.
Before attempting to use any of these packages or to discover if you should use them, review their
usage rules to understand the correct patterns, conventions, and best practices.
<!-- usage-rules-header-end -->

Expand Down
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ FROM ${BUILDER_IMAGE} AS builder

# install build dependencies
RUN apt-get update \
&& apt-get install -y --no-install-recommends build-essential git \
&& apt-get install -y --no-install-recommends build-essential git libvips-dev \
&& rm -rf /var/lib/apt/lists/*

# prepare build dir
Expand Down Expand Up @@ -71,7 +71,7 @@ RUN mix release
FROM ${RUNNER_IMAGE} AS final

RUN apt-get update \
&& apt-get install -y --no-install-recommends libstdc++6 openssl libncurses6 locales ca-certificates \
&& apt-get install -y --no-install-recommends libstdc++6 openssl libncurses6 locales ca-certificates libvips \
&& rm -rf /var/lib/apt/lists/*

# Set the locale
Expand Down
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,34 @@ Huddlz is under active development. The landing page with huddl listings has bee
- **Database**: PostgreSQL
- **Testing**: Cucumber/Gherkin for behavior-driven development

## Dependencies

### System Dependencies

**macOS:**
```bash
brew bundle # or: brew install vips
```

**Ubuntu/Debian:**
```bash
apt install libvips-dev
```

**Fedora:**
```bash
dnf install vips-devel
```

### Language Runtimes

This project uses [mise](https://mise.jdx.dev/) for version management:
```bash
mise install
```

This installs Elixir 1.19.3 (OTP 28) and Erlang 28.1.1 as specified in `.mise.toml`.

## Getting Started

To start your Phoenix server:
Expand Down
9 changes: 9 additions & 0 deletions config/config.exs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@
# General application configuration
import Config

config :ash_oban, pro?: false

config :huddlz, Oban,
engine: Oban.Engines.Basic,
notifier: Oban.Notifiers.Postgres,
queues: [default: 10, profile_picture_cleanup: 5],
repo: Huddlz.Repo,
plugins: [{Oban.Plugins.Cron, []}]

config :ash,
allow_forbidden_field_for_relationships_by_default?: true,
include_embedded_source_by_default?: false,
Expand Down
10 changes: 10 additions & 0 deletions config/dev.exs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,16 @@ config :phoenix_live_view,
# To use SendGrid in development, comment out the line below and set SENDGRID_API_KEY
config :swoosh, :api_client, false

config :huddlz, :storage, adapter: Huddlz.Storage.Local

# To use S3/Tigris in development:
# 1. Set BUCKET_NAME and AWS_ENDPOINT_URL_S3 environment variables
# 2. Uncomment the config below and comment out the Local adapter above
# config :huddlz, :storage,
# adapter: Huddlz.Storage.S3,
# bucket: System.get_env("BUCKET_NAME"),
# endpoint: System.get_env("AWS_ENDPOINT_URL_S3")

# Optional: Enable SendGrid in development
# if sendgrid_api_key = System.get_env("SENDGRID_API_KEY") do
# config :huddlz, Huddlz.Mailer,
Expand Down
20 changes: 20 additions & 0 deletions config/runtime.exs
Original file line number Diff line number Diff line change
Expand Up @@ -148,4 +148,24 @@ if config_env() == :prod do

# Configure Swoosh API client to use Req (already included in deps)
config :swoosh, :api_client, Swoosh.ApiClient.Req

# Tigris S3 Storage - env vars set automatically by `fly storage create`
bucket_name =
System.get_env("BUCKET_NAME") ||
raise "environment variable BUCKET_NAME is missing"

aws_endpoint =
System.get_env("AWS_ENDPOINT_URL_S3") ||
raise "environment variable AWS_ENDPOINT_URL_S3 is missing"

# These are used by req_s3 for authentication
System.get_env("AWS_ACCESS_KEY_ID") ||
raise "environment variable AWS_ACCESS_KEY_ID is missing"

System.get_env("AWS_SECRET_ACCESS_KEY") ||
raise "environment variable AWS_SECRET_ACCESS_KEY is missing"

config :huddlz, :storage,
bucket: bucket_name,
endpoint: aws_endpoint
end
4 changes: 4 additions & 0 deletions config/test.exs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Config
config :huddlz, Oban, testing: :manual
config :huddlz, token_signing_secret: "B/l8TS6gx/jZednXDgVLAka5u5vIqk22"
config :bcrypt_elixir, log_rounds: 1

Expand Down Expand Up @@ -46,3 +47,6 @@ config :huddlz, env: :test

# Configure PhoenixTest
config :phoenix_test, :endpoint, HuddlzWeb.Endpoint

# Local file storage for tests
config :huddlz, :storage, adapter: Huddlz.Storage.Local
8 changes: 8 additions & 0 deletions lib/huddlz/accounts.ex
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,13 @@ defmodule Huddlz.Accounts do
define :get_by_email, action: :get_by_email, args: [:email]
define :update_display_name, action: :update_display_name, args: [:display_name]
end

resource Huddlz.Accounts.ProfilePicture do
define :create_profile_picture, action: :create
define :get_current_profile_picture, action: :get_current_for_user, args: [:user_id]
define :list_profile_pictures, action: :list_for_user, args: [:user_id]
define :delete_profile_picture, action: :destroy
define :soft_delete_profile_picture, action: :soft_delete
end
end
end
195 changes: 195 additions & 0 deletions lib/huddlz/accounts/profile_picture.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
defmodule Huddlz.Accounts.ProfilePicture do
@moduledoc """
Profile picture resource for storing user avatars.

The current profile picture for a user is determined by the most recent
record by `inserted_at`. Old pictures remain in the database until cleaned
up by a background job.
"""

alias Huddlz.Storage.ProfilePictures

use Ash.Resource,
otp_app: :huddlz,
domain: Huddlz.Accounts,
authorizers: [Ash.Policy.Authorizer],
data_layer: AshPostgres.DataLayer,
extensions: [AshOban]

postgres do
table "profile_pictures"
repo Huddlz.Repo

custom_indexes do
index [:user_id, :inserted_at]
end
end

oban do
triggers do
trigger :cleanup_storage do
action :hard_delete
# No scheduler - triggered immediately via run_oban_trigger
scheduler_cron false
queue :profile_picture_cleanup
# Retry with exponential backoff (max_attempts defaults to 20)
backoff :exponential
log_final_error? true
worker_module_name Huddlz.Workers.ProfilePictureCleanup
end
end
end

actions do
defaults [:read, :destroy]

create :create do
description "Upload a new profile picture for a user"
primary? true
accept [:filename, :content_type, :size_bytes, :storage_path, :thumbnail_path, :user_id]
end

read :get_current_for_user do
description "Get the current (most recent) profile picture for a user"
get? true

argument :user_id, :uuid do
allow_nil? false
end

filter expr(user_id == ^arg(:user_id) and is_nil(deleted_at))
prepare build(sort: [inserted_at: :desc], limit: 1)
end

read :list_for_user do
description "Get all non-deleted profile pictures for a user"

argument :user_id, :uuid do
allow_nil? false
end

filter expr(user_id == ^arg(:user_id) and is_nil(deleted_at))
prepare build(sort: [inserted_at: :desc])
end

update :soft_delete do
description "Soft-delete a profile picture and trigger cleanup job"
accept []
change set_attribute(:deleted_at, &DateTime.utc_now/0)
change run_oban_trigger(:cleanup_storage)
end

destroy :hard_delete do
description "Hard-delete a profile picture and remove from storage"
require_atomic? false

change fn changeset, _context ->
Ash.Changeset.before_action(changeset, fn changeset ->
record = changeset.data

# Delete original
case ProfilePictures.delete(record.storage_path) do
:ok -> :ok
{:error, reason} -> raise "Storage delete failed: #{inspect(reason)}"
end

# Delete thumbnail (if exists) - ignore errors for orphaned thumbnails
if record.thumbnail_path do
ProfilePictures.delete(record.thumbnail_path)
end

changeset
end)
end
end
end

policies do
bypass actor_attribute_equals(:role, :admin) do
authorize_if always()
end

# Users can upload pictures for themselves
policy action(:create) do
description "Users can only upload profile pictures for themselves"
authorize_if Huddlz.Accounts.ProfilePicture.Checks.IsOwnPicture
end

# Anyone can read profile pictures (they're public)
policy action_type(:read) do
authorize_if always()
end

# Users can destroy their own pictures
policy action(:destroy) do
description "Users can only delete their own profile pictures"
authorize_if relates_to_actor_via(:user)
end

# Users can soft-delete their own pictures
policy action(:soft_delete) do
description "Users can only soft-delete their own profile pictures"
authorize_if relates_to_actor_via(:user)
end

# Hard delete is only called by Oban workers (no actor)
policy action(:hard_delete) do
description "Hard delete is called by background jobs"
authorize_if always()
end
end

attributes do
uuid_primary_key :id

attribute :filename, :string do
allow_nil? false
public? true
description "Original filename of the uploaded image"
end

attribute :content_type, :string do
allow_nil? false
public? true
description "MIME type of the image (e.g., image/jpeg, image/png)"
end

attribute :size_bytes, :integer do
allow_nil? false
public? true
description "File size in bytes"
end

attribute :storage_path, :string do
allow_nil? false
public? true
description "Path to the original file in the storage system (S3, local, etc.)"
end

attribute :thumbnail_path, :string do
allow_nil? true
public? true
description "Path to the resized thumbnail in storage"
end

create_timestamp :inserted_at

attribute :deleted_at, :utc_datetime_usec do
allow_nil? true
public? false
description "Timestamp when the picture was soft-deleted"
end
end

relationships do
belongs_to :user, Huddlz.Accounts.User do
attribute_type :uuid
allow_nil? false
public? true
end
end

identities do
identity :unique_storage_path, [:storage_path]
end
end
20 changes: 20 additions & 0 deletions lib/huddlz/accounts/profile_picture/checks/is_own_picture.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
defmodule Huddlz.Accounts.ProfilePicture.Checks.IsOwnPicture do
@moduledoc """
Check that verifies the user_id being set matches the actor's id.
Used for create actions where we can't use expression-based filters.
"""
use Ash.Policy.SimpleCheck

@impl true
def describe(_opts) do
"user_id matches actor's id"
end

@impl true
def match?(nil, _context, _opts), do: false

def match?(actor, %{changeset: changeset}, _opts) do
user_id = Ash.Changeset.get_attribute(changeset, :user_id)
user_id == actor.id
end
end
Loading
0