diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..22e4f4ce7 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,57 @@ +# Git +.git +.gitignore +.gitattributes + +# CI/CD +.github + +# Docker +Dockerfile +docker-compose.yml +.dockerignore + +# Documentation +README.md +CHANGELOG.md + +# Logs +log/* +tmp/* +*.log + +# Environment files +.env* +!.env.example + +# Dependencies +node_modules/ +vendor/bundle/ + +# Test coverage +coverage/ + +# Database +*.sqlite3 +*.sqlite3-journal +postgres-data/ + +# Editor files +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# OS files +.DS_Store +Thumbs.db + +# Temporary files +/tmp/ +/storage/ + +# Assets (will be built in container) +/public/assets/ +/public/packs/ +/app/assets/builds/ \ No newline at end of file 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..038861c23 --- /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 google-chrome-stable curl libjemalloc2 libvips postgresql-client + + - 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..e8e61ef04 --- /dev/null +++ b/.gitignore @@ -0,0 +1,68 @@ +# See https://help.github.com/articles/ignoring-files for more about ignoring files. +# +# If you find yourself ignoring temporary files generated by your text editor +# or operating system, you probably want to add a global ignore instead: +# git config --global core.excludesfile '~/.gitignore_global' + +# Ignore bundler config. +/.bundle + +# Ignore all environment files (except templates). +/.env* +!/.env*.erb + +# 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. +/app/assets/builds/* +!/app/assets/builds/.keep +/public/assets +/public/packs +/public/packs-test +/node_modules +/yarn-error.log +yarn-debug.log* +.yarn-integrity + +# Ignore master key for decrypting credentials and more. +/config/master.key +/config/credentials/*.key + +# Ignore Docker volumes +/postgres-data + +# Ignore coverage reports +/coverage + +# Ignore RubyMine project files +.idea/ + +# Ignore VSCode settings +.vscode/ + +# Ignore OS files +.DS_Store +Thumbs.db + +# Ignore SimpleCov coverage +/coverage/ + +# Ignore test screenshots +/tmp/screenshots/ + +# Ignore system test downloads +/tmp/downloads/ \ No newline at end of file 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/.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..03463f3c5 --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +ruby-3.3.0 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..644e66864 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,31 @@ +FROM ruby:3.3.0 + +# Instalar dependências do sistema +RUN apt-get update -qq && apt-get install -y \ + nodejs \ + npm \ + postgresql-client \ + libvips \ + && rm -rf /var/lib/apt/lists/* + +# Instalar Yarn +RUN npm install -g yarn + +# Configurar diretório de trabalho +WORKDIR /app + +# Copiar arquivos de dependências +COPY Gemfile Gemfile.lock package.json yarn.lock* ./ + +# Instalar gems e dependências JS +RUN bundle install && \ + yarn install --check-files + +# Copiar o restante da aplicação +COPY . . + +# Expor porta +EXPOSE 3000 + +# Comando padrão +CMD ["bash", "-c", "rm -f tmp/pids/server.pid && bundle exec rails server -b 0.0.0.0"] \ No newline at end of file diff --git a/Gemfile b/Gemfile new file mode 100644 index 000000000..7e9949477 --- /dev/null +++ b/Gemfile @@ -0,0 +1,40 @@ +source 'https://rubygems.org' +ruby '3.3.0' + +gem 'cgi', '~> 0.4.1' +gem 'rails', '~> 7.1.0' +gem "sprockets-rails" +gem 'pg', '~> 1.1' +gem 'puma', '>= 5.0' +gem 'importmap-rails' +gem 'turbo-rails' +gem 'stimulus-rails' +gem 'cssbundling-rails' +gem 'jbuilder' +gem 'tzinfo-data', platforms: %i[ windows jruby ] +gem 'bootsnap', require: false +gem 'image_processing', '~> 1.2' + +# Gems adicionais +gem 'devise' +gem 'react-rails' + +group :development, :test do + gem 'debug', platforms: %i[ mri windows ] + gem 'rspec-rails' + gem 'factory_bot_rails' + gem 'faker' + gem 'rubocop-rails-omakase', require: false +end + +group :development do + gem 'web-console' +end + +group :test do + gem 'capybara' + gem 'selenium-webdriver' + gem 'simplecov', require: false + gem 'shoulda-matchers', '~> 6.0' + gem 'database_cleaner-active_record' +end \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 000000000..9d2b25272 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,407 @@ +GEM + remote: https://rubygems.org/ + specs: + actioncable (7.1.6) + actionpack (= 7.1.6) + activesupport (= 7.1.6) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + zeitwerk (~> 2.6) + actionmailbox (7.1.6) + actionpack (= 7.1.6) + activejob (= 7.1.6) + activerecord (= 7.1.6) + activestorage (= 7.1.6) + activesupport (= 7.1.6) + mail (>= 2.7.1) + net-imap + net-pop + net-smtp + actionmailer (7.1.6) + actionpack (= 7.1.6) + actionview (= 7.1.6) + activejob (= 7.1.6) + activesupport (= 7.1.6) + mail (~> 2.5, >= 2.5.4) + net-imap + net-pop + net-smtp + rails-dom-testing (~> 2.2) + actionpack (7.1.6) + actionview (= 7.1.6) + activesupport (= 7.1.6) + cgi + nokogiri (>= 1.8.5) + racc + rack (>= 2.2.4) + rack-session (>= 1.0.1) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + actiontext (7.1.6) + actionpack (= 7.1.6) + activerecord (= 7.1.6) + activestorage (= 7.1.6) + activesupport (= 7.1.6) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (7.1.6) + activesupport (= 7.1.6) + builder (~> 3.1) + cgi + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + activejob (7.1.6) + activesupport (= 7.1.6) + globalid (>= 0.3.6) + activemodel (7.1.6) + activesupport (= 7.1.6) + activerecord (7.1.6) + activemodel (= 7.1.6) + activesupport (= 7.1.6) + timeout (>= 0.4.0) + activestorage (7.1.6) + actionpack (= 7.1.6) + activejob (= 7.1.6) + activerecord (= 7.1.6) + activesupport (= 7.1.6) + marcel (~> 1.0) + activesupport (7.1.6) + base64 + benchmark (>= 0.3) + bigdecimal + concurrent-ruby (~> 1.0, >= 1.0.2) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + logger (>= 1.4.2) + minitest (>= 5.1) + mutex_m + securerandom (>= 0.3) + tzinfo (~> 2.0) + addressable (2.8.7) + public_suffix (>= 2.0.2, < 7.0) + ast (2.4.3) + babel-source (5.8.35) + babel-transpiler (0.7.0) + babel-source (>= 4.0, < 6) + execjs (~> 2.0) + base64 (0.3.0) + bcrypt (3.1.20) + benchmark (0.5.0) + bigdecimal (3.3.1) + bindex (0.8.1) + bootsnap (1.18.6) + msgpack (~> 1.2) + 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) + cgi (0.4.2) + concurrent-ruby (1.3.5) + connection_pool (2.5.4) + crass (1.0.6) + cssbundling-rails (1.4.3) + railties (>= 6.0.0) + database_cleaner-active_record (2.2.2) + activerecord (>= 5.a) + database_cleaner-core (~> 2.0) + database_cleaner-core (2.0.1) + 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) + diff-lcs (1.6.2) + docile (1.4.1) + drb (2.2.3) + erb (5.1.3) + erubi (1.13.1) + execjs (2.10.0) + 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) + ffi (1.17.2-x86_64-linux-gnu) + globalid (1.3.0) + activesupport (>= 6.1) + i18n (1.14.7) + concurrent-ruby (~> 1.0) + image_processing (1.14.0) + mini_magick (>= 4.9.5, < 6) + ruby-vips (>= 2.0.17, < 3) + 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) + 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_magick (5.3.1) + logger + mini_mime (1.1.5) + minitest (5.26.0) + msgpack (1.8.0) + mutex_m (0.3.0) + net-imap (0.5.12) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.2.2) + timeout + net-smtp (0.5.1) + net-protocol + nio4r (2.7.5) + nokogiri (1.18.10-x86_64-linux-gnu) + racc (~> 1.4) + orm_adapter (0.5.0) + parallel (1.27.0) + parser (3.3.10.0) + ast (~> 2.4.1) + racc + pg (1.6.2-x86_64-linux) + pp (0.6.3) + prettyprint + prettyprint (0.2.0) + prism (1.6.0) + psych (5.2.6) + date + stringio + public_suffix (6.0.2) + puma (7.1.0) + nio4r (~> 2.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 (7.1.6) + actioncable (= 7.1.6) + actionmailbox (= 7.1.6) + actionmailer (= 7.1.6) + actionpack (= 7.1.6) + actiontext (= 7.1.6) + actionview (= 7.1.6) + activejob (= 7.1.6) + activemodel (= 7.1.6) + activerecord (= 7.1.6) + activestorage (= 7.1.6) + activesupport (= 7.1.6) + bundler (>= 1.15.0) + railties (= 7.1.6) + 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 (7.1.6) + actionpack (= 7.1.6) + activesupport (= 7.1.6) + cgi + irb + 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 + react-rails (3.2.1) + babel-transpiler (>= 0.7.0) + connection_pool + execjs + railties (>= 3.2) + tilt + 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) + 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 (7.1.1) + actionpack (>= 7.0) + activesupport (>= 7.0) + railties (>= 7.0) + rspec-core (~> 3.13) + rspec-expectations (~> 3.13) + rspec-mocks (~> 3.13) + rspec-support (~> 3.13) + rspec-support (3.13.6) + 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) + ruby-vips (2.2.5) + ffi (~> 1.12) + logger + 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) + shoulda-matchers (6.5.0) + activesupport (>= 5.2.0) + simplecov (0.22.0) + docile (~> 1.1) + simplecov-html (~> 0.11) + simplecov_json_formatter (~> 0.1) + simplecov-html (0.13.2) + simplecov_json_formatter (0.1.4) + sprockets (4.2.2) + concurrent-ruby (~> 1.0) + logger + rack (>= 2.2.4, < 4) + sprockets-rails (3.5.2) + actionpack (>= 6.1) + activesupport (>= 6.1) + sprockets (>= 3.0.0) + stimulus-rails (1.3.4) + railties (>= 6.0.0) + stringio (3.1.7) + thor (1.4.0) + tilt (2.6.1) + 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) + 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 + x86_64-linux + +DEPENDENCIES + bootsnap + capybara + cgi (~> 0.4.1) + cssbundling-rails + database_cleaner-active_record + debug + devise + factory_bot_rails + faker + image_processing (~> 1.2) + importmap-rails + jbuilder + pg (~> 1.1) + puma (>= 5.0) + rails (~> 7.1.0) + react-rails + rspec-rails + rubocop-rails-omakase + selenium-webdriver + shoulda-matchers (~> 6.0) + simplecov + sprockets-rails + stimulus-rails + turbo-rails + tzinfo-data + web-console + +RUBY VERSION + ruby 3.3.0p0 + +BUNDLED WITH + 2.5.3 diff --git a/Procfile.dev b/Procfile.dev new file mode 100644 index 000000000..34c16939a --- /dev/null +++ b/Procfile.dev @@ -0,0 +1,2 @@ +web: env RUBY_DEBUG_OPEN=true bin/rails server +css: yarn build:css --watch diff --git a/README.md b/README.md index e18f57431..b7472eef9 100644 --- a/README.md +++ b/README.md @@ -1,67 +1,57 @@ -# 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, ... +# User Management App +## 📋 Overview + +This project was built for the Fullstack Developer Test at Umanni. +It is a responsive user management application using the latest stack. + +## 🚀 Tech Stack + +Backend: **Ruby on Rails 7, PostgreSQL** + +Frontend: **SCSS + Bulma** + +Authentication: **Devise** + +Testing: **RSpec, Capybara** + +Containerization: **Docker & docker-compose** + +## 🧱 Features + +Admin can: +- Access dashboard after login +- View total users and users by role +- Create, edit, delete users +- Toggle user roles +- Import users from spreadsheet and track progress + +User can: +- View, edit, and delete their own profile + +Visitor can: +- Register as a normal user + +## 🐳 Run with Docker +``` +docker-compose up --build +``` + +App available at: http://localhost:3000 + +## ⚙️ Run Locally +``` +bundle install +rails db:create db:migrate +bin/dev +``` + +## 🧪 Run Tests +``` +bundle exec rspec +``` + +## 📄 Notes + +Tests coverage ≥ 90% + +Includes .gitignore, .dockerignore, and SCSS styling \ No newline at end of file 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/config/manifest.js b/app/assets/config/manifest.js new file mode 100644 index 000000000..65b736aa8 --- /dev/null +++ b/app/assets/config/manifest.js @@ -0,0 +1,3 @@ +//= link_tree ../images +//= link_tree ../builds +//= link application.css \ No newline at end of file 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.scss b/app/assets/stylesheets/application.scss new file mode 100644 index 000000000..9bb639d13 --- /dev/null +++ b/app/assets/stylesheets/application.scss @@ -0,0 +1,181 @@ +@use "bulma/bulma" as *; + +/* =============================== + Global Theme */ +:root { + --primary-color: #5a4fcf; + --primary-color-dark: #463eb3; + --secondary-color: #232946; + --accent-color: #eebbc3; + --light-bg: #f5f6fa; + --text-dark: #2b2d42; + --text-light: #f9f9f9; +} + +body { + background-color: var(--light-bg); + font-family: "Inter", "Roboto", sans-serif; + color: var(--text-dark); + line-height: 1.7; +} + +/* =============================== + Navbar */ +.navbar { + background: linear-gradient(90deg, var(--primary-color-dark), var(--primary-color)); + box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15); + + .navbar-item, .navbar-link { + color: var(--text-light) !important; + font-weight: 500; + transition: background-color 0.3s ease, color 0.3s ease; + } + + .navbar-item:hover { + background-color: rgba(255, 255, 255, 0.1); + } + + .button.is-danger.is-light { + background-color: #ff6b6b; + border: none; + color: white; + transition: all 0.2s ease; + } + + .button.is-danger.is-light:hover { + background-color: #e63946; + } + + .button.is-light { + background-color: var(--accent-color); + color: var(--secondary-color); + } +} + +/* =============================== + Sections & Containers */ +.section { + padding-top: 3rem; + padding-bottom: 3rem; +} + +.container { + max-width: 1080px; + margin: 0 auto; +} + +/* =============================== + Flash Messages */ +.notification { + border-radius: 10px; + font-weight: 500; + padding: 1rem 1.5rem; + box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05); + margin-bottom: 1.5rem; + position: relative; + border-left: 6px solid transparent; + animation: fadeIn 0.4s ease; + + &.is-success { + background-color: #eafaf1; + border-left-color: #38b000; + color: #155724; + } + + &.is-danger { + background-color: #ffe5e5; + border-left-color: #e63946; + color: #9b1d1d; + } + + &.is-info { + background-color: #e7f0ff; + border-left-color: #0077b6; + color: #0a3d62; + } + + .delete { + float: right; + background: none; + border: none; + font-size: 1.2rem; + } +} + +@keyframes fadeIn { + from { opacity: 0; transform: translateY(-10px); } + to { opacity: 1; transform: translateY(0); } +} + +/* =============================== + Buttons */ +.button { + border-radius: 8px; + transition: all 0.25s ease; + font-weight: 500; + + &.is-primary { + background-color: var(--primary-color); + color: white; + border: none; + + &:hover { + background-color: var(--primary-color-dark); + transform: translateY(-2px); + box-shadow: 0 4px 10px rgba(90, 79, 207, 0.4); + } + } + + &.is-light { + background-color: var(--accent-color); + color: var(--secondary-color); + + &:hover { + background-color: #fcd5da; + } + } +} + +/* =============================== + Cards */ +.card { + border-radius: 14px; + background-color: white; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); + transition: transform 0.25s ease, box-shadow 0.25s ease; + + &:hover { + transform: translateY(-4px); + box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12); + } + + .card-content { + padding: 2rem; + } +} + +/* =============================== + Forms */ +input, select, textarea { + border-radius: 8px; + border: 1px solid #ddd; + padding: 0.75rem; + width: 100%; + transition: all 0.2s ease; + + &:focus { + border-color: var(--primary-color); + box-shadow: 0 0 0 0.125em rgba(90, 79, 207, 0.25); + } +} + +/* =============================== + Footer */ +footer.footer { + background-color: var(--secondary-color); + color: var(--text-light); + text-align: center; + padding: 2rem 1rem; + margin-top: 3rem; + font-size: 0.95rem; +} diff --git a/app/channels/application_cable/channel.rb b/app/channels/application_cable/channel.rb new file mode 100644 index 000000000..d67269728 --- /dev/null +++ b/app/channels/application_cable/channel.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/app/channels/application_cable/connection.rb b/app/channels/application_cable/connection.rb new file mode 100644 index 000000000..0ff5442f4 --- /dev/null +++ b/app/channels/application_cable/connection.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/app/controllers/admin/dashboard_controller.rb b/app/controllers/admin/dashboard_controller.rb new file mode 100644 index 000000000..bcc99233b --- /dev/null +++ b/app/controllers/admin/dashboard_controller.rb @@ -0,0 +1,25 @@ +module Admin + class DashboardController < ApplicationController + layout 'admin' + + include Authorizable + before_action :require_admin! + + def index + require_admin! + + metrics = { + total_users: User.count, + users_by_role: { + admin: User.admin.count, + user: User.user.count + } + } + + respond_to do |format| + format.json { render json: metrics } + format.html { render json: metrics } + end + end + end +end diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb new file mode 100644 index 000000000..54b05c0da --- /dev/null +++ b/app/controllers/admin/users_controller.rb @@ -0,0 +1,69 @@ +module Admin + class UsersController < ApplicationController + layout 'admin' + + include Authorizable + before_action :require_admin! + + def index + @users = if params[:query].present? + User.where("full_name ILIKE :query OR email ILIKE :query", query: "%#{params[:query]}%") + .order(:full_name) + else + User.all.order(:full_name) + end + end + + def new + @user = User.new + end + + def create + @user = User.new(user_params) + if @user.save + redirect_to admin_users_path, notice: 'Usuário criado com sucesso' + else + flash.now[:alert] = 'Usuário não pôde ser criado' + render :new, status: :unprocessable_entity + end + end + + def edit + @user = User.find(params[:id]) + end + + def update + @user = User.find(params[:id]) + if @user.update(user_params) + redirect_to admin_users_path, notice: 'Usuário atualizado com sucesso' + else + flash.now[:alert] = 'Usuário não pôde ser atualizado' + render :edit, status: :unprocessable_entity + end + end + + def destroy + @user = User.find(params[:id]) + @user.destroy + redirect_to admin_users_path, notice: 'Usuário excluído com sucesso' + end + + def toggle_role + @user = User.find(params[:id]) + + if @user.admin? + @user.user! + else + @user.admin! + end + + redirect_to admin_users_path, notice: 'Função do usuário atualizada com sucesso' + end + + private + + def user_params + params.require(:user).permit(:full_name, :email, :password, :role) + end + end +end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb new file mode 100644 index 000000000..1ddf44efc --- /dev/null +++ b/app/controllers/application_controller.rb @@ -0,0 +1,25 @@ +class ApplicationController < ActionController::Base + include Authorizable + before_action :configure_permitted_parameters, if: :devise_controller? + + protected + + def configure_permitted_parameters + devise_parameter_sanitizer.permit(:sign_up, keys: [:full_name]) + devise_parameter_sanitizer.permit(:account_update, keys: [:full_name]) + end + + # redirecionamento após login + def after_sign_in_path_for(resource) + if resource.admin? + dashboard_index_path + else + dashboard_index_path # Por enquanto todos vão para dashboard + end + end + + # redirecionamento após cadastro + def after_sign_up_path_for(resource) + dashboard_index_path + end +end \ No newline at end of file diff --git a/app/controllers/concerns/.keep b/app/controllers/concerns/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/controllers/concerns/authorizable.rb b/app/controllers/concerns/authorizable.rb new file mode 100644 index 000000000..36f541311 --- /dev/null +++ b/app/controllers/concerns/authorizable.rb @@ -0,0 +1,29 @@ +module Authorizable + extend ActiveSupport::Concern + + included do + rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized if defined?(Pundit) + end + + private + + def require_admin! + unless user_signed_in? + redirect_to new_user_session_path, alert: 'Você precisa fazer login antes de continuar.' + return + end + + unless current_user.admin? + redirect_to root_path, alert: 'Acesso restrito a administradores' + end + end + + def require_user! + authenticate_user! + end + + def user_not_authorized + flash[:alert] = 'Você não tem autorização para realizar esta ação.' + redirect_to(request.referrer || root_path) + end +end \ No newline at end of file diff --git a/app/controllers/dashboard_controller.rb b/app/controllers/dashboard_controller.rb new file mode 100644 index 000000000..de96f6892 --- /dev/null +++ b/app/controllers/dashboard_controller.rb @@ -0,0 +1,7 @@ +class DashboardController < ApplicationController + before_action :authenticate_user! + + def index + @user = current_user + end +end \ No newline at end of file diff --git a/app/controllers/pages_controller.rb b/app/controllers/pages_controller.rb new file mode 100644 index 000000000..45f463e4c --- /dev/null +++ b/app/controllers/pages_controller.rb @@ -0,0 +1,4 @@ +class PagesController < ApplicationController + def home + end +end diff --git a/app/controllers/profiles_controller.rb b/app/controllers/profiles_controller.rb new file mode 100644 index 000000000..741f18680 --- /dev/null +++ b/app/controllers/profiles_controller.rb @@ -0,0 +1,39 @@ +class ProfilesController < ApplicationController + before_action :authenticate_user! + before_action :set_user + before_action :ensure_correct_user, only: %i[show edit update destroy] + + def show; end + + def edit; end + + def update + if @user.update(user_params) + redirect_to profile_path, notice: 'Perfil atualizado com sucesso' + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + @user.destroy + redirect_to root_path, notice: 'Conta excluída com sucesso.' + end + + private + + def set_user + @user = User.find(params[:id]) if params[:id] + @user ||= current_user + end + + def ensure_correct_user + unless @user == current_user + redirect_to root_path, alert: 'Acesso não autorizado' + end + end + + def user_params + params.require(:user).permit(:full_name, :email, :avatar) + end +end 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/helpers/dashboard_helper.rb b/app/helpers/dashboard_helper.rb new file mode 100644 index 000000000..a94ddfc2e --- /dev/null +++ b/app/helpers/dashboard_helper.rb @@ -0,0 +1,2 @@ +module DashboardHelper +end diff --git a/app/helpers/pages_helper.rb b/app/helpers/pages_helper.rb new file mode 100644 index 000000000..2c057fd05 --- /dev/null +++ b/app/helpers/pages_helper.rb @@ -0,0 +1,2 @@ +module PagesHelper +end diff --git a/app/javascript/packs/avatar_preview.js b/app/javascript/packs/avatar_preview.js new file mode 100644 index 000000000..d1d08bb30 --- /dev/null +++ b/app/javascript/packs/avatar_preview.js @@ -0,0 +1,18 @@ +document.addEventListener("DOMContentLoaded", () => { + const fileInput = document.getElementById("user_avatar"); + const previewImage = document.getElementById("avatar-preview"); + + if (fileInput && previewImage) { + fileInput.addEventListener("change", (event) => { + const file = event.target.files[0]; + if (!file) return; + + const reader = new FileReader(); + reader.onload = (e) => { + previewImage.src = e.target.result; + previewImage.style.display = "block"; + }; + reader.readAsDataURL(file); + }); + } +}); 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..8b59d5344 --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,52 @@ +require 'open-uri' + +class User < ApplicationRecord + devise :database_authenticatable, :registerable, + :recoverable, :rememberable, :validatable, :trackable + + has_one_attached :avatar + + attr_accessor :avatar_url + + enum role: { user: 0, admin: 1 } + + validates :full_name, presence: true, length: { minimum: 2, maximum: 100 } + validates :email, presence: true, uniqueness: true, format: { with: URI::MailTo::EMAIL_REGEXP } + validate :avatar_validation + + before_validation :attach_avatar_from_url, if: -> { avatar_url.present? && avatar.blank? } + + after_initialize :set_default_role, if: :new_record? + + private + + def set_default_role + self.role ||= :user + end + + def avatar_validation + return unless avatar.attached? + + if avatar.byte_size > 5.megabytes + errors.add(:avatar, 'is too large (max 5MB)') + end + + acceptable_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'] + unless acceptable_types.include?(avatar.content_type) + errors.add(:avatar, 'must be a JPEG, PNG, or GIF') + end + end + + def attach_avatar_from_url + begin + file = URI.open(avatar_url) + filename = File.basename(URI.parse(avatar_url).path.presence || 'avatar.png') + content_type = file.respond_to?(:content_type) ? file.content_type : 'image/png' + + avatar.attach(io: file, filename: filename, content_type: content_type) + rescue StandardError + errors.add(:avatar_url, 'não pôde ser carregado') + throw(:abort) + end + end +end \ No newline at end of file diff --git a/app/views/admin/dashboard/index.html.erb b/app/views/admin/dashboard/index.html.erb new file mode 100644 index 000000000..9c9adbcf9 --- /dev/null +++ b/app/views/admin/dashboard/index.html.erb @@ -0,0 +1,38 @@ +
+
+

Painel Administrativo

+

Visão geral do sistema

+ +
+
+
+ + + +

Usuários Totais

+

<%= User.count %>

+
+
+ +
+
+ + + +

Usuários Comuns

+

<%= User.user.count %>

+
+
+ +
+
+ + + +

Administradores

+

<%= User.admin.count %>

+
+
+
+
+
diff --git a/app/views/admin/users/_form.html.erb b/app/views/admin/users/_form.html.erb new file mode 100644 index 000000000..c4e0e596d --- /dev/null +++ b/app/views/admin/users/_form.html.erb @@ -0,0 +1,46 @@ +
+ <%= form_with model: [:admin, @user], local: true do |f| %> +

Gerenciar Usuário

+ +
+ <%= f.label :full_name, "Nome completo", class: "label has-text-weight-semibold" %> +
+ <%= f.text_field :full_name, class: "input", placeholder: "Digite o nome completo" %> + +
+
+ +
+ <%= f.label :email, "Email", class: "label has-text-weight-semibold" %> +
+ <%= f.email_field :email, class: "input", placeholder: "email@exemplo.com" %> + +
+
+ +
+ <%= f.label :password, "Senha (opcional)", class: "label has-text-weight-semibold" %> +
+ <%= f.password_field :password, class: "input", placeholder: "••••••••" %> + +
+
+ +
+ <%= f.label :role, "Função", class: "label has-text-weight-semibold" %> +
+
+ <%= f.select :role, User.roles.keys.map { |r| [r.titleize, r] } %> +
+ +
+
+ +
+
+ <%= f.submit "Salvar", class: "button is-primary is-medium mr-2" %> + <%= link_to "Cancelar", admin_users_path, class: "button is-light is-medium" %> +
+
+ <% end %> +
diff --git a/app/views/admin/users/edit.html.erb b/app/views/admin/users/edit.html.erb new file mode 100644 index 000000000..fd7f82eb5 --- /dev/null +++ b/app/views/admin/users/edit.html.erb @@ -0,0 +1,8 @@ +
+
+
+

Editar Usuário

+ <%= render "form" %> +
+
+
diff --git a/app/views/admin/users/index.html.erb b/app/views/admin/users/index.html.erb new file mode 100644 index 000000000..0e631b1a9 --- /dev/null +++ b/app/views/admin/users/index.html.erb @@ -0,0 +1,74 @@ +
+
+
+

Gerenciamento de Usuários

+ + +
+
+ <%= form_with url: admin_users_path, method: :get, local: true, class: "is-fullwidth" do |f| %> +
+
+ <%= f.text_field :q, value: @query, placeholder: "Buscar por nome ou email", class: "input is-rounded" %> +
+
+ <%= f.submit "Buscar", class: "button is-primary" %> +
+
+ <% end %> +
+ +
+
+ <%= link_to "Novo Usuário", new_admin_user_path, class: "button is-link is-rounded" %> +
+
+
+ + +
+ + + + + + + + + + + <% @users.each do |user| %> + + + + + + + <% end %> + +
NomeEmailFunçãoAções
<%= user.full_name %><%= user.email %> + <% if user.admin? %> + admin + <% else %> + user + <% end %> + + <%= link_to edit_admin_user_path(user), class: "button is-small is-info is-light mr-2" do %> + + <% end %> + + <%= link_to admin_user_path(user), + method: :delete, + data: { confirm: "Tem certeza que deseja excluir #{user.full_name}?" }, + class: "button is-small is-danger is-light" do %> + + <% end %> +
+
+ + <% if @users.empty? %> +

Nenhum usuário encontrado.

+ <% end %> +
+
+
diff --git a/app/views/admin/users/new.html.erb b/app/views/admin/users/new.html.erb new file mode 100644 index 000000000..0d3b04114 --- /dev/null +++ b/app/views/admin/users/new.html.erb @@ -0,0 +1,8 @@ +
+
+
+

Novo Usuário

+ <%= render "form" %> +
+
+
diff --git a/app/views/dashboard/index.html.erb b/app/views/dashboard/index.html.erb new file mode 100644 index 000000000..a79c11295 --- /dev/null +++ b/app/views/dashboard/index.html.erb @@ -0,0 +1,36 @@ +
+
+
+ +

+ Welcome, <%= @user.full_name %>! +

+ +

+ Role: + + <%= @user.role %> + +

+ +
+ <%= link_to 'Edit Profile', edit_user_registration_path, class: 'button', style: 'background-color: #5a4fcf; color: white; border: none; font-weight: 500; border-radius: 8px; padding: 0.75em 1.5em; transition: 0.3s;' %> + + <%= button_to 'Logout', destroy_user_session_path, method: :delete, + class: 'button', + style: 'background-color: #e63946; color: white; border: none; font-weight: 500; border-radius: 8px; padding: 0.75em 1.5em; transition: 0.3s;' %> +
+ +
+
+
+ + 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..b82e3365a --- /dev/null +++ b/app/views/devise/registrations/edit.html.erb @@ -0,0 +1,43 @@ +

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" %> +
+ + <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %> +
Currently waiting confirmation for: <%= resource.unconfirmed_email %>
+ <% end %> + +
+ <%= 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..40466eb2b --- /dev/null +++ b/app/views/devise/registrations/new.html.erb @@ -0,0 +1,54 @@ +
+
+
+
+
+

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: 'label' %> +
+ <%= f.text_field :full_name, autofocus: true, class: 'input', placeholder: 'John Doe' %> +
+
+ +
+ <%= f.label :email, class: 'label' %> +
+ <%= f.email_field :email, autocomplete: "email", class: 'input', placeholder: 'john@example.com' %> +
+
+ +
+ <%= f.label :password, class: 'label' %> + <% if @minimum_password_length %> + (<%= @minimum_password_length %> characters minimum) + <% end %> +
+ <%= f.password_field :password, autocomplete: "new-password", class: 'input' %> +
+
+ +
+ <%= f.label :password_confirmation, class: 'label' %> +
+ <%= f.password_field :password_confirmation, autocomplete: "new-password", class: 'input' %> +
+
+ +
+
+ <%= f.submit "Sign up", class: 'button is-primary is-fullwidth' %> +
+
+ <% end %> + + <%= render "devise/shared/links" %> +
+
+
+
+
\ No newline at end of file diff --git a/app/views/devise/sessions/new.html.erb b/app/views/devise/sessions/new.html.erb new file mode 100644 index 000000000..c32f8dd64 --- /dev/null +++ b/app/views/devise/sessions/new.html.erb @@ -0,0 +1,48 @@ +
+
+
+
+
+

Log in

+ + <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %> +
+ <%= f.label :email, class: 'label has-text-weight-semibold' %> +
+ <%= f.email_field :email, autofocus: true, autocomplete: "email", class: 'input is-medium', placeholder: 'your@email.com' %> + +
+
+ +
+ <%= f.label :password, class: 'label has-text-weight-semibold' %> +
+ <%= f.password_field :password, autocomplete: "current-password", class: 'input is-medium', placeholder: '••••••••' %> + +
+
+ + <% if devise_mapping.rememberable? %> +
+ +
+ <% end %> + +
+
+ <%= f.submit "Log in", class: 'button is-primary is-fullwidth is-medium' %> +
+
+ <% 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) + %> +

+ +
+<% 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" %> diff --git a/app/views/layouts/admin.html.erb b/app/views/layouts/admin.html.erb new file mode 100644 index 000000000..e1a8888c3 --- /dev/null +++ b/app/views/layouts/admin.html.erb @@ -0,0 +1,56 @@ + + + + Umanni Admin + + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> + <%= javascript_importmap_tags %> + + + + + +
+
+ <% flash.each do |key, message| %> +
+ <%= message %> +
+ <% end %> + +
+
+ <%= yield %> +
+
+
+
+ + + + diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb new file mode 100644 index 000000000..57292cefb --- /dev/null +++ b/app/views/layouts/application.html.erb @@ -0,0 +1,95 @@ + + + + Umanni App + + + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> + + + + + + + + +
+
+ <% flash.each do |type, message| %> + <% css_class = + case type.to_sym + when :notice then "notification is-success" + when :alert then "notification is-danger" + else "notification is-info" + end %> + +
+ + <%= message %> +
+ <% end %> +
+
+ + +
+
+ <%= 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/pages/home.html.erb b/app/views/pages/home.html.erb new file mode 100644 index 000000000..2ee76fdf8 --- /dev/null +++ b/app/views/pages/home.html.erb @@ -0,0 +1,23 @@ +
+
+
+

Umanni Fullstack Challenge

+

Sistema de Gestão de Usuários

+ + <% if user_signed_in? %> +
+ <%= link_to "Meu Perfil", profile_path, class: "button is-light is-medium" %> + <% if current_user.admin? %> + <%= link_to "Painel Admin", admin_dashboard_path, class: "button is-primary is-medium" %> + <% end %> + <%= button_to "Sair", destroy_user_session_path, method: :delete, class: "button is-danger is-medium" %> +
+ <% else %> +
+ <%= link_to "Entrar", new_user_session_path, class: "button is-primary is-medium" %> + <%= link_to "Cadastrar", new_user_registration_path, class: "button is-light is-medium" %> +
+ <% end %> +
+
+
diff --git a/app/views/profiles/edit.html.erb b/app/views/profiles/edit.html.erb new file mode 100644 index 000000000..bffa3594d --- /dev/null +++ b/app/views/profiles/edit.html.erb @@ -0,0 +1,80 @@ +
+
+
+

Editar Perfil

+ + <%= form_with model: @user, url: profile_path, local: true, html: { multipart: true } do |f| %> +
+ <%= f.label :full_name, 'Nome completo', class: 'label has-text-weight-semibold' %> +
+ <%= f.text_field :full_name, class: 'input', placeholder: 'Seu nome completo' %> + +
+
+ +
+ <%= f.label :email, 'Email', class: 'label has-text-weight-semibold' %> +
+ <%= f.email_field :email, class: 'input', placeholder: 'email@exemplo.com' %> + +
+
+ +
+ <%= f.label :avatar, 'Foto de Perfil', class: 'label has-text-weight-semibold' %> +
+ +
+ +
+ <% if @user.avatar.attached? %> + <%= image_tag(@user.avatar, id: 'avatar-preview', class: 'is-rounded has-shadow') %> + <% else %> + + <% end %> +
+
+ +
+
+ <%= f.submit 'Salvar alterações', class: 'button is-primary is-medium' %> +
+
+ <% end %> +
+
+
+ + diff --git a/app/views/profiles/show.html.erb b/app/views/profiles/show.html.erb new file mode 100644 index 000000000..565548472 --- /dev/null +++ b/app/views/profiles/show.html.erb @@ -0,0 +1,26 @@ +
+
+
+

Meu Perfil

+ +
+ <% if @user.avatar.attached? %> + <%= image_tag @user.avatar, class: 'is-rounded has-shadow' %> + <% else %> + + <% end %> +
+ +

Nome: <%= @user.full_name %>

+

Email: <%= @user.email %>

+ +
+ <%= link_to 'Editar Perfil', edit_profile_path, class: 'button is-primary' %> + <%= button_to 'Excluir Conta', profile_path, + method: :delete, + data: { confirm: 'Tem certeza que deseja excluir sua conta?' }, + class: 'button is-danger' %> +
+
+
+
diff --git a/app/views/pwa/manifest.json.erb b/app/views/pwa/manifest.json.erb new file mode 100644 index 000000000..c295730cd --- /dev/null +++ b/app/views/pwa/manifest.json.erb @@ -0,0 +1,22 @@ +{ + "name": "App", + "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": "App.", + "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/dev b/bin/dev new file mode 100755 index 000000000..d80a02dbc --- /dev/null +++ b/bin/dev @@ -0,0 +1,11 @@ +#!/usr/bin/env sh + +if gem list --no-installed --exact --silent foreman; then + echo "Installing foreman..." + gem install foreman +fi + +# Default to port 3000 if not specified +export PORT="${PORT:-3000}" + +exec foreman start -f Procfile.dev --env /dev/null "$@" diff --git a/bin/docker-entrypoint b/bin/docker-entrypoint new file mode 100755 index 000000000..840d093a9 --- /dev/null +++ b/bin/docker-entrypoint @@ -0,0 +1,13 @@ +#!/bin/bash -e + +# Enable jemalloc for reduced memory usage and latency. +if [ -z "${LD_PRELOAD+x}" ] && [ -f /usr/lib/*/libjemalloc.so.2 ]; then + export LD_PRELOAD="$(echo /usr/lib/*/libjemalloc.so.2)" +fi + +# If running the rails server then create or migrate existing database +if [ "${1}" == "./bin/rails" ] && [ "${2}" == "server" ]; then + ./bin/rails db:prepare +fi + +exec "${@}" 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..eb1e55ed7 --- /dev/null +++ b/bin/setup @@ -0,0 +1,37 @@ +#!/usr/bin/env ruby +require "fileutils" + +APP_ROOT = File.expand_path("..", __dir__) +APP_NAME = "app" + +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! "gem install bundler --conservative" + 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" + + puts "\n== Restarting application server ==" + system! "bin/rails restart" + + # puts "\n== Configuring puma-dev ==" + # system "ln -nfs #{APP_ROOT} ~/.puma-dev/#{APP_NAME}" + # system "curl -Is https://#{APP_NAME}.test/up | head -n 1" +end 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..96749f2a0 --- /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 App + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 7.1 + + # 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..f39dc046c --- /dev/null +++ b/config/cable.yml @@ -0,0 +1,10 @@ +development: + adapter: async + +test: + adapter: test + +production: + adapter: redis + url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> + channel_prefix: app_production diff --git a/config/credentials.yml.enc b/config/credentials.yml.enc new file mode 100644 index 000000000..b7e62f4b1 --- /dev/null +++ b/config/credentials.yml.enc @@ -0,0 +1 @@ +wfSes04O0X4wi5ZMwCqBcUU4oL0Ggd1B8wguPPgQpsRmAENcxROBboP5J6R3KYaQ6U6iafN1lrNqzTE9qI4Mio0ga7IluhyNFbmlet3HfeshQ/21Zht2ITJIqMVc6T6aITXlkB8uk9Qq/9PWLV9CiZOApyRWh4Cou7S8Fj8Qfp+EwsWc8VUlsT2bmuAYrZNlwKBZqxFOsWa6fi7MWvBVAGQ9F22Nh9nH3/K0g9RR1JMrijwC9QIXQPTzAPVVpx7HZg33Zq0kPFOnBaZ454ClHbb+JLtnzm9kE166IdtU5SQCteOD4rYKjoe8fMMJDooBG4Pk1TJdLUUSRQQmkPTq++jDZrod9ClSY5j3k9spu2t0gPn0vnkYYqyPeI5GTCtAYP9SffFRZQl7BhgVAAHAyAgAFYQk--KV7g5e9nyFWyQyqx--xRRmfAC62uAH1geLiQgxrw== \ No newline at end of file diff --git a/config/database.yml b/config/database.yml new file mode 100644 index 000000000..47f136f13 --- /dev/null +++ b/config/database.yml @@ -0,0 +1,19 @@ +default: &default + adapter: postgresql + encoding: unicode + host: <%= ENV.fetch("DATABASE_HOST") { "db" } %> + username: <%= ENV.fetch("POSTGRES_USER") { "postgres" } %> + password: <%= ENV.fetch("POSTGRES_PASSWORD") { "password" } %> + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + +development: + <<: *default + database: umanni_development + +test: + <<: *default + database: umanni_test + +production: + <<: *default + database: <%= ENV.fetch("POSTGRES_DB") { "umanni_production" } %> \ No newline at end of file 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..b28c782b3 --- /dev/null +++ b/config/environments/development.rb @@ -0,0 +1,76 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded any time + # it changes. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + 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 caching. By default caching is disabled. + # Run rails dev:cache to toggle 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.cache_store = :memory_store + config.public_file_server.headers = { + "Cache-Control" => "public, max-age=#{2.days.to_i}" + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # 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 + + config.action_mailer.perform_caching = false + + # Default URL for mailers + config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # 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 + + # 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 +end \ No newline at end of file diff --git a/config/environments/production.rb b/config/environments/production.rb new file mode 100644 index 000000000..bfc86e4e4 --- /dev/null +++ b/config/environments/production.rb @@ -0,0 +1,105 @@ +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. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Ensures that a master key has been made available in ENV["RAILS_MASTER_KEY"], config/master.key, or an environment + # key such as config/credentials/production.key. This key is used to decrypt credentials (and other encrypted files). + # config.require_master_key = true + + # Disable serving static files from `public/`, relying on NGINX/Apache to do so instead. + # config.public_file_server.enabled = false + + # Compress CSS using a preprocessor. + # config.assets.css_compressor = :sass + + # Do not fall back to assets pipeline if a precompiled asset is missed. + config.assets.compile = false + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = "http://assets.example.com" + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache + # config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Mount Action Cable outside main process or domain. + # config.action_cable.mount_path = nil + # config.action_cable.url = "wss://example.com/cable" + # config.action_cable.allowed_request_origins = [ "http://example.com", /http:\/\/example.*/ ] + + # Assume all access to the app is happening through a SSL-terminating reverse proxy. + # Can be used together with config.force_ssl for Strict-Transport-Security and secure cookies. + # 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 by default + config.logger = ActiveSupport::Logger.new(STDOUT) + .tap { |logger| logger.formatter = ::Logger::Formatter.new } + .then { |logger| ActiveSupport::TaggedLogging.new(logger) } + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # "info" includes generic and useful information about system operation, but avoids logging too much + # information to avoid inadvertent exposure of personally identifiable information (PII). If you + # want to log everything, set the level to "debug". + config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment). + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "app_production" + + # Disable caching for Action Mailer templates even if Action Controller + # caching is enabled. + config.action_mailer.perform_caching = false + + # 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 + + # 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 + + # Don't log any deprecations. + config.active_support.report_deprecations = false + + # 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..0c616a1bf --- /dev/null +++ b/config/environments/test.rb @@ -0,0 +1,67 @@ +require "active_support/core_ext/integer/time" + +# 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=#{1.hour.to_i}" } + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + 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 + + # Disable caching for Action Mailer templates even if Action Controller + # caching is enabled. + config.action_mailer.perform_caching = false + + # 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 + + # Unlike controllers, the mailer instance doesn't have any context about the + # incoming request so you'll need to provide the :host parameter yourself. + config.action_mailer.default_url_options = { host: "www.example.com" } + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # 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/initializers/assets.rb b/config/initializers/assets.rb new file mode 100644 index 000000000..e69de29bb 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..6498533c1 --- /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 = '7747ae4091bd7513606ae9932d60b9d7ae5df069f4507fbefc941917dd3a6d0352f1296b96e5ec4ce4876719926ed99558bc0e1e70d35b55ddb46e2c291509af' + + # ==> 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 = 'f04e7f5e6c609b624ecf9fecae4a62c7ff8c8053e104a51ec3f5e793cb571b17d98ce879932f3eefc6f632e1298df0ba99219c678d91a22965bd1b452f91d19d' + + # 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..c010b83dd --- /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 +] 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/initializers/permissions_policy.rb b/config/initializers/permissions_policy.rb new file mode 100644 index 000000000..7db3b9577 --- /dev/null +++ b/config/initializers/permissions_policy.rb @@ -0,0 +1,13 @@ +# Be sure to restart your server when you modify this file. + +# Define an application-wide HTTP permissions policy. For further +# information see: https://developers.google.com/web/updates/2018/06/feature-policy + +# Rails.application.config.permissions_policy do |policy| +# policy.camera :none +# policy.gyroscope :none +# policy.microphone :none +# policy.usb :none +# policy.fullscreen :self +# policy.payment :self, "https://secure.example.com" +# 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..03c166f4c --- /dev/null +++ b/config/puma.rb @@ -0,0 +1,34 @@ +# 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. +# +# 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 +# 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 + +# 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/routes.rb b/config/routes.rb new file mode 100644 index 000000000..8916737d1 --- /dev/null +++ b/config/routes.rb @@ -0,0 +1,24 @@ +Rails.application.routes.draw do + devise_for :users + # Root (visitantes) + root 'pages#home' + + get 'pages/home' + + # Authenticated routes + authenticated :user do + root to: 'dashboard#index', as: :authenticated_root + resource :profile, only: %i[show edit update destroy] + end + + # Admin routes + namespace :admin do + get 'dashboard', to: 'dashboard#index' + resources :users, only: [:index, :new, :create, :edit, :update, :destroy] do + patch :toggle_role, on: :member + end + end + + # Dashboard público + get 'dashboard/index' +end \ No newline at end of file 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/migrate/20251106030818_devise_create_users.rb b/db/migrate/20251106030818_devise_create_users.rb new file mode 100644 index 000000000..a56ec1fcb --- /dev/null +++ b/db/migrate/20251106030818_devise_create_users.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +class DeviseCreateUsers < ActiveRecord::Migration[7.1] + def change + create_table :users do |t| + ## Database authenticatable + t.string :email, null: false, default: "" + t.string :encrypted_password, null: false, default: "" + + ## Custom fields + t.string :full_name, null: false + t.integer :role, null: false, default: 0 + + ## 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 + + t.timestamps null: false + end + + add_index :users, :email, unique: true + add_index :users, :reset_password_token, unique: true + end +end diff --git a/db/migrate/20251106034457_create_active_storage_tables.active_storage.rb b/db/migrate/20251106034457_create_active_storage_tables.active_storage.rb new file mode 100644 index 000000000..e4706aa21 --- /dev/null +++ b/db/migrate/20251106034457_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/schema.rb b/db/schema.rb new file mode 100644 index 000000000..eff6ec666 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,66 @@ +# 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[7.1].define(version: 2025_11_06_034457) do + # These are extensions that must be enabled in order to support this database + enable_extension "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 "full_name", null: false + t.integer "role", default: 0, null: false + t.string "reset_password_token" + t.datetime "reset_password_sent_at" + t.datetime "remember_created_at" + 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" + t.datetime "created_at", null: false + t.datetime "updated_at", 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..08ea243df --- /dev/null +++ b/db/seeds.rb @@ -0,0 +1,47 @@ +# 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 + +# docker compose up -d +# docker compose exec web rails db:seed +require 'faker' + +puts "🧹 Limpando banco de dados..." +User.destroy_all + +puts "👑 Criando administrador..." +admin = User.create!( + full_name: "Administrador", + email: "admin@email", + password: "123456", + password_confirmation: "123456", + role: :admin +) + +puts "✅ Admin criado: #{admin.email}" + +puts "👥 Criando usuários comuns..." +3.times do + user = User.create!( + full_name: Faker::Name.name, + email: Faker::Internet.unique.email, + password: "123456", + password_confirmation: "123456", + role: :user + ) + + # Avatar aleatório via URL (usando LoremFlickr) + file = URI.open("https://loremflickr.com/300/300/portrait?lock=#{rand(1..9999)}") + user.avatar.attach(io: file, filename: "avatar_#{user.id}.jpg", content_type: 'image/jpeg') + + puts "👤 Criado usuário: #{user.full_name} (#{user.email})" +end + +puts "🎉 Seeds finalizados com sucesso!" +puts "Login do admin: admin@email / senha: 123456" diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 000000000..8ad2149d3 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,40 @@ +services: + db: + image: postgres:16 + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: password + POSTGRES_DB: umanni_development + volumes: + - postgres_data:/var/lib/postgresql/data + ports: + - "5432:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U postgres"] + interval: 5s + timeout: 5s + retries: 5 + + web: + build: . + command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails server -b 0.0.0.0" + volumes: + - .:/app + - bundle_cache:/usr/local/bundle + ports: + - "3000:3000" + depends_on: + db: + condition: service_healthy + environment: + DATABASE_HOST: db + POSTGRES_USER: postgres + POSTGRES_PASSWORD: password + POSTGRES_DB: umanni_development + RAILS_ENV: ${RAILS_ENV:-development} + stdin_open: true + tty: true + +volumes: + postgres_data: + bundle_cache: \ No newline at end of file diff --git a/lib/assets/.keep b/lib/assets/.keep new file mode 100644 index 000000000..e69de29bb 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/package.json b/package.json new file mode 100644 index 000000000..e5e09e98e --- /dev/null +++ b/package.json @@ -0,0 +1,11 @@ +{ + "name": "app", + "private": "true", + "dependencies": { + "bulma": "^1.0.4", + "sass": "^1.93.3" + }, + "scripts": { + "build:css": "sass ./app/assets/stylesheets/application.scss:./app/assets/builds/application.css --no-source-map --load-path=node_modules" + } +} diff --git a/public/404.html b/public/404.html new file mode 100644 index 000000000..2be3af26f --- /dev/null +++ b/public/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+

If you are 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..7cf1e168e --- /dev/null +++ b/public/406-unsupported-browser.html @@ -0,0 +1,66 @@ + + + + Your browser is not supported (406) + + + + + + +
+
+

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..c08eac0d1 --- /dev/null +++ b/public/422.html @@ -0,0 +1,67 @@ + + + + The change you wanted was rejected (422) + + + + + + +
+
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+

If you are 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..78a030af2 --- /dev/null +++ b/public/500.html @@ -0,0 +1,66 @@ + + + + We're sorry, but something went wrong (500) + + + + + + +
+
+

We're sorry, but something went wrong.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/public/icon.png b/public/icon.png new file mode 100644 index 000000000..f3b5abcbd Binary files /dev/null and b/public/icon.png differ diff --git a/public/icon.svg b/public/icon.svg new file mode 100644 index 000000000..78307ccd4 --- /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/spec/factories/users.rb b/spec/factories/users.rb new file mode 100644 index 000000000..a2997d65b --- /dev/null +++ b/spec/factories/users.rb @@ -0,0 +1,13 @@ +FactoryBot.define do + factory :user do + full_name { Faker::Name.name } + email { Faker::Internet.unique.email } + password { 'password123' } + password_confirmation { 'password123' } + role { :user } + + trait :admin do + role { :admin } + end + end +end \ No newline at end of file diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb new file mode 100644 index 000000000..07b6fb42b --- /dev/null +++ b/spec/models/user_spec.rb @@ -0,0 +1,140 @@ +require 'rails_helper' +require 'stringio' + +RSpec.describe User, type: :model do + describe 'validations' do + it { should validate_presence_of(:full_name) } + it { should validate_presence_of(:email) } + it { should validate_length_of(:full_name).is_at_least(2).is_at_most(100) } + + it 'validates email format' do + user = build(:user, email: 'invalid_email') + + expect(user).not_to be_valid + expect(user.errors[:email]).to include('is invalid') + end + + it 'validates email uniqueness' do + create(:user, email: 'test@example.com') + user = build(:user, email: 'test@example.com') + + expect(user).not_to be_valid + end + end + + describe 'enums' do + it { should define_enum_for(:role).with_values(user: 0, admin: 1) } + end + + describe 'default values' do + it 'sets default role as user' do + user = User.new(full_name: 'Test', email: 'test@example.com', password: '123456') + + expect(user.role).to eq('user') + end + end + + describe 'role methods' do + let(:user) { create(:user) } + let(:admin) { create(:user, :admin) } + + it 'checks if user is admin' do + expect(user.admin?).to be false + expect(admin.admin?).to be true + end + + it 'checks if user is regular user' do + expect(user.user?).to be true + expect(admin.user?).to be false + end + end + + describe 'avatar attachment' do + it 'has one attached avatar' do + user = build(:user) + expect(user).to respond_to(:avatar) + end + + it 'validates file size' do + user = build(:user) + + fake_file_io = StringIO.new('a' * 6.megabytes) + + user.avatar.attach( + io: fake_file_io, + filename: 'large_file.png', + content_type: 'image/png' + ) + + user.valid? + + expect(user.errors[:avatar]).to include('is too large (max 5MB)') + end + + it 'validates content type' do + user = build(:user) + + fake_file_io = StringIO.new('this is not an image') + + user.avatar.attach( + io: fake_file_io, + filename: 'test.txt', + content_type: 'text/plain' + ) + + user.valid? + + expect(user.errors[:avatar]).to include('must be a JPEG, PNG, or GIF') + end + end + + describe 'avatar via URL' do + let(:user) { build(:user, full_name: 'Marcos', email: 'marcos@example.com', password: '123456') } + + context 'when URL is valid' do + it 'attaches avatar from given URL' do + # simula download da imagem com StringIO + fake_image = StringIO.new('fake image data') + allow(URI).to receive(:open).and_return(fake_image) + + user.avatar_url = 'https://example.com/avatar.png' + user.save + + expect(user.avatar).to be_attached + end + end + + context 'when URL is invalid' do + it 'adds error and aborts save' do + allow(URI).to receive(:open).and_raise(OpenURI::HTTPError.new('404 Not Found', nil)) + + user.avatar_url = 'https://invalid-url.com/avatar.png' + expect(user.save).to eq(false) + expect(user.errors[:avatar_url]).to include('não pôde ser carregado') + end + end + end + + describe 'authorization helpers' do + let(:user) { create(:user) } + let(:admin) { create(:user, :admin) } + + it 'user cannot be admin' do + expect(user.admin?).to be false + end + + it 'admin is admin' do + expect(admin.admin?).to be true + end + + it 'can change user to admin' do + user.admin! + expect(user.admin?).to be true + end + + it 'can change admin to user' do + admin.user! + expect(admin.user?).to be true + end + end +end \ No newline at end of file diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb new file mode 100644 index 000000000..14578398e --- /dev/null +++ b/spec/rails_helper.rb @@ -0,0 +1,100 @@ +require 'simplecov' +SimpleCov.start 'rails' do + add_filter 'channels' + add_filter 'mailers' + add_filter 'jobs' + add_filter '/spec/' + add_filter '/config/' + add_filter '/vendor/' + minimum_coverage 90 +end +# 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! + +require 'shoulda/matchers' +require 'database_cleaner/active_record' + +# 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 } + +# Checks for pending migrations and applies them before tests are run. +# 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| + config.before(type: :system) do + driven_by(:rack_test) + end + + # 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 + + # 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/7-1/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") + + # FactoryBot + config.include FactoryBot::Syntax::Methods +end + +# Shoulda Matchers +Shoulda::Matchers.configure do |config| + config.integrate do |with| + with.test_framework :rspec + with.library :rails + end +end \ No newline at end of file diff --git a/spec/requests/admin/dashboard_spec.rb b/spec/requests/admin/dashboard_spec.rb new file mode 100644 index 000000000..afa57d1f2 --- /dev/null +++ b/spec/requests/admin/dashboard_spec.rb @@ -0,0 +1,42 @@ +require 'rails_helper' + +RSpec.describe 'Admin::Dashboard', type: :request do + let(:admin) { create(:user, role: :admin) } + let(:user) { create(:user) } + + describe 'GET /admin/dashboard' do + context 'when admin is signed in' do + before { sign_in admin } + + it 'returns JSON metrics of users' do + get '/admin/dashboard' + + expect(response).to have_http_status(:ok) + + json = JSON.parse(response.body) + expect(json).to include('total_users', 'users_by_role') + expect(json['users_by_role']).to be_a(Hash) + end + end + + context 'when regular user is signed in' do + before { sign_in user } + + it 'redirects to root with alert' do + get '/admin/dashboard' + + expect(response).to redirect_to(root_path) + follow_redirect! + + expect(response.body).to include('Acesso restrito a administradores') + end + end + + context 'when not authenticated' do + it 'redirects to sign in' do + get '/admin/dashboard' + expect(response).to redirect_to(new_user_session_path) + end + end + end +end diff --git a/spec/requests/admin/users_spec.rb b/spec/requests/admin/users_spec.rb new file mode 100644 index 000000000..f03abb488 --- /dev/null +++ b/spec/requests/admin/users_spec.rb @@ -0,0 +1,175 @@ +require 'rails_helper' + +RSpec.describe "Admin::Users", type: :request do + let!(:admin) { create(:user, :admin) } + let!(:users) { create_list(:user, 3) } + + describe "GET /admin/users" do + context "when admin is signed in" do + before do + sign_in admin + get admin_users_path + end + + it "returns http success" do + expect(response).to have_http_status(:success) + end + + it "renders list of users" do + users.each do |user| + expect(response.body).to include(user.full_name) + end + end + end + + context "when regular user is signed in" do + let(:user) { create(:user) } + + before do + sign_in user + get admin_users_path + end + + it "redirects to root with alert" do + expect(response).to redirect_to(root_path) + follow_redirect! + expect(response.body).to include('Acesso restrito a administradores') + end + end + end + + describe "GET /admin/users with search query" do + let!(:admin) { create(:user, :admin) } + let!(:user_john) { create(:user, full_name: 'John Doe', email: 'john@example.com') } + let!(:user_jane) { create(:user, full_name: 'Jane Smith', email: 'jane@example.com') } + + before do + sign_in admin + end + + it "returns only matching users by name" do + get admin_users_path, params: { query: 'John' } + expect(response.body).to include('John Doe') + expect(response.body).not_to include('Jane Smith') + end + + it "returns only matching users by email" do + get admin_users_path, params: { query: 'jane@example.com' } + expect(response.body).to include('Jane Smith') + expect(response.body).not_to include('John Doe') + end + end + + describe "POST /admin/users" do + let(:admin) { create(:user, :admin) } + + before { sign_in admin } + + it "creates a new user with valid attributes" do + expect { + post admin_users_path, params: { + user: { + full_name: 'New User', + email: 'newuser@example.com', + password: '123456', + role: 'user' + } + } + }.to change(User, :count).by(1) + + follow_redirect! + expect(response.body).to include('Usuário criado com sucesso') + expect(User.last.full_name).to eq('New User') + end + + it "does not create user with invalid data" do + expect { + post admin_users_path, params: { + user: { + full_name: '', + email: 'invalid', + password: '', + role: 'user' + } + } + }.not_to change(User, :count) + + expect(response.body).to include('não pôde ser criado') + end + end + + describe "PATCH /admin/users/:id" do + let(:admin) { create(:user, :admin) } + let!(:user) { create(:user, full_name: 'Old Name', email: 'old@example.com', role: :user) } + + before { sign_in admin } + + it "updates user attributes successfully" do + patch admin_user_path(user), params: { + user: { + full_name: 'Updated Name', + email: 'updated@example.com', + role: 'admin' + } + } + + expect(response).to redirect_to(admin_users_path) + follow_redirect! + expect(response.body).to include('Usuário atualizado com sucesso') + user.reload + expect(user.full_name).to eq('Updated Name') + expect(user.role).to eq('admin') + end + + it "renders errors when update fails" do + patch admin_user_path(user), params: { + user: { + email: '' # inválido + } + } + + expect(response.body).to include('Usuário não pôde ser atualizado') + user.reload + expect(user.email).to eq('old@example.com') + end + end + + describe "DELETE /admin/users/:id" do + let(:admin) { create(:user, :admin) } + let!(:user) { create(:user, full_name: 'User To Delete', email: 'delete@example.com') } + + before { sign_in admin } + + it "deletes the user successfully" do + expect { + delete admin_user_path(user) + }.to change(User, :count).by(-1) + + follow_redirect! + expect(response.body).to include('Usuário excluído com sucesso') + end + end + + describe "PATCH /admin/users/:id/toggle_role" do + let(:admin) { create(:user, :admin) } + let!(:user) { create(:user, role: :user) } + + before { sign_in admin } + + it "toggles the user role from user to admin" do + patch toggle_role_admin_user_path(user) + expect(response).to redirect_to(admin_users_path) + follow_redirect! + expect(response.body).to include('Função do usuário atualizada com sucesso') + user.reload + expect(user.role).to eq('admin') + end + + it "toggles the user role from admin to user" do + user.update(role: :admin) + patch toggle_role_admin_user_path(user) + user.reload + expect(user.role).to eq('user') + end + end +end diff --git a/spec/requests/authentication_spec.rb b/spec/requests/authentication_spec.rb new file mode 100644 index 000000000..7c4682cfe --- /dev/null +++ b/spec/requests/authentication_spec.rb @@ -0,0 +1,91 @@ +require 'rails_helper' + +RSpec.describe 'Authentication', type: :request do + describe 'POST /users (Sign Up)' do + let(:valid_attributes) do + { + user: { + full_name: 'John Doe', + email: 'john@example.com', + password: 'password123', + password_confirmation: 'password123' + } + } + end + + context 'with valid parameters' do + it 'creates a new user' do + expect { + post user_registration_path, params: valid_attributes + }.to change(User, :count).by(1) + end + + it 'redirects to authenticated root' do + post user_registration_path, params: valid_attributes + expect(response).to redirect_to(dashboard_index_path) + end + + it 'creates user with default role' do + post user_registration_path, params: valid_attributes + expect(User.last.role).to eq('user') + end + end + + context 'with invalid parameters' do + it 'does not create a new user without full_name' do + invalid_attributes = valid_attributes.deep_dup + invalid_attributes[:user][:full_name] = '' + + expect { + post user_registration_path, params: invalid_attributes + }.not_to change(User, :count) + end + + it 'does not create a new user with invalid email' do + invalid_attributes = valid_attributes.deep_dup + invalid_attributes[:user][:email] = 'invalid_email' + + expect { + post user_registration_path, params: invalid_attributes + }.not_to change(User, :count) + end + end + end + + describe 'POST /users/sign_in (Login)' do + let!(:user) { create(:user, email: 'test@example.com', password: 'password123') } + + context 'with valid credentials' do + it 'signs in the user' do + post user_session_path, params: { + user: { email: 'test@example.com', password: 'password123' } + } + expect(response).to redirect_to(dashboard_index_path) + end + end + + context 'with invalid credentials' do + it 'does not sign in with wrong password' do + post user_session_path, params: { + user: { email: 'test@example.com', password: 'wrongpassword' } + } + expect(response).not_to redirect_to(authenticated_root_path) + end + end + end + + describe 'DELETE /users/sign_out (Logout)' do + let(:user) { create(:user) } + + it 'signs out the user' do + post user_session_path, params: { + user: { email: user.email, password: user.password } + } + + delete destroy_user_session_path + + expect(response).to have_http_status(:redirect) + expect(response).to redirect_to(root_path) + end + end +end \ No newline at end of file diff --git a/spec/requests/authorization_spec.rb b/spec/requests/authorization_spec.rb new file mode 100644 index 000000000..97000eaf9 --- /dev/null +++ b/spec/requests/authorization_spec.rb @@ -0,0 +1,48 @@ +require 'rails_helper' + +RSpec.describe 'Authorization', type: :request do + let(:user) { create(:user) } + let(:admin) { create(:user, :admin) } + + describe 'Admin-only actions' do + # Criar um endpoint de teste posteriormente + # Por enquanto testar o conceito com helpers + + it 'admin can access admin areas' do + post user_session_path, params: { + user: { email: admin.email, password: admin.password } + } + + get dashboard_index_path + expect(response).to have_http_status(:success) + end + + it 'regular user can access user areas' do + post user_session_path, params: { + user: { email: user.email, password: user.password } + } + + get dashboard_index_path + expect(response).to have_http_status(:success) + end + + it 'unauthenticated user is redirected to login' do + get dashboard_index_path + expect(response).to redirect_to(new_user_session_path) + end + end + + describe 'Role switching' do + it 'can promote user to admin' do + expect(user.admin?).to be false + user.admin! + expect(user.admin?).to be true + end + + it 'can demote admin to user' do + expect(admin.admin?).to be true + admin.user! + expect(admin.user?).to be true + end + end +end \ No newline at end of file diff --git a/spec/requests/dashboard_spec.rb b/spec/requests/dashboard_spec.rb new file mode 100644 index 000000000..1036cfe59 --- /dev/null +++ b/spec/requests/dashboard_spec.rb @@ -0,0 +1,27 @@ +require 'rails_helper' + +RSpec.describe "Dashboards", type: :request do + describe "GET /index" do + context 'when user is authenticated' do + let(:user) { create(:user) } + + before do + post user_session_path, params: { + user: { email: user.email, password: user.password } + } + end + + it "returns http success" do + get dashboard_index_path + expect(response).to have_http_status(:success) + end + end + + context 'when user is not authenticated' do + it "redirects to login" do + get dashboard_index_path + expect(response).to redirect_to(new_user_session_path) + end + end + end +end \ No newline at end of file diff --git a/spec/requests/pages_spec.rb b/spec/requests/pages_spec.rb new file mode 100644 index 000000000..652559df8 --- /dev/null +++ b/spec/requests/pages_spec.rb @@ -0,0 +1,12 @@ +require 'rails_helper' + +RSpec.describe "Pages", type: :request do + describe "GET /home" do + it "returns http success" do + get "/pages/home" + + expect(response).to have_http_status(:success) + end + end + +end diff --git a/spec/requests/profiles_spec.rb b/spec/requests/profiles_spec.rb new file mode 100644 index 000000000..6f2a9c21c --- /dev/null +++ b/spec/requests/profiles_spec.rb @@ -0,0 +1,54 @@ +require 'rails_helper' + +RSpec.describe 'Profiles', type: :request do + let(:user) { create(:user) } + + before { sign_in user } + + describe 'GET /profile' do + it 'renders the profile page successfully' do + get profile_path + expect(response).to have_http_status(:ok) + expect(response.body).to include(user.full_name) + expect(response.body).to include(user.email) + end + end + + describe 'PATCH /profile' do + it 'updates the user information' do + patch profile_path, params: { user: { full_name: 'Updated Name' } } + + expect(response).to redirect_to(profile_path) + follow_redirect! + + expect(response.body).to include('Perfil atualizado com sucesso') + expect(response.body).to include('Updated Name') + end + + it 're-renders edit when invalid' do + patch profile_path, params: { user: { email: '' } } + expect(response).to have_http_status(:unprocessable_entity) + end + end + + describe 'DELETE /profile' do + it 'deletes the current user' do + delete profile_path + + expect(response).to redirect_to(root_path) + expect(User.exists?(user.id)).to be_falsey + end + end + + describe 'access control' do + it 'prevents user from accessing another profile' do + other_user = create(:user) + get edit_profile_path, params: { id: other_user.id } + + expect(response).to redirect_to(root_path) + follow_redirect! + + expect(response.body).to include('Acesso não autorizado') + end + end +end diff --git a/spec/requests/redirects_spec.rb b/spec/requests/redirects_spec.rb new file mode 100644 index 000000000..3d8dbd970 --- /dev/null +++ b/spec/requests/redirects_spec.rb @@ -0,0 +1,79 @@ +require 'rails_helper' + +RSpec.describe 'Custom Redirects', type: :request do + describe 'After login redirects' do + context 'when user is admin' do + let(:admin) { create(:user, :admin) } + + it 'redirects to admin dashboard after login' do + post user_session_path, params: { + user: { email: admin.email, password: admin.password } + } + + expect(response).to redirect_to(dashboard_index_path) + end + + it 'redirects to admin dashboard after sign up' do + post user_registration_path, params: { + user: { + full_name: 'Admin User', + email: 'admin@example.com', + password: 'password123', + password_confirmation: 'password123', + role: 'admin' + } + } + + # Não pode se cadastrar como admin diretamente, deve ser user + # testar isso também + expect(User.last.role).to eq('user') + end + end + + context 'when user is regular user' do + let(:user) { create(:user) } + + it 'redirects to user profile after login' do + post user_session_path, params: { + user: { email: user.email, password: user.password } + } + + # Por enquanto vai para dashboard, depois criar profile_path + expect(response).to redirect_to(dashboard_index_path) + end + end + end + + describe 'Authorization enforcement' do + let(:user) { create(:user) } + let(:admin) { create(:user, :admin) } + + context 'regular user accessing admin areas' do + before do + post user_session_path, params: { + user: { email: user.email, password: user.password } + } + end + + it 'cannot access admin user management' do + get '/admin/users' + + expect(response).to have_http_status(:found) + end + end + + context 'admin accessing admin areas' do + before do + post user_session_path, params: { + user: { email: admin.email, password: admin.password } + } + end + + it 'can access admin user management' do + get '/admin/users' + + expect(response).to have_http_status(:success).or have_http_status(:not_found) + end + end + end +end \ No newline at end of file diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 000000000..327b58ea1 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,94 @@ +# 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.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/support/devise_methods.rb b/spec/support/devise_methods.rb new file mode 100644 index 000000000..1ef004593 --- /dev/null +++ b/spec/support/devise_methods.rb @@ -0,0 +1,9 @@ +include Warden::Test::Helpers + +RSpec.configure do |config| + config.include Devise::Test::IntegrationHelpers, type: :request + config.include Devise::Test::IntegrationHelpers, type: :system + config.include Devise::Test::ControllerHelpers, type: :controller + + config.after { Warden.test_reset! } +end diff --git a/spec/system/layouts_spec.rb b/spec/system/layouts_spec.rb new file mode 100644 index 000000000..25e5ff01d --- /dev/null +++ b/spec/system/layouts_spec.rb @@ -0,0 +1,54 @@ +require 'rails_helper' + +RSpec.describe 'Layout and Navigation', type: :system do + let!(:user) { create(:user, full_name: 'Usuário Comum', email: 'user@example.com') } + let!(:admin) { create(:user, :admin, full_name: 'Admin User', email: 'admin@example.com') } + + before do + driven_by(:rack_test) + end + + describe 'Public layout' do + it 'shows login and signup links when logged out' do + visit root_path + expect(page).to have_link('Entrar') + expect(page).to have_link('Cadastrar') + expect(page).not_to have_link('Dashboard') + end + end + + describe 'User layout' do + before { login_as(user, scope: :user) } + + it 'shows navbar with dashboard and profile links' do + visit dashboard_index_path + expect(page).to have_link('Dashboard') + expect(page).to have_link('Perfil') + expect(page).to have_button('Sair') + end + + it 'shows success flash message styled with Bulma' do + visit dashboard_index_path + visit profile_path + expect(page).to have_css('.notification', class: /is-(success|danger)/).or have_no_css('.notification') + end + end + + describe 'Admin layout' do + before { login_as(admin, scope: :user) } + + it 'uses the admin layout and shows admin navbar links' do + visit admin_users_path + expect(page).to have_link('Usuários') + expect(page).to have_link('Dashboard') + expect(page).to have_button('Sair') + end + + it 'shows flash message with Bulma styling' do + visit admin_users_path + + visit admin_dashboard_path + expect(page).to have_css('.notification', class: /is-(success|danger)/).or have_no_css('.notification') + end + end +end diff --git a/spec/system/profile_flow_spec.rb b/spec/system/profile_flow_spec.rb new file mode 100644 index 000000000..563cae55f --- /dev/null +++ b/spec/system/profile_flow_spec.rb @@ -0,0 +1,23 @@ +require 'rails_helper' + +RSpec.describe 'Profile management', type: :system do + let(:user) { create(:user) } + + it 'allows user to view, edit and delete their profile' do + sign_in user + visit profile_path + + expect(page).to have_content(user.full_name) + expect(page).to have_content(user.email) + + click_link 'Editar' + fill_in 'Nome completo', with: 'Usuário Atualizado' + click_button 'Salvar' + + expect(page).to have_content('Perfil atualizado com sucesso') + expect(page).to have_content('Usuário Atualizado') + + click_button 'Excluir Conta' + expect(page).to have_content('Conta excluída com sucesso') + end +end diff --git a/spec/system/profile_ui_spec.rb b/spec/system/profile_ui_spec.rb new file mode 100644 index 000000000..1ccbf741a --- /dev/null +++ b/spec/system/profile_ui_spec.rb @@ -0,0 +1,39 @@ +require 'rails_helper' + +RSpec.describe 'Profile UI', type: :system do + let!(:user) { create(:user, full_name: 'Marcos Gomes', email: 'marcos@example.com', password: 'password123') } + + before do + driven_by(:rack_test) + login_as(user, scope: :user) + end + + describe 'Viewing profile' do + it 'shows the user information correctly formatted' do + visit profile_path + expect(page).to have_content('Meu Perfil') + expect(page).to have_content('Marcos Gomes') + expect(page).to have_content('marcos@example.com') + expect(page).to have_link('Editar') + expect(page).to have_button('Excluir Conta') + end + end + + describe 'Editing profile' do + it 'shows a styled form for editing' do + visit edit_profile_path + expect(page).to have_selector('form') + expect(page).to have_field('Nome completo') + expect(page).to have_field('Email') + expect(page).to have_button('Salvar alterações') + end + end + + describe 'Avatar upload' do + it 'shows a preview area for avatar' do + visit edit_profile_path + expect(page).to have_content('Foto de Perfil') + expect(page).to have_selector('input[type=file]') + end + end +end 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/channels/application_cable/connection_test.rb b/test/channels/application_cable/connection_test.rb new file mode 100644 index 000000000..6340bf9c0 --- /dev/null +++ b/test/channels/application_cable/connection_test.rb @@ -0,0 +1,13 @@ +require "test_helper" + +module ApplicationCable + class ConnectionTest < ActionCable::Connection::TestCase + # test "connects with cookies" do + # cookies.signed[:user_id] = 42 + # + # connect + # + # assert_equal connection.user_id, "42" + # end + end +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/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/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/vendor/.keep b/vendor/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/yarn.lock b/yarn.lock new file mode 100644 index 000000000..b568a0b8e --- /dev/null +++ b/yarn.lock @@ -0,0 +1,191 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +"@parcel/watcher-android-arm64@2.5.1": + version "2.5.1" + resolved "https://registry.yarnpkg.com/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.5.1.tgz#507f836d7e2042f798c7d07ad19c3546f9848ac1" + integrity sha512-KF8+j9nNbUN8vzOFDpRMsaKBHZ/mcjEjMToVMJOhTozkDonQFFrRcfdLWn6yWKCmJKmdVxSgHiYvTCef4/qcBA== + +"@parcel/watcher-darwin-arm64@2.5.1": + version "2.5.1" + resolved "https://registry.yarnpkg.com/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.5.1.tgz#3d26dce38de6590ef79c47ec2c55793c06ad4f67" + integrity sha512-eAzPv5osDmZyBhou8PoF4i6RQXAfeKL9tjb3QzYuccXFMQU0ruIc/POh30ePnaOyD1UXdlKguHBmsTs53tVoPw== + +"@parcel/watcher-darwin-x64@2.5.1": + version "2.5.1" + resolved "https://registry.yarnpkg.com/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.5.1.tgz#99f3af3869069ccf774e4ddfccf7e64fd2311ef8" + integrity sha512-1ZXDthrnNmwv10A0/3AJNZ9JGlzrF82i3gNQcWOzd7nJ8aj+ILyW1MTxVk35Db0u91oD5Nlk9MBiujMlwmeXZg== + +"@parcel/watcher-freebsd-x64@2.5.1": + version "2.5.1" + resolved "https://registry.yarnpkg.com/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.5.1.tgz#14d6857741a9f51dfe51d5b08b7c8afdbc73ad9b" + integrity sha512-SI4eljM7Flp9yPuKi8W0ird8TI/JK6CSxju3NojVI6BjHsTyK7zxA9urjVjEKJ5MBYC+bLmMcbAWlZ+rFkLpJQ== + +"@parcel/watcher-linux-arm-glibc@2.5.1": + version "2.5.1" + resolved "https://registry.yarnpkg.com/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.5.1.tgz#43c3246d6892381db473bb4f663229ad20b609a1" + integrity sha512-RCdZlEyTs8geyBkkcnPWvtXLY44BCeZKmGYRtSgtwwnHR4dxfHRG3gR99XdMEdQ7KeiDdasJwwvNSF5jKtDwdA== + +"@parcel/watcher-linux-arm-musl@2.5.1": + version "2.5.1" + resolved "https://registry.yarnpkg.com/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.5.1.tgz#663750f7090bb6278d2210de643eb8a3f780d08e" + integrity sha512-6E+m/Mm1t1yhB8X412stiKFG3XykmgdIOqhjWj+VL8oHkKABfu/gjFj8DvLrYVHSBNC+/u5PeNrujiSQ1zwd1Q== + +"@parcel/watcher-linux-arm64-glibc@2.5.1": + version "2.5.1" + resolved "https://registry.yarnpkg.com/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.5.1.tgz#ba60e1f56977f7e47cd7e31ad65d15fdcbd07e30" + integrity sha512-LrGp+f02yU3BN9A+DGuY3v3bmnFUggAITBGriZHUREfNEzZh/GO06FF5u2kx8x+GBEUYfyTGamol4j3m9ANe8w== + +"@parcel/watcher-linux-arm64-musl@2.5.1": + version "2.5.1" + resolved "https://registry.yarnpkg.com/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.5.1.tgz#f7fbcdff2f04c526f96eac01f97419a6a99855d2" + integrity sha512-cFOjABi92pMYRXS7AcQv9/M1YuKRw8SZniCDw0ssQb/noPkRzA+HBDkwmyOJYp5wXcsTrhxO0zq1U11cK9jsFg== + +"@parcel/watcher-linux-x64-glibc@2.5.1": + version "2.5.1" + resolved "https://registry.yarnpkg.com/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.5.1.tgz#4d2ea0f633eb1917d83d483392ce6181b6a92e4e" + integrity sha512-GcESn8NZySmfwlTsIur+49yDqSny2IhPeZfXunQi48DMugKeZ7uy1FX83pO0X22sHntJ4Ub+9k34XQCX+oHt2A== + +"@parcel/watcher-linux-x64-musl@2.5.1": + version "2.5.1" + resolved "https://registry.yarnpkg.com/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.5.1.tgz#277b346b05db54f55657301dd77bdf99d63606ee" + integrity sha512-n0E2EQbatQ3bXhcH2D1XIAANAcTZkQICBPVaxMeaCVBtOpBZpWJuf7LwyWPSBDITb7In8mqQgJ7gH8CILCURXg== + +"@parcel/watcher-win32-arm64@2.5.1": + version "2.5.1" + resolved "https://registry.yarnpkg.com/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.5.1.tgz#7e9e02a26784d47503de1d10e8eab6cceb524243" + integrity sha512-RFzklRvmc3PkjKjry3hLF9wD7ppR4AKcWNzH7kXR7GUe0Igb3Nz8fyPwtZCSquGrhU5HhUNDr/mKBqj7tqA2Vw== + +"@parcel/watcher-win32-ia32@2.5.1": + version "2.5.1" + resolved "https://registry.yarnpkg.com/@parcel/watcher-win32-ia32/-/watcher-win32-ia32-2.5.1.tgz#2d0f94fa59a873cdc584bf7f6b1dc628ddf976e6" + integrity sha512-c2KkcVN+NJmuA7CGlaGD1qJh1cLfDnQsHjE89E60vUEMlqduHGCdCLJCID5geFVM0dOtA3ZiIO8BoEQmzQVfpQ== + +"@parcel/watcher-win32-x64@2.5.1": + version "2.5.1" + resolved "https://registry.yarnpkg.com/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.5.1.tgz#ae52693259664ba6f2228fa61d7ee44b64ea0947" + integrity sha512-9lHBdJITeNR++EvSQVUcaZoWupyHfXe1jZvGZ06O/5MflPcuPLtEphScIBL+AiCWBO46tDSHzWyD0uDmmZqsgA== + +"@parcel/watcher@^2.4.1": + version "2.5.1" + resolved "https://registry.yarnpkg.com/@parcel/watcher/-/watcher-2.5.1.tgz#342507a9cfaaf172479a882309def1e991fb1200" + integrity sha512-dfUnCxiN9H4ap84DvD2ubjw+3vUNpstxa0TneY/Paat8a3R4uQZDLSvWjmznAY/DoahqTHl9V46HF/Zs3F29pg== + dependencies: + detect-libc "^1.0.3" + is-glob "^4.0.3" + micromatch "^4.0.5" + node-addon-api "^7.0.0" + optionalDependencies: + "@parcel/watcher-android-arm64" "2.5.1" + "@parcel/watcher-darwin-arm64" "2.5.1" + "@parcel/watcher-darwin-x64" "2.5.1" + "@parcel/watcher-freebsd-x64" "2.5.1" + "@parcel/watcher-linux-arm-glibc" "2.5.1" + "@parcel/watcher-linux-arm-musl" "2.5.1" + "@parcel/watcher-linux-arm64-glibc" "2.5.1" + "@parcel/watcher-linux-arm64-musl" "2.5.1" + "@parcel/watcher-linux-x64-glibc" "2.5.1" + "@parcel/watcher-linux-x64-musl" "2.5.1" + "@parcel/watcher-win32-arm64" "2.5.1" + "@parcel/watcher-win32-ia32" "2.5.1" + "@parcel/watcher-win32-x64" "2.5.1" + +braces@^3.0.3: + version "3.0.3" + resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.3.tgz#490332f40919452272d55a8480adc0c441358789" + integrity sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA== + dependencies: + fill-range "^7.1.1" + +bulma@^1.0.4: + version "1.0.4" + resolved "https://registry.yarnpkg.com/bulma/-/bulma-1.0.4.tgz#942dc017a3a201fa9f0e0c8db3dd52f3cff86712" + integrity sha512-Ffb6YGXDiZYX3cqvSbHWqQ8+LkX6tVoTcZuVB3lm93sbAVXlO0D6QlOTMnV6g18gILpAXqkG2z9hf9z4hCjz2g== + +chokidar@^4.0.0: + version "4.0.3" + resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-4.0.3.tgz#7be37a4c03c9aee1ecfe862a4a23b2c70c205d30" + integrity sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA== + dependencies: + readdirp "^4.0.1" + +detect-libc@^1.0.3: + version "1.0.3" + resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-1.0.3.tgz#fa137c4bd698edf55cd5cd02ac559f91a4c4ba9b" + integrity sha512-pGjwhsmsp4kL2RTz08wcOlGN83otlqHeD/Z5T8GXZB+/YcpQ/dgo+lbU8ZsGxV0HIvqqxo9l7mqYwyYMD9bKDg== + +fill-range@^7.1.1: + version "7.1.1" + resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.1.1.tgz#44265d3cac07e3ea7dc247516380643754a05292" + integrity sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg== + dependencies: + to-regex-range "^5.0.1" + +immutable@^5.0.2: + version "5.1.4" + resolved "https://registry.yarnpkg.com/immutable/-/immutable-5.1.4.tgz#e3f8c1fe7b567d56cf26698f31918c241dae8c1f" + integrity sha512-p6u1bG3YSnINT5RQmx/yRZBpenIl30kVxkTLDyHLIMk0gict704Q9n+thfDI7lTRm9vXdDYutVzXhzcThxTnXA== + +is-extglob@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" + integrity sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ== + +is-glob@^4.0.3: + version "4.0.3" + resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.3.tgz#64f61e42cbbb2eec2071a9dac0b28ba1e65d5084" + integrity sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg== + dependencies: + is-extglob "^2.1.1" + +is-number@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" + integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== + +micromatch@^4.0.5: + version "4.0.8" + resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.8.tgz#d66fa18f3a47076789320b9b1af32bd86d9fa202" + integrity sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA== + dependencies: + braces "^3.0.3" + picomatch "^2.3.1" + +node-addon-api@^7.0.0: + version "7.1.1" + resolved "https://registry.yarnpkg.com/node-addon-api/-/node-addon-api-7.1.1.tgz#1aba6693b0f255258a049d621329329322aad558" + integrity sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ== + +picomatch@^2.3.1: + version "2.3.1" + resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42" + integrity sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA== + +readdirp@^4.0.1: + version "4.1.2" + resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-4.1.2.tgz#eb85801435fbf2a7ee58f19e0921b068fc69948d" + integrity sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg== + +sass@^1.93.3: + version "1.93.3" + resolved "https://registry.yarnpkg.com/sass/-/sass-1.93.3.tgz#3ff0aa5879dc910d32eae10c282a2847bd63e758" + integrity sha512-elOcIZRTM76dvxNAjqYrucTSI0teAF/L2Lv0s6f6b7FOwcwIuA357bIE871580AjHJuSvLIRUosgV+lIWx6Rgg== + dependencies: + chokidar "^4.0.0" + immutable "^5.0.2" + source-map-js ">=0.6.2 <2.0.0" + optionalDependencies: + "@parcel/watcher" "^2.4.1" + +"source-map-js@>=0.6.2 <2.0.0": + version "1.2.1" + resolved "https://registry.yarnpkg.com/source-map-js/-/source-map-js-1.2.1.tgz#1ce5650fddd87abc099eda37dcff024c2667ae46" + integrity sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA== + +to-regex-range@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" + integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ== + dependencies: + is-number "^7.0.0"