From bc7687392973640a8ed37645397a67945276ddad Mon Sep 17 00:00:00 2001 From: vitaotm Date: Mon, 3 Nov 2025 00:28:25 -0300 Subject: [PATCH 01/17] First commit - Set up devise User - add gems - install active_storage --- .dockerignore | 51 +++ .gitattributes | 9 + .github/dependabot.yml | 12 + .github/workflows/ci.yml | 101 +++++ .gitignore | 34 ++ .kamal/hooks/docker-setup.sample | 3 + .kamal/hooks/post-app-boot.sample | 3 + .kamal/hooks/post-deploy.sample | 14 + .kamal/hooks/post-proxy-reboot.sample | 3 + .kamal/hooks/pre-app-boot.sample | 3 + .kamal/hooks/pre-build.sample | 51 +++ .kamal/hooks/pre-connect.sample | 47 ++ .kamal/hooks/pre-deploy.sample | 122 +++++ .kamal/hooks/pre-proxy-reboot.sample | 3 + .kamal/secrets | 17 + .rubocop.yml | 8 + .ruby-version | 1 + Dockerfile | 72 +++ Gemfile | 69 +++ Gemfile.lock | 424 ++++++++++++++++++ Rakefile | 6 + app/assets/images/.keep | 0 app/assets/stylesheets/application.css | 10 + app/controllers/application_controller.rb | 4 + app/controllers/concerns/.keep | 0 app/helpers/application_helper.rb | 2 + app/javascript/application.js | 3 + app/javascript/controllers/application.js | 9 + .../controllers/hello_controller.js | 7 + app/javascript/controllers/index.js | 4 + app/jobs/application_job.rb | 7 + app/mailers/application_mailer.rb | 4 + app/models/application_record.rb | 3 + app/models/concerns/.keep | 0 app/models/user.rb | 6 + app/views/layouts/application.html.erb | 28 ++ app/views/layouts/mailer.html.erb | 13 + app/views/layouts/mailer.text.erb | 1 + app/views/pwa/manifest.json.erb | 22 + app/views/pwa/service-worker.js | 26 ++ bin/brakeman | 7 + bin/bundle | 109 +++++ bin/dev | 2 + bin/docker-entrypoint | 14 + bin/importmap | 4 + bin/jobs | 6 + bin/kamal | 27 ++ bin/rails | 4 + bin/rake | 4 + bin/rubocop | 8 + bin/setup | 34 ++ bin/thrust | 5 + config.ru | 6 + config/application.rb | 27 ++ config/boot.rb | 4 + config/cable.yml | 17 + config/cache.yml | 16 + config/credentials.yml.enc | 1 + config/database.yml | 98 ++++ config/deploy.yml | 116 +++++ config/environment.rb | 5 + config/environments/development.rb | 72 +++ config/environments/production.rb | 90 ++++ config/environments/test.rb | 53 +++ config/importmap.rb | 7 + config/initializers/assets.rb | 7 + .../initializers/content_security_policy.rb | 25 ++ config/initializers/devise.rb | 313 +++++++++++++ .../initializers/filter_parameter_logging.rb | 8 + config/initializers/inflections.rb | 16 + config/locales/devise.en.yml | 65 +++ config/locales/en.yml | 31 ++ config/puma.rb | 41 ++ config/queue.yml | 18 + config/recurring.yml | 15 + config/routes.rb | 15 + config/storage.yml | 34 ++ db/cable_schema.rb | 11 + db/cache_schema.rb | 14 + .../20251103032403_devise_create_users.rb | 44 ++ .../20251103032531_add_fields_to_users.rb | 6 + ...te_active_storage_tables.active_storage.rb | 57 +++ db/queue_schema.rb | 129 ++++++ db/schema.rb | 61 +++ db/seeds.rb | 9 + lib/tasks/.keep | 0 log/.keep | 0 public/400.html | 114 +++++ public/404.html | 114 +++++ public/406-unsupported-browser.html | 114 +++++ public/422.html | 114 +++++ public/500.html | 114 +++++ public/icon.png | Bin 0 -> 4166 bytes public/icon.svg | 3 + public/robots.txt | 1 + script/.keep | 0 storage/.keep | 0 test/application_system_test_case.rb | 5 + test/controllers/.keep | 0 test/fixtures/files/.keep | 0 test/fixtures/users.yml | 11 + test/helpers/.keep | 0 test/integration/.keep | 0 test/mailers/.keep | 0 test/models/.keep | 0 test/models/user_test.rb | 7 + test/system/.keep | 0 test/test_helper.rb | 15 + tmp/.keep | 0 tmp/pids/.keep | 0 tmp/storage/.keep | 0 vendor/.keep | 0 vendor/javascript/.keep | 0 113 files changed, 3469 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitattributes create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100755 .kamal/hooks/docker-setup.sample create mode 100755 .kamal/hooks/post-app-boot.sample create mode 100755 .kamal/hooks/post-deploy.sample create mode 100755 .kamal/hooks/post-proxy-reboot.sample create mode 100755 .kamal/hooks/pre-app-boot.sample create mode 100755 .kamal/hooks/pre-build.sample create mode 100755 .kamal/hooks/pre-connect.sample create mode 100755 .kamal/hooks/pre-deploy.sample create mode 100755 .kamal/hooks/pre-proxy-reboot.sample create mode 100644 .kamal/secrets create mode 100644 .rubocop.yml create mode 100644 .ruby-version create mode 100644 Dockerfile create mode 100644 Gemfile create mode 100644 Gemfile.lock create mode 100644 Rakefile create mode 100644 app/assets/images/.keep create mode 100644 app/assets/stylesheets/application.css create mode 100644 app/controllers/application_controller.rb create mode 100644 app/controllers/concerns/.keep create mode 100644 app/helpers/application_helper.rb create mode 100644 app/javascript/application.js create mode 100644 app/javascript/controllers/application.js create mode 100644 app/javascript/controllers/hello_controller.js create mode 100644 app/javascript/controllers/index.js create mode 100644 app/jobs/application_job.rb create mode 100644 app/mailers/application_mailer.rb create mode 100644 app/models/application_record.rb create mode 100644 app/models/concerns/.keep create mode 100644 app/models/user.rb create mode 100644 app/views/layouts/application.html.erb create mode 100644 app/views/layouts/mailer.html.erb create mode 100644 app/views/layouts/mailer.text.erb create mode 100644 app/views/pwa/manifest.json.erb create mode 100644 app/views/pwa/service-worker.js create mode 100755 bin/brakeman create mode 100755 bin/bundle create mode 100755 bin/dev create mode 100755 bin/docker-entrypoint create mode 100755 bin/importmap create mode 100755 bin/jobs create mode 100755 bin/kamal create mode 100755 bin/rails create mode 100755 bin/rake create mode 100755 bin/rubocop create mode 100755 bin/setup create mode 100755 bin/thrust create mode 100644 config.ru create mode 100644 config/application.rb create mode 100644 config/boot.rb create mode 100644 config/cable.yml create mode 100644 config/cache.yml create mode 100644 config/credentials.yml.enc create mode 100644 config/database.yml create mode 100644 config/deploy.yml create mode 100644 config/environment.rb create mode 100644 config/environments/development.rb create mode 100644 config/environments/production.rb create mode 100644 config/environments/test.rb create mode 100644 config/importmap.rb create mode 100644 config/initializers/assets.rb create mode 100644 config/initializers/content_security_policy.rb create mode 100644 config/initializers/devise.rb create mode 100644 config/initializers/filter_parameter_logging.rb create mode 100644 config/initializers/inflections.rb create mode 100644 config/locales/devise.en.yml create mode 100644 config/locales/en.yml create mode 100644 config/puma.rb create mode 100644 config/queue.yml create mode 100644 config/recurring.yml create mode 100644 config/routes.rb create mode 100644 config/storage.yml create mode 100644 db/cable_schema.rb create mode 100644 db/cache_schema.rb create mode 100644 db/migrate/20251103032403_devise_create_users.rb create mode 100644 db/migrate/20251103032531_add_fields_to_users.rb create mode 100644 db/migrate/20251103032728_create_active_storage_tables.active_storage.rb create mode 100644 db/queue_schema.rb create mode 100644 db/schema.rb create mode 100644 db/seeds.rb create mode 100644 lib/tasks/.keep create mode 100644 log/.keep create mode 100644 public/400.html create mode 100644 public/404.html create mode 100644 public/406-unsupported-browser.html create mode 100644 public/422.html create mode 100644 public/500.html create mode 100644 public/icon.png create mode 100644 public/icon.svg create mode 100644 public/robots.txt create mode 100644 script/.keep create mode 100644 storage/.keep create mode 100644 test/application_system_test_case.rb create mode 100644 test/controllers/.keep create mode 100644 test/fixtures/files/.keep create mode 100644 test/fixtures/users.yml create mode 100644 test/helpers/.keep create mode 100644 test/integration/.keep create mode 100644 test/mailers/.keep create mode 100644 test/models/.keep create mode 100644 test/models/user_test.rb create mode 100644 test/system/.keep create mode 100644 test/test_helper.rb create mode 100644 tmp/.keep create mode 100644 tmp/pids/.keep create mode 100644 tmp/storage/.keep create mode 100644 vendor/.keep create mode 100644 vendor/javascript/.keep diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..325bfc036 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,51 @@ +# See https://docs.docker.com/engine/reference/builder/#dockerignore-file for more about ignoring files. + +# Ignore git directory. +/.git/ +/.gitignore + +# Ignore bundler config. +/.bundle + +# Ignore all environment files. +/.env* + +# Ignore all default key files. +/config/master.key +/config/credentials/*.key + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/.keep + +# Ignore storage (uploaded files in development and any SQLite databases). +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/.keep + +# Ignore assets. +/node_modules/ +/app/assets/builds/* +!/app/assets/builds/.keep +/public/assets + +# Ignore CI service files. +/.github + +# Ignore Kamal files. +/config/deploy*.yml +/.kamal + +# Ignore development files +/.devcontainer + +# Ignore Docker-related files +/.dockerignore +/Dockerfile* diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..8dc432343 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# See https://git-scm.com/docs/gitattributes for more about git attribute files. + +# Mark the database schema as having been generated. +db/schema.rb linguist-generated + +# Mark any vendored files as having been vendored. +vendor/* linguist-vendored +config/credentials/*.yml.enc diff=rails_credentials +config/credentials.yml.enc diff=rails_credentials diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..f0527e6be --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +version: 2 +updates: +- package-ecosystem: bundler + directory: "/" + schedule: + interval: daily + open-pull-requests-limit: 10 +- package-ecosystem: github-actions + directory: "/" + schedule: + interval: daily + open-pull-requests-limit: 10 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..37adcd3b0 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,101 @@ +name: CI + +on: + pull_request: + push: + branches: [ main ] + +jobs: + scan_ruby: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: .ruby-version + bundler-cache: true + + - name: Scan for common Rails security vulnerabilities using static analysis + run: bin/brakeman --no-pager + + scan_js: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: .ruby-version + bundler-cache: true + + - name: Scan for security vulnerabilities in JavaScript dependencies + run: bin/importmap audit + + lint: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: .ruby-version + bundler-cache: true + + - name: Lint code for consistent style + run: bin/rubocop -f github + + test: + runs-on: ubuntu-latest + + services: + postgres: + image: postgres + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + ports: + - 5432:5432 + options: --health-cmd="pg_isready" --health-interval=10s --health-timeout=5s --health-retries=3 + + # redis: + # image: redis + # ports: + # - 6379:6379 + # options: --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 + + steps: + - name: Install packages + run: sudo apt-get update && sudo apt-get install --no-install-recommends -y build-essential git libpq-dev libyaml-dev pkg-config google-chrome-stable + + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: .ruby-version + bundler-cache: true + + - name: Run tests + env: + RAILS_ENV: test + DATABASE_URL: postgres://postgres:postgres@localhost:5432 + # REDIS_URL: redis://localhost:6379/0 + run: bin/rails db:test:prepare test test:system + + - name: Keep screenshots from failed system tests + uses: actions/upload-artifact@v4 + if: failure() + with: + name: screenshots + path: ${{ github.workspace }}/tmp/screenshots + if-no-files-found: ignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..f92525ca5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,34 @@ +# See https://help.github.com/articles/ignoring-files for more about ignoring files. +# +# Temporary files generated by your text editor or operating system +# belong in git's global ignore instead: +# `$XDG_CONFIG_HOME/git/ignore` or `~/.config/git/ignore` + +# Ignore bundler config. +/.bundle + +# Ignore all environment files. +/.env* + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/ +!/tmp/pids/.keep + +# Ignore storage (uploaded files in development and any SQLite databases). +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/ +!/tmp/storage/.keep + +/public/assets + +# Ignore master key for decrypting credentials and more. +/config/master.key diff --git a/.kamal/hooks/docker-setup.sample b/.kamal/hooks/docker-setup.sample new file mode 100755 index 000000000..2fb07d7d7 --- /dev/null +++ b/.kamal/hooks/docker-setup.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Docker set up on $KAMAL_HOSTS..." diff --git a/.kamal/hooks/post-app-boot.sample b/.kamal/hooks/post-app-boot.sample new file mode 100755 index 000000000..70f9c4bc9 --- /dev/null +++ b/.kamal/hooks/post-app-boot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Booted app version $KAMAL_VERSION on $KAMAL_HOSTS..." diff --git a/.kamal/hooks/post-deploy.sample b/.kamal/hooks/post-deploy.sample new file mode 100755 index 000000000..fd364c2a7 --- /dev/null +++ b/.kamal/hooks/post-deploy.sample @@ -0,0 +1,14 @@ +#!/bin/sh + +# A sample post-deploy hook +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) +# KAMAL_RUNTIME + +echo "$KAMAL_PERFORMER deployed $KAMAL_VERSION to $KAMAL_DESTINATION in $KAMAL_RUNTIME seconds" diff --git a/.kamal/hooks/post-proxy-reboot.sample b/.kamal/hooks/post-proxy-reboot.sample new file mode 100755 index 000000000..1435a677f --- /dev/null +++ b/.kamal/hooks/post-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Rebooted kamal-proxy on $KAMAL_HOSTS" diff --git a/.kamal/hooks/pre-app-boot.sample b/.kamal/hooks/pre-app-boot.sample new file mode 100755 index 000000000..45f735504 --- /dev/null +++ b/.kamal/hooks/pre-app-boot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Booting app version $KAMAL_VERSION on $KAMAL_HOSTS..." diff --git a/.kamal/hooks/pre-build.sample b/.kamal/hooks/pre-build.sample new file mode 100755 index 000000000..c5a55678b --- /dev/null +++ b/.kamal/hooks/pre-build.sample @@ -0,0 +1,51 @@ +#!/bin/sh + +# A sample pre-build hook +# +# Checks: +# 1. We have a clean checkout +# 2. A remote is configured +# 3. The branch has been pushed to the remote +# 4. The version we are deploying matches the remote +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) + +if [ -n "$(git status --porcelain)" ]; then + echo "Git checkout is not clean, aborting..." >&2 + git status --porcelain >&2 + exit 1 +fi + +first_remote=$(git remote) + +if [ -z "$first_remote" ]; then + echo "No git remote set, aborting..." >&2 + exit 1 +fi + +current_branch=$(git branch --show-current) + +if [ -z "$current_branch" ]; then + echo "Not on a git branch, aborting..." >&2 + exit 1 +fi + +remote_head=$(git ls-remote $first_remote --tags $current_branch | cut -f1) + +if [ -z "$remote_head" ]; then + echo "Branch not pushed to remote, aborting..." >&2 + exit 1 +fi + +if [ "$KAMAL_VERSION" != "$remote_head" ]; then + echo "Version ($KAMAL_VERSION) does not match remote HEAD ($remote_head), aborting..." >&2 + exit 1 +fi + +exit 0 diff --git a/.kamal/hooks/pre-connect.sample b/.kamal/hooks/pre-connect.sample new file mode 100755 index 000000000..77744bdca --- /dev/null +++ b/.kamal/hooks/pre-connect.sample @@ -0,0 +1,47 @@ +#!/usr/bin/env ruby + +# A sample pre-connect check +# +# Warms DNS before connecting to hosts in parallel +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) +# KAMAL_RUNTIME + +hosts = ENV["KAMAL_HOSTS"].split(",") +results = nil +max = 3 + +elapsed = Benchmark.realtime do + results = hosts.map do |host| + Thread.new do + tries = 1 + + begin + Socket.getaddrinfo(host, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME) + rescue SocketError + if tries < max + puts "Retrying DNS warmup: #{host}" + tries += 1 + sleep rand + retry + else + puts "DNS warmup failed: #{host}" + host + end + end + + tries + end + end.map(&:value) +end + +retries = results.sum - hosts.size +nopes = results.count { |r| r == max } + +puts "Prewarmed %d DNS lookups in %.2f sec: %d retries, %d failures" % [ hosts.size, elapsed, retries, nopes ] diff --git a/.kamal/hooks/pre-deploy.sample b/.kamal/hooks/pre-deploy.sample new file mode 100755 index 000000000..05b3055b7 --- /dev/null +++ b/.kamal/hooks/pre-deploy.sample @@ -0,0 +1,122 @@ +#!/usr/bin/env ruby + +# A sample pre-deploy hook +# +# Checks the Github status of the build, waiting for a pending build to complete for up to 720 seconds. +# +# Fails unless the combined status is "success" +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_COMMAND +# KAMAL_SUBCOMMAND +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) + +# Only check the build status for production deployments +if ENV["KAMAL_COMMAND"] == "rollback" || ENV["KAMAL_DESTINATION"] != "production" + exit 0 +end + +require "bundler/inline" + +# true = install gems so this is fast on repeat invocations +gemfile(true, quiet: true) do + source "https://rubygems.org" + + gem "octokit" + gem "faraday-retry" +end + +MAX_ATTEMPTS = 72 +ATTEMPTS_GAP = 10 + +def exit_with_error(message) + $stderr.puts message + exit 1 +end + +class GithubStatusChecks + attr_reader :remote_url, :git_sha, :github_client, :combined_status + + def initialize + @remote_url = github_repo_from_remote_url + @git_sha = `git rev-parse HEAD`.strip + @github_client = Octokit::Client.new(access_token: ENV["GITHUB_TOKEN"]) + refresh! + end + + def refresh! + @combined_status = github_client.combined_status(remote_url, git_sha) + end + + def state + combined_status[:state] + end + + def first_status_url + first_status = combined_status[:statuses].find { |status| status[:state] == state } + first_status && first_status[:target_url] + end + + def complete_count + combined_status[:statuses].count { |status| status[:state] != "pending"} + end + + def total_count + combined_status[:statuses].count + end + + def current_status + if total_count > 0 + "Completed #{complete_count}/#{total_count} checks, see #{first_status_url} ..." + else + "Build not started..." + end + end + + private + def github_repo_from_remote_url + url = `git config --get remote.origin.url`.strip.delete_suffix(".git") + if url.start_with?("https://github.com/") + url.delete_prefix("https://github.com/") + elsif url.start_with?("git@github.com:") + url.delete_prefix("git@github.com:") + else + url + end + end +end + + +$stdout.sync = true + +begin + puts "Checking build status..." + + attempts = 0 + checks = GithubStatusChecks.new + + loop do + case checks.state + when "success" + puts "Checks passed, see #{checks.first_status_url}" + exit 0 + when "failure" + exit_with_error "Checks failed, see #{checks.first_status_url}" + when "pending" + attempts += 1 + end + + exit_with_error "Checks are still pending, gave up after #{MAX_ATTEMPTS * ATTEMPTS_GAP} seconds" if attempts == MAX_ATTEMPTS + + puts checks.current_status + sleep(ATTEMPTS_GAP) + checks.refresh! + end +rescue Octokit::NotFound + exit_with_error "Build status could not be found" +end diff --git a/.kamal/hooks/pre-proxy-reboot.sample b/.kamal/hooks/pre-proxy-reboot.sample new file mode 100755 index 000000000..061f8059e --- /dev/null +++ b/.kamal/hooks/pre-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Rebooting kamal-proxy on $KAMAL_HOSTS..." diff --git a/.kamal/secrets b/.kamal/secrets new file mode 100644 index 000000000..9a771a398 --- /dev/null +++ b/.kamal/secrets @@ -0,0 +1,17 @@ +# Secrets defined here are available for reference under registry/password, env/secret, builder/secrets, +# and accessories/*/env/secret in config/deploy.yml. All secrets should be pulled from either +# password manager, ENV, or a file. DO NOT ENTER RAW CREDENTIALS HERE! This file needs to be safe for git. + +# Example of extracting secrets from 1password (or another compatible pw manager) +# SECRETS=$(kamal secrets fetch --adapter 1password --account your-account --from Vault/Item KAMAL_REGISTRY_PASSWORD RAILS_MASTER_KEY) +# KAMAL_REGISTRY_PASSWORD=$(kamal secrets extract KAMAL_REGISTRY_PASSWORD ${SECRETS}) +# RAILS_MASTER_KEY=$(kamal secrets extract RAILS_MASTER_KEY ${SECRETS}) + +# Use a GITHUB_TOKEN if private repositories are needed for the image +# GITHUB_TOKEN=$(gh config get -h github.com oauth_token) + +# Grab the registry password from ENV +KAMAL_REGISTRY_PASSWORD=$KAMAL_REGISTRY_PASSWORD + +# Improve security by using a password manager. Never check config/master.key into git! +RAILS_MASTER_KEY=$(cat config/master.key) diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 000000000..f9d86d4a5 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,8 @@ +# Omakase Ruby styling for Rails +inherit_gem: { rubocop-rails-omakase: rubocop.yml } + +# Overwrite or add rules to create your own house style +# +# # Use `[a, [b, c]]` not `[ a, [ b, c ] ]` +# Layout/SpaceInsideArrayLiteralBrackets: +# Enabled: false diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 000000000..54978911c --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +ruby-3.4.5 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..8e8ef3fb0 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,72 @@ +# syntax=docker/dockerfile:1 +# check=error=true + +# This Dockerfile is designed for production, not development. Use with Kamal or build'n'run by hand: +# docker build -t fullstack_developer . +# docker run -d -p 80:80 -e RAILS_MASTER_KEY= --name fullstack_developer fullstack_developer + +# For a containerized dev environment, see Dev Containers: https://guides.rubyonrails.org/getting_started_with_devcontainer.html + +# Make sure RUBY_VERSION matches the Ruby version in .ruby-version +ARG RUBY_VERSION=3.4.5 +FROM docker.io/library/ruby:$RUBY_VERSION-slim AS base + +# Rails app lives here +WORKDIR /rails + +# Install base packages +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y curl libjemalloc2 libvips postgresql-client && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# Set production environment +ENV RAILS_ENV="production" \ + BUNDLE_DEPLOYMENT="1" \ + BUNDLE_PATH="/usr/local/bundle" \ + BUNDLE_WITHOUT="development" + +# Throw-away build stage to reduce size of final image +FROM base AS build + +# Install packages needed to build gems +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y build-essential git libpq-dev libyaml-dev pkg-config && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# Install application gems +COPY Gemfile Gemfile.lock ./ +RUN bundle install && \ + rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git && \ + bundle exec bootsnap precompile --gemfile + +# Copy application code +COPY . . + +# Precompile bootsnap code for faster boot times +RUN bundle exec bootsnap precompile app/ lib/ + +# Precompiling assets for production without requiring secret RAILS_MASTER_KEY +RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile + + + + +# Final stage for app image +FROM base + +# Copy built artifacts: gems, application +COPY --from=build "${BUNDLE_PATH}" "${BUNDLE_PATH}" +COPY --from=build /rails /rails + +# Run and own only the runtime files as a non-root user for security +RUN groupadd --system --gid 1000 rails && \ + useradd rails --uid 1000 --gid 1000 --create-home --shell /bin/bash && \ + chown -R rails:rails db log storage tmp +USER 1000:1000 + +# Entrypoint prepares the database. +ENTRYPOINT ["/rails/bin/docker-entrypoint"] + +# Start server via Thruster by default, this can be overwritten at runtime +EXPOSE 80 +CMD ["./bin/thrust", "./bin/rails", "server"] diff --git a/Gemfile b/Gemfile new file mode 100644 index 000000000..6bdb2375a --- /dev/null +++ b/Gemfile @@ -0,0 +1,69 @@ +source "https://rubygems.org" + +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem "rails", "~> 8.0.4" +# The modern asset pipeline for Rails [https://github.com/rails/propshaft] +gem "propshaft" +# Use postgresql as the database for Active Record +gem "pg", "~> 1.1" +# Use the Puma web server [https://github.com/puma/puma] +gem "puma", ">= 5.0" +# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails] +gem "importmap-rails" +# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev] +gem "turbo-rails" +# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev] +gem "stimulus-rails" +# Build JSON APIs with ease [https://github.com/rails/jbuilder] +gem "jbuilder" + +# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] +# gem "bcrypt", "~> 3.1.7" + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem "tzinfo-data", platforms: %i[ windows jruby ] + +# Use the database-backed adapters for Rails.cache, Active Job, and Action Cable +gem "solid_cache" +gem "solid_queue" +gem "solid_cable" + +# Reduces boot times through caching; required in config/boot.rb +gem "bootsnap", require: false + +# Deploy this application anywhere as a Docker container [https://kamal-deploy.org] +gem "kamal", require: false + +# Add HTTP asset caching/compression and X-Sendfile acceleration to Puma [https://github.com/basecamp/thruster/] +gem "thruster", require: false + +# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] +# gem "image_processing", "~> 1.2" + +group :development, :test do + # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem + gem "debug", platforms: %i[ mri windows ], require: "debug/prelude" + + # Static analysis for security vulnerabilities [https://brakemanscanner.org/] + gem "brakeman", require: false + + # Omakase Ruby styling [https://github.com/rails/rubocop-rails-omakase/] + gem "rubocop-rails-omakase", require: false +end + +group :development do + # Use console on exceptions pages [https://github.com/rails/web-console] + gem "web-console" +end + +group :test do + # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing] + gem "capybara" + gem "selenium-webdriver" +end + +gem "devise", "~> 4.9" +gem "pundit", "~> 2.5" +gem "sidekiq", "~> 8.0" +gem "roo", "~> 3.0" +gem "down", "~> 5.4" diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 000000000..0a85ddfc9 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,424 @@ +GEM + remote: https://rubygems.org/ + specs: + actioncable (8.0.4) + actionpack (= 8.0.4) + activesupport (= 8.0.4) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + zeitwerk (~> 2.6) + actionmailbox (8.0.4) + actionpack (= 8.0.4) + activejob (= 8.0.4) + activerecord (= 8.0.4) + activestorage (= 8.0.4) + activesupport (= 8.0.4) + mail (>= 2.8.0) + actionmailer (8.0.4) + actionpack (= 8.0.4) + actionview (= 8.0.4) + activejob (= 8.0.4) + activesupport (= 8.0.4) + mail (>= 2.8.0) + rails-dom-testing (~> 2.2) + actionpack (8.0.4) + actionview (= 8.0.4) + activesupport (= 8.0.4) + nokogiri (>= 1.8.5) + rack (>= 2.2.4) + rack-session (>= 1.0.1) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + useragent (~> 0.16) + actiontext (8.0.4) + actionpack (= 8.0.4) + activerecord (= 8.0.4) + activestorage (= 8.0.4) + activesupport (= 8.0.4) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (8.0.4) + activesupport (= 8.0.4) + builder (~> 3.1) + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + activejob (8.0.4) + activesupport (= 8.0.4) + globalid (>= 0.3.6) + activemodel (8.0.4) + activesupport (= 8.0.4) + activerecord (8.0.4) + activemodel (= 8.0.4) + activesupport (= 8.0.4) + timeout (>= 0.4.0) + activestorage (8.0.4) + actionpack (= 8.0.4) + activejob (= 8.0.4) + activerecord (= 8.0.4) + activesupport (= 8.0.4) + marcel (~> 1.0) + activesupport (8.0.4) + base64 + benchmark (>= 0.3) + bigdecimal + concurrent-ruby (~> 1.0, >= 1.3.1) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + logger (>= 1.4.2) + minitest (>= 5.1) + securerandom (>= 0.3) + tzinfo (~> 2.0, >= 2.0.5) + uri (>= 0.13.1) + addressable (2.8.7) + public_suffix (>= 2.0.2, < 7.0) + ast (2.4.3) + base64 (0.3.0) + bcrypt (3.1.20) + bcrypt_pbkdf (1.1.1) + benchmark (0.5.0) + bigdecimal (3.3.1) + bindex (0.8.1) + bootsnap (1.18.6) + msgpack (~> 1.2) + brakeman (7.1.0) + racc + builder (3.3.0) + capybara (3.40.0) + addressable + matrix + mini_mime (>= 0.1.3) + nokogiri (~> 1.11) + rack (>= 1.6.0) + rack-test (>= 0.6.3) + regexp_parser (>= 1.5, < 3.0) + xpath (~> 3.2) + concurrent-ruby (1.3.5) + connection_pool (2.5.4) + crass (1.0.6) + csv (3.3.5) + date (3.5.0) + debug (1.11.0) + irb (~> 1.10) + reline (>= 0.3.8) + devise (4.9.4) + bcrypt (~> 3.0) + orm_adapter (~> 0.1) + railties (>= 4.1.0) + responders + warden (~> 1.2.3) + dotenv (3.1.8) + down (5.4.2) + addressable (~> 2.8) + drb (2.2.3) + ed25519 (1.4.0) + erb (5.1.3) + erubi (1.13.1) + et-orbi (1.4.0) + tzinfo + fugit (1.12.1) + et-orbi (~> 1.4) + raabro (~> 1.4) + globalid (1.3.0) + activesupport (>= 6.1) + i18n (1.14.7) + concurrent-ruby (~> 1.0) + importmap-rails (2.2.2) + actionpack (>= 6.0.0) + activesupport (>= 6.0.0) + railties (>= 6.0.0) + io-console (0.8.1) + irb (1.15.3) + pp (>= 0.6.0) + rdoc (>= 4.0.0) + reline (>= 0.4.2) + jbuilder (2.14.1) + actionview (>= 7.0.0) + activesupport (>= 7.0.0) + json (2.15.2) + kamal (2.8.2) + activesupport (>= 7.0) + base64 (~> 0.2) + bcrypt_pbkdf (~> 1.0) + concurrent-ruby (~> 1.2) + dotenv (~> 3.1) + ed25519 (~> 1.4) + net-ssh (~> 7.3) + sshkit (>= 1.23.0, < 2.0) + thor (~> 1.3) + zeitwerk (>= 2.6.18, < 3.0) + language_server-protocol (3.17.0.5) + lint_roller (1.1.0) + logger (1.7.0) + loofah (2.24.1) + crass (~> 1.0.2) + nokogiri (>= 1.12.0) + mail (2.9.0) + logger + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.1.0) + matrix (0.4.3) + mini_mime (1.1.5) + minitest (5.26.0) + msgpack (1.8.0) + net-imap (0.5.12) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.2.2) + timeout + net-scp (4.1.0) + net-ssh (>= 2.6.5, < 8.0.0) + net-sftp (4.0.0) + net-ssh (>= 5.0.0, < 8.0.0) + net-smtp (0.5.1) + net-protocol + net-ssh (7.3.0) + nio4r (2.7.5) + nokogiri (1.18.10-aarch64-linux-gnu) + racc (~> 1.4) + nokogiri (1.18.10-aarch64-linux-musl) + racc (~> 1.4) + nokogiri (1.18.10-arm-linux-gnu) + racc (~> 1.4) + nokogiri (1.18.10-arm-linux-musl) + racc (~> 1.4) + nokogiri (1.18.10-x86_64-linux-gnu) + racc (~> 1.4) + nokogiri (1.18.10-x86_64-linux-musl) + racc (~> 1.4) + orm_adapter (0.5.0) + ostruct (0.6.3) + parallel (1.27.0) + parser (3.3.10.0) + ast (~> 2.4.1) + racc + pg (1.6.2) + pg (1.6.2-aarch64-linux) + pg (1.6.2-aarch64-linux-musl) + pg (1.6.2-x86_64-linux) + pg (1.6.2-x86_64-linux-musl) + pp (0.6.3) + prettyprint + prettyprint (0.2.0) + prism (1.6.0) + propshaft (1.3.1) + actionpack (>= 7.0.0) + activesupport (>= 7.0.0) + rack + psych (5.2.6) + date + stringio + public_suffix (6.0.2) + puma (7.1.0) + nio4r (~> 2.0) + pundit (2.5.2) + activesupport (>= 3.0.0) + raabro (1.4.0) + racc (1.8.1) + rack (3.2.4) + rack-session (2.1.1) + base64 (>= 0.1.0) + rack (>= 3.0.0) + rack-test (2.2.0) + rack (>= 1.3) + rackup (2.2.1) + rack (>= 3) + rails (8.0.4) + actioncable (= 8.0.4) + actionmailbox (= 8.0.4) + actionmailer (= 8.0.4) + actionpack (= 8.0.4) + actiontext (= 8.0.4) + actionview (= 8.0.4) + activejob (= 8.0.4) + activemodel (= 8.0.4) + activerecord (= 8.0.4) + activestorage (= 8.0.4) + activesupport (= 8.0.4) + bundler (>= 1.15.0) + railties (= 8.0.4) + rails-dom-testing (2.3.0) + activesupport (>= 5.0.0) + minitest + nokogiri (>= 1.6) + rails-html-sanitizer (1.6.2) + loofah (~> 2.21) + nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0) + railties (8.0.4) + actionpack (= 8.0.4) + activesupport (= 8.0.4) + irb (~> 1.13) + rackup (>= 1.0.0) + rake (>= 12.2) + thor (~> 1.0, >= 1.2.2) + tsort (>= 0.2) + zeitwerk (~> 2.6) + rainbow (3.1.1) + rake (13.3.1) + rdoc (6.15.1) + erb + psych (>= 4.0.0) + tsort + redis-client (0.26.1) + connection_pool + regexp_parser (2.11.3) + reline (0.6.2) + io-console (~> 0.5) + responders (3.2.0) + actionpack (>= 7.0) + railties (>= 7.0) + rexml (3.4.4) + roo (3.0.0) + base64 (~> 0.2) + csv (~> 3) + logger (~> 1) + nokogiri (~> 1) + rubyzip (>= 3.0.0, < 4.0.0) + rubocop (1.81.7) + json (~> 2.3) + language_server-protocol (~> 3.17.0.2) + lint_roller (~> 1.1.0) + parallel (~> 1.10) + parser (>= 3.3.0.2) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 2.9.3, < 3.0) + rubocop-ast (>= 1.47.1, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 4.0) + rubocop-ast (1.47.1) + parser (>= 3.3.7.2) + prism (~> 1.4) + rubocop-performance (1.26.1) + lint_roller (~> 1.1) + rubocop (>= 1.75.0, < 2.0) + rubocop-ast (>= 1.47.1, < 2.0) + rubocop-rails (2.33.4) + activesupport (>= 4.2.0) + lint_roller (~> 1.1) + rack (>= 1.1) + rubocop (>= 1.75.0, < 2.0) + rubocop-ast (>= 1.44.0, < 2.0) + rubocop-rails-omakase (1.1.0) + rubocop (>= 1.72) + rubocop-performance (>= 1.24) + rubocop-rails (>= 2.30) + ruby-progressbar (1.13.0) + rubyzip (3.2.2) + securerandom (0.4.1) + selenium-webdriver (4.38.0) + base64 (~> 0.2) + logger (~> 1.4) + rexml (~> 3.2, >= 3.2.5) + rubyzip (>= 1.2.2, < 4.0) + websocket (~> 1.0) + sidekiq (8.0.8) + connection_pool (>= 2.5.0) + json (>= 2.9.0) + logger (>= 1.6.2) + rack (>= 3.1.0) + redis-client (>= 0.23.2) + solid_cable (3.0.12) + actioncable (>= 7.2) + activejob (>= 7.2) + activerecord (>= 7.2) + railties (>= 7.2) + solid_cache (1.0.8) + activejob (>= 7.2) + activerecord (>= 7.2) + railties (>= 7.2) + solid_queue (1.2.4) + activejob (>= 7.1) + activerecord (>= 7.1) + concurrent-ruby (>= 1.3.1) + fugit (~> 1.11) + railties (>= 7.1) + thor (>= 1.3.1) + sshkit (1.24.0) + base64 + logger + net-scp (>= 1.1.2) + net-sftp (>= 2.1.2) + net-ssh (>= 2.8.0) + ostruct + stimulus-rails (1.3.4) + railties (>= 6.0.0) + stringio (3.1.7) + thor (1.4.0) + thruster (0.1.16) + thruster (0.1.16-aarch64-linux) + thruster (0.1.16-x86_64-linux) + timeout (0.4.4) + tsort (0.2.0) + turbo-rails (2.0.20) + actionpack (>= 7.1.0) + railties (>= 7.1.0) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + unicode-display_width (3.2.0) + unicode-emoji (~> 4.1) + unicode-emoji (4.1.0) + uri (1.1.0) + useragent (0.16.11) + warden (1.2.9) + rack (>= 2.0.9) + web-console (4.2.1) + actionview (>= 6.0.0) + activemodel (>= 6.0.0) + bindex (>= 0.4.0) + railties (>= 6.0.0) + websocket (1.2.11) + websocket-driver (0.8.0) + base64 + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + xpath (3.2.0) + nokogiri (~> 1.8) + zeitwerk (2.7.3) + +PLATFORMS + aarch64-linux + aarch64-linux-gnu + aarch64-linux-musl + arm-linux-gnu + arm-linux-musl + x86_64-linux + x86_64-linux-gnu + x86_64-linux-musl + +DEPENDENCIES + bootsnap + brakeman + capybara + debug + devise (~> 4.9) + down (~> 5.4) + importmap-rails + jbuilder + kamal + pg (~> 1.1) + propshaft + puma (>= 5.0) + pundit (~> 2.5) + rails (~> 8.0.4) + roo (~> 3.0) + rubocop-rails-omakase + selenium-webdriver + sidekiq (~> 8.0) + solid_cable + solid_cache + solid_queue + stimulus-rails + thruster + turbo-rails + tzinfo-data + web-console + +BUNDLED WITH + 2.6.9 diff --git a/Rakefile b/Rakefile new file mode 100644 index 000000000..9a5ea7383 --- /dev/null +++ b/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative "config/application" + +Rails.application.load_tasks diff --git a/app/assets/images/.keep b/app/assets/images/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/assets/stylesheets/application.css b/app/assets/stylesheets/application.css new file mode 100644 index 000000000..fe93333c0 --- /dev/null +++ b/app/assets/stylesheets/application.css @@ -0,0 +1,10 @@ +/* + * This is a manifest file that'll be compiled into application.css. + * + * With Propshaft, assets are served efficiently without preprocessing steps. You can still include + * application-wide styles in this file, but keep in mind that CSS precedence will follow the standard + * cascading order, meaning styles declared later in the document or manifest will override earlier ones, + * depending on specificity. + * + * Consider organizing styles into separate files for maintainability. + */ diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb new file mode 100644 index 000000000..0d95db22b --- /dev/null +++ b/app/controllers/application_controller.rb @@ -0,0 +1,4 @@ +class ApplicationController < ActionController::Base + # Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has. + allow_browser versions: :modern +end diff --git a/app/controllers/concerns/.keep b/app/controllers/concerns/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb new file mode 100644 index 000000000..de6be7945 --- /dev/null +++ b/app/helpers/application_helper.rb @@ -0,0 +1,2 @@ +module ApplicationHelper +end diff --git a/app/javascript/application.js b/app/javascript/application.js new file mode 100644 index 000000000..0d7b49404 --- /dev/null +++ b/app/javascript/application.js @@ -0,0 +1,3 @@ +// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails +import "@hotwired/turbo-rails" +import "controllers" diff --git a/app/javascript/controllers/application.js b/app/javascript/controllers/application.js new file mode 100644 index 000000000..1213e85c7 --- /dev/null +++ b/app/javascript/controllers/application.js @@ -0,0 +1,9 @@ +import { Application } from "@hotwired/stimulus" + +const application = Application.start() + +// Configure Stimulus development experience +application.debug = false +window.Stimulus = application + +export { application } diff --git a/app/javascript/controllers/hello_controller.js b/app/javascript/controllers/hello_controller.js new file mode 100644 index 000000000..5975c0789 --- /dev/null +++ b/app/javascript/controllers/hello_controller.js @@ -0,0 +1,7 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + connect() { + this.element.textContent = "Hello World!" + } +} diff --git a/app/javascript/controllers/index.js b/app/javascript/controllers/index.js new file mode 100644 index 000000000..1156bf836 --- /dev/null +++ b/app/javascript/controllers/index.js @@ -0,0 +1,4 @@ +// Import and register all your controllers from the importmap via controllers/**/*_controller +import { application } from "controllers/application" +import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading" +eagerLoadControllersFrom("controllers", application) diff --git a/app/jobs/application_job.rb b/app/jobs/application_job.rb new file mode 100644 index 000000000..d394c3d10 --- /dev/null +++ b/app/jobs/application_job.rb @@ -0,0 +1,7 @@ +class ApplicationJob < ActiveJob::Base + # Automatically retry jobs that encountered a deadlock + # retry_on ActiveRecord::Deadlocked + + # Most jobs are safe to ignore if the underlying records are no longer available + # discard_on ActiveJob::DeserializationError +end diff --git a/app/mailers/application_mailer.rb b/app/mailers/application_mailer.rb new file mode 100644 index 000000000..3c34c8148 --- /dev/null +++ b/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: "from@example.com" + layout "mailer" +end diff --git a/app/models/application_record.rb b/app/models/application_record.rb new file mode 100644 index 000000000..b63caeb8a --- /dev/null +++ b/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end diff --git a/app/models/concerns/.keep b/app/models/concerns/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 000000000..47567994e --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,6 @@ +class User < ApplicationRecord + # Include default devise modules. Others available are: + # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable + devise :database_authenticatable, :registerable, + :recoverable, :rememberable, :validatable +end diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb new file mode 100644 index 000000000..88e6744a5 --- /dev/null +++ b/app/views/layouts/application.html.erb @@ -0,0 +1,28 @@ + + + + <%= content_for(:title) || "Fullstack Developer" %> + + + + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= yield :head %> + + <%# Enable PWA manifest for installable apps (make sure to enable in config/routes.rb too!) %> + <%#= tag.link rel: "manifest", href: pwa_manifest_path(format: :json) %> + + + + + + <%# Includes all stylesheet files in app/assets/stylesheets %> + <%= stylesheet_link_tag :app, "data-turbo-track": "reload" %> + <%= javascript_importmap_tags %> + + + + <%= yield %> + + diff --git a/app/views/layouts/mailer.html.erb b/app/views/layouts/mailer.html.erb new file mode 100644 index 000000000..3aac9002e --- /dev/null +++ b/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/app/views/layouts/mailer.text.erb b/app/views/layouts/mailer.text.erb new file mode 100644 index 000000000..37f0bddbd --- /dev/null +++ b/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/app/views/pwa/manifest.json.erb b/app/views/pwa/manifest.json.erb new file mode 100644 index 000000000..13a7b4eff --- /dev/null +++ b/app/views/pwa/manifest.json.erb @@ -0,0 +1,22 @@ +{ + "name": "FullstackDeveloper", + "icons": [ + { + "src": "/icon.png", + "type": "image/png", + "sizes": "512x512" + }, + { + "src": "/icon.png", + "type": "image/png", + "sizes": "512x512", + "purpose": "maskable" + } + ], + "start_url": "/", + "display": "standalone", + "scope": "/", + "description": "FullstackDeveloper.", + "theme_color": "red", + "background_color": "red" +} diff --git a/app/views/pwa/service-worker.js b/app/views/pwa/service-worker.js new file mode 100644 index 000000000..b3a13fb7b --- /dev/null +++ b/app/views/pwa/service-worker.js @@ -0,0 +1,26 @@ +// Add a service worker for processing Web Push notifications: +// +// self.addEventListener("push", async (event) => { +// const { title, options } = await event.data.json() +// event.waitUntil(self.registration.showNotification(title, options)) +// }) +// +// self.addEventListener("notificationclick", function(event) { +// event.notification.close() +// event.waitUntil( +// clients.matchAll({ type: "window" }).then((clientList) => { +// for (let i = 0; i < clientList.length; i++) { +// let client = clientList[i] +// let clientPath = (new URL(client.url)).pathname +// +// if (clientPath == event.notification.data.path && "focus" in client) { +// return client.focus() +// } +// } +// +// if (clients.openWindow) { +// return clients.openWindow(event.notification.data.path) +// } +// }) +// ) +// }) diff --git a/bin/brakeman b/bin/brakeman new file mode 100755 index 000000000..ace1c9ba0 --- /dev/null +++ b/bin/brakeman @@ -0,0 +1,7 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +ARGV.unshift("--ensure-latest") + +load Gem.bin_path("brakeman", "brakeman") diff --git a/bin/bundle b/bin/bundle new file mode 100755 index 000000000..50da5fdf9 --- /dev/null +++ b/bin/bundle @@ -0,0 +1,109 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'bundle' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require "rubygems" + +m = Module.new do + module_function + + def invoked_as_script? + File.expand_path($0) == File.expand_path(__FILE__) + end + + def env_var_version + ENV["BUNDLER_VERSION"] + end + + def cli_arg_version + return unless invoked_as_script? # don't want to hijack other binstubs + return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` + bundler_version = nil + update_index = nil + ARGV.each_with_index do |a, i| + if update_index && update_index.succ == i && a.match?(Gem::Version::ANCHORED_VERSION_PATTERN) + bundler_version = a + end + next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ + bundler_version = $1 + update_index = i + end + bundler_version + end + + def gemfile + gemfile = ENV["BUNDLE_GEMFILE"] + return gemfile if gemfile && !gemfile.empty? + + File.expand_path("../Gemfile", __dir__) + end + + def lockfile + lockfile = + case File.basename(gemfile) + when "gems.rb" then gemfile.sub(/\.rb$/, ".locked") + else "#{gemfile}.lock" + end + File.expand_path(lockfile) + end + + def lockfile_version + return unless File.file?(lockfile) + lockfile_contents = File.read(lockfile) + return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ + Regexp.last_match(1) + end + + def bundler_requirement + @bundler_requirement ||= + env_var_version || + cli_arg_version || + bundler_requirement_for(lockfile_version) + end + + def bundler_requirement_for(version) + return "#{Gem::Requirement.default}.a" unless version + + bundler_gem_version = Gem::Version.new(version) + + bundler_gem_version.approximate_recommendation + end + + def load_bundler! + ENV["BUNDLE_GEMFILE"] ||= gemfile + + activate_bundler + end + + def activate_bundler + gem_error = activation_error_handling do + gem "bundler", bundler_requirement + end + return if gem_error.nil? + require_error = activation_error_handling do + require "bundler/version" + end + return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) + warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" + exit 42 + end + + def activation_error_handling + yield + nil + rescue StandardError, LoadError => e + e + end +end + +m.load_bundler! + +if m.invoked_as_script? + load Gem.bin_path("bundler", "bundle") +end diff --git a/bin/dev b/bin/dev new file mode 100755 index 000000000..5f91c2054 --- /dev/null +++ b/bin/dev @@ -0,0 +1,2 @@ +#!/usr/bin/env ruby +exec "./bin/rails", "server", *ARGV diff --git a/bin/docker-entrypoint b/bin/docker-entrypoint new file mode 100755 index 000000000..57567d69b --- /dev/null +++ b/bin/docker-entrypoint @@ -0,0 +1,14 @@ +#!/bin/bash -e + +# Enable jemalloc for reduced memory usage and latency. +if [ -z "${LD_PRELOAD+x}" ]; then + LD_PRELOAD=$(find /usr/lib -name libjemalloc.so.2 -print -quit) + export LD_PRELOAD +fi + +# If running the rails server then create or migrate existing database +if [ "${@: -2:1}" == "./bin/rails" ] && [ "${@: -1:1}" == "server" ]; then + ./bin/rails db:prepare +fi + +exec "${@}" diff --git a/bin/importmap b/bin/importmap new file mode 100755 index 000000000..36502ab16 --- /dev/null +++ b/bin/importmap @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby + +require_relative "../config/application" +require "importmap/commands" diff --git a/bin/jobs b/bin/jobs new file mode 100755 index 000000000..dcf59f309 --- /dev/null +++ b/bin/jobs @@ -0,0 +1,6 @@ +#!/usr/bin/env ruby + +require_relative "../config/environment" +require "solid_queue/cli" + +SolidQueue::Cli.start(ARGV) diff --git a/bin/kamal b/bin/kamal new file mode 100755 index 000000000..cbe59b95e --- /dev/null +++ b/bin/kamal @@ -0,0 +1,27 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'kamal' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +bundle_binstub = File.expand_path("bundle", __dir__) + +if File.file?(bundle_binstub) + if File.read(bundle_binstub, 300).include?("This file was generated by Bundler") + load(bundle_binstub) + else + abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. +Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") + end +end + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("kamal", "kamal") diff --git a/bin/rails b/bin/rails new file mode 100755 index 000000000..efc037749 --- /dev/null +++ b/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path("../config/application", __dir__) +require_relative "../config/boot" +require "rails/commands" diff --git a/bin/rake b/bin/rake new file mode 100755 index 000000000..4fbf10b96 --- /dev/null +++ b/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "rake" +Rake.application.run diff --git a/bin/rubocop b/bin/rubocop new file mode 100755 index 000000000..40330c0ff --- /dev/null +++ b/bin/rubocop @@ -0,0 +1,8 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +# explicit rubocop config increases performance slightly while avoiding config confusion. +ARGV.unshift("--config", File.expand_path("../.rubocop.yml", __dir__)) + +load Gem.bin_path("rubocop", "rubocop") diff --git a/bin/setup b/bin/setup new file mode 100755 index 000000000..be3db3c0d --- /dev/null +++ b/bin/setup @@ -0,0 +1,34 @@ +#!/usr/bin/env ruby +require "fileutils" + +APP_ROOT = File.expand_path("..", __dir__) + +def system!(*args) + system(*args, exception: true) +end + +FileUtils.chdir APP_ROOT do + # This script is a way to set up or update your development environment automatically. + # This script is idempotent, so that you can run it at any time and get an expectable outcome. + # Add necessary setup steps to this file. + + puts "== Installing dependencies ==" + system("bundle check") || system!("bundle install") + + # puts "\n== Copying sample files ==" + # unless File.exist?("config/database.yml") + # FileUtils.cp "config/database.yml.sample", "config/database.yml" + # end + + puts "\n== Preparing database ==" + system! "bin/rails db:prepare" + + puts "\n== Removing old logs and tempfiles ==" + system! "bin/rails log:clear tmp:clear" + + unless ARGV.include?("--skip-server") + puts "\n== Starting development server ==" + STDOUT.flush # flush the output before exec(2) so that it displays + exec "bin/dev" + end +end diff --git a/bin/thrust b/bin/thrust new file mode 100755 index 000000000..36bde2d83 --- /dev/null +++ b/bin/thrust @@ -0,0 +1,5 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("thruster", "thrust") diff --git a/config.ru b/config.ru new file mode 100644 index 000000000..4a3c09a68 --- /dev/null +++ b/config.ru @@ -0,0 +1,6 @@ +# This file is used by Rack-based servers to start the application. + +require_relative "config/environment" + +run Rails.application +Rails.application.load_server diff --git a/config/application.rb b/config/application.rb new file mode 100644 index 000000000..554285b9d --- /dev/null +++ b/config/application.rb @@ -0,0 +1,27 @@ +require_relative "boot" + +require "rails/all" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module FullstackDeveloper + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 8.0 + + # Please, add to the `ignore` list any other `lib` subdirectories that do + # not contain `.rb` files, or that should not be reloaded or eager loaded. + # Common ones are `templates`, `generators`, or `middleware`, for example. + config.autoload_lib(ignore: %w[assets tasks]) + + # Configuration for the application, engines, and railties goes here. + # + # These settings can be overridden in specific environments using the files + # in config/environments, which are processed later. + # + # config.time_zone = "Central Time (US & Canada)" + # config.eager_load_paths << Rails.root.join("extras") + end +end diff --git a/config/boot.rb b/config/boot.rb new file mode 100644 index 000000000..988a5ddc4 --- /dev/null +++ b/config/boot.rb @@ -0,0 +1,4 @@ +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +require "bundler/setup" # Set up gems listed in the Gemfile. +require "bootsnap/setup" # Speed up boot time by caching expensive operations. diff --git a/config/cable.yml b/config/cable.yml new file mode 100644 index 000000000..b9adc5aa3 --- /dev/null +++ b/config/cable.yml @@ -0,0 +1,17 @@ +# Async adapter only works within the same process, so for manually triggering cable updates from a console, +# and seeing results in the browser, you must do so from the web console (running inside the dev process), +# not a terminal started via bin/rails console! Add "console" to any action or any ERB template view +# to make the web console appear. +development: + adapter: async + +test: + adapter: test + +production: + adapter: solid_cable + connects_to: + database: + writing: cable + polling_interval: 0.1.seconds + message_retention: 1.day diff --git a/config/cache.yml b/config/cache.yml new file mode 100644 index 000000000..19d490843 --- /dev/null +++ b/config/cache.yml @@ -0,0 +1,16 @@ +default: &default + store_options: + # Cap age of oldest cache entry to fulfill retention policies + # max_age: <%= 60.days.to_i %> + max_size: <%= 256.megabytes %> + namespace: <%= Rails.env %> + +development: + <<: *default + +test: + <<: *default + +production: + database: cache + <<: *default diff --git a/config/credentials.yml.enc b/config/credentials.yml.enc new file mode 100644 index 000000000..2e940e522 --- /dev/null +++ b/config/credentials.yml.enc @@ -0,0 +1 @@ +jWbb+LNZZpdYNFTMidGKz9HYv+qBqstYNEHHKtestxPTWl66rEPR3nPi+GDcgI6/cWZFRwDehW8qjhkGL+FxocMwv3YWTB9INhcMEm1+NaKRmJHcQHV61P1FLqVbDQerRroIahKJ3CMQ1GdxRVjv1hNCfHDejo9nP7RNTYMWJxQPT4dum3mnIn8WzEqxxVMuP5ctYcMPXjcfyOInm5wo0JF7trr32fEt7MK9SiG9MvsNU/L4eEmV6vUQ3Ph0f8+GnEOKgLxMGoIEvmNZWdtcmN4T6MDGpTrIZ8aOlzfGfgDuxjF4nND3A66UwndWHmJvDLBes9W8NMjU5f+nmXki4C7ea0aT6kBLU2bWSpZcq69NMrHos8zHgJcDIhC1SetpZZUngjE6ZJzbNOnmIMmY22LTO3Ksl0dPQrR+EitxoyGZOr+pXpCzanoBjkVyHMYUBmnSrzEGpzEm5wANfdlFzQgj8g9YNRnSK43mCUfukdGgmg9NpXuECEwI--jJwOC5o9upVJdjeX--08UDtTpFxpOmcHnFd173dQ== \ No newline at end of file diff --git a/config/database.yml b/config/database.yml new file mode 100644 index 000000000..7e092b028 --- /dev/null +++ b/config/database.yml @@ -0,0 +1,98 @@ +# PostgreSQL. Versions 9.3 and up are supported. +# +# Install the pg driver: +# gem install pg +# On macOS with Homebrew: +# gem install pg -- --with-pg-config=/usr/local/bin/pg_config +# On Windows: +# gem install pg +# Choose the win32 build. +# Install PostgreSQL and put its /bin directory on your path. +# +# Configure Using Gemfile +# gem "pg" +# +default: &default + adapter: postgresql + encoding: unicode + # For details on connection pooling, see Rails configuration guide + # https://guides.rubyonrails.org/configuring.html#database-pooling + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + + +development: + <<: *default + database: fullstack_developer_development + + # The specified database role being used to connect to PostgreSQL. + # To create additional roles in PostgreSQL see `$ createuser --help`. + # When left blank, PostgreSQL will use the default role. This is + # the same name as the operating system user running Rails. + #username: fullstack_developer + + # The password associated with the PostgreSQL role (username). + #password: + + # Connect on a TCP socket. Omitted by default since the client uses a + # domain socket that doesn't need configuration. Windows does not have + # domain sockets, so uncomment these lines. + #host: localhost + + # The TCP port the server listens on. Defaults to 5432. + # If your server runs on a different port number, change accordingly. + #port: 5432 + + # Schema search path. The server defaults to $user,public + #schema_search_path: myapp,sharedapp,public + + # Minimum log levels, in increasing order: + # debug5, debug4, debug3, debug2, debug1, + # log, notice, warning, error, fatal, and panic + # Defaults to warning. + #min_messages: notice + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: fullstack_developer_test + +# As with config/credentials.yml, you never want to store sensitive information, +# like your database password, in your source code. If your source code is +# ever seen by anyone, they now have access to your database. +# +# Instead, provide the password or a full connection URL as an environment +# variable when you boot the app. For example: +# +# DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" +# +# If the connection URL is provided in the special DATABASE_URL environment +# variable, Rails will automatically merge its configuration values on top of +# the values provided in this file. Alternatively, you can specify a connection +# URL environment variable explicitly: +# +# production: +# url: <%= ENV["MY_APP_DATABASE_URL"] %> +# +# Read https://guides.rubyonrails.org/configuring.html#configuring-a-database +# for a full overview on how database connection configuration can be specified. +# +production: + primary: &primary_production + <<: *default + database: fullstack_developer_production + username: fullstack_developer + password: <%= ENV["FULLSTACK_DEVELOPER_DATABASE_PASSWORD"] %> + cache: + <<: *primary_production + database: fullstack_developer_production_cache + migrations_paths: db/cache_migrate + queue: + <<: *primary_production + database: fullstack_developer_production_queue + migrations_paths: db/queue_migrate + cable: + <<: *primary_production + database: fullstack_developer_production_cable + migrations_paths: db/cable_migrate diff --git a/config/deploy.yml b/config/deploy.yml new file mode 100644 index 000000000..5371ed121 --- /dev/null +++ b/config/deploy.yml @@ -0,0 +1,116 @@ +# Name of your application. Used to uniquely configure containers. +service: fullstack_developer + +# Name of the container image. +image: your-user/fullstack_developer + +# Deploy to these servers. +servers: + web: + - 192.168.0.1 + # job: + # hosts: + # - 192.168.0.1 + # cmd: bin/jobs + +# Enable SSL auto certification via Let's Encrypt and allow for multiple apps on a single web server. +# Remove this section when using multiple web servers and ensure you terminate SSL at your load balancer. +# +# Note: If using Cloudflare, set encryption mode in SSL/TLS setting to "Full" to enable CF-to-app encryption. +proxy: + ssl: true + host: app.example.com + +# Credentials for your image host. +registry: + # Specify the registry server, if you're not using Docker Hub + # server: registry.digitalocean.com / ghcr.io / ... + username: your-user + + # Always use an access token rather than real password when possible. + password: + - KAMAL_REGISTRY_PASSWORD + +# Inject ENV variables into containers (secrets come from .kamal/secrets). +env: + secret: + - RAILS_MASTER_KEY + clear: + # Run the Solid Queue Supervisor inside the web server's Puma process to do jobs. + # When you start using multiple servers, you should split out job processing to a dedicated machine. + SOLID_QUEUE_IN_PUMA: true + + # Set number of processes dedicated to Solid Queue (default: 1) + # JOB_CONCURRENCY: 3 + + # Set number of cores available to the application on each server (default: 1). + # WEB_CONCURRENCY: 2 + + # Match this to any external database server to configure Active Record correctly + # Use fullstack_developer-db for a db accessory server on same machine via local kamal docker network. + # DB_HOST: 192.168.0.2 + + # Log everything from Rails + # RAILS_LOG_LEVEL: debug + +# Aliases are triggered with "bin/kamal ". You can overwrite arguments on invocation: +# "bin/kamal logs -r job" will tail logs from the first server in the job section. +aliases: + console: app exec --interactive --reuse "bin/rails console" + shell: app exec --interactive --reuse "bash" + logs: app logs -f + dbc: app exec --interactive --reuse "bin/rails dbconsole" + + +# Use a persistent storage volume for sqlite database files and local Active Storage files. +# Recommended to change this to a mounted volume path that is backed up off server. +volumes: + - "fullstack_developer_storage:/rails/storage" + + +# Bridge fingerprinted assets, like JS and CSS, between versions to avoid +# hitting 404 on in-flight requests. Combines all files from new and old +# version inside the asset_path. +asset_path: /rails/public/assets + +# Configure the image builder. +builder: + arch: amd64 + + # # Build image via remote server (useful for faster amd64 builds on arm64 computers) + # remote: ssh://docker@docker-builder-server + # + # # Pass arguments and secrets to the Docker build process + # args: + # RUBY_VERSION: ruby-3.4.5 + # secrets: + # - GITHUB_TOKEN + # - RAILS_MASTER_KEY + +# Use a different ssh user than root +# ssh: +# user: app + +# Use accessory services (secrets come from .kamal/secrets). +# accessories: +# db: +# image: mysql:8.0 +# host: 192.168.0.2 +# # Change to 3306 to expose port to the world instead of just local network. +# port: "127.0.0.1:3306:3306" +# env: +# clear: +# MYSQL_ROOT_HOST: '%' +# secret: +# - MYSQL_ROOT_PASSWORD +# files: +# - config/mysql/production.cnf:/etc/mysql/my.cnf +# - db/production.sql:/docker-entrypoint-initdb.d/setup.sql +# directories: +# - data:/var/lib/mysql +# redis: +# image: redis:7.0 +# host: 192.168.0.2 +# port: 6379 +# directories: +# - data:/data diff --git a/config/environment.rb b/config/environment.rb new file mode 100644 index 000000000..cac531577 --- /dev/null +++ b/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative "application" + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/config/environments/development.rb b/config/environments/development.rb new file mode 100644 index 000000000..4cc21c4eb --- /dev/null +++ b/config/environments/development.rb @@ -0,0 +1,72 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Make code changes take effect immediately without server restart. + config.enable_reloading = true + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable server timing. + config.server_timing = true + + # Enable/disable Action Controller caching. By default Action Controller caching is disabled. + # Run rails dev:cache to toggle Action Controller caching. + if Rails.root.join("tmp/caching-dev.txt").exist? + config.action_controller.perform_caching = true + config.action_controller.enable_fragment_cache_logging = true + config.public_file_server.headers = { "cache-control" => "public, max-age=#{2.days.to_i}" } + else + config.action_controller.perform_caching = false + end + + # Change to :null_store to avoid any caching. + config.cache_store = :memory_store + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + # Make template changes take effect immediately. + config.action_mailer.perform_caching = false + + # Set localhost to be used by links generated in mailer templates. + config.action_mailer.default_url_options = { host: "localhost", port: 3000 } + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Highlight code that triggered database queries in logs. + config.active_record.verbose_query_logs = true + + # Append comments with runtime information tags to SQL queries in logs. + config.active_record.query_log_tags_enabled = true + + # Highlight code that enqueued background job in logs. + config.active_job.verbose_enqueue_logs = true + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + config.action_view.annotate_rendered_view_with_filenames = true + + # Uncomment if you wish to allow Action Cable access from any origin. + # config.action_cable.disable_request_forgery_protection = true + + # Raise error when a before_action's only/except options reference missing actions. + config.action_controller.raise_on_missing_callback_actions = true + + # Apply autocorrection by RuboCop to files generated by `bin/rails generate`. + # config.generators.apply_rubocop_autocorrect_after_generate! +end diff --git a/config/environments/production.rb b/config/environments/production.rb new file mode 100644 index 000000000..bdcd01d1b --- /dev/null +++ b/config/environments/production.rb @@ -0,0 +1,90 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.enable_reloading = false + + # Eager load code on boot for better performance and memory savings (ignored by Rake tasks). + config.eager_load = true + + # Full error reports are disabled. + config.consider_all_requests_local = false + + # Turn on fragment caching in view templates. + config.action_controller.perform_caching = true + + # Cache assets for far-future expiry since they are all digest stamped. + config.public_file_server.headers = { "cache-control" => "public, max-age=#{1.year.to_i}" } + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = "http://assets.example.com" + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Assume all access to the app is happening through a SSL-terminating reverse proxy. + config.assume_ssl = true + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + config.force_ssl = true + + # Skip http-to-https redirect for the default health check endpoint. + # config.ssl_options = { redirect: { exclude: ->(request) { request.path == "/up" } } } + + # Log to STDOUT with the current request id as a default log tag. + config.log_tags = [ :request_id ] + config.logger = ActiveSupport::TaggedLogging.logger(STDOUT) + + # Change to "debug" to log everything (including potentially personally-identifiable information!) + config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") + + # Prevent health checks from clogging up the logs. + config.silence_healthcheck_path = "/up" + + # Don't log any deprecations. + config.active_support.report_deprecations = false + + # Replace the default in-process memory cache store with a durable alternative. + config.cache_store = :solid_cache_store + + # Replace the default in-process and non-durable queuing backend for Active Job. + config.active_job.queue_adapter = :solid_queue + config.solid_queue.connects_to = { database: { writing: :queue } } + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Set host to be used by links generated in mailer templates. + config.action_mailer.default_url_options = { host: "example.com" } + + # Specify outgoing SMTP server. Remember to add smtp/* credentials via rails credentials:edit. + # config.action_mailer.smtp_settings = { + # user_name: Rails.application.credentials.dig(:smtp, :user_name), + # password: Rails.application.credentials.dig(:smtp, :password), + # address: "smtp.example.com", + # port: 587, + # authentication: :plain + # } + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false + + # Only use :id for inspections in production. + config.active_record.attributes_for_inspect = [ :id ] + + # Enable DNS rebinding protection and other `Host` header attacks. + # config.hosts = [ + # "example.com", # Allow requests from example.com + # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` + # ] + # + # Skip DNS rebinding protection for the default health check endpoint. + # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } +end diff --git a/config/environments/test.rb b/config/environments/test.rb new file mode 100644 index 000000000..c2095b117 --- /dev/null +++ b/config/environments/test.rb @@ -0,0 +1,53 @@ +# The test environment is used exclusively to run your application's +# test suite. You never need to work with it otherwise. Remember that +# your test database is "scratch space" for the test suite and is wiped +# and recreated between test runs. Don't rely on the data there! + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # While tests run files are not watched, reloading is not necessary. + config.enable_reloading = false + + # Eager loading loads your entire application. When running a single test locally, + # this is usually not necessary, and can slow down your test suite. However, it's + # recommended that you enable it in continuous integration systems to ensure eager + # loading is working properly before deploying your code. + config.eager_load = ENV["CI"].present? + + # Configure public file server for tests with cache-control for performance. + config.public_file_server.headers = { "cache-control" => "public, max-age=3600" } + + # Show full error reports. + config.consider_all_requests_local = true + config.cache_store = :null_store + + # Render exception templates for rescuable exceptions and raise for other exceptions. + config.action_dispatch.show_exceptions = :rescuable + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Store uploaded files on the local file system in a temporary directory. + config.active_storage.service = :test + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Set host to be used by links generated in mailer templates. + config.action_mailer.default_url_options = { host: "example.com" } + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true + + # Raise error when a before_action's only/except options reference missing actions. + config.action_controller.raise_on_missing_callback_actions = true +end diff --git a/config/importmap.rb b/config/importmap.rb new file mode 100644 index 000000000..909dfc542 --- /dev/null +++ b/config/importmap.rb @@ -0,0 +1,7 @@ +# Pin npm packages by running ./bin/importmap + +pin "application" +pin "@hotwired/turbo-rails", to: "turbo.min.js" +pin "@hotwired/stimulus", to: "stimulus.min.js" +pin "@hotwired/stimulus-loading", to: "stimulus-loading.js" +pin_all_from "app/javascript/controllers", under: "controllers" diff --git a/config/initializers/assets.rb b/config/initializers/assets.rb new file mode 100644 index 000000000..487324424 --- /dev/null +++ b/config/initializers/assets.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# Version of your assets, change this if you want to expire all your assets. +Rails.application.config.assets.version = "1.0" + +# Add additional assets to the asset load path. +# Rails.application.config.assets.paths << Emoji.images_path diff --git a/config/initializers/content_security_policy.rb b/config/initializers/content_security_policy.rb new file mode 100644 index 000000000..b3076b38f --- /dev/null +++ b/config/initializers/content_security_policy.rb @@ -0,0 +1,25 @@ +# Be sure to restart your server when you modify this file. + +# Define an application-wide content security policy. +# See the Securing Rails Applications Guide for more information: +# https://guides.rubyonrails.org/security.html#content-security-policy-header + +# Rails.application.configure do +# config.content_security_policy do |policy| +# policy.default_src :self, :https +# policy.font_src :self, :https, :data +# policy.img_src :self, :https, :data +# policy.object_src :none +# policy.script_src :self, :https +# policy.style_src :self, :https +# # Specify URI for violation reports +# # policy.report_uri "/csp-violation-report-endpoint" +# end +# +# # Generate session nonces for permitted importmap, inline scripts, and inline styles. +# config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } +# config.content_security_policy_nonce_directives = %w(script-src style-src) +# +# # Report violations without enforcing the policy. +# # config.content_security_policy_report_only = true +# end diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb new file mode 100644 index 000000000..a1f84028a --- /dev/null +++ b/config/initializers/devise.rb @@ -0,0 +1,313 @@ +# frozen_string_literal: true + +# Assuming you have not yet modified this file, each configuration option below +# is set to its default value. Note that some are commented out while others +# are not: uncommented lines are intended to protect your configuration from +# breaking changes in upgrades (i.e., in the event that future versions of +# Devise change the default values for those options). +# +# Use this hook to configure devise mailer, warden hooks and so forth. +# Many of these configuration options can be set straight in your model. +Devise.setup do |config| + # The secret key used by Devise. Devise uses this key to generate + # random tokens. Changing this key will render invalid all existing + # confirmation, reset password and unlock tokens in the database. + # Devise will use the `secret_key_base` as its `secret_key` + # by default. You can change it below and use your own secret key. + # config.secret_key = '774c02bf9e9cf7488783067e5dde8b21e2af2b24872d7cb3cb70c531721f0eb9f4ee61b226ab7844099ec4ceec569fc7b22ebdb09ca7831dbe0ea61b2dae480b' + + # ==> Controller configuration + # Configure the parent class to the devise controllers. + # config.parent_controller = 'DeviseController' + + # ==> Mailer Configuration + # Configure the e-mail address which will be shown in Devise::Mailer, + # note that it will be overwritten if you use your own mailer class + # with default "from" parameter. + config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' + + # Configure the class responsible to send e-mails. + # config.mailer = 'Devise::Mailer' + + # Configure the parent class responsible to send e-mails. + # config.parent_mailer = 'ActionMailer::Base' + + # ==> ORM configuration + # Load and configure the ORM. Supports :active_record (default) and + # :mongoid (bson_ext recommended) by default. Other ORMs may be + # available as additional gems. + require 'devise/orm/active_record' + + # ==> Configuration for any authentication mechanism + # Configure which keys are used when authenticating a user. The default is + # just :email. You can configure it to use [:username, :subdomain], so for + # authenticating a user, both parameters are required. Remember that those + # parameters are used only when authenticating and not when retrieving from + # session. If you need permissions, you should implement that in a before filter. + # You can also supply a hash where the value is a boolean determining whether + # or not authentication should be aborted when the value is not present. + # config.authentication_keys = [:email] + + # Configure parameters from the request object used for authentication. Each entry + # given should be a request method and it will automatically be passed to the + # find_for_authentication method and considered in your model lookup. For instance, + # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. + # The same considerations mentioned for authentication_keys also apply to request_keys. + # config.request_keys = [] + + # Configure which authentication keys should be case-insensitive. + # These keys will be downcased upon creating or modifying a user and when used + # to authenticate or find a user. Default is :email. + config.case_insensitive_keys = [:email] + + # Configure which authentication keys should have whitespace stripped. + # These keys will have whitespace before and after removed upon creating or + # modifying a user and when used to authenticate or find a user. Default is :email. + config.strip_whitespace_keys = [:email] + + # Tell if authentication through request.params is enabled. True by default. + # It can be set to an array that will enable params authentication only for the + # given strategies, for example, `config.params_authenticatable = [:database]` will + # enable it only for database (email + password) authentication. + # config.params_authenticatable = true + + # Tell if authentication through HTTP Auth is enabled. False by default. + # It can be set to an array that will enable http authentication only for the + # given strategies, for example, `config.http_authenticatable = [:database]` will + # enable it only for database authentication. + # For API-only applications to support authentication "out-of-the-box", you will likely want to + # enable this with :database unless you are using a custom strategy. + # The supported strategies are: + # :database = Support basic authentication with authentication key + password + # config.http_authenticatable = false + + # If 401 status code should be returned for AJAX requests. True by default. + # config.http_authenticatable_on_xhr = true + + # The realm used in Http Basic Authentication. 'Application' by default. + # config.http_authentication_realm = 'Application' + + # It will change confirmation, password recovery and other workflows + # to behave the same regardless if the e-mail provided was right or wrong. + # Does not affect registerable. + # config.paranoid = true + + # By default Devise will store the user in session. You can skip storage for + # particular strategies by setting this option. + # Notice that if you are skipping storage for all authentication paths, you + # may want to disable generating routes to Devise's sessions controller by + # passing skip: :sessions to `devise_for` in your config/routes.rb + config.skip_session_storage = [:http_auth] + + # By default, Devise cleans up the CSRF token on authentication to + # avoid CSRF token fixation attacks. This means that, when using AJAX + # requests for sign in and sign up, you need to get a new CSRF token + # from the server. You can disable this option at your own risk. + # config.clean_up_csrf_token_on_authentication = true + + # When false, Devise will not attempt to reload routes on eager load. + # This can reduce the time taken to boot the app but if your application + # requires the Devise mappings to be loaded during boot time the application + # won't boot properly. + # config.reload_routes = true + + # ==> Configuration for :database_authenticatable + # For bcrypt, this is the cost for hashing the password and defaults to 12. If + # using other algorithms, it sets how many times you want the password to be hashed. + # The number of stretches used for generating the hashed password are stored + # with the hashed password. This allows you to change the stretches without + # invalidating existing passwords. + # + # Limiting the stretches to just one in testing will increase the performance of + # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use + # a value less than 10 in other environments. Note that, for bcrypt (the default + # algorithm), the cost increases exponentially with the number of stretches (e.g. + # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). + config.stretches = Rails.env.test? ? 1 : 12 + + # Set up a pepper to generate the hashed password. + # config.pepper = 'c21b01526917545dc122e633753f26a6ec95652746219ce72b472d18929dd5d700bc7c013e7c90eec6b0ae6f9a4f59b626d276bb5154f07d470a6aa979a61087' + + # Send a notification to the original email when the user's email is changed. + # config.send_email_changed_notification = false + + # Send a notification email when the user's password is changed. + # config.send_password_change_notification = false + + # ==> Configuration for :confirmable + # A period that the user is allowed to access the website even without + # confirming their account. For instance, if set to 2.days, the user will be + # able to access the website for two days without confirming their account, + # access will be blocked just in the third day. + # You can also set it to nil, which will allow the user to access the website + # without confirming their account. + # Default is 0.days, meaning the user cannot access the website without + # confirming their account. + # config.allow_unconfirmed_access_for = 2.days + + # A period that the user is allowed to confirm their account before their + # token becomes invalid. For example, if set to 3.days, the user can confirm + # their account within 3 days after the mail was sent, but on the fourth day + # their account can't be confirmed with the token any more. + # Default is nil, meaning there is no restriction on how long a user can take + # before confirming their account. + # config.confirm_within = 3.days + + # If true, requires any email changes to be confirmed (exactly the same way as + # initial account confirmation) to be applied. Requires additional unconfirmed_email + # db field (see migrations). Until confirmed, new email is stored in + # unconfirmed_email column, and copied to email column on successful confirmation. + config.reconfirmable = true + + # Defines which key will be used when confirming an account + # config.confirmation_keys = [:email] + + # ==> Configuration for :rememberable + # The time the user will be remembered without asking for credentials again. + # config.remember_for = 2.weeks + + # Invalidates all the remember me tokens when the user signs out. + config.expire_all_remember_me_on_sign_out = true + + # If true, extends the user's remember period when remembered via cookie. + # config.extend_remember_period = false + + # Options to be passed to the created cookie. For instance, you can set + # secure: true in order to force SSL only cookies. + # config.rememberable_options = {} + + # ==> Configuration for :validatable + # Range for password length. + config.password_length = 6..128 + + # Email regex used to validate email formats. It simply asserts that + # one (and only one) @ exists in the given string. This is mainly + # to give user feedback and not to assert the e-mail validity. + config.email_regexp = /\A[^@\s]+@[^@\s]+\z/ + + # ==> Configuration for :timeoutable + # The time you want to timeout the user session without activity. After this + # time the user will be asked for credentials again. Default is 30 minutes. + # config.timeout_in = 30.minutes + + # ==> Configuration for :lockable + # Defines which strategy will be used to lock an account. + # :failed_attempts = Locks an account after a number of failed attempts to sign in. + # :none = No lock strategy. You should handle locking by yourself. + # config.lock_strategy = :failed_attempts + + # Defines which key will be used when locking and unlocking an account + # config.unlock_keys = [:email] + + # Defines which strategy will be used to unlock an account. + # :email = Sends an unlock link to the user email + # :time = Re-enables login after a certain amount of time (see :unlock_in below) + # :both = Enables both strategies + # :none = No unlock strategy. You should handle unlocking by yourself. + # config.unlock_strategy = :both + + # Number of authentication tries before locking an account if lock_strategy + # is failed attempts. + # config.maximum_attempts = 20 + + # Time interval to unlock the account if :time is enabled as unlock_strategy. + # config.unlock_in = 1.hour + + # Warn on the last attempt before the account is locked. + # config.last_attempt_warning = true + + # ==> Configuration for :recoverable + # + # Defines which key will be used when recovering the password for an account + # config.reset_password_keys = [:email] + + # Time interval you can reset your password with a reset password key. + # Don't put a too small interval or your users won't have the time to + # change their passwords. + config.reset_password_within = 6.hours + + # When set to false, does not sign a user in automatically after their password is + # reset. Defaults to true, so a user is signed in automatically after a reset. + # config.sign_in_after_reset_password = true + + # ==> Configuration for :encryptable + # Allow you to use another hashing or encryption algorithm besides bcrypt (default). + # You can use :sha1, :sha512 or algorithms from others authentication tools as + # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20 + # for default behavior) and :restful_authentication_sha1 (then you should set + # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper). + # + # Require the `devise-encryptable` gem when using anything other than bcrypt + # config.encryptor = :sha512 + + # ==> Scopes configuration + # Turn scoped views on. Before rendering "sessions/new", it will first check for + # "users/sessions/new". It's turned off by default because it's slower if you + # are using only default views. + # config.scoped_views = false + + # Configure the default scope given to Warden. By default it's the first + # devise role declared in your routes (usually :user). + # config.default_scope = :user + + # Set this configuration to false if you want /users/sign_out to sign out + # only the current scope. By default, Devise signs out all scopes. + # config.sign_out_all_scopes = true + + # ==> Navigation configuration + # Lists the formats that should be treated as navigational. Formats like + # :html should redirect to the sign in page when the user does not have + # access, but formats like :xml or :json, should return 401. + # + # If you have any extra navigational formats, like :iphone or :mobile, you + # should add them to the navigational formats lists. + # + # The "*/*" below is required to match Internet Explorer requests. + # config.navigational_formats = ['*/*', :html, :turbo_stream] + + # The default HTTP method used to sign out a resource. Default is :delete. + config.sign_out_via = :delete + + # ==> OmniAuth + # Add a new OmniAuth provider. Check the wiki for more information on setting + # up on your models and hooks. + # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' + + # ==> Warden configuration + # If you want to use other strategies, that are not supported by Devise, or + # change the failure app, you can configure them inside the config.warden block. + # + # config.warden do |manager| + # manager.intercept_401 = false + # manager.default_strategies(scope: :user).unshift :some_external_strategy + # end + + # ==> Mountable engine configurations + # When using Devise inside an engine, let's call it `MyEngine`, and this engine + # is mountable, there are some extra configurations to be taken into account. + # The following options are available, assuming the engine is mounted as: + # + # mount MyEngine, at: '/my_engine' + # + # The router that invoked `devise_for`, in the example above, would be: + # config.router_name = :my_engine + # + # When using OmniAuth, Devise cannot automatically set OmniAuth path, + # so you need to do it manually. For the users scope, it would be: + # config.omniauth_path_prefix = '/my_engine/users/auth' + + # ==> Hotwire/Turbo configuration + # When using Devise with Hotwire/Turbo, the http status for error responses + # and some redirects must match the following. The default in Devise for existing + # apps is `200 OK` and `302 Found` respectively, but new apps are generated with + # these new defaults that match Hotwire/Turbo behavior. + # Note: These might become the new default in future versions of Devise. + config.responder.error_status = :unprocessable_entity + config.responder.redirect_status = :see_other + + # ==> Configuration for :registerable + + # When set to false, does not sign a user in automatically after their password is + # changed. Defaults to true, so a user is signed in automatically after changing a password. + # config.sign_in_after_change_password = true +end diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb new file mode 100644 index 000000000..c0b717f7e --- /dev/null +++ b/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file. +# Use this to limit dissemination of sensitive information. +# See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors. +Rails.application.config.filter_parameters += [ + :passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, :cvv, :cvc +] diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb new file mode 100644 index 000000000..3860f659e --- /dev/null +++ b/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, "\\1en" +# inflect.singular /^(ox)en/i, "\\1" +# inflect.irregular "person", "people" +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym "RESTful" +# end diff --git a/config/locales/devise.en.yml b/config/locales/devise.en.yml new file mode 100644 index 000000000..260e1c4ba --- /dev/null +++ b/config/locales/devise.en.yml @@ -0,0 +1,65 @@ +# Additional translations at https://github.com/heartcombo/devise/wiki/I18n + +en: + devise: + confirmations: + confirmed: "Your email address has been successfully confirmed." + send_instructions: "You will receive an email with instructions for how to confirm your email address in a few minutes." + send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes." + failure: + already_authenticated: "You are already signed in." + inactive: "Your account is not activated yet." + invalid: "Invalid %{authentication_keys} or password." + locked: "Your account is locked." + last_attempt: "You have one more attempt before your account is locked." + not_found_in_database: "Invalid %{authentication_keys} or password." + timeout: "Your session expired. Please sign in again to continue." + unauthenticated: "You need to sign in or sign up before continuing." + unconfirmed: "You have to confirm your email address before continuing." + mailer: + confirmation_instructions: + subject: "Confirmation instructions" + reset_password_instructions: + subject: "Reset password instructions" + unlock_instructions: + subject: "Unlock instructions" + email_changed: + subject: "Email Changed" + password_change: + subject: "Password Changed" + omniauth_callbacks: + failure: "Could not authenticate you from %{kind} because \"%{reason}\"." + success: "Successfully authenticated from %{kind} account." + passwords: + no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided." + send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes." + send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." + updated: "Your password has been changed successfully. You are now signed in." + updated_not_active: "Your password has been changed successfully." + registrations: + destroyed: "Bye! Your account has been successfully cancelled. We hope to see you again soon." + signed_up: "Welcome! You have signed up successfully." + signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated." + signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked." + signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please follow the link to activate your account." + update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and follow the confirmation link to confirm your new email address." + updated: "Your account has been updated successfully." + updated_but_not_signed_in: "Your account has been updated successfully, but since your password was changed, you need to sign in again." + sessions: + signed_in: "Signed in successfully." + signed_out: "Signed out successfully." + already_signed_out: "Signed out successfully." + unlocks: + send_instructions: "You will receive an email with instructions for how to unlock your account in a few minutes." + send_paranoid_instructions: "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes." + unlocked: "Your account has been unlocked successfully. Please sign in to continue." + errors: + messages: + already_confirmed: "was already confirmed, please try signing in" + confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" + expired: "has expired, please request a new one" + not_found: "not found" + not_locked: "was not locked" + not_saved: + one: "1 error prohibited this %{resource} from being saved:" + other: "%{count} errors prohibited this %{resource} from being saved:" diff --git a/config/locales/en.yml b/config/locales/en.yml new file mode 100644 index 000000000..6c349ae5e --- /dev/null +++ b/config/locales/en.yml @@ -0,0 +1,31 @@ +# Files in the config/locales directory are used for internationalization and +# are automatically loaded by Rails. If you want to use locales other than +# English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t "hello" +# +# In views, this is aliased to just `t`: +# +# <%= t("hello") %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# To learn more about the API, please read the Rails Internationalization guide +# at https://guides.rubyonrails.org/i18n.html. +# +# Be aware that YAML interprets the following case-insensitive strings as +# booleans: `true`, `false`, `on`, `off`, `yes`, `no`. Therefore, these strings +# must be quoted to be interpreted as strings. For example: +# +# en: +# "yes": yup +# enabled: "ON" + +en: + hello: "Hello world" diff --git a/config/puma.rb b/config/puma.rb new file mode 100644 index 000000000..a248513b2 --- /dev/null +++ b/config/puma.rb @@ -0,0 +1,41 @@ +# This configuration file will be evaluated by Puma. The top-level methods that +# are invoked here are part of Puma's configuration DSL. For more information +# about methods provided by the DSL, see https://puma.io/puma/Puma/DSL.html. +# +# Puma starts a configurable number of processes (workers) and each process +# serves each request in a thread from an internal thread pool. +# +# You can control the number of workers using ENV["WEB_CONCURRENCY"]. You +# should only set this value when you want to run 2 or more workers. The +# default is already 1. +# +# The ideal number of threads per worker depends both on how much time the +# application spends waiting for IO operations and on how much you wish to +# prioritize throughput over latency. +# +# As a rule of thumb, increasing the number of threads will increase how much +# traffic a given process can handle (throughput), but due to CRuby's +# Global VM Lock (GVL) it has diminishing returns and will degrade the +# response time (latency) of the application. +# +# The default is set to 3 threads as it's deemed a decent compromise between +# throughput and latency for the average Rails application. +# +# Any libraries that use a connection pool or another resource pool should +# be configured to provide at least as many connections as the number of +# threads. This includes Active Record's `pool` parameter in `database.yml`. +threads_count = ENV.fetch("RAILS_MAX_THREADS", 3) +threads threads_count, threads_count + +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. +port ENV.fetch("PORT", 3000) + +# Allow puma to be restarted by `bin/rails restart` command. +plugin :tmp_restart + +# Run the Solid Queue supervisor inside of Puma for single-server deployments +plugin :solid_queue if ENV["SOLID_QUEUE_IN_PUMA"] + +# Specify the PID file. Defaults to tmp/pids/server.pid in development. +# In other environments, only set the PID file if requested. +pidfile ENV["PIDFILE"] if ENV["PIDFILE"] diff --git a/config/queue.yml b/config/queue.yml new file mode 100644 index 000000000..9eace59c4 --- /dev/null +++ b/config/queue.yml @@ -0,0 +1,18 @@ +default: &default + dispatchers: + - polling_interval: 1 + batch_size: 500 + workers: + - queues: "*" + threads: 3 + processes: <%= ENV.fetch("JOB_CONCURRENCY", 1) %> + polling_interval: 0.1 + +development: + <<: *default + +test: + <<: *default + +production: + <<: *default diff --git a/config/recurring.yml b/config/recurring.yml new file mode 100644 index 000000000..b4207f9b0 --- /dev/null +++ b/config/recurring.yml @@ -0,0 +1,15 @@ +# examples: +# periodic_cleanup: +# class: CleanSoftDeletedRecordsJob +# queue: background +# args: [ 1000, { batch_size: 500 } ] +# schedule: every hour +# periodic_cleanup_with_command: +# command: "SoftDeletedRecord.due.delete_all" +# priority: 2 +# schedule: at 5am every day + +production: + clear_solid_queue_finished_jobs: + command: "SolidQueue::Job.clear_finished_in_batches(sleep_between_batches: 0.3)" + schedule: every hour at minute 12 diff --git a/config/routes.rb b/config/routes.rb new file mode 100644 index 000000000..be25e8b39 --- /dev/null +++ b/config/routes.rb @@ -0,0 +1,15 @@ +Rails.application.routes.draw do + devise_for :users + # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html + + # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. + # Can be used by load balancers and uptime monitors to verify that the app is live. + get "up" => "rails/health#show", as: :rails_health_check + + # Render dynamic PWA files from app/views/pwa/* (remember to link manifest in application.html.erb) + # get "manifest" => "rails/pwa#manifest", as: :pwa_manifest + # get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker + + # Defines the root path route ("/") + # root "posts#index" +end diff --git a/config/storage.yml b/config/storage.yml new file mode 100644 index 000000000..4942ab669 --- /dev/null +++ b/config/storage.yml @@ -0,0 +1,34 @@ +test: + service: Disk + root: <%= Rails.root.join("tmp/storage") %> + +local: + service: Disk + root: <%= Rails.root.join("storage") %> + +# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) +# amazon: +# service: S3 +# access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> +# secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> +# region: us-east-1 +# bucket: your_own_bucket-<%= Rails.env %> + +# Remember not to checkin your GCS keyfile to a repository +# google: +# service: GCS +# project: your_project +# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> +# bucket: your_own_bucket-<%= Rails.env %> + +# Use bin/rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) +# microsoft: +# service: AzureStorage +# storage_account_name: your_account_name +# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> +# container: your_container_name-<%= Rails.env %> + +# mirror: +# service: Mirror +# primary: local +# mirrors: [ amazon, google, microsoft ] diff --git a/db/cable_schema.rb b/db/cable_schema.rb new file mode 100644 index 000000000..23666604a --- /dev/null +++ b/db/cable_schema.rb @@ -0,0 +1,11 @@ +ActiveRecord::Schema[7.1].define(version: 1) do + create_table "solid_cable_messages", force: :cascade do |t| + t.binary "channel", limit: 1024, null: false + t.binary "payload", limit: 536870912, null: false + t.datetime "created_at", null: false + t.integer "channel_hash", limit: 8, null: false + t.index ["channel"], name: "index_solid_cable_messages_on_channel" + t.index ["channel_hash"], name: "index_solid_cable_messages_on_channel_hash" + t.index ["created_at"], name: "index_solid_cable_messages_on_created_at" + end +end diff --git a/db/cache_schema.rb b/db/cache_schema.rb new file mode 100644 index 000000000..6005a2972 --- /dev/null +++ b/db/cache_schema.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +ActiveRecord::Schema[7.2].define(version: 1) do + create_table "solid_cache_entries", force: :cascade do |t| + t.binary "key", limit: 1024, null: false + t.binary "value", limit: 536870912, null: false + t.datetime "created_at", null: false + t.integer "key_hash", limit: 8, null: false + t.integer "byte_size", limit: 4, null: false + t.index ["byte_size"], name: "index_solid_cache_entries_on_byte_size" + t.index ["key_hash", "byte_size"], name: "index_solid_cache_entries_on_key_hash_and_byte_size" + t.index ["key_hash"], name: "index_solid_cache_entries_on_key_hash", unique: true + end +end diff --git a/db/migrate/20251103032403_devise_create_users.rb b/db/migrate/20251103032403_devise_create_users.rb new file mode 100644 index 000000000..74745e4c6 --- /dev/null +++ b/db/migrate/20251103032403_devise_create_users.rb @@ -0,0 +1,44 @@ +# frozen_string_literal: true + +class DeviseCreateUsers < ActiveRecord::Migration[8.0] + def change + create_table :users do |t| + ## Database authenticatable + t.string :email, null: false, default: "" + t.string :encrypted_password, null: false, default: "" + + ## Recoverable + t.string :reset_password_token + t.datetime :reset_password_sent_at + + ## Rememberable + t.datetime :remember_created_at + + ## Trackable + # t.integer :sign_in_count, default: 0, null: false + # t.datetime :current_sign_in_at + # t.datetime :last_sign_in_at + # t.string :current_sign_in_ip + # t.string :last_sign_in_ip + + ## Confirmable + # t.string :confirmation_token + # t.datetime :confirmed_at + # t.datetime :confirmation_sent_at + # t.string :unconfirmed_email # Only if using reconfirmable + + ## Lockable + # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts + # t.string :unlock_token # Only if unlock strategy is :email or :both + # t.datetime :locked_at + + + t.timestamps null: false + end + + add_index :users, :email, unique: true + add_index :users, :reset_password_token, unique: true + # add_index :users, :confirmation_token, unique: true + # add_index :users, :unlock_token, unique: true + end +end diff --git a/db/migrate/20251103032531_add_fields_to_users.rb b/db/migrate/20251103032531_add_fields_to_users.rb new file mode 100644 index 000000000..8973d3832 --- /dev/null +++ b/db/migrate/20251103032531_add_fields_to_users.rb @@ -0,0 +1,6 @@ +class AddFieldsToUsers < ActiveRecord::Migration[8.0] + def change + add_column :users, :full_name, :string + add_column :users, :role, :integer, default: 0, null: false + end +end diff --git a/db/migrate/20251103032728_create_active_storage_tables.active_storage.rb b/db/migrate/20251103032728_create_active_storage_tables.active_storage.rb new file mode 100644 index 000000000..6bd8bd082 --- /dev/null +++ b/db/migrate/20251103032728_create_active_storage_tables.active_storage.rb @@ -0,0 +1,57 @@ +# This migration comes from active_storage (originally 20170806125915) +class CreateActiveStorageTables < ActiveRecord::Migration[7.0] + def change + # Use Active Record's configured type for primary and foreign keys + primary_key_type, foreign_key_type = primary_and_foreign_key_types + + create_table :active_storage_blobs, id: primary_key_type do |t| + t.string :key, null: false + t.string :filename, null: false + t.string :content_type + t.text :metadata + t.string :service_name, null: false + t.bigint :byte_size, null: false + t.string :checksum + + if connection.supports_datetime_with_precision? + t.datetime :created_at, precision: 6, null: false + else + t.datetime :created_at, null: false + end + + t.index [ :key ], unique: true + end + + create_table :active_storage_attachments, id: primary_key_type do |t| + t.string :name, null: false + t.references :record, null: false, polymorphic: true, index: false, type: foreign_key_type + t.references :blob, null: false, type: foreign_key_type + + if connection.supports_datetime_with_precision? + t.datetime :created_at, precision: 6, null: false + else + t.datetime :created_at, null: false + end + + t.index [ :record_type, :record_id, :name, :blob_id ], name: :index_active_storage_attachments_uniqueness, unique: true + t.foreign_key :active_storage_blobs, column: :blob_id + end + + create_table :active_storage_variant_records, id: primary_key_type do |t| + t.belongs_to :blob, null: false, index: false, type: foreign_key_type + t.string :variation_digest, null: false + + t.index [ :blob_id, :variation_digest ], name: :index_active_storage_variant_records_uniqueness, unique: true + t.foreign_key :active_storage_blobs, column: :blob_id + end + end + + private + def primary_and_foreign_key_types + config = Rails.configuration.generators + setting = config.options[config.orm][:primary_key_type] + primary_key_type = setting || :primary_key + foreign_key_type = setting || :bigint + [ primary_key_type, foreign_key_type ] + end +end diff --git a/db/queue_schema.rb b/db/queue_schema.rb new file mode 100644 index 000000000..85194b6a8 --- /dev/null +++ b/db/queue_schema.rb @@ -0,0 +1,129 @@ +ActiveRecord::Schema[7.1].define(version: 1) do + create_table "solid_queue_blocked_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "queue_name", null: false + t.integer "priority", default: 0, null: false + t.string "concurrency_key", null: false + t.datetime "expires_at", null: false + t.datetime "created_at", null: false + t.index [ "concurrency_key", "priority", "job_id" ], name: "index_solid_queue_blocked_executions_for_release" + t.index [ "expires_at", "concurrency_key" ], name: "index_solid_queue_blocked_executions_for_maintenance" + t.index [ "job_id" ], name: "index_solid_queue_blocked_executions_on_job_id", unique: true + end + + create_table "solid_queue_claimed_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.bigint "process_id" + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_claimed_executions_on_job_id", unique: true + t.index [ "process_id", "job_id" ], name: "index_solid_queue_claimed_executions_on_process_id_and_job_id" + end + + create_table "solid_queue_failed_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.text "error" + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_failed_executions_on_job_id", unique: true + end + + create_table "solid_queue_jobs", force: :cascade do |t| + t.string "queue_name", null: false + t.string "class_name", null: false + t.text "arguments" + t.integer "priority", default: 0, null: false + t.string "active_job_id" + t.datetime "scheduled_at" + t.datetime "finished_at" + t.string "concurrency_key" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index [ "active_job_id" ], name: "index_solid_queue_jobs_on_active_job_id" + t.index [ "class_name" ], name: "index_solid_queue_jobs_on_class_name" + t.index [ "finished_at" ], name: "index_solid_queue_jobs_on_finished_at" + t.index [ "queue_name", "finished_at" ], name: "index_solid_queue_jobs_for_filtering" + t.index [ "scheduled_at", "finished_at" ], name: "index_solid_queue_jobs_for_alerting" + end + + create_table "solid_queue_pauses", force: :cascade do |t| + t.string "queue_name", null: false + t.datetime "created_at", null: false + t.index [ "queue_name" ], name: "index_solid_queue_pauses_on_queue_name", unique: true + end + + create_table "solid_queue_processes", force: :cascade do |t| + t.string "kind", null: false + t.datetime "last_heartbeat_at", null: false + t.bigint "supervisor_id" + t.integer "pid", null: false + t.string "hostname" + t.text "metadata" + t.datetime "created_at", null: false + t.string "name", null: false + t.index [ "last_heartbeat_at" ], name: "index_solid_queue_processes_on_last_heartbeat_at" + t.index [ "name", "supervisor_id" ], name: "index_solid_queue_processes_on_name_and_supervisor_id", unique: true + t.index [ "supervisor_id" ], name: "index_solid_queue_processes_on_supervisor_id" + end + + create_table "solid_queue_ready_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "queue_name", null: false + t.integer "priority", default: 0, null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_ready_executions_on_job_id", unique: true + t.index [ "priority", "job_id" ], name: "index_solid_queue_poll_all" + t.index [ "queue_name", "priority", "job_id" ], name: "index_solid_queue_poll_by_queue" + end + + create_table "solid_queue_recurring_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "task_key", null: false + t.datetime "run_at", null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_recurring_executions_on_job_id", unique: true + t.index [ "task_key", "run_at" ], name: "index_solid_queue_recurring_executions_on_task_key_and_run_at", unique: true + end + + create_table "solid_queue_recurring_tasks", force: :cascade do |t| + t.string "key", null: false + t.string "schedule", null: false + t.string "command", limit: 2048 + t.string "class_name" + t.text "arguments" + t.string "queue_name" + t.integer "priority", default: 0 + t.boolean "static", default: true, null: false + t.text "description" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index [ "key" ], name: "index_solid_queue_recurring_tasks_on_key", unique: true + t.index [ "static" ], name: "index_solid_queue_recurring_tasks_on_static" + end + + create_table "solid_queue_scheduled_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "queue_name", null: false + t.integer "priority", default: 0, null: false + t.datetime "scheduled_at", null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_scheduled_executions_on_job_id", unique: true + t.index [ "scheduled_at", "priority", "job_id" ], name: "index_solid_queue_dispatch_all" + end + + create_table "solid_queue_semaphores", force: :cascade do |t| + t.string "key", null: false + t.integer "value", default: 1, null: false + t.datetime "expires_at", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index [ "expires_at" ], name: "index_solid_queue_semaphores_on_expires_at" + t.index [ "key", "value" ], name: "index_solid_queue_semaphores_on_key_and_value" + t.index [ "key" ], name: "index_solid_queue_semaphores_on_key", unique: true + end + + add_foreign_key "solid_queue_blocked_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_claimed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_failed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_ready_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_recurring_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_scheduled_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade +end diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 000000000..4b6e9e447 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,61 @@ +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# This file is the source Rails uses to define your schema when running `bin/rails +# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to +# be faster and is potentially less error prone than running all of your +# migrations from scratch. Old migrations may fail to apply correctly if those +# migrations use external dependencies or application code. +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema[8.0].define(version: 2025_11_03_032728) do + # These are extensions that must be enabled in order to support this database + enable_extension "pg_catalog.plpgsql" + + create_table "active_storage_attachments", force: :cascade do |t| + t.string "name", null: false + t.string "record_type", null: false + t.bigint "record_id", null: false + t.bigint "blob_id", null: false + t.datetime "created_at", null: false + t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id" + t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true + end + + create_table "active_storage_blobs", force: :cascade do |t| + t.string "key", null: false + t.string "filename", null: false + t.string "content_type" + t.text "metadata" + t.string "service_name", null: false + t.bigint "byte_size", null: false + t.string "checksum" + t.datetime "created_at", null: false + t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true + end + + create_table "active_storage_variant_records", force: :cascade do |t| + t.bigint "blob_id", null: false + t.string "variation_digest", null: false + t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true + end + + create_table "users", force: :cascade do |t| + t.string "email", default: "", null: false + t.string "encrypted_password", default: "", null: false + t.string "reset_password_token" + t.datetime "reset_password_sent_at" + t.datetime "remember_created_at" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.string "full_name" + t.integer "role", default: 0, null: false + t.index ["email"], name: "index_users_on_email", unique: true + t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true + end + + add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id" + add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id" +end diff --git a/db/seeds.rb b/db/seeds.rb new file mode 100644 index 000000000..4fbd6ed97 --- /dev/null +++ b/db/seeds.rb @@ -0,0 +1,9 @@ +# This file should ensure the existence of records required to run the application in every environment (production, +# development, test). The code here should be idempotent so that it can be executed at any point in every environment. +# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). +# +# Example: +# +# ["Action", "Comedy", "Drama", "Horror"].each do |genre_name| +# MovieGenre.find_or_create_by!(name: genre_name) +# end diff --git a/lib/tasks/.keep b/lib/tasks/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/log/.keep b/log/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/public/400.html b/public/400.html new file mode 100644 index 000000000..282dbc8cc --- /dev/null +++ b/public/400.html @@ -0,0 +1,114 @@ + + + + + + + The server cannot process the request due to a client error (400 Bad Request) + + + + + + + + + + + + + +
+
+ +
+
+

The server cannot process the request due to a client error. Please check the request and try again. If you’re the application owner check the logs for more information.

+
+
+ + + + diff --git a/public/404.html b/public/404.html new file mode 100644 index 000000000..c0670bc87 --- /dev/null +++ b/public/404.html @@ -0,0 +1,114 @@ + + + + + + + The page you were looking for doesn’t exist (404 Not found) + + + + + + + + + + + + + +
+
+ +
+
+

The page you were looking for doesn’t exist. You may have mistyped the address or the page may have moved. If you’re the application owner check the logs for more information.

+
+
+ + + + diff --git a/public/406-unsupported-browser.html b/public/406-unsupported-browser.html new file mode 100644 index 000000000..9532a9ccd --- /dev/null +++ b/public/406-unsupported-browser.html @@ -0,0 +1,114 @@ + + + + + + + Your browser is not supported (406 Not Acceptable) + + + + + + + + + + + + + +
+
+ +
+
+

Your browser is not supported.
Please upgrade your browser to continue.

+
+
+ + + + diff --git a/public/422.html b/public/422.html new file mode 100644 index 000000000..8bcf06014 --- /dev/null +++ b/public/422.html @@ -0,0 +1,114 @@ + + + + + + + The change you wanted was rejected (422 Unprocessable Entity) + + + + + + + + + + + + + +
+
+ +
+
+

The change you wanted was rejected. Maybe you tried to change something you didn’t have access to. If you’re the application owner check the logs for more information.

+
+
+ + + + diff --git a/public/500.html b/public/500.html new file mode 100644 index 000000000..d77718c3a --- /dev/null +++ b/public/500.html @@ -0,0 +1,114 @@ + + + + + + + We’re sorry, but something went wrong (500 Internal Server Error) + + + + + + + + + + + + + +
+
+ +
+
+

We’re sorry, but something went wrong.
If you’re the application owner check the logs for more information.

+
+
+ + + + diff --git a/public/icon.png b/public/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..c4c9dbfbbd2f7c1421ffd5727188146213abbcef GIT binary patch literal 4166 zcmd6qU;WFw?|v@m)Sk^&NvB8tcujdV-r1b=i(NJxn&7{KTb zX$3(M+3TP2o^#KAo{#tIjl&t~(8D-k004kqPglzn0HFG(Q~(I*AKsD#M*g7!XK0T7 zN6P7j>HcT8rZgKl$v!xr806dyN19Bd4C0x_R*I-a?#zsTvb_89cyhuC&T**i|Rc zq5b8M;+{8KvoJ~uj9`u~d_f6`V&3+&ZX9x5pc8s)d175;@pjm(?dapmBcm0&vl9+W zx1ZD2o^nuyUHWj|^A8r>lUorO`wFF;>9XL-Jy!P}UXC{(z!FO%SH~8k`#|9;Q|eue zqWL0^Bp(fg_+Pkm!fDKRSY;+^@BF?AJE zCUWpXPst~hi_~u)SzYBDZroR+Z4xeHIlm_3Yc_9nZ(o_gg!jDgVa=E}Y8uDgem9`b zf=mfJ_@(BXSkW53B)F2s!&?_R4ptb1fYXlF++@vPhd=marQgEGRZS@B4g1Mu?euknL= z67P~tZ?*>-Hmi7GwlisNHHJDku-dSm7g@!=a}9cSL6Pa^w^2?&?$Oi8ibrr>w)xqx zOH_EMU@m05)9kuNR>>4@H%|){U$^yvVQ(YgOlh;5oU_-vivG-p4=LrN-k7D?*?u1u zsWly%tfAzKd6Fb=`eU2un_uaTXmcT#tlOL+aRS=kZZf}A7qT8lvcTx~7j` z*b>=z)mwg7%B2_!D0!1IZ?Nq{^Y$uI4Qx*6T!E2Col&2{k?ImCO=dD~A&9f9diXy^$x{6CwkBimn|1E09 zAMSezYtiL?O6hS37KpvDM?22&d{l)7h-!F)C-d3j8Z`c@($?mfd{R82)H>Qe`h{~G z!I}(2j(|49{LR?w4Jspl_i!(4T{31|dqCOpI52r5NhxYV+cDAu(xp*4iqZ2e-$YP= zoFOPmm|u*7C?S{Fp43y+V;>~@FFR76bCl@pTtyB93vNWy5yf;HKr8^0d7&GVIslYm zo3Tgt@M!`8B6IW&lK{Xk>%zp41G%`(DR&^u z5^pwD4>E6-w<8Kl2DzJ%a@~QDE$(e87lNhy?-Qgep!$b?5f7+&EM7$e>|WrX+=zCb z=!f5P>MxFyy;mIRxjc(H*}mceXw5a*IpC0PEYJ8Y3{JdoIW)@t97{wcUB@u+$FCCO z;s2Qe(d~oJC^`m$7DE-dsha`glrtu&v&93IZadvl_yjp!c89>zo;Krk+d&DEG4?x$ zufC1n+c1XD7dolX1q|7}uelR$`pT0Z)1jun<39$Sn2V5g&|(j~Z!wOddfYiZo7)A< z!dK`aBHOOk+-E_xbWCA3VR-+o$i5eO9`rMI#p_0xQ}rjEpGW;U!&&PKnivOcG(|m9 z!C8?WC6nCXw25WVa*eew)zQ=h45k8jSIPbq&?VE{oG%?4>9rwEeB4&qe#?-y_es4c|7ufw%+H5EY#oCgv!Lzv291#-oNlX~X+Jl5(riC~r z=0M|wMOP)Tt8@hNg&%V@Z9@J|Q#K*hE>sr6@oguas9&6^-=~$*2Gs%h#GF@h)i=Im z^iKk~ipWJg1VrvKS;_2lgs3n1zvNvxb27nGM=NXE!D4C!U`f*K2B@^^&ij9y}DTLB*FI zEnBL6y{jc?JqXWbkIZd7I16hA>(f9T!iwbIxJj~bKPfrO;>%*5nk&Lf?G@c2wvGrY&41$W{7HM9+b@&XY@>NZM5s|EK_Dp zQX60CBuantx>|d#DsaZ*8MW(we|#KTYZ=vNa#d*DJQe6hr~J6{_rI#?wi@s|&O}FR zG$kfPxheXh1?IZ{bDT-CWB4FTvO-k5scW^mi8?iY5Q`f8JcnnCxiy@m@D-%lO;y0pTLhh6i6l@x52j=#^$5_U^os}OFg zzdHbo(QI`%9#o*r8GCW~T3UdV`szO#~)^&X_(VW>o~umY9-ns9-V4lf~j z`QBD~pJ4a#b`*6bJ^3RS5y?RAgF7K5$ll97Y8#WZduZ`j?IEY~H(s^doZg>7-tk*t z4_QE1%%bb^p~4F5SB$t2i1>DBG1cIo;2(xTaj*Y~hlM{tSDHojL-QPg%Mo%6^7FrpB*{ z4G0@T{-77Por4DCMF zB_5Y~Phv%EQ64W8^GS6h?x6xh;w2{z3$rhC;m+;uD&pR74j+i22P5DS-tE8ABvH(U~indEbBUTAAAXfHZg5QpB@TgV9eI<)JrAkOI z8!TSOgfAJiWAXeM&vR4Glh;VxH}WG&V$bVb`a`g}GSpwggti*&)taV1@Ak|{WrV|5 zmNYx)Ans=S{c52qv@+jmGQ&vd6>6yX6IKq9O$3r&0xUTdZ!m1!irzn`SY+F23Rl6# zFRxws&gV-kM1NX(3(gnKpGi0Q)Dxi~#?nyzOR9!en;Ij>YJZVFAL*=R%7y%Mz9hU% zs>+ZB?qRmZ)nISx7wxY)y#cd$iaC~{k0avD>BjyF1q^mNQ1QcwsxiTySe<6C&cC6P zE`vwO9^k-d`9hZ!+r@Jnr+MF*2;2l8WjZ}DrwDUHzSF{WoG zucbSWguA!3KgB3MU%HH`R;XqVv0CcaGq?+;v_A5A2kpmk5V%qZE3yzQ7R5XWhq=eR zyUezH=@V)y>L9T-M-?tW(PQYTRBKZSVb_!$^H-Pn%ea;!vS_?M<~Tm>_rWIW43sPW z=!lY&fWc1g7+r?R)0p8(%zp&vl+FK4HRkns%BW+Up&wK8!lQ2~bja|9bD12WrKn#M zK)Yl9*8$SI7MAwSK$%)dMd>o+1UD<2&aQMhyjS5R{-vV+M;Q4bzl~Z~=4HFj_#2V9 zB)Gfzx3ncy@uzx?yzi}6>d%-?WE}h7v*w)Jr_gBl!2P&F3DX>j_1#--yjpL%<;JMR z*b70Gr)MMIBWDo~#<5F^Q0$VKI;SBIRneuR7)yVsN~A9I@gZTXe)E?iVII+X5h0~H zx^c(fP&4>!*q>fb6dAOC?MI>Cz3kld#J*;uik+Ps49cwm1B4 zZc1|ZxYyTv;{Z!?qS=D)sgRKx^1AYf%;y_V&VgZglfU>d+Ufk5&LV$sKv}Hoj+s; xK3FZRYdhbXT_@RW*ff3@`D1#ps#~H)p+y&j#(J|vk^lW{fF9OJt5(B-_&*Xgn9~3N literal 0 HcmV?d00001 diff --git a/public/icon.svg b/public/icon.svg new file mode 100644 index 000000000..04b34bf83 --- /dev/null +++ b/public/icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/robots.txt b/public/robots.txt new file mode 100644 index 000000000..c19f78ab6 --- /dev/null +++ b/public/robots.txt @@ -0,0 +1 @@ +# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/script/.keep b/script/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/storage/.keep b/storage/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/application_system_test_case.rb b/test/application_system_test_case.rb new file mode 100644 index 000000000..cee29fd21 --- /dev/null +++ b/test/application_system_test_case.rb @@ -0,0 +1,5 @@ +require "test_helper" + +class ApplicationSystemTestCase < ActionDispatch::SystemTestCase + driven_by :selenium, using: :headless_chrome, screen_size: [ 1400, 1400 ] +end diff --git a/test/controllers/.keep b/test/controllers/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/fixtures/files/.keep b/test/fixtures/files/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml new file mode 100644 index 000000000..d7a332924 --- /dev/null +++ b/test/fixtures/users.yml @@ -0,0 +1,11 @@ +# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +# This model initially had no columns defined. If you add columns to the +# model remove the "{}" from the fixture names and add the columns immediately +# below each fixture, per the syntax in the comments below +# +one: {} +# column: value +# +two: {} +# column: value diff --git a/test/helpers/.keep b/test/helpers/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/integration/.keep b/test/integration/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/mailers/.keep b/test/mailers/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/models/.keep b/test/models/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/models/user_test.rb b/test/models/user_test.rb new file mode 100644 index 000000000..5c07f4900 --- /dev/null +++ b/test/models/user_test.rb @@ -0,0 +1,7 @@ +require "test_helper" + +class UserTest < ActiveSupport::TestCase + # test "the truth" do + # assert true + # end +end diff --git a/test/system/.keep b/test/system/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 000000000..0c22470ec --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,15 @@ +ENV["RAILS_ENV"] ||= "test" +require_relative "../config/environment" +require "rails/test_help" + +module ActiveSupport + class TestCase + # Run tests in parallel with specified workers + parallelize(workers: :number_of_processors) + + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... + end +end diff --git a/tmp/.keep b/tmp/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/tmp/pids/.keep b/tmp/pids/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/tmp/storage/.keep b/tmp/storage/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/vendor/.keep b/vendor/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/vendor/javascript/.keep b/vendor/javascript/.keep new file mode 100644 index 000000000..e69de29bb From 32d0a66d848965564c9f8beb69c1206bbcd4e7ee Mon Sep 17 00:00:00 2001 From: vitaotm Date: Mon, 3 Nov 2025 14:19:16 -0300 Subject: [PATCH 02/17] Set up Pundit for authorization --- app/controllers/application_controller.rb | 19 +++++ app/models/user.rb | 38 ++++++++++ app/policies/application_policy.rb | 53 ++++++++++++++ app/policies/user_policy.rb | 35 ++++++++++ app/views/devise/confirmations/new.html.erb | 16 +++++ .../mailer/confirmation_instructions.html.erb | 5 ++ .../devise/mailer/email_changed.html.erb | 7 ++ .../devise/mailer/password_change.html.erb | 3 + .../reset_password_instructions.html.erb | 8 +++ .../mailer/unlock_instructions.html.erb | 7 ++ app/views/devise/passwords/edit.html.erb | 25 +++++++ app/views/devise/passwords/new.html.erb | 16 +++++ app/views/devise/registrations/edit.html.erb | 70 +++++++++++++++++++ app/views/devise/registrations/new.html.erb | 45 ++++++++++++ app/views/devise/sessions/new.html.erb | 26 +++++++ .../devise/shared/_error_messages.html.erb | 15 ++++ app/views/devise/shared/_links.html.erb | 25 +++++++ app/views/devise/unlocks/new.html.erb | 16 +++++ 18 files changed, 429 insertions(+) create mode 100644 app/policies/application_policy.rb create mode 100644 app/policies/user_policy.rb create mode 100644 app/views/devise/confirmations/new.html.erb create mode 100644 app/views/devise/mailer/confirmation_instructions.html.erb create mode 100644 app/views/devise/mailer/email_changed.html.erb create mode 100644 app/views/devise/mailer/password_change.html.erb create mode 100644 app/views/devise/mailer/reset_password_instructions.html.erb create mode 100644 app/views/devise/mailer/unlock_instructions.html.erb create mode 100644 app/views/devise/passwords/edit.html.erb create mode 100644 app/views/devise/passwords/new.html.erb create mode 100644 app/views/devise/registrations/edit.html.erb create mode 100644 app/views/devise/registrations/new.html.erb create mode 100644 app/views/devise/sessions/new.html.erb create mode 100644 app/views/devise/shared/_error_messages.html.erb create mode 100644 app/views/devise/shared/_links.html.erb create mode 100644 app/views/devise/unlocks/new.html.erb diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 0d95db22b..3f03a82d2 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,4 +1,23 @@ class ApplicationController < ActionController::Base # Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has. + # + include Pundit::Authorization + before_action :configure_permitted_parameters, if: :devise_controller? allow_browser versions: :modern + + rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized + + protected + + def configure_permitted_parameters + devise_parameter_sanitizer.permit(:sign_up, keys: [ :full_name, :avatar_image, :avatar_url ]) + devise_parameter_sanitizer.permit(:account_update, keys: [ :full_name, :avatar_url, :avatar_image ]) + end + + private + + def user_not_authorized + flash[:alert] = "You are not authorized to perform this action" + redirect_to(request.referrer || root_path) + end end diff --git a/app/models/user.rb b/app/models/user.rb index 47567994e..60c60ab54 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -3,4 +3,42 @@ class User < ApplicationRecord # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable + + # enum role: { user: 0, admin: 1 } + + has_one_attached :avatar_image + + attr_accessor :avatar_url + + validates :full_name, presence: true + + before_validation :download_avatar_from_url, if: -> { avatar_url.present? } + after_create_commit :broadcast_dashboard_update + after_update_commit :broadcast_dashboard_update, if: :saved_change_to_role? + after_destroy_commit :broadcast_dashboard_update + + private + + def download_avatar_from_url + require "down" + begin + tempfile = Down.download(avatar_url) + self.avatar_image.attach(io: tempfile, filename: tempfile.original_filename) + rescue + Rails.logger.error "Avatar URL download failed: #{e.message}" + errors.add(:avatar_url, "is not a valid image URL or could not be downloaded") + end + end + + def broadcast_dashboard_update + Turbo::StreamsChannel.broadcast_dashboard_update_to( + "admin_dashboard_stats", + target: "admin_dashboard_stats", + partial: "admin/dashboard/stats", + locals: { + total_users: User.count, + users_by_role: User.group(:role).count + } + ) + end end diff --git a/app/policies/application_policy.rb b/app/policies/application_policy.rb new file mode 100644 index 000000000..be644fe34 --- /dev/null +++ b/app/policies/application_policy.rb @@ -0,0 +1,53 @@ +# frozen_string_literal: true + +class ApplicationPolicy + attr_reader :user, :record + + def initialize(user, record) + @user = user + @record = record + end + + def index? + false + end + + def show? + false + end + + def create? + false + end + + def new? + create? + end + + def update? + false + end + + def edit? + update? + end + + def destroy? + false + end + + class Scope + def initialize(user, scope) + @user = user + @scope = scope + end + + def resolve + raise NoMethodError, "You must define #resolve in #{self.class}" + end + + private + + attr_reader :user, :scope + end +end diff --git a/app/policies/user_policy.rb b/app/policies/user_policy.rb new file mode 100644 index 000000000..335551a3d --- /dev/null +++ b/app/policies/user_policy.rb @@ -0,0 +1,35 @@ +class UserPolicy < ApplicationPolicy + def index? + user.admin? + end + + def show? + user.admin? || record == user + end + + def create? + user.admin? + end + + def update? + user.admin? || record == user + end + + def destroy? + user.admin? || record == user + end + + def toggle_role? + user.admin? + end + + class Scope < ApplicationPolicy::Scope + def resolve + if user.admin? + scope.all + else + scope.where(id: user.id) + end + end + end +end diff --git a/app/views/devise/confirmations/new.html.erb b/app/views/devise/confirmations/new.html.erb new file mode 100644 index 000000000..b12dd0cbe --- /dev/null +++ b/app/views/devise/confirmations/new.html.erb @@ -0,0 +1,16 @@ +

Resend confirmation instructions

+ +<%= form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f| %> + <%= render "devise/shared/error_messages", resource: resource %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, autocomplete: "email", value: (resource.pending_reconfirmation? ? resource.unconfirmed_email : resource.email) %> +
+ +
+ <%= f.submit "Resend confirmation instructions" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/mailer/confirmation_instructions.html.erb b/app/views/devise/mailer/confirmation_instructions.html.erb new file mode 100644 index 000000000..dc55f64f6 --- /dev/null +++ b/app/views/devise/mailer/confirmation_instructions.html.erb @@ -0,0 +1,5 @@ +

Welcome <%= @email %>!

+ +

You can confirm your account email through the link below:

+ +

<%= link_to 'Confirm my account', confirmation_url(@resource, confirmation_token: @token) %>

diff --git a/app/views/devise/mailer/email_changed.html.erb b/app/views/devise/mailer/email_changed.html.erb new file mode 100644 index 000000000..32f4ba803 --- /dev/null +++ b/app/views/devise/mailer/email_changed.html.erb @@ -0,0 +1,7 @@ +

Hello <%= @email %>!

+ +<% if @resource.try(:unconfirmed_email?) %> +

We're contacting you to notify you that your email is being changed to <%= @resource.unconfirmed_email %>.

+<% else %> +

We're contacting you to notify you that your email has been changed to <%= @resource.email %>.

+<% end %> diff --git a/app/views/devise/mailer/password_change.html.erb b/app/views/devise/mailer/password_change.html.erb new file mode 100644 index 000000000..b41daf476 --- /dev/null +++ b/app/views/devise/mailer/password_change.html.erb @@ -0,0 +1,3 @@ +

Hello <%= @resource.email %>!

+ +

We're contacting you to notify you that your password has been changed.

diff --git a/app/views/devise/mailer/reset_password_instructions.html.erb b/app/views/devise/mailer/reset_password_instructions.html.erb new file mode 100644 index 000000000..f667dc12f --- /dev/null +++ b/app/views/devise/mailer/reset_password_instructions.html.erb @@ -0,0 +1,8 @@ +

Hello <%= @resource.email %>!

+ +

Someone has requested a link to change your password. You can do this through the link below.

+ +

<%= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token) %>

+ +

If you didn't request this, please ignore this email.

+

Your password won't change until you access the link above and create a new one.

diff --git a/app/views/devise/mailer/unlock_instructions.html.erb b/app/views/devise/mailer/unlock_instructions.html.erb new file mode 100644 index 000000000..41e148bf2 --- /dev/null +++ b/app/views/devise/mailer/unlock_instructions.html.erb @@ -0,0 +1,7 @@ +

Hello <%= @resource.email %>!

+ +

Your account has been locked due to an excessive number of unsuccessful sign in attempts.

+ +

Click the link below to unlock your account:

+ +

<%= link_to 'Unlock my account', unlock_url(@resource, unlock_token: @token) %>

diff --git a/app/views/devise/passwords/edit.html.erb b/app/views/devise/passwords/edit.html.erb new file mode 100644 index 000000000..5fbb9ff0a --- /dev/null +++ b/app/views/devise/passwords/edit.html.erb @@ -0,0 +1,25 @@ +

Change your password

+ +<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :put }) do |f| %> + <%= render "devise/shared/error_messages", resource: resource %> + <%= f.hidden_field :reset_password_token %> + +
+ <%= f.label :password, "New password" %>
+ <% if @minimum_password_length %> + (<%= @minimum_password_length %> characters minimum)
+ <% end %> + <%= f.password_field :password, autofocus: true, autocomplete: "new-password" %> +
+ +
+ <%= f.label :password_confirmation, "Confirm new password" %>
+ <%= f.password_field :password_confirmation, autocomplete: "new-password" %> +
+ +
+ <%= f.submit "Change my password" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/passwords/new.html.erb b/app/views/devise/passwords/new.html.erb new file mode 100644 index 000000000..9b486b81b --- /dev/null +++ b/app/views/devise/passwords/new.html.erb @@ -0,0 +1,16 @@ +

Forgot your password?

+ +<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %> + <%= render "devise/shared/error_messages", resource: resource %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, autocomplete: "email" %> +
+ +
+ <%= f.submit "Send me reset password instructions" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/registrations/edit.html.erb b/app/views/devise/registrations/edit.html.erb new file mode 100644 index 000000000..78ecd2423 --- /dev/null +++ b/app/views/devise/registrations/edit.html.erb @@ -0,0 +1,70 @@ +

Edit + <%= resource_name.to_s.humanize %>

+ +<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %> + <%= render "devise/shared/error_messages", resource: resource %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, autocomplete: "email" %> +
+ +
+ <%= f.label :full_name %>
+ <%= f.text_field :full_name, autofocus: true, autocomplete: "My Name" %> +
+ + <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %> +
Currently waiting confirmation for: + <%= resource.unconfirmed_email %>
+ <% end %> + +
+ <%= f.label :avatar_image %>
+ <%= f.file_field :avatar_image, class: "form-control" %> +
+ +
+ <%= f.label :avatar_url, class: "form-label" %>
+ <%= f.file_field :avatar_url, class: "form-control" %> +
+ +
+ <%= f.label :password %> + (leave blank if you don't want to change it)
+ <%= f.password_field :password, autocomplete: "new-password" %> + <% if @minimum_password_length %> +
+ <%= @minimum_password_length %> + characters minimum + <% end %> +
+ +
+ <%= f.label :password_confirmation %>
+ <%= f.password_field :password_confirmation, autocomplete: "new-password" %> +
+ +
+ <%= f.label :current_password %> + (we need your current password to confirm your changes)
+ <%= f.password_field :current_password, autocomplete: "current-password" %> +
+ +
+ <%= f.submit "Update" %> +
+<% end %> + +

Cancel my account

+ +
Unhappy? + <%= button_to "Cancel my account", + registration_path(resource_name), + data: { + confirm: "Are you sure?", + turbo_confirm: "Are you sure?", + }, + method: :delete %>
+ +<%= link_to "Back", :back %> diff --git a/app/views/devise/registrations/new.html.erb b/app/views/devise/registrations/new.html.erb new file mode 100644 index 000000000..0f7325905 --- /dev/null +++ b/app/views/devise/registrations/new.html.erb @@ -0,0 +1,45 @@ +

Sign up

+ +<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> + <%= render "devise/shared/error_messages", resource: resource %> + +
+ <%= f.label :full_name %>
+ <%= f.text_field :full_name, autofocus: true, autocomplete: "My Name" %> +
+ +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, autocomplete: "email" %> +
+ +
+ <%= f.label :avatar_image %>
+ <%= f.file_field :avatar_image, class: "form-control" %> +
+ +
+ <%= f.label :avatar_url, class: "form-label" %>
+ <%= f.file_field :avatar_url, class: "form-control" %> +
+ +
+ <%= f.label :password %> + <% if @minimum_password_length %> + (<%= @minimum_password_length %> + characters minimum) + <% end %>
+ <%= f.password_field :password, autocomplete: "new-password" %> +
+ +
+ <%= f.label :password_confirmation %>
+ <%= f.password_field :password_confirmation, autocomplete: "new-password" %> +
+ +
+ <%= f.submit "Sign up" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/sessions/new.html.erb b/app/views/devise/sessions/new.html.erb new file mode 100644 index 000000000..5ede96489 --- /dev/null +++ b/app/views/devise/sessions/new.html.erb @@ -0,0 +1,26 @@ +

Log in

+ +<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %> +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, autocomplete: "email" %> +
+ +
+ <%= f.label :password %>
+ <%= f.password_field :password, autocomplete: "current-password" %> +
+ + <% if devise_mapping.rememberable? %> +
+ <%= f.check_box :remember_me %> + <%= f.label :remember_me %> +
+ <% end %> + +
+ <%= f.submit "Log in" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/shared/_error_messages.html.erb b/app/views/devise/shared/_error_messages.html.erb new file mode 100644 index 000000000..cabfe307e --- /dev/null +++ b/app/views/devise/shared/_error_messages.html.erb @@ -0,0 +1,15 @@ +<% if resource.errors.any? %> +
+

+ <%= I18n.t("errors.messages.not_saved", + count: resource.errors.count, + resource: resource.class.model_name.human.downcase) + %> +

+
    + <% resource.errors.full_messages.each do |message| %> +
  • <%= message %>
  • + <% end %> +
+
+<% end %> diff --git a/app/views/devise/shared/_links.html.erb b/app/views/devise/shared/_links.html.erb new file mode 100644 index 000000000..7a75304ba --- /dev/null +++ b/app/views/devise/shared/_links.html.erb @@ -0,0 +1,25 @@ +<%- if controller_name != 'sessions' %> + <%= link_to "Log in", new_session_path(resource_name) %>
+<% end %> + +<%- if devise_mapping.registerable? && controller_name != 'registrations' %> + <%= link_to "Sign up", new_registration_path(resource_name) %>
+<% end %> + +<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %> + <%= link_to "Forgot your password?", new_password_path(resource_name) %>
+<% end %> + +<%- if devise_mapping.confirmable? && controller_name != 'confirmations' %> + <%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %>
+<% end %> + +<%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %> + <%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %>
+<% end %> + +<%- if devise_mapping.omniauthable? %> + <%- resource_class.omniauth_providers.each do |provider| %> + <%= button_to "Sign in with #{OmniAuth::Utils.camelize(provider)}", omniauth_authorize_path(resource_name, provider), data: { turbo: false } %>
+ <% end %> +<% end %> diff --git a/app/views/devise/unlocks/new.html.erb b/app/views/devise/unlocks/new.html.erb new file mode 100644 index 000000000..ffc34de8d --- /dev/null +++ b/app/views/devise/unlocks/new.html.erb @@ -0,0 +1,16 @@ +

Resend unlock instructions

+ +<%= form_for(resource, as: resource_name, url: unlock_path(resource_name), html: { method: :post }) do |f| %> + <%= render "devise/shared/error_messages", resource: resource %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, autocomplete: "email" %> +
+ +
+ <%= f.submit "Resend unlock instructions" %> +
+<% end %> + +<%= render "devise/shared/links" %> From e20694e095d5fe5e69176745a3e2b43ae722a3b5 Mon Sep 17 00:00:00 2001 From: vitaotm Date: Mon, 3 Nov 2025 14:25:59 -0300 Subject: [PATCH 03/17] Configure routes and role-based login redirects --- app/controllers/application_controller.rb | 9 +++++++++ config/routes.rb | 15 +++++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 3f03a82d2..0146a6963 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -3,6 +3,7 @@ class ApplicationController < ActionController::Base # include Pundit::Authorization before_action :configure_permitted_parameters, if: :devise_controller? + before_action :authonticate_user! allow_browser versions: :modern rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized @@ -14,6 +15,14 @@ def configure_permitted_parameters devise_parameter_sanitizer.permit(:account_update, keys: [ :full_name, :avatar_url, :avatar_image ]) end + def after_sign_in_path_for(resource) + if resource.admin? + admin_dashboard_path + else + profile_path + end + end + private def user_not_authorized diff --git a/config/routes.rb b/config/routes.rb index be25e8b39..4f68ebe5d 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -4,12 +4,23 @@ # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. # Can be used by load balancers and uptime monitors to verify that the app is live. - get "up" => "rails/health#show", as: :rails_health_check + namespace :admin do + get "dashboard", to: "dashboard#show" + + resources :users + + patch "users/:id/toggle_role", to: "users#toggle_role", as: toggle_user_role + + resources :user_imports, only: [ :new, :crete, :show ] + end + + resources :profile, only: [ :show, :edit, :update, :destroy ] # Render dynamic PWA files from app/views/pwa/* (remember to link manifest in application.html.erb) # get "manifest" => "rails/pwa#manifest", as: :pwa_manifest # get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker # Defines the root path route ("/") - # root "posts#index" + root "admin/dashboard#show" + get "up" => "rails/health#show", as: :rails_health_check end From f24aa315ab60c6d18f91980f41aa479cbcbec674 Mon Sep 17 00:00:00 2001 From: vitaotm Date: Mon, 3 Nov 2025 15:50:17 -0300 Subject: [PATCH 04/17] Build realtime admin dashboard --- app/controllers/admin/base_controller.rb | 12 ++++++++++ app/controllers/admin/dashboard_controller.rb | 6 +++++ app/controllers/application_controller.rb | 2 +- app/helpers/admin/base_helper.rb | 2 ++ app/helpers/admin/dashboard_helper.rb | 2 ++ app/models/user.rb | 6 ++--- app/views/admin/dashboard/_stats.html.erb | 24 +++++++++++++++++++ app/views/admin/dashboard/show.html.erb | 7 ++++++ config/routes.rb | 7 +++--- .../controllers/admin/base_controller_test.rb | 7 ++++++ .../admin/dashboard_controller_test.rb | 8 +++++++ 11 files changed, 76 insertions(+), 7 deletions(-) create mode 100644 app/controllers/admin/base_controller.rb create mode 100644 app/controllers/admin/dashboard_controller.rb create mode 100644 app/helpers/admin/base_helper.rb create mode 100644 app/helpers/admin/dashboard_helper.rb create mode 100644 app/views/admin/dashboard/_stats.html.erb create mode 100644 app/views/admin/dashboard/show.html.erb create mode 100644 test/controllers/admin/base_controller_test.rb create mode 100644 test/controllers/admin/dashboard_controller_test.rb diff --git a/app/controllers/admin/base_controller.rb b/app/controllers/admin/base_controller.rb new file mode 100644 index 000000000..03166097c --- /dev/null +++ b/app/controllers/admin/base_controller.rb @@ -0,0 +1,12 @@ +class Admin::BaseController < ApplicationController + before_action :require_admin + + private + + def require_admin + unless current_user.admin? + flash[:notice] = "You must be an admin to access this section" + redirect_to profile_path + end + end +end diff --git a/app/controllers/admin/dashboard_controller.rb b/app/controllers/admin/dashboard_controller.rb new file mode 100644 index 000000000..2770bba54 --- /dev/null +++ b/app/controllers/admin/dashboard_controller.rb @@ -0,0 +1,6 @@ +class Admin::DashboardController < ApplicationController + def show + @total_users = User.count + @users_by_role = User.group(:role).count + end +end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 0146a6963..0f05fdca2 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -3,7 +3,7 @@ class ApplicationController < ActionController::Base # include Pundit::Authorization before_action :configure_permitted_parameters, if: :devise_controller? - before_action :authonticate_user! + before_action :authenticate_user! allow_browser versions: :modern rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized diff --git a/app/helpers/admin/base_helper.rb b/app/helpers/admin/base_helper.rb new file mode 100644 index 000000000..f24ad87c9 --- /dev/null +++ b/app/helpers/admin/base_helper.rb @@ -0,0 +1,2 @@ +module Admin::BaseHelper +end diff --git a/app/helpers/admin/dashboard_helper.rb b/app/helpers/admin/dashboard_helper.rb new file mode 100644 index 000000000..4052b7c4b --- /dev/null +++ b/app/helpers/admin/dashboard_helper.rb @@ -0,0 +1,2 @@ +module Admin::DashboardHelper +end diff --git a/app/models/user.rb b/app/models/user.rb index 60c60ab54..78c8155f9 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -4,7 +4,7 @@ class User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable - # enum role: { user: 0, admin: 1 } + enum :role, { user: 0, admin: 1 } has_one_attached :avatar_image @@ -24,14 +24,14 @@ def download_avatar_from_url begin tempfile = Down.download(avatar_url) self.avatar_image.attach(io: tempfile, filename: tempfile.original_filename) - rescue + rescue Down::Error => e Rails.logger.error "Avatar URL download failed: #{e.message}" errors.add(:avatar_url, "is not a valid image URL or could not be downloaded") end end def broadcast_dashboard_update - Turbo::StreamsChannel.broadcast_dashboard_update_to( + Turbo::StreamsChannel.broadcast_update_to( "admin_dashboard_stats", target: "admin_dashboard_stats", partial: "admin/dashboard/stats", diff --git a/app/views/admin/dashboard/_stats.html.erb b/app/views/admin/dashboard/_stats.html.erb new file mode 100644 index 000000000..361425494 --- /dev/null +++ b/app/views/admin/dashboard/_stats.html.erb @@ -0,0 +1,24 @@ +
+
+
+
Total users
+

<%= total_users %>

+
+
+
+
+
Users by Role
+
    +
  • + Admins + <%= users_by_role["admin"] || 0 %> +
  • +
  • + Users + <%= users_by_role["user"] || 0 %> +
  • +
+
+
+ +
diff --git a/app/views/admin/dashboard/show.html.erb b/app/views/admin/dashboard/show.html.erb new file mode 100644 index 000000000..77a56f32b --- /dev/null +++ b/app/views/admin/dashboard/show.html.erb @@ -0,0 +1,7 @@ +

Admin Dashboard#show

+<%= turbo_stream_from "admin_dashboard_stats" %> +<%= turbo_frame_tag "admin_dashboard_stats" do %> + <%= render "admin/dashboard/stats", + total_users: @total_users, + users_by_role: @users_by_role %> +<% end %> diff --git a/config/routes.rb b/config/routes.rb index 4f68ebe5d..0fcb6eee1 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -6,16 +6,17 @@ # Can be used by load balancers and uptime monitors to verify that the app is live. namespace :admin do + get "dashboard/show" get "dashboard", to: "dashboard#show" resources :users - patch "users/:id/toggle_role", to: "users#toggle_role", as: toggle_user_role + patch "users/:id/toggle_role", to: "users#toggle_role", as: :toggle_user_role - resources :user_imports, only: [ :new, :crete, :show ] + resources :user_imports, only: [ :new, :create, :show ] end - resources :profile, only: [ :show, :edit, :update, :destroy ] + resource :profile, only: [ :show, :edit, :update, :destroy ] # Render dynamic PWA files from app/views/pwa/* (remember to link manifest in application.html.erb) # get "manifest" => "rails/pwa#manifest", as: :pwa_manifest # get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker diff --git a/test/controllers/admin/base_controller_test.rb b/test/controllers/admin/base_controller_test.rb new file mode 100644 index 000000000..36364cbaf --- /dev/null +++ b/test/controllers/admin/base_controller_test.rb @@ -0,0 +1,7 @@ +require "test_helper" + +class Admin::BaseControllerTest < ActionDispatch::IntegrationTest + # test "the truth" do + # assert true + # end +end diff --git a/test/controllers/admin/dashboard_controller_test.rb b/test/controllers/admin/dashboard_controller_test.rb new file mode 100644 index 000000000..8a2eb2bc4 --- /dev/null +++ b/test/controllers/admin/dashboard_controller_test.rb @@ -0,0 +1,8 @@ +require "test_helper" + +class Admin::DashboardControllerTest < ActionDispatch::IntegrationTest + test "should get show" do + get admin_dashboard_show_url + assert_response :success + end +end From 2591510f9d27b310001e802b150d7bf39b89b6f9 Mon Sep 17 00:00:00 2001 From: vitaotm Date: Mon, 3 Nov 2025 16:33:51 -0300 Subject: [PATCH 05/17] Implement admin user management CRUD --- app/controllers/admin/users_controller.rb | 67 +++++++++++++++++++ app/helpers/admin/users_helper.rb | 2 + app/views/admin/users/create.html.erb | 2 + app/views/admin/users/destroy.html.erb | 2 + app/views/admin/users/edit.html.erb | 2 + app/views/admin/users/index.html.erb | 10 +++ app/views/admin/users/new.html.erb | 2 + app/views/admin/users/show.html.erb | 2 + app/views/admin/users/update.html.erb | 2 + config/routes.rb | 7 ++ .../admin/users_controller_test.rb | 38 +++++++++++ 11 files changed, 136 insertions(+) create mode 100644 app/controllers/admin/users_controller.rb create mode 100644 app/helpers/admin/users_helper.rb create mode 100644 app/views/admin/users/create.html.erb create mode 100644 app/views/admin/users/destroy.html.erb create mode 100644 app/views/admin/users/edit.html.erb create mode 100644 app/views/admin/users/index.html.erb create mode 100644 app/views/admin/users/new.html.erb create mode 100644 app/views/admin/users/show.html.erb create mode 100644 app/views/admin/users/update.html.erb create mode 100644 test/controllers/admin/users_controller_test.rb diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb new file mode 100644 index 000000000..4c31e0dc7 --- /dev/null +++ b/app/controllers/admin/users_controller.rb @@ -0,0 +1,67 @@ +class Admin::UsersController < Admin::BaseController + before_action :set_user, only: [ :show, :edit, :update, :destroy, :toggle_role ] + + def index + @users = policy_scope(User) + end + + def show + authorize @user + end + + def new + @user = User.new + authorize @user + end + + def create + @user = User.new + authorize @user + + if @user.save + redirect_to admin_user_path(@user), notice: "User created" + else + render :new, status: :unprocessable_entity + end + end + + def edit + authorize @user + end + + def update + authorize @user + if @user.update(user_params) + redirect_to admin_user_path(@user), notice: "User updated" + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + authorize @user + @user.destroy + redirect_to admin_users_path, notice: "User deleted" + end + + def toggle_role + authorize @user, :toggle_role? + + if @user.admin? + @user.user! + else + @user.admin! + end + end + + + private + + def set_user + @user = User.find(params[:id]) + end + + def user_params + params.require(:user).permit(:full_name, :email, :password, :password_confirmations, :role, :avatar_image, :avatar_url) + end +end diff --git a/app/helpers/admin/users_helper.rb b/app/helpers/admin/users_helper.rb new file mode 100644 index 000000000..5995c2aa8 --- /dev/null +++ b/app/helpers/admin/users_helper.rb @@ -0,0 +1,2 @@ +module Admin::UsersHelper +end diff --git a/app/views/admin/users/create.html.erb b/app/views/admin/users/create.html.erb new file mode 100644 index 000000000..d0fedfb9b --- /dev/null +++ b/app/views/admin/users/create.html.erb @@ -0,0 +1,2 @@ +

Admin::Users#create

+

Find me in app/views/admin/users/create.html.erb

diff --git a/app/views/admin/users/destroy.html.erb b/app/views/admin/users/destroy.html.erb new file mode 100644 index 000000000..c80f2fdb0 --- /dev/null +++ b/app/views/admin/users/destroy.html.erb @@ -0,0 +1,2 @@ +

Admin::Users#destroy

+

Find me in app/views/admin/users/destroy.html.erb

diff --git a/app/views/admin/users/edit.html.erb b/app/views/admin/users/edit.html.erb new file mode 100644 index 000000000..363be9579 --- /dev/null +++ b/app/views/admin/users/edit.html.erb @@ -0,0 +1,2 @@ +

Admin::Users#edit

+

Find me in app/views/admin/users/edit.html.erb

diff --git a/app/views/admin/users/index.html.erb b/app/views/admin/users/index.html.erb new file mode 100644 index 000000000..d93315d3d --- /dev/null +++ b/app/views/admin/users/index.html.erb @@ -0,0 +1,10 @@ +

Admin::Users#index

+ + <%= button_to( + @user.admin? ? "Make User" : "Make Admin", + admin_toggle_user_role_path(@user), + method: :patch, + class: @user.admin? ? "btn btn-sm btn-warning" : "btn btn-sm btn-success", + ) %> + + diff --git a/app/views/admin/users/new.html.erb b/app/views/admin/users/new.html.erb new file mode 100644 index 000000000..d380347ba --- /dev/null +++ b/app/views/admin/users/new.html.erb @@ -0,0 +1,2 @@ +

Admin::Users#new

+

Find me in app/views/admin/users/new.html.erb

diff --git a/app/views/admin/users/show.html.erb b/app/views/admin/users/show.html.erb new file mode 100644 index 000000000..9ce4ddb33 --- /dev/null +++ b/app/views/admin/users/show.html.erb @@ -0,0 +1,2 @@ +

Admin::Users#show

+

Find me in app/views/admin/users/show.html.erb

diff --git a/app/views/admin/users/update.html.erb b/app/views/admin/users/update.html.erb new file mode 100644 index 000000000..2851bd886 --- /dev/null +++ b/app/views/admin/users/update.html.erb @@ -0,0 +1,2 @@ +

Admin::Users#update

+

Find me in app/views/admin/users/update.html.erb

diff --git a/config/routes.rb b/config/routes.rb index 0fcb6eee1..0cdcee311 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -6,6 +6,13 @@ # Can be used by load balancers and uptime monitors to verify that the app is live. namespace :admin do + get "users/index" + get "users/show" + get "users/new" + get "users/create" + get "users/edit" + get "users/update" + get "users/destroy" get "dashboard/show" get "dashboard", to: "dashboard#show" diff --git a/test/controllers/admin/users_controller_test.rb b/test/controllers/admin/users_controller_test.rb new file mode 100644 index 000000000..6fc82174c --- /dev/null +++ b/test/controllers/admin/users_controller_test.rb @@ -0,0 +1,38 @@ +require "test_helper" + +class Admin::UsersControllerTest < ActionDispatch::IntegrationTest + test "should get index" do + get admin_users_index_url + assert_response :success + end + + test "should get show" do + get admin_users_show_url + assert_response :success + end + + test "should get new" do + get admin_users_new_url + assert_response :success + end + + test "should get create" do + get admin_users_create_url + assert_response :success + end + + test "should get edit" do + get admin_users_edit_url + assert_response :success + end + + test "should get update" do + get admin_users_update_url + assert_response :success + end + + test "should get destroy" do + get admin_users_destroy_url + assert_response :success + end +end From d1deb389badf4a9e9257148eab6cc391b476c367 Mon Sep 17 00:00:00 2001 From: vitaotm Date: Mon, 3 Nov 2025 17:21:35 -0300 Subject: [PATCH 06/17] Build user profile management page --- app/controllers/profiles_controller.rb | 36 ++++++++++ app/helpers/profiles_helper.rb | 2 + app/views/profiles/destroy.html.erb | 2 + app/views/profiles/edit.html.erb | 72 ++++++++++++++++++++ app/views/profiles/show.html.erb | 24 +++++++ app/views/profiles/update.html.erb | 2 + config/routes.rb | 4 ++ test/controllers/profiles_controller_test.rb | 23 +++++++ 8 files changed, 165 insertions(+) create mode 100644 app/controllers/profiles_controller.rb create mode 100644 app/helpers/profiles_helper.rb create mode 100644 app/views/profiles/destroy.html.erb create mode 100644 app/views/profiles/edit.html.erb create mode 100644 app/views/profiles/show.html.erb create mode 100644 app/views/profiles/update.html.erb create mode 100644 test/controllers/profiles_controller_test.rb diff --git a/app/controllers/profiles_controller.rb b/app/controllers/profiles_controller.rb new file mode 100644 index 000000000..fc697b385 --- /dev/null +++ b/app/controllers/profiles_controller.rb @@ -0,0 +1,36 @@ +class ProfilesController < ApplicationController + before_action :set_user_profile + + def show + authorize @user_profile + end + + def edit + authorize @user_profile + end + + def update + authorize @user_profile + if @user_profile.update(profile_params) + redirect_to profile_path, notice: "Profile updated" + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + authorize @user_profile + @user_profile.destroy + redirect_to root_path, notice: "Your account has been deleted." + end + + private + + def set_user_profile + @user_profile = current_user + end + + def profile_params + params.require(:user).permit(:full_name, :email, :password, :password_confirmation, :avatar_image, :avatar_url) + end +end diff --git a/app/helpers/profiles_helper.rb b/app/helpers/profiles_helper.rb new file mode 100644 index 000000000..4e430508f --- /dev/null +++ b/app/helpers/profiles_helper.rb @@ -0,0 +1,2 @@ +module ProfilesHelper +end diff --git a/app/views/profiles/destroy.html.erb b/app/views/profiles/destroy.html.erb new file mode 100644 index 000000000..c6bd7c169 --- /dev/null +++ b/app/views/profiles/destroy.html.erb @@ -0,0 +1,2 @@ +

Profiles#destroy

+

Find me in app/views/profiles/destroy.html.erb

diff --git a/app/views/profiles/edit.html.erb b/app/views/profiles/edit.html.erb new file mode 100644 index 000000000..85bbc006a --- /dev/null +++ b/app/views/profiles/edit.html.erb @@ -0,0 +1,72 @@ +

Edit My Profile

+ +<%= form_with(model: @user_profile, url: profile_path, method: :patch) do |f| %> + <% if @user_profile.errors.any? %> +
+

<%= pluralize(@user_profile.errors.count, "error") %> + prohibited this profile from being saved:

+
    + <% @user_profile.errors.each do |error| %> +
  • <%= error.full_message %>
  • + <% end %> +
+
+ <% end %> + +
+ <%= f.label :full_name, class: "form-label" %> + <%= f.text_field :full_name, class: "form-control" %> +
+ +
+ <%= f.label :email, class: "form-label" %> + <%= f.email_field :email, class: "form-control" %> +
+ +
+ <%= f.label :avatar_image, "Upload New Avatar", class: "form-label" %> + <%= f.file_field :avatar_image, class: "form-control" %> +
+ +
+ <%= f.label :avatar_url, "Or paste Avatar URL", class: "form-label" %> + <%= f.url_field :avatar_url, class: "form-control", placeholder: "https://..." %> +
+ +
+

Leave fields below blank if you don't want to change your password.

+ +
+ <%= f.label :password, class: "form-label" %> + <%= f.password_field :password, class: "form-control", autocomplete: "new-password" %> + <% if @minimum_password_length %> +
<%= @minimum_password_length %> + characters minimum
+ <% end %> +
+ +
+ <%= f.label :password_confirmation, class: "form-label" %> + <%= f.password_field :password_confirmation, + class: "form-control", + autocomplete: "new-password" %> +
+ +
+ <%= f.submit "Update Profile", class: "btn btn-primary" %> +
+<% end %> + +
+ +
+

Delete Account

+

This action is permanent and cannot be undone.

+ <%= button_to "Delete My Account", + profile_path, + method: :delete, + data: { + turbo_confirm: "Are you sure you want to delete your account?", + }, + class: "btn btn-danger" %> +
diff --git a/app/views/profiles/show.html.erb b/app/views/profiles/show.html.erb new file mode 100644 index 000000000..f4f0eeb25 --- /dev/null +++ b/app/views/profiles/show.html.erb @@ -0,0 +1,24 @@ +

My Profile

+
+
+
+ <% if @user_profile.avatar_image.attached? %> + <%= image_tag @user_profile.avatar_image, class: "img-fluid rouded-start" %> + <% else %> + + <% end %> +
+
+
+
<%= @user_profile.full_name %>
+

+ <%= @user_profile.email %> +

+

+ Role:<%= @user_profile.role.humanize %> +

+ <%= link_to "Edit my profile", edit_profile_path, class: "btn btn-primary" %> +
+
+
+
diff --git a/app/views/profiles/update.html.erb b/app/views/profiles/update.html.erb new file mode 100644 index 000000000..03471d8d4 --- /dev/null +++ b/app/views/profiles/update.html.erb @@ -0,0 +1,2 @@ +

Profiles#update

+

Find me in app/views/profiles/update.html.erb

diff --git a/config/routes.rb b/config/routes.rb index 0cdcee311..a477f1915 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,4 +1,8 @@ Rails.application.routes.draw do + get "profiles/show" + get "profiles/edit" + get "profiles/update" + get "profiles/destroy" devise_for :users # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html diff --git a/test/controllers/profiles_controller_test.rb b/test/controllers/profiles_controller_test.rb new file mode 100644 index 000000000..3ce205010 --- /dev/null +++ b/test/controllers/profiles_controller_test.rb @@ -0,0 +1,23 @@ +require "test_helper" + +class ProfilesControllerTest < ActionDispatch::IntegrationTest + test "should get show" do + get profiles_show_url + assert_response :success + end + + test "should get edit" do + get profiles_edit_url + assert_response :success + end + + test "should get update" do + get profiles_update_url + assert_response :success + end + + test "should get destroy" do + get profiles_destroy_url + assert_response :success + end +end From b2d0541729a1a4c059a8d1b21e3c95ec2c578352 Mon Sep 17 00:00:00 2001 From: vitaotm Date: Mon, 3 Nov 2025 22:48:44 -0300 Subject: [PATCH 07/17] Implement realtime user imports with sidekiq --- Gemfile | 2 + Gemfile.lock | 3 + Procfile.dev | 4 ++ .../{application.css => application.scss} | 0 .../admin/user_imports_controller.rb | 26 +++++++++ app/helpers/admin/user_imports_helper.rb | 2 + app/jobs/import_users_job.rb | 52 ++++++++++++++++++ app/models/user_import.rb | 8 +++ .../admin/user_imports/_progress.html.erb | 20 +++++++ app/views/admin/user_imports/create.html.erb | 2 + app/views/admin/user_imports/new.html.erb | 2 + app/views/admin/user_imports/show.html.erb | 14 +++++ config/application.rb | 1 + config/routes.rb | 3 + .../20251103204435_create_user_imports.rb | 12 ++++ db/schema.rb | 11 +++- dump.rdb | Bin 0 -> 514 bytes .../admin/user_imports_controller_test.rb | 18 ++++++ test/fixtures/user_imports.yml | 13 +++++ test/jobs/import_users_job_test.rb | 7 +++ test/models/user_import_test.rb | 7 +++ 21 files changed, 206 insertions(+), 1 deletion(-) create mode 100644 Procfile.dev rename app/assets/stylesheets/{application.css => application.scss} (100%) create mode 100644 app/controllers/admin/user_imports_controller.rb create mode 100644 app/helpers/admin/user_imports_helper.rb create mode 100644 app/jobs/import_users_job.rb create mode 100644 app/models/user_import.rb create mode 100644 app/views/admin/user_imports/_progress.html.erb create mode 100644 app/views/admin/user_imports/create.html.erb create mode 100644 app/views/admin/user_imports/new.html.erb create mode 100644 app/views/admin/user_imports/show.html.erb create mode 100644 db/migrate/20251103204435_create_user_imports.rb create mode 100644 dump.rdb create mode 100644 test/controllers/admin/user_imports_controller_test.rb create mode 100644 test/fixtures/user_imports.yml create mode 100644 test/jobs/import_users_job_test.rb create mode 100644 test/models/user_import_test.rb diff --git a/Gemfile b/Gemfile index 6bdb2375a..411f9436c 100644 --- a/Gemfile +++ b/Gemfile @@ -67,3 +67,5 @@ gem "pundit", "~> 2.5" gem "sidekiq", "~> 8.0" gem "roo", "~> 3.0" gem "down", "~> 5.4" + +gem "foreman", "~> 0.90.0" diff --git a/Gemfile.lock b/Gemfile.lock index 0a85ddfc9..52b999034 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -118,6 +118,8 @@ GEM erubi (1.13.1) et-orbi (1.4.0) tzinfo + foreman (0.90.0) + thor (~> 1.4) fugit (1.12.1) et-orbi (~> 1.4) raabro (~> 1.4) @@ -399,6 +401,7 @@ DEPENDENCIES debug devise (~> 4.9) down (~> 5.4) + foreman (~> 0.90.0) importmap-rails jbuilder kamal diff --git a/Procfile.dev b/Procfile.dev new file mode 100644 index 000000000..09df3acb1 --- /dev/null +++ b/Procfile.dev @@ -0,0 +1,4 @@ +web: bin/rails s -p 3000 +sidekiq: bundle exec sidekiq +redis: redis-server +css: tailwindcss:watch diff --git a/app/assets/stylesheets/application.css b/app/assets/stylesheets/application.scss similarity index 100% rename from app/assets/stylesheets/application.css rename to app/assets/stylesheets/application.scss diff --git a/app/controllers/admin/user_imports_controller.rb b/app/controllers/admin/user_imports_controller.rb new file mode 100644 index 000000000..9bce858ac --- /dev/null +++ b/app/controllers/admin/user_imports_controller.rb @@ -0,0 +1,26 @@ +class Admin::UserImportsController < Admin::BaseController + def new + @user_import = UserImport.new + end + + def create + @user_import = UserImport.new + + if @user_import.save + ImportUsersJob.perform_later(@user_import_params) + redirect_to admin_user_import_path(@user_import), notice: "Import started." + else + render :new, status: :unprocessable_entity + end + end + + def show + @user_import = UserImport.find(params[:id]) + end + + private + + def user_import_params + params.require(:user_import).permit(:file) + end +end diff --git a/app/helpers/admin/user_imports_helper.rb b/app/helpers/admin/user_imports_helper.rb new file mode 100644 index 000000000..55c4d9ab8 --- /dev/null +++ b/app/helpers/admin/user_imports_helper.rb @@ -0,0 +1,2 @@ +module Admin::UserImportsHelper +end diff --git a/app/jobs/import_users_job.rb b/app/jobs/import_users_job.rb new file mode 100644 index 000000000..1f9d93cdc --- /dev/null +++ b/app/jobs/import_users_job.rb @@ -0,0 +1,52 @@ +class ImportUsersJob < ApplicationJob + queue_as :default + + def perform(user_import_id) + user_import = UserImport.find(user_import_id) + user_import.update!(status: :processing, processed_count: 0, error_log: "") + + user_import.broadcast_replace_to user_import, target: "user_import_status" + + errors = [] + processed = 0 + + begin + spreadsheet = Roo::Spreadsheet.open(user_import.file.download, extension: :xlsx) # or :csv + user_import.update!(total_count: spreadsheet.last_row - 1) # -1 for header + + spreadsheet.each_with_index do |row, idx| + next if idx == 0 # Skip header row + + full_name, email = row[0], row[1] # Assuming Col A = Name, Col B = Email + + user = User.new( + full_name: full_name, + email: email, + password: SecureRandom.hex(10) # Assign a random password + ) + + if user.save + processed += 1 + else + errors << "Row #{idx + 1}: #{user.errors.full_messages.join(', ')}" + end + + if processed % 10 == 0 || idx == spreadsheet.last_row - 1 + user_import.update!(processed_count: processed) + user_import.broadcast_update_to( + user_import, + target: "import_progress_bar", + partial: "admin/user_imports/progress", + locals: { import: user_import } + ) + end + end + + user_import.update!(status: :completed, error_log: errors.join("\n")) + rescue => e + user_import.update!(status: :failed, error_log: "Fatal error: #{e.message}") + end + + user_import.broadcast_replace_to user_import, target: "user_import_status" + end +end diff --git a/app/models/user_import.rb b/app/models/user_import.rb new file mode 100644 index 000000000..faedb8661 --- /dev/null +++ b/app/models/user_import.rb @@ -0,0 +1,8 @@ +class UserImport < ApplicationRecord + include Turbo::Broadcastable + + has_one_attached :file + + enum :status, { pending: 0, processing: 1, completed: 2, failed: 3 } + validates :file, presence: true +end diff --git a/app/views/admin/user_imports/_progress.html.erb b/app/views/admin/user_imports/_progress.html.erb new file mode 100644 index 000000000..314cc59bb --- /dev/null +++ b/app/views/admin/user_imports/_progress.html.erb @@ -0,0 +1,20 @@ +<% total = import.total_count.to_i +processed = import.processed_count.to_i +percentage = total.zero? ? 0 : (processed.to_f / total * 100).round %> + +<%= processed %> + / + <%= total %> + Users Imported +
+
+ <%= percentage %>% +
+
diff --git a/app/views/admin/user_imports/create.html.erb b/app/views/admin/user_imports/create.html.erb new file mode 100644 index 000000000..d79361add --- /dev/null +++ b/app/views/admin/user_imports/create.html.erb @@ -0,0 +1,2 @@ +

Admin::UserImports#create

+

Find me in app/views/admin/user_imports/create.html.erb

diff --git a/app/views/admin/user_imports/new.html.erb b/app/views/admin/user_imports/new.html.erb new file mode 100644 index 000000000..1e7e27e1d --- /dev/null +++ b/app/views/admin/user_imports/new.html.erb @@ -0,0 +1,2 @@ +

Admin::UserImports#new

+

Find me in app/views/admin/user_imports/new.html.erb

diff --git a/app/views/admin/user_imports/show.html.erb b/app/views/admin/user_imports/show.html.erb new file mode 100644 index 000000000..13748b62c --- /dev/null +++ b/app/views/admin/user_imports/show.html.erb @@ -0,0 +1,14 @@ +

Import Progress

+<%= turbo_stream_from @user_import %> + +<%= turbo_frame_tag "user_import_status" do %> +

Status: + <%= @user_import.status.humanize %>

+<% end %> + +<%= turbo_frame_tag "inport_progress_bar" do %> + <%= render "progress", import: @user_import %> +<% end %> + +

Error Log:

+
<%= @user_import.error_log.presence || "No errors." %>
diff --git a/config/application.rb b/config/application.rb index 554285b9d..444f7ffde 100644 --- a/config/application.rb +++ b/config/application.rb @@ -23,5 +23,6 @@ class Application < Rails::Application # # config.time_zone = "Central Time (US & Canada)" # config.eager_load_paths << Rails.root.join("extras") + config.active_job.queue_adapter = :sidekiq end end diff --git a/config/routes.rb b/config/routes.rb index a477f1915..3f8c4fcde 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -10,6 +10,9 @@ # Can be used by load balancers and uptime monitors to verify that the app is live. namespace :admin do + get "user_imports/new" + get "user_imports/create" + get "user_imports/show" get "users/index" get "users/show" get "users/new" diff --git a/db/migrate/20251103204435_create_user_imports.rb b/db/migrate/20251103204435_create_user_imports.rb new file mode 100644 index 000000000..d1fa7150d --- /dev/null +++ b/db/migrate/20251103204435_create_user_imports.rb @@ -0,0 +1,12 @@ +class CreateUserImports < ActiveRecord::Migration[8.0] + def change + create_table :user_imports do |t| + t.integer :status + t.integer :processed_count + t.integer :total_count + t.text :error_log + + t.timestamps + end + end +end diff --git a/db/schema.rb b/db/schema.rb index 4b6e9e447..4a7d9dc6e 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[8.0].define(version: 2025_11_03_032728) do +ActiveRecord::Schema[8.0].define(version: 2025_11_03_204435) do # These are extensions that must be enabled in order to support this database enable_extension "pg_catalog.plpgsql" @@ -42,6 +42,15 @@ t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true end + create_table "user_imports", force: :cascade do |t| + t.integer "status" + t.integer "processed_count" + t.integer "total_count" + t.text "error_log" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + create_table "users", force: :cascade do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false diff --git a/dump.rdb b/dump.rdb new file mode 100644 index 0000000000000000000000000000000000000000..cc764f9ca0073622287065b9ef0569413674970e GIT binary patch literal 514 zcma*kJ#W)M7zgl6>R3&Rgg_M0DW^j)*_JPf6US4KS}G)_BBlzJv;DX^^=zm2k~XSR z30B0w$^-)&3+zZCe35K&lvb@N69+JJryv`lN4;Lv zl8|!c#$2n#sA?pd=dj$_ZSrc>C`jEL^5u`u>!?~~W#-0A!2fB{A84F&R<7hx>uNy{#4rD`?(G*y4|NPg>_pcwnts!LH`!8WzyvWLL zqwf!z?GrLCl`dEgBqIN4; Date: Tue, 4 Nov 2025 14:18:47 -0300 Subject: [PATCH 08/17] Add tailwind css style to project, - Install tailwind dependencies - Update gitignore file - Update bin/dev file - Adds navbar to application.html.erb - Update gems, adds foreman and a Procfile.dev --- .gitignore | 4 + Gemfile | 2 + Gemfile.lock | 9 + Procfile.dev | 2 +- app/assets/builds/.keep | 0 .../{application.scss => application.css} | 0 app/assets/tailwind/application.css | 85 ++++++ app/views/admin/dashboard/_stats.html.erb | 44 +-- app/views/admin/dashboard/show.html.erb | 16 +- .../admin/user_imports/_progress.html.erb | 13 +- app/views/admin/user_imports/new.html.erb | 20 +- app/views/admin/user_imports/show.html.erb | 29 +- app/views/admin/users/_form.html.erb | 72 +++++ app/views/admin/users/edit.html.erb | 10 +- app/views/admin/users/index.html.erb | 70 ++++- app/views/admin/users/new.html.erb | 10 +- app/views/admin/users/show.html.erb | 62 +++- app/views/devise/passwords/new.html.erb | 32 ++- app/views/devise/registrations/edit.html.erb | 130 +++++---- app/views/devise/registrations/new.html.erb | 99 ++++--- app/views/devise/sessions/new.html.erb | 48 ++-- app/views/devise/shared/_links.html.erb | 54 ++-- app/views/layouts/_navbar.html.erb | 272 ++++++++++++++++++ app/views/layouts/application.html.erb | 10 +- app/views/profiles/edit.html.erb | 128 +++++---- app/views/profiles/show.html.erb | 39 +-- bin/dev | 18 +- dump.rdb | Bin 514 -> 1263 bytes package-lock.json | 203 +++++++++++++ package.json | 5 + yarn.lock | 91 ++++++ 31 files changed, 1283 insertions(+), 294 deletions(-) create mode 100644 app/assets/builds/.keep rename app/assets/stylesheets/{application.scss => application.css} (100%) create mode 100644 app/assets/tailwind/application.css create mode 100644 app/views/admin/users/_form.html.erb create mode 100644 app/views/layouts/_navbar.html.erb create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 yarn.lock diff --git a/.gitignore b/.gitignore index f92525ca5..67cc4ac76 100644 --- a/.gitignore +++ b/.gitignore @@ -30,5 +30,9 @@ /public/assets +/node_modules # Ignore master key for decrypting credentials and more. /config/master.key + +/app/assets/builds/* +!/app/assets/builds/.keep diff --git a/Gemfile b/Gemfile index 411f9436c..19b8762ff 100644 --- a/Gemfile +++ b/Gemfile @@ -69,3 +69,5 @@ gem "roo", "~> 3.0" gem "down", "~> 5.4" gem "foreman", "~> 0.90.0" + +gem "tailwindcss-rails", "~> 4.4" diff --git a/Gemfile.lock b/Gemfile.lock index 52b999034..ebf0df09d 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -352,6 +352,14 @@ GEM stimulus-rails (1.3.4) railties (>= 6.0.0) stringio (3.1.7) + tailwindcss-rails (4.4.0) + railties (>= 7.0.0) + tailwindcss-ruby (~> 4.0) + tailwindcss-ruby (4.1.16) + tailwindcss-ruby (4.1.16-aarch64-linux-gnu) + tailwindcss-ruby (4.1.16-aarch64-linux-musl) + tailwindcss-ruby (4.1.16-x86_64-linux-gnu) + tailwindcss-ruby (4.1.16-x86_64-linux-musl) thor (1.4.0) thruster (0.1.16) thruster (0.1.16-aarch64-linux) @@ -418,6 +426,7 @@ DEPENDENCIES solid_cache solid_queue stimulus-rails + tailwindcss-rails (~> 4.4) thruster turbo-rails tzinfo-data diff --git a/Procfile.dev b/Procfile.dev index 09df3acb1..202bd7cf0 100644 --- a/Procfile.dev +++ b/Procfile.dev @@ -1,4 +1,4 @@ web: bin/rails s -p 3000 sidekiq: bundle exec sidekiq redis: redis-server -css: tailwindcss:watch +css: bin/rails tailwindcss:watch diff --git a/app/assets/builds/.keep b/app/assets/builds/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/assets/stylesheets/application.scss b/app/assets/stylesheets/application.css similarity index 100% rename from app/assets/stylesheets/application.scss rename to app/assets/stylesheets/application.css diff --git a/app/assets/tailwind/application.css b/app/assets/tailwind/application.css new file mode 100644 index 000000000..521f743cb --- /dev/null +++ b/app/assets/tailwind/application.css @@ -0,0 +1,85 @@ +@import "tailwindcss"; + + +@plugin '@tailwindcss/typography'; + + +@layer components { + .red-card { + @apply bg-red-500 my-4 w-3/4 mx-auto p-4; + } + + .red-card p { + @apply text-white text-2xl; + } + + .form-label { + @apply block text-sm font-medium text-gray-700 mb-1; + } + + .form-input { + @apply block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500; + } + + .form-link { + @apply font-medium text-blue-600 hover:text-blue-500; + } + + .file-field { + @apply block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100; + } + + .button { + @apply bg-blue-600 text-white px-5 py-2 rounded-lg hover:bg-blue-700 cursor-pointer; + } + + .button-danger { + @apply w-full bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700; + } + + .title-h1 { + @apply text-3xl font-bold; + } + + .title-h3 { + @apply text-xl font-semibold mb-4; + } + + .title-h5 { + @apply text-lg font-medium text-gray-500 mb-4; + } + + .table-head { + @apply px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider; + } + + .table-data { + @apply px-6 py-4 whitespace-nowrap; + } + + .list-item { + @apply py-3 flex justify-between items-center; + } + + .admin-badge { + @apply px-2 py-1 text-xs font-semibold text-blue-800 bg-blue-100 rounded-full; + } + + .user-badge { + @apply px-2 py-1 text-xs font-semibold text-gray-800 bg-gray-100 rounded-full; + } + + .container-class { + @apply mt-8 sm:mx-auto sm:w-full sm:max-w-md; + } + .card-class { + @apply bg-white py-8 px-4 shadow-md sm:rounded-lg sm:px-10; + } + /* .input_class { */ + /* @apply block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500; */ + /* } */ + /**/ + /* .label-class { */ + /* @apply block text-sm font-medium text-red mb-1; */ + /* } */ +} diff --git a/app/views/admin/dashboard/_stats.html.erb b/app/views/admin/dashboard/_stats.html.erb index 361425494..339d1693d 100644 --- a/app/views/admin/dashboard/_stats.html.erb +++ b/app/views/admin/dashboard/_stats.html.erb @@ -1,24 +1,26 @@ -
-
-
-
Total users
-

<%= total_users %>

-
-
-
-
-
Users by Role
-
    -
  • - Admins - <%= users_by_role["admin"] || 0 %> -
  • -
  • - Users - <%= users_by_role["user"] || 0 %> -
  • -
-
+
+ <%# Total Users Card %> +
+
Total Users
+

<%= total_users %>

+ <%# Users by Role Card %> +
+
Users by Role
+
    +
  • + Admins + + <%= users_by_role["admin"] || 0 %> + +
  • +
  • + Users + + <%= users_by_role["user"] || 0 %> + +
  • +
+
diff --git a/app/views/admin/dashboard/show.html.erb b/app/views/admin/dashboard/show.html.erb index 77a56f32b..6941e3b78 100644 --- a/app/views/admin/dashboard/show.html.erb +++ b/app/views/admin/dashboard/show.html.erb @@ -1,7 +1,9 @@ -

Admin Dashboard#show

-<%= turbo_stream_from "admin_dashboard_stats" %> -<%= turbo_frame_tag "admin_dashboard_stats" do %> - <%= render "admin/dashboard/stats", - total_users: @total_users, - users_by_role: @users_by_role %> -<% end %> +
+

Admin Dashboard

+ <%= turbo_stream_from "admin_dashboard_stats" %> + <%= turbo_frame_tag "admin_dashboard_stats" do %> + <%= render "admin/dashboard/stats", + total_users: @total_users, + users_by_role: @users_by_role %> + <% end %> +
diff --git a/app/views/admin/user_imports/_progress.html.erb b/app/views/admin/user_imports/_progress.html.erb index 314cc59bb..99a6438d2 100644 --- a/app/views/admin/user_imports/_progress.html.erb +++ b/app/views/admin/user_imports/_progress.html.erb @@ -2,18 +2,17 @@ processed = import.processed_count.to_i percentage = total.zero? ? 0 : (processed.to_f / total * 100).round %> -<%= processed %> +<%= processed %> / <%= total %> Users Imported -
+
<%= percentage %>%
diff --git a/app/views/admin/user_imports/new.html.erb b/app/views/admin/user_imports/new.html.erb index 1e7e27e1d..90a10ce07 100644 --- a/app/views/admin/user_imports/new.html.erb +++ b/app/views/admin/user_imports/new.html.erb @@ -1,2 +1,18 @@ -

Admin::UserImports#new

-

Find me in app/views/admin/user_imports/new.html.erb

+
+ +

Import Users

+ +
+ <%= form_with(model: [:admin, @user_import]) do |f| %> +
+ <%= f.label :file, "Upload Spreadsheet (.xlsx, .csv)", class: "form-label" %> + <%= f.file_field :file, + required: true, + class: + "block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100" %> +
+ + <%= f.submit "Start Import", class: "button" %> + <% end %> +
+
diff --git a/app/views/admin/user_imports/show.html.erb b/app/views/admin/user_imports/show.html.erb index 13748b62c..29a9f656a 100644 --- a/app/views/admin/user_imports/show.html.erb +++ b/app/views/admin/user_imports/show.html.erb @@ -1,14 +1,23 @@ -

Import Progress

<%= turbo_stream_from @user_import %> -<%= turbo_frame_tag "user_import_status" do %> -

Status: - <%= @user_import.status.humanize %>

-<% end %> +

Import Progress

-<%= turbo_frame_tag "inport_progress_bar" do %> - <%= render "progress", import: @user_import %> -<% end %> +
+ <%= turbo_frame_tag "user_import_status" do %> +

+ Status: + + <%= @user_import.status.humanize %> + +

+ <% end %> -

Error Log:

-
<%= @user_import.error_log.presence || "No errors." %>
+ <%= turbo_frame_tag "import_progress_bar" do %> + <%= render "progress", import: @user_import %> + <% end %> + +

Error Log:

+
+    <%= @user_import.error_log.presence || "No errors." %>
+  
+
diff --git a/app/views/admin/users/_form.html.erb b/app/views/admin/users/_form.html.erb new file mode 100644 index 000000000..d3e369c02 --- /dev/null +++ b/app/views/admin/users/_form.html.erb @@ -0,0 +1,72 @@ +<%= form_with(model: [:admin, user]) do |f| %> + <% if user.errors.any? %> + + <% end %> + +
+ <%= f.label :full_name, class: "form.label" %> + <%= f.text_field :full_name, class: "form-input" %> +
+ +
+ <%= f.label :email, class: "form.label" %> + <%= f.email_field :email, class: "form-input" %> +
+ +
+ <%= f.label :role, class: "form.label" %> + <%= f.select :role, + User.roles.keys.map { |r| [r.humanize, r] }, + {}, + class: "form-input" %> +
+ +
+ <%= f.label :avatar_image, "Upload New Avatar", class: "form.label" %> + <%= f.file_field :avatar_image, + class: + "block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100" %> +
+ +
+ <%= f.label :avatar_url, "Or paste Avatar URL", class: "form.label" %> + <%= f.url_field :avatar_url, class: "form-input", placeholder: "https://..." %> +
+ +
+ +
+ <%= f.label :password, class: "form.label" %> + <%= f.password_field :password, + class: "form-input", + autocomplete: "new-password", + placeholder: "Leave blank to keep unchanged" %> +
+ +
+ <%= f.label :password_confirmation, class: "form.label" %> + <%= f.password_field :password_confirmation, + class: "form-input", + autocomplete: "new-password" %> +
+ +
+ <%= f.submit "Save User", + class: + "bg-blue-600 text-white px-5 py-2 rounded-lg hover:bg-blue-700 cursor-pointer" %> + <%= link_to "Cancel", admin_users_path, class: "text-gray-600 hover:text-gray-900" %> +
+<% end %> diff --git a/app/views/admin/users/edit.html.erb b/app/views/admin/users/edit.html.erb index 363be9579..32d592c74 100644 --- a/app/views/admin/users/edit.html.erb +++ b/app/views/admin/users/edit.html.erb @@ -1,2 +1,8 @@ -

Admin::Users#edit

-

Find me in app/views/admin/users/edit.html.erb

+
+ +

Edit User

+ +
+ <%= render "form", user: @user %> +
+
diff --git a/app/views/admin/users/index.html.erb b/app/views/admin/users/index.html.erb index d93315d3d..b1446f23d 100644 --- a/app/views/admin/users/index.html.erb +++ b/app/views/admin/users/index.html.erb @@ -1,10 +1,62 @@ -

Admin::Users#index

- - <%= button_to( - @user.admin? ? "Make User" : "Make Admin", - admin_toggle_user_role_path(@user), - method: :patch, - class: @user.admin? ? "btn btn-sm btn-warning" : "btn btn-sm btn-success", - ) %> +
+
+

User Management

+ <%= link_to "New User", + new_admin_user_path, + class: "bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700" %> +
- +
+ + + + + + + + + + + <% @users.each do |user| %> + + + + + + + <% end %> + +
Full NameEmailRoleActions
<%= user.full_name %><%= user.email %> + <% if user.admin? %> + Admin + <% else %> + User + <% end %> + + <%= link_to "View", + admin_user_path(user), + class: "text-blue-600 hover:text-blue-900 mr-3" %> + <%= link_to "Edit", + edit_admin_user_path(user), + class: "text-indigo-600 hover:text-indigo-900 mr-3" %> + + <%= button_to( + user.admin? ? "Make User" : "Make Admin", + admin_toggle_user_role_path(user), + method: :patch, + class: "inline text-yellow-600 hover:text-yellow-900 mr-3", + data: { + turbo_confirm: "Are you sure?", + }, + ) %> + + <%= button_to "Delete", + admin_user_path(user), + method: :delete, + class: "inline text-red-600 hover:text-red-900", + data: { + turbo_confirm: "Are you sure you want to delete this user?", + } %> +
+
+
diff --git a/app/views/admin/users/new.html.erb b/app/views/admin/users/new.html.erb index d380347ba..b29bc0847 100644 --- a/app/views/admin/users/new.html.erb +++ b/app/views/admin/users/new.html.erb @@ -1,2 +1,8 @@ -

Admin::Users#new

-

Find me in app/views/admin/users/new.html.erb

+
+ +

New User

+ +
+ <%= render "form", user: @user %> +
+
diff --git a/app/views/admin/users/show.html.erb b/app/views/admin/users/show.html.erb index 9ce4ddb33..2aa18c78c 100644 --- a/app/views/admin/users/show.html.erb +++ b/app/views/admin/users/show.html.erb @@ -1,2 +1,60 @@ -

Admin::Users#show

-

Find me in app/views/admin/users/show.html.erb

+
+
+

User Details

+ <%= link_to "Back to User List", + admin_users_path, + class: "text-gray-600 hover:text-gray-900" %> +
+ +
+
+
+ <% if @user.avatar_image.attached? %> + <%= image_tag @user.avatar_image, + class: "h-48 w-full object-cover md:h-full md:w-48" %> + <% else %> + Default Avatar + <% end %> +
+
+
<%= @user.full_name %>
+

<%= @user.email %>

+ +

+ Role: + <% if @user.admin? %> + + Admin + + <% else %> + + User + + <% end %> +

+ +
+ <%= link_to "Edit This User", + edit_admin_user_path(@user), + class: + "inline-block bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700 transition-colors" %> +
+
+
+
+ +
diff --git a/app/views/devise/passwords/new.html.erb b/app/views/devise/passwords/new.html.erb index 9b486b81b..cd003a220 100644 --- a/app/views/devise/passwords/new.html.erb +++ b/app/views/devise/passwords/new.html.erb @@ -1,16 +1,20 @@ -

Forgot your password?

+
+

Forgot your password?

+ <%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %> + <%= render "devise/shared/error_messages", resource: resource %> -<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %> - <%= render "devise/shared/error_messages", resource: resource %> +
+ <%= f.label :email, class: "form-label" %> + <%= f.email_field :email, + autofocus: true, + autocomplete: "email", + class: "form-input" %> +
+
+
+ <%= f.submit "Send me reset password instructions", class: "button" %> +
+ <% end %> -
- <%= f.label :email %>
- <%= f.email_field :email, autofocus: true, autocomplete: "email" %> -
- -
- <%= f.submit "Send me reset password instructions" %> -
-<% end %> - -<%= render "devise/shared/links" %> + <%= render "devise/shared/links" %> +
diff --git a/app/views/devise/registrations/edit.html.erb b/app/views/devise/registrations/edit.html.erb index 78ecd2423..ecd4c7b4b 100644 --- a/app/views/devise/registrations/edit.html.erb +++ b/app/views/devise/registrations/edit.html.erb @@ -1,70 +1,86 @@ -

Edit - <%= resource_name.to_s.humanize %>

+<%# Define Tailwind classes as ERB variables for reuse %> +<% card_class = "bg-white py-8 px-4 shadow-md sm:rounded-lg sm:px-10" %> +<% file_input_class = + "block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100" %> +<% button_class = + "w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 cursor-pointer" %> -<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %> - <%= render "devise/shared/error_messages", resource: resource %> +
+

Edit Account

-
- <%= f.label :email %>
- <%= f.email_field :email, autofocus: true, autocomplete: "email" %> -
+
+ <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %> + <%= render "devise/shared/error_messages", resource: resource %> -
- <%= f.label :full_name %>
- <%= f.text_field :full_name, autofocus: true, autocomplete: "My Name" %> -
+
+ <%= f.label :full_name, class: "form-label" %> + <%= f.text_field :full_name, autofocus: true, class: "form-input" %> +
- <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %> -
Currently waiting confirmation for: - <%= resource.unconfirmed_email %>
- <% end %> +
+ <%= f.label :email, class: "form-label" %> + <%= f.email_field :email, autocomplete: "email", class: "form-input" %> +
-
- <%= f.label :avatar_image %>
- <%= f.file_field :avatar_image, class: "form-control" %> -
+
+ <%= f.label :avatar_image, "Upload Avatar", class: "form-label" %> + <%= f.file_field :avatar_image, class: file_input_class %> +
-
- <%= f.label :avatar_url, class: "form-label" %>
- <%= f.file_field :avatar_url, class: "form-control" %> -
+
+ <%= f.label :avatar_url, "Or paste Avatar URL", class: "form-label" %> + <%= f.url_field :avatar_url, class: "form-input", placeholder: "https://..." %> +
-
- <%= f.label :password %> - (leave blank if you don't want to change it)
- <%= f.password_field :password, autocomplete: "new-password" %> - <% if @minimum_password_length %> -
- <%= @minimum_password_length %> - characters minimum - <% end %> -
+
+

Leave fields below blank if you don't want to change your password.

-
- <%= f.label :password_confirmation %>
- <%= f.password_field :password_confirmation, autocomplete: "new-password" %> -
+
+ <%= f.label :password, class: "form-label" %> + <%= f.password_field :password, autocomplete: "new-password", class: "form-input" %> + <% if @minimum_password_length %> +

(<%= @minimum_password_length %> + characters minimum)

+ <% end %> +
-
- <%= f.label :current_password %> - (we need your current password to confirm your changes)
- <%= f.password_field :current_password, autocomplete: "current-password" %> -
+
+ <%= f.label :password_confirmation, class: "form-label" %> + <%= f.password_field :password_confirmation, + autocomplete: "new-password", + class: "form-input" %> +
-
- <%= f.submit "Update" %> -
-<% end %> +
+

You must provide your current password to save changes.

-

Cancel my account

+
+ <%= f.label :current_password, class: "form-label" %> + <%= f.password_field :current_password, + autocomplete: "current-password", + class: "form-input", + required: true %> +
-
Unhappy? - <%= button_to "Cancel my account", - registration_path(resource_name), - data: { - confirm: "Are you sure?", - turbo_confirm: "Are you sure?", - }, - method: :delete %>
+
+ <%= f.submit "Update Account", class: "button" %> +
+ <% end %> +
-<%= link_to "Back", :back %> +
+

Cancel my account

+

Unhappy? This action is permanent.

+ <%= button_to "Cancel my account", + registration_path(resource_name), + data: { + turbo_confirm: "Are you sure?", + }, + method: :delete, + class: "button-danger" %> +
+ +
+ <%= link_to "Back", :back %> +
+
diff --git a/app/views/devise/registrations/new.html.erb b/app/views/devise/registrations/new.html.erb index 0f7325905..97f2478d7 100644 --- a/app/views/devise/registrations/new.html.erb +++ b/app/views/devise/registrations/new.html.erb @@ -1,45 +1,60 @@ -

Sign up

- -<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> - <%= render "devise/shared/error_messages", resource: resource %> - -
- <%= f.label :full_name %>
- <%= f.text_field :full_name, autofocus: true, autocomplete: "My Name" %> -
- -
- <%= f.label :email %>
- <%= f.email_field :email, autofocus: true, autocomplete: "email" %> +<%# Define Tailwind classes as ERB variables for reuse %> +<% container_class = "" %> +<% file_input_class = + "block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100" %> +<% button_class = + "w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 cursor-pointer" %> + +
+

Sign up

+ +
+ <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> + <%= render "devise/shared/error_messages", resource: resource %> + +
+ <%= f.label :full_name, class: "form-label" %> + <%= f.text_field :full_name, autofocus: true, class: "form-input" %> +
+ +
+ <%= f.label :email, class: "form-label" %> + <%= f.email_field :email, autocomplete: "email", class: "form-input" %> +
+ +
+ <%= f.label :avatar_image, "Upload Avatar", class: "form-label" %> + <%= f.file_field :avatar_image, class: file_input_class %> +
+ +
+ <%= f.label :avatar_url, "Or paste Avatar URL", class: "form-label" %> + <%= f.url_field :avatar_url, class: "form-input", placeholder: "https://..." %> +
+ +
+ <%= f.label :password, class: "form-label" %> + <%= f.password_field :password, autocomplete: "new-password", class: "form-input" %> + <% if @minimum_password_length %> +

(<%= @minimum_password_length %> + characters minimum)

+ <% end %> +
+ +
+ <%= f.label :password_confirmation, class: "form-label" %> + <%= f.password_field :password_confirmation, + autocomplete: "new-password", + class: "form-input" %> +
+ +
+ <%= f.submit "Sign up", class: "button" %> +
+ <% end %>
-
- <%= f.label :avatar_image %>
- <%= f.file_field :avatar_image, class: "form-control" %> +
+ <%= render "devise/shared/links" %>
- -
- <%= f.label :avatar_url, class: "form-label" %>
- <%= f.file_field :avatar_url, class: "form-control" %> -
- -
- <%= f.label :password %> - <% if @minimum_password_length %> - (<%= @minimum_password_length %> - characters minimum) - <% end %>
- <%= f.password_field :password, autocomplete: "new-password" %> -
- -
- <%= f.label :password_confirmation %>
- <%= f.password_field :password_confirmation, autocomplete: "new-password" %> -
- -
- <%= f.submit "Sign up" %> -
-<% end %> - -<%= render "devise/shared/links" %> +
diff --git a/app/views/devise/sessions/new.html.erb b/app/views/devise/sessions/new.html.erb index 5ede96489..a35ecab05 100644 --- a/app/views/devise/sessions/new.html.erb +++ b/app/views/devise/sessions/new.html.erb @@ -1,26 +1,32 @@ -

Log in

+
+

Log in

+
+ <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %> + <%= f.label :email, class: "form-label" %> + <%= f.email_field :email, + autofocus: true, + autocomplete: "email", + class: "form-input" %> -<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %> -
- <%= f.label :email %>
- <%= f.email_field :email, autofocus: true, autocomplete: "email" %> -
+
+ <%= f.label :password, class: "form-label" %> + <%= f.password_field :password, + autocomplete: "current-password", + class: "form-input" %> +
-
- <%= f.label :password %>
- <%= f.password_field :password, autocomplete: "current-password" %> -
+ <% if devise_mapping.rememberable? %> +
+ <%= f.check_box :remember_me %> + <%= f.label :remember_me %> +
+ <% end %> - <% if devise_mapping.rememberable? %> -
- <%= f.check_box :remember_me %> - <%= f.label :remember_me %> -
- <% end %> +
+ <%= f.submit "Log in", class: "button" %> +
+ <% end %> -
- <%= f.submit "Log in" %>
-<% end %> - -<%= render "devise/shared/links" %> + <%= render "devise/shared/links" %> +
diff --git a/app/views/devise/shared/_links.html.erb b/app/views/devise/shared/_links.html.erb index 7a75304ba..ad55b6e9e 100644 --- a/app/views/devise/shared/_links.html.erb +++ b/app/views/devise/shared/_links.html.erb @@ -1,25 +1,43 @@ -<%- if controller_name != 'sessions' %> - <%= link_to "Log in", new_session_path(resource_name) %>
-<% end %> +
-<%- if devise_mapping.registerable? && controller_name != 'registrations' %> - <%= link_to "Sign up", new_registration_path(resource_name) %>
-<% end %> + <%- if controller_name != 'sessions' %> + <%= link_to "Log in", new_session_path(resource_name), class: "form-link" %> + <% end %> -<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %> - <%= link_to "Forgot your password?", new_password_path(resource_name) %>
-<% end %> + <%- if devise_mapping.registerable? && controller_name != 'registrations' %> + <%= link_to "Sign up", new_registration_path(resource_name), class: "form-link" %> + <% end %> -<%- if devise_mapping.confirmable? && controller_name != 'confirmations' %> - <%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %>
-<% end %> + <%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %> + <%= link_to "Forgot your password?", + new_password_path(resource_name), + class: "form-link" %> + <% end %> -<%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %> - <%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %>
-<% end %> + <%- if devise_mapping.confirmable? && controller_name != 'confirmations' %> + <%= link_to "Didn't receive confirmation instructions?", + new_confirmation_path(resource_name), + class: "form-link" %> + <% end %> -<%- if devise_mapping.omniauthable? %> - <%- resource_class.omniauth_providers.each do |provider| %> - <%= button_to "Sign in with #{OmniAuth::Utils.camelize(provider)}", omniauth_authorize_path(resource_name, provider), data: { turbo: false } %>
+ <%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %> + <%= link_to "Didn't receive unlock instructions?", + new_unlock_path(resource_name), + class: "form-link" %> <% end %> + +
+ +<%- if devise_mapping.omniauthable? %> +
+ <%- resource_class.omniauth_providers.each do |provider| %> + <%= button_to "Sign in with #{OmniAuth::Utils.camelize(provider)}", + omniauth_authorize_path(resource_name, provider), + data: { + turbo: false, + }, + class: + "w-full flex justify-center py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500" %> + <% end %> +
<% end %> diff --git a/app/views/layouts/_navbar.html.erb b/app/views/layouts/_navbar.html.erb new file mode 100644 index 000000000..52bf928ae --- /dev/null +++ b/app/views/layouts/_navbar.html.erb @@ -0,0 +1,272 @@ + + +<%#
%> diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 88e6744a5..6fb1596b0 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -7,6 +7,7 @@ <%= csrf_meta_tags %> <%= csp_meta_tag %> + <%= stylesheet_link_tag "tailwind", "data-turbo-track": "reload" %> <%= yield :head %> @@ -20,9 +21,16 @@ <%# Includes all stylesheet files in app/assets/stylesheets %> <%= stylesheet_link_tag :app, "data-turbo-track": "reload" %> <%= javascript_importmap_tags %> + - <%= yield %> + <%= render "layouts/navbar" %> +
+ <%= yield %> +
diff --git a/app/views/profiles/edit.html.erb b/app/views/profiles/edit.html.erb index 85bbc006a..032d17869 100644 --- a/app/views/profiles/edit.html.erb +++ b/app/views/profiles/edit.html.erb @@ -1,72 +1,80 @@ -

Edit My Profile

+
-<%= form_with(model: @user_profile, url: profile_path, method: :patch) do |f| %> - <% if @user_profile.errors.any? %> -
-

<%= pluralize(@user_profile.errors.count, "error") %> - prohibited this profile from being saved:

-
    - <% @user_profile.errors.each do |error| %> -
  • <%= error.full_message %>
  • - <% end %> -
-
- <% end %> +

Edit My Profile

+
+ <%= form_with(model: @user_profile, url: profile_path, method: :patch) do |f| %> + <% if @user_profile.errors.any? %> + + <% end %> -
- <%= f.label :full_name, class: "form-label" %> - <%= f.text_field :full_name, class: "form-control" %> -
+
+ <%= f.label :full_name, class: "form-label" %> + <%= f.text_field :full_name, class: "form-input" %> +
-
- <%= f.label :email, class: "form-label" %> - <%= f.email_field :email, class: "form-control" %> -
+
+ <%= f.label :email, class: "form-label" %> + <%= f.email_field :email, class: "form-input" %> +
-
- <%= f.label :avatar_image, "Upload New Avatar", class: "form-label" %> - <%= f.file_field :avatar_image, class: "form-control" %> -
+
+ <%= f.label :avatar_image, "Upload New Avatar", class: "form-label" %> + <%= f.file_field :avatar_image, class: "file-field" %> +
-
- <%= f.label :avatar_url, "Or paste Avatar URL", class: "form-label" %> - <%= f.url_field :avatar_url, class: "form-control", placeholder: "https://..." %> -
+
+ <%= f.label :avatar_url, "Or paste Avatar URL", class: "form-label" %> + <%= f.url_field :avatar_url, class: "form-input", placeholder: "https://..." %> +
-
-

Leave fields below blank if you don't want to change your password.

+
+

Leave fields below blank if you don't want to change your password.

-
- <%= f.label :password, class: "form-label" %> - <%= f.password_field :password, class: "form-control", autocomplete: "new-password" %> - <% if @minimum_password_length %> -
<%= @minimum_password_length %> - characters minimum
+
+ <%= f.label :password, class: "form-label" %> + <%= f.password_field :password, class: "form-input", autocomplete: "new-password" %> + <% if @minimum_password_length %> +
<%= @minimum_password_length %> + characters minimum
+ <% end %> +
+ +
+ <%= f.label :password_confirmation, class: "form-label" %> + <%= f.password_field :password_confirmation, + class: "form-input", + autocomplete: "new-password" %> +
+ +
+ <%= f.submit "Update Profile", class: "button" %> +
<% end %> -
-
- <%= f.label :password_confirmation, class: "form-label" %> - <%= f.password_field :password_confirmation, - class: "form-control", - autocomplete: "new-password" %>
+
-
- <%= f.submit "Update Profile", class: "btn btn-primary" %> +
+

Delete Account

+

This action is permanent and cannot be undone.

+ <%= button_to "Delete My Account", + profile_path, + method: :delete, + data: { + turbo_confirm: "Are you sure you want to delete your account?", + }, + class: "bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700" %>
-<% end %> - -
- -
-

Delete Account

-

This action is permanent and cannot be undone.

- <%= button_to "Delete My Account", - profile_path, - method: :delete, - data: { - turbo_confirm: "Are you sure you want to delete your account?", - }, - class: "btn btn-danger" %> -
diff --git a/app/views/profiles/show.html.erb b/app/views/profiles/show.html.erb index f4f0eeb25..383f79143 100644 --- a/app/views/profiles/show.html.erb +++ b/app/views/profiles/show.html.erb @@ -1,23 +1,30 @@ -

My Profile

-
-
-
- <% if @user_profile.avatar_image.attached? %> - <%= image_tag @user_profile.avatar_image, class: "img-fluid rouded-start" %> - <% else %> - - <% end %> -
-
-
-
<%= @user_profile.full_name %>
-

+

+

My Profile

+
+
+
+ <% if @user_profile.avatar_image.attached? %> + <%= image_tag @user_profile.avatar_image, + class: "h-48 w-full object-cover md:h-full md:w-48" %> + <% else %> + + <% end %> +
+
+
<%= @user_profile.full_name %>
+

<%= @user_profile.email %>

-

+

Role:<%= @user_profile.role.humanize %>

- <%= link_to "Edit my profile", edit_profile_path, class: "btn btn-primary" %> + <%= link_to "Edit my profile", + edit_profile_path, + class: + "mt-6 inline-block bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors" %>
diff --git a/bin/dev b/bin/dev index 5f91c2054..ad72c7d53 100755 --- a/bin/dev +++ b/bin/dev @@ -1,2 +1,16 @@ -#!/usr/bin/env ruby -exec "./bin/rails", "server", *ARGV +#!/usr/bin/env sh + +if ! gem list foreman -i --silent; then + echo "Installing foreman..." + gem install foreman +fi + +# Default to port 3000 if not specified +export PORT="${PORT:-3000}" + +# Let the debug gem allow remote connections, +# but avoid loading until `debugger` is called +export RUBY_DEBUG_OPEN="true" +export RUBY_DEBUG_LAZY="true" + +exec foreman start -f Procfile.dev "$@" diff --git a/dump.rdb b/dump.rdb index cc764f9ca0073622287065b9ef0569413674970e..e3d84c16ca9030b3dd88dd46154c20148ff81282 100644 GIT binary patch literal 1263 zcmb7^KTH!*9LHbFaYCt32%sdIUe3tWYkGg%-c%9>Q>ngLOgF|hsR|;Ar#(L9T@_xVX`~JS4-_2i|zOs-=h+;id z#`X$Sgfh6jskj(d>LC|QiwIeZl4_>jYf!5IwGT?js`q&WOrZdU+WY=7RPV!1PRL>c zRrCXW9~x-XUdc<30|-S<-`SK@QA{YCqNXc*a%MI&g6Oo_6nD_Lx$P5&dUsVrj^bIxAo>r^PZ!RH-9i?{&1&Y!5} zV^N+^>{2k7Fy(bIsYy~&Nvcv@6eT&GOvWO7$ujvvnHW#;GB?vRtp#;#yb(oF*!yncYw z;BTB{UD3MdsoL!1Y3I?y+kfKe_v^l0ZT_fT(8qHo+`isF@$@y+kxn)b-UFj-JL*Ua z-2l4Zj+^#18`U+9eb)ki+{cXSIc(Wr>QX{d1yK|dN)n?bZf8Gdmj=BMcR$vrk3VrCT2QH`~{gQ zN>H10lu8oQ6= 0.4" + } + }, + "node_modules/is-core-module": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", + "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postcss": { + "version": "8.5.6", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", + "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "peer": true, + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-import": { + "version": "16.1.1", + "resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-16.1.1.tgz", + "integrity": "sha512-2xVS1NCZAfjtVdvXiyegxzJ447GyqCeEI5V7ApgQVOWnros1p5lGNovJNapwPpMombyFBfqDwt7AD3n2l0KOfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.0.0", + "read-cache": "^1.0.0", + "resolve": "^1.1.7" + }, + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "postcss": "^8.0.0" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/read-cache": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", + "integrity": "sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "pify": "^2.3.0" + } + }, + "node_modules/resolve": { + "version": "1.22.11", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz", + "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-core-module": "^2.16.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 000000000..f84aaf706 --- /dev/null +++ b/package.json @@ -0,0 +1,5 @@ +{ + "devDependencies": { + "postcss-import": "^16.1.1" + } +} diff --git a/yarn.lock b/yarn.lock new file mode 100644 index 000000000..1ecaaa1b5 --- /dev/null +++ b/yarn.lock @@ -0,0 +1,91 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +function-bind@^1.1.2: + version "1.1.2" + resolved "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz" + integrity sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA== + +hasown@^2.0.2: + version "2.0.2" + resolved "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz" + integrity sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ== + dependencies: + function-bind "^1.1.2" + +is-core-module@^2.16.1: + version "2.16.1" + resolved "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz" + integrity sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w== + dependencies: + hasown "^2.0.2" + +nanoid@^3.3.11: + version "3.3.11" + resolved "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz" + integrity sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w== + +path-parse@^1.0.7: + version "1.0.7" + resolved "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz" + integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw== + +picocolors@^1.1.1: + version "1.1.1" + resolved "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz" + integrity sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA== + +pify@^2.3.0: + version "2.3.0" + resolved "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz" + integrity sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog== + +postcss-import@^16.1.1: + version "16.1.1" + resolved "https://registry.npmjs.org/postcss-import/-/postcss-import-16.1.1.tgz" + integrity sha512-2xVS1NCZAfjtVdvXiyegxzJ447GyqCeEI5V7ApgQVOWnros1p5lGNovJNapwPpMombyFBfqDwt7AD3n2l0KOfQ== + dependencies: + postcss-value-parser "^4.0.0" + read-cache "^1.0.0" + resolve "^1.1.7" + +postcss-value-parser@^4.0.0: + version "4.2.0" + resolved "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz" + integrity sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ== + +postcss@^8.0.0: + version "8.5.6" + resolved "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz" + integrity sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg== + dependencies: + nanoid "^3.3.11" + picocolors "^1.1.1" + source-map-js "^1.2.1" + +read-cache@^1.0.0: + version "1.0.0" + resolved "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz" + integrity sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA== + dependencies: + pify "^2.3.0" + +resolve@^1.1.7: + version "1.22.11" + resolved "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz" + integrity sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ== + dependencies: + is-core-module "^2.16.1" + path-parse "^1.0.7" + supports-preserve-symlinks-flag "^1.0.0" + +source-map-js@^1.2.1: + version "1.2.1" + resolved "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz" + integrity sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA== + +supports-preserve-symlinks-flag@^1.0.0: + version "1.0.0" + resolved "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz" + integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w== From 43e69bdeb0a4f4c57e0d02d206cd87b4069dc478 Mon Sep 17 00:00:00 2001 From: vitaotm Date: Tue, 4 Nov 2025 15:15:13 -0300 Subject: [PATCH 09/17] Update routes - Fix #update on profiles controller --- app/controllers/profiles_controller.rb | 19 +++++---- .../controllers/remove_element_controller.js | 19 +++++++++ app/views/layouts/_flash.html.erb | 38 ++++++++++++++++++ app/views/layouts/application.html.erb | 1 + config/routes.rb | 2 +- dump.rdb | Bin 1263 -> 1620 bytes 6 files changed, 70 insertions(+), 9 deletions(-) create mode 100644 app/javascript/controllers/remove_element_controller.js create mode 100644 app/views/layouts/_flash.html.erb diff --git a/app/controllers/profiles_controller.rb b/app/controllers/profiles_controller.rb index fc697b385..3a226c9fb 100644 --- a/app/controllers/profiles_controller.rb +++ b/app/controllers/profiles_controller.rb @@ -11,19 +11,22 @@ def edit def update authorize @user_profile - if @user_profile.update(profile_params) - redirect_to profile_path, notice: "Profile updated" + + params_to_update = profile_params + + if params_to_update[:password].blank? + params_to_update.delete(:password) + params_to_update.delete(:password_confirmation) + end + + if @user_profile.update(params_to_update) + bypass_sign_in(@user_profile) if params_to_update[:password].present? + redirect_to profile_path, notice: "Profile updated." else render :edit, status: :unprocessable_entity end end - def destroy - authorize @user_profile - @user_profile.destroy - redirect_to root_path, notice: "Your account has been deleted." - end - private def set_user_profile diff --git a/app/javascript/controllers/remove_element_controller.js b/app/javascript/controllers/remove_element_controller.js new file mode 100644 index 000000000..2715f4acf --- /dev/null +++ b/app/javascript/controllers/remove_element_controller.js @@ -0,0 +1,19 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + static values = { + delay: { type: Number, default: 3000 } + } + + connect() { + if (this.hasDelayValue) { + setTimeout(() => { + this.remove() + }, this.delayValue) + } + } + + remove() { + this.element.remove() + } +} diff --git a/app/views/layouts/_flash.html.erb b/app/views/layouts/_flash.html.erb new file mode 100644 index 000000000..8ecb141d8 --- /dev/null +++ b/app/views/layouts/_flash.html.erb @@ -0,0 +1,38 @@ +<% if notice.present? %> + +<% end %> + +<% if alert.present? %> + +<% end %> diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 6fb1596b0..c0587622d 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -29,6 +29,7 @@ <%= render "layouts/navbar" %> + <%= render "layouts/flash" %>
<%= yield %>
diff --git a/config/routes.rb b/config/routes.rb index 3f8c4fcde..a88278550 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -36,6 +36,6 @@ # get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker # Defines the root path route ("/") - root "admin/dashboard#show" + root "profiles#show" get "up" => "rails/health#show", as: :rails_health_check end diff --git a/dump.rdb b/dump.rdb index e3d84c16ca9030b3dd88dd46154c20148ff81282..2cf0317bf3bd0b446fc460b708c07536a86c273a 100644 GIT binary patch delta 583 zcmaFQd4*?!p~f*guFPK?rNyZ!y1A*jhdOdZ8Gdmj=BMcB<0p2iZu0(SO7W_f-F z?&6Zf605Yt%$(Ge0}PYDFin`O$`UX!)Zb2ot*|t;G__a&WEUetdrE3rVrfnZ$NxWZ zduL;FtkGd32RC^)plTL|ITJTZ3b57W7Rweh0_~Ou+Rex~c`;LvRgy4U0LYyzs%4oa ziTNeDx`{=}89AAGr4?2d7MAE?!^V=CmzICn;iDtxWI0AtGjn4DGd)vasF_*nDDf9$ zrYJ#m=_r*XrYpEIyOrkTD4235XY0D8mZj$87o-*`xKHk43=rJ7pqm38?h4Boj3>Wl zG&B@6G&eIcGPg7YnrmTbVPQtSg?_&`C3K{|*jz02d0OcABHS)Fu}*t+af_q7 zo8WBJMQ{*B#7$=x!BIgCqTv30-|zpwFT7^=;K;R}3*OsWj1qN)u3TJYd%=5~SNGLL zkI@)>f{%_oSA=PPAh}|0;Axtd#DO7fK@B?kqF1wtg)Q4OGGegm*Du|-@f;_jfpu)4 z5`;*zF&^tw8Uaz9giN$CCGwW!ico2Vp={=B%jzUur(wN8oAMOD5vyG%M?0C{xO|vS z;=C+Dw;N&;A#55+STm8PmGw+BiWXYz{18ZMt$;?7?}dyCO~x+fwo;%c+i2EnlrhRK z-OB#<&?rU*wwwZimSIzZ3`+dsbD@~~_l{f;lf@!`6lVEEdY7*WgG#(%X3kOofIb#^ zk>h(oNQr~W$WS3v%X$p>t>g*`wm(0d68K%ZIt*uM)%EP(t!J5l0PHTz{B_n$s& H&b)jB%_)4H From 2b6ac656f64a9fd336484d5d518e8f5cb1bad576 Mon Sep 17 00:00:00 2001 From: vitaotm Date: Tue, 4 Nov 2025 15:38:29 -0300 Subject: [PATCH 10/17] Update gitignore --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 67cc4ac76..bec709b24 100644 --- a/.gitignore +++ b/.gitignore @@ -9,7 +9,7 @@ # Ignore all environment files. /.env* - +/*.rdb # Ignore all logfiles and tempfiles. /log/* /tmp/* From c6d0f5d679b14b8d6336b7804cf166207e1c7ead Mon Sep 17 00:00:00 2001 From: vitaotm Date: Tue, 4 Nov 2025 16:29:10 -0300 Subject: [PATCH 11/17] Fix typo on users controller --- app/controllers/admin/users_controller.rb | 40 ++++++++++++++++------ dump.rdb | Bin 1620 -> 0 bytes 2 files changed, 30 insertions(+), 10 deletions(-) delete mode 100644 dump.rdb diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb index 4c31e0dc7..a4bb13ac9 100644 --- a/app/controllers/admin/users_controller.rb +++ b/app/controllers/admin/users_controller.rb @@ -15,11 +15,11 @@ def new end def create - @user = User.new + @user = User.new(user_params) authorize @user if @user.save - redirect_to admin_user_path(@user), notice: "User created" + redirect_to admin_user_path(@user), notice: "User created." else render :new, status: :unprocessable_entity end @@ -31,8 +31,16 @@ def edit def update authorize @user - if @user.update(user_params) - redirect_to admin_user_path(@user), notice: "User updated" + + # Use the same password-blank-check from the profiles controller + params_to_update = user_params + if params_to_update[:password].blank? + params_to_update.delete(:password) + params_to_update.delete(:password_confirmation) + end + + if @user.update(params_to_update) + redirect_to admin_user_path(@user), notice: "User updated." else render :edit, status: :unprocessable_entity end @@ -41,19 +49,21 @@ def update def destroy authorize @user @user.destroy - redirect_to admin_users_path, notice: "User deleted" + redirect_to admin_users_path, notice: "User deleted." end + # Our custom action def toggle_role - authorize @user, :toggle_role? + authorize @user, :toggle_role? # Specific policy check if @user.admin? - @user.user! + @user.user! # Toggles to user else - @user.admin! + @user.admin! # Toggles to admin end - end + redirect_to admin_users_path, notice: "User role updated." + end private @@ -61,7 +71,17 @@ def set_user @user = User.find(params[:id]) end + # --- THIS IS THE CRITICAL METHOD --- + # Make sure your file has this exact method def user_params - params.require(:user).permit(:full_name, :email, :password, :password_confirmations, :role, :avatar_image, :avatar_url) + params.require(:user).permit( + :full_name, + :email, + :password, + :password_confirmation, + :role, + :avatar_image, + :avatar_url + ) end end diff --git a/dump.rdb b/dump.rdb deleted file mode 100644 index 2cf0317bf3bd0b446fc460b708c07536a86c273a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1620 zcmb7EOHUI~7`+4S$orvyl4v>^1FKFmkIuBr!juGPbfpktq5`?o-onVV19R_G5Lo+K zxzGh@;zl<{j6Z-_O5#6o<%W$b-MG=DHr6{W#X?nJR+E|gecw6fJLis%j$ED)MM)~O zWT7>WmW3>G{LzpU3Kv=&lr*tmm;~oy1%HB=X_WtPsl_ZbxfmsdG)m|1TfLyr1nrby zK#X$W7x>xJRlGHDgMH5c0Qxb3L|<_11j4jLmql3>BuNm%Ie$-c^*i2)jm9PeleC}# zyv&*e+9WMNCoyN48FxvKMu%iY)7!!-8iGnhO^GlyxZ6J1tw~W`QltnJjj$RKmBCW+ z^Xv6%>vVKi$L&>Fl_W8|Dn)cz+EHThK%7qSfoH>%N)}BJ+kvx4*M~FETE2^}*v6^V zG`_ISH*D;7bH0W13{wIf2N~r2`xC&$xz&Gm62d}xY!{ta`!L1nsp~Ukfb9nWo&evI zD!vA$RLplS)$!HzuyTTafoea>_s{D3%EVL9v<~hKfYzEnIZ)hu`gr;@#A3%P* z3cw>Y*7otL*X~Gp=?wLBt+wTNrWoIAQ0oBi?C}9@PgDVUisauabqk{kpP*f>z&-4u zi(G`eJZCWAUJ|9CYmuf>ae8Z`Zj;ox@{SxE3yjgz|8p+uITth3xPgjsi<{poIv$ci zJ3j7Qsa6K#3|rodZ{V*1Jsd^WXJ%6NPVC!ob6|y^voXoQG~#u>u9^=9csFS&l>$Q46Uw)Y?#x?_4mGymt-IDM6mVS#Gp(%(W~|ZB5JzBPfe3djUCIJdm(6 z3Dj*g3A1HIpbq zOv1%?o8P^7)Ugq#iAbfW(ZM)Ro-<%S(MJZri+TP1@@8-EN0!q} cX!Ye)7am#eS+lJseoX1dm#-^lACOPK0YsedBLDyZ From fa32b5d60f162da3fd4adaf0a7c487a5d6aa7994 Mon Sep 17 00:00:00 2001 From: vitaotm Date: Wed, 5 Nov 2025 11:14:48 -0300 Subject: [PATCH 12/17] Add unit tests - Set up docker compose - Update gems for testing --- .rspec | 1 + Gemfile | 10 ++ Gemfile.lock | 43 ++++++ app/controllers/admin/base_controller.rb | 2 +- app/jobs/import_users_job.rb | 24 +++- app/views/admin/user_imports/_status.html.erb | 22 +++ app/views/admin/users/show.html.erb | 1 + config/environments/test.rb | 1 + config/routes.rb | 42 +++--- docker-compose.yml | 44 ++++++ spec/factories/users.rb | 11 ++ spec/fixtures/files/users.xlsx | 0 spec/jobs/import_users_job_spec.rb | 54 ++++++++ spec/models/user_spec.rb | 33 +++++ spec/policies/user_policy_spec.rb | 68 ++++++++++ spec/rails_helper.rb | 77 +++++++++++ spec/requests/admin/users_spec.rb | 53 ++++++++ spec/requests/profiles_spec.rb | 32 +++++ spec/spec_helper.rb | 126 ++++++++++++++++++ spec/system/user_signups_spec.rb | 29 ++++ 20 files changed, 638 insertions(+), 35 deletions(-) create mode 100644 .rspec create mode 100644 app/views/admin/user_imports/_status.html.erb create mode 100644 docker-compose.yml create mode 100644 spec/factories/users.rb create mode 100644 spec/fixtures/files/users.xlsx create mode 100644 spec/jobs/import_users_job_spec.rb create mode 100644 spec/models/user_spec.rb create mode 100644 spec/policies/user_policy_spec.rb create mode 100644 spec/rails_helper.rb create mode 100644 spec/requests/admin/users_spec.rb create mode 100644 spec/requests/profiles_spec.rb create mode 100644 spec/spec_helper.rb create mode 100644 spec/system/user_signups_spec.rb diff --git a/.rspec b/.rspec new file mode 100644 index 000000000..c99d2e739 --- /dev/null +++ b/.rspec @@ -0,0 +1 @@ +--require spec_helper diff --git a/Gemfile b/Gemfile index 19b8762ff..8628d72c4 100644 --- a/Gemfile +++ b/Gemfile @@ -71,3 +71,13 @@ gem "down", "~> 5.4" gem "foreman", "~> 0.90.0" gem "tailwindcss-rails", "~> 4.4" + +# Gemfile +group :development, :test do + gem "rspec-rails" # The main RSpec testing framework + gem "factory_bot_rails" # For creating test data ("factories") + gem "faker" # For generating fake data (names, emails) + gem "shoulda-matchers" # For simple one-line tests (e.g., "validate_presence_of") + gem "rspec-sidekiq" + gem "pundit-matchers", "~>4.0" +end diff --git a/Gemfile.lock b/Gemfile.lock index ebf0df09d..e158b7409 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -109,6 +109,7 @@ GEM railties (>= 4.1.0) responders warden (~> 1.2.3) + diff-lcs (1.6.2) dotenv (3.1.8) down (5.4.2) addressable (~> 2.8) @@ -118,6 +119,13 @@ GEM erubi (1.13.1) et-orbi (1.4.0) tzinfo + factory_bot (6.5.6) + activesupport (>= 6.1.0) + factory_bot_rails (6.5.1) + factory_bot (~> 6.5) + railties (>= 6.1.0) + faker (3.5.2) + i18n (>= 1.8.11, < 2) foreman (0.90.0) thor (~> 1.4) fugit (1.12.1) @@ -222,6 +230,11 @@ GEM nio4r (~> 2.0) pundit (2.5.2) activesupport (>= 3.0.0) + pundit-matchers (4.0.0) + rspec-core (~> 3.12) + rspec-expectations (~> 3.12) + rspec-mocks (~> 3.12) + rspec-support (~> 3.12) raabro (1.4.0) racc (1.8.1) rack (3.2.4) @@ -283,6 +296,28 @@ GEM logger (~> 1) nokogiri (~> 1) rubyzip (>= 3.0.0, < 4.0.0) + rspec-core (3.13.6) + rspec-support (~> 3.13.0) + rspec-expectations (3.13.5) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.13.0) + rspec-mocks (3.13.7) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.13.0) + rspec-rails (8.0.2) + actionpack (>= 7.2) + activesupport (>= 7.2) + railties (>= 7.2) + rspec-core (~> 3.13) + rspec-expectations (~> 3.13) + rspec-mocks (~> 3.13) + rspec-support (~> 3.13) + rspec-sidekiq (5.2.0) + rspec-core (~> 3.0) + rspec-expectations (~> 3.0) + rspec-mocks (~> 3.0) + sidekiq (>= 5, < 9) + rspec-support (3.13.6) rubocop (1.81.7) json (~> 2.3) language_server-protocol (~> 3.17.0.2) @@ -320,6 +355,8 @@ GEM rexml (~> 3.2, >= 3.2.5) rubyzip (>= 1.2.2, < 4.0) websocket (~> 1.0) + shoulda-matchers (7.0.1) + activesupport (>= 7.1) sidekiq (8.0.8) connection_pool (>= 2.5.0) json (>= 2.9.0) @@ -409,6 +446,8 @@ DEPENDENCIES debug devise (~> 4.9) down (~> 5.4) + factory_bot_rails + faker foreman (~> 0.90.0) importmap-rails jbuilder @@ -417,10 +456,14 @@ DEPENDENCIES propshaft puma (>= 5.0) pundit (~> 2.5) + pundit-matchers (~> 4.0) rails (~> 8.0.4) roo (~> 3.0) + rspec-rails + rspec-sidekiq rubocop-rails-omakase selenium-webdriver + shoulda-matchers sidekiq (~> 8.0) solid_cable solid_cache diff --git a/app/controllers/admin/base_controller.rb b/app/controllers/admin/base_controller.rb index 03166097c..6b8c34367 100644 --- a/app/controllers/admin/base_controller.rb +++ b/app/controllers/admin/base_controller.rb @@ -5,7 +5,7 @@ class Admin::BaseController < ApplicationController def require_admin unless current_user.admin? - flash[:notice] = "You must be an admin to access this section" + flash[:alert] = "You must be an admin to access this section." redirect_to profile_path end end diff --git a/app/jobs/import_users_job.rb b/app/jobs/import_users_job.rb index 1f9d93cdc..c857d04ae 100644 --- a/app/jobs/import_users_job.rb +++ b/app/jobs/import_users_job.rb @@ -5,24 +5,29 @@ def perform(user_import_id) user_import = UserImport.find(user_import_id) user_import.update!(status: :processing, processed_count: 0, error_log: "") - user_import.broadcast_replace_to user_import, target: "user_import_status" + user_import.broadcast_replace_to( + user_import, # The stream name + target: "user_import_status", + partial: "admin/user_imports/status", + locals: { user_import: user_import } + ) errors = [] processed = 0 begin - spreadsheet = Roo::Spreadsheet.open(user_import.file.download, extension: :xlsx) # or :csv - user_import.update!(total_count: spreadsheet.last_row - 1) # -1 for header + spreadsheet = Roo::Spreadsheet.open(user_import.file.download, extension: :xlsx) + user_import.update!(total_count: spreadsheet.last_row - 1) spreadsheet.each_with_index do |row, idx| next if idx == 0 # Skip header row - full_name, email = row[0], row[1] # Assuming Col A = Name, Col B = Email + full_name, email = row[0], row[1] user = User.new( full_name: full_name, email: email, - password: SecureRandom.hex(10) # Assign a random password + password: SecureRandom.hex(10) ) if user.save @@ -45,8 +50,13 @@ def perform(user_import_id) user_import.update!(status: :completed, error_log: errors.join("\n")) rescue => e user_import.update!(status: :failed, error_log: "Fatal error: #{e.message}") + ensure + user_import.broadcast_replace_to( + user_import, # The stream name + target: "user_import_status", + partial: "admin/user_imports/status", + locals: { user_import: user_import } + ) end - - user_import.broadcast_replace_to user_import, target: "user_import_status" end end diff --git a/app/views/admin/user_imports/_status.html.erb b/app/views/admin/user_imports/_status.html.erb new file mode 100644 index 000000000..aeb3e5324 --- /dev/null +++ b/app/views/admin/user_imports/_status.html.erb @@ -0,0 +1,22 @@ +<% status_color = + case user_import.status + when "processing" + "bg-blue-600" + when "completed" + "bg-green-600" + when "failed" + "bg-red-600" + else + "bg-gray-500" + end %> +

+ Status: + + <%= user_import.status.humanize %> + +

diff --git a/app/views/admin/users/show.html.erb b/app/views/admin/users/show.html.erb index 2aa18c78c..0ace7742b 100644 --- a/app/views/admin/users/show.html.erb +++ b/app/views/admin/users/show.html.erb @@ -1,3 +1,4 @@ +<%# <% unless current_user.admin? %>

User Details

diff --git a/config/environments/test.rb b/config/environments/test.rb index c2095b117..3374b51ac 100644 --- a/config/environments/test.rb +++ b/config/environments/test.rb @@ -50,4 +50,5 @@ # Raise error when a before_action's only/except options reference missing actions. config.action_controller.raise_on_missing_callback_actions = true + config.active_job.queue_adapter = :test end diff --git a/config/routes.rb b/config/routes.rb index a88278550..7200d2a10 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,41 +1,29 @@ Rails.application.routes.draw do - get "profiles/show" - get "profiles/edit" - get "profiles/update" - get "profiles/destroy" + # This MUST be at the top, outside any 'admin' namespace devise_for :users - # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html - - # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. - # Can be used by load balancers and uptime monitors to verify that the app is live. + # Admin-specific routes namespace :admin do - get "user_imports/new" - get "user_imports/create" - get "user_imports/show" - get "users/index" - get "users/show" - get "users/new" - get "users/create" - get "users/edit" - get "users/update" - get "users/destroy" - get "dashboard/show" get "dashboard", to: "dashboard#show" - resources :users - patch "users/:id/toggle_role", to: "users#toggle_role", as: :toggle_user_role - resources :user_imports, only: [ :new, :create, :show ] end + # User Profile routes resource :profile, only: [ :show, :edit, :update, :destroy ] - # Render dynamic PWA files from app/views/pwa/* (remember to link manifest in application.html.erb) - # get "manifest" => "rails/pwa#manifest", as: :pwa_manifest - # get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker - # Defines the root path route ("/") + # Root path + # This logic will redirect signed-in users correctly root "profiles#show" - get "up" => "rails/health#show", as: :rails_health_check + + # As a fallback, redirect admins to their dashboard if they hit the root + authenticated :user, ->(u) { u.admin? } do + root to: "admin/dashboard#show", as: :admin_root + end + + # Redirect regular users to their profile + authenticated :user do + root to: "profiles#show", as: :user_root + end end diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 000000000..095f0df16 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,44 @@ +services: + web: + build: . + command: bundle exec rails s -b 0.0.0.0 + volumes: + - .:/rails + ports: + - "3000:3000" + depends_on: + - db + environment: + RAILS_ENV: development + DATABASE_URL: postgres://postgres:password@db:5432/umanni_dev + RAILS_MASTER_KEY: ${RAILS_MASTER_KEY} # Will be created + + db: + image: postgres:17 + volumes: + - postgres_data:/var/lib/postgresql/data + environment: + POSTGRES_PASSWORD: password + ports: + - "5432:5432" + redis: + image: redis:7 + volumes: + - redis_data:/data + + sidekiq: + build: . + command: bundle exec sidekiq + volumes: + - .:/rails + depends_on: + - web + - db + - redis + environment: + DATABASE_URL: postgres://postgres:password@db:5432/umanni_dev + REDIS_URL: redis://redis:6379/0 + +volumes: + postgres_data: + redis_data: diff --git a/spec/factories/users.rb b/spec/factories/users.rb new file mode 100644 index 000000000..ad3d794ff --- /dev/null +++ b/spec/factories/users.rb @@ -0,0 +1,11 @@ +FactoryBot.define do + factory :user do + full_name { Faker::Name.name } + email { Faker::Internet.email } + password { "password123" } + # Creates an admin user: create(:user, :admin) + trait :admin do + role { :admin } + end + end +end diff --git a/spec/fixtures/files/users.xlsx b/spec/fixtures/files/users.xlsx new file mode 100644 index 000000000..e69de29bb diff --git a/spec/jobs/import_users_job_spec.rb b/spec/jobs/import_users_job_spec.rb new file mode 100644 index 000000000..73e61ceec --- /dev/null +++ b/spec/jobs/import_users_job_spec.rb @@ -0,0 +1,54 @@ +require 'rails_helper' + +RSpec.describe ImportUsersJob, type: :job do + include ActiveJob::TestHelper + + # Factory for user_import (requires a file attachment) + FactoryBot.define do + factory :user_import do + # Attach a real file from your 'spec/fixtures' folder + file { Rack::Test::UploadedFile.new(Rails.root.join('spec/fixtures/files/users.xlsx'), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') } + end + end + + # Create a dummy users.xlsx file in 'spec/fixtures/files/users.xlsx' for this to work + + let(:user_import) { create(:user_import) } + + it "enqueues the job" do + expect { + ImportUsersJob.perform_later(user_import.id) + }.to have_enqueued_job + end + + it "creates new users from the spreadsheet" do + # Mock the Roo spreadsheet parser + spreadsheet_data = [ + [ "full_name", "email" ], # Header row + [ "Job User 1", "job1@example.com" ], + [ "Job User 2", "job2@example.com" ] + ] + + # Mock the 'Down' gem download + allow(Down).to receive(:download).and_return(Rails.root.join('spec/fixtures/files/users.xlsx')) + + # Mock the spreadsheet + spreadsheet_mock = instance_double(Roo::Excelx) + allow(Roo::Spreadsheet).to receive(:open).and_return(spreadsheet_mock) + allow(spreadsheet_mock).to receive(:each_with_index).and_yield(spreadsheet_data[1], 1).and_yield(spreadsheet_data[2], 2) + allow(spreadsheet_mock).to receive(:last_row).and_return(3) + + # Perform the job + # We use perform_enqueued_jobs to run the job immediately + expect { + perform_enqueued_jobs { ImportUsersJob.perform_later(user_import.id) } + }.to change(User, :count).by(2) + + expect(User.last.email).to eq("job2@example.com") + expect(user_import.reload.status).to eq("completed") + end + + it "logs errors for invalid users" do + # ... (similar test, but yield invalid data) ... + end +end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb new file mode 100644 index 000000000..7b147db43 --- /dev/null +++ b/spec/models/user_spec.rb @@ -0,0 +1,33 @@ +require 'rails_helper' + +RSpec.describe User, type: :model do + describe 'validations' do + it { should validate_presence_of(:full_name) } + # Test Devise validation (email presence) + it { should validate_presence_of(:email) } + # Test uniqueness (after creating one user) + subject { create(:user) } + it { should validate_uniqueness_of(:email).case_insensitive } + end + + describe 'associations' do + it { should have_one_attached(:avatar_image) } + end + + describe 'enums' do + # Test that the enum is defined correctly + it { should define_enum_for(:role).with_values(user: 0, admin: 1) } + + it 'defaults to :user role' do + user = User.new + expect(user.role).to eq('user') + expect(user.user?).to be(true) + end + + it 'can be set to :admin role' do + admin = build(:user, :admin) + expect(admin.role).to eq('admin') + expect(admin.admin?).to be(true) + end + end +end diff --git a/spec/policies/user_policy_spec.rb b/spec/policies/user_policy_spec.rb new file mode 100644 index 000000000..64a24a6b3 --- /dev/null +++ b/spec/policies/user_policy_spec.rb @@ -0,0 +1,68 @@ +require 'rails_helper' + +RSpec.describe UserPolicy, type: :policy do + # Use `subject` to define the policy being tested + subject { described_class.new(user, record) } + + let(:base_user) { create(:user) } + let(:other_user) { create(:user) } + let(:admin) { create(:user, :admin) } + + # --- Test a Regular User --- + context 'as a regular user' do + let(:user) { base_user } + + describe 'permissions for their own profile' do + let(:record) { base_user } # The record is themselves + + it { is_expected.to permit_action(:show) } + it { is_expected.to permit_action(:update) } + it { is_expected.to permit_action(:destroy) } + end + + describe 'permissions for another user' do + let(:record) { other_user } # The record is someone else + + it { is_expected.not_to permit_action(:show) } + it { is_expected.not_to permit_action(:index) } + it { is_expected.not_to permit_action(:create) } + it { is_expected.not_to permit_action(:update) } + it { is_expected.not_to permit_action(:destroy) } + it { is_expected.not_to permit_action(:toggle_role) } + end + end + + # --- Test an Admin --- + context 'as an admin' do + let(:user) { admin } # The user is the admin + let(:record) { other_user } # The record is someone else + + it 'permits all actions' do + is_expected.to permit_all_actions + end + end + + # --- Test the Scope --- + describe "Scope" do + # Note: `user` and `admin` are created here by the `let!` + let!(:user) { create(:user) } + let!(:admin) { create(:user, :admin) } + + before do + # Create 3 more users + create_list(:user, 3) + end + + it "as a user, only returns self" do + user_scope = Pundit.policy_scope!(user, User) + expect(user_scope.count).to eq(1) + expect(user_scope.first).to eq(user) + end + + it "as an admin, returns all users" do + admin_scope = Pundit.policy_scope!(admin, User) + # 1 user + 1 admin + 3 created = 5 total + expect(admin_scope.count).to eq(5) + end + end +end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb new file mode 100644 index 000000000..6277c914f --- /dev/null +++ b/spec/rails_helper.rb @@ -0,0 +1,77 @@ +# This file is copied to spec/ when you run 'rails generate rspec:install' +require 'spec_helper' +ENV['RAILS_ENV'] ||= 'test' +require_relative '../config/environment' +# Prevent database truncation if the environment is production +abort("The Rails environment is running in production mode!") if Rails.env.production? +# Uncomment the line below in case you have `--require rails_helper` in the `.rspec` file +# that will avoid rails generators crashing because migrations haven't been run yet +# return unless Rails.env.test? +require 'rspec/rails' +# Add additional requires below this line. Rails is not loaded until this point! + +# Requires supporting ruby files with custom matchers and macros, etc, in +# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are +# run as spec files by default. This means that files in spec/support that end +# in _spec.rb will both be required and run as specs, causing the specs to be +# run twice. It is recommended that you do not name files matching this glob to +# end with _spec.rb. You can configure this pattern with the --pattern +# option on the command line or in ~/.rspec, .rspec or `.rspec-local`. +# +# The following line is provided for convenience purposes. It has the downside +# of increasing the boot-up time by auto-requiring all files in the support +# directory. Alternatively, in the individual `*_spec.rb` files, manually +# require only the support files necessary. +# +# Rails.root.glob('spec/support/**/*.rb').sort_by(&:to_s).each { |f| require f } + +# Ensures that the test database schema matches the current schema file. +# If there are pending migrations it will invoke `db:test:prepare` to +# recreate the test database by loading the schema. +# If you are not using ActiveRecord, you can remove these lines. +begin + ActiveRecord::Migration.maintain_test_schema! +rescue ActiveRecord::PendingMigrationError => e + abort e.to_s.strip +end +RSpec.configure do |config| + # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures + config.fixture_paths = [ + Rails.root.join('spec/fixtures') + ] + + # If you're not using ActiveRecord, or you'd prefer not to run each of your + # examples within a transaction, remove the following line or assign false + # instead of true. + config.use_transactional_fixtures = true + + # sidekiq-testing + + config.before(:each) do + Sidekiq::Testing.inline! + end + # You can uncomment this line to turn off ActiveRecord support entirely. + # config.use_active_record = false + + # RSpec Rails uses metadata to mix in different behaviours to your tests, + # for example enabling you to call `get` and `post` in request specs. e.g.: + # + # RSpec.describe UsersController, type: :request do + # # ... + # end + # + # The different available types are documented in the features, such as in + # https://rspec.info/features/8-0/rspec-rails + # + # You can also this infer these behaviours automatically by location, e.g. + # /spec/models would pull in the same behaviour as `type: :model` but this + # behaviour is considered legacy and will be removed in a future version. + # + # To enable this behaviour uncomment the line below. + # config.infer_spec_type_from_file_location! + + # Filter lines from Rails gems in backtraces. + config.filter_rails_from_backtrace! + # arbitrary gems may also be filtered via: + # config.filter_gems_from_backtrace("gem name") +end diff --git a/spec/requests/admin/users_spec.rb b/spec/requests/admin/users_spec.rb new file mode 100644 index 000000000..b4a8e4af8 --- /dev/null +++ b/spec/requests/admin/users_spec.rb @@ -0,0 +1,53 @@ +require 'rails_helper' + +RSpec.describe "Admin::Users", type: :request do + let(:user) { create(:user) } + let(:admin) { create(:user, :admin) } + + context "as a regular user" do + before do + sign_in user, scope: :user + end + + it "is redirected when trying to access the user list" do + get admin_users_path + # Use the new root path helper from your routes file + expect(response).to redirect_to(profile_path) + expect(flash[:alert]).to eq("You must be an admin to access this section.") + end + end + + context "as an admin" do + before do + sign_in admin, scope: :user + end + + let!(:user_to_toggle) { create(:user) } + + it "can access the user list" do + get admin_users_path + expect(response).to be_successful + end + + it "can create a new user" do + user_attributes = attributes_for(:user, full_name: "Created by Admin") + + expect { + post admin_users_path, params: { user: user_attributes } + }.to change(User, :count).by(1) + + expect(User.last.full_name).to eq("Created by Admin") + end + + let!(:user_to_toggle) { create(:user) } + it "can toggle a user's role" do + # Create the user we are going to toggle + expect(user_to_toggle.admin?).to be(false) + + # Use the specific user in the path + patch admin_toggle_user_role_path(user_to_toggle) + + expect(user_to_toggle.reload.admin?).to be(true) + end + end +end diff --git a/spec/requests/profiles_spec.rb b/spec/requests/profiles_spec.rb new file mode 100644 index 000000000..61e6a80de --- /dev/null +++ b/spec/requests/profiles_spec.rb @@ -0,0 +1,32 @@ +require 'rails_helper' + +RSpec.describe "Profiles", type: :request do + let(:user) { create(:user) } + + context "when not logged in" do + it "redirects to the login page" do + get profile_path + expect(response).to redirect_to(new_user_session_path) + end + end + + context "when logged in" do + before do + sign_in user + end + + it "can see their own profile" do + get profile_path + expect(response).to be_successful + expect(response.body).to include(user.full_name) + end + + it "can update their profile without a password" do + patch profile_path, params: { + user: { full_name: "New Name", email: user.email } + } + expect(response).to redirect_to(profile_path) + expect(user.reload.full_name).to eq("New Name") + end + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 000000000..7417dd480 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,126 @@ +require 'spec_helper' +ENV['RAILS_ENV'] ||= 'test' +require_relative '../config/environment' +abort("The Rails environment is running in production mode!") if Rails.env.production? +require 'rspec/rails' +require 'pundit/matchers' +# --- ADD THESE LINES --- +# require 'sidekiq/testing' +# require 'pundit/rspec' +require 'shoulda/matchers' +# This file was generated by the `rails generate rspec:install` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# See https://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +RSpec.configure do |config| + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.include FactoryBot::Syntax::Methods + + # pundit + config.include Pundit::Matchers, type: :policy + + config.include Devise::Test::IntegrationHelpers, type: :request + # For system (browser) specs + config.include Devise::Test::IntegrationHelpers, type: :system + + # 3. Sidekiq testing mode (inline: jobs run immediately) + config.before(:each) do + Sidekiq::Testing.inline! + end + + # 4. Shoulda-Matchers configuration + Shoulda::Matchers.configure do |shoulda_config| + shoulda_config.integrate do |with| + with.test_framework :rspec + with.library :rails + end + end + + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true + end + + # This option will default to `:apply_to_host_groups` in RSpec 4 (and will + # have no way to turn it off -- the option exists only for backwards + # compatibility in RSpec 3). It causes shared context metadata to be + # inherited by the metadata hash of host groups and examples, rather than + # triggering implicit auto-inclusion in groups with matching metadata. + config.shared_context_metadata_behavior = :apply_to_host_groups + +# The settings below are suggested to provide a good initial experience +# with RSpec, but feel free to customize to your heart's content. +=begin + # This allows you to limit a spec run to individual examples or groups + # you care about by tagging them with `:focus` metadata. When nothing + # is tagged with `:focus`, all examples get run. RSpec also provides + # aliases for `it`, `describe`, and `context` that include `:focus` + # metadata: `fit`, `fdescribe` and `fcontext`, respectively. + config.filter_run_when_matching :focus + + # Allows RSpec to persist some state between runs in order to support + # the `--only-failures` and `--next-failure` CLI options. We recommend + # you configure your source control system to ignore this file. + config.example_status_persistence_file_path = "spec/examples.txt" + + # Limits the available syntax to the non-monkey patched syntax that is + # recommended. For more details, see: + # https://rspec.info/features/3-12/rspec-core/configuration/zero-monkey-patching-mode/ + config.disable_monkey_patching! + + # Many RSpec users commonly either run the entire suite or an individual + # file, and it's useful to allow more verbose output when running an + # individual spec file. + if config.files_to_run.one? + # Use the documentation formatter for detailed output, + # unless a formatter has already been configured + # (e.g. via a command-line flag). + config.default_formatter = "doc" + end + + # Print the 10 slowest examples and example groups at the + # end of the spec run, to help surface which specs are running + # particularly slow. + config.profile_examples = 10 + + # Run specs in random order to surface order dependencies. If you find an + # order dependency and want to debug it, you can fix the order by providing + # the seed, which is printed after each run. + # --seed 1234 + config.order = :random + + # Seed global randomization in this process using the `--seed` CLI option. + # Setting this allows you to use `--seed` to deterministically reproduce + # test failures related to randomization by passing the same `--seed` value + # as the one that triggered the failure. + Kernel.srand config.seed +=end +end diff --git a/spec/system/user_signups_spec.rb b/spec/system/user_signups_spec.rb new file mode 100644 index 000000000..360f32df1 --- /dev/null +++ b/spec/system/user_signups_spec.rb @@ -0,0 +1,29 @@ +require 'rails_helper' + +RSpec.describe "UserSignups", type: :system do + before do + driven_by(:rack_test) # Use this for fast, headless tests + # driven_by(:selenium_chrome_headless) # Use this if you need JavaScript + end + + it "allows a visitor to sign up" do + visit root_path + + # From the navbar + click_on "Sign Up" + + expect(page).to have_content("Sign up") + + fill_in "Full name", with: "Test User" + fill_in "Email", with: "test@example.com" + fill_in "Password", with: "password123" + fill_in "Password confirmation", with: "password123" + + click_button "Sign up" + + # Should redirect to the profile page + expect(page).to have_content("My Profile") + expect(page).to have_content("Test User") + expect(User.last.email).to eq("test@example.com") + end +end From ef0fe95836f16b82d21c9e8be911c4efb9eb1916 Mon Sep 17 00:00:00 2001 From: vitaotm Date: Wed, 5 Nov 2025 14:41:34 -0300 Subject: [PATCH 13/17] Remove URL avatar attach, was causing a loop bug --- app/controllers/admin/users_controller.rb | 2 -- app/controllers/application_controller.rb | 24 ++++++-------------- app/models/user.rb | 13 ----------- app/views/admin/users/_form.html.erb | 5 ---- app/views/devise/registrations/edit.html.erb | 5 ---- app/views/devise/registrations/new.html.erb | 5 ---- app/views/profiles/edit.html.erb | 5 ---- 7 files changed, 7 insertions(+), 52 deletions(-) diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb index a4bb13ac9..ceb1d62f6 100644 --- a/app/controllers/admin/users_controller.rb +++ b/app/controllers/admin/users_controller.rb @@ -71,8 +71,6 @@ def set_user @user = User.find(params[:id]) end - # --- THIS IS THE CRITICAL METHOD --- - # Make sure your file has this exact method def user_params params.require(:user).permit( :full_name, diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 0f05fdca2..4e88f6cec 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,32 +1,22 @@ class ApplicationController < ActionController::Base - # Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has. - # include Pundit::Authorization + before_action :configure_permitted_parameters, if: :devise_controller? - before_action :authenticate_user! allow_browser versions: :modern + before_action :authenticate_user! - rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized protected def configure_permitted_parameters - devise_parameter_sanitizer.permit(:sign_up, keys: [ :full_name, :avatar_image, :avatar_url ]) + devise_parameter_sanitizer.permit(:sing_up, keys: [ :full_name, :avatar_image, :avatar_url ]) devise_parameter_sanitizer.permit(:account_update, keys: [ :full_name, :avatar_url, :avatar_image ]) end - def after_sign_in_path_for(resource) - if resource.admin? - admin_dashboard_path - else - profile_path - end - end - - private + protected - def user_not_authorized - flash[:alert] = "You are not authorized to perform this action" - redirect_to(request.referrer || root_path) + def configure_permitted_parameters + devise_parameter_sanitizer.permit(:sign_up, keys: [ :full_name, :avatar_image, :avatar_url ]) + devise_parameter_sanitizer.permit(:account_update, keys: [ :full_name, :avatar_image, :avatar_url ]) end end diff --git a/app/models/user.rb b/app/models/user.rb index 78c8155f9..a5473f4cf 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -8,28 +8,15 @@ class User < ApplicationRecord has_one_attached :avatar_image - attr_accessor :avatar_url validates :full_name, presence: true - before_validation :download_avatar_from_url, if: -> { avatar_url.present? } after_create_commit :broadcast_dashboard_update after_update_commit :broadcast_dashboard_update, if: :saved_change_to_role? after_destroy_commit :broadcast_dashboard_update private - def download_avatar_from_url - require "down" - begin - tempfile = Down.download(avatar_url) - self.avatar_image.attach(io: tempfile, filename: tempfile.original_filename) - rescue Down::Error => e - Rails.logger.error "Avatar URL download failed: #{e.message}" - errors.add(:avatar_url, "is not a valid image URL or could not be downloaded") - end - end - def broadcast_dashboard_update Turbo::StreamsChannel.broadcast_update_to( "admin_dashboard_stats", diff --git a/app/views/admin/users/_form.html.erb b/app/views/admin/users/_form.html.erb index d3e369c02..170017b57 100644 --- a/app/views/admin/users/_form.html.erb +++ b/app/views/admin/users/_form.html.erb @@ -41,11 +41,6 @@ "block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100" %>
-
- <%= f.label :avatar_url, "Or paste Avatar URL", class: "form.label" %> - <%= f.url_field :avatar_url, class: "form-input", placeholder: "https://..." %> -
-
diff --git a/app/views/devise/registrations/edit.html.erb b/app/views/devise/registrations/edit.html.erb index ecd4c7b4b..0fb62783d 100644 --- a/app/views/devise/registrations/edit.html.erb +++ b/app/views/devise/registrations/edit.html.erb @@ -27,11 +27,6 @@ <%= f.file_field :avatar_image, class: file_input_class %>
-
- <%= f.label :avatar_url, "Or paste Avatar URL", class: "form-label" %> - <%= f.url_field :avatar_url, class: "form-input", placeholder: "https://..." %> -
-

Leave fields below blank if you don't want to change your password.

diff --git a/app/views/devise/registrations/new.html.erb b/app/views/devise/registrations/new.html.erb index 97f2478d7..ad146bcb1 100644 --- a/app/views/devise/registrations/new.html.erb +++ b/app/views/devise/registrations/new.html.erb @@ -27,11 +27,6 @@ <%= f.file_field :avatar_image, class: file_input_class %>
-
- <%= f.label :avatar_url, "Or paste Avatar URL", class: "form-label" %> - <%= f.url_field :avatar_url, class: "form-input", placeholder: "https://..." %> -
-
<%= f.label :password, class: "form-label" %> <%= f.password_field :password, autocomplete: "new-password", class: "form-input" %> diff --git a/app/views/profiles/edit.html.erb b/app/views/profiles/edit.html.erb index 032d17869..d5af6127c 100644 --- a/app/views/profiles/edit.html.erb +++ b/app/views/profiles/edit.html.erb @@ -35,11 +35,6 @@ <%= f.file_field :avatar_image, class: "file-field" %>
-
- <%= f.label :avatar_url, "Or paste Avatar URL", class: "form-label" %> - <%= f.url_field :avatar_url, class: "form-input", placeholder: "https://..." %> -
-

Leave fields below blank if you don't want to change your password.

From fd6c8f15f1be8f020f56c86f243063419f6ecce0 Mon Sep 17 00:00:00 2001 From: vitaotm Date: Wed, 5 Nov 2025 17:39:19 -0300 Subject: [PATCH 14/17] Fix user import job - Update README - Update gems - Update routes --- Gemfile | 21 ++-- Gemfile.lock | 10 +- README.md | 108 ++++++++++++++++++ .../admin/user_imports_controller.rb | 5 +- app/jobs/import_users_job.rb | 71 ++++++------ app/models/user_import.rb | 7 +- app/views/admin/user_imports/show.html.erb | 39 ++++--- app/views/layouts/_navbar.html.erb | 4 + config/routes.rb | 5 + 9 files changed, 203 insertions(+), 67 deletions(-) diff --git a/Gemfile b/Gemfile index 8628d72c4..a02ad1268 100644 --- a/Gemfile +++ b/Gemfile @@ -53,7 +53,6 @@ end group :development do # Use console on exceptions pages [https://github.com/rails/web-console] - gem "web-console" end group :test do @@ -62,22 +61,26 @@ group :test do gem "selenium-webdriver" end -gem "devise", "~> 4.9" -gem "pundit", "~> 2.5" -gem "sidekiq", "~> 8.0" -gem "roo", "~> 3.0" -gem "down", "~> 5.4" +# gem "down", "~> 5.4" gem "foreman", "~> 0.90.0" gem "tailwindcss-rails", "~> 4.4" - +gem "active_storage_validations" # Gemfile -group :development, :test do +group :development do + gem "devise", "~> 4.9" + gem "pundit", "~> 2.5" + gem "sidekiq", "~> 8.0" + gem "roo", "~> 3.0" + gem "web-console" +end + +group :test do + gem "rspec-sidekiq" gem "rspec-rails" # The main RSpec testing framework gem "factory_bot_rails" # For creating test data ("factories") gem "faker" # For generating fake data (names, emails) gem "shoulda-matchers" # For simple one-line tests (e.g., "validate_presence_of") - gem "rspec-sidekiq" gem "pundit-matchers", "~>4.0" end diff --git a/Gemfile.lock b/Gemfile.lock index e158b7409..1b282935c 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -44,6 +44,12 @@ GEM erubi (~> 1.11) rails-dom-testing (~> 2.2) rails-html-sanitizer (~> 1.6) + active_storage_validations (3.0.2) + activejob (>= 6.1.4) + activemodel (>= 6.1.4) + activestorage (>= 6.1.4) + activesupport (>= 6.1.4) + marcel (>= 1.0.3) activejob (8.0.4) activesupport (= 8.0.4) globalid (>= 0.3.6) @@ -111,8 +117,6 @@ GEM warden (~> 1.2.3) diff-lcs (1.6.2) dotenv (3.1.8) - down (5.4.2) - addressable (~> 2.8) drb (2.2.3) ed25519 (1.4.0) erb (5.1.3) @@ -440,12 +444,12 @@ PLATFORMS x86_64-linux-musl DEPENDENCIES + active_storage_validations bootsnap brakeman capybara debug devise (~> 4.9) - down (~> 5.4) factory_bot_rails faker foreman (~> 0.90.0) diff --git a/README.md b/README.md index e18f57431..61bf44ff2 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,111 @@ +# Fullstack-Developer TEST UMANNI + +- This is a developper test by umanni + +## Installation + +- Use Ruby 3.4 or latter and rails 8.0 or latter +- Use PostgreSQL 18 or latter +- Use Yarn 1.22.22 +- Node v25.1.0 + +Check your versions: + +``` + ruby -v + rails -v + postgres --version + yarn --version + node -v +``` + +System dependencies + +GEMS: + +- Devise; +- Pundit; + +## Configuration + +- Clone this repo or fork it `git clone git@github.com:vitaoTM/Fullstack-Developer.git` + +#### To run local: + +``` +# Create database and migrate it +bin/rails db:create db:migrate + +``` + +Create admin user, must be done through rails console: + +- Do not forget to change your credentials: + +``` +rails console + +# You will enter rails console: +# run: + +# This will create a admin user if you do not read this and only copy and paste to your terminal (you can delete this line) + +adm = User.create(full_name: "Admin", email: "admin@admin.com", password: "123456", password_confirmation: "123456") +adm.admin! + +u = User.create(full_name: "ADD YOU NAME HERE", email: "ADD YOUR EMAIL HERE", password: "SET A PASSWORD", password_confirmation: "CONFIRM YOUR PASSWORD") + +u.admin! + +exit + +``` + +- Run server: +``` +bin/dev +``` + +- To exit server just press Ctrl-C + +- Run tests: + +``` +rspec spec/ +``` + + +#### Run with Docker: + +- This should be enouth to play with the web application: + +``` +docker-compose build +docker-compose up -d +docker-compose exec web bin/rails db:create db:migrate +docker-compose exec web bin/rails console + +#inside rails console run: + +adm = User.create(full_name: "Admin", email: "admin@admin.com", password: "123456", password_confirmation: "123456") +adm.admin! + +u = User.create(full_name: "ADD YOU NAME HERE", email: "ADD YOUR EMAIL HERE", password: "SET A PASSWORD", password_confirmation: "CONFIRM YOUR PASSWORD") + +u.admin! + +exit +``` + +- To run tests in docker: + +``` +docker-compose exec web rspec spec +``` + + + + # Fullstack Developer Test - Check this readme.md diff --git a/app/controllers/admin/user_imports_controller.rb b/app/controllers/admin/user_imports_controller.rb index 9bce858ac..40750a217 100644 --- a/app/controllers/admin/user_imports_controller.rb +++ b/app/controllers/admin/user_imports_controller.rb @@ -4,10 +4,11 @@ def new end def create - @user_import = UserImport.new + @user_import = UserImport.new(user_import_params) if @user_import.save - ImportUsersJob.perform_later(@user_import_params) + ImportUsersJob.perform_later(@user_import) + redirect_to admin_user_import_path(@user_import), notice: "Import started." else render :new, status: :unprocessable_entity diff --git a/app/jobs/import_users_job.rb b/app/jobs/import_users_job.rb index c857d04ae..8e545c9cc 100644 --- a/app/jobs/import_users_job.rb +++ b/app/jobs/import_users_job.rb @@ -1,12 +1,11 @@ class ImportUsersJob < ApplicationJob queue_as :default - def perform(user_import_id) - user_import = UserImport.find(user_import_id) + def perform(user_import) user_import.update!(status: :processing, processed_count: 0, error_log: "") user_import.broadcast_replace_to( - user_import, # The stream name + user_import, target: "user_import_status", partial: "admin/user_imports/status", locals: { user_import: user_import } @@ -16,43 +15,49 @@ def perform(user_import_id) processed = 0 begin - spreadsheet = Roo::Spreadsheet.open(user_import.file.download, extension: :xlsx) - user_import.update!(total_count: spreadsheet.last_row - 1) - - spreadsheet.each_with_index do |row, idx| - next if idx == 0 # Skip header row - - full_name, email = row[0], row[1] - - user = User.new( - full_name: full_name, - email: email, - password: SecureRandom.hex(10) - ) - - if user.save - processed += 1 - else - errors << "Row #{idx + 1}: #{user.errors.full_messages.join(', ')}" - end - - if processed % 10 == 0 || idx == spreadsheet.last_row - 1 - user_import.update!(processed_count: processed) - user_import.broadcast_update_to( - user_import, - target: "import_progress_bar", - partial: "admin/user_imports/progress", - locals: { import: user_import } + user_import.file.open do |tempfile| + file_ext = user_import.file.filename.extension.to_sym + + spreadsheet = Roo::Spreadsheet.open(tempfile.path, extension: file_ext) + + user_import.update!(total_count: spreadsheet.last_row - 1) + + spreadsheet.each_with_index do |row, idx| + next if idx == 0 # Skip header row + + full_name, email = row[0], row[1] + + user = User.new( + full_name: full_name, + email: email, + password: SecureRandom.hex(10) ) - end + + if user.save + processed += 1 + else + errors << "Row #{idx + 1}: #{user.errors.full_messages.join(', ')}" + end + + if processed % 10 == 0 || idx == spreadsheet.last_row - 1 + user_import.update!(processed_count: processed) + user_import.broadcast_update_to( + user_import, + target: "import_progress_bar", + partial: "admin/user_imports/progress", + locals: { import: user_import } + ) + end + end # end spreadsheet.each + + user_import.update!(status: :completed, error_log: errors.join("\n")) end - user_import.update!(status: :completed, error_log: errors.join("\n")) rescue => e user_import.update!(status: :failed, error_log: "Fatal error: #{e.message}") ensure user_import.broadcast_replace_to( - user_import, # The stream name + user_import, target: "user_import_status", partial: "admin/user_imports/status", locals: { user_import: user_import } diff --git a/app/models/user_import.rb b/app/models/user_import.rb index faedb8661..d41b216c3 100644 --- a/app/models/user_import.rb +++ b/app/models/user_import.rb @@ -2,7 +2,10 @@ class UserImport < ApplicationRecord include Turbo::Broadcastable has_one_attached :file - enum :status, { pending: 0, processing: 1, completed: 2, failed: 3 } - validates :file, presence: true + + validates :file, content_type: [ + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "text/csv" + ] end diff --git a/app/views/admin/user_imports/show.html.erb b/app/views/admin/user_imports/show.html.erb index 29a9f656a..e1a8bc7cb 100644 --- a/app/views/admin/user_imports/show.html.erb +++ b/app/views/admin/user_imports/show.html.erb @@ -1,23 +1,26 @@ -<%= turbo_stream_from @user_import %> +
-

Import Progress

+ <%= turbo_stream_from @user_import %> -
- <%= turbo_frame_tag "user_import_status" do %> -

- Status: - - <%= @user_import.status.humanize %> - -

- <% end %> +

Import Progress

- <%= turbo_frame_tag "import_progress_bar" do %> - <%= render "progress", import: @user_import %> - <% end %> +
+ <%= turbo_frame_tag "user_import_status" do %> +

+ Status: + + <%= @user_import.status&.humanize %> + +

+ <% end %> -

Error Log:

-
-    <%= @user_import.error_log.presence || "No errors." %>
-  
+ <%= turbo_frame_tag "import_progress_bar" do %> + <%= render "progress", import: @user_import %> + <% end %> + +

Error Log:

+
+      <%= @user_import.error_log.presence || "No errors." %>
+    
+
diff --git a/app/views/layouts/_navbar.html.erb b/app/views/layouts/_navbar.html.erb index 52bf928ae..a4836af6a 100644 --- a/app/views/layouts/_navbar.html.erb +++ b/app/views/layouts/_navbar.html.erb @@ -23,6 +23,10 @@ admin_users_path, class: "text-gray-700 hover:text-blue-600 px-3 py-2 rounded-md text-sm font-medium" %> + <%= link_to "Import Users", + new_admin_user_import_path, + class: + "text-gray-700 hover:text-blue-600 px-3 py-2 rounded-md text-sm font-medium" %> <% else %> <%# --- Regular User Links --- %> <%= link_to "My Profile", diff --git a/config/routes.rb b/config/routes.rb index 7200d2a10..8269a1c15 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,6 +1,11 @@ +require "sidekiq/web" + Rails.application.routes.draw do # This MUST be at the top, outside any 'admin' namespace devise_for :users + authenticate :user, ->(u) { u.admin? } do + mount Sidekiq::Web => "/sidekiq" + end # Admin-specific routes namespace :admin do From afe640cd389faaf1d7ad9e9fba7c52b55dfbcb76 Mon Sep 17 00:00:00 2001 From: vitaotm Date: Wed, 5 Nov 2025 18:36:33 -0300 Subject: [PATCH 15/17] Configure sidekiq environment for web and worker - Updates docker-compose.yml --- Gemfile | 8 ++++---- config/initializers/sidekiq.rb | 9 +++++++++ docker-compose.yml | 8 ++++++-- 3 files changed, 19 insertions(+), 6 deletions(-) create mode 100644 config/initializers/sidekiq.rb diff --git a/Gemfile b/Gemfile index a02ad1268..c33110e8a 100644 --- a/Gemfile +++ b/Gemfile @@ -67,12 +67,12 @@ gem "foreman", "~> 0.90.0" gem "tailwindcss-rails", "~> 4.4" gem "active_storage_validations" +gem "devise", "~> 4.9" +gem "pundit", "~> 2.5" +gem "roo", "~> 3.0" +gem "sidekiq", "~> 8.0" # Gemfile group :development do - gem "devise", "~> 4.9" - gem "pundit", "~> 2.5" - gem "sidekiq", "~> 8.0" - gem "roo", "~> 3.0" gem "web-console" end diff --git a/config/initializers/sidekiq.rb b/config/initializers/sidekiq.rb new file mode 100644 index 000000000..742e03955 --- /dev/null +++ b/config/initializers/sidekiq.rb @@ -0,0 +1,9 @@ +redis_url = ENV.fetch("REDIS_URL", "redis://localhost:6379/0") + +Sidekiq.configure_server do |config| + config.redis = { url: redis_url } +end + +Sidekiq.configure_client do |config| + config.redis = { url: redis_url } +end diff --git a/docker-compose.yml b/docker-compose.yml index 095f0df16..cfae0e01e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,10 +8,12 @@ services: - "3000:3000" depends_on: - db + - redis environment: RAILS_ENV: development DATABASE_URL: postgres://postgres:password@db:5432/umanni_dev - RAILS_MASTER_KEY: ${RAILS_MASTER_KEY} # Will be created + REDIS_URL: redis://redis:6379/0 + RAILS_MASTER_KEY: ${RAILS_MASTER_KEY} db: image: postgres:17 @@ -21,6 +23,7 @@ services: POSTGRES_PASSWORD: password ports: - "5432:5432" + redis: image: redis:7 volumes: @@ -32,12 +35,13 @@ services: volumes: - .:/rails depends_on: - - web - db - redis environment: + RAILS_ENV: development DATABASE_URL: postgres://postgres:password@db:5432/umanni_dev REDIS_URL: redis://redis:6379/0 + RAILS_MASTER_KEY: ${RAILS_MASTER_KEY} volumes: postgres_data: From 3d4ee288f047bdbd40a0bcf5803b5bb0eeed0a81 Mon Sep 17 00:00:00 2001 From: vitaotm Date: Thu, 6 Nov 2025 01:25:22 -0300 Subject: [PATCH 16/17] Update Readme --- README.md | 273 ++++++++++++++++++++++++++++++------------------------ 1 file changed, 152 insertions(+), 121 deletions(-) diff --git a/README.md b/README.md index 61bf44ff2..9ecd69670 100644 --- a/README.md +++ b/README.md @@ -1,44 +1,103 @@ # Fullstack-Developer TEST UMANNI -- This is a developper test by umanni +This is a developper test by umanni. A responsive user management system. +Main features: -## Installation +- Admin dashboard: a stats from all users grouped by role +- User management (CRUD): admins can create, read, update and delete any user +- Profile management: Regular users can CRUD their own profile +- CSV import: Admins can bulk import new users via CSV files. -- Use Ruby 3.4 or latter and rails 8.0 or latter -- Use PostgreSQL 18 or latter -- Use Yarn 1.22.22 -- Node v25.1.0 +### Versions used in this project +
-Check your versions: +|System| Version Command | Version | +|:------|:-------------------:|:---------:| +|[ruby](https://www.ruby-lang.org/en/documentation/installation/)| `ruby -v`|`3.4.5` | +|[rails](https://guides.rubyonrails.org/)|`rails -v`|`8.0.4`| +|[redis](https://redis.io/docs/latest/operate/oss_and_stack/install/install-redis/)/valkey|`redis-cli -v`| `valkey-cli 8.1.4` | +|[postgreSQL](https://www.postgresql.org/download/)| `psql -V`| `18` | +|[tailwind](https://tailwindcss.com/blog/tailwindcss-v4)| `npm view tailwindcss version`| `4.1.16` | +|[node](https://nodejs.org/en) | `node -v`| `v25.1.0` | + +
+ +## Clone or download this repo + +``` +git clone git@github.com:vitaoTM/Fullstack-Developer.git +cd Fullstack-Developer +``` + +## Get Started with Docker + +1. Build and Run the app + +``` +docker-compose build +docker-compose up -d +``` + +2. Set up database ``` - ruby -v - rails -v - postgres --version - yarn --version - node -v +docker-compose exec web bin/rails db:setup +``` + +3. Create admin User +You'll need to create the first user via rails console + + +``` +# Start the console: + +docker-compose exec web bin/rails console + +# inside the console, run: + +u = User.create(full_name: "Adim User", email: "admin@admim.com", password: "password123", password_confirmation: "password123") +u.admin! +u.save + +# To exit rails console type: + +exit ``` -System dependencies +4. Access the app + +The application should be runnig: +- Check: `http://localhost:3000` +- Log in with the credentials you just created. -GEMS: +5. Stopping the application -- Devise; -- Pundit; +To stop all running Docker containers: +``` +docker-compose down +``` -## Configuration +## Get Started Locally -- Clone this repo or fork it `git clone git@github.com:vitaoTM/Fullstack-Developer.git` +To run locally please check: +- Ruby version file: `.ruby-version` +- Rails: see `Gemfile` +- PostgreSQL: Must be installed and runnig. +- Node & Yarn: Make sure its all installed. -#### To run local: + +1. Setup Database and install gems and JS packages ``` -# Create database and migrate it +bundle install +yarn install bin/rails db:create db:migrate ``` -Create admin user, must be done through rails console: +2. Create Admin User + +- Create admin user, must be done through rails console: - Do not forget to change your credentials: @@ -61,115 +120,87 @@ exit ``` -- Run server: +3. Run The App + ``` bin/dev ``` +- Access the app at `http://localhost:3000` - To exit server just press Ctrl-C -- Run tests: +4. Run Tests (Local): ``` rspec spec/ ``` -#### Run with Docker: - -- This should be enouth to play with the web application: - -``` -docker-compose build -docker-compose up -d -docker-compose exec web bin/rails db:create db:migrate -docker-compose exec web bin/rails console - -#inside rails console run: - -adm = User.create(full_name: "Admin", email: "admin@admin.com", password: "123456", password_confirmation: "123456") -adm.admin! - -u = User.create(full_name: "ADD YOU NAME HERE", email: "ADD YOUR EMAIL HERE", password: "SET A PASSWORD", password_confirmation: "CONFIRM YOUR PASSWORD") - -u.admin! - -exit -``` - -- To run tests in docker: - -``` -docker-compose exec web rspec spec -``` - - - - -# Fullstack Developer Test - -- Check this readme.md -- Create a branch to develop your task -- Push to remote in 1 week (date will be checked from branch creation/assigned date) - -# Requirements: -- Latest version of the stack -- Write unit and integration tests -- Deliver with a working Dockerfile -- Use docker-compose.yml if needed -- Show your best practices ex: design patters, linters etc. - -# The Test -Here we'll try to simulate a "real sprint" that you'll, probably, be assigned while working as Fullstack at Umanni. -# The Task -- Create a responsive application to manage users. -- A user must have: -1- full_name -2- email -3- avatar_image (upload from file or url) -4- role (admin/no-admin) -# The App -## Admin Use cases -- As an Admin, I must be able to access a User Admin Dashboard. -- As an Admin, I must be able to see on Dashboard: - - Total number of Users - - Total number of Users grouped by Role -- As an Admin, I must be redirected to User Admin Dashboard after login -- As an Admin, I must be able to list, create, edit and delete Users. -- As an Admin, I must be able to toggle the User Role. -- As an Admin, I must be able to import a Spreadsheet into the system, in order to create new Users -- As an Admin, I must be able to see the progress of Users imports. -## User Use Cases -- As an User, I must be redirected to my Profile after login -- As an User, I must be able only to see my info, edit and delete my profile. -## Visitor Use Cases -- As a Visitor, I can register myself as a normal User. - -# The Start. -- Your deadline is 1 week after accepting this test. -# The Rules -These one are required. Not doing one of them will invalidate your submission. -- You must write down a README in English explaining how to build and run your app. -- The Frontend must have a framework Bootstrap, Foundation, MDL or any other frameworks, remember you are here as a Fullstack not a backend developer. -- You must use realtime related stuff (counters on Admin Dashboard, import progress, etc) -- You must treat errors accordingly. -- You must use a open source lib to authenticate Users. -- And, of course, if you're doing this test, we assume that you have knowledge of git (clone, commit, push, pull, fetch, rebase, merge, stash), and be acquainted with github niceties such as Pull Request based on workflows. -# What we're expecting to see: -- Use SCSS to your CSS; -- .gitignore, .dockerignore -- A proper way to manage app configuration -- Consider multiple Browser support ex: Edge, Chrome, Firefox and Safari. -- Organize & optimize your code and images -- Form validation (frontend validation included) -- Tests with at least 90% coverage -- Be able to use, pjax, turbolinks, intercooler, unpoly (yes, we believe in good old server side rendering) -# Extra points -- Use a Dockerfile -- docker-compose.yml -- React in some ui components when it makes sense -- Stress tests -# What will be assessed -- Code's Semantic, Cleanness and Maintainability; -- Understanding of REST and proper use of HTTP Methods (POST, GET, PUT, PATCH, DELETE, OPTIONS); -- Basic Security tests against Injections, XSS/XSRF, ... + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 32a6ea67a76ebee62abed94a9e19aef670038489 Mon Sep 17 00:00:00 2001 From: Vitor Grosskopf <60250422+vitaoTM@users.noreply.github.com> Date: Thu, 6 Nov 2025 01:37:46 -0300 Subject: [PATCH 17/17] Update README with admin user creation instructions Add instructions for creating the first admin user. --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 9ecd69670..d4671b135 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,7 @@ docker-compose exec web bin/rails db:setup ``` 3. Create admin User + You'll need to create the first user via rails console