diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..bb56daf --- /dev/null +++ b/.dockerignore @@ -0,0 +1,31 @@ +# See https://docs.docker.com/engine/reference/builder/#dockerignore-file for more about ignoring files. + +# Ignore git directory. +/.git/ + +# Ignore bundler config. +/.bundle + +# Ignore all environment files (except templates). +/.env* +!/.env*.erb + +# Ignore all default key files. +/config/master.key +/config/credentials/*.key + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/.keep + +# Ignore storage (uploaded files in development and any SQLite databases). +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/.keep diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8dc4323 --- /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/workflows/linters.yml b/.github/workflows/linters.yml new file mode 100644 index 0000000..560212b --- /dev/null +++ b/.github/workflows/linters.yml @@ -0,0 +1,30 @@ +name: Linters + +on: pull_request + +env: + FORCE_COLOR: 1 + +jobs: + rubocop: + name: Rubocop + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-ruby@v1 + with: + ruby-version: 3.1.x + - name: Setup Rubocop + run: | + gem install --no-document rubocop -v '>= 1.0, < 2.0' # https://docs.rubocop.org/en/stable/installation/ + [ -f .rubocop.yml ] || wget https://raw.githubusercontent.com/microverseinc/linters-config/master/ror/.rubocop.yml + - name: Rubocop Report + run: rubocop --color + nodechecker: + name: node_modules checker + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v3 + - name: Check node_modules existence + run: | + if [ -d "node_modules/" ]; then echo -e "\e[1;31mThe node_modules/ folder was pushed to the repo. Please remove it from the GitHub repository and try again."; echo -e "\e[1;32mYou can set up a .gitignore file with this folder included on it to prevent this from happening in the future." && exit 1; fi \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7e6b54f --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +# 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/ +!/tmp/pids/.keep + +# Ignore storage (uploaded files in development and any SQLite databases). +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/ +!/tmp/storage/.keep + +# Ignore master key for decrypting credentials and more. +/config/master.key diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..b58b603 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,5 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ diff --git a/.idea/final-capstone-back-end.iml b/.idea/final-capstone-back-end.iml new file mode 100644 index 0000000..24643cc --- /dev/null +++ b/.idea/final-capstone-back-end.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..a03cbb1 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.rspec b/.rspec new file mode 100644 index 0000000..c99d2e7 --- /dev/null +++ b/.rspec @@ -0,0 +1 @@ +--require spec_helper diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..07baeb4 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,60 @@ +AllCops: + NewCops: enable + Exclude: + - "db/**/*" + - "bin/*" + - "config/**/*" + - "Guardfile" + - "Rakefile" + - "node_modules/**/*" + + DisplayCopNames: true + +Layout/LineLength: + Max: 120 +Metrics/MethodLength: + Include: + - "app/controllers/*" + - "app/models/*" + Max: 20 +Metrics/AbcSize: + Include: + - "app/controllers/*" + - "app/models/*" + Max: 50 +Metrics/ClassLength: + Max: 150 +Metrics/BlockLength: + AllowedMethods: ['describe'] + Max: 30 + +Style/Documentation: + Enabled: false +Style/ClassAndModuleChildren: + Enabled: false +Style/EachForSimpleLoop: + Enabled: false +Style/AndOr: + Enabled: false +Style/DefWithParentheses: + Enabled: false +Style/FrozenStringLiteralComment: + EnforcedStyle: never + +Layout/HashAlignment: + EnforcedColonStyle: key +Layout/ExtraSpacing: + AllowForAlignment: false +Layout/MultilineMethodCallIndentation: + Enabled: true + EnforcedStyle: indented +Lint/RaiseException: + Enabled: false +Lint/StructNewOverride: + Enabled: false +Style/HashEachMethods: + Enabled: false +Style/HashTransformKeys: + Enabled: false +Style/HashTransformValues: + Enabled: false \ No newline at end of file diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 0000000..9e79f6c --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +ruby-3.2.2 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..11d58b9 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,59 @@ +# syntax = docker/dockerfile:1 + +# Make sure RUBY_VERSION matches the Ruby version in .ruby-version and Gemfile +ARG RUBY_VERSION=3.2.2 +FROM registry.docker.com/library/ruby:$RUBY_VERSION-slim as base + +# Rails app lives here +WORKDIR /rails + +# Set production environment +ENV RAILS_ENV="production" \ + BUNDLE_DEPLOYMENT="1" \ + BUNDLE_PATH="/usr/local/bundle" \ + BUNDLE_WITHOUT="development" + + +# Throw-away build stage to reduce size of final image +FROM base as build + +# Install packages needed to build gems +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y build-essential git libpq-dev libvips pkg-config + +# Install application gems +COPY Gemfile Gemfile.lock ./ +RUN bundle install && \ + rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git && \ + bundle exec bootsnap precompile --gemfile + +# Copy application code +COPY . . + +# Precompile bootsnap code for faster boot times +RUN bundle exec bootsnap precompile app/ lib/ + + +# Final stage for app image +FROM base + +# Install packages needed for deployment +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y curl libvips postgresql-client && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# Copy built artifacts: gems, application +COPY --from=build /usr/local/bundle /usr/local/bundle +COPY --from=build /rails /rails + +# Run and own only the runtime files as a non-root user for security +RUN useradd rails --create-home --shell /bin/bash && \ + chown -R rails:rails db log storage tmp +USER rails:rails + +# Entrypoint prepares the database. +ENTRYPOINT ["/rails/bin/docker-entrypoint"] + +# Start the server by default, this can be overwritten at runtime +EXPOSE 3000 +CMD ["./bin/rails", "server"] diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..bcccea8 --- /dev/null +++ b/Gemfile @@ -0,0 +1,68 @@ +source 'https://rubygems.org' + +ruby '3.2.2' + +# .env file support +gem 'dotenv-rails' + +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem 'rails', '~> 7.1.1' + +# Use postgresql as the database for Active Record +gem 'pg', '~> 1.1' + +# Use the Puma web server [https://github.com/puma/puma] +gem 'puma', '>= 5.0' + +# Build JSON APIs with ease [https://github.com/rails/jbuilder] +# gem "jbuilder" + +# Use Redis adapter to run Action Cable in production +# gem "redis", ">= 4.0.1" + +# Use Kredis to get higher-level data types in Redis [https://github.com/rails/kredis] +# gem "kredis" + +# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] +# gem "bcrypt", "~> 3.1.7" + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem 'tzinfo-data', platforms: %i[windows jruby] + +# Reduces boot times through caching; required in config/boot.rb +gem 'bootsnap', require: false + +# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] +# gem "image_processing", "~> 1.2" + +# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin Ajax possible +gem 'rack-cors' + +# User authentication +gem 'devise' +gem 'devise-jwt' +gem 'jsonapi-serializer' + +gem 'rswag-api' +gem 'rswag-ui' + +group :development, :test do + # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem + gem 'debug', platforms: %i[mri windows] + gem 'factory_bot_rails' + gem 'faker' + gem 'httparty' + gem 'rack-test' + gem 'rails-controller-testing' + gem 'rspec-rails', '>= 3.9.0' + gem 'rswag-specs' + gem 'shoulda-matchers' +end + +group :development do + gem 'bullet', group: 'development' + # Speed up commands on slow machines / big apps [https://github.com/rails/spring] + # gem "spring" +end + +gem 'rubocop', '>= 1.0', '< 2.0' diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..ecbc61f --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,341 @@ +GEM + remote: https://rubygems.org/ + specs: + actioncable (7.1.1) + actionpack (= 7.1.1) + activesupport (= 7.1.1) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + zeitwerk (~> 2.6) + actionmailbox (7.1.1) + actionpack (= 7.1.1) + activejob (= 7.1.1) + activerecord (= 7.1.1) + activestorage (= 7.1.1) + activesupport (= 7.1.1) + mail (>= 2.7.1) + net-imap + net-pop + net-smtp + actionmailer (7.1.1) + actionpack (= 7.1.1) + actionview (= 7.1.1) + activejob (= 7.1.1) + activesupport (= 7.1.1) + mail (~> 2.5, >= 2.5.4) + net-imap + net-pop + net-smtp + rails-dom-testing (~> 2.2) + actionpack (7.1.1) + actionview (= 7.1.1) + activesupport (= 7.1.1) + nokogiri (>= 1.8.5) + rack (>= 2.2.4) + rack-session (>= 1.0.1) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + actiontext (7.1.1) + actionpack (= 7.1.1) + activerecord (= 7.1.1) + activestorage (= 7.1.1) + activesupport (= 7.1.1) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (7.1.1) + activesupport (= 7.1.1) + builder (~> 3.1) + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + activejob (7.1.1) + activesupport (= 7.1.1) + globalid (>= 0.3.6) + activemodel (7.1.1) + activesupport (= 7.1.1) + activerecord (7.1.1) + activemodel (= 7.1.1) + activesupport (= 7.1.1) + timeout (>= 0.4.0) + activestorage (7.1.1) + actionpack (= 7.1.1) + activejob (= 7.1.1) + activerecord (= 7.1.1) + activesupport (= 7.1.1) + marcel (~> 1.0) + activesupport (7.1.1) + base64 + bigdecimal + concurrent-ruby (~> 1.0, >= 1.0.2) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + minitest (>= 5.1) + mutex_m + tzinfo (~> 2.0) + addressable (2.8.5) + public_suffix (>= 2.0.2, < 6.0) + ast (2.4.2) + base64 (0.1.1) + bcrypt (3.1.19) + bigdecimal (3.1.4) + bootsnap (1.16.0) + msgpack (~> 1.2) + builder (3.2.4) + bullet (7.1.2) + activesupport (>= 3.0.0) + uniform_notifier (~> 1.11) + concurrent-ruby (1.2.2) + connection_pool (2.4.1) + crass (1.0.6) + date (3.3.3) + debug (1.8.0) + irb (>= 1.5.0) + reline (>= 0.3.1) + devise (4.9.3) + bcrypt (~> 3.0) + orm_adapter (~> 0.1) + railties (>= 4.1.0) + responders + warden (~> 1.2.3) + devise-jwt (0.11.0) + devise (~> 4.0) + warden-jwt_auth (~> 0.8) + diff-lcs (1.5.0) + dotenv (2.8.1) + dotenv-rails (2.8.1) + dotenv (= 2.8.1) + railties (>= 3.2) + drb (2.1.1) + ruby2_keywords + dry-auto_inject (1.0.1) + dry-core (~> 1.0) + zeitwerk (~> 2.6) + dry-configurable (1.1.0) + dry-core (~> 1.0, < 2) + zeitwerk (~> 2.6) + dry-core (1.0.1) + concurrent-ruby (~> 1.0) + zeitwerk (~> 2.6) + erubi (1.12.0) + factory_bot (6.2.1) + activesupport (>= 5.0.0) + factory_bot_rails (6.2.0) + factory_bot (~> 6.2.0) + railties (>= 5.0.0) + faker (3.2.1) + i18n (>= 1.8.11, < 2) + globalid (1.2.1) + activesupport (>= 6.1) + httparty (0.21.0) + mini_mime (>= 1.0.0) + multi_xml (>= 0.5.2) + i18n (1.14.1) + concurrent-ruby (~> 1.0) + io-console (0.6.0) + irb (1.8.3) + rdoc + reline (>= 0.3.8) + json (2.6.3) + json-schema (3.0.0) + addressable (>= 2.8) + jsonapi-serializer (2.2.0) + activesupport (>= 4.2) + jwt (2.7.1) + language_server-protocol (3.17.0.3) + loofah (2.21.4) + crass (~> 1.0.2) + nokogiri (>= 1.12.0) + mail (2.8.1) + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.0.2) + mini_mime (1.1.5) + minitest (5.20.0) + msgpack (1.7.2) + multi_xml (0.6.0) + mutex_m (0.1.2) + net-imap (0.4.2) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.2.1) + timeout + net-smtp (0.4.0) + net-protocol + nio4r (2.5.9) + nokogiri (1.15.4-x64-mingw-ucrt) + racc (~> 1.4) + nokogiri (1.15.4-x86_64-linux) + racc (~> 1.4) + orm_adapter (0.5.0) + parallel (1.23.0) + parser (3.2.2.4) + ast (~> 2.4.1) + racc + pg (1.5.4) + pg (1.5.4-x64-mingw-ucrt) + psych (5.1.1.1) + stringio + public_suffix (5.0.3) + puma (6.4.0) + nio4r (~> 2.0) + racc (1.7.1) + rack (3.0.8) + rack-cors (2.0.1) + rack (>= 2.0.0) + rack-session (2.0.0) + rack (>= 3.0.0) + rack-test (2.1.0) + rack (>= 1.3) + rackup (2.1.0) + rack (>= 3) + webrick (~> 1.8) + rails (7.1.1) + actioncable (= 7.1.1) + actionmailbox (= 7.1.1) + actionmailer (= 7.1.1) + actionpack (= 7.1.1) + actiontext (= 7.1.1) + actionview (= 7.1.1) + activejob (= 7.1.1) + activemodel (= 7.1.1) + activerecord (= 7.1.1) + activestorage (= 7.1.1) + activesupport (= 7.1.1) + bundler (>= 1.15.0) + railties (= 7.1.1) + rails-controller-testing (1.0.5) + actionpack (>= 5.0.1.rc1) + actionview (>= 5.0.1.rc1) + activesupport (>= 5.0.1.rc1) + rails-dom-testing (2.2.0) + activesupport (>= 5.0.0) + minitest + nokogiri (>= 1.6) + rails-html-sanitizer (1.6.0) + loofah (~> 2.21) + nokogiri (~> 1.14) + railties (7.1.1) + actionpack (= 7.1.1) + activesupport (= 7.1.1) + irb + rackup (>= 1.0.0) + rake (>= 12.2) + thor (~> 1.0, >= 1.2.2) + zeitwerk (~> 2.6) + rainbow (3.1.1) + rake (13.0.6) + rdoc (6.5.0) + psych (>= 4.0.0) + regexp_parser (2.8.2) + reline (0.3.9) + io-console (~> 0.5) + responders (3.1.1) + actionpack (>= 5.2) + railties (>= 5.2) + rexml (3.2.6) + rspec-core (3.12.2) + rspec-support (~> 3.12.0) + rspec-expectations (3.12.3) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.12.0) + rspec-mocks (3.12.6) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.12.0) + rspec-rails (6.0.3) + actionpack (>= 6.1) + activesupport (>= 6.1) + railties (>= 6.1) + rspec-core (~> 3.12) + rspec-expectations (~> 3.12) + rspec-mocks (~> 3.12) + rspec-support (~> 3.12) + rspec-support (3.12.1) + rswag-api (2.11.0) + railties (>= 3.1, < 7.2) + rswag-specs (2.11.0) + activesupport (>= 3.1, < 7.2) + json-schema (>= 2.2, < 4.0) + railties (>= 3.1, < 7.2) + rspec-core (>= 2.14) + rswag-ui (2.11.0) + actionpack (>= 3.1, < 7.2) + railties (>= 3.1, < 7.2) + rubocop (1.57.2) + json (~> 2.3) + language_server-protocol (>= 3.17.0) + parallel (~> 1.10) + parser (>= 3.2.2.4) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 1.8, < 3.0) + rexml (>= 3.2.5, < 4.0) + rubocop-ast (>= 1.28.1, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 3.0) + rubocop-ast (1.30.0) + parser (>= 3.2.1.0) + ruby-progressbar (1.13.0) + ruby2_keywords (0.0.5) + shoulda-matchers (5.3.0) + activesupport (>= 5.2.0) + stringio (3.0.8) + thor (1.3.0) + timeout (0.4.0) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + tzinfo-data (1.2023.3) + tzinfo (>= 1.0.0) + unicode-display_width (2.5.0) + uniform_notifier (1.16.0) + warden (1.2.9) + rack (>= 2.0.9) + warden-jwt_auth (0.8.0) + dry-auto_inject (>= 0.8, < 2) + dry-configurable (>= 0.13, < 2) + jwt (~> 2.1) + warden (~> 1.2) + webrick (1.8.1) + websocket-driver (0.7.6) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + zeitwerk (2.6.12) + +PLATFORMS + x64-mingw-ucrt + x86_64-linux + +DEPENDENCIES + bootsnap + bullet + debug + devise + devise-jwt + dotenv-rails + factory_bot_rails + faker + httparty + jsonapi-serializer + pg (~> 1.1) + puma (>= 5.0) + rack-cors + rack-test + rails (~> 7.1.1) + rails-controller-testing + rspec-rails (>= 3.9.0) + rswag-api + rswag-specs + rswag-ui + rubocop (>= 1.0, < 2.0) + shoulda-matchers + tzinfo-data + +RUBY VERSION + ruby 3.2.2p53 + +BUNDLED WITH + 2.4.20 diff --git a/LICENSE b/LICENSE index d78cb34..d45b715 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2023 Javier Grau +Copyright (c) 2023 Anthony Vasquez, Manuel Sanchez, Javier Grau Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index a7c95d7..939a08c 100644 --- a/README.md +++ b/README.md @@ -1 +1,279 @@ -# final-capstone-back-end \ No newline at end of file +
+ + + +

Final Capstone Back End

+ +
+ +# ๐Ÿ“— Table of Contents + +- [๐Ÿ“— Table of Contents](#-table-of-contents) +- [๐Ÿ“– final\_capstone\_back\_end ](#-final_capstone_back_end-) + - [๐Ÿ›  ER Diagram ](#-er-diagram-) + - [๐Ÿ’ป link to front end ](#-link-to-front-end-) + - [๐Ÿ’ป link to Kanban board information ](#-link-to-kanban-board-information-) + - [๐Ÿ›  Built With ](#-built-with-) + - [Tech Stack ](#tech-stack-) + - [Key Features ](#key-features-) + - [๐Ÿ’ป Getting Started ](#-getting-started-) + - [Prerequisites](#prerequisites) + - [Setup](#setup) + - [Install](#install) + - [Database Setup](#database-setup) + - [Usage](#usage) + - [๐Ÿ”ฌ Running Tests ](#-running-tests-) + - [Test Suite](#test-suite) + - [๐Ÿ’ป API Documentation ](#-api-documentation-) + - [๐Ÿ‘ฅ Authors ](#-authors-) + - [๐Ÿ”ญ Future Features ](#-future-features-) + - [๐Ÿค Contributing ](#-contributing-) + - [โญ๏ธ Show your support ](#๏ธ-show-your-support-) + - [๐Ÿ™ Acknowledgments ](#-acknowledgments-) + - [โ“ FAQ (OPTIONAL) ](#-faq-optional-) + - [๐Ÿ“ License ](#-license-) + + +# ๐Ÿ“– Final Capstone Back End + +**final_capstone_back_end** The back-end component of this final capstone project is developed using Ruby on Rails, configured to serve as an API. This API is designed to facilitate creation of places to rent, and to allow users to make reservations for those places. It leverages a PostgreSQL database to manage and store reservation data. The API is designed to be consumed by a front-end application, which is developed using React.js. + +## ๐Ÿ›  ER Diagram + +![ER Diagram](./src/ERD.png) + + +

(back to top)

+ +## ๐Ÿ’ป Link to front end + + +[Link to Front End](https://github.com/grauJavier/final-capstone-front-end) + +

(back to top)

+ +## ๐Ÿ’ป link to Kanban board information + +[Link to Kanban Board](https://github.com/grauJavier/final-capstone-back-end/projects/1) + +[Initial state](https://github.com/grauJavier/final-capstone-front-end/issues/38) + +This project was completed by three Team members: + +- Javier Grau +- Manuel Sanchez +- Anthony Vรกsquez + +

(back to top)

+ +## ๐Ÿ›  Built With + +### Tech Stack + +
+ Technologies + +
+
+Linters + +
+ + +### Key Features + +- **Ruby on Rails** +- **API Endpoint** +- **Professional Documentation** +- **Linting for Code Quality** +- **Postgres Database** +- **Git Version Control** + + +

(back to top)

+ + +## ๐Ÿ’ป Getting Started + +To get a local copy up and running, follow these steps: + +### Prerequisites + +Before you begin, ensure you have the following prerequisites installed on your system: + +- Ruby: You need Ruby to run the Ruby on Rails application. +- Bundler: Bundler is used to manage gem dependencies for your Ruby project. + +### Setup + +In your terminal, navigate to the folder of your choice and clone the repository with the following commands: + +```sh +cd my-folder +git clone git@github.com:grauJavier/final-capstone-back-end.git + +``` + +### Install + +After cloning the project, change into the project directory: + +```sh +cd final_capstone_back_end + +``` + +Install this project with: + +- gem install rails +- bundle install + +### Credentials setup +In order to create databases and run the tests, you need to follow this steps: +1. Remove config/master.key and config/credentials.yml.enc if they exist. +2. Run `rails secret`. This will generate a key. Copy and reserve the key to use later. +3. If you use Windows run: `$env:EDITOR="code --wait"; rails credentials:edit` If you use Linux run: `EDITOR="code --wait" bin/rails credentials:edit` +4. Your editor will open a file, add at the bottom `devise_jwt_secret_key: ` +5. Save the file and close the editor. New master.key, credentials.yml.enc files will be generated, and the key will be stored in `Rails.application.credentials.devise_jwt_secret_key`. + +### Database Setup + +Create and migrate your database with: + +```sh + +rails db:create +rails db:migrate +rails db:seed + +``` +### Usage + +To run the project, execute the following command: + +```sh + +rails server +or +rails s + +``` +This should start your local server on http://localhost:3000/. Now, you can use the REST API client of your choice to interact with the API. + +

(back to top)

+ + +## ๐Ÿ”ฌ Running Tests + +To run tests, navigate to the directory where the project is located on your machine, open your terminal, and follow these steps: + +### Test Suite + +This project contains a suite of unit tests which you can run to ensure everything is functioning as expected. To run these tests, you need RSpec installed. + +To install RSpec if you haven't already, run: + +```sh +gem install rspec + +``` + +After you've installed RSpec, you can run the tests with: + +```sh + +rspec + +``` + +

(back to top)

+ +## ๐Ÿ’ป API Documentation + +
+ +[API Documentation](https://renteaze-d1cc8b293660.herokuapp.com/api-docs/index.html) + + +![API Methods](./src/API_documentation.png) + +
+ +

(back to top)

+ +## ๐Ÿ‘ฅ Authors + +๐Ÿ‘ค **Javier Grau** + +- GitHub: [@grauJavier](https://github.com/grauJavier) +- LinkedIn: [Javier Grau](https://www.linkedin.com/in/javiergrau) + +๐Ÿ‘ค **Manuel Sanchez** + +- GitHub: [@Luffytaro22](https://github.com/Luffytaro22) +- LinkedIn: [Manuel Sanchez](https://www.linkedin.com/in/manuel-alejandro-sanchez-sierra/) + +๐Ÿ‘ค **lRebornsl** + +- GitHub: [@lRebornsl](https://github.com/lRebornsl) +- Twitter: [@RebornsDev](https://twitter.com/RebornsDev) +- LinkedIn: [Anthony Vรกsquez](https://www.linkedin.com/in/avvm98/) + +

(back to top)

+ + +## ๐Ÿ”ญ Future Features + +- [ ] **Implement proper user authentication from the front-end to the server** +- [ ] **Add authorizations to users** + + +

(back to top)

+ +## ๐Ÿค Contributing + +Contributions, issues, and feature requests are welcome! + +Feel free to check the [issues page](https://github.com/grauJavier/final-capstone-back-end/issues). + +

(back to top)

+ + +## โญ๏ธ Show your support + +If you like this project please feel free to send me corrections for make it better I would feel glad to read your comments. +And think If you enjoy gift me a star. + +

(back to top)

+ +## ๐Ÿ™ Acknowledgments + +- Behance and Murat Korkmaz for the [original design](https://www.behance.net/gallery/26425031/Vespa-Responsive-Redesign) +- Microverse for providing the opportunity to learn in a collaborative environment. +- React.js Documentation for valuable resources on React development. +- GitHub for version control and collaboration tools. + +

(back to top)

+ +## โ“ FAQ (OPTIONAL) + +- **Can I use with a templeate your project?** + + - Of course we would feel honored. + +- **Your project is free license?** + + - Yeah, you can use it completely. + +

(back to top)

+ + +## ๐Ÿ“ License + +This project is licensed under the MIT License - you can click here to have more details [MIT](./LICENSE). + +

(back to top)

diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..9a5ea73 --- /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/channels/application_cable/channel.rb b/app/channels/application_cable/channel.rb new file mode 100644 index 0000000..d672697 --- /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 0000000..0ff5442 --- /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/application_controller.rb b/app/controllers/application_controller.rb new file mode 100644 index 0000000..6d696ee --- /dev/null +++ b/app/controllers/application_controller.rb @@ -0,0 +1,10 @@ +class ApplicationController < ActionController::API + before_action :configure_permitted_parameters, if: :devise_controller? + + protected + + def configure_permitted_parameters + devise_parameter_sanitizer.permit(:sign_up, keys: %i[username]) + devise_parameter_sanitizer.permit(:account_update, keys: %i[username]) + end +end diff --git a/app/controllers/cities_controller.rb b/app/controllers/cities_controller.rb new file mode 100644 index 0000000..3f90b1f --- /dev/null +++ b/app/controllers/cities_controller.rb @@ -0,0 +1,19 @@ +class CitiesController < ApplicationController + before_action :find_place, only: [:show] + + def index + cities = City.all + render json: cities + end + + def show + city = City.find_by(id: @place.city_id) + render json: city + end + + private + + def find_place + @place = Place.where(user_id: params[:user_id]).find_by(id: params[:place_id]) + end +end diff --git a/app/controllers/concerns/.keep b/app/controllers/concerns/.keep new file mode 100644 index 0000000..e69de29 diff --git a/app/controllers/concerns/rack_sessions_fix.rb b/app/controllers/concerns/rack_sessions_fix.rb new file mode 100644 index 0000000..985359b --- /dev/null +++ b/app/controllers/concerns/rack_sessions_fix.rb @@ -0,0 +1,19 @@ +module RackSessionsFix + extend ActiveSupport::Concern + class FakeRackSession < Hash + def enabled? + false + end + + def destroy; end + end + included do + before_action :set_fake_session + + private + + def set_fake_session + request.env['rack.session'] ||= FakeRackSession.new + end + end +end diff --git a/app/controllers/details_controller.rb b/app/controllers/details_controller.rb new file mode 100644 index 0000000..4d089a2 --- /dev/null +++ b/app/controllers/details_controller.rb @@ -0,0 +1,7 @@ +class DetailsController < ApplicationController + def index + details = Detail.includes(:place).find_by(place_id: params[:place_id]) + render json: details.as_json(include: { place: { only: %i[name user_id image_url description], + include: { city: { only: %i[name id] } } } }) + end +end diff --git a/app/controllers/places_controller.rb b/app/controllers/places_controller.rb new file mode 100644 index 0000000..90c0833 --- /dev/null +++ b/app/controllers/places_controller.rb @@ -0,0 +1,64 @@ +class PlacesController < ApplicationController + before_action :find_places, only: %i[create update destroy] + + def index + places = if params[:city_id].present? + Place.where(city_id: params[:city_id]) + elsif params[:user_id].present? + Place.where(user_id: params[:user_id]) + elsif params[:id].present? + Place.where(id: params[:id]) + else + Place.all + end + render json: places.as_json(include: { city: { only: %i[name] } }) + end + + def show + place = Place.find_by(id: params[:id]) + render json: place + end + + def create + place = @places.new(place_params) + place.build_detail(details_params) + if place.save + render json: place.as_json(include: { city: { only: %i[name] } }), status: :created + else + render json: place.errors, status: :unprocessable_entity + end + end + + def update + place = @places.find(params[:id]) + if place.update(place_params) + place.detail.update(details_params) if place.detail.present? + render json: place, status: :ok + else + render json: place.errors, status: :unprocessable_entity + end + end + + def destroy + place = @places.find(params[:id]) + if place.destroy + render json: { message: 'Place deteled successfully!' }, status: :ok, head: :no_content + else + render json: place.errors, status: :unprocessable_entity, head: :no_content + end + end + + private + + def find_places + @places = Place.where(user_id: params[:user_id]) + end + + def place_params + params.require(:place).permit(:city_id, :name, :image_url, :description) + end + + def details_params + params.require(:details).permit(:place_type, :bedrooms, :beds, :bathrooms, :property_type, :price) + end +end diff --git a/app/controllers/reservations_controller.rb b/app/controllers/reservations_controller.rb new file mode 100644 index 0000000..de35726 --- /dev/null +++ b/app/controllers/reservations_controller.rb @@ -0,0 +1,68 @@ +class ReservationsController < ApplicationController + before_action :find_reservations, only: %i[index show create update destroy] + + # GET + def index + reservations = @reservations.includes(place: :city) + + render json: reservations.as_json( + include: { + place: { only: %i[name image_url description], + include: { city: { only: :name } } } + } + ), status: :ok + end + + # GET + def show + reservation = @reservations.find_by(id: params[:id]) + render json: reservation, status: :ok + end + + # POST + def create + reservation = @reservations.new(reservation_params) + + if reservation.save + render json: reservation.as_json( + include: { + place: { only: %i[name image_url description], + include: { city: { only: :name } } } + } + ), status: :ok + else + render json: { errors: reservation.errors.full_messages }, status: :unprocessable_entity + end + end + + # PATCH/PUT + def update + reservation = @reservations.find(params[:id]) + if reservation.update(reservation_params) + render json: reservation, status: :ok + else + render json: { errors: reservation.errors.full_messages }, status: :unprocessable_entity + end + end + + # DELETE + def destroy + reservation = @reservations.find(params[:id]) + if reservation.destroy + render json: { message: 'Reservation deteled successfully!' }, status: :ok, head: :no_content + else + render json: reservation.errors, status: :unprocessable_entity, head: :no_content + end + end + + private + + # Find all the reservations for a user. + def find_reservations + @reservations = Reservation.where(user_id: params[:user_id]) + end + + def reservation_params + params.require(:reservation).permit(:place_id, :schedule_date) + end +end diff --git a/app/controllers/users/registrations_controller.rb b/app/controllers/users/registrations_controller.rb new file mode 100644 index 0000000..49b238c --- /dev/null +++ b/app/controllers/users/registrations_controller.rb @@ -0,0 +1,19 @@ +class Users::RegistrationsController < Devise::RegistrationsController + include RackSessionsFix + respond_to :json + + private + + def respond_with(current_user, _opts = {}) + if resource.persisted? + render json: { + status: { code: 200, message: 'Signed up successfully.' }, + data: UserSerializer.new(current_user).serializable_hash[:data][:attributes] + } + else + render json: { + status: { message: "User couldn't be created successfully. #{current_user.errors.full_messages.to_sentence}" } + }, status: :unprocessable_entity + end + end +end diff --git a/app/controllers/users/sessions_controller.rb b/app/controllers/users/sessions_controller.rb new file mode 100644 index 0000000..ee96a57 --- /dev/null +++ b/app/controllers/users/sessions_controller.rb @@ -0,0 +1,35 @@ +class Users::SessionsController < Devise::SessionsController + include RackSessionsFix + respond_to :json + + private + + def respond_with(current_user, _opts = {}) + render json: { + status: { + code: 200, message: 'Logged in successfully.', + data: { user: UserSerializer.new(current_user).serializable_hash[:data][:attributes] } + } + }, status: :ok + end + + def respond_to_on_destroy + if request.headers['Authorization'].present? + jwt_payload = JWT.decode(request.headers['Authorization'].split.last, + Rails.application.credentials.devise_jwt_secret_key!).first + current_user = User.find(jwt_payload['sub']) + end + + if current_user + render json: { + status: 200, + message: 'Logged out successfully.' + }, status: :ok + else + render json: { + status: 401, + message: "Couldn't find an active session." + }, status: :unauthorized + end + end +end diff --git a/app/jobs/application_job.rb b/app/jobs/application_job.rb new file mode 100644 index 0000000..d394c3d --- /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 0000000..286b223 --- /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 0000000..b63caeb --- /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/city.rb b/app/models/city.rb new file mode 100644 index 0000000..511dfee --- /dev/null +++ b/app/models/city.rb @@ -0,0 +1,6 @@ +class City < ApplicationRecord + has_many :reservations + has_many :places + + validates :name, presence: true, length: { maximum: 100 } +end diff --git a/app/models/concerns/.keep b/app/models/concerns/.keep new file mode 100644 index 0000000..e69de29 diff --git a/app/models/detail.rb b/app/models/detail.rb new file mode 100644 index 0000000..8cb597a --- /dev/null +++ b/app/models/detail.rb @@ -0,0 +1,10 @@ +class Detail < ApplicationRecord + belongs_to :place + + validates :place_type, presence: true + validates :bedrooms, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 1 } + validates :beds, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 1 } + validates :bathrooms, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 1 } + validates :property_type, presence: true + validates :price, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0 } +end diff --git a/app/models/place.rb b/app/models/place.rb new file mode 100644 index 0000000..b638969 --- /dev/null +++ b/app/models/place.rb @@ -0,0 +1,11 @@ +class Place < ApplicationRecord + belongs_to :user + has_one :detail, dependent: :destroy + belongs_to :city + has_many :reservations, dependent: :destroy + + validates :name, presence: true, length: { minimum: 3, maximum: 255 } + validates :image_url, presence: true, format: { with: %r{\Ahttps?://\S+\z}, message: 'Invalid URL format' } + validates :description, presence: true, length: { minimum: 3, maximum: 255 } + validates :city, presence: true +end diff --git a/app/models/reservation.rb b/app/models/reservation.rb new file mode 100644 index 0000000..34f1d16 --- /dev/null +++ b/app/models/reservation.rb @@ -0,0 +1,15 @@ +class Reservation < ApplicationRecord + belongs_to :user + belongs_to :place + + validates_presence_of :user, :place, :schedule_date + validate :schedule_date_in_future + + private + + def schedule_date_in_future + return unless schedule_date.present? && schedule_date < Date.today + + errors.add(:schedule_date, 'must be in the future') + end +end diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 0000000..4c28d2e --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,10 @@ +class User < ApplicationRecord + include Devise::JWT::RevocationStrategies::JTIMatcher + + devise :database_authenticatable, :registerable, + :recoverable, :rememberable, :validatable, :jwt_authenticatable, jwt_revocation_strategy: self + has_many :reservations + has_many :places + + validates :username, presence: true, length: { maximum: 150 } +end diff --git a/app/serializers/user_serializer.rb b/app/serializers/user_serializer.rb new file mode 100644 index 0000000..e11b0fd --- /dev/null +++ b/app/serializers/user_serializer.rb @@ -0,0 +1,4 @@ +class UserSerializer + include JSONAPI::Serializer + attributes :id, :email, :username +end diff --git a/app/views/layouts/mailer.html.erb b/app/views/layouts/mailer.html.erb new file mode 100644 index 0000000..3aac900 --- /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 0000000..37f0bdd --- /dev/null +++ b/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/bin/bundle b/bin/bundle new file mode 100755 index 0000000..42c7fd7 --- /dev/null +++ b/bin/bundle @@ -0,0 +1,109 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'bundle' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require "rubygems" + +m = Module.new do + module_function + + def invoked_as_script? + File.expand_path($0) == File.expand_path(__FILE__) + end + + def env_var_version + ENV["BUNDLER_VERSION"] + end + + def cli_arg_version + return unless invoked_as_script? # don't want to hijack other binstubs + return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` + bundler_version = nil + update_index = nil + ARGV.each_with_index do |a, i| + if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN + bundler_version = a + end + next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ + bundler_version = $1 + update_index = i + end + bundler_version + end + + def gemfile + gemfile = ENV["BUNDLE_GEMFILE"] + return gemfile if gemfile && !gemfile.empty? + + File.expand_path("../Gemfile", __dir__) + end + + def lockfile + lockfile = + case File.basename(gemfile) + when "gems.rb" then gemfile.sub(/\.rb$/, ".locked") + else "#{gemfile}.lock" + end + File.expand_path(lockfile) + end + + def lockfile_version + return unless File.file?(lockfile) + lockfile_contents = File.read(lockfile) + return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ + Regexp.last_match(1) + end + + def bundler_requirement + @bundler_requirement ||= + env_var_version || + cli_arg_version || + bundler_requirement_for(lockfile_version) + end + + def bundler_requirement_for(version) + return "#{Gem::Requirement.default}.a" unless version + + bundler_gem_version = Gem::Version.new(version) + + bundler_gem_version.approximate_recommendation + end + + def load_bundler! + ENV["BUNDLE_GEMFILE"] ||= gemfile + + activate_bundler + end + + def activate_bundler + gem_error = activation_error_handling do + gem "bundler", bundler_requirement + end + return if gem_error.nil? + require_error = activation_error_handling do + require "bundler/version" + end + return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) + warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" + exit 42 + end + + def activation_error_handling + yield + nil + rescue StandardError, LoadError => e + e + end +end + +m.load_bundler! + +if m.invoked_as_script? + load Gem.bin_path("bundler", "bundle") +end diff --git a/bin/docker-entrypoint b/bin/docker-entrypoint new file mode 100755 index 0000000..67ef493 --- /dev/null +++ b/bin/docker-entrypoint @@ -0,0 +1,8 @@ +#!/bin/bash -e + +# 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 0000000..efc0377 --- /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 0000000..4fbf10b --- /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/setup b/bin/setup new file mode 100755 index 0000000..3cd5a9d --- /dev/null +++ b/bin/setup @@ -0,0 +1,33 @@ +#!/usr/bin/env ruby +require "fileutils" + +# path to your application root. +APP_ROOT = File.expand_path("..", __dir__) + +def system!(*args) + system(*args, exception: true) +end + +FileUtils.chdir APP_ROOT do + # This script is a way to set up or update your development environment automatically. + # This script is idempotent, so that you can run it at any time and get an expectable outcome. + # Add necessary setup steps to this file. + + puts "== Installing dependencies ==" + system! "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" +end diff --git a/config.ru b/config.ru new file mode 100644 index 0000000..ad1fbf2 --- /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 0000000..352431d --- /dev/null +++ b/config/application.rb @@ -0,0 +1,32 @@ +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 FinalCapstoneBackEnd + 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") + + # Only loads a smaller set of middleware suitable for API only apps. + # Middleware like session, flash, cookies can be added back manually. + # Skip views, helpers and assets when generating a new resource. + config.api_only = true + end +end diff --git a/config/boot.rb b/config/boot.rb new file mode 100644 index 0000000..988a5dd --- /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 0000000..f2f2cad --- /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: final_capstone_back_end_production diff --git a/config/credentials.yml.enc b/config/credentials.yml.enc new file mode 100644 index 0000000..2a9ba0b --- /dev/null +++ b/config/credentials.yml.enc @@ -0,0 +1 @@ +a6Q5e4Bx8aEhyIhtgauk4LDDXVsJ7D2C6j7OET2h2YLq6u473LFKA3nZJeXcdaWQMJaDrKsxGghqG9i/X7Y8CTeKd4BLTytL1p6x9qShfz/4nEXgrQmw800twDS7vbKWJySdVv0wM6AIBBAPjRX1XYk390kxb1Y1RZQaXqIYw8c1GqJvHlV6uPEPNq7qHJ4b0HiOpnWyHJf/6TsqgV+Qf2fXn+KVYZpMGQo0T4OIfUGuI12GGxxPxF0IAkyujo3l3GbL0M6fCwAD/6cyY4Z3XbSQu/+0paD64NGhAiYRKX76eSd5jidCIRbtupnDRaGQ2kAdkVAEg9e2XULFczxCahwGAbaRH1zBi3q9sDuFzL9sW5rYiWJuIVnw4/wuUUH9C2UcUCeygqod6wiHA1E8zubL/fJdmiMfJu1XI9yFz8OWQoug1Iv0ocfmtxMVtM3zhTVxKIea6A3Bdi2jwkE0QNBbvGlxvPvOJkK1ouyV/qw/3Yt46R4aCQDr9mcUmU+5cSxIPzkSus95HSfkG5dt9YM45GvLxqvfw9Jnp3ojYgffo59LARUJeTIIAgJFVv97KfnEvfOCZ95hpgo19VZ9mWMAoNTn72o+5FeWBdlhlTsZu5bTyX7NGjSysVqhhsMTf0gigMkMJhFvCOHLHva5THVOaUE4zdo=--o2iguLELWOu3RQ20--eulql6lfRFHqQQ/c8xlufQ== \ No newline at end of file diff --git a/config/database.yml b/config/database.yml new file mode 100644 index 0000000..ad3c97a --- /dev/null +++ b/config/database.yml @@ -0,0 +1,84 @@ +# PostgreSQL. Versions 9.3 and up are supported. +# +# Install the pg driver: +# gem install pg +# On macOS with Homebrew: +# gem install pg -- --with-pg-config=/usr/local/bin/pg_config +# On Windows: +# gem install pg +# Choose the win32 build. +# Install PostgreSQL and put its /bin directory on your path. +# +# Configure Using Gemfile +# gem "pg" +# +default: &default + adapter: postgresql + encoding: unicode + # For details on connection pooling, see Rails configuration guide + # https://guides.rubyonrails.org/configuring.html#database-pooling + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + username: <%= ENV["LOCAL_DATABASE_USERNAME"] %> + password: <%= ENV["LOCAL_DATABASE_PASSWORD"] %> + +development: + <<: *default + database: final_capstone_back_end_development + + # The specified database role being used to connect to PostgreSQL. + # To create additional roles in PostgreSQL see `$ createuser --help`. + # When left blank, PostgreSQL will use the default role. This is + # the same name as the operating system user running Rails. + #username: final_capstone_back_end + + # The password associated with the PostgreSQL role (username). + #password: + + # Connect on a TCP socket. Omitted by default since the client uses a + # domain socket that doesn't need configuration. Windows does not have + # domain sockets, so uncomment these lines. + #host: localhost + + # The TCP port the server listens on. Defaults to 5432. + # If your server runs on a different port number, change accordingly. + #port: 5432 + + # Schema search path. The server defaults to $user,public + #schema_search_path: myapp,sharedapp,public + + # Minimum log levels, in increasing order: + # debug5, debug4, debug3, debug2, debug1, + # log, notice, warning, error, fatal, and panic + # Defaults to warning. + #min_messages: notice + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: final_capstone_back_end_test + +# As with config/credentials.yml, you never want to store sensitive information, +# like your database password, in your source code. If your source code is +# ever seen by anyone, they now have access to your database. +# +# Instead, provide the password or a full connection URL as an environment +# variable when you boot the app. For example: +# +# DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" +# +# If the connection URL is provided in the special DATABASE_URL environment +# variable, Rails will automatically merge its configuration values on top of +# the values provided in this file. Alternatively, you can specify a connection +# URL environment variable explicitly: +# +# production: +# url: <%= ENV["MY_APP_DATABASE_URL"] %> +# +# Read https://guides.rubyonrails.org/configuring.html#configuring-a-database +# for a full overview on how database connection configuration can be specified. +# +production: + <<: *default + url: <%= ENV['DATABASE_URL'] %> diff --git a/config/environment.rb b/config/environment.rb new file mode 100644 index 0000000..cac5315 --- /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 0000000..bf53a51 --- /dev/null +++ b/config/environments/development.rb @@ -0,0 +1,82 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + config.after_initialize do + Bullet.enable = true + Bullet.alert = true + Bullet.bullet_logger = true + Bullet.console = true + Bullet.rails_logger = true + Bullet.add_footer = true + end + + # 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 + + config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } + + # 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.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 + + # 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 diff --git a/config/environments/production.rb b/config/environments/production.rb new file mode 100644 index 0000000..e99a554 --- /dev/null +++ b/config/environments/production.rb @@ -0,0 +1,90 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.enable_reloading = false + + # Eager load code on boot. 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 + + # 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 + + # Enable static file serving from the `/public` folder (turn off if using NGINX/Apache for it). + config.public_file_server.enabled = true + + # 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 + + # 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 include 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 = "final_capstone_back_end_production" + + 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 + + # 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 0000000..0dda9f9 --- /dev/null +++ b/config/environments/test.rb @@ -0,0 +1,64 @@ +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.enabled = true + 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 + + # Raise exceptions instead of rendering exception templates. + 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 + + 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 + + # 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/cors.rb b/config/initializers/cors.rb new file mode 100644 index 0000000..cb7ed82 --- /dev/null +++ b/config/initializers/cors.rb @@ -0,0 +1,17 @@ +# Be sure to restart your server when you modify this file. + +# Avoid CORS issues when API is called from the frontend app. +# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin Ajax requests. + +# Read more: https://github.com/cyu/rack-cors + +Rails.application.config.middleware.insert_before 0, Rack::Cors do + allow do + origins "*" + + resource "*", + headers: :any, + methods: [:get, :post, :put, :patch, :delete, :options, :head], + expose: [:Authorization] + end +end diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb new file mode 100644 index 0000000..acf7c00 --- /dev/null +++ b/config/initializers/devise.rb @@ -0,0 +1,324 @@ +# 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 = 'e8deb31c490f9813871fd11db26ddfd32e3ee5e728dc0dd50653306cd648d21a0ddc80141ba0465b1684a8a9d942439c2e0dd3fad271ccae675513da71b54719' + + # ==> 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 = '1e01347bd21974218c6b4783c3602d52ba9337552be7373c43c6e2784f7bcf4038cd6a478c62677cc6d52217e8249a48a6e0a6806ba5f6506da32ddad4741e23' + + # 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 = [] + + # 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 + + config.jwt do |jwt| + jwt.secret = Rails.application.credentials.devise_jwt_secret_key! + jwt.dispatch_requests = [ + ['POST', %r{^/login$}] + ] + jwt.revocation_requests = [ + ['DELETE', %r{^/logout$}] + ] + jwt.expiration_time = 30.minutes.to_i +end +end diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb new file mode 100644 index 0000000..c2d89e2 --- /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, :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 0000000..3860f65 --- /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/rswag_api.rb b/config/initializers/rswag_api.rb new file mode 100644 index 0000000..4d72f68 --- /dev/null +++ b/config/initializers/rswag_api.rb @@ -0,0 +1,14 @@ +Rswag::Api.configure do |c| + + # Specify a root folder where Swagger JSON files are located + # This is used by the Swagger middleware to serve requests for API descriptions + # NOTE: If you're using rswag-specs to generate Swagger, you'll need to ensure + # that it's configured to generate files in the same folder + c.swagger_root = Rails.root.to_s + '/swagger' + + # Inject a lambda function to alter the returned Swagger prior to serialization + # The function will have access to the rack env for the current request + # For example, you could leverage this to dynamically assign the "host" property + # + #c.swagger_filter = lambda { |swagger, env| swagger['host'] = env['HTTP_HOST'] } +end diff --git a/config/initializers/rswag_ui.rb b/config/initializers/rswag_ui.rb new file mode 100644 index 0000000..0a768c1 --- /dev/null +++ b/config/initializers/rswag_ui.rb @@ -0,0 +1,16 @@ +Rswag::Ui.configure do |c| + + # List the Swagger endpoints that you want to be documented through the + # swagger-ui. The first parameter is the path (absolute or relative to the UI + # host) to the corresponding endpoint and the second is a title that will be + # displayed in the document selector. + # NOTE: If you're using rspec-api to expose Swagger files + # (under swagger_root) as JSON or YAML endpoints, then the list below should + # correspond to the relative paths for those endpoints. + + c.swagger_endpoint '/api-docs/v1/swagger.yaml', 'API V1 Docs' + + # Add Basic Auth in case your API is private + # c.basic_auth_enabled = true + # c.basic_auth_credentials 'username', 'password' +end diff --git a/config/locales/devise.en.yml b/config/locales/devise.en.yml new file mode 100644 index 0000000..260e1c4 --- /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 0000000..6c349ae --- /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 0000000..42eef65 --- /dev/null +++ b/config/puma.rb @@ -0,0 +1,36 @@ +# 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 can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers: a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum; this matches the default thread size of Active Record. +max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } +min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } +threads min_threads_count, max_threads_count + +# Specifies that the worker count should equal the number of processors in production. +if ENV["RAILS_ENV"] == "production" + require "concurrent-ruby" + workers ENV.fetch("WEB_CONCURRENCY") { 4 } +end + +# Specifies the `worker_timeout` threshold that Puma will use to wait before +# terminating a worker in development environments. +worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development" + +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. +port ENV.fetch("PORT") { 3000 } + +# Specifies the `environment` that Puma will run in. +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the `pidfile` that Puma will use. +pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } + +preload_app! + +# Allow puma to be restarted by `bin/rails restart` command. +plugin :tmp_restart diff --git a/config/routes.rb b/config/routes.rb new file mode 100644 index 0000000..cfb7116 --- /dev/null +++ b/config/routes.rb @@ -0,0 +1,35 @@ +Rails.application.routes.draw do + mount Rswag::Ui::Engine => '/api-docs' + mount Rswag::Api::Engine => '/api-docs' + # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html + devise_for :users, path: '', path_names: { + sign_in: 'login', + sign_out: 'logout', + registration: 'signup' + }, + controllers: { + sessions: 'users/sessions', + registrations: 'users/registrations' + } + + # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. + # Can be used by load balancers and uptime monitors to verify that the app is live. + get "up" => "rails/health#show", as: :rails_health_check + + # Defines the root path route ("/") + # root "posts#index" + + + resources :users do + resources :reservations, only: [:index, :show, :create, :update, :destroy] + get "places/:place_id/city(.:format)" => "cities#show", as: :place_cities + resources :places, only: [:create, :update, :destroy] + end + + get "places/:place_id/details" => "details#index", as: :place_details + + + resources :cities, only: [:index] + + resources :places, only: [:index, :show] +end diff --git a/config/storage.yml b/config/storage.yml new file mode 100644 index 0000000..4942ab6 --- /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/20231026150813_devise_create_users.rb b/db/migrate/20231026150813_devise_create_users.rb new file mode 100644 index 0000000..6c790fb --- /dev/null +++ b/db/migrate/20231026150813_devise_create_users.rb @@ -0,0 +1,43 @@ +class DeviseCreateUsers < ActiveRecord::Migration[7.1] + def change + create_table :users do |t| + t.string :username, null: false, default: "" + ## Database authenticatable + t.string :email, null: false, default: "" + t.string :encrypted_password, null: false, default: "" + + ## Recoverable + t.string :reset_password_token + t.datetime :reset_password_sent_at + + ## Rememberable + t.datetime :remember_created_at + + ## Trackable + # t.integer :sign_in_count, default: 0, null: false + # t.datetime :current_sign_in_at + # t.datetime :last_sign_in_at + # t.string :current_sign_in_ip + # t.string :last_sign_in_ip + + ## Confirmable + # t.string :confirmation_token + # t.datetime :confirmed_at + # t.datetime :confirmation_sent_at + # t.string :unconfirmed_email # Only if using reconfirmable + + ## Lockable + # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts + # t.string :unlock_token # Only if unlock strategy is :email or :both + # t.datetime :locked_at + + + t.timestamps null: false + end + + add_index :users, :email, unique: true + add_index :users, :reset_password_token, unique: true + # add_index :users, :confirmation_token, unique: true + # add_index :users, :unlock_token, unique: true + end +end diff --git a/db/migrate/20231026154304_create_cities.rb b/db/migrate/20231026154304_create_cities.rb new file mode 100644 index 0000000..115f8b0 --- /dev/null +++ b/db/migrate/20231026154304_create_cities.rb @@ -0,0 +1,9 @@ +class CreateCities < ActiveRecord::Migration[7.1] + def change + create_table :cities do |t| + t.string :name + + t.timestamps + end + end +end diff --git a/db/migrate/20231026154427_create_places.rb b/db/migrate/20231026154427_create_places.rb new file mode 100644 index 0000000..f1ea20a --- /dev/null +++ b/db/migrate/20231026154427_create_places.rb @@ -0,0 +1,13 @@ +class CreatePlaces < ActiveRecord::Migration[7.1] + def change + create_table :places do |t| + t.references :user, null: false, foreign_key: true + t.references :city, null: false, foreign_key: true + t.string :name + t.string :image_url + t.string :description + + t.timestamps + end + end +end diff --git a/db/migrate/20231026154555_create_details.rb b/db/migrate/20231026154555_create_details.rb new file mode 100644 index 0000000..5a3875b --- /dev/null +++ b/db/migrate/20231026154555_create_details.rb @@ -0,0 +1,15 @@ +class CreateDetails < ActiveRecord::Migration[7.1] + def change + create_table :details do |t| + t.references :place, null: false, foreign_key: true + t.string :place_type + t.integer :bedrooms + t.integer :beds + t.integer :bathrooms + t.string :property_type + t.integer :price + + t.timestamps + end + end +end diff --git a/db/migrate/20231026155958_create_reservations.rb b/db/migrate/20231026155958_create_reservations.rb new file mode 100644 index 0000000..67b03dd --- /dev/null +++ b/db/migrate/20231026155958_create_reservations.rb @@ -0,0 +1,12 @@ +class CreateReservations < ActiveRecord::Migration[7.1] + def change + create_table :reservations do |t| + t.references :user, null: false, foreign_key: true + t.references :place, null: false, foreign_key: true + t.date :schedule_date + + + t.timestamps + end + end +end diff --git a/db/migrate/20231026202957_add_jti_to_users.rb b/db/migrate/20231026202957_add_jti_to_users.rb new file mode 100644 index 0000000..d17072b --- /dev/null +++ b/db/migrate/20231026202957_add_jti_to_users.rb @@ -0,0 +1,6 @@ +class AddJtiToUsers < ActiveRecord::Migration[7.1] + def change + add_column :users, :jti, :string, null: false + add_index :users, :jti, unique: true + end +end diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 0000000..00871e1 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,78 @@ +# 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: 2023_10_26_202957) do + # These are extensions that must be enabled in order to support this database + enable_extension "plpgsql" + + create_table "cities", force: :cascade do |t| + t.string "name" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + + create_table "details", force: :cascade do |t| + t.bigint "place_id", null: false + t.string "place_type" + t.integer "bedrooms" + t.integer "beds" + t.integer "bathrooms" + t.string "property_type" + t.integer "price" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["place_id"], name: "index_details_on_place_id" + end + + create_table "places", force: :cascade do |t| + t.bigint "user_id", null: false + t.bigint "city_id", null: false + t.string "name" + t.string "image_url" + t.string "description" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["city_id"], name: "index_places_on_city_id" + t.index ["user_id"], name: "index_places_on_user_id" + end + + create_table "reservations", force: :cascade do |t| + t.bigint "user_id", null: false + t.bigint "place_id", null: false + t.date "schedule_date" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["place_id"], name: "index_reservations_on_place_id" + t.index ["user_id"], name: "index_reservations_on_user_id" + end + + create_table "users", force: :cascade do |t| + t.string "username", default: "", null: false + t.string "email", default: "", null: false + t.string "encrypted_password", default: "", null: false + t.string "reset_password_token" + t.datetime "reset_password_sent_at" + t.datetime "remember_created_at" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.string "jti", null: false + t.index ["email"], name: "index_users_on_email", unique: true + t.index ["jti"], name: "index_users_on_jti", unique: true + t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true + end + + add_foreign_key "details", "places" + add_foreign_key "places", "cities" + add_foreign_key "places", "users" + add_foreign_key "reservations", "places" + add_foreign_key "reservations", "users" +end diff --git a/db/seeds.rb b/db/seeds.rb new file mode 100644 index 0000000..a28e5b4 --- /dev/null +++ b/db/seeds.rb @@ -0,0 +1,71 @@ +# Seed Users +users_data = [ + { email: 'graujavier@gmail.com', username: 'Javier', password: '123456' }, + { email: 'sanchezmanuel@gmail.com', username: 'Manuel', password: '123456' }, + { email: 'vasquezanthony@gmail.com', username: 'Anthony', password: '123456' }, +] + +users = users_data.map do |user_data| + User.find_or_create_by!(email: user_data[:email]) do |u| + u.username = user_data[:username] + u.password = user_data[:password] + end +end + +# Seed Cities +cities_data = [ + 'New York City, USA', + 'London, UK', + 'Paris, France', + 'Tokyo, Japan', + 'Sydney, Australia', + 'Shanghai, China', + 'Berlin, Germany', + 'Rome, Italy', + 'Hong Kong, China', + 'Dubai, UAE', + 'Istanbul, Turkey', + 'Singapore', + 'Beijing, China', + 'Seoul, South Korea', + 'Moscow, Russia' +] + +adjectives = ["Beautiful", "Gorgeous", "Brilliant", "Charming", "Elegant", "Fascinating", "Graceful", "Incredible", "Magnificent"] +property_type = ["Apartment", "House", "Guest House", "Hotel"] + +# Data Fetching Photos from Unsplash +base_url = 'https://api.unsplash.com/search/photos?query=' +access_key = 'D5vfOwznTRQV6XfGv_rMQ2fsxPmwB41nSNimzUNUUJE' +query = 'hotel room'.parameterize +orientation = 'squarish' + +response = HTTParty.get(base_url, query: { query: query, orientation: orientation }, headers: { 'Authorization' => "Client-ID #{access_key}" }) + +# Seed a place for each city +cities_data.each do |city_name| + city = City.find_or_create_by!(name: city_name) + image_url = response['results'].sample['urls']['regular'] + place_name = "#{adjectives.sample} #{property_type.sample}" + + Place.find_or_create_by!(name: place_name, city: city) do |place| + place.user = users.sample + place.image_url = image_url + place.description = "Description of #{place_name}" + end +end + +# Seed a details for each place +Place.all.each do |place| + Detail.find_or_create_by!(place: place) do |detail| + detail.place = place + detail.place_type = ["Room", "Entire Place"].sample + detail.bedrooms = rand(1..5) + detail.beds = rand(1..10) + detail.bathrooms = rand(1..5) + detail.property_type = property_type.sample + detail.price = rand(500..5000) + end +end + +puts 'Seeds created successfully!' diff --git a/lib/tasks/.keep b/lib/tasks/.keep new file mode 100644 index 0000000..e69de29 diff --git a/log/.keep b/log/.keep new file mode 100644 index 0000000..e69de29 diff --git a/public/robots.txt b/public/robots.txt new file mode 100644 index 0000000..c19f78a --- /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/cities.rb b/spec/factories/cities.rb new file mode 100644 index 0000000..0ab2d6c --- /dev/null +++ b/spec/factories/cities.rb @@ -0,0 +1,7 @@ +require 'faker' + +FactoryBot.define do + factory :city do + name { Faker::Address.city } + end +end diff --git a/spec/factories/details.rb b/spec/factories/details.rb new file mode 100644 index 0000000..a1825e9 --- /dev/null +++ b/spec/factories/details.rb @@ -0,0 +1,13 @@ +require 'faker' + +FactoryBot.define do + factory :detail do + place_type { Faker::Lorem.word } + bedrooms { Faker::Number.between(from: 1, to: 10) } + beds { Faker::Number.between(from: 1, to: 10) } + bathrooms { Faker::Number.between(from: 1, to: 10) } + property_type { Faker::Lorem.word } + price { Faker::Number.between(from: 50, to: 500) } + place + end +end diff --git a/spec/factories/places.rb b/spec/factories/places.rb new file mode 100644 index 0000000..f61af76 --- /dev/null +++ b/spec/factories/places.rb @@ -0,0 +1,11 @@ +require 'faker' + +FactoryBot.define do + factory :place do + name { Faker::Lorem.words(number: 3).join(' ') } + image_url { Faker::Internet.url } + description { Faker::Lorem.sentence } + user + city + end +end diff --git a/spec/factories/reservations.rb b/spec/factories/reservations.rb new file mode 100644 index 0000000..d026233 --- /dev/null +++ b/spec/factories/reservations.rb @@ -0,0 +1,8 @@ +# spec/factories/reservations.rb +FactoryBot.define do + factory :reservation do + user + place + schedule_date { Date.today } + end +end diff --git a/spec/factories/users.rb b/spec/factories/users.rb new file mode 100644 index 0000000..fd906b9 --- /dev/null +++ b/spec/factories/users.rb @@ -0,0 +1,9 @@ +require 'faker' + +FactoryBot.define do + factory :user do + username { Faker::Internet.username } + email { Faker::Internet.email } + password { Faker::Internet.password } + end +end diff --git a/spec/integration/api/cities_spec.rb b/spec/integration/api/cities_spec.rb new file mode 100644 index 0000000..a073393 --- /dev/null +++ b/spec/integration/api/cities_spec.rb @@ -0,0 +1,34 @@ +require 'swagger_helper' + +RSpec.describe 'api/cities', type: :request do + path '/cities' do + get 'Retrieves a list of cities' do + tags 'Cities' + produces 'application/json' + response '200', 'cities found' do + schema type: :array, + items: { + properties: { + name: { type: :string } + } + } + run_test! + end + end + end + + path '/users/{user_id}/places/{place_id}/city' do + get 'Retrieves a city' do + tags 'Cities' + produces 'application/json' + parameter name: :user_id, in: :path, type: :string, + description: 'User ID' + parameter name: :place_id, in: :path, type: :string, description: 'Place ID' + response '200', 'city found' do + let(:user_id) { create(:user).id } + let(:place_id) { create(:place, user_id:).id } + run_test! + end + end + end +end diff --git a/spec/integration/api/details_spec.rb b/spec/integration/api/details_spec.rb new file mode 100644 index 0000000..d4a98a0 --- /dev/null +++ b/spec/integration/api/details_spec.rb @@ -0,0 +1,17 @@ +require 'swagger_helper' + +RSpec.describe 'api/details', type: :request do + path '/places/{place_id}/details' do + get 'Retrieves details for a specific place' do + tags 'Details' + produces 'application/json' + parameter name: :place_id, in: :path, type: :integer, description: 'Place ID' + response '200', 'details found' do + let(:user) { create(:user) } + let(:user_id) { user.id } + let(:place_id) { create(:place, user_id:).id } + run_test! + end + end + end +end diff --git a/spec/integration/api/places_spec.rb b/spec/integration/api/places_spec.rb new file mode 100644 index 0000000..a39d864 --- /dev/null +++ b/spec/integration/api/places_spec.rb @@ -0,0 +1,144 @@ +require 'swagger_helper' + +PLACE_SCHEMA = { + type: :object, + properties: { + place: { + type: :object, + properties: { + city_id: { type: :integer }, + name: { type: :string }, + image_url: { type: :string }, + description: { type: :string } + }, + required: %w[city_id name image_url description] + }, + details: { + type: :object, + properties: { + place_type: { type: :string }, + bedrooms: { type: :integer }, + beds: { type: :integer }, + bathrooms: { type: :integer }, + property_type: { type: :string }, + price: { type: :integer } + }, + required: %w[place_type bedrooms beds bathrooms property_type price] + } + }, + required: %w[place details] +}.freeze + +def place_valid_response + let(:user) { create(:user) } + let(:user_id) { user.id } + let(:place) { create(:place, user_id:) } +end + +def place_invalid_response + let(:user_id) { -678 } + let(:place) { nil } + run_test! +end + +RSpec.describe 'api/places', type: :request do + path '/places' do + get 'Retrieves a list of places' do + tags 'Places' + produces 'application/json' + parameter name: :user_id, in: :query, type: :string, description: 'User ID' + response '200', 'places found' do + schema type: :array, + items: { + properties: { + city: { name: { type: :string } }, + name: { type: :string }, + image_url: { type: :string }, + description: { type: :string } + } + } + let(:user_id) { create(:user).id } + run_test! + end + end + end + + path '/places/{id}' do + get 'Retrieves a place' do + tags 'Places' + produces 'application/json' + parameter name: :id, in: :path, type: :string, description: 'Place ID' + response '200', 'place found' do + let(:place) { create(:place) } + let(:id) { place.id } + run_test! + end + + response '404', 'place not found' do + let(:id) { 'invalid' } + end + end + end + + path '/users/{user_id}/places' do + post 'Creates a place' do + tags 'Places' + consumes 'application/json' + parameter name: :user_id, in: :path, type: :string, description: 'User ID' + parameter name: :place, in: :body, schema: PLACE_SCHEMA + + response '201', 'place created' do + place_valid_response + end + + response '400', 'invalid request' do + place_invalid_response + end + end + end + + path '/users/{user_id}/places/{id}' do + put 'Updates a place' do + tags 'Places' + consumes 'application/json' + parameter name: :user_id, in: :path, type: :string, description: 'User ID' + parameter name: :id, in: :path, type: :string, description: 'Place ID' + parameter name: :place, in: :body, schema: PLACE_SCHEMA + + response '200', 'place updated' do + let(:user_id) { create(:user).id } + let(:place) { create(:place, user_id:) } + let(:id) { place.id } + run_test! + end + + response '404', 'invalid request' do + let(:user_id) { 'invalid' } + let(:place) { 'invalid' } + let(:id) { 'invalid' } + run_test! + end + end + end + + path '/users/{user_id}/places/{id}' do + delete 'Deletes a place' do + tags 'Places' + parameter name: :user_id, in: :path, type: :integer, description: 'User ID' + parameter name: :id, in: :path, type: :string, description: 'Place ID' + + response '200', 'place deleted' do + let(:user_id) { create(:user).id } + let(:place) { create(:place, user_id:) } + let(:id) { place.id } + run_test! + end + + response '404', 'place not found' do + let(:user_id) { 'invalid' } + let(:id) { 'invalid' } + run_test! + end + end + end +end diff --git a/spec/integration/api/reservations_spec.rb b/spec/integration/api/reservations_spec.rb new file mode 100644 index 0000000..8715c71 --- /dev/null +++ b/spec/integration/api/reservations_spec.rb @@ -0,0 +1,127 @@ +require 'swagger_helper' + +RSpec.describe 'api/reservations', type: :request do + path '/users/{user_id}/reservations' do + get 'Retrieves a list of reservations' do + tags 'Reservations' + produces 'application/json' + parameter name: :user_id, in: :path, type: :integer, description: 'User ID' + response '200', 'reservations found' do + schema type: :array, + items: { + properties: { + place: { + type: :object, + properties: { + name: { type: :string }, + image_url: { type: :string }, + description: { type: :string }, + city: { + type: :object, + properties: { + name: { type: :string } + } + } + } + } + } + } + let(:user_id) { create(:user).id } + run_test! + end + end + end + + path '/users/{user_id}/reservations' do + post 'Creates a reservation' do + tags 'Reservations' + consumes 'application/json' + parameter name: :user_id, in: :path, type: :integer, description: 'User ID' + parameter name: :reservation, in: :body, schema: { + type: :object, + properties: { + place_id: { type: :integer }, + schedule_date: { type: :string, format: :date } + }, + required: %w[place_id schedule_date] + } + response '200', 'reservation created' do + let(:user_id) { create(:user).id } + let(:reservation) { { place_id: create(:place).id, schedule_date: '2023-12-31' } } + run_test! + end + + response '422', 'invalid request' do + let(:user_id) { create(:user).id } + let(:reservation) { { place_id: nil, schedule_date: 'invalid' } } + run_test! + end + end + end + + path '/users/{user_id}/reservations/{id}' do + get 'Retrieves a reservation' do + tags 'Reservations' + produces 'application/json' + parameter name: :user_id, in: :path, type: :integer, description: 'User ID' + parameter name: :id, in: :path, type: :integer, description: 'Reservation ID' + response '200', 'reservation found' do + let(:user) { create(:user) } + let(:user_id) { user.id } + let(:reservation) { create(:reservation, user_id:) } + let(:id) { reservation.id } + run_test! + end + end + end + + path '/users/{user_id}/reservations/{id}' do + put 'Updates a reservation' do + tags 'Reservations' + consumes 'application/json' + parameter name: :user_id, in: :path, type: :integer, description: 'User ID' + parameter name: :id, in: :path, type: :integer, description: 'Reservation ID' + parameter name: :reservation, in: :body, schema: { + type: :object, + properties: { + place_id: { type: :integer }, + schedule_date: { type: :string, format: :date } + } + } + response '200', 'reservation updated' do + let(:user_id) { create(:user).id } + let(:reservation) { create(:reservation, user_id:) } + let(:id) { reservation.id } + let(:reservation_params) { { place_id: create(:place).id, schedule_date: '2023-12-31' } } + run_test! + end + + response '404', 'invalid request' do + let(:user_id) { 'invalid' } + let(:reservation) { 'invalid' } + let(:id) { 'invalid' } + run_test! + end + end + end + + path '/users/{user_id}/reservations/{id}' do + delete 'Deletes a reservation' do + tags 'Reservations' + parameter name: :user_id, in: :path, type: :integer, description: 'User ID' + parameter name: :id, in: :path, type: :integer, description: 'Reservation ID' + response '200', 'reservation deleted' do + let(:user_id) { create(:user).id } + let(:reservation) { create(:reservation, user_id:) } + let(:id) { reservation.id } + run_test! + end + + response '404', 'reservation not found' do + let(:user_id) { create(:user).id } + let(:id) { 'invalid' } + run_test! + end + end + end +end diff --git a/spec/integration/api/users_spec.rb b/spec/integration/api/users_spec.rb new file mode 100644 index 0000000..071b189 --- /dev/null +++ b/spec/integration/api/users_spec.rb @@ -0,0 +1,44 @@ +require 'swagger_helper' + +USER_PARAMS = { + type: :object, + properties: { + user: { + type: :object, + properties: { + username: { type: :string }, + email: { type: :string }, + password: { type: :string } + }, + required: %w[username email password] + } + }, + required: %w[user] +}.freeze + +RSpec.describe 'api/users', type: :request do + path '/signup' do + post 'Create a new user' do + tags 'Users' + consumes 'application/json' + parameter name: :user, in: :body, schema: USER_PARAMS + response '200', 'user created' do + let(:user) do + { + user: { + username: 'test', + email: 'example@gmail.com', + password: 'password123' + } + } + end + run_test! + end + + response '422', 'invalid request' do + let(:user) { 'invalid' } + run_test! + end + end + end +end diff --git a/spec/models/city_spec.rb b/spec/models/city_spec.rb new file mode 100644 index 0000000..a63e37c --- /dev/null +++ b/spec/models/city_spec.rb @@ -0,0 +1,22 @@ +require 'rails_helper' + +RSpec.describe City, type: :model do + describe 'validations' do + it { should validate_presence_of(:name) } + + it 'validates that name is not empty' do + city = build(:city, name: '') + expect(city).to be_invalid + expect(city).to be_invalid + end + + it 'validates that the name has a maximun length of 100' do + city = build(:city, name: 'aaaaa' * 25) + expect(city).to be_invalid + end + end + + describe 'associations' do + it { should have_many(:places) } + end +end diff --git a/spec/models/detail_spec.rb b/spec/models/detail_spec.rb new file mode 100644 index 0000000..f035f18 --- /dev/null +++ b/spec/models/detail_spec.rb @@ -0,0 +1,16 @@ +require 'rails_helper' + +RSpec.describe Detail, type: :model do + it { should belong_to(:place) } + + it { should validate_presence_of(:place_type) } + it { should validate_presence_of(:bedrooms) } + it { should validate_numericality_of(:bedrooms).only_integer.is_greater_than_or_equal_to(1) } + it { should validate_presence_of(:beds) } + it { should validate_numericality_of(:beds).only_integer.is_greater_than_or_equal_to(1) } + it { should validate_presence_of(:bathrooms) } + it { should validate_numericality_of(:bathrooms).only_integer.is_greater_than_or_equal_to(1) } + it { should validate_presence_of(:property_type) } + it { should validate_presence_of(:price) } + it { should validate_numericality_of(:price).only_integer.is_greater_than_or_equal_to(0) } +end diff --git a/spec/models/place_spec.rb b/spec/models/place_spec.rb new file mode 100644 index 0000000..4ef7cf3 --- /dev/null +++ b/spec/models/place_spec.rb @@ -0,0 +1,16 @@ +require 'rails_helper' + +RSpec.describe Place, type: :model do + it { should belong_to(:user) } + it { should belong_to(:city) } + it { should have_one(:detail).dependent(:destroy) } + + it { should validate_presence_of(:name) } + it { should validate_presence_of(:city) } + it { should validate_length_of(:name).is_at_least(3).is_at_most(255) } + it { should validate_presence_of(:image_url) } + it { should allow_value('http://example.com').for(:image_url) } + it { should_not allow_value('invalid_url').for(:image_url) } + it { should validate_presence_of(:description) } + it { should validate_length_of(:description).is_at_least(3).is_at_most(255) } +end diff --git a/spec/models/reservation_spec.rb b/spec/models/reservation_spec.rb new file mode 100644 index 0000000..ed5a9dd --- /dev/null +++ b/spec/models/reservation_spec.rb @@ -0,0 +1,20 @@ +require 'rails_helper' + +RSpec.describe Reservation, type: :model do + describe 'validations' do + it { should validate_presence_of(:user) } + it { should validate_presence_of(:place) } + it { should validate_presence_of(:schedule_date) } + + it 'validates that schedule_date is in the future' do + reservation = build(:reservation, schedule_date: '2020-12-12') + expect(reservation).to be_invalid + expect(reservation.errors[:schedule_date]).to include('must be in the future') + end + end + + describe 'associations' do + it { should belong_to(:user) } + it { should belong_to(:place) } + end +end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb new file mode 100644 index 0000000..a3c9675 --- /dev/null +++ b/spec/models/user_spec.rb @@ -0,0 +1,24 @@ +require 'rails_helper' + +RSpec.describe User, type: :model do + describe 'validations' do + it { should validate_presence_of(:username) } + it { should validate_presence_of(:email) } + it { should validate_presence_of(:password) } + + it 'validates that username is not empty' do + user = build(:user, username: '') + expect(user).to be_invalid + end + + it 'validates that the username has a maximun length of 150' do + user = build(:user, username: 'aaaaa' * 35) + expect(user).to be_invalid + end + end + + describe 'associations' do + it { should have_many(:reservations) } + it { should have_many(:places) } + end +end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb new file mode 100644 index 0000000..2572cd0 --- /dev/null +++ b/spec/rails_helper.rb @@ -0,0 +1,73 @@ +# 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? +require 'rspec/rails' +# Add additional requires below this line. Rails is not loaded until this point! + +# Requires supporting ruby files with custom matchers and macros, etc, in +# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are +# run as spec files by default. This means that files in spec/support that end +# in _spec.rb will both be required and run as specs, causing the specs to be +# run twice. It is recommended that you do not name files matching this glob to +# end with _spec.rb. You can configure this pattern with the --pattern +# option on the command line or in ~/.rspec, .rspec or `.rspec-local`. +# +# The following line is provided for convenience purposes. It has the downside +# of increasing the boot-up time by auto-requiring all files in the support +# directory. Alternatively, in the individual `*_spec.rb` files, manually +# require only the support files necessary. +# +# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.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.include FactoryBot::Syntax::Methods + config.include Devise::Test::ControllerHelpers, type: :controller + # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures + config.fixture_path = "#{Rails.root}/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 can automatically mix in different behaviours to your tests + # based on their file location, for example enabling you to call `get` and + # `post` in specs under `spec/controllers`. + # + # You can disable this behaviour by removing the line below, and instead + # explicitly tag your specs with their type, e.g.: + # + # RSpec.describe UsersController, type: :controller do + # # ... + # end + # + # The different available types are documented in the features, such as in + # https://rspec.info/features/6-0/rspec-rails + 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") + + require 'shoulda/matchers' + Shoulda::Matchers.configure do |configuration| + configuration.integrate do |with| + with.test_framework :rspec + with.library :rails + end + end +end diff --git a/spec/requests/cities_spec.rb b/spec/requests/cities_spec.rb new file mode 100644 index 0000000..f1d73ea --- /dev/null +++ b/spec/requests/cities_spec.rb @@ -0,0 +1,27 @@ +require 'rails_helper' + +RSpec.describe 'Cities', type: :request do + describe 'GET /cities' do + it 'shows all the cities' do + city = FactoryBot.create(:city) + + get cities_path + + expect(response).to have_http_status(200) + expect(response.body).to include(city.name) + end + end + + describe 'GET /places/:place_id/city' do + it 'shows the city for a place' do + user = FactoryBot.create(:user) + city = FactoryBot.create(:city) + place = FactoryBot.create(:place, user:, city:) + + get user_place_cities_path(user, place) + + expect(response).to have_http_status(200) + expect(response.body).to include(city.name) + end + end +end diff --git a/spec/requests/details_spec.rb b/spec/requests/details_spec.rb new file mode 100644 index 0000000..c2742f4 --- /dev/null +++ b/spec/requests/details_spec.rb @@ -0,0 +1,21 @@ +require 'rails_helper' + +RSpec.describe 'Details API', type: :request do + let(:user) { create(:user) } + let(:place) { create(:place, user_id: user.id) } + let!(:detail) { create(:detail, place_id: place.id) } + + describe 'GET /places/:place_id/details' do + before { get "/places/#{place.id}/details" } + + it 'returns details' do + parsed_response = JSON.parse(response.body) + expect(parsed_response).not_to be_empty + expect(parsed_response['id']).to eq(detail.id) + end + + it 'returns status code 200' do + expect(response).to have_http_status(200) + end + end +end diff --git a/spec/requests/places_spec.rb b/spec/requests/places_spec.rb new file mode 100644 index 0000000..99e6439 --- /dev/null +++ b/spec/requests/places_spec.rb @@ -0,0 +1,37 @@ +require 'rails_helper' + +RSpec.describe 'Places API', type: :request do + let(:user) { create(:user) } + let!(:places) { create_list(:place, 10, user_id: user.id) } + let(:place_id) { places.first.id } + + describe 'GET /places' do + before { get '/places' } + + it 'returns places' do + expect(response.body).not_to be_empty + parsed_response = JSON.parse(response.body) + expect(parsed_response.size).to eq(10) + end + + it 'returns status code 200' do + expect(response).to have_http_status(200) + end + end + + describe 'GET /places/:id' do + before { get "/places/#{place_id}" } + + context 'when the record exists' do + it 'returns the place' do + expect(response.body).not_to be_empty + parsed_response = JSON.parse(response.body) + expect(parsed_response['id']).to eq(place_id) + end + + it 'returns status code 200' do + expect(response).to have_http_status(200) + end + end + end +end diff --git a/spec/requests/reservations_request_spec.rb b/spec/requests/reservations_request_spec.rb new file mode 100644 index 0000000..eb84b54 --- /dev/null +++ b/spec/requests/reservations_request_spec.rb @@ -0,0 +1,75 @@ +require 'rails_helper' + +RSpec.describe 'Reservations API', type: :request do + describe 'GET /users/:user_id/reservations' do + it 'returns a list of reservations' do + user = create(:user) + create_list(:reservation, 3, user:) + + get "/users/#{user.id}/reservations" + + expect(response).to have_http_status(200) + + reservations_json = JSON.parse(response.body) + expect(reservations_json.length).to eq(3) + end + end + + describe 'GET /users/:user_id/reservations/:reservation_id' do + it 'returns a specific reservation' do + user = create(:user) + reservation = create(:reservation, user:) + + get "/users/#{user.id}/reservations/#{reservation.id}" + + expect(response).to have_http_status(200) + + reservation_json = JSON.parse(response.body) + expect(reservation_json['id']).to eq(reservation.id) + end + end + + describe 'POST /users/:user_id/reservations' do + it 'creates a new reservation' do + user = create(:user) + place = create(:place) + + reservation_params = { + place_id: place.id, + schedule_date: Date.tomorrow + } + + post "/users/#{user.id}/reservations", params: { reservation: reservation_params } + + expect(response).to have_http_status(200) + end + end + + describe 'PATCH /users/:user_id/reservations/:reservation_id' do + it 'updates a reservation' do + user = create(:user) + reservation = create(:reservation, user:) + updated_schedule_date = Date.tomorrow + 2.days + + patch "/users/#{user.id}/reservations/#{reservation.id}", params: { + reservation: { schedule_date: updated_schedule_date } + } + + expect(response).to have_http_status(200) + reservation_json = JSON.parse(response.body) + expect(reservation_json['schedule_date']).to eq(updated_schedule_date.to_s) + end + end + + describe 'DELETE /users/:user_id/reservations/:reservation_id' do + it 'deletes a reservation' do + user = create(:user) + reservation = create(:reservation, user:) + + delete "/users/#{user.id}/reservations/#{reservation.id}" + + expect(response).to have_http_status(200) + expect { reservation.reload }.to raise_error(ActiveRecord::RecordNotFound) + end + end +end diff --git a/spec/requests/users_spec.rb b/spec/requests/users_spec.rb new file mode 100644 index 0000000..42456cf --- /dev/null +++ b/spec/requests/users_spec.rb @@ -0,0 +1,43 @@ +require 'rails_helper' + +RSpec.describe 'Users', type: :request do + describe 'POST /login' do + it 'logs in a user' do + user = FactoryBot.create(:user) + + post user_session_path, params: { user: { email: user.email, password: user.password } } + + json_response = JSON.parse(response.body) + + expect(response).to have_http_status(200) + expect(json_response['status']['message']).to eq('Logged in successfully.') + end + end + + describe 'DELETE /logout' do + it 'logs out a user' do + user = FactoryBot.create(:user) + + post user_session_path, params: { user: { email: user.email, password: user.password } } + + key = response.headers['authorization'] + + delete destroy_user_session_path, headers: { Authorization: key } + + expect(response).to have_http_status(200) + end + end + + describe 'POST /signup' do + it 'signs up a user' do + user_params = FactoryBot.attributes_for(:user) + + post user_registration_path, params: { user: user_params } + + json_response = JSON.parse(response.body) + + expect(response).to have_http_status(200) + expect(json_response['status']['message']).to eq('Signed up successfully.') + end + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..9c96a9b --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,92 @@ +# 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. + # # 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 diff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rb new file mode 100644 index 0000000..feaae2b --- /dev/null +++ b/spec/swagger_helper.rb @@ -0,0 +1,41 @@ +require 'rails_helper' + +RSpec.configure do |config| + # Specify a root folder where Swagger JSON files are generated + # NOTE: If you're using the rswag-api to serve API descriptions, you'll need + # to ensure that it's configured to serve Swagger from the same folder + config.swagger_root = Rails.root.join('swagger').to_s + + # Define one or more Swagger documents and provide global metadata for each one + # When you run the 'rswag:specs:swaggerize' rake task, the complete Swagger will + # be generated at the provided relative path under swagger_root + # By default, the operations defined in spec files are added to the first + # document below. You can override this behavior by adding a swagger_doc tag to the + # the root example_group in your specs, e.g. describe '...', swagger_doc: 'v2/swagger.json' + config.swagger_docs = { + 'v1/swagger.yaml' => { + openapi: '3.0.1', + info: { + title: 'API V1', + version: 'v1' + }, + paths: {}, + servers: [ + { + url: 'https://{defaultHost}', + variables: { + defaultHost: { + default: 'www.example.com' + } + } + } + ] + } + } + + # Specify the format of the output Swagger file when running 'rswag:specs:swaggerize'. + # The swagger_docs configuration option has the filename including format in + # the key, this may want to be changed to avoid putting yaml in json files. + # Defaults to json. Accepts ':json' and ':yaml'. + config.swagger_format = :yaml +end diff --git a/src/API_documentation.png b/src/API_documentation.png new file mode 100644 index 0000000..d99fb7e Binary files /dev/null and b/src/API_documentation.png differ diff --git a/src/ERD.png b/src/ERD.png new file mode 100644 index 0000000..99277b8 Binary files /dev/null and b/src/ERD.png differ diff --git a/storage/.keep b/storage/.keep new file mode 100644 index 0000000..e69de29 diff --git a/swagger/v1/swagger.yaml b/swagger/v1/swagger.yaml new file mode 100644 index 0000000..3d512af --- /dev/null +++ b/swagger/v1/swagger.yaml @@ -0,0 +1,431 @@ +--- +openapi: 3.0.1 +info: + title: API V1 + version: v1 +paths: + "/cities": + get: + summary: Retrieves a list of cities + tags: + - Cities + responses: + '200': + description: cities found + content: + application/json: + schema: + type: array + items: + properties: + name: + type: string + "/users/{user_id}/places/{place_id}/city": + get: + summary: Retrieves a city + tags: + - Cities + parameters: + - name: user_id + in: path + description: User ID + required: true + schema: + type: string + - name: place_id + in: path + description: Place ID + required: true + schema: + type: string + responses: + '200': + description: city found + "/places/{place_id}/details": + get: + summary: Retrieves details for a specific place + tags: + - Details + parameters: + - name: place_id + in: path + description: Place ID + required: true + schema: + type: integer + responses: + '200': + description: details found + "/places": + get: + summary: Retrieves a list of places + tags: + - Places + parameters: + - name: user_id + in: query + description: User ID + schema: + type: string + responses: + '200': + description: places found + content: + application/json: + schema: + type: array + items: + properties: + city: + name: + type: string + name: + type: string + image_url: + type: string + description: + type: string + "/places/{id}": + get: + summary: Retrieves a place + tags: + - Places + parameters: + - name: id + in: path + description: Place ID + required: true + schema: + type: string + responses: + '200': + description: place found + "/users/{user_id}/places": + post: + summary: Creates a place + tags: + - Places + parameters: + - name: user_id + in: path + description: User ID + required: true + schema: + type: string + responses: + '400': + description: invalid request + requestBody: + content: + application/json: + schema: + type: object + properties: + place: + type: object + properties: + city_id: + type: integer + name: + type: string + image_url: + type: string + description: + type: string + required: + - city_id + - name + - image_url + - description + details: + type: object + properties: + place_type: + type: string + bedrooms: + type: integer + beds: + type: integer + bathrooms: + type: integer + property_type: + type: string + price: + type: integer + required: + - place_type + - bedrooms + - beds + - bathrooms + - property_type + - price + required: + - place + - details + "/users/{user_id}/places/{id}": + put: + summary: Updates a place + tags: + - Places + parameters: + - name: user_id + in: path + description: User ID + required: true + schema: + type: string + - name: id + in: path + description: Place ID + required: true + schema: + type: string + responses: + '200': + description: place updated + '404': + description: invalid request + requestBody: + content: + application/json: + schema: + type: object + properties: + place: + type: object + properties: + city_id: + type: integer + name: + type: string + image_url: + type: string + description: + type: string + required: + - city_id + - name + - image_url + - description + details: + type: object + properties: + place_type: + type: string + bedrooms: + type: integer + beds: + type: integer + bathrooms: + type: integer + property_type: + type: string + price: + type: integer + required: + - place_type + - bedrooms + - beds + - bathrooms + - property_type + - price + required: + - place + - details + delete: + summary: Deletes a place + tags: + - Places + parameters: + - name: user_id + in: path + description: User ID + required: true + schema: + type: integer + - name: id + in: path + description: Place ID + required: true + schema: + type: string + responses: + '204': + description: place deleted + '404': + description: place not found + "/users/{user_id}/reservations": + get: + summary: Retrieves a list of reservations + tags: + - Reservations + parameters: + - name: user_id + in: path + description: User ID + required: true + schema: + type: integer + responses: + '200': + description: reservations found + content: + application/json: + schema: + type: array + items: + properties: + place: + type: object + properties: + name: + type: string + image_url: + type: string + description: + type: string + city: + type: object + properties: + name: + type: string + post: + summary: Creates a reservation + tags: + - Reservations + parameters: + - name: user_id + in: path + description: User ID + required: true + schema: + type: integer + responses: + '200': + description: reservation created + '422': + description: invalid request + requestBody: + content: + application/json: + schema: + type: object + properties: + place_id: + type: integer + schedule_date: + type: string + format: date + required: + - place_id + - schedule_date + "/users/{user_id}/reservations/{id}": + get: + summary: Retrieves a reservation + tags: + - Reservations + parameters: + - name: user_id + in: path + description: User ID + required: true + schema: + type: integer + - name: id + in: path + description: Reservation ID + required: true + schema: + type: integer + responses: + '200': + description: reservation found + put: + summary: Updates a reservation + tags: + - Reservations + parameters: + - name: user_id + in: path + description: User ID + required: true + schema: + type: integer + - name: id + in: path + description: Reservation ID + required: true + schema: + type: integer + responses: + '200': + description: reservation updated + '404': + description: invalid request + requestBody: + content: + application/json: + schema: + type: object + properties: + place_id: + type: integer + schedule_date: + type: string + format: date + delete: + summary: Deletes a reservation + tags: + - Reservations + parameters: + - name: user_id + in: path + description: User ID + required: true + schema: + type: integer + - name: id + in: path + description: Reservation ID + required: true + schema: + type: integer + responses: + '204': + description: reservation deleted + '404': + description: reservation not found + "/signup": + post: + summary: Create a new user + tags: + - Users + parameters: [] + responses: + '200': + description: user created + '422': + description: invalid request + requestBody: + content: + application/json: + schema: + type: object + properties: + user: + type: object + properties: + username: + type: string + email: + type: string + password: + type: string + required: + - username + - email + - password + required: + - user +servers: +- url: https://renteaze-d1cc8b293660.herokuapp.com diff --git a/tmp/.keep b/tmp/.keep new file mode 100644 index 0000000..e69de29 diff --git a/tmp/pids/.keep b/tmp/pids/.keep new file mode 100644 index 0000000..e69de29 diff --git a/tmp/storage/.keep b/tmp/storage/.keep new file mode 100644 index 0000000..e69de29 diff --git a/vendor/.keep b/vendor/.keep new file mode 100644 index 0000000..e69de29