├── .bundler-audit.yml ├── .dockerignore ├── .env.example ├── .env.test ├── .github ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── ci.yml ├── .gitignore ├── .rspec ├── .rubocop.yml ├── .ruby-version ├── Brewfile ├── Dockerfile ├── Gemfile ├── Gemfile.lock ├── Procfile ├── README.md ├── Rakefile ├── app.json ├── app ├── controllers │ ├── application_controller.rb │ ├── concerns │ │ ├── .keep │ │ └── authenticable_user.rb │ ├── graphql_controller.rb │ └── uploads_controller.rb ├── forms │ ├── application_form.rb │ ├── update_user_form.rb │ └── update_user_password_form.rb ├── graphql │ ├── application_schema.rb │ ├── concerns │ │ ├── authenticable_graphql_user.rb │ │ ├── execution_error_responder.rb │ │ ├── skip_authentication.rb │ │ └── triggerable_events.rb │ ├── loaders │ │ ├── association_loader.rb │ │ └── record_loader.rb │ ├── mutations │ │ ├── base_mutation.rb │ │ ├── confirm_user.rb │ │ ├── omniauth_sign_in_or_sign_up.rb │ │ ├── presign_data.rb │ │ ├── request_password_recovery.rb │ │ ├── sign_in.rb │ │ ├── sign_out.rb │ │ ├── sign_up.rb │ │ ├── update_password.rb │ │ ├── update_token.rb │ │ └── update_user.rb │ ├── resolvers │ │ ├── activities.rb │ │ ├── base.rb │ │ ├── current_user.rb │ │ └── public_activities.rb │ └── types │ │ ├── activity_event_type.rb │ │ ├── activity_type.rb │ │ ├── base_argument.rb │ │ ├── base_connection.rb │ │ ├── base_edge.rb │ │ ├── base_enum.rb │ │ ├── base_field.rb │ │ ├── base_input_object.rb │ │ ├── base_interface.rb │ │ ├── base_object.rb │ │ ├── base_scalar.rb │ │ ├── base_union.rb │ │ ├── confirm_user_input.rb │ │ ├── current_user_type.rb │ │ ├── image_uploader_metadata_type.rb │ │ ├── image_uploader_type.rb │ │ ├── mutation_type.rb │ │ ├── node_type.rb │ │ ├── omniauth_input.rb │ │ ├── payloads │ │ ├── confirm_user_payload.rb │ │ ├── presign_data_payload.rb │ │ ├── request_password_recovery_payload.rb │ │ ├── sign_in_payload.rb │ │ ├── sign_out_payload.rb │ │ ├── sign_up_payload.rb │ │ ├── update_password_payload.rb │ │ ├── update_token_payload.rb │ │ └── update_user_payload.rb │ │ ├── presign_data_input.rb │ │ ├── presign_field_type.rb │ │ ├── presign_type.rb │ │ ├── public_activity_type.rb │ │ ├── query_type.rb │ │ ├── request_password_recovery_input.rb │ │ ├── sign_in_input.rb │ │ ├── sign_out_input.rb │ │ ├── sign_up_input.rb │ │ ├── update_password_input.rb │ │ ├── update_user_input.rb │ │ └── user_type.rb ├── interactors │ ├── authenticate_by_email_and_password.rb │ ├── authenticate_by_google_auth_code.rb │ ├── concerns │ │ ├── authenticable_interactor.rb │ │ └── transactional_interactor.rb │ ├── confirm_user.rb │ ├── create_access_token.rb │ ├── create_possession_token.rb │ ├── create_refresh_token.rb │ ├── create_user.rb │ ├── create_user_activity.rb │ ├── find_refresh_token.rb │ ├── omniauth │ │ └── google │ │ │ ├── build_auth_client.rb │ │ │ ├── exchange_auth_code.rb │ │ │ ├── fetch_user_info.rb │ │ │ └── find_or_create_user.rb │ ├── omniauth_authenticate_user.rb │ ├── omniauth_sign_in_or_sign_up.rb │ ├── prepare_presign_image.rb │ ├── request_password_reset.rb │ ├── signin_user.rb │ ├── signout_user.rb │ ├── signup_user.rb │ ├── update_existing_refresh_token.rb │ ├── update_password.rb │ ├── update_password │ │ ├── find_user_by_token.rb │ │ └── update_user_password.rb │ ├── update_token_pair.rb │ └── update_user.rb ├── jobs │ ├── application_job.rb │ └── register_activity_job.rb ├── mailers │ └── application_mailer.rb ├── models │ ├── activity.rb │ ├── application_record.rb │ ├── concerns │ │ └── .keep │ ├── jwt_token.rb │ ├── possession_token.rb │ ├── refresh_token.rb │ ├── trigger_event.rb │ └── user.rb ├── policies │ ├── activity_policy.rb │ └── application_policy.rb ├── query_objects │ ├── base_filtered_query.rb │ └── filtered_activities_query.rb ├── storages │ └── local_storage.rb ├── uploaders │ └── image_uploader.rb ├── validators │ ├── existing_password_validator.rb │ └── expiration_validator.rb └── views │ ├── application_mailer │ ├── confirm_user.html.erb │ ├── password_recovery.html.erb │ └── password_recovery.text.erb │ └── layouts │ ├── mailer.html.erb │ └── mailer.text.erb ├── bin ├── brakeman ├── bundle-audit ├── bundler-audit ├── docker-entrypoint ├── docker-quality ├── docker-server ├── docker-setup ├── docker-sync ├── docker-tests ├── quality ├── rails ├── rake ├── rspec ├── rubocop ├── server ├── setup ├── spring ├── tests └── wait-for ├── client_secrets.json ├── config.ru ├── config ├── application.rb ├── boot.rb ├── cable.yml ├── credentials.yml.enc ├── database.yml ├── environment.rb ├── environments │ ├── development.rb │ ├── production.rb │ └── test.rb ├── initializers │ ├── action_mailer.rb │ ├── application_controller_renderer.rb │ ├── backtrace_silencers.rb │ ├── cors.rb │ ├── events.rb │ ├── filter_parameter_logging.rb │ ├── health_check.rb │ ├── inflections.rb │ ├── locales.rb │ ├── mime_types.rb │ ├── rack_deflater.rb │ ├── session_store.rb │ ├── shrine.rb │ ├── sidekiq.rb │ ├── sidekiq_web.rb │ ├── strong_migrations.rb │ └── wrap_parameters.rb ├── locales │ ├── en.yml │ ├── models │ │ └── update_user_password_form │ │ │ └── en.yml │ └── password_recovery.en.yml ├── puma.rb ├── routes.rb ├── sidekiq.yml ├── spring.rb └── storage.yml ├── db ├── migrate │ ├── 20200210115945_create_users.rb │ ├── 20200519104937_create_refresh_tokens.rb │ ├── 20200528082200_add_jti_to_refresh_tokens.rb │ ├── 20200602140429_remove_client_uid_from_refresh_tokens.rb │ ├── 20200604082036_add_password_reset_token_to_users.rb │ ├── 20200609122433_create_activities.rb │ ├── 20200617151148_add_avatar_to_users.rb │ ├── 20210604132857_add_confirmed_at_to_users.rb │ ├── 20210604145805_create_possession_tokens.rb │ ├── 20230523063638_add_original_token_to_refresh_tokens.rb │ ├── 20230523063747_add_foreign_key_to_original_token_to_refresh_tokens.rb │ └── 20230523065737_add_uniq_index_to_token_on_refresh_tokens.rb ├── schema.rb └── seeds.rb ├── docker-compose.linux.yml ├── docker-compose.osx.yml ├── docker-compose.yml ├── docker-sync.yml ├── lib └── tasks │ └── .keep ├── log └── .keep ├── public └── robots.txt ├── spec ├── acceptance │ ├── authentication_user_spec.rb │ └── image_uploading_spec.rb ├── factories │ ├── access_tokens.rb │ ├── activities.rb │ ├── dummy │ │ └── jwt_token.rb │ ├── possession_tokens.rb │ ├── refresh_tokens.rb │ ├── sequences.rb │ └── users.rb ├── fixtures │ ├── files │ │ ├── fake_image.png │ │ └── test.txt │ ├── images │ │ └── avatar.jpg │ └── json │ │ └── acceptance │ │ ├── current_user.json │ │ ├── graphql │ │ ├── confirm_user.json │ │ ├── first_page_query_type_activities.json │ │ ├── mutations │ │ │ ├── update_token_existing.json │ │ │ ├── update_token_invalid.json │ │ │ └── update_token_valid.json │ │ ├── presign_data.json │ │ ├── presign_data_wrong.json │ │ ├── query_type_me.json │ │ ├── query_type_me_unauthorized.json │ │ ├── query_type_me_with_activities.json │ │ ├── request_password_recovery.json │ │ ├── request_password_recovery_wrong.json │ │ ├── second_page_query_type_activities.json │ │ ├── sign_in.json │ │ ├── sign_in_with_google.json │ │ ├── sign_in_wrong.json │ │ ├── sign_up.json │ │ ├── sign_up_wrong.json │ │ ├── update_password.json │ │ ├── update_password_expired.json │ │ ├── update_password_wrong.json │ │ ├── update_token_failed.json │ │ └── update_user.json │ │ ├── not_user.json │ │ └── sign_out │ │ └── success.json ├── graphql │ ├── mutations │ │ ├── confirm_user_spec.rb │ │ ├── omniauth_sign_in_or_sign_up_spec.rb │ │ ├── presign_data_spec.rb │ │ ├── request_password_recovery_spec.rb │ │ ├── sign_in_spec.rb │ │ ├── sign_out_spec.rb │ │ ├── sign_up_spec.rb │ │ ├── update_password_spec.rb │ │ ├── update_token_existing_spec.rb │ │ ├── update_token_invalid_spec.rb │ │ ├── update_token_not_unique_spec.rb │ │ ├── update_token_valid_spec.rb │ │ └── update_user_spec.rb │ └── types │ │ ├── activity_type_n_plus_one_spec.rb │ │ ├── query_type_activity_spec.rb │ │ └── query_type_me_spec.rb ├── interactors │ ├── authenticate_by_email_and_password_spec.rb │ ├── authenticate_by_google_auth_code_spec.rb │ ├── confirm_user_spec.rb │ ├── create_access_token_spec.rb │ ├── create_possession_token_spec.rb │ ├── create_refresh_token_spec.rb │ ├── create_user_activity_spec.rb │ ├── create_user_spec.rb │ ├── find_refresh_token_spec.rb │ ├── omniauth │ │ └── google │ │ │ ├── build_auth_client_spec.rb │ │ │ ├── exchange_auth_code_spec.rb │ │ │ ├── fetch_user_info_spec.rb │ │ │ └── find_or_create_user_spec.rb │ ├── omniauth_authenticate_user_spec.rb │ ├── prepare_presign_image_spec.rb │ ├── request_password_reset_spec.rb │ ├── signin_user_spec.rb │ ├── signout_user_spec.rb │ ├── signup_user_spec.rb │ ├── update_existing_refresh_token_spec.rb │ ├── update_password_spec.rb │ ├── update_token_pair_spec.rb │ └── update_user_spec.rb ├── jobs │ └── register_activity_job_spec.rb ├── mailers │ ├── application_mailer_spec.rb │ └── previews │ │ └── application_mailer_preview.rb ├── policies │ └── activity_policy_spec.rb ├── query_objects │ └── filtered_activities_query_spec.rb ├── rails_helper.rb ├── spec_helper.rb ├── support │ ├── active_job.rb │ ├── database_cleaner.rb │ ├── factory_bot.rb │ ├── matchers │ │ └── have_jwt_token_payload.rb │ ├── n_plus_one_control.rb │ ├── shared_contexts │ │ ├── when_time_is_frozen.rb │ │ ├── with_interactor.rb │ │ ├── with_mail_delivery_stubbed.rb │ │ └── with_stubbed_organizer.rb │ └── shared_examples │ │ ├── activity_source.rb │ │ ├── failed_interactor.rb │ │ ├── full_graphql_request.rb │ │ ├── graphql_request.rb │ │ ├── performs_constant_number_of_queries_request.rb │ │ └── success_interactor.rb ├── uploaders │ └── image_uploader_spec.rb └── validators │ ├── existing_password_validator_spec.rb │ └── expiration_validator_spec.rb ├── storage └── .keep ├── tmp └── .keep └── vendor └── .keep /.bundler-audit.yml: -------------------------------------------------------------------------------- 1 | --- 2 | ignore: 3 | - CVE-2022-22577 4 | - CVE-2022-27777 5 | - CVE-2022-32224 6 | - CVE-2022-32511 7 | - CVE-2022-29181 8 | - CVE-2022-30123 9 | - CVE-2022-30122 10 | - CVE-2022-32209 11 | - CVE-2022-31163 12 | - GHSA-cgx6-hpwq-fhv5 13 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | # Ignore files not needed when building a Docker image of this project 2 | 3 | # Ignore environment file since there are could be some sensitive credentials 4 | .env 5 | 6 | # Ignore the temporary files: 7 | /tmp/* 8 | /log/*.log 9 | 10 | # Ignore the gems installed by bundler, as they should be installed from zero 11 | # by the Docker image building process: 12 | /vendor/bundle 13 | .bundle 14 | 15 | # Ignore shell & console artifacts, such as bash, byebug and pry history logs: 16 | .bash_history 17 | .byebug_hist 18 | .pry_history 19 | 20 | # Ignore the docker-compose project files: 21 | docker-compose.yml 22 | 23 | # To avoid including the project's dependency cache in Docker's build context 24 | .semaphore-cache -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | # CORS hostnames based on https://github.com/cyu/rack-cors 2 | CORS_ORIGINS=127.0.0.1:5000,localhost:5000,lvh.me:5000 3 | 4 | # Session store configuration 5 | SESSION_STORE_KEY=app_session 6 | 7 | # Exclude gems that are part of the specified named group 8 | BUNDLE_WITHOUT= 9 | 10 | # Name of docker image 11 | IMAGE_NAME=rails_base_graphql_api 12 | 13 | # Allow connect to remote database (in separate container) 14 | DATABASE_CLEANER_ALLOW_REMOTE_DATABASE_URL=true 15 | 16 | AUTH_SECRET_TOKEN=big_secret_token 17 | 18 | REDIS_URL=redis://redis:6379/1 19 | 20 | # AWS S3 Configuration 21 | S3_BUCKET_NAME= 22 | S3_BUCKET_REGION= 23 | S3_ACCESS_KEY_ID= 24 | S3_SECRET_ACCESS_KEY= 25 | 26 | # Mailer Configuration 27 | SENDGRID_USERNAME=app1234@gmail.com 28 | SENDGRID_PASSWORD=qwerty 29 | MAILER_SENDER_ADDRESS=noreply@example.com 30 | PASSWORD_RECOVERY_LINK_TEMPLATE="http://lvh.me:5000/password_reset?token=%{password_reset_token}" 31 | CONFIRM_USER_LINK_TEMPLATE="http://lvh.me:5000/confirm_user?token=%{token_value}" 32 | 33 | # Hostname for URL helpers 34 | HOST=localhost:3000 35 | 36 | # Oauth 37 | GOOGLE_CLIENT_ID= 38 | GOOGLE_CLIENT_SECRET= 39 | 40 | # Token length 41 | CONFIRMATION_TOKEN_LENGTH=40 42 | -------------------------------------------------------------------------------- /.env.test: -------------------------------------------------------------------------------- 1 | # CORS hostnames based on https://github.com/cyu/rack-cors 2 | CORS_ORIGINS=127.0.0.1:5000,localhost:5000,lvh.me:5000 3 | 4 | # Exclude gems that are part of the specified named group 5 | BUNDLE_WITHOUT= 6 | 7 | # Name of docker image 8 | IMAGE_NAME=rails_base_graphql_api 9 | 10 | # Allow connect to remote database (in separate container) 11 | DATABASE_CLEANER_ALLOW_REMOTE_DATABASE_URL=true 12 | 13 | AUTH_SECRET_TOKEN=big_secret_token 14 | 15 | REDIS_URL=redis://redis:6379/1 16 | 17 | # AWS S3 Configuration 18 | S3_BUCKET_NAME= 19 | S3_BUCKET_REGION= 20 | S3_ACCESS_KEY_ID= 21 | S3_SECRET_ACCESS_KEY= 22 | 23 | # Mailer Configuration 24 | SENDGRID_USERNAME=app1234@gmail.com 25 | SENDGRID_PASSWORD=qwerty 26 | MAILER_SENDER_ADDRESS=noreply@example.com 27 | PASSWORD_RECOVERY_LINK_TEMPLATE="http://lvh.me:5000/password_reset?token=%{password_reset_token}" 28 | 29 | # Hostname for URL helpers 30 | HOST=localhost:3000 31 | 32 | # Oauth 33 | GOOGLE_CLIENT_ID=google_client_id 34 | GOOGLE_CLIENT_SECRET=google_client_secret 35 | GOOGLE_PROJECT_ID=google_project_id 36 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Summary 2 | 3 | A brief description of the pull request. 4 | 5 | ### How it works 6 | 7 | Screenshots/screencasts of the pull request introduced functionality. 8 | 9 | ### Test plan 10 | 11 | List of steps to manually test introduced functionality: 12 | 13 | * Open GraphiQL App 14 | * Make request using schema: 15 | ``` 16 | query { 17 | me: { 18 | id 19 | name 20 | } 21 | } 22 | ``` 23 | * ... 24 | 25 | ### Review notes 26 | 27 | While reviewing pull-request (especially when it's your pull-request), 28 | please make sure that: 29 | 30 | - you understand what problem is solved by PR and how is it solved 31 | - new tests are in place, no redundant tests 32 | - DB schema changes reflect new migrations 33 | - newly introduced DB fields have indexes and constraints 34 | - there are no missed files (migrations, view templates) 35 | - required ENV variables added and described in `.env.example` and added to Heroku 36 | - associated Heroku review app works correctly with introduced changes 37 | 38 | ### Deploy notes 39 | 40 | Notes regarding deployment the contained body of work. 41 | These should note any db migrations, ENV variables, services, scripts, etc. 42 | 43 | ### References 44 | * Resolves #### Issue 45 | * [GitHub Pull Request ####](https://github.com/fs/rails-base-graphql-api/pull/####) 46 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | pull_request: 4 | push: 5 | branches: 6 | - 'master' 7 | 8 | jobs: 9 | ci: 10 | runs-on: ubuntu-latest 11 | env: 12 | DATABASE_URL: postgres://postgres:postgres@localhost:5432 13 | REDIS_URL: redis://localhost:6379/0 14 | RAILS_ENV: test 15 | services: 16 | postgres: 17 | image: postgres 18 | ports: ['5432:5432'] 19 | env: 20 | POSTGRES_PASSWORD: postgres 21 | options: >- 22 | --health-cmd pg_isready 23 | --health-interval 10s 24 | --health-timeout 5s 25 | --health-retries 5 26 | redis: 27 | image: redis 28 | ports: ['6379:6379'] 29 | options: --entrypoint redis-server 30 | steps: 31 | - name: Checkout code 32 | uses: actions/checkout@v2 33 | 34 | - name: Setup Ruby 35 | uses: ruby/setup-ruby@v1 36 | with: 37 | bundler-cache: true 38 | 39 | - name: Run quality checks 40 | run: bin/quality 41 | 42 | - name: Setup db 43 | run: bin/rails db:setup 44 | 45 | - name: Run tests 46 | run: bin/tests 47 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files for more about ignoring files. 2 | # 3 | # If you find yourself ignoring temporary files generated by your text editor 4 | # or operating system, you probably want to add a global ignore instead: 5 | # git config --global core.excludesfile '~/.gitignore_global' 6 | 7 | # Ignore bundler config. 8 | /.bundle 9 | 10 | # Ignore all logfiles and tempfiles. 11 | /log/* 12 | /tmp/* 13 | !/log/.keep 14 | !/tmp/.keep 15 | /coverage/* 16 | 17 | # Ignore uploaded files in development. 18 | /storage/* 19 | /public/uploads/* 20 | !/storage/.keep 21 | .byebug_history 22 | 23 | # Ignore master key for decrypting credentials and more. 24 | /config/master.key 25 | 26 | .env 27 | .docker-sync/* 28 | docker-compose.override.yml 29 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --require spec_helper 2 | -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | 3.2.2 2 | -------------------------------------------------------------------------------- /Brewfile: -------------------------------------------------------------------------------- 1 | brew "postgres" 2 | brew "redis" 3 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | ###################### 2 | # Stage: Builder 3 | FROM ruby:3.2.2-alpine as Builder 4 | 5 | ARG BUNDLER_VERSION 6 | 7 | RUN apk add --update --no-cache \ 8 | build-base \ 9 | gcompat \ 10 | postgresql-dev \ 11 | libpq-dev \ 12 | git \ 13 | imagemagick \ 14 | tzdata 15 | 16 | # Remove bundle config if exist 17 | RUN rm -f .bundle/config 18 | 19 | RUN gem install bundler:$BUNDLER_VERSION 20 | 21 | WORKDIR /app 22 | 23 | # Install gems 24 | ARG BUNDLE_WITHOUT 25 | ENV BUNDLE_WITHOUT ${BUNDLE_WITHOUT} 26 | 27 | RUN bundle config set without ${BUNDLE_WITHOUT} 28 | 29 | COPY . /app/ 30 | RUN bundle install -j4 --retry 3 \ 31 | # Remove unneeded files (cached *.gem, *.o, *.c) 32 | && rm -rf /usr/local/bundle/cache/*.gem \ 33 | && find /usr/local/bundle/gems/ -name "*.c" -delete \ 34 | && find /usr/local/bundle/gems/ -name "*.o" -delete 35 | 36 | # Remove folders not needed in resulting image 37 | ARG FOLDERS_TO_REMOVE 38 | RUN rm -rf $FOLDERS_TO_REMOVE 39 | 40 | ############################### 41 | # Stage Final 42 | FROM ruby:3.2.2-alpine as Final 43 | 44 | # Add Alpine packages 45 | RUN apk add --update --no-cache \ 46 | build-base \ 47 | gcompat \ 48 | postgresql-client \ 49 | libpq-dev \ 50 | imagemagick \ 51 | tzdata \ 52 | file \ 53 | git 54 | 55 | # Copy app with gems from former build stage 56 | COPY --from=Builder /usr/local/bundle/ /usr/local/bundle/ 57 | COPY --from=Builder /app/ /app/ 58 | 59 | WORKDIR /app 60 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | ruby File.read(".ruby-version").strip 4 | 5 | # the most important stuff 6 | gem "pg" 7 | gem "rails", "~> 7.0.0" 8 | 9 | # all other gems 10 | gem "action_policy-graphql" 11 | gem "aws-sdk-s3" 12 | gem "bcrypt" 13 | gem "bootsnap", require: false 14 | gem "enumerize" 15 | gem "google-api-client" 16 | gem "graphql" 17 | gem "graphql-batch" 18 | gem "graphql-persisted_queries" 19 | gem "graphql-rails_logger" 20 | gem "health_check" 21 | gem "interactor" 22 | gem "jwt" 23 | gem "newrelic_rpm" 24 | gem "open-uri" 25 | gem "puma" 26 | gem "rack-cors" 27 | gem "shrine" 28 | gem "sidekiq" 29 | gem "strong_migrations" 30 | 31 | group :development do 32 | gem "letter_opener" 33 | gem "listen" 34 | gem "spring" 35 | gem "spring-watcher-listen" 36 | end 37 | 38 | group :development, :test do 39 | gem "brakeman" 40 | gem "bundler-audit" 41 | gem "byebug" 42 | gem "dotenv-rails" 43 | gem "factory_bot_rails" 44 | gem "ffaker" 45 | gem "rspec-rails" 46 | gem "rubocop", require: false 47 | gem "rubocop-graphql", require: false 48 | gem "rubocop-rails", require: false 49 | gem "rubocop-rspec", require: false 50 | end 51 | 52 | group :test do 53 | gem "database_cleaner-active_record" 54 | gem "email_spec" 55 | gem "n_plus_one_control" 56 | gem "simplecov", require: false 57 | end 58 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: bundle exec puma 2 | worker: bundle exec sidekiq 3 | release: bundle exec rake db:migrate 4 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # Add your own tasks in files placed in lib/tasks ending in .rake, 2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 3 | 4 | require_relative "config/application" 5 | 6 | Rails.application.load_tasks 7 | -------------------------------------------------------------------------------- /app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rails_base_graphql_api", 3 | "env": { 4 | "AUTH_SECRET_TOKEN": { 5 | "required": true 6 | }, 7 | "CORS_ORIGINS": { 8 | "required": true 9 | }, 10 | "LANG": { 11 | "required": true 12 | }, 13 | "MAILER_SENDER_ADDRESS": { 14 | "required": true 15 | }, 16 | "RACK_ENV": { 17 | "required": true 18 | }, 19 | "RAILS_ENV": { 20 | "required": true 21 | }, 22 | "RAILS_LOG_TO_STDOUT": { 23 | "required": true 24 | }, 25 | "RAILS_SERVE_STATIC_FILES": { 26 | "required": true 27 | }, 28 | "SECRET_KEY_BASE": { 29 | "required": true 30 | } 31 | }, 32 | "formation": { 33 | "web": { 34 | "quantity": 1, 35 | "size": "Free" 36 | }, 37 | "worker": { 38 | "quantity": 1, 39 | "size": "Free" 40 | } 41 | }, 42 | "addons": ["heroku-postgresql", "heroku-redis"], 43 | "buildpacks": [ 44 | { 45 | "url": "heroku/ruby" 46 | } 47 | ] 48 | } 49 | -------------------------------------------------------------------------------- /app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::API 2 | include AuthenticableUser 3 | include ExecutionErrorResponder 4 | end 5 | -------------------------------------------------------------------------------- /app/controllers/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fs/rails-base-graphql-api/dc1f74ea2ffdb4f8632ba627dc85df216bc332e3/app/controllers/concerns/.keep -------------------------------------------------------------------------------- /app/controllers/concerns/authenticable_user.rb: -------------------------------------------------------------------------------- 1 | module AuthenticableUser 2 | def current_user 3 | @current_user ||= User.find_by(id: jwt_token.sub) if valid_to_authenticate? 4 | end 5 | 6 | private 7 | 8 | def valid_to_authenticate? 9 | token && jwt_token.valid? && jwt_token.access? && active_refresh_token? 10 | end 11 | 12 | def active_refresh_token? 13 | RefreshToken.active.exists?(jti: jwt_token.jti) 14 | end 15 | 16 | def jwt_token 17 | @jwt_token ||= JWTToken.new(token) 18 | end 19 | 20 | def token 21 | @token ||= request.headers["Authorization"].to_s.match(/Bearer (.*)/).to_a.last 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /app/controllers/graphql_controller.rb: -------------------------------------------------------------------------------- 1 | class GraphqlController < ApplicationController 2 | def execute 3 | trigger_events if execution_success? 4 | 5 | render json: execute_query 6 | rescue StandardError => e 7 | raise e unless Rails.env.development? 8 | 9 | handle_error_in_development e 10 | end 11 | 12 | private 13 | 14 | def execute_query 15 | @execute_query ||= ApplicationSchema.execute(params[:query], **query_options) 16 | end 17 | 18 | def query_options 19 | options = { 20 | variables: ensure_hash(params[:variables]), 21 | context: execution_context.deep_symbolize_keys, 22 | operation_name: params[:operationName] 23 | } 24 | options.merge!(max_depth: nil, max_complexity: nil) if introspection? 25 | options 26 | end 27 | 28 | def execution_context 29 | { 30 | current_user: current_user, 31 | token: token, 32 | extensions: ensure_hash(params[:extensions]) 33 | } 34 | end 35 | 36 | def introspection? 37 | params[:query].match?(/IntrospectionQuery/) 38 | end 39 | 40 | def trigger_events 41 | return if execute_query.context[:trigger_events].blank? 42 | 43 | execute_query.context[:trigger_events].compact_blank.each do |trigger_event| 44 | ActiveSupport::Notifications.instrument trigger_event.event, trigger_event.options 45 | end 46 | end 47 | 48 | def execution_success? 49 | execute_query.to_h["errors"].blank? 50 | end 51 | 52 | def ensure_hash(ambiguous_param) 53 | case ambiguous_param 54 | when String 55 | ambiguous_param.present? ? ensure_hash(JSON.parse(ambiguous_param)) : {} 56 | when Hash, ActionController::Parameters 57 | ambiguous_param 58 | when nil 59 | {} 60 | else 61 | raise ArgumentError, "Unexpected parameter: #{ambiguous_param}" 62 | end 63 | end 64 | 65 | def handle_error_in_development(exception) 66 | logger.error exception.message 67 | logger.error exception.backtrace.join("\n") 68 | 69 | error = { error: { message: exception.message, backtrace: exception.backtrace }, data: {} } 70 | 71 | render json: error, status: :internal_server_error 72 | end 73 | end 74 | -------------------------------------------------------------------------------- /app/controllers/uploads_controller.rb: -------------------------------------------------------------------------------- 1 | class UploadsController < ApplicationController 2 | def image 3 | ImageUploader.upload_response(:cache, request.env) 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /app/forms/application_form.rb: -------------------------------------------------------------------------------- 1 | class ApplicationForm 2 | include ActiveModel::Model 3 | 4 | attr_reader :model 5 | 6 | def initialize(model = nil) 7 | @model = model 8 | assign_model_attributes if model 9 | end 10 | 11 | def assign_attributes(attrs) 12 | attrs.each do |key, value| 13 | public_send "#{key}=", value 14 | end 15 | self 16 | end 17 | 18 | def model_attributes 19 | attributes.slice(*model_attribute_names).compact 20 | end 21 | 22 | private 23 | 24 | def attributes 25 | attribute_names.index_with { |attribute| public_send(attribute) } 26 | end 27 | 28 | def assign_model_attributes 29 | assign_attributes(model.attributes.symbolize_keys.slice(*model_attribute_names)) 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /app/forms/update_user_form.rb: -------------------------------------------------------------------------------- 1 | class UpdateUserForm < ApplicationForm 2 | USER_ATTRIBUTES = %i[first_name last_name email password avatar].freeze 3 | ATTRIBUTES = (USER_ATTRIBUTES + %i[current_password]).freeze 4 | 5 | attr_accessor(*ATTRIBUTES) 6 | 7 | validates :email, format: { with: URI::MailTo::EMAIL_REGEXP } 8 | validates :current_password, existing_password: true, presence: true, unless: -> { password.blank? } 9 | validates :password, length: { maximum: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED }, 10 | allow_nil: true, allow_blank: true 11 | 12 | def attribute_names 13 | @attribute_names ||= ATTRIBUTES 14 | end 15 | 16 | def model_attribute_names 17 | @model_attribute_names ||= USER_ATTRIBUTES 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /app/forms/update_user_password_form.rb: -------------------------------------------------------------------------------- 1 | class UpdateUserPasswordForm < ApplicationForm 2 | ATTRIBUTES = %i[password password_reset_sent_at].freeze 3 | 4 | attr_accessor(*ATTRIBUTES) 5 | 6 | validates :password, length: { maximum: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED }, presence: true 7 | validates :password_reset_sent_at, expiration: { timeout: 15.minutes }, presence: true 8 | 9 | def attribute_names 10 | @attribute_names ||= ATTRIBUTES 11 | end 12 | 13 | def model_attribute_names 14 | @model_attribute_names ||= attribute_names 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /app/graphql/application_schema.rb: -------------------------------------------------------------------------------- 1 | require "graphql/batch" 2 | 3 | class ApplicationSchema < GraphQL::Schema 4 | mutation(Types::MutationType) 5 | query(Types::QueryType) 6 | 7 | use GraphQL::Batch 8 | use GraphQL::PersistedQueries, 9 | compiled_queries: true, 10 | store: :redis_with_local_cache, 11 | redis_client: -> { RedisClient.new(url: ENV.fetch("REDIS_URL", "redis://localhost:6379/1"), protocol: 2) } 12 | 13 | max_complexity 250 14 | max_depth 10 15 | default_max_page_size 25 16 | 17 | rescue_from(ActiveRecord::RecordNotFound) do |_err, _obj, _args, _ctx, field| 18 | raise GraphQL::ExecutionError.new("#{field.type.unwrap.graphql_name} not found", 19 | extensions: { message: "Not Found", status: 404, code: :not_found }) 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /app/graphql/concerns/authenticable_graphql_user.rb: -------------------------------------------------------------------------------- 1 | module AuthenticableGraphqlUser 2 | extend ActiveSupport::Concern 3 | 4 | private 5 | 6 | def ready?(*) 7 | return true if current_user 8 | 9 | raise_unauthorized_error! 10 | end 11 | 12 | def raise_unauthorized_error! 13 | raise execution_error(error_data: authentication_error) 14 | end 15 | 16 | def authentication_error 17 | { message: "Invalid credentials", status: 401, code: :unauthorized } 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /app/graphql/concerns/execution_error_responder.rb: -------------------------------------------------------------------------------- 1 | module ExecutionErrorResponder 2 | extend ActiveSupport::Concern 3 | 4 | private 5 | 6 | def execution_error(error_data:) 7 | GraphQL::ExecutionError.new( 8 | error_data[:message], 9 | extensions: execution_error_extensions(error_data) 10 | ) 11 | end 12 | 13 | def execution_error_extensions(error_data) 14 | { 15 | detail: error_data[:detail], 16 | status: error_data[:status] || 422, 17 | code: error_data[:code] || :unprocessable_entity 18 | } 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /app/graphql/concerns/skip_authentication.rb: -------------------------------------------------------------------------------- 1 | module SkipAuthentication 2 | extend ActiveSupport::Concern 3 | 4 | def ready?(*) 5 | true 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /app/graphql/concerns/triggerable_events.rb: -------------------------------------------------------------------------------- 1 | module TriggerableEvents 2 | extend ActiveSupport::Concern 3 | 4 | private 5 | 6 | def append_trigger_event(trigger_event) 7 | context[:trigger_events] ||= [] 8 | context[:trigger_events] << trigger_event 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /app/graphql/loaders/association_loader.rb: -------------------------------------------------------------------------------- 1 | module Loaders 2 | class AssociationLoader < GraphQL::Batch::Loader 3 | def self.validate(model, association_name) 4 | new(model, association_name) 5 | nil 6 | end 7 | 8 | def initialize(model, association_name) 9 | super 10 | @model = model 11 | @association_name = association_name 12 | validate 13 | end 14 | 15 | def load(record) 16 | raise TypeError, "#{@model} loader can't load association for #{record.class}" unless record.is_a?(@model) 17 | return Promise.resolve(read_association(record)) if association_loaded?(record) 18 | 19 | super 20 | end 21 | 22 | def cache_key(record) 23 | record.object_id 24 | end 25 | 26 | def perform(records) 27 | preload_association(records) 28 | records.each { |record| fulfill(record, read_association(record)) } 29 | end 30 | 31 | private 32 | 33 | def validate 34 | return if @model.reflect_on_association(@association_name) 35 | 36 | raise ArgumentError, "No association #{@association_name} on #{@model}" 37 | end 38 | 39 | def preload_association(records) 40 | ::ActiveRecord::Associations::Preloader.new.preload(records, @association_name) 41 | end 42 | 43 | def read_association(record) 44 | record.public_send(@association_name) 45 | end 46 | 47 | def association_loaded?(record) 48 | record.association(@association_name).loaded? 49 | end 50 | end 51 | end 52 | -------------------------------------------------------------------------------- /app/graphql/loaders/record_loader.rb: -------------------------------------------------------------------------------- 1 | module Loaders 2 | class RecordLoader < GraphQL::Batch::Loader 3 | def initialize(model) 4 | super() 5 | 6 | @model = model 7 | end 8 | 9 | def perform(ids) 10 | @model.where(id: ids).each { |record| fulfill(record.id, record) } 11 | ids.each { |id| fulfill(id, nil) unless fulfilled?(id) } 12 | end 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /app/graphql/mutations/base_mutation.rb: -------------------------------------------------------------------------------- 1 | module Mutations 2 | class BaseMutation < GraphQL::Schema::Mutation 3 | include AuthenticableGraphqlUser 4 | include ExecutionErrorResponder 5 | 6 | description "Base mutation for all mutations" 7 | 8 | argument_class Types::BaseArgument 9 | field_class Types::BaseField 10 | object_class Types::BaseObject 11 | 12 | private 13 | 14 | def current_user 15 | context[:current_user] 16 | end 17 | 18 | def token 19 | context[:token] 20 | end 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /app/graphql/mutations/confirm_user.rb: -------------------------------------------------------------------------------- 1 | module Mutations 2 | class ConfirmUser < BaseMutation 3 | include SkipAuthentication 4 | 5 | description "Confirm user mutation" 6 | 7 | argument :input, Types::ConfirmUserInput, "Data Input", required: true 8 | 9 | type Types::Payloads::ConfirmUserPayload 10 | 11 | def resolve(input:) 12 | result = ::ConfirmUser.call(value: input.value) 13 | 14 | result.success? ? result : execution_error(error_data: result.error_data) 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /app/graphql/mutations/omniauth_sign_in_or_sign_up.rb: -------------------------------------------------------------------------------- 1 | module Mutations 2 | class OmniauthSignInOrSignUp < BaseMutation 3 | include SkipAuthentication 4 | 5 | description "Signin with Google OAuth mutation" 6 | 7 | argument :input, Types::OmniauthInput, "Data Input", required: true 8 | 9 | type Types::Payloads::SignInPayload 10 | 11 | def resolve(input:) 12 | signin_user = ::OmniauthSignInOrSignUp.call(input.to_h) 13 | 14 | signin_user.success? ? signin_user : execution_error(error_data: signin_user.error_data) 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /app/graphql/mutations/presign_data.rb: -------------------------------------------------------------------------------- 1 | module Mutations 2 | class PresignData < BaseMutation 3 | description "Presign file data mutation" 4 | 5 | argument :input, Types::PresignDataInput, "Data Input", required: true 6 | 7 | type Types::Payloads::PresignDataPayload 8 | 9 | def resolve(input:) 10 | presign_image = PreparePresignImage.call(input.to_h) 11 | 12 | presign_image.success? ? presign_image : execution_error(error_data: presign_image.error_data) 13 | end 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /app/graphql/mutations/request_password_recovery.rb: -------------------------------------------------------------------------------- 1 | module Mutations 2 | class RequestPasswordRecovery < BaseMutation 3 | include SkipAuthentication 4 | 5 | description "Request reset password flow mutation" 6 | 7 | argument :input, Types::RequestPasswordRecoveryInput, "Data Input", required: true 8 | 9 | type Types::Payloads::RequestPasswordRecoveryPayload 10 | 11 | def resolve(input:) 12 | result = RequestPasswordReset.call(input.to_h) 13 | 14 | result.success? ? success_response : result.error_data 15 | end 16 | 17 | private 18 | 19 | def success_response 20 | { 21 | message: I18n.t("password_recovery.sent.message"), 22 | detail: I18n.t("password_recovery.sent.detail") 23 | } 24 | end 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /app/graphql/mutations/sign_in.rb: -------------------------------------------------------------------------------- 1 | module Mutations 2 | class SignIn < BaseMutation 3 | include SkipAuthentication 4 | 5 | description "Sign in with email mutation" 6 | 7 | argument :input, Types::SignInInput, "Data Input", required: true 8 | 9 | type Types::Payloads::SignInPayload 10 | 11 | def resolve(input:) 12 | signin_user = SigninUser.call(input.to_h) 13 | 14 | signin_user.success? ? signin_user : execution_error(error_data: signin_user.error_data) 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /app/graphql/mutations/sign_out.rb: -------------------------------------------------------------------------------- 1 | module Mutations 2 | class SignOut < BaseMutation 3 | description "Sign out mutation" 4 | 5 | argument :input, Types::SignOutInput, "Data Input", required: true 6 | 7 | type Types::Payloads::SignOutPayload 8 | 9 | def resolve(input:) 10 | SignoutUser.call(token: token, user: current_user, everywhere: input.everywhere) 11 | 12 | { 13 | message: "User signed out successfully" 14 | } 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /app/graphql/mutations/sign_up.rb: -------------------------------------------------------------------------------- 1 | module Mutations 2 | class SignUp < BaseMutation 3 | include SkipAuthentication 4 | 5 | description "Sign up mutation" 6 | 7 | argument :input, Types::SignUpInput, "Data Input", required: true 8 | 9 | type Types::Payloads::SignUpPayload 10 | 11 | def resolve(input:) 12 | signup_user = SignupUser.call(user_params: input.to_h) 13 | 14 | signup_user.success? ? signup_user : execution_error(error_data: signup_user.error_data) 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /app/graphql/mutations/update_password.rb: -------------------------------------------------------------------------------- 1 | module Mutations 2 | class UpdatePassword < BaseMutation 3 | include SkipAuthentication 4 | 5 | description "Update user password mutation" 6 | 7 | argument :input, Types::UpdatePasswordInput, "Data Input", required: true 8 | 9 | type Types::Payloads::UpdatePasswordPayload 10 | 11 | def resolve(input:) 12 | result = ::UpdatePassword.call(input.to_h) 13 | 14 | result.success? ? result : execution_error(error_data: result.error_data) 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /app/graphql/mutations/update_token.rb: -------------------------------------------------------------------------------- 1 | module Mutations 2 | class UpdateToken < BaseMutation 3 | include SkipAuthentication 4 | 5 | description "Update short live access token mutation" 6 | 7 | type Types::Payloads::UpdateTokenPayload 8 | 9 | MAX_RETRIES_COUNT = 5 10 | 11 | def resolve 12 | @retries ||= MAX_RETRIES_COUNT 13 | UpdateTokenPair.call!(token: token) 14 | rescue ActiveRecord::RecordNotUnique, ActiveRecord::RecordNotSaved, Interactor::Failure => _e 15 | prevent_constant_token_refresh 16 | (@retries -= 1).negative? ? raise_unauthorized_error! : retry 17 | end 18 | 19 | private 20 | 21 | def prevent_constant_token_refresh 22 | sleep(rand.seconds) 23 | end 24 | 25 | def raise_unauthorized_error! 26 | raise execution_error(error_data: authentication_error) 27 | end 28 | 29 | def authentication_error 30 | { message: "Invalid credentials", status: 401, code: :unauthorized } 31 | end 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /app/graphql/mutations/update_user.rb: -------------------------------------------------------------------------------- 1 | module Mutations 2 | class UpdateUser < BaseMutation 3 | description "Update user info mutation" 4 | 5 | argument :input, Types::UpdateUserInput, "Data Input", required: true 6 | 7 | type Types::Payloads::UpdateUserPayload 8 | 9 | def resolve(input:) 10 | update_user = ::UpdateUser.call( 11 | user: current_user, user_params: input.to_h 12 | ) 13 | 14 | update_user.success? ? update_user : execution_error(error_data: update_user.error_data) 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /app/graphql/resolvers/activities.rb: -------------------------------------------------------------------------------- 1 | module Resolvers 2 | class Activities < Resolvers::Base 3 | description "Fetch activities" 4 | 5 | argument :events, [Types::ActivityEventType], "Filter by events", required: false 6 | 7 | type Types::ActivityType.connection_type, null: true 8 | 9 | def fetch_data 10 | FilteredActivitiesQuery.new(raw_relation, options).all.to_a 11 | end 12 | 13 | def raw_relation 14 | authorized_scope(Activity.all, with: ::ActivityPolicy) 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /app/graphql/resolvers/base.rb: -------------------------------------------------------------------------------- 1 | module Resolvers 2 | class Base < GraphQL::Schema::Resolver 3 | include ExecutionErrorResponder 4 | include ActionPolicy::GraphQL::Behaviour 5 | include TriggerableEvents 6 | 7 | description "Base resolver" 8 | 9 | argument_class Types::BaseArgument 10 | 11 | def resolve(**options) 12 | @options = options 13 | append_trigger_event(trigger_event) if trigger_event.present? 14 | fetch_data 15 | end 16 | 17 | private 18 | 19 | attr_reader :options 20 | 21 | def fetch_data 22 | raise NotImplementedError 23 | end 24 | 25 | def current_user 26 | context[:current_user] 27 | end 28 | 29 | def trigger_event 30 | end 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /app/graphql/resolvers/current_user.rb: -------------------------------------------------------------------------------- 1 | module Resolvers 2 | class CurrentUser < Resolvers::Base 3 | description "Fetch current user" 4 | 5 | type Types::CurrentUserType, null: true 6 | 7 | def resolve 8 | current_user 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /app/graphql/resolvers/public_activities.rb: -------------------------------------------------------------------------------- 1 | module Resolvers 2 | class PublicActivities < Resolvers::Base 3 | description "Fetch public activities" 4 | 5 | type Types::PublicActivityType.connection_type, null: true 6 | 7 | def fetch_data 8 | Activity.public_events 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /app/graphql/types/activity_event_type.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class ActivityEventType < Types::BaseEnum 3 | description "Data type for Activity Event" 4 | 5 | value "USER_LOGGED_IN", value: "user_logged_in" 6 | value "USER_REGISTERED", value: "user_registered" 7 | value "USER_RESET_PASSWORD", value: "user_reset_password" 8 | value "RESET_PASSWORD_REQUESTED", value: "reset_password_requested" 9 | value "USER_UPDATED", value: "user_updated" 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /app/graphql/types/activity_type.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class ActivityType < Types::BaseObject 3 | description "Data type for Activity" 4 | 5 | field :id, ID, "ID", null: false 6 | 7 | field :body, String, "Body", null: false 8 | field :created_at, GraphQL::Types::ISO8601DateTime, "Created datetime", null: false 9 | field :event, ActivityEventType, "Event type from Enum", null: false 10 | field :title, String, "Title", null: false 11 | field :user, Types::UserType, "Activity initiator", null: false 12 | 13 | def user 14 | Loaders::RecordLoader.for(User).load(object.user_id) 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /app/graphql/types/base_argument.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class BaseArgument < GraphQL::Schema::Argument 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/graphql/types/base_connection.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class BaseConnection < Types::BaseObject 3 | include GraphQL::Types::Relay::ConnectionBehaviors 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /app/graphql/types/base_edge.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class BaseEdge < Types::BaseObject 3 | include GraphQL::Types::Relay::EdgeBehaviors 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /app/graphql/types/base_enum.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class BaseEnum < GraphQL::Schema::Enum 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/graphql/types/base_field.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class BaseField < GraphQL::Schema::Field 3 | argument_class Types::BaseArgument 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /app/graphql/types/base_input_object.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class BaseInputObject < GraphQL::Schema::InputObject 3 | argument_class Types::BaseArgument 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /app/graphql/types/base_interface.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | module BaseInterface 3 | include GraphQL::Schema::Interface 4 | 5 | field_class Types::BaseField 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /app/graphql/types/base_object.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class BaseObject < GraphQL::Schema::Object 3 | include ActionPolicy::GraphQL::Behaviour 4 | 5 | field_class Types::BaseField 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /app/graphql/types/base_scalar.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class BaseScalar < GraphQL::Schema::Scalar 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/graphql/types/base_union.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class BaseUnion < GraphQL::Schema::Union 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/graphql/types/confirm_user_input.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class ConfirmUserInput < Types::BaseInputObject 3 | description "Input object for user confirmation flow" 4 | 5 | argument :value, String, "Token", required: true 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /app/graphql/types/current_user_type.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class CurrentUserType < Types::BaseObject 3 | description "Data type for Current User" 4 | 5 | field :id, ID, "ID", null: false 6 | 7 | field :avatar_url, String, "URL for avatar image", null: true 8 | field :confirmed_at, GraphQL::Types::ISO8601DateTime, "Confirmation datetime", null: true 9 | field :email, String, "Email", null: false 10 | field :first_name, String, "First Name", null: true 11 | field :last_name, String, "Last Name", null: true 12 | 13 | field :activities, resolver: Resolvers::Activities, connection: true, description: "Activities array" 14 | 15 | delegate :avatar, to: :object 16 | delegate :url, to: :avatar, prefix: true, allow_nil: true 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /app/graphql/types/image_uploader_metadata_type.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class ImageUploaderMetadataType < Types::BaseInputObject 3 | description "Data type for file" 4 | 5 | argument :filename, String, "Filename", required: true 6 | argument :mime_type, String, "Filetype", required: true 7 | argument :size, Integer, "Size in bytes", required: true 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /app/graphql/types/image_uploader_type.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class ImageUploaderType < Types::BaseInputObject 3 | description "Data type for file direct upload" 4 | 5 | argument :id, String, "ID", required: true 6 | argument :metadata, Types::ImageUploaderMetadataType, "File metadata", required: true 7 | argument :storage, String, "Storage: cache or store", required: false, default_value: "cache" 8 | 9 | def prepare 10 | to_hash 11 | end 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /app/graphql/types/mutation_type.rb: -------------------------------------------------------------------------------- 1 | # rubocop:disable GraphQL/ExtractType 2 | module Types 3 | class MutationType < Types::BaseObject 4 | description "Mutations" 5 | 6 | field :sign_in, mutation: Mutations::SignIn, description: "Sign in" 7 | field :sign_out, mutation: Mutations::SignOut, description: "Sign out" 8 | field :sign_up, mutation: Mutations::SignUp, description: "Sign up" 9 | 10 | field :update_password, mutation: Mutations::UpdatePassword, description: "Update user password" 11 | field :update_token, mutation: Mutations::UpdateToken, description: "Update short live access token" 12 | field :update_user, mutation: Mutations::UpdateUser, description: "Update user info" 13 | 14 | field :confirm_user, 15 | mutation: Mutations::ConfirmUser, 16 | description: "Confirm user email" 17 | field :omniauth_sign_in_or_sign_up, 18 | mutation: Mutations::OmniauthSignInOrSignUp, 19 | description: "Authenticate with OAuth" 20 | field :request_password_recovery, 21 | mutation: Mutations::RequestPasswordRecovery, 22 | description: "Reset password request" 23 | 24 | field :presign_data, 25 | mutation: Mutations::PresignData, 26 | description: "File presign data for upload" 27 | end 28 | end 29 | # rubocop:enable GraphQL/ExtractType 30 | -------------------------------------------------------------------------------- /app/graphql/types/node_type.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | module NodeType 3 | include Types::BaseInterface 4 | include GraphQL::Types::Relay::NodeBehaviors 5 | 6 | description "An object with an ID" 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /app/graphql/types/omniauth_input.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class OmniauthInput < Types::BaseInputObject 3 | description "Input object for oauth authentication" 4 | 5 | argument :auth_code, String, "OAuth token from provider", required: true 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /app/graphql/types/payloads/confirm_user_payload.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | module Payloads 3 | class ConfirmUserPayload < Types::BaseObject 4 | description "Payload object for user confirmation mutation" 5 | 6 | field :me, Types::CurrentUserType, "Current User", null: false, method: :user 7 | end 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /app/graphql/types/payloads/presign_data_payload.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | module Payloads 3 | class PresignDataPayload < Types::BaseObject 4 | description "Payload object for presign file data mutation" 5 | 6 | field :data, Types::PresignType, "Data", null: false, method: :presign_data 7 | end 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /app/graphql/types/payloads/request_password_recovery_payload.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | module Payloads 3 | class RequestPasswordRecoveryPayload < Types::BaseObject 4 | description "Payload object for request password reset mutation" 5 | 6 | field :detail, String, "Detail", null: false 7 | field :message, String, "Message", null: false 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /app/graphql/types/payloads/sign_in_payload.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | module Payloads 3 | class SignInPayload < Types::BaseObject 4 | description "Payload object for sign in mutation" 5 | 6 | field :access_token, String, "Short live access token", null: false 7 | field :refresh_token, String, "Long live refresh token", null: false 8 | 9 | field :me, Types::CurrentUserType, "Current User", null: true, method: :user 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /app/graphql/types/payloads/sign_out_payload.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | module Payloads 3 | class SignOutPayload < Types::BaseObject 4 | description "Payload object for sign out mutation" 5 | 6 | field :message, String, "Confirmation message", null: false 7 | end 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /app/graphql/types/payloads/sign_up_payload.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | module Payloads 3 | class SignUpPayload < Types::BaseObject 4 | description "Payload object for sign up mutation" 5 | 6 | field :access_token, String, "Short live access token", null: false 7 | field :refresh_token, String, "Long live refresh token", null: false 8 | 9 | field :me, Types::CurrentUserType, "Current User", null: true, method: :user 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /app/graphql/types/payloads/update_password_payload.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | module Payloads 3 | class UpdatePasswordPayload < Types::BaseObject 4 | description "Payload object for update password mutation" 5 | 6 | field :access_token, String, "Short live access token", null: false 7 | field :refresh_token, String, "Long live refresh token", null: false 8 | 9 | field :me, Types::CurrentUserType, "Current User", null: true, method: :user 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /app/graphql/types/payloads/update_token_payload.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | module Payloads 3 | class UpdateTokenPayload < Types::BaseObject 4 | description "Payload object for update token mutation" 5 | 6 | field :access_token, String, "Short live access token", null: false 7 | field :refresh_token, String, "Long live refresh token", null: false 8 | 9 | field :me, Types::CurrentUserType, "Current User", null: true, method: :user 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /app/graphql/types/payloads/update_user_payload.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | module Payloads 3 | class UpdateUserPayload < Types::BaseObject 4 | description "Payload object for update user mutation" 5 | 6 | field :me, Types::CurrentUserType, "Current User", null: false, method: :user 7 | end 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /app/graphql/types/presign_data_input.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class PresignDataInput < Types::BaseInputObject 3 | description "Input object for prepare presigned URL" 4 | 5 | argument :filename, String, "Filename for presign", required: true 6 | argument :type, String, "Filetype", required: true 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /app/graphql/types/presign_field_type.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class PresignFieldType < Types::BaseObject 3 | description "Data type for presign fields" 4 | 5 | field :key, String, "Key", null: false 6 | field :value, String, "Value", null: false 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /app/graphql/types/presign_type.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class PresignType < Types::BaseObject 3 | description "Data type to presign file for upload" 4 | 5 | field :fields, [PresignFieldType], "Metadata fields used as headers on upload to storage", null: false 6 | field :url, String, "URL where to upload file", null: false 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /app/graphql/types/public_activity_type.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class PublicActivityType < Types::BaseObject 3 | description "Data type for Public Activity" 4 | 5 | field :id, ID, "ID", null: false 6 | 7 | field :body, String, "Body", null: false 8 | field :title, String, "Title", null: false 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /app/graphql/types/query_type.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class QueryType < Types::BaseObject 3 | include GraphQL::Types::Relay::HasNodeField 4 | include GraphQL::Types::Relay::HasNodesField 5 | 6 | description "Base query" 7 | 8 | field :me, description: "Current User", resolver: Resolvers::CurrentUser 9 | 10 | field :activities, description: "Activities", resolver: Resolvers::PublicActivities, connection: true 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /app/graphql/types/request_password_recovery_input.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class RequestPasswordRecoveryInput < Types::BaseInputObject 3 | description "Input object for reset password flow" 4 | 5 | argument :email, String, "Email", required: true 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /app/graphql/types/sign_in_input.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class SignInInput < Types::BaseInputObject 3 | description "Input object for sign in" 4 | 5 | argument :email, String, "Email", required: true 6 | argument :password, String, "Password", required: true 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /app/graphql/types/sign_out_input.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class SignOutInput < Types::BaseInputObject 3 | description "Input object for sign out" 4 | 5 | argument :everywhere, Boolean, "If true all sessions will reset", required: false 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /app/graphql/types/sign_up_input.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class SignUpInput < Types::BaseInputObject 3 | description "Input object for sign up" 4 | 5 | argument :avatar, Types::ImageUploaderType, "URL to avatar image", required: false 6 | argument :email, String, "Email", required: true 7 | argument :first_name, String, "First Name", required: false 8 | argument :last_name, String, "Last Name", required: false 9 | argument :password, String, "Password", required: true 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /app/graphql/types/update_password_input.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class UpdatePasswordInput < Types::BaseInputObject 3 | description "Input object for update user password on reset password" 4 | 5 | argument :password, String, "A new password", required: true 6 | argument :reset_token, String, "Password reset token", required: true 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /app/graphql/types/update_user_input.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class UpdateUserInput < Types::BaseInputObject 3 | description "Input object for update user info" 4 | 5 | argument :avatar, Types::ImageUploaderType, "Avatar data", required: false 6 | argument :email, String, "Email", required: false 7 | argument :first_name, String, "First Name", required: false 8 | argument :last_name, String, "Last Name", required: false 9 | 10 | argument :current_password, String, "Password", required: false 11 | argument :password, String, "Password", required: false 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /app/graphql/types/user_type.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class UserType < Types::BaseObject 3 | description "Base user info" 4 | 5 | field :id, ID, "ID", null: false 6 | 7 | field :avatar_url, String, "URL to avatar image", null: true 8 | field :email, String, "Email", null: false 9 | field :first_name, String, "First Name", null: true 10 | field :last_name, String, "Last Name", null: true 11 | 12 | delegate :avatar, to: :object 13 | delegate :url, to: :avatar, prefix: true, allow_nil: true 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /app/interactors/authenticate_by_email_and_password.rb: -------------------------------------------------------------------------------- 1 | class AuthenticateByEmailAndPassword 2 | include Interactor 3 | include AuthenticableInteractor 4 | 5 | delegate :email, :password, to: :context 6 | 7 | def call 8 | raise_unauthorized_error! unless authenticated? 9 | context.user = user 10 | end 11 | 12 | private 13 | 14 | def authenticated? 15 | user&.authenticate(password) 16 | end 17 | 18 | def user 19 | @user ||= User.find_by(email: email) 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /app/interactors/authenticate_by_google_auth_code.rb: -------------------------------------------------------------------------------- 1 | class AuthenticateByGoogleAuthCode 2 | include Interactor::Organizer 3 | 4 | organize Omniauth::Google::BuildAuthClient, 5 | Omniauth::Google::ExchangeAuthCode, 6 | Omniauth::Google::FetchUserInfo, 7 | Omniauth::Google::FindOrCreateUser 8 | end 9 | -------------------------------------------------------------------------------- /app/interactors/concerns/authenticable_interactor.rb: -------------------------------------------------------------------------------- 1 | module AuthenticableInteractor 2 | extend ActiveSupport::Concern 3 | 4 | private 5 | 6 | def raise_unauthorized_error! 7 | context.fail!( 8 | error_data: { 9 | message: "Invalid credentials", 10 | status: 401, 11 | code: :unauthorized 12 | } 13 | ) 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /app/interactors/concerns/transactional_interactor.rb: -------------------------------------------------------------------------------- 1 | module TransactionalInteractor 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | around do |interactor| 6 | ActiveRecord::Base.transaction do 7 | interactor.call(context) 8 | end 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /app/interactors/confirm_user.rb: -------------------------------------------------------------------------------- 1 | class ConfirmUser 2 | include Interactor 3 | 4 | delegate :value, to: :context 5 | 6 | def call 7 | context.fail!(error_data: error_data) if token.blank? 8 | 9 | user.update(confirmed_at: Time.current) 10 | token.destroy 11 | end 12 | 13 | private 14 | 15 | def token 16 | @token ||= PossessionToken.find_by(value: value) 17 | end 18 | 19 | def user 20 | context.user ||= token.user 21 | end 22 | 23 | def error_data 24 | { message: "Invalid value", status: 400, code: :bad_request } 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /app/interactors/create_access_token.rb: -------------------------------------------------------------------------------- 1 | class CreateAccessToken 2 | include Interactor 3 | 4 | ACCESS_TOKEN_TTL = 1.hour 5 | 6 | delegate :user, :jti, to: :context 7 | 8 | def call 9 | context.jti ||= generate_jti 10 | context.access_token = access_token 11 | end 12 | 13 | private 14 | 15 | def access_token 16 | JWT.encode(payload, ENV.fetch("AUTH_SECRET_TOKEN"), "HS256") 17 | end 18 | 19 | def payload 20 | { 21 | sub: user.id, 22 | exp: ACCESS_TOKEN_TTL.from_now.to_i, 23 | jti: jti, 24 | type: "access" 25 | } 26 | end 27 | 28 | def generate_jti 29 | Digest::MD5.hexdigest("#{user.id}-#{Time.current.to_i}") 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /app/interactors/create_possession_token.rb: -------------------------------------------------------------------------------- 1 | class CreatePossessionToken 2 | include Interactor 3 | 4 | delegate :user, to: :context 5 | 6 | def call 7 | context.possession_token = possession_token 8 | end 9 | 10 | private 11 | 12 | def possession_token 13 | PossessionToken.create( 14 | user_id: user.id, 15 | value: generate_value 16 | ) 17 | end 18 | 19 | def generate_value 20 | generated_value = SecureRandom.hex(token_length) 21 | return generated_value unless PossessionToken.exists?(value: generated_value) 22 | 23 | generate_value 24 | end 25 | 26 | def token_length 27 | ENV.fetch("CONFIRMATION_TOKEN_LENGTH", 40).to_i 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /app/interactors/create_refresh_token.rb: -------------------------------------------------------------------------------- 1 | class CreateRefreshToken 2 | include Interactor 3 | include AuthenticableInteractor 4 | 5 | REFRESH_TOKEN_TTL = 30.days 6 | 7 | delegate :user, :jti, :substitution_token, to: :context 8 | 9 | def call 10 | context.substitution_token ||= refresh_token 11 | context.refresh_token = substitution_token.token 12 | 13 | raise_unauthorized_error! unless substitution_token.save 14 | end 15 | 16 | private 17 | 18 | def refresh_token 19 | @refresh_token ||= RefreshToken.new( 20 | user_id: user.id, 21 | expires_at: REFRESH_TOKEN_TTL.from_now, 22 | token: refresh_token_value, 23 | jti: jti 24 | ) 25 | end 26 | 27 | def refresh_token_value 28 | @refresh_token_value ||= JWT.encode(payload, ENV.fetch("AUTH_SECRET_TOKEN"), "HS256") 29 | end 30 | 31 | def payload 32 | { 33 | sub: user.id, 34 | exp: REFRESH_TOKEN_TTL.from_now.to_i, 35 | jti: jti, 36 | type: "refresh" 37 | } 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /app/interactors/create_user.rb: -------------------------------------------------------------------------------- 1 | class CreateUser 2 | include Interactor 3 | 4 | delegate :user_params, to: :context 5 | 6 | def call 7 | context.user = User.new(user_params) 8 | 9 | context.fail!(error_data: error_data) unless context.user.save 10 | end 11 | 12 | private 13 | 14 | def error_data 15 | { message: "Record Invalid", detail: context.user.errors.to_a } 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /app/interactors/create_user_activity.rb: -------------------------------------------------------------------------------- 1 | class CreateUserActivity 2 | include Interactor 3 | 4 | delegate :user, :event, to: :context 5 | 6 | def call 7 | user.activities.create!(activity_attributes) 8 | end 9 | 10 | private 11 | 12 | def activity_attributes 13 | { 14 | event: event, 15 | title: event.to_s.titleize, 16 | body: activity_body 17 | } 18 | end 19 | 20 | def activity_body 21 | I18n.t("activity.#{event}", first_name: user.first_name, last_name: user.last_name, email: user.email) 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /app/interactors/find_refresh_token.rb: -------------------------------------------------------------------------------- 1 | class FindRefreshToken 2 | include Interactor 3 | include AuthenticableInteractor 4 | 5 | delegate :token, to: :context 6 | 7 | before do 8 | raise_unauthorized_error! unless valid_to_authorize? 9 | end 10 | 11 | def call 12 | context.jti = jwt_token.jti 13 | context.user = refresh_token.user 14 | context.existing_refresh_token = refresh_token 15 | context.substitution_token = context.existing_refresh_token.substitution_token 16 | end 17 | 18 | private 19 | 20 | def valid_to_authorize? 21 | jwt_token.valid? && jwt_token.refresh? && refresh_token 22 | end 23 | 24 | def refresh_token 25 | @refresh_token ||= RefreshToken.active.find_by(token: token) 26 | end 27 | 28 | def jwt_token 29 | @jwt_token ||= JWTToken.new(token) 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /app/interactors/omniauth/google/build_auth_client.rb: -------------------------------------------------------------------------------- 1 | require "google/api_client/client_secrets" 2 | 3 | module Omniauth 4 | module Google 5 | class BuildAuthClient 6 | include Interactor 7 | 8 | delegate :auth_code, to: :context 9 | 10 | def call 11 | context.auth_client = auth_client 12 | update_auth_client! 13 | end 14 | 15 | private 16 | 17 | def auth_client 18 | @auth_client ||= client_secrets.to_authorization 19 | end 20 | 21 | def update_auth_client! 22 | auth_client.update!( 23 | client_id: ENV.fetch("GOOGLE_CLIENT_ID"), 24 | client_secret: ENV.fetch("GOOGLE_CLIENT_SECRET"), 25 | redirect_uri: "postmessage", 26 | code: auth_code 27 | ) 28 | end 29 | 30 | def client_secrets 31 | ::Google::APIClient::ClientSecrets.load 32 | end 33 | end 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /app/interactors/omniauth/google/exchange_auth_code.rb: -------------------------------------------------------------------------------- 1 | module Omniauth 2 | module Google 3 | class ExchangeAuthCode 4 | include Interactor 5 | include AuthenticableInteractor 6 | 7 | delegate :auth_client, to: :context 8 | 9 | def call 10 | auth_client.fetch_access_token! 11 | rescue Signet::AuthorizationError 12 | raise_unauthorized_error! 13 | end 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /app/interactors/omniauth/google/fetch_user_info.rb: -------------------------------------------------------------------------------- 1 | require "google/apis/oauth2_v2" 2 | 3 | module Omniauth 4 | module Google 5 | class FetchUserInfo 6 | include Interactor 7 | 8 | delegate :auth_client, to: :context 9 | 10 | def call 11 | context.user_info = user_info 12 | end 13 | 14 | private 15 | 16 | def user_info 17 | oauth_service.get_userinfo(options: { authorization: auth_client }) 18 | end 19 | 20 | def oauth_service 21 | ::Google::Apis::Oauth2V2::Oauth2Service.new 22 | end 23 | end 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /app/interactors/omniauth/google/find_or_create_user.rb: -------------------------------------------------------------------------------- 1 | module Omniauth 2 | module Google 3 | class FindOrCreateUser 4 | include Interactor 5 | include AuthenticableInteractor 6 | 7 | delegate :user_info, :user, to: :context 8 | delegate :email, :family_name, :given_name, :picture, to: :user_info 9 | 10 | def call 11 | context.user = user 12 | raise_unauthorized_error! unless user.valid? 13 | end 14 | 15 | private 16 | 17 | def user 18 | @user ||= User.find_or_create_by(email: email) do |user| 19 | user.first_name = given_name 20 | user.last_name = family_name 21 | user.password = SecureRandom.hex(20) 22 | user.avatar = URI.open(picture) if picture.present? 23 | end 24 | end 25 | end 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /app/interactors/omniauth_authenticate_user.rb: -------------------------------------------------------------------------------- 1 | class OmniauthAuthenticateUser 2 | include Interactor 3 | 4 | delegate :auth_code, to: :context 5 | 6 | def call 7 | context.fail!(error_data: authenticate.error_data) if authenticate.failure? 8 | context.user = authenticate.user 9 | end 10 | 11 | private 12 | 13 | def authenticate 14 | @authenticate ||= AuthenticateByGoogleAuthCode.call(auth_code: auth_code) 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /app/interactors/omniauth_sign_in_or_sign_up.rb: -------------------------------------------------------------------------------- 1 | class OmniauthSignInOrSignUp 2 | include Interactor::Organizer 3 | 4 | delegate :user, to: :context 5 | 6 | organize OmniauthAuthenticateUser, 7 | CreateAccessToken, 8 | CreateRefreshToken 9 | 10 | after do 11 | RegisterActivityJob.perform_later(user.id, :user_logged_in) 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /app/interactors/prepare_presign_image.rb: -------------------------------------------------------------------------------- 1 | class PreparePresignImage 2 | include Interactor 3 | 4 | ALLOWED_TYPES = %w[image/jpeg image/png image/webp].freeze 5 | UPLOAD_SIZE_LIMIT = 10.megabyte 6 | 7 | PRESIGN_DATA = Struct.new(:url, :fields) 8 | PRESIGN_FIELD = Struct.new(:key, :value) 9 | 10 | delegate :filename, :type, to: :context 11 | 12 | def call 13 | context.fail!(error_data: error_data) unless ALLOWED_TYPES.include?(type) 14 | context.presign_data = presign_data 15 | end 16 | 17 | private 18 | 19 | def presign_data 20 | PRESIGN_DATA.new(upload_params[:url], presign_fields) 21 | end 22 | 23 | def presign_fields 24 | upload_params[:fields].map do |key, value| 25 | PRESIGN_FIELD.new(key, value) 26 | end 27 | end 28 | 29 | def upload_params 30 | @upload_params ||= storage.presign(location, **options).slice(:url, :fields) 31 | end 32 | 33 | def location 34 | SecureRandom.hex + File.extname(filename) 35 | end 36 | 37 | def options 38 | { 39 | content_disposition: ContentDisposition.inline(filename), 40 | content_type: type, 41 | content_length_range: 0..UPLOAD_SIZE_LIMIT 42 | } 43 | end 44 | 45 | def storage 46 | Shrine.find_storage(:cache) 47 | end 48 | 49 | def error_data 50 | { message: "Wrong file type", status: 415, code: :unsupported_media_type } 51 | end 52 | end 53 | -------------------------------------------------------------------------------- /app/interactors/request_password_reset.rb: -------------------------------------------------------------------------------- 1 | class RequestPasswordReset 2 | include Interactor 3 | include TransactionalInteractor 4 | 5 | delegate :email, to: :context 6 | 7 | def call 8 | user ? generate_password_reset_token : raise_error 9 | end 10 | 11 | after do 12 | ApplicationMailer.password_recovery(user).deliver_later 13 | RegisterActivityJob.perform_later(user.id, :reset_password_requested) 14 | end 15 | 16 | private 17 | 18 | def user 19 | @user ||= User.find_by(email: email) 20 | end 21 | 22 | def generate_password_reset_token 23 | user.regenerate_password_reset_token 24 | user.password_reset_sent_at = Time.current 25 | user.save! 26 | end 27 | 28 | def raise_error 29 | context.fail!(error_data: error_data) 30 | end 31 | 32 | def error_data 33 | { 34 | message: I18n.t("password_recovery.not_found.message"), 35 | detail: I18n.t("password_recovery.not_found.detail", email: email) 36 | } 37 | end 38 | end 39 | -------------------------------------------------------------------------------- /app/interactors/signin_user.rb: -------------------------------------------------------------------------------- 1 | class SigninUser 2 | include Interactor::Organizer 3 | 4 | delegate :user, to: :context 5 | 6 | organize AuthenticateByEmailAndPassword, 7 | CreateAccessToken, 8 | CreateRefreshToken 9 | 10 | after do 11 | RegisterActivityJob.perform_later(user.id, :user_logged_in) 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /app/interactors/signout_user.rb: -------------------------------------------------------------------------------- 1 | class SignoutUser 2 | include Interactor 3 | 4 | delegate :user, :token, :everywhere, to: :context 5 | 6 | def call 7 | refresh_tokens = user.refresh_tokens 8 | refresh_tokens = refresh_tokens.where(token: token) unless everywhere 9 | refresh_tokens.destroy_all 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /app/interactors/signup_user.rb: -------------------------------------------------------------------------------- 1 | class SignupUser 2 | include Interactor::Organizer 3 | include TransactionalInteractor 4 | 5 | delegate :user, to: :context 6 | 7 | organize CreateUser, 8 | CreateAccessToken, 9 | CreateRefreshToken, 10 | CreatePossessionToken 11 | 12 | after do 13 | RegisterActivityJob.perform_later(user.id, :user_registered) 14 | ApplicationMailer.confirm_user(context.possession_token).deliver_later 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /app/interactors/update_existing_refresh_token.rb: -------------------------------------------------------------------------------- 1 | class UpdateExistingRefreshToken 2 | include Interactor 3 | include AuthenticableInteractor 4 | 5 | TOKEN_GRACE_PERIOD = 60 6 | 7 | delegate :existing_refresh_token, :substitution_token, to: :context 8 | 9 | def call 10 | existing_refresh_token.assign_attributes(token_attributes) 11 | 12 | raise_unauthorized_error! unless existing_refresh_token.save 13 | end 14 | 15 | private 16 | 17 | def token_attributes 18 | { 19 | expires_at: TOKEN_GRACE_PERIOD.seconds.from_now, 20 | substitution_token: substitution_token 21 | } 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /app/interactors/update_password.rb: -------------------------------------------------------------------------------- 1 | class UpdatePassword 2 | include Interactor::Organizer 3 | include TransactionalInteractor 4 | 5 | delegate :user, to: :context 6 | 7 | organize FindUserByToken, 8 | UpdateUserPassword, 9 | CreateAccessToken, 10 | CreateRefreshToken 11 | 12 | after do 13 | RegisterActivityJob.perform_later(user.id, :user_reset_password) 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /app/interactors/update_password/find_user_by_token.rb: -------------------------------------------------------------------------------- 1 | class UpdatePassword 2 | class FindUserByToken 3 | include Interactor 4 | include AuthenticableInteractor 5 | 6 | delegate :reset_token, to: :context 7 | 8 | def call 9 | context.user = find_user 10 | 11 | raise_unauthorized_error! unless context.user 12 | end 13 | 14 | private 15 | 16 | def find_user 17 | User.find_by(password_reset_token: reset_token) 18 | end 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /app/interactors/update_password/update_user_password.rb: -------------------------------------------------------------------------------- 1 | class UpdatePassword 2 | class UpdateUserPassword 3 | include Interactor 4 | 5 | delegate :password, :user, to: :context 6 | 7 | def call 8 | context.fail!(error_data: error_data) unless update_user_password_form.valid? && update_user_password 9 | end 10 | 11 | private 12 | 13 | def update_user_password 14 | user.update(update_user_password_attributes) 15 | end 16 | 17 | def update_user_password_attributes 18 | update_user_password_form 19 | .model_attributes 20 | .merge(password_reset_token: nil, password_reset_sent_at: nil) 21 | end 22 | 23 | def update_user_password_form 24 | @update_user_password_form ||= UpdateUserPasswordForm.new(user).assign_attributes(password: password) 25 | end 26 | 27 | def error_data 28 | { message: "Record Invalid", detail: update_user_password_form.errors.to_a } 29 | end 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /app/interactors/update_token_pair.rb: -------------------------------------------------------------------------------- 1 | class UpdateTokenPair 2 | include Interactor::Organizer 3 | include TransactionalInteractor 4 | 5 | organize FindRefreshToken, 6 | CreateAccessToken, 7 | CreateRefreshToken, 8 | UpdateExistingRefreshToken 9 | end 10 | -------------------------------------------------------------------------------- /app/interactors/update_user.rb: -------------------------------------------------------------------------------- 1 | class UpdateUser 2 | include Interactor 3 | 4 | delegate :user_params, :user, to: :context 5 | 6 | def call 7 | context.fail!(error_data: error_data) unless update_user_form.valid? && update_user 8 | end 9 | 10 | after do 11 | RegisterActivityJob.perform_later(user.id, :user_updated) 12 | end 13 | 14 | private 15 | 16 | def update_user 17 | user.update(update_user_form.model_attributes) 18 | end 19 | 20 | def update_user_form 21 | @update_user_form ||= UpdateUserForm.new(user).assign_attributes(user_params) 22 | end 23 | 24 | def error_data 25 | { message: "Record Invalid", detail: update_user_form.errors.to_a } 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /app/jobs/application_job.rb: -------------------------------------------------------------------------------- 1 | class ApplicationJob < ActiveJob::Base 2 | # Automatically retry jobs that encountered a deadlock 3 | # retry_on ActiveRecord::Deadlocked 4 | 5 | # Most jobs are safe to ignore if the underlying records are no longer available 6 | # discard_on ActiveJob::DeserializationError 7 | end 8 | -------------------------------------------------------------------------------- /app/jobs/register_activity_job.rb: -------------------------------------------------------------------------------- 1 | class RegisterActivityJob < ApplicationJob 2 | queue_as :events 3 | 4 | def perform(user_id, event) 5 | user = User.find(user_id) 6 | CreateUserActivity.call!(user: user, event: event) 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /app/mailers/application_mailer.rb: -------------------------------------------------------------------------------- 1 | class ApplicationMailer < ActionMailer::Base 2 | layout "mailer" 3 | 4 | def password_recovery(user) 5 | @user = user 6 | @password_recovery_link = format( 7 | ENV.fetch("PASSWORD_RECOVERY_LINK_TEMPLATE"), 8 | password_reset_token: user.password_reset_token 9 | ) 10 | 11 | mail(to: user.email) 12 | end 13 | 14 | def confirm_user(possession_token) 15 | @user = possession_token.user 16 | @confirmation_link = format( 17 | ENV.fetch("CONFIRM_USER_LINK_TEMPLATE"), 18 | token_value: possession_token.value 19 | ) 20 | 21 | mail(to: @user.email) 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /app/models/activity.rb: -------------------------------------------------------------------------------- 1 | class Activity < ApplicationRecord 2 | extend Enumerize 3 | 4 | EVENTS = %i[user_registered user_logged_in user_updated reset_password_requested 5 | user_reset_password].freeze 6 | 7 | enumerize :event, in: EVENTS 8 | 9 | belongs_to :user 10 | 11 | scope :public_events, -> { where(event: %i[user_registered]) } 12 | 13 | validates :title, :body, presence: true 14 | end 15 | -------------------------------------------------------------------------------- /app/models/application_record.rb: -------------------------------------------------------------------------------- 1 | class ApplicationRecord < ActiveRecord::Base 2 | self.abstract_class = true 3 | end 4 | -------------------------------------------------------------------------------- /app/models/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fs/rails-base-graphql-api/dc1f74ea2ffdb4f8632ba627dc85df216bc332e3/app/models/concerns/.keep -------------------------------------------------------------------------------- /app/models/jwt_token.rb: -------------------------------------------------------------------------------- 1 | class JWTToken 2 | def initialize(token) 3 | @token = token 4 | end 5 | 6 | def valid? 7 | payload.present? 8 | end 9 | 10 | def access? 11 | type == "access" 12 | end 13 | 14 | def refresh? 15 | type == "refresh" 16 | end 17 | 18 | def type 19 | payload["type"] 20 | end 21 | 22 | def jti 23 | payload["jti"] 24 | end 25 | 26 | def sub 27 | payload["sub"] 28 | end 29 | 30 | private 31 | 32 | attr_reader :token 33 | 34 | def payload 35 | @payload ||= JWT.decode(token, ENV.fetch("AUTH_SECRET_TOKEN"), true, algorithm: "HS256").first 36 | rescue JWT::DecodeError 37 | {} 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /app/models/possession_token.rb: -------------------------------------------------------------------------------- 1 | class PossessionToken < ApplicationRecord 2 | belongs_to :user 3 | 4 | validates :value, presence: true, uniqueness: true 5 | end 6 | -------------------------------------------------------------------------------- /app/models/refresh_token.rb: -------------------------------------------------------------------------------- 1 | class RefreshToken < ApplicationRecord 2 | belongs_to :user 3 | belongs_to :original_token, class_name: "RefreshToken", optional: true 4 | 5 | has_one :substitution_token, class_name: "RefreshToken", foreign_key: :original_token_id, 6 | dependent: :destroy, inverse_of: :original_token 7 | 8 | validates :token, :expires_at, presence: true 9 | validates :token, uniqueness: true 10 | validates :original_token_id, uniqueness: true, allow_blank: true 11 | 12 | scope :active, -> { where("expires_at >= ?", Time.current) } 13 | end 14 | -------------------------------------------------------------------------------- /app/models/trigger_event.rb: -------------------------------------------------------------------------------- 1 | TriggerEvent = Struct.new(:event, :options, keyword_init: true) 2 | -------------------------------------------------------------------------------- /app/models/user.rb: -------------------------------------------------------------------------------- 1 | class User < ApplicationRecord 2 | include ImageUploader::Attachment(:avatar) 3 | 4 | has_secure_password 5 | has_secure_token :password_reset_token 6 | 7 | has_many :activities, dependent: :destroy 8 | has_many :refresh_tokens, dependent: :destroy 9 | 10 | validates :email, presence: true, uniqueness: true 11 | validates :email, format: { with: URI::MailTo::EMAIL_REGEXP } 12 | end 13 | -------------------------------------------------------------------------------- /app/policies/activity_policy.rb: -------------------------------------------------------------------------------- 1 | class ActivityPolicy < ApplicationPolicy 2 | relation_scope do |relation| 3 | relation.where(user: user) 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /app/policies/application_policy.rb: -------------------------------------------------------------------------------- 1 | class ApplicationPolicy < ActionPolicy::Base 2 | end 3 | -------------------------------------------------------------------------------- /app/query_objects/base_filtered_query.rb: -------------------------------------------------------------------------------- 1 | class BaseFilteredQuery 2 | def initialize(relation, filter_params = {}) 3 | @relation = relation 4 | @filter_params = filter_params 5 | end 6 | 7 | def all 8 | filter_params.reduce(relation) do |relation, (key, value)| 9 | public_send("by_#{key}", relation, value) 10 | end 11 | end 12 | 13 | private 14 | 15 | attr_reader :relation, :filter_params 16 | end 17 | -------------------------------------------------------------------------------- /app/query_objects/filtered_activities_query.rb: -------------------------------------------------------------------------------- 1 | class FilteredActivitiesQuery < BaseFilteredQuery 2 | ALLOWED_PARAMS = [:events].freeze 3 | 4 | def by_events(relation, events) 5 | relation.where(event: events) 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /app/storages/local_storage.rb: -------------------------------------------------------------------------------- 1 | class LocalStorage < Shrine::Storage::FileSystem 2 | CONVERSION_FIELDS = { 3 | cache_control: "Cache-Control", 4 | content_disposition: "Content-Disposition", 5 | content_encoding: "Content-Encoding", 6 | content_length_range: "content-length-range", 7 | content_type: "Content-Type" 8 | }.freeze 9 | 10 | delegate :images_upload_url, to: :url_helpers 11 | 12 | def presign(id, **options) 13 | { 14 | method: :post, 15 | url: images_upload_url(default_url_options), 16 | fields: { key: [storage_key, id].join("/") }.merge(converted_options(options)) 17 | } 18 | end 19 | 20 | def url(id, **_options) 21 | req = ActionDispatch::Request.new("HTTP_HOST" => ENV.fetch("HOST", nil)) 22 | 23 | [req.url, prefix, id].join("/") 24 | end 25 | 26 | private 27 | 28 | def storage_key 29 | Shrine.storages.key(self) 30 | end 31 | 32 | def url_helpers 33 | Rails.application.routes.url_helpers 34 | end 35 | 36 | def default_url_options 37 | Rails.application.config.action_controller.default_url_options 38 | end 39 | 40 | def converted_options(options) 41 | CONVERSION_FIELDS.each do |key, value| 42 | options[value] = options.delete(key) 43 | end 44 | 45 | options.compact 46 | end 47 | end 48 | -------------------------------------------------------------------------------- /app/uploaders/image_uploader.rb: -------------------------------------------------------------------------------- 1 | class ImageUploader < Shrine 2 | ALLOWED_EXTENSIONS = %w[jpg jpeg png webp].freeze 3 | ALLOWED_MIME_TYPES = %w[image/jpeg image/png image/webp].freeze 4 | 5 | Attacher.validate do 6 | validate_mime_type ALLOWED_MIME_TYPES 7 | validate_extension ALLOWED_EXTENSIONS 8 | end 9 | 10 | def generate_location(io, record: nil, derivative: nil, **options) 11 | options[:key]&.split("/")&.last || super 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /app/validators/existing_password_validator.rb: -------------------------------------------------------------------------------- 1 | class ExistingPasswordValidator < ActiveModel::EachValidator 2 | def validate_each(record, attribute, value) 3 | return if record.model.authenticate(value) 4 | 5 | record.errors.add(attribute, "is incorrect") 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /app/validators/expiration_validator.rb: -------------------------------------------------------------------------------- 1 | class ExpirationValidator < ActiveModel::EachValidator 2 | DEFAULT_TIMEOUT = 1.hour 3 | 4 | def validate_each(record, attribute, value) 5 | return if value.nil? || (options[:timeout] || DEFAULT_TIMEOUT).since(value).future? 6 | 7 | record.errors.add(attribute, :time_expired) 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /app/views/application_mailer/confirm_user.html.erb: -------------------------------------------------------------------------------- 1 |

Confirmation was sent for your account

2 | 3 |

Hello, <%= @user.first_name %> <%= @user.last_name %>.

4 | 5 |

6 | Follow <%= link_to "this link", @confirmation_link %> 7 | to confirm your account. 8 |

9 | -------------------------------------------------------------------------------- /app/views/application_mailer/password_recovery.html.erb: -------------------------------------------------------------------------------- 1 |

Password reset was requested for your account

2 | 3 |

Hello, <%= @user.first_name %> <%= @user.last_name %>.

4 |

5 | Someone requested a password reset 6 | for account with email <%= @user.email %>. 7 |

8 | 9 |

10 | Follow <%= link_to "this link", @password_recovery_link %> 11 | to reset your password. 12 |

13 | -------------------------------------------------------------------------------- /app/views/application_mailer/password_recovery.text.erb: -------------------------------------------------------------------------------- 1 | Password reset was requested for your account 2 | ============================================= 3 | 4 | Hello, <%= @user.first_name %> <%= @user.last_name %>. 5 | 6 | Someone requested a password reset 7 | for account with email <%= @user.email %>. 8 | 9 | Follow link 10 | <%= link_to "this link", @password_recovery_link %> 11 | to reset your password. 12 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 14 | 15 | 16 | 17 | <%= yield %> 18 | 19 | 20 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.text.erb: -------------------------------------------------------------------------------- 1 | <%= yield %> 2 | -------------------------------------------------------------------------------- /bin/brakeman: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | # 5 | # This file was generated by Bundler. 6 | # 7 | # The application 'brakeman' is installed as part of a gem, and 8 | # this file is here to facilitate running it. 9 | # 10 | 11 | require "pathname" 12 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", 13 | Pathname.new(__FILE__).realpath) 14 | 15 | bundle_binstub = File.expand_path("../bundle", __FILE__) 16 | 17 | if File.file?(bundle_binstub) 18 | if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/ 19 | load(bundle_binstub) 20 | else 21 | abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. 22 | Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") 23 | end 24 | end 25 | 26 | require "rubygems" 27 | require "bundler/setup" 28 | 29 | load Gem.bin_path("brakeman", "brakeman") 30 | -------------------------------------------------------------------------------- /bin/bundle-audit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | # 5 | # This file was generated by Bundler. 6 | # 7 | # The application 'bundle-audit' is installed as part of a gem, and 8 | # this file is here to facilitate running it. 9 | # 10 | 11 | require "pathname" 12 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", 13 | Pathname.new(__FILE__).realpath) 14 | 15 | bundle_binstub = File.expand_path("../bundle", __FILE__) 16 | 17 | if File.file?(bundle_binstub) 18 | if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/ 19 | load(bundle_binstub) 20 | else 21 | abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. 22 | Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") 23 | end 24 | end 25 | 26 | require "rubygems" 27 | require "bundler/setup" 28 | 29 | load Gem.bin_path("bundler-audit", "bundle-audit") 30 | -------------------------------------------------------------------------------- /bin/bundler-audit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | # 5 | # This file was generated by Bundler. 6 | # 7 | # The application 'bundler-audit' is installed as part of a gem, and 8 | # this file is here to facilitate running it. 9 | # 10 | 11 | require "pathname" 12 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", 13 | Pathname.new(__FILE__).realpath) 14 | 15 | bundle_binstub = File.expand_path("../bundle", __FILE__) 16 | 17 | if File.file?(bundle_binstub) 18 | if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/ 19 | load(bundle_binstub) 20 | else 21 | abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. 22 | Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") 23 | end 24 | end 25 | 26 | require "rubygems" 27 | require "bundler/setup" 28 | 29 | load Gem.bin_path("bundler-audit", "bundler-audit") 30 | -------------------------------------------------------------------------------- /bin/docker-entrypoint: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -e 4 | 5 | if [ -f tmp/pids/server.pid ]; then 6 | rm tmp/pids/server.pid 7 | fi 8 | 9 | bundle install 10 | bundle exec rails db:prepare 11 | bundle exec rails server -b 0.0.0.0 12 | -------------------------------------------------------------------------------- /bin/docker-quality: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | set -e 4 | 5 | docker-compose up --detach 6 | docker-compose exec app bin/quality 7 | -------------------------------------------------------------------------------- /bin/docker-server: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | set -e 4 | 5 | docker-compose up 6 | -------------------------------------------------------------------------------- /bin/docker-setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | set -e 4 | 5 | if [ ! -f .env ]; then 6 | cp .env.example .env 7 | fi 8 | 9 | if [ ! -f docker-compose.override.yml ]; then 10 | cp docker-compose.linux.yml docker-compose.override.yml 11 | fi 12 | 13 | docker-compose up --detach 14 | docker-compose stop 15 | -------------------------------------------------------------------------------- /bin/docker-sync: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | set -e 4 | 5 | gem install docker-sync 6 | docker-sync start 7 | cp docker-compose.osx.yml docker-compose.override.yml 8 | -------------------------------------------------------------------------------- /bin/docker-tests: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | docker-compose up --detach 4 | docker-compose exec app bin/rails db:schema:load 5 | docker-compose exec app bin/rspec ${@:-spec} 6 | -------------------------------------------------------------------------------- /bin/quality: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | set -e 4 | 5 | bin/rubocop 6 | bin/brakeman --quiet --skip-libs --exit-on-warn --no-pager --except EOLRuby 7 | bin/bundle-audit update 8 | bin/bundle-audit check 9 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | APP_PATH = File.expand_path("../config/application", __dir__) 3 | require_relative "../config/boot" 4 | require "rails/commands" 5 | -------------------------------------------------------------------------------- /bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require_relative "../config/boot" 3 | require "rake" 4 | Rake.application.run 5 | -------------------------------------------------------------------------------- /bin/rspec: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | # 5 | # This file was generated by Bundler. 6 | # 7 | # The application 'rspec' is installed as part of a gem, and 8 | # this file is here to facilitate running it. 9 | # 10 | 11 | require "pathname" 12 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", 13 | Pathname.new(__FILE__).realpath) 14 | 15 | bundle_binstub = File.expand_path("../bundle", __FILE__) 16 | 17 | if File.file?(bundle_binstub) 18 | if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/ 19 | load(bundle_binstub) 20 | else 21 | abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. 22 | Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") 23 | end 24 | end 25 | 26 | require "rubygems" 27 | require "bundler/setup" 28 | 29 | load Gem.bin_path("rspec-core", "rspec") 30 | -------------------------------------------------------------------------------- /bin/rubocop: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | # 5 | # This file was generated by Bundler. 6 | # 7 | # The application 'rubocop' is installed as part of a gem, and 8 | # this file is here to facilitate running it. 9 | # 10 | 11 | require "pathname" 12 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", 13 | Pathname.new(__FILE__).realpath) 14 | 15 | bundle_binstub = File.expand_path("../bundle", __FILE__) 16 | 17 | if File.file?(bundle_binstub) 18 | if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/ 19 | load(bundle_binstub) 20 | else 21 | abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. 22 | Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") 23 | end 24 | end 25 | 26 | require "rubygems" 27 | require "bundler/setup" 28 | 29 | load Gem.bin_path("rubocop", "rubocop") 30 | -------------------------------------------------------------------------------- /bin/server: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | bin/rails server --port 3000 --binding lvh.me 4 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | set -e 4 | 5 | # Setup dependencies on macOS 6 | if [ `uname -s` = "Darwin" ]; then 7 | echo "Install Homebrew dependencies ..." 8 | if [ -x "$(command -v brew)" ]; then 9 | brew bundle check --no-upgrade || brew bundle --no-upgrade 10 | fi 11 | 12 | echo "Install Ruby ..." 13 | RUBY_VERSION=$(<.ruby-version) 14 | MAJOR_RUBY_VERSION=$(echo $RUBY_VERSION | cut -d'.' -f1 | bc) 15 | XCODE_VERSION=$(pkgutil --pkg-info=com.apple.pkg.CLTools_Executables | awk '/version:/ {print $2}') 16 | MAJOR_XCODE_VERSION=$(echo $XCODE_VERSION | cut -d'.' -f1 | bc) 17 | if [ -x "$(command -v rbenv)" ] && [ -z "$(rbenv versions --bare | grep $RUBY_VERSION)" ]; then 18 | # GFLAGS changed in XCode 12 and older ruby versions should be installed with 19 | # https://github.com/rbenv/ruby-build/issues/1489 20 | if [ $MAJOR_XCODE_VERSION -ge 12 ] && [ $MAJOR_RUBY_VERSION -lt 3 ]; then 21 | CFLAGS="-Wno-error=implicit-function-declaration" rbenv install $RUBY_VERSION 22 | else 23 | rbenv install $RUBY_VERSION 24 | fi 25 | fi 26 | fi 27 | 28 | # Setup specific Bundler options if this is CI 29 | if [ "$CI" ]; then 30 | BUNDLER_ARGS="--without development staging production" 31 | fi 32 | 33 | # Make sure we have Bundler installed 34 | echo "Install Bundler ..." 35 | gem install bundler --conservative 36 | 37 | # Set up Ruby dependencies via Bundler into .bundle folder 38 | echo "Install gems ..." 39 | rm -f .bundle/config 40 | 41 | bundle check --path .bundle > /dev/null 2>&1 || 42 | bundle config set --local path '.bundle' && bundle install $BUNDLER_ARGS 43 | 44 | # Set up configurable environment variables 45 | if [ ! -f .env ]; then 46 | cp .env.example .env 47 | fi 48 | 49 | # Set up database and add any development seed data 50 | echo "Setup database" 51 | bin/rails db:setup 52 | 53 | # Clean log files and tmp directory 54 | bin/rails log:clear tmp:clear 55 | -------------------------------------------------------------------------------- /bin/spring: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | if !defined?(Spring) && [nil, "development", "test"].include?(ENV["RAILS_ENV"]) 3 | gem "bundler" 4 | require "bundler" 5 | 6 | # Load Spring without loading other gems in the Gemfile, for speed. 7 | Bundler.locked_gems&.specs&.find { |spec| spec.name == "spring" }&.tap do |spring| 8 | Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path 9 | gem "spring", spring.version 10 | require "spring/binstub" 11 | rescue Gem::LoadError 12 | # Ignore when Spring is not installed. 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /bin/tests: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | set -e 4 | 5 | bin/rspec spec 6 | -------------------------------------------------------------------------------- /client_secrets.json: -------------------------------------------------------------------------------- 1 | { 2 | "web": { 3 | "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", 4 | "auth_uri": "https://accounts.google.com/o/oauth2/auth", 5 | "token_uri": "https://oauth2.googleapis.com/token" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require_relative "config/environment" 4 | 5 | run Rails.application 6 | Rails.application.load_server 7 | -------------------------------------------------------------------------------- /config/application.rb: -------------------------------------------------------------------------------- 1 | require_relative "boot" 2 | 3 | require "rails" 4 | # Pick the frameworks you want: 5 | require "active_model/railtie" 6 | require "active_job/railtie" 7 | require "active_record/railtie" 8 | # require "active_storage/engine" 9 | require "action_controller/railtie" 10 | require "action_mailer/railtie" 11 | # require "action_mailbox/engine" 12 | # require "action_text/engine" 13 | require "action_view/railtie" 14 | # require "action_cable/engine" 15 | # require "rails/test_unit/railtie" 16 | 17 | # Require the gems listed in Gemfile, including any gems 18 | # you've limited to :test, :development, or :production. 19 | Bundler.require(*Rails.groups) 20 | 21 | module RailsBaseGraphqlApi 22 | class Application < Rails::Application 23 | # Initialize configuration defaults for originally generated Rails version. 24 | config.load_defaults 7.0 25 | 26 | # Configuration for the application, engines, and railties goes here. 27 | # 28 | # These settings can be overridden in specific environments using the files 29 | # in config/environments, which are processed later. 30 | # 31 | # config.time_zone = "Central Time (US & Canada)" 32 | # config.eager_load_paths << Rails.root.join("extras") 33 | 34 | # Only loads a smaller set of middleware suitable for API only apps. 35 | # Middleware like session, flash, cookies can be added back manually. 36 | # Skip views, helpers and assets when generating a new resource. 37 | config.api_only = true 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /config/boot.rb: -------------------------------------------------------------------------------- 1 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) 2 | 3 | require "bundler/setup" # Set up gems listed in the Gemfile. 4 | require "bootsnap/setup" # Speed up boot time by caching expensive operations. 5 | -------------------------------------------------------------------------------- /config/cable.yml: -------------------------------------------------------------------------------- 1 | development: 2 | adapter: async 3 | 4 | test: 5 | adapter: test 6 | 7 | production: 8 | adapter: redis 9 | url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> 10 | channel_prefix: rails_base_graphql_api_production 11 | -------------------------------------------------------------------------------- /config/credentials.yml.enc: -------------------------------------------------------------------------------- 1 | EEVo5J3cnhPYJTSA14h97rEKJXk3A0I++IOx3XXdzdqDFZX0OWhHjxBUvTeoIUBbnaFqXURdLlgb4AheCabHDEbD7KQk2mMQA7twJY26CP+CzLxbvwRzx3+oNW4ri73V7Mmtq2LMHn8aAD5XiWt2Eb04qq4Recegp9cNYDQ0ByJ1hZb+nIBnxYE+hsQbgksa1GEFWWcHc3/In/sQ1NjJ6JBe4+NCRCgcYiShJ1D2z2WYSaf3OKScWNluJ/Kka5Xv+rSV2mqFZEaKKH3guJ1YR6Q23dmvv3XrAuk4cyp8n0zhAZDAxUqHY7I/Q07n2qEZX+dFyBoQzcPVGLE48LlG/AkUK3sy4m69Fq2y8+JIGe7b4vfBcE/4P+wWwdtJOZ/qn4P4S21rvCwu2HSqwnlEPYJ4dXKH3iJntj0f--0c0XehX2o6guINN4--0xVJTsP6tKN74jbB5vpYNQ== -------------------------------------------------------------------------------- /config/database.yml: -------------------------------------------------------------------------------- 1 | defaults: &defaults 2 | adapter: postgresql 3 | encoding: unicode 4 | min_messages: warning 5 | timeout: 5000 6 | pool: <%= [ENV.fetch("MAX_THREADS", 5), ENV.fetch("DB_POOL", 5)].max %> 7 | url: <%= ENV["DATABASE_URL"] %> 8 | 9 | development: 10 | database: <%= ENV.fetch("DB_NAME", "#{Rails.root.basename}_dev") %> 11 | <<: *defaults 12 | 13 | test: 14 | database: <%= ENV.fetch("DB_NAME", "#{Rails.root.basename}_test") %> 15 | <<: *defaults 16 | -------------------------------------------------------------------------------- /config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the Rails application. 2 | require_relative "application" 3 | 4 | # Initialize the Rails application. 5 | Rails.application.initialize! 6 | -------------------------------------------------------------------------------- /config/environments/development.rb: -------------------------------------------------------------------------------- 1 | require "active_support/core_ext/integer/time" 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # In the development environment your application's code is reloaded any time 7 | # it changes. This slows down response time but is perfect for development 8 | # since you don't have to restart the web server when you make code changes. 9 | config.cache_classes = false 10 | 11 | # Do not eager load code on boot. 12 | config.eager_load = false 13 | 14 | # Show full error reports. 15 | config.consider_all_requests_local = true 16 | 17 | # Enable server timing 18 | config.server_timing = true 19 | 20 | # Enable/disable caching. By default caching is disabled. 21 | # Run rails dev:cache to toggle caching. 22 | if Rails.root.join("tmp/caching-dev.txt").exist? 23 | config.cache_store = :memory_store 24 | config.public_file_server.headers = { 25 | "Cache-Control" => "public, max-age=#{2.days.to_i}" 26 | } 27 | else 28 | config.action_controller.perform_caching = false 29 | 30 | config.cache_store = :null_store 31 | end 32 | 33 | config.action_controller.default_url_options = { host: ENV.fetch("HOST", "localhost:3000") } 34 | 35 | # Don't care if the mailer can't send. 36 | config.action_mailer.raise_delivery_errors = false 37 | 38 | config.action_mailer.perform_caching = false 39 | 40 | config.action_mailer.delivery_method = :smtp 41 | config.action_mailer.smtp_settings = { address: "mailcatcher", port: 1025 } 42 | 43 | # Print deprecation notices to the Rails logger. 44 | config.active_support.deprecation = :log 45 | 46 | # Raise exceptions for disallowed deprecations. 47 | config.active_support.disallowed_deprecation = :raise 48 | 49 | # Tell Active Support which deprecation messages to disallow. 50 | config.active_support.disallowed_deprecation_warnings = [] 51 | 52 | # Raise an error on page load if there are pending migrations. 53 | config.active_record.migration_error = :page_load 54 | 55 | # Highlight code that triggered database queries in logs. 56 | config.active_record.verbose_query_logs = true 57 | 58 | # Raises error for missing translations. 59 | # config.i18n.raise_on_missing_translations = true 60 | 61 | # Annotate rendered view with file names. 62 | # config.action_view.annotate_rendered_view_with_filenames = true 63 | 64 | # Use an evented file watcher to asynchronously detect changes in source code, 65 | # routes, locales, etc. This feature depends on the listen gem. 66 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker 67 | 68 | # Uncomment if you wish to allow Action Cable access from any origin. 69 | # config.action_cable.disable_request_forgery_protection = true 70 | end 71 | -------------------------------------------------------------------------------- /config/environments/test.rb: -------------------------------------------------------------------------------- 1 | require "active_support/core_ext/integer/time" 2 | 3 | # The test environment is used exclusively to run your application's 4 | # test suite. You never need to work with it otherwise. Remember that 5 | # your test database is "scratch space" for the test suite and is wiped 6 | # and recreated between test runs. Don't rely on the data there! 7 | 8 | Rails.application.configure do 9 | # Settings specified here will take precedence over those in config/application.rb. 10 | 11 | # Turn false under Spring and add config.action_view.cache_template_loading = true. 12 | config.cache_classes = true 13 | 14 | # Eager loading loads your whole application. When running a single test locally, 15 | # this probably isn't necessary. It's a good idea to do in a continuous integration 16 | # system, or in some way before deploying your code. 17 | config.eager_load = ENV["CI"].present? 18 | 19 | # Configure public file server for tests with Cache-Control for performance. 20 | config.public_file_server.enabled = true 21 | config.public_file_server.headers = { 22 | "Cache-Control" => "public, max-age=#{1.hour.to_i}" 23 | } 24 | 25 | # Show full error reports and disable caching. 26 | config.consider_all_requests_local = true 27 | config.action_controller.perform_caching = false 28 | config.cache_store = :null_store 29 | 30 | # Raise exceptions instead of rendering exception templates. 31 | config.action_dispatch.show_exceptions = false 32 | 33 | # Disable request forgery protection in test environment. 34 | config.action_controller.allow_forgery_protection = false 35 | 36 | config.action_mailer.perform_caching = false 37 | 38 | # Tell Action Mailer not to deliver emails to the real world. 39 | # The :test delivery method accumulates sent emails in the 40 | # ActionMailer::Base.deliveries array. 41 | config.action_mailer.delivery_method = :test 42 | 43 | # Print deprecation notices to the stderr. 44 | config.active_support.deprecation = :stderr 45 | 46 | # Raise exceptions for disallowed deprecations. 47 | config.active_support.disallowed_deprecation = :raise 48 | 49 | # Tell Active Support which deprecation messages to disallow. 50 | config.active_support.disallowed_deprecation_warnings = [] 51 | 52 | # Raises error for missing translations. 53 | # config.i18n.raise_on_missing_translations = true 54 | 55 | # Annotate rendered view with file names. 56 | # config.action_view.annotate_rendered_view_with_filenames = true 57 | end 58 | -------------------------------------------------------------------------------- /config/initializers/action_mailer.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Set default From address for all Mailers 3 | config.action_mailer.default_options = { from: ENV.fetch("MAILER_SENDER_ADDRESS") } 4 | end 5 | -------------------------------------------------------------------------------- /config/initializers/application_controller_renderer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # ActiveSupport::Reloader.to_prepare do 4 | # ApplicationController.renderer.defaults.merge!( 5 | # http_host: 'example.org', 6 | # https: false 7 | # ) 8 | # end 9 | -------------------------------------------------------------------------------- /config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| /my_noisy_library/.match?(line) } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code 7 | # by setting BACKTRACE=1 before calling your invocation, like "BACKTRACE=1 ./bin/rails runner 'MyClass.perform'". 8 | Rails.backtrace_cleaner.remove_silencers! if ENV["BACKTRACE"] 9 | -------------------------------------------------------------------------------- /config/initializers/cors.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Avoid CORS issues when API is called from the frontend app. 4 | # Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. 5 | 6 | # Read more: https://github.com/cyu/rack-cors 7 | 8 | if ENV["CORS_ORIGINS"].present? 9 | Rails.application.config.middleware.insert_before 0, Rack::Cors do 10 | allow do 11 | origins(*ENV.fetch("CORS_ORIGINS").split(",")) 12 | 13 | resource "*", 14 | headers: :any, 15 | methods: %i[get post put patch delete options head] 16 | end 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /config/initializers/events.rb: -------------------------------------------------------------------------------- 1 | # ActiveSupport::Notifications.subscribe "some_event" do |_name, _start, _finish, _id, payload| 2 | # # do something 3 | # end 4 | -------------------------------------------------------------------------------- /config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Configure parameters to be filtered from the log file. Use this to limit dissemination of 4 | # sensitive information. See the ActiveSupport::ParameterFilter documentation for supported 5 | # notations and behaviors. 6 | Rails.application.config.filter_parameters += %i[password passw secret token _key crypt salt certificate otp ssn] 7 | -------------------------------------------------------------------------------- /config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new inflection rules using the following format. Inflections 4 | # are locale specific, and you may define rules for as many different 5 | # locales as you wish. All of these examples are active by default: 6 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 7 | # inflect.plural /^(ox)$/i, "\\1en" 8 | # inflect.singular /^(ox)en/i, "\\1" 9 | # inflect.irregular "person", "people" 10 | # inflect.uncountable %w( fish sheep ) 11 | # end 12 | 13 | # These inflection rules are supported but not enabled by default: 14 | ActiveSupport::Inflector.inflections(:en) do |inflect| 15 | inflect.acronym "JWT" 16 | end 17 | -------------------------------------------------------------------------------- /config/initializers/locales.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | config.i18n.load_path += Dir[Rails.root.join("config/locales/**/*.{rb,yml}")] 3 | end 4 | -------------------------------------------------------------------------------- /config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new mime types for use in respond_to blocks: 4 | # Mime::Type.register "text/richtext", :rtf 5 | -------------------------------------------------------------------------------- /config/initializers/rack_deflater.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | config.middleware.insert_after ActionDispatch::Static, Rack::Deflater 3 | end 4 | -------------------------------------------------------------------------------- /config/initializers/session_store.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # This also configures session_options for use below 3 | config.session_store :cookie_store, key: ENV.fetch("SESSION_STORE_KEY", "#{Rails.root.basename}_session") 4 | 5 | # Required for all session management (regardless of session_store) 6 | config.middleware.use ActionDispatch::Cookies 7 | 8 | config.middleware.use config.session_store, config.session_options 9 | end 10 | -------------------------------------------------------------------------------- /config/initializers/shrine.rb: -------------------------------------------------------------------------------- 1 | require "shrine" 2 | require "shrine/storage/file_system" 3 | require "shrine/storage/s3" 4 | require "shrine/storage/memory" 5 | 6 | Rails.application.reloader.to_prepare do 7 | Shrine.plugin :activerecord 8 | Shrine.plugin :cached_attachment_data 9 | Shrine.plugin :determine_mime_type 10 | Shrine.plugin :remove_attachment 11 | Shrine.plugin :restore_cached_data 12 | Shrine.plugin :validation 13 | Shrine.plugin :validation_helpers 14 | 15 | def s3_options 16 | { 17 | access_key_id: ENV.fetch("S3_ACCESS_KEY_ID", nil), 18 | secret_access_key: ENV.fetch("S3_SECRET_ACCESS_KEY", nil), 19 | region: ENV.fetch("S3_BUCKET_REGION", nil), 20 | bucket: ENV.fetch("S3_BUCKET_NAME", nil) 21 | } 22 | end 23 | 24 | def amazon_s3_storages 25 | { 26 | cache: Shrine::Storage::S3.new(prefix: "cache", **s3_options), 27 | store: Shrine::Storage::S3.new(prefix: "store", upload_options: { acl: "public-read" }, **s3_options) 28 | } 29 | end 30 | 31 | def memory_storages 32 | { 33 | cache: Shrine::Storage::Memory.new, 34 | store: Shrine::Storage::Memory.new 35 | } 36 | end 37 | 38 | def filesystem_storages 39 | { 40 | cache: LocalStorage.new("public", prefix: "/uploads/cache"), 41 | store: LocalStorage.new("public", prefix: "/uploads") 42 | } 43 | end 44 | 45 | def local_storages 46 | Rails.env.test? ? memory_storages : filesystem_storages 47 | end 48 | 49 | if s3_options.values.all?(&:present?) 50 | Shrine.storages = amazon_s3_storages 51 | else 52 | Shrine.plugin :upload_endpoint, upload_context: ->(request) { { key: request.params["key"] } } 53 | Shrine.storages = local_storages 54 | end 55 | end 56 | -------------------------------------------------------------------------------- /config/initializers/sidekiq.rb: -------------------------------------------------------------------------------- 1 | require "sidekiq/web" 2 | 3 | Rails.application.configure do 4 | config.active_job.queue_adapter = :sidekiq 5 | end 6 | 7 | Sidekiq.configure_server do |config| 8 | config.redis = { url: ENV.fetch("REDIS_URL", "redis://localhost:6379/1"), protocol: 2 } 9 | end 10 | 11 | Sidekiq.configure_client do |config| 12 | config.redis = { url: ENV.fetch("REDIS_URL", "redis://localhost:6379/1"), protocol: 2 } 13 | end 14 | -------------------------------------------------------------------------------- /config/initializers/sidekiq_web.rb: -------------------------------------------------------------------------------- 1 | if ENV["SIDEKIQ_USERNAME"] && ENV["SIDEKIQ_PASSWORD"] 2 | Sidekiq::Web.use Rack::Auth::Basic do |username, password| 3 | ActiveSupport::SecurityUtils.secure_compare(username, ENV["SIDEKIQ_USERNAME"]) & 4 | ActiveSupport::SecurityUtils.secure_compare(password, ENV["SIDEKIQ_PASSWORD"]) 5 | end 6 | end 7 | -------------------------------------------------------------------------------- /config/initializers/strong_migrations.rb: -------------------------------------------------------------------------------- 1 | # Mark existing migrations as safe 2 | StrongMigrations.start_after = 20_200_615_113_414 3 | 4 | # Set timeouts for migrations 5 | # If you use PgBouncer in transaction mode, delete these lines and set timeouts on the database user 6 | StrongMigrations.lock_timeout = 10.seconds 7 | StrongMigrations.statement_timeout = 1.hour 8 | 9 | # Analyze tables after indexes are added 10 | # Outdated statistics can sometimes hurt performance 11 | StrongMigrations.auto_analyze = true 12 | 13 | # Add custom checks 14 | # StrongMigrations.add_check do |method, args| 15 | # if method == :add_index && args[0].to_s == "users" 16 | # stop! "No more indexes on the users table" 17 | # end 18 | # end 19 | -------------------------------------------------------------------------------- /config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # This file contains settings for ActionController::ParamsWrapper which 4 | # is enabled by default. 5 | 6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 7 | ActiveSupport.on_load(:action_controller) do 8 | wrap_parameters format: [:json] 9 | end 10 | 11 | # To enable root element in JSON for ActiveRecord objects. 12 | # ActiveSupport.on_load(:active_record) do 13 | # self.include_root_in_json = true 14 | # end 15 | -------------------------------------------------------------------------------- /config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Files in the config/locales directory are used for internationalization 2 | # and are automatically loaded by Rails. If you want to use locales other 3 | # than English, add the necessary files in this directory. 4 | # 5 | # To use the locales, use `I18n.t`: 6 | # 7 | # I18n.t 'hello' 8 | # 9 | # In views, this is aliased to just `t`: 10 | # 11 | # <%= t('hello') %> 12 | # 13 | # To use a different locale, set it with `I18n.locale`: 14 | # 15 | # I18n.locale = :es 16 | # 17 | # This would use the information in config/locales/es.yml. 18 | # 19 | # The following keys must be escaped otherwise they will not be retrieved by 20 | # the default I18n backend: 21 | # 22 | # true, false, on, off, yes, no 23 | # 24 | # Instead, surround them with single quotes. 25 | # 26 | # en: 27 | # 'true': 'foo' 28 | # 29 | # To learn more, please read the Rails Internationalization guide 30 | # available at https://guides.rubyonrails.org/i18n.html. 31 | 32 | en: 33 | hello: "Hello world" 34 | activity: 35 | user_updated: "User updated with the next attributes:\n First name - %{first_name},\n Last name - %{last_name},\n Email - %{email}\n" 36 | user_logged_in: "User logged in with the next attributes:\n First name - %{first_name},\n Last name - %{last_name}\n" 37 | user_registered: "New user registered with the next attributes:\n First name - %{first_name},\n Last name - %{last_name}\n" 38 | user_reset_password: "User reset password" 39 | reset_password_requested: "User requested reset password instructions" 40 | -------------------------------------------------------------------------------- /config/locales/models/update_user_password_form/en.yml: -------------------------------------------------------------------------------- 1 | en: 2 | errors: 3 | messages: 4 | time_expired: "has expired" 5 | -------------------------------------------------------------------------------- /config/locales/password_recovery.en.yml: -------------------------------------------------------------------------------- 1 | en: 2 | password_recovery: 3 | sent: 4 | message: Instructions sent 5 | detail: Password recovery instructions were sent if that account exists 6 | not_found: 7 | message: Record not found 8 | detail: User with email %{email} not found 9 | -------------------------------------------------------------------------------- /config/puma.rb: -------------------------------------------------------------------------------- 1 | # Puma can serve each request in a thread from an internal thread pool. 2 | # The `threads` method setting takes two numbers: a minimum and maximum. 3 | # Any libraries that use thread pools should be configured to match 4 | # the maximum value specified for Puma. Default is set to 5 threads for minimum 5 | # and maximum; this matches the default thread size of Active Record. 6 | # 7 | max_threads_count = ENV.fetch("RAILS_MAX_THREADS", 5) 8 | min_threads_count = ENV.fetch("RAILS_MIN_THREADS", max_threads_count) 9 | threads min_threads_count, max_threads_count 10 | 11 | # Specifies the `worker_timeout` threshold that Puma will use to wait before 12 | # terminating a worker in development environments. 13 | # 14 | worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development" 15 | 16 | # Specifies the `port` that Puma will listen on to receive requests; default is 3000. 17 | # 18 | port ENV.fetch("PORT", 3000) 19 | 20 | # Specifies the `environment` that Puma will run in. 21 | # 22 | environment ENV.fetch("RAILS_ENV") { "development" } 23 | 24 | # Specifies the `pidfile` that Puma will use. 25 | pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } 26 | 27 | # Specifies the number of `workers` to boot in clustered mode. 28 | # Workers are forked web server processes. If using threads and workers together 29 | # the concurrency of the application would be max `threads` * `workers`. 30 | # Workers do not work on JRuby or Windows (both of which do not support 31 | # processes). 32 | # 33 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 } 34 | 35 | # Use the `preload_app!` method when specifying a `workers` number. 36 | # This directive tells Puma to first boot the application and load code 37 | # before forking the application. This takes advantage of Copy On Write 38 | # process behavior so workers use less memory. 39 | # 40 | # preload_app! 41 | 42 | # Allow puma to be restarted by `rails restart` command. 43 | plugin :tmp_restart 44 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | require "sidekiq/web" 2 | 3 | Rails.application.routes.draw do 4 | mount Sidekiq::Web, at: "/sidekiq" 5 | 6 | post "/images/upload", to: "uploads#image" 7 | 8 | post "/graphql", to: "graphql#execute" 9 | end 10 | -------------------------------------------------------------------------------- /config/sidekiq.yml: -------------------------------------------------------------------------------- 1 | # Sample configuration file for Sidekiq. 2 | # Options here can still be overridden by cmd line args. 3 | # Place this file at config/sidekiq.yml and Sidekiq will 4 | # pick it up automatically. 5 | --- 6 | :verbose: true 7 | :concurrency: <%= ENV.fetch("REDIS_CONCURRENCY", 10) %> 8 | 9 | # Set timeout to 8 on Heroku, longer if you manage your own systems. 10 | :timeout: 8 11 | 12 | # Sidekiq will run this file through ERB when reading it so you can 13 | # even put in dynamic logic, like a host-specific queue. 14 | # http://www.mikeperham.com/2013/11/13/advanced-sidekiq-host-specific-queues/ 15 | :queues: 16 | - default 17 | - events 18 | - mailers 19 | -------------------------------------------------------------------------------- /config/spring.rb: -------------------------------------------------------------------------------- 1 | Spring.watch( 2 | ".ruby-version", 3 | ".rbenv-vars", 4 | "tmp/restart.txt", 5 | "tmp/caching-dev.txt" 6 | ) 7 | -------------------------------------------------------------------------------- /config/storage.yml: -------------------------------------------------------------------------------- 1 | test: 2 | service: Disk 3 | root: <%= Rails.root.join("tmp/storage") %> 4 | 5 | local: 6 | service: Disk 7 | root: <%= Rails.root.join("storage") %> 8 | 9 | # Use rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) 10 | # amazon: 11 | # service: S3 12 | # access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> 13 | # secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> 14 | # region: us-east-1 15 | # bucket: your_own_bucket 16 | 17 | # Remember not to checkin your GCS keyfile to a repository 18 | # google: 19 | # service: GCS 20 | # project: your_project 21 | # credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> 22 | # bucket: your_own_bucket 23 | 24 | # Use rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) 25 | # microsoft: 26 | # service: AzureStorage 27 | # storage_account_name: your_account_name 28 | # storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> 29 | # container: your_container_name 30 | 31 | # mirror: 32 | # service: Mirror 33 | # primary: local 34 | # mirrors: [ amazon, google, microsoft ] 35 | -------------------------------------------------------------------------------- /db/migrate/20200210115945_create_users.rb: -------------------------------------------------------------------------------- 1 | class CreateUsers < ActiveRecord::Migration[6.0] 2 | def change 3 | enable_extension("citext") 4 | 5 | create_table :users do |t| 6 | t.citext :email, null: false 7 | t.string :first_name 8 | t.string :last_name 9 | t.string :password_digest, null: false 10 | 11 | t.timestamps 12 | end 13 | 14 | add_index :users, :email, unique: true 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /db/migrate/20200519104937_create_refresh_tokens.rb: -------------------------------------------------------------------------------- 1 | class CreateRefreshTokens < ActiveRecord::Migration[6.0] 2 | def change 3 | create_table :refresh_tokens do |t| 4 | t.string :token, index: true, null: false 5 | t.references :user, foreign_key: true, null: false 6 | t.datetime :expires_at, null: false, precision: 6 7 | t.string :client_uid, index: true 8 | 9 | t.timestamps 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /db/migrate/20200528082200_add_jti_to_refresh_tokens.rb: -------------------------------------------------------------------------------- 1 | class AddJtiToRefreshTokens < ActiveRecord::Migration[6.0] 2 | def change 3 | add_column :refresh_tokens, :jti, :string, index: true 4 | 5 | add_index :refresh_tokens, :jti 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /db/migrate/20200602140429_remove_client_uid_from_refresh_tokens.rb: -------------------------------------------------------------------------------- 1 | class RemoveClientUidFromRefreshTokens < ActiveRecord::Migration[6.0] 2 | def change 3 | remove_column :refresh_tokens, :client_uid 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /db/migrate/20200604082036_add_password_reset_token_to_users.rb: -------------------------------------------------------------------------------- 1 | class AddPasswordResetTokenToUsers < ActiveRecord::Migration[6.0] 2 | def change 3 | add_column :users, :password_reset_token, :string 4 | add_column :users, :password_reset_sent_at, :datetime, precision: 6 5 | 6 | add_index :users, :password_reset_token 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /db/migrate/20200609122433_create_activities.rb: -------------------------------------------------------------------------------- 1 | class CreateActivities < ActiveRecord::Migration[6.0] 2 | def change 3 | create_table :activities do |t| 4 | t.string :title, null: false 5 | t.text :body, null: false 6 | t.string :event, null: false 7 | t.references :user, null: false, foreign_key: true 8 | 9 | t.timestamps 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /db/migrate/20200617151148_add_avatar_to_users.rb: -------------------------------------------------------------------------------- 1 | class AddAvatarToUsers < ActiveRecord::Migration[6.0] 2 | def change 3 | add_column :users, :avatar_data, :text 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /db/migrate/20210604132857_add_confirmed_at_to_users.rb: -------------------------------------------------------------------------------- 1 | class AddConfirmedAtToUsers < ActiveRecord::Migration[6.0] 2 | def change 3 | add_column :users, :confirmed_at, :datetime, precision: 6 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /db/migrate/20210604145805_create_possession_tokens.rb: -------------------------------------------------------------------------------- 1 | class CreatePossessionTokens < ActiveRecord::Migration[6.0] 2 | def change 3 | create_table :possession_tokens do |t| 4 | t.string :value, null: false, unique: true 5 | 6 | t.belongs_to :user, foreign_key: true, null: false 7 | t.timestamps 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /db/migrate/20230523063638_add_original_token_to_refresh_tokens.rb: -------------------------------------------------------------------------------- 1 | class AddOriginalTokenToRefreshTokens < ActiveRecord::Migration[7.0] 2 | disable_ddl_transaction! 3 | 4 | def change 5 | add_reference :refresh_tokens, :original_token, null: true, 6 | index: { unique: true, algorithm: :concurrently } 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /db/migrate/20230523063747_add_foreign_key_to_original_token_to_refresh_tokens.rb: -------------------------------------------------------------------------------- 1 | class AddForeignKeyToOriginalTokenToRefreshTokens < ActiveRecord::Migration[7.0] 2 | def change 3 | safety_assured do 4 | add_foreign_key :refresh_tokens, :refresh_tokens, column: :original_token_id 5 | end 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /db/migrate/20230523065737_add_uniq_index_to_token_on_refresh_tokens.rb: -------------------------------------------------------------------------------- 1 | class AddUniqIndexToTokenOnRefreshTokens < ActiveRecord::Migration[7.0] 2 | disable_ddl_transaction! 3 | 4 | def change 5 | remove_index :refresh_tokens, :token 6 | add_index :refresh_tokens, :token, unique: true, algorithm: :concurrently 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /db/seeds.rb: -------------------------------------------------------------------------------- 1 | Activity.destroy_all 2 | User.destroy_all 3 | 4 | john_doe = User.create!(email: "john.doe@example.com", first_name: "John", last_name: "Doe", password: "123456") 5 | Activity.create!( 6 | user: john_doe, 7 | title: "User registered", 8 | body: "New user registered with the next attributes: First Name - John, Last Name - Doe", 9 | event: :user_registered 10 | ) 11 | 12 | darth_vader = User.create!( 13 | email: "darth.vader@example.com", 14 | first_name: "Darth", 15 | last_name: "Vader", 16 | password: "123456" 17 | ) 18 | Activity.create!( 19 | user: darth_vader, 20 | title: "User registered", 21 | body: "New user registered with the next attributes: First Name - Darth, Last Name - Vader", 22 | event: :user_registered 23 | ) 24 | -------------------------------------------------------------------------------- /docker-compose.linux.yml: -------------------------------------------------------------------------------- 1 | version: "3.8" 2 | 3 | services: 4 | app: 5 | volumes: 6 | - .:/app 7 | sidekiq: 8 | volumes: 9 | - .:/app 10 | -------------------------------------------------------------------------------- /docker-compose.osx.yml: -------------------------------------------------------------------------------- 1 | version: "3.8" 2 | 3 | services: 4 | app: 5 | volumes: 6 | - app-files:/app:nocopy 7 | sidekiq: 8 | volumes: 9 | - app-files:/app:nocopy 10 | 11 | volumes: 12 | app-files: 13 | external: true 14 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.8" 2 | 3 | x-app: &app_base 4 | depends_on: 5 | - db 6 | - redis 7 | image: ${IMAGE_NAME} 8 | environment: 9 | - DATABASE_URL=postgres://postgres:password@db 10 | - RAILS_ENV 11 | - RACK_ENV 12 | - DATABASE_CLEANER_ALLOW_REMOTE_DATABASE_URL 13 | - AUTH_SECRET_TOKEN 14 | - MAILER_SENDER_ADDRESS 15 | - PASSWORD_RECOVERY_LINK_TEMPLATE 16 | build: 17 | context: . 18 | args: 19 | - BUNDLE_WITHOUT="${BUNDLE_WITHOUT}" 20 | - BUNDLER_VERSION=2.4.13 21 | - FOLDERS_TO_REMOVE="" 22 | links: 23 | - db 24 | volumes: 25 | - ruby-bundle:/usr/local/bundle 26 | 27 | services: 28 | db: 29 | image: postgres:15-alpine 30 | environment: 31 | - POSTGRES_PASSWORD=password 32 | ports: 33 | - "5432:5432" 34 | volumes: 35 | - db-data:/var/lib/postgresql/data 36 | mailcatcher: 37 | image: schickling/mailcatcher 38 | ports: 39 | - "1025:1025" 40 | - "1080:1080" 41 | redis: 42 | image: redis:7.0.11-alpine 43 | sysctls: 44 | - net.core.somaxconn=511 45 | app: 46 | <<: *app_base 47 | stdin_open: true 48 | tty: true 49 | depends_on: 50 | - mailcatcher 51 | ports: 52 | - "3000:3000" 53 | command: bin/docker-entrypoint 54 | sidekiq: 55 | <<: *app_base 56 | depends_on: 57 | - app 58 | environment: 59 | - REDIS_URL 60 | command: sh -c './bin/wait-for app:3000 -- bundle exec sidekiq' 61 | 62 | volumes: 63 | ruby-bundle: 64 | db-data: 65 | -------------------------------------------------------------------------------- /docker-sync.yml: -------------------------------------------------------------------------------- 1 | version: "2" 2 | syncs: 3 | app-files: 4 | notify_terminal: true 5 | src: './' 6 | sync_excludes: ['.git', '.bundle'] 7 | -------------------------------------------------------------------------------- /lib/tasks/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fs/rails-base-graphql-api/dc1f74ea2ffdb4f8632ba627dc85df216bc332e3/lib/tasks/.keep -------------------------------------------------------------------------------- /log/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fs/rails-base-graphql-api/dc1f74ea2ffdb4f8632ba627dc85df216bc332e3/log/.keep -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | -------------------------------------------------------------------------------- /spec/acceptance/authentication_user_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe "Authenticate user", type: :request do 4 | include_context "when time is frozen" 5 | 6 | let!(:user) { create(:user, id: 111_111) } 7 | let(:refresh_token) { nil } 8 | let(:query) do 9 | <<-GRAPHQL 10 | query { 11 | me { 12 | id 13 | } 14 | } 15 | GRAPHQL 16 | end 17 | 18 | before do 19 | refresh_token 20 | post "/graphql", headers: { authorization: "Bearer #{token.token}" }, params: { query: query } 21 | end 22 | 23 | context "with valid token and valid refresh token" do 24 | let(:token) { build(:access_token, user_id: user.id) } 25 | let(:refresh_token) { create(:refresh_token, user: user, jti: token.jti) } 26 | 27 | it_behaves_like "full graphql request", "return current user" do 28 | let(:fixture_path) { "json/acceptance/current_user.json" } 29 | end 30 | end 31 | 32 | context "with valid token and expired refresh token" do 33 | let(:token) { build(:access_token, user_id: user.id) } 34 | let(:refresh_token) { create(:refresh_token, :expired, user: user, jti: token.jti) } 35 | 36 | it_behaves_like "full graphql request", "return null" do 37 | let(:fixture_path) { "json/acceptance/not_user.json" } 38 | end 39 | end 40 | 41 | context "with valid token and without refresh token" do 42 | let(:token) { build(:access_token, user_id: user.id) } 43 | 44 | it_behaves_like "full graphql request", "return null" do 45 | let(:fixture_path) { "json/acceptance/not_user.json" } 46 | end 47 | end 48 | 49 | context "with invalid token" do 50 | let(:token) { build(:access_token, :invalid, user_id: user.id) } 51 | 52 | it_behaves_like "full graphql request", "return null" do 53 | let(:fixture_path) { "json/acceptance/not_user.json" } 54 | end 55 | end 56 | 57 | context "with expired token" do 58 | let(:token) { build(:access_token, :expired, user_id: user.id) } 59 | 60 | it_behaves_like "full graphql request", "return null" do 61 | let(:fixture_path) { "json/acceptance/not_user.json" } 62 | end 63 | end 64 | 65 | context "when use refresh token for receiving user" do 66 | let(:token) { build(:refresh_token, user: user) } 67 | 68 | it_behaves_like "full graphql request", "return null" do 69 | let(:fixture_path) { "json/acceptance/not_user.json" } 70 | end 71 | end 72 | end 73 | -------------------------------------------------------------------------------- /spec/acceptance/image_uploading_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe "Upload image", type: :request do 4 | let(:avatar_image_path) { Rails.root.join("spec/fixtures/images/avatar.jpg") } 5 | let(:file_key) { "c379cbc5050227055116049764dc283b.png" } 6 | let(:storage_key) { "cache" } 7 | let(:params) do 8 | { 9 | key: "#{storage_key}/#{file_key}", 10 | content_disposition: "inline; filename='avatar.png'; filename*=UTF-8''avatar.png", 11 | content_type: "image/png", 12 | content_length_range: "0..10485760", 13 | file: Rack::Test::UploadedFile.new(avatar_image_path, "image/png") 14 | } 15 | end 16 | 17 | before { post "/images/upload", params: params } 18 | 19 | after { Shrine.storages[:cache].clear! } 20 | 21 | it "uploads image" do 22 | expect(Shrine.storages[:cache].store).to have_key(file_key) 23 | end 24 | 25 | it "returns 204 status" do 26 | expect(response).to have_http_status(:no_content) 27 | expect(response.body).to be_empty 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /spec/factories/access_tokens.rb: -------------------------------------------------------------------------------- 1 | require_relative "dummy/jwt_token" 2 | 3 | FactoryBot.define do 4 | factory :access_token, class: "Dummy::JWTToken" do 5 | initialize_with { new(attributes) } 6 | 7 | user_id { rand(1_000_000) } 8 | exp { 1.hour.since.to_i } 9 | jti { SecureRandom.hex } 10 | 11 | trait :invalid do 12 | token { "bad_token" } 13 | end 14 | 15 | trait :expired do 16 | exp { 1.hour.ago.to_i } 17 | end 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /spec/factories/activities.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :activity do 3 | title { generate(:activity_title) } 4 | body { "New user registered." } 5 | event { :user_registered } 6 | user 7 | 8 | trait :public do 9 | event { :user_registered } 10 | end 11 | 12 | trait :private do 13 | event { :user_updated } 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /spec/factories/dummy/jwt_token.rb: -------------------------------------------------------------------------------- 1 | module Dummy 2 | class JWTToken 3 | attr_reader :jti 4 | 5 | def initialize(attrs) 6 | @token = attrs[:token] 7 | @user_id = attrs[:user_id] || rand(1_000_000) 8 | @exp = attrs[:exp] || 1.hour.since.to_i 9 | @jti = attrs[:jti] || SecureRandom.hex 10 | @type = attrs[:type] || "access" 11 | end 12 | 13 | def token 14 | @token ||= JWT.encode(payload, ENV.fetch("AUTH_SECRET_TOKEN"), "HS256") 15 | end 16 | 17 | private 18 | 19 | def payload 20 | { 21 | sub: @user_id, 22 | exp: @exp, 23 | jti: @jti, 24 | type: @type 25 | } 26 | end 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /spec/factories/possession_tokens.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :possession_token do 3 | user 4 | 5 | value { "token" } 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /spec/factories/refresh_tokens.rb: -------------------------------------------------------------------------------- 1 | require_relative "dummy/jwt_token" 2 | 3 | FactoryBot.define do 4 | factory :refresh_token do 5 | user 6 | expires_at { 1.year.since } 7 | jti { "jti" } 8 | token do 9 | Dummy::JWTToken.new( 10 | user_id: user.id, 11 | exp: expires_at.to_i, 12 | jti: jti, 13 | type: "refresh" 14 | ).token 15 | end 16 | 17 | trait :expired do 18 | expires_at { 1.hour.ago } 19 | end 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /spec/factories/sequences.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | sequence :user_email do |n| 3 | "user_#{n}@example.com" 4 | end 5 | sequence :activity_title do |n| 6 | "User ##{n} registered!" 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /spec/factories/users.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :user do 3 | email { generate(:user_email) } 4 | password { "password" } 5 | first_name { FFaker::Name.first_name } 6 | last_name { FFaker::Name.first_name } 7 | 8 | trait :with_reset_token do 9 | password_reset_token { "reset_token" } 10 | password_reset_sent_at { Time.zone.now } 11 | end 12 | 13 | trait :with_data do 14 | email { "adam@serwer.com" } 15 | first_name { "Adam" } 16 | last_name { "Serwer" } 17 | end 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /spec/fixtures/files/fake_image.png: -------------------------------------------------------------------------------- 1 | fake image file 2 | -------------------------------------------------------------------------------- /spec/fixtures/files/test.txt: -------------------------------------------------------------------------------- 1 | text test file 2 | -------------------------------------------------------------------------------- /spec/fixtures/images/avatar.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fs/rails-base-graphql-api/dc1f74ea2ffdb4f8632ba627dc85df216bc332e3/spec/fixtures/images/avatar.jpg -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/current_user.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "me": { 4 | "id": "111111" 5 | } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/confirm_user.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "confirmUser": { 4 | "me": { 5 | "id": "123456", 6 | "confirmedAt": "2020-05-10T12:30:00Z" 7 | } 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/first_page_query_type_activities.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "activities": { 4 | "edges": [{ 5 | "cursor": "MQ", 6 | "node": { 7 | "id": ":id", 8 | "title": "User registered", 9 | "body": "New user registered with the next attributes: First Name - John, Last Name - Doe" 10 | } 11 | }], 12 | "pageInfo": { 13 | "endCursor": "MQ", 14 | "hasNextPage": true, 15 | "hasPreviousPage": false, 16 | "startCursor": "MQ" 17 | } 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/mutations/update_token_existing.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "updateToken": { 4 | "me": { 5 | "id": "111111" 6 | }, 7 | "accessToken": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOjExMTExMSwiZXhwIjoxNTg5MTE3NDAwLCJqdGkiOiI0NmQzMDBlYTM5YWI0NjZkNzk1ODZhODU2YTQxZWUzMiIsInR5cGUiOiJhY2Nlc3MifQ.orCV2LaLViyaUXJJ8Hnk7l5uRkN1O22PQRneuBPw6ps", 8 | "refreshToken": "13f08fc63d67f72e9818cc66e87a2cf4" 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/mutations/update_token_invalid.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "updateToken": null 4 | }, 5 | "errors": [ 6 | { 7 | "message": "Invalid credentials", 8 | "extensions": { 9 | "status": 401, 10 | "code": "unauthorized", 11 | "detail": null 12 | }, 13 | "locations": [ 14 | { "line": 2, "column": 9 } 15 | ], 16 | "path": ["updateToken"] 17 | } 18 | ] 19 | } 20 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/mutations/update_token_valid.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "updateToken": { 4 | "accessToken": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOjExMTExMSwiZXhwIjoxNTg5MTE3NDAwLCJqdGkiOiI0NmQzMDBlYTM5YWI0NjZkNzk1ODZhODU2YTQxZWUzMiIsInR5cGUiOiJhY2Nlc3MifQ.orCV2LaLViyaUXJJ8Hnk7l5uRkN1O22PQRneuBPw6ps", 5 | "refreshToken": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOjExMTExMSwiZXhwIjoxNTkxNzA1ODAwLCJqdGkiOiI0NmQzMDBlYTM5YWI0NjZkNzk1ODZhODU2YTQxZWUzMiIsInR5cGUiOiJyZWZyZXNoIn0.oPPlwvYdHwF45vY7Lu_XMR3NGHnWZ9BhRwcAUToYQsg" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/presign_data.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "presignData": { 4 | "data": { 5 | "url": "http://some-url.com", 6 | "fields": [{ 7 | "key": "key", 8 | "value": "value" 9 | }] 10 | } 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/presign_data_wrong.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "presignData": null 4 | }, 5 | "errors": [ 6 | { 7 | "message": "Wrong file type", 8 | "extensions": { 9 | "status": 415, 10 | "code": "unsupported_media_type", 11 | "detail": null 12 | }, 13 | "locations": [ 14 | { "line": 2, "column": 9 } 15 | ], 16 | "path": ["presignData"] 17 | } 18 | ] 19 | } 20 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/query_type_me.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "me": { 4 | "id": ":id", 5 | "email": ":email", 6 | "firstName": ":first_name", 7 | "lastName": ":last_name" 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/query_type_me_unauthorized.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "me": null 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/query_type_me_with_activities.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "me": { 4 | "activities": { 5 | "edges": [ 6 | { 7 | "node": { 8 | "event": "USER_UPDATED", 9 | "id": ":activity_id" 10 | } 11 | } 12 | ] 13 | }, 14 | "id": ":id", 15 | "email": "adam@serwer.com", 16 | "firstName": "Adam", 17 | "lastName": "Serwer" 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/request_password_recovery.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "requestPasswordRecovery": { 4 | "message": "Instructions sent", 5 | "detail": "Password recovery instructions were sent if that account exists" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/request_password_recovery_wrong.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "requestPasswordRecovery": { 4 | "message": "Record not found", 5 | "detail": "User with email zaphod.beeblebrox@gmail.com not found" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/second_page_query_type_activities.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "activities": { 4 | "edges": [{ 5 | "cursor": "Mg", 6 | "node": { 7 | "id": ":id", 8 | "title": "User registered", 9 | "body": "New user registered with the next attributes: First Name - Will, Last Name - Smith" 10 | } 11 | }], 12 | "pageInfo": { 13 | "endCursor": "Mg", 14 | "hasNextPage": false, 15 | "hasPreviousPage": true, 16 | "startCursor": "Mg" 17 | } 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/sign_in.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "signIn": { 4 | "accessToken": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOjExMTExMSwiZXhwIjoxNTg5MTE3NDAwLCJqdGkiOiI3ZmM2ZDIxOTEzODExYmU0OGRiNzQ0MTdmOWEyNjU5OCIsInR5cGUiOiJhY2Nlc3MifQ.e-wdSHA4hdSL3NzSrQMzPb1ggFCJDgRW_MGrcXPHwPM", 5 | "refreshToken": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOjExMTExMSwiZXhwIjoxNTkxNzA1ODAwLCJqdGkiOiI3ZmM2ZDIxOTEzODExYmU0OGRiNzQ0MTdmOWEyNjU5OCIsInR5cGUiOiJyZWZyZXNoIn0.NcsFRIy6_P5FU4iEm-28hBWRMRDMGn8ei7dKJJfpD_0", 6 | "me": { 7 | "id": "111111", 8 | "email": "bilbo.baggins@shire.com" 9 | } 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/sign_in_with_google.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "omniauthSignInOrSignUp": { 4 | "accessToken": ":accessToken", 5 | "refreshToken": ":refreshToken", 6 | "me": { 7 | "id": ":id", 8 | "email": "adam@serwer.com" 9 | } 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/sign_in_wrong.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "signIn": null 4 | }, 5 | "errors": [ 6 | { 7 | "message": "Invalid credentials", 8 | "extensions": { 9 | "status": 401, 10 | "code": "unauthorized", 11 | "detail": null 12 | }, 13 | "locations": [ 14 | { "line": 2, "column": 9 } 15 | ], 16 | "path": ["signIn"] 17 | } 18 | ] 19 | } 20 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/sign_up.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "signUp": { 4 | "me": { 5 | "id": ":id", 6 | "email": "bilbo.baggins@shire.com", 7 | "avatarUrl": ":avatar_url" 8 | }, 9 | "accessToken": ":accessToken", 10 | "refreshToken": ":refreshToken" 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/sign_up_wrong.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "signUp": null 4 | }, 5 | "errors": [ 6 | { 7 | "message": "Record Invalid", 8 | "extensions": { 9 | "status": 422, 10 | "code": "unprocessable_entity", 11 | "detail": ["Email is invalid"] 12 | }, 13 | "locations": [ 14 | { "line": 2, "column": 9 } 15 | ], 16 | "path": ["signUp"] 17 | } 18 | ] 19 | } 20 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/update_password.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "updatePassword": { 4 | "me": { 5 | "id": "111111", 6 | "email": "john.doe@example.com", 7 | "firstName": "John", 8 | "lastName": "Doe" 9 | }, 10 | "accessToken": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOjExMTExMSwiZXhwIjoxNTg5MTE3NDAwLCJqdGkiOiI3ZmM2ZDIxOTEzODExYmU0OGRiNzQ0MTdmOWEyNjU5OCIsInR5cGUiOiJhY2Nlc3MifQ.e-wdSHA4hdSL3NzSrQMzPb1ggFCJDgRW_MGrcXPHwPM", 11 | "refreshToken": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOjExMTExMSwiZXhwIjoxNTkxNzA1ODAwLCJqdGkiOiI3ZmM2ZDIxOTEzODExYmU0OGRiNzQ0MTdmOWEyNjU5OCIsInR5cGUiOiJyZWZyZXNoIn0.NcsFRIy6_P5FU4iEm-28hBWRMRDMGn8ei7dKJJfpD_0" 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/update_password_expired.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "updatePassword": null 4 | }, 5 | "errors": [ 6 | { 7 | "message": "Record Invalid", 8 | "extensions": { 9 | "status": 422, 10 | "code": "unprocessable_entity", 11 | "detail": ["Password reset sent at has expired"] 12 | }, 13 | "locations": [ 14 | { 15 | "line": 2, 16 | "column": 9 17 | } 18 | ], 19 | "path": ["updatePassword"] 20 | } 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/update_password_wrong.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "updatePassword": null 4 | }, 5 | "errors": [ 6 | { 7 | "message": "Invalid credentials", 8 | "extensions": { 9 | "status": 401, 10 | "code": "unauthorized", 11 | "detail": null 12 | }, 13 | "locations": [ 14 | { 15 | "line": 2, 16 | "column": 9 17 | } 18 | ], 19 | "path": ["updatePassword"] 20 | } 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/update_token_failed.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "updateToken": null 4 | }, 5 | "errors": [ 6 | { 7 | "message": "Invalid credentials", 8 | "extensions": { 9 | "status": 401, 10 | "code": "unauthorized", 11 | "detail": null 12 | }, 13 | "locations": [ 14 | { 15 | "line": 2, 16 | "column": 9 17 | } 18 | ], 19 | "path": ["updateToken"] 20 | } 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/graphql/update_user.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "updateUser": { 4 | "me": { 5 | "id": ":id", 6 | "email": "new_email_11@example.com", 7 | "firstName": "Randle", 8 | "lastName": "McMurphy", 9 | "avatarUrl": ":avatar_url" 10 | } 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/not_user.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "me": null 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /spec/fixtures/json/acceptance/sign_out/success.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": { 3 | "signOut": { 4 | "message": "User signed out successfully" 5 | } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /spec/graphql/mutations/confirm_user_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe Mutations::ConfirmUser do 4 | include_context "when time is frozen" 5 | 6 | let(:schema_context) { { current_user: user } } 7 | let(:user) { create(:user, id: 123_456, password: "123456") } 8 | let(:possession_token) { create(:possession_token, user: user) } 9 | 10 | let(:query) do 11 | <<-GRAPHQL 12 | mutation { 13 | confirmUser ( 14 | input: { 15 | value: "#{possession_token.value}" 16 | } 17 | ) { 18 | me { 19 | id 20 | confirmedAt 21 | } 22 | } 23 | } 24 | GRAPHQL 25 | end 26 | 27 | it_behaves_like "graphql request", "returns updated user info" do 28 | let(:fixture_path) { "json/acceptance/graphql/confirm_user.json" } 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /spec/graphql/mutations/presign_data_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe Mutations::PresignData do 4 | let(:schema_context) { { current_user: user } } 5 | let(:user) { create(:user) } 6 | let(:query) do 7 | <<-GRAPHQL 8 | mutation { 9 | presignData ( 10 | input: { 11 | filename: "avatar.png", 12 | type: "#{file_type}" 13 | } 14 | ) { 15 | data { 16 | url 17 | fields { 18 | key 19 | value 20 | } 21 | } 22 | } 23 | } 24 | GRAPHQL 25 | end 26 | 27 | context "with valid file type" do 28 | let(:file_type) { "image/png" } 29 | let(:s3_storage) { instance_double(Shrine::Storage::S3, presign: presign_data) } 30 | let(:presign_data) { { url: "http://some-url.com", fields: { key: :value } } } 31 | 32 | before do 33 | allow(Shrine).to receive(:find_storage).and_return(s3_storage) 34 | end 35 | 36 | it_behaves_like "graphql request", "returns data for direct upload" do 37 | let(:fixture_path) { "json/acceptance/graphql/presign_data.json" } 38 | end 39 | end 40 | 41 | context "with invalid file type" do 42 | let(:file_type) { "wrong_type" } 43 | 44 | it_behaves_like "graphql request", "returns error" do 45 | let(:fixture_path) { "json/acceptance/graphql/presign_data_wrong.json" } 46 | end 47 | end 48 | end 49 | -------------------------------------------------------------------------------- /spec/graphql/mutations/request_password_recovery_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe Mutations::RequestPasswordRecovery do 4 | let(:query) do 5 | <<-GRAPHQL 6 | mutation { 7 | requestPasswordRecovery( 8 | input: { 9 | email: "zaphod.beeblebrox@gmail.com" 10 | } 11 | ) { 12 | message 13 | detail 14 | } 15 | } 16 | GRAPHQL 17 | end 18 | 19 | context "when user exists" do 20 | let(:fixture_path) { "json/acceptance/graphql/request_password_recovery.json" } 21 | 22 | before { create(:user, email: "zaphod.beeblebrox@gmail.com") } 23 | 24 | it_behaves_like "graphql request", "returns info message" 25 | end 26 | 27 | context "when user doesn't exist" do 28 | let(:fixture_path) { "json/acceptance/graphql/request_password_recovery_wrong.json" } 29 | 30 | it_behaves_like "graphql request", "returns error" 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /spec/graphql/mutations/sign_in_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe Mutations::SignIn do 4 | include_context "when time is frozen" 5 | 6 | let(:query) do 7 | <<-GRAPHQL 8 | mutation { 9 | signIn ( 10 | input: { 11 | email: "bilbo.baggins@shire.com", 12 | password: "#{password}" 13 | } 14 | ) { 15 | me { 16 | id 17 | email 18 | } 19 | refreshToken 20 | accessToken 21 | } 22 | } 23 | GRAPHQL 24 | end 25 | 26 | before do 27 | create(:user, id: 111_111, email: "bilbo.baggins@shire.com", password: "TheRing") 28 | end 29 | 30 | context "with valid credentials" do 31 | let(:password) { "TheRing" } 32 | 33 | it_behaves_like "graphql request", "gets user token" do 34 | let(:fixture_path) { "json/acceptance/graphql/sign_in.json" } 35 | end 36 | end 37 | 38 | context "with invalid credentials" do 39 | let(:password) { "Sauron" } 40 | 41 | it_behaves_like "graphql request", "returns error" do 42 | let(:fixture_path) { "json/acceptance/graphql/sign_in_wrong.json" } 43 | end 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /spec/graphql/mutations/sign_out_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe Mutations::SignOut, type: :request do 4 | let(:user) { create(:user) } 5 | let(:everywhere) { true } 6 | let(:refresh_token) { create(:refresh_token, user: user) } 7 | let(:query) do 8 | <<-GRAPHQL 9 | mutation { 10 | signOut( 11 | input: { 12 | everywhere: #{everywhere} 13 | } 14 | ) 15 | { 16 | message 17 | } 18 | } 19 | GRAPHQL 20 | end 21 | 22 | let(:execution_context) do 23 | { 24 | context: { 25 | current_user: user, token: refresh_token.token, everywhere: everywhere 26 | } 27 | } 28 | end 29 | let(:schema_context) { { current_user: user } } 30 | 31 | it_behaves_like "graphql request", "return current user" do 32 | let(:fixture_path) { "json/acceptance/sign_out/success.json" } 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /spec/graphql/mutations/sign_up_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe Mutations::SignUp do 4 | include_context "when time is frozen" 5 | 6 | before do 7 | allow(JWT).to receive(:encode).and_return("jwt.token.success") 8 | end 9 | 10 | let(:registered_user) { User.last } 11 | let(:uploader) { ImageUploader.new(:cache) } 12 | let(:avatar_image_path) { Rails.root.join("spec/fixtures/images/avatar.jpg") } 13 | let(:uploaded_file) { uploader.upload(File.open(avatar_image_path, binmode: true)) } 14 | let(:avatar_id) { uploaded_file.id } 15 | 16 | let(:query) do 17 | <<-GRAPHQL 18 | mutation { 19 | signUp( 20 | input: { 21 | email: "#{email}", 22 | password: "TheRing", 23 | avatar: { 24 | id: "#{avatar_id}", 25 | metadata: { 26 | size: 1098178, 27 | filename: "avatar.jpg", 28 | mimeType: "image/jpg" 29 | } 30 | } 31 | } 32 | ) { 33 | me { 34 | id 35 | email 36 | avatarUrl 37 | } 38 | accessToken 39 | refreshToken 40 | } 41 | } 42 | GRAPHQL 43 | end 44 | 45 | context "with valid data" do 46 | let(:email) { "bilbo.baggins@shire.com" } 47 | 48 | it_behaves_like "graphql request", "registers a new user" do 49 | let(:fixture_path) { "json/acceptance/graphql/sign_up.json" } 50 | let(:prepared_fixture_file) do 51 | fixture_file.gsub( 52 | /:id|:avatar_url|:accessToken|:refreshToken/, 53 | ":id" => registered_user.id, 54 | ":avatar_url" => registered_user.avatar.url, 55 | ":accessToken" => "jwt.token.success", 56 | ":refreshToken" => "jwt.token.success" 57 | ) 58 | end 59 | end 60 | end 61 | 62 | context "with invalid data" do 63 | let(:email) { "bilbo.baggins" } 64 | 65 | it_behaves_like "graphql request", "returns error" do 66 | let(:fixture_path) { "json/acceptance/graphql/sign_up_wrong.json" } 67 | end 68 | end 69 | end 70 | -------------------------------------------------------------------------------- /spec/graphql/mutations/update_password_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe Mutations::UpdatePassword do 4 | include_context "when time is frozen" 5 | 6 | let(:user) do 7 | create(:user, :with_reset_token, id: 111_111, email: "john.doe@example.com", first_name: "John", last_name: "Doe") 8 | end 9 | 10 | let(:query) do 11 | <<-GRAPHQL 12 | mutation { 13 | updatePassword( 14 | input: { 15 | password: "new_password", 16 | resetToken: "#{reset_token}" 17 | } 18 | ) { 19 | me { 20 | id 21 | email 22 | firstName 23 | lastName 24 | } 25 | accessToken, 26 | refreshToken 27 | } 28 | } 29 | GRAPHQL 30 | end 31 | 32 | context "with valid data" do 33 | let(:reset_token) { user.password_reset_token } 34 | 35 | it_behaves_like "graphql request", "returns user info" do 36 | let(:fixture_path) { "json/acceptance/graphql/update_password.json" } 37 | end 38 | end 39 | 40 | context "with wrong token" do 41 | let(:reset_token) { "wrong_token" } 42 | 43 | it_behaves_like "graphql request", "returns error" do 44 | let(:fixture_path) { "json/acceptance/graphql/update_password_wrong.json" } 45 | end 46 | end 47 | 48 | context "with expired token" do 49 | let(:current_time) { user.password_reset_sent_at + 15.minutes + 1 } 50 | let(:reset_token) { user.password_reset_token } 51 | 52 | before { freeze_time } 53 | 54 | it_behaves_like "graphql request", "returns error" do 55 | let(:fixture_path) { "json/acceptance/graphql/update_password_expired.json" } 56 | end 57 | end 58 | end 59 | -------------------------------------------------------------------------------- /spec/graphql/mutations/update_token_existing_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe Mutations::UpdateToken do 4 | include_context "when time is frozen" 5 | 6 | let(:schema_context) { { token: current_refresh_token.token } } 7 | let(:user) { create(:user, id: 111_111) } 8 | let(:current_refresh_token) { create(:refresh_token, user: user, jti: "46d300ea39ab466d79586a856a41ee32") } 9 | let(:substitution_token_value) { "13f08fc63d67f72e9818cc66e87a2cf4" } 10 | 11 | let(:query) do 12 | <<-GRAPHQL 13 | mutation { 14 | updateToken { 15 | me { 16 | id 17 | } 18 | accessToken 19 | refreshToken 20 | } 21 | } 22 | GRAPHQL 23 | end 24 | 25 | before do 26 | create(:refresh_token, user: user, token: substitution_token_value, original_token: current_refresh_token) 27 | end 28 | 29 | it_behaves_like "graphql request", "returns updated user token" do 30 | let(:fixture_path) { "json/acceptance/graphql/mutations/update_token_existing.json" } 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /spec/graphql/mutations/update_token_invalid_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe Mutations::UpdateToken do 4 | include_context "when time is frozen" 5 | 6 | let(:schema_context) { { current_user: user, token: valid_access_token.token } } 7 | let(:user) { create(:user) } 8 | let(:valid_access_token) { build(:access_token, user_id: user.id) } 9 | 10 | let(:query) do 11 | <<-GRAPHQL 12 | mutation { 13 | updateToken { 14 | me { 15 | id 16 | } 17 | accessToken 18 | refreshToken 19 | } 20 | } 21 | GRAPHQL 22 | end 23 | 24 | it_behaves_like "graphql request", "returns error" do 25 | let(:fixture_path) { "json/acceptance/graphql/mutations/update_token_invalid.json" } 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /spec/graphql/mutations/update_token_not_unique_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe Mutations::UpdateToken do 4 | include_context "when time is frozen" 5 | 6 | let(:schema_context) { { current_user: user, token: current_refresh_token.token } } 7 | let(:user) { create(:user, id: 111_111) } 8 | let(:current_refresh_token) { create(:refresh_token, user: user) } 9 | 10 | let(:query) do 11 | <<-GRAPHQL 12 | mutation { 13 | updateToken { 14 | me { 15 | id 16 | } 17 | accessToken 18 | refreshToken 19 | } 20 | } 21 | GRAPHQL 22 | end 23 | 24 | before do 25 | create(:refresh_token, user: user, jti: current_refresh_token.jti, expires_at: 30.days.since) 26 | end 27 | 28 | it_behaves_like "graphql request", "returns error" do 29 | let(:fixture_path) { "json/acceptance/graphql/mutations/update_token_invalid.json" } 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /spec/graphql/mutations/update_token_valid_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe Mutations::UpdateToken do 4 | include_context "when time is frozen" 5 | 6 | let(:schema_context) { { token: refresh_token.token } } 7 | let(:user) { create(:user, id: 111_111) } 8 | let(:refresh_token) { create(:refresh_token, user: user, jti: "46d300ea39ab466d79586a856a41ee32") } 9 | 10 | let(:query) do 11 | <<-GRAPHQL 12 | mutation{ 13 | updateToken { 14 | accessToken 15 | refreshToken 16 | } 17 | } 18 | GRAPHQL 19 | end 20 | 21 | it_behaves_like "graphql request", "returns updated user token" do 22 | let(:fixture_path) { "json/acceptance/graphql/mutations/update_token_valid.json" } 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /spec/graphql/mutations/update_user_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe Mutations::UpdateUser do 4 | let(:schema_context) { { current_user: user } } 5 | let(:user) { create(:user, password: "123456") } 6 | let(:uploader) { ImageUploader.new(:cache) } 7 | let(:avatar_image_path) { Rails.root.join("spec/fixtures/images/avatar.jpg") } 8 | let(:uploaded_file) { uploader.upload(File.open(avatar_image_path, binmode: true)) } 9 | let(:avatar_id) { uploaded_file.id } 10 | 11 | let(:query) do 12 | <<-GRAPHQL 13 | mutation { 14 | updateUser ( 15 | input: { 16 | email: "new_email_11@example.com", 17 | firstName: "Randle", 18 | lastName: "McMurphy", 19 | currentPassword: "123456", 20 | password: "qwerty", 21 | avatar: { 22 | id: "#{avatar_id}", 23 | metadata: { 24 | size: 1098178, 25 | filename: "avatar.jpg", 26 | mimeType: "image/jpg" 27 | } 28 | } 29 | } 30 | ) { 31 | me { 32 | id 33 | email 34 | firstName 35 | lastName 36 | avatarUrl 37 | } 38 | } 39 | } 40 | GRAPHQL 41 | end 42 | 43 | it_behaves_like "graphql request", "returns updated user info" do 44 | let(:fixture_path) { "json/acceptance/graphql/update_user.json" } 45 | 46 | let(:prepared_fixture_file) do 47 | fixture_file.gsub( 48 | /:id|:avatar_url/, 49 | ":id" => user.id, 50 | ":avatar_url" => user.avatar.url 51 | ) 52 | end 53 | end 54 | end 55 | -------------------------------------------------------------------------------- /spec/graphql/types/activity_type_n_plus_one_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe Types::ActivityType, :n_plus_one do 4 | let!(:user) { create(:user) } 5 | 6 | let(:query) do 7 | <<-GRAPHQL 8 | query { 9 | activities { 10 | edges { 11 | cursor 12 | node { 13 | id 14 | user { 15 | id 16 | } 17 | } 18 | } 19 | } 20 | } 21 | GRAPHQL 22 | end 23 | 24 | populate { |n| create_list(:activity, n, user: user) } 25 | 26 | include_examples "performs constant number of queries request" 27 | end 28 | -------------------------------------------------------------------------------- /spec/graphql/types/query_type_me_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe Types::QueryType do 4 | let(:schema_context) { { current_user: user } } 5 | let!(:user) { create(:user, :with_data) } 6 | 7 | let(:query) do 8 | <<-GRAPHQL 9 | query { 10 | me { 11 | id 12 | email 13 | firstName 14 | lastName 15 | } 16 | } 17 | GRAPHQL 18 | end 19 | 20 | context "with user" do 21 | it_behaves_like "graphql request", "gets current_user info" do 22 | let(:fixture_path) { "json/acceptance/graphql/query_type_me.json" } 23 | let(:prepared_fixture_file) do 24 | fixture_file.gsub( 25 | /:id|:email|:first_name|:last_name/, 26 | ":id" => user.id, 27 | ":email" => user.email, 28 | ":first_name" => user.first_name, 29 | ":last_name" => user.last_name 30 | ) 31 | end 32 | end 33 | 34 | context "with activities query" do 35 | let!(:activity) { create(:activity, user: user, event: :user_updated) } 36 | let(:query) do 37 | <<-GRAPHQL 38 | query { 39 | me { 40 | id 41 | email 42 | firstName 43 | lastName 44 | activities(events: [USER_UPDATED]){ 45 | edges { 46 | node { 47 | id 48 | event 49 | } 50 | } 51 | } 52 | } 53 | } 54 | GRAPHQL 55 | end 56 | 57 | before do 58 | create(:activity, event: :user_updated) 59 | end 60 | 61 | it_behaves_like "graphql request", "gets current_user info" do 62 | let(:fixture_path) { "json/acceptance/graphql/query_type_me_with_activities.json" } 63 | let(:prepared_fixture_file) do 64 | fixture_file.gsub( 65 | /:id|:activity_id/, 66 | ":id" => user.id, 67 | ":activity_id" => activity.id 68 | ) 69 | end 70 | end 71 | end 72 | end 73 | 74 | context "without user" do 75 | it_behaves_like "graphql request", "gets current_user info" do 76 | let(:schema_context) { { current_user: nil } } 77 | let(:fixture_path) { "json/acceptance/graphql/query_type_me_unauthorized.json" } 78 | end 79 | end 80 | end 81 | -------------------------------------------------------------------------------- /spec/interactors/authenticate_by_email_and_password_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe AuthenticateByEmailAndPassword do 4 | include_context "with interactor" 5 | 6 | let(:initial_context) do 7 | { email: "user@flatstack.com", password: password } 8 | end 9 | 10 | let!(:user) { create(:user, email: "user@flatstack.com", password: "password") } 11 | 12 | describe ".call" do 13 | context "with valid credentials" do 14 | let(:password) { "password" } 15 | 16 | it_behaves_like "success interactor" 17 | 18 | it "provides user instance" do 19 | interactor.run 20 | 21 | expect(context.user).to eq(user) 22 | end 23 | end 24 | 25 | context "with invalid credentials" do 26 | let(:password) { "wrong_password" } 27 | let(:error_data) do 28 | { 29 | message: "Invalid credentials", 30 | status: 401, 31 | code: :unauthorized 32 | } 33 | end 34 | 35 | it_behaves_like "failed interactor" 36 | end 37 | end 38 | end 39 | -------------------------------------------------------------------------------- /spec/interactors/authenticate_by_google_auth_code_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe AuthenticateByGoogleAuthCode do 4 | subject { described_class.organized } 5 | 6 | let(:expected_interactors) do 7 | [ 8 | Omniauth::Google::BuildAuthClient, 9 | Omniauth::Google::ExchangeAuthCode, 10 | Omniauth::Google::FetchUserInfo, 11 | Omniauth::Google::FindOrCreateUser 12 | ] 13 | end 14 | 15 | it { is_expected.to eq(expected_interactors) } 16 | end 17 | -------------------------------------------------------------------------------- /spec/interactors/confirm_user_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe ConfirmUser do 4 | describe ".call" do 5 | include_context "with interactor" 6 | include_context "when time is frozen" 7 | 8 | let(:user) { create(:user, password: "123456") } 9 | let(:possession_token) { create(:possession_token, user: user) } 10 | let(:initial_context) { { user: user, value: possession_token.value } } 11 | let(:confirmed_at) { Time.current } 12 | 13 | context "with valid data" do 14 | let(:user_id) { user.id } 15 | let(:event) { :user_updated } 16 | 17 | it_behaves_like "success interactor" 18 | 19 | it "updates user" do 20 | interactor.run 21 | 22 | expect(user).to have_attributes( 23 | confirmed_at: confirmed_at 24 | ) 25 | 26 | expect(PossessionToken.count).to be_zero 27 | end 28 | end 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /spec/interactors/create_access_token_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe CreateAccessToken do 4 | include_context "with interactor" 5 | include_context "when time is frozen" 6 | 7 | let(:initial_context) { { user: user, jti: jti } } 8 | let(:user) { create(:user, id: 111_111) } 9 | 10 | describe ".call" do 11 | context "with existing jti" do 12 | let(:jti) { "existing_token_jti" } 13 | let(:expected_jti) { "existing_token_jti" } 14 | let(:expected_token_payload) do 15 | { 16 | "sub" => 111_111, 17 | "exp" => 1_589_117_400, 18 | "jti" => "existing_token_jti", 19 | "type" => "access" 20 | } 21 | end 22 | 23 | it_behaves_like "success interactor" 24 | 25 | it "provides previous token jti" do 26 | interactor.run 27 | 28 | expect(context.jti).to eq(expected_jti) 29 | end 30 | 31 | it "generates access token with correct payload" do 32 | interactor.run 33 | 34 | expect(context.access_token).to have_jwt_token_payload(expected_token_payload) 35 | end 36 | end 37 | 38 | context "with generate jti" do 39 | let(:jti) { nil } 40 | let(:expected_jti) { "7fc6d21913811be48db74417f9a26598" } 41 | let(:expected_token_payload) do 42 | { 43 | "sub" => 111_111, 44 | "exp" => 1_589_117_400, 45 | "jti" => "7fc6d21913811be48db74417f9a26598", 46 | "type" => "access" 47 | } 48 | end 49 | 50 | it_behaves_like "success interactor" 51 | 52 | it "generates new access token jti" do 53 | interactor.run 54 | 55 | expect(context.jti).to eq(expected_jti) 56 | end 57 | 58 | it "generates access token with correct payload" do 59 | interactor.run 60 | 61 | expect(context.access_token).to have_jwt_token_payload(expected_token_payload) 62 | end 63 | end 64 | end 65 | end 66 | -------------------------------------------------------------------------------- /spec/interactors/create_possession_token_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe CreatePossessionToken do 4 | include_context "with interactor" 5 | include_context "when time is frozen" 6 | 7 | let(:initial_context) { { user: user } } 8 | let(:user) { create(:user, id: 111_111) } 9 | 10 | let(:possession_token_length) { 80 } 11 | let(:saved_possession_token) { PossessionToken.last } 12 | 13 | let(:possession_token_attributes) do 14 | { 15 | user_id: 111_111 16 | } 17 | end 18 | 19 | describe ".call" do 20 | it_behaves_like "success interactor" 21 | 22 | it "creates possession token" do 23 | expect { interactor.run }.to change(PossessionToken, :count).by(1) 24 | expect(saved_possession_token).to have_attributes(possession_token_attributes) 25 | end 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /spec/interactors/create_refresh_token_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe CreateRefreshToken do 4 | include_context "with interactor" 5 | include_context "when time is frozen" 6 | 7 | let(:initial_context) { { user: user, jti: "jti", substitution_token: substitution_token } } 8 | 9 | let(:user) { create(:user, id: 111_111) } 10 | let(:refresh_token) { build(:refresh_token, user: user, jti: "jti", expires_at: 30.days.since) } 11 | let(:created_refresh_token) { RefreshToken.last } 12 | let(:substitution_token) { nil } 13 | 14 | let(:expected_refresh_token_attributes) do 15 | { 16 | user_id: 111_111, 17 | token: refresh_token.token, 18 | jti: "jti", 19 | expires_at: 30.days.since 20 | } 21 | end 22 | 23 | describe ".call" do 24 | it_behaves_like "success interactor" 25 | 26 | it "provides generated refresh token" do 27 | interactor.run 28 | 29 | expect(context.refresh_token).to eq(refresh_token.token) 30 | end 31 | 32 | it "creates refresh token" do 33 | expect { interactor.run }.to change(RefreshToken, :count).from(0).to(1) 34 | end 35 | 36 | it "creates refresh token with correct attributes" do 37 | interactor.run 38 | 39 | expect(created_refresh_token).to have_attributes(expected_refresh_token_attributes) 40 | end 41 | 42 | context "when substitution token provided" do 43 | let(:substitution_token) { create(:refresh_token, user: user, token: "substitution_token_value") } 44 | 45 | it_behaves_like "success interactor" 46 | 47 | it "provides refresh token" do 48 | interactor.run 49 | 50 | expect(context.refresh_token).to eq("substitution_token_value") 51 | end 52 | 53 | it "does not create refresh token" do 54 | interactor.run 55 | 56 | expect(user.refresh_tokens.count).to eq(1) 57 | end 58 | end 59 | end 60 | end 61 | -------------------------------------------------------------------------------- /spec/interactors/create_user_activity_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe CreateUserActivity do 4 | include_context "with interactor" 5 | 6 | let(:initial_context) { { user: user, event: :user_registered } } 7 | let(:user) { create(:user, first_name: "John", last_name: "Doe") } 8 | let(:activity) { user.activities.last } 9 | 10 | describe ".call" do 11 | it_behaves_like "success interactor" 12 | 13 | it "creates registered activity" do 14 | expect { interactor.run }.to change { user.activities.count }.by(1) 15 | 16 | expect(activity).to have_attributes( 17 | event: "user_registered", 18 | title: "User Registered", 19 | body: <<~TXT 20 | New user registered with the next attributes: 21 | First name - John, 22 | Last name - Doe 23 | TXT 24 | ) 25 | end 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /spec/interactors/create_user_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe CreateUser do 4 | include_context "with interactor" 5 | 6 | let(:initial_context) { { user_params: user_params } } 7 | 8 | describe ".call" do 9 | context "with valid data" do 10 | let(:user_params) do 11 | { 12 | email: "user@example.com", password: "password", 13 | first_name: "Bilbo", last_name: "Baggings" 14 | } 15 | end 16 | 17 | it_behaves_like "success interactor" 18 | 19 | it "creates user" do 20 | interactor.run 21 | 22 | expect(context.user).to be_persisted 23 | expect(context.user).to have_attributes( 24 | email: "user@example.com", 25 | password: "password", 26 | first_name: "Bilbo", 27 | last_name: "Baggings" 28 | ) 29 | end 30 | end 31 | 32 | context "with invalid data" do 33 | let(:user_params) do 34 | { email: "user", password: "" } 35 | end 36 | let(:error_data) do 37 | { message: "Record Invalid", detail: ["Password can't be blank", "Email is invalid"] } 38 | end 39 | 40 | it_behaves_like "failed interactor" 41 | end 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /spec/interactors/find_refresh_token_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe FindRefreshToken do 4 | include_context "with interactor" 5 | 6 | let(:initial_context) { { token: jwt_token } } 7 | let(:user) { create(:user, id: 111_111) } 8 | let!(:another_refresh_token) { create(:refresh_token, token: "another_token", jti: "jti") } 9 | 10 | let(:error_data) do 11 | { message: "Invalid credentials", status: 401, code: :unauthorized } 12 | end 13 | 14 | describe ".call" do 15 | context "with empty token" do 16 | let(:jwt_token) { nil } 17 | 18 | it_behaves_like "failed interactor" 19 | end 20 | 21 | context "with invalid token" do 22 | let(:jwt_token) { "fake_token" } 23 | 24 | it_behaves_like "failed interactor" 25 | end 26 | 27 | context "with valid access token" do 28 | let(:access_token) { build(:access_token) } 29 | let(:jwt_token) { access_token.token } 30 | 31 | it_behaves_like "failed interactor" 32 | end 33 | 34 | context "with does not persisted valid refresh token" do 35 | let(:refresh_token) { build(:refresh_token, user: user) } 36 | let(:jwt_token) { refresh_token.token } 37 | 38 | it_behaves_like "failed interactor" 39 | end 40 | 41 | context "with persisted valid refresh token" do 42 | let(:refresh_token) { create(:refresh_token, user: user, substitution_token: substitution_token) } 43 | let(:jwt_token) { refresh_token.token } 44 | let(:substitution_token) { nil } 45 | 46 | it_behaves_like "success interactor" 47 | 48 | it "sets context jti" do 49 | interactor.run 50 | 51 | expect(context.jti).to eq(refresh_token.jti) 52 | end 53 | 54 | it "sets context user" do 55 | interactor.run 56 | 57 | expect(context.user).to eq(user) 58 | end 59 | 60 | it "provides refresh token" do 61 | interactor.run 62 | 63 | expect(context.existing_refresh_token).to eq(refresh_token) 64 | end 65 | 66 | it "does not provide substituting refresh token" do 67 | interactor.run 68 | 69 | expect(context.substitution_token).to be_nil 70 | end 71 | end 72 | 73 | context "with valid refresh token and substituting token" do 74 | let(:refresh_token) { create(:refresh_token, user: user, substitution_token: substitution_token) } 75 | let(:jwt_token) { refresh_token.token } 76 | let(:substitution_token) { another_refresh_token } 77 | 78 | it "provides substituting refresh token" do 79 | interactor.run 80 | 81 | expect(context.substitution_token).to eq(another_refresh_token) 82 | end 83 | end 84 | 85 | context "with valid expired refresh token" do 86 | let(:refresh_token) { create(:refresh_token, :expired, user: user) } 87 | let(:jwt_token) { refresh_token.token } 88 | 89 | it_behaves_like "failed interactor" 90 | end 91 | end 92 | end 93 | -------------------------------------------------------------------------------- /spec/interactors/omniauth/google/build_auth_client_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe Omniauth::Google::BuildAuthClient do 4 | subject(:context) { described_class.call(auth_code: auth_code) } 5 | 6 | let(:expected_attributes) do 7 | { 8 | access_token: nil, 9 | access_type: :offline, 10 | additional_parameters: {}, 11 | authorization_uri: expected_authorization_uri, 12 | client_id: "google_client_id", 13 | client_secret: "google_client_secret", 14 | code: "random_authorization_code", 15 | expires_at: nil, 16 | expiry: 60, 17 | extension_parameters: {}, 18 | id_token: nil, 19 | issued_at: nil, 20 | issuer: nil, 21 | password: nil, 22 | principal: nil, 23 | redirect_uri: expected_redirect_uri, 24 | refresh_token: nil, 25 | scope: nil, 26 | state: nil, 27 | target_audience: nil, 28 | token_credential_uri: expected_token_credential_uri, 29 | username: nil 30 | } 31 | end 32 | let(:expected_authorization_uri) do 33 | Addressable::URI.parse("https://accounts.google.com/o/oauth2/auth?" \ 34 | "access_type=offline&" \ 35 | "client_id=google_client_id&" \ 36 | "redirect_uri=postmessage&" \ 37 | "response_type=code") 38 | end 39 | let(:expected_redirect_uri) { Addressable::URI.parse("postmessage") } 40 | let(:expected_token_credential_uri) { Addressable::URI.parse("https://oauth2.googleapis.com/token") } 41 | let(:auth_code) { "random_authorization_code" } 42 | 43 | describe ".call" do 44 | it "builds auth client" do 45 | context 46 | expect(context.auth_client).to be_instance_of(Signet::OAuth2::Client) 47 | expect(context.auth_client).to have_attributes(expected_attributes) 48 | end 49 | end 50 | end 51 | -------------------------------------------------------------------------------- /spec/interactors/omniauth/google/exchange_auth_code_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe Omniauth::Google::ExchangeAuthCode do 4 | subject(:context) { described_class.call(auth_client: auth_client_double) } 5 | 6 | let(:auth_client_double) { instance_double Signet::OAuth2::Client } 7 | 8 | before do 9 | allow(auth_client_double).to receive(:fetch_access_token!) 10 | end 11 | 12 | describe ".call" do 13 | it "exchanges auth code to access token and refresh token" do 14 | expect(context).to be_success 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /spec/interactors/omniauth/google/fetch_user_info_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | require "google/apis/oauth2_v2" 3 | 4 | describe Omniauth::Google::FetchUserInfo do 5 | subject(:context) { described_class.call(auth_client: auth_client_double) } 6 | 7 | let(:auth_client_double) { instance_double Signet::OAuth2::Client } 8 | let(:oauth_2_service_double) { instance_double Google::Apis::Oauth2V2::Oauth2Service } 9 | let(:userinfo_double) { instance_double Google::Apis::Oauth2V2::Userinfo } 10 | let(:expected_options) { { options: { authorization: auth_client_double } } } 11 | 12 | before do 13 | allow(Google::Apis::Oauth2V2::Oauth2Service).to receive(:new).and_return(oauth_2_service_double) 14 | allow(oauth_2_service_double).to receive(:get_userinfo).with(expected_options).and_return(userinfo_double) 15 | end 16 | 17 | describe ".call" do 18 | it "exchanges auth code to access token and refresh token" do 19 | expect(context.user_info).to be(userinfo_double) 20 | end 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /spec/interactors/omniauth/google/find_or_create_user_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | require "google/apis/oauth2_v2" 3 | 4 | describe Omniauth::Google::FindOrCreateUser do 5 | include_context "with interactor" 6 | 7 | let(:initial_context) { { user_info: user_info } } 8 | 9 | let(:user_info) do 10 | instance_double Google::Apis::Oauth2V2::Userinfo, given_name: "FirstName", 11 | family_name: "LastName", 12 | email: "user@flatstack.com", 13 | picture: "spec/fixtures/images/avatar.jpg" 14 | end 15 | 16 | describe ".call" do 17 | context "when user not exists" do 18 | it "creates user" do 19 | interactor.run 20 | 21 | expect(context.user).to have_attributes( 22 | first_name: "FirstName", 23 | last_name: "LastName", 24 | email: "user@flatstack.com" 25 | ) 26 | 27 | expect(context.user.avatar_url).not_to be_nil 28 | 29 | expect(context.user).to be_persisted 30 | end 31 | end 32 | 33 | context "when user exists" do 34 | let!(:user) { create(:user, email: "user@flatstack.com", first_name: "Carlee", last_name: "Eleanor") } 35 | 36 | it "creates user" do 37 | interactor.run 38 | 39 | expect(context.user).to have_attributes( 40 | first_name: "Carlee", 41 | last_name: "Eleanor", 42 | email: "user@flatstack.com" 43 | ) 44 | 45 | expect(context.user).to be_persisted 46 | expect(context.user).to eq user 47 | end 48 | end 49 | end 50 | end 51 | -------------------------------------------------------------------------------- /spec/interactors/omniauth_authenticate_user_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe OmniauthAuthenticateUser do 4 | include_context "with interactor" 5 | 6 | let(:initial_context) do 7 | { auth_code: auth_code } 8 | end 9 | 10 | let!(:user) { create(:user, email: "user@flatstack.com", password: "password") } 11 | 12 | describe ".call" do 13 | let(:expected_context) { Interactor::Context.new(user: user) } 14 | 15 | context "with Google auth" do 16 | let(:auth_code) { "token" } 17 | 18 | before do 19 | allow(AuthenticateByGoogleAuthCode).to receive(:call).and_return(expected_context) 20 | end 21 | 22 | it_behaves_like "success interactor" 23 | 24 | it "provides user instance" do 25 | expect(AuthenticateByGoogleAuthCode) 26 | .to receive(:call).with(auth_code: auth_code) 27 | 28 | interactor.run 29 | end 30 | end 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /spec/interactors/prepare_presign_image_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe PreparePresignImage do 4 | include_context "with interactor" 5 | 6 | let(:initial_context) { { filename: filename, type: file_type } } 7 | let(:filename) { "avatar.png" } 8 | 9 | describe ".call" do 10 | context "with valid data" do 11 | let(:file_type) { "image/png" } 12 | let(:s3_storage) { instance_double(Shrine::Storage::S3, presign: presign_data) } 13 | let(:presign_data) { { url: "http://some-url.com", fields: { key: :value } } } 14 | 15 | before do 16 | allow(Shrine).to receive(:find_storage).and_return(s3_storage) 17 | end 18 | 19 | it_behaves_like "success interactor" 20 | end 21 | 22 | context "with invalid data" do 23 | let(:file_type) { "wrong_type" } 24 | let(:error_data) do 25 | { message: "Wrong file type", status: 415, code: :unsupported_media_type } 26 | end 27 | 28 | it_behaves_like "failed interactor" 29 | end 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /spec/interactors/request_password_reset_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe RequestPasswordReset do 4 | include_context "with interactor" 5 | include_context "with mail delivery stubbed" 6 | 7 | let(:initial_context) { { email: user.email } } 8 | 9 | before do 10 | allow(ApplicationMailer).to receive(:password_recovery).and_return(delivery) 11 | end 12 | 13 | context "when user exists" do 14 | let(:user) { create(:user) } 15 | let(:user_id) { user.id } 16 | let(:event) { :reset_password_requested } 17 | 18 | it_behaves_like "success interactor" 19 | 20 | it "sends email" do 21 | expect(ApplicationMailer).to receive(:password_recovery) 22 | interactor.run 23 | end 24 | 25 | it_behaves_like "activity source" 26 | end 27 | 28 | context "when user doesn't exist" do 29 | let(:user) { build(:user, email: "user@test.it") } 30 | let(:error_data) { { message: "Record not found", detail: "User with email user@test.it not found" } } 31 | 32 | it_behaves_like "failed interactor" 33 | 34 | it "doesn't send email" do 35 | expect(ApplicationMailer).not_to receive(:password_recovery) 36 | interactor.run 37 | end 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /spec/interactors/signin_user_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe SigninUser do 4 | describe "#after" do 5 | let(:user_id) { 213_689 } 6 | let(:user) { create(:user, id: user_id) } 7 | let(:initial_context) { { user: user } } 8 | let(:event) { :user_logged_in } 9 | 10 | context "when organizer succeeds" do 11 | include_context "with stubbed organizer" 12 | 13 | it_behaves_like "activity source" 14 | end 15 | 16 | context "when organizer failures" do 17 | include_context "with stubbed organizer", failure: true 18 | 19 | it "does not schedule create activity job" do 20 | expect { interactor.run }.not_to have_enqueued_job(RegisterActivityJob) 21 | end 22 | end 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /spec/interactors/signout_user_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe SignoutUser do 4 | include_context "with interactor" 5 | 6 | let(:initial_context) do 7 | { 8 | user: user, 9 | everywhere: everywhere, 10 | token: "token" 11 | } 12 | end 13 | let(:refresh_token) { create(:refresh_token, user: user) } 14 | let(:user) { create(:user) } 15 | 16 | before do 17 | create(:refresh_token, token: "other", user: user) 18 | end 19 | 20 | describe ".call" do 21 | context "when everywhere is false" do 22 | let(:everywhere) { false } 23 | 24 | it "removes refresh token" do 25 | interactor.run 26 | 27 | expect(user.refresh_tokens.count).to eq(1) 28 | end 29 | end 30 | 31 | context "when everywhere is true" do 32 | let(:everywhere) { true } 33 | 34 | it "removes all refresh tokens" do 35 | interactor.run 36 | 37 | expect(user.refresh_tokens.count).to be_zero 38 | end 39 | end 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /spec/interactors/signup_user_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe SignupUser do 4 | describe "#after" do 5 | let(:user_id) { 213_689 } 6 | let(:user) { create(:user, id: user_id) } 7 | let(:initial_context) { { user: user } } 8 | let(:event) { :user_registered } 9 | 10 | context "when organizer succeeds" do 11 | include_context "with stubbed organizer" 12 | 13 | it_behaves_like "activity source" 14 | end 15 | 16 | context "when organizer failures" do 17 | include_context "with stubbed organizer", failure: true 18 | 19 | it "does not schedule create activity job" do 20 | expect { interactor.run }.not_to have_enqueued_job(RegisterActivityJob) 21 | end 22 | end 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /spec/interactors/update_existing_refresh_token_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe UpdateExistingRefreshToken do 4 | include_context "with interactor" 5 | include_context "when time is frozen" 6 | 7 | let(:initial_context) do 8 | { 9 | existing_refresh_token: refresh_token, 10 | substitution_token: substitution_token 11 | } 12 | end 13 | let(:refresh_token) { create(:refresh_token) } 14 | let(:substitution_token) { create(:refresh_token, token: "subtoken") } 15 | 16 | describe ".call" do 17 | it "updates existing refresh token attributes" do 18 | interactor.run 19 | 20 | expect(refresh_token).to have_attributes( 21 | substitution_token: substitution_token, 22 | expires_at: "2020-05-10 12:31:00".to_datetime 23 | ) 24 | end 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /spec/interactors/update_password_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe UpdatePassword do 4 | include_context "with interactor" 5 | 6 | let(:user) { create(:user, :with_reset_token) } 7 | let(:initial_context) { { password: "123456", reset_token: reset_token } } 8 | 9 | context "when token valid" do 10 | let(:reset_token) { user.password_reset_token } 11 | let(:user_id) { user.id } 12 | let(:event) { :user_reset_password } 13 | 14 | it_behaves_like "success interactor" 15 | 16 | it "clears password_reset_* attributes" do 17 | interactor.run 18 | 19 | expect(user.reload).to have_attributes( 20 | password_reset_token: nil, 21 | password_reset_sent_at: nil 22 | ) 23 | end 24 | 25 | it_behaves_like "activity source" 26 | end 27 | 28 | context "when token is wrong" do 29 | let(:reset_token) { "wrong-token" } 30 | let(:error_data) do 31 | { 32 | message: "Invalid credentials", 33 | status: 401, 34 | code: :unauthorized 35 | } 36 | end 37 | 38 | it_behaves_like "failed interactor" 39 | end 40 | 41 | context "when token has expired" do 42 | let(:expiration_time) { user.password_reset_sent_at + 15.minutes + 1 } 43 | let(:reset_token) { user.password_reset_token } 44 | let(:error_data) do 45 | { 46 | message: "Record Invalid", 47 | detail: ["Password reset sent at has expired"] 48 | } 49 | end 50 | 51 | before do 52 | travel_to expiration_time 53 | freeze_time 54 | end 55 | 56 | it_behaves_like "failed interactor" 57 | end 58 | end 59 | -------------------------------------------------------------------------------- /spec/interactors/update_token_pair_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe UpdateTokenPair do 4 | include_context "with interactor" 5 | include_context "when time is frozen" 6 | 7 | let(:initial_context) { { token: refresh_token.token } } 8 | let(:user) { create(:user, id: 111_111) } 9 | let!(:refresh_token) do 10 | create(:refresh_token, user: user, 11 | jti: "46d300ea39ab466d79586a856a41ee32", 12 | substitution_token: substitution_token) 13 | end 14 | let(:substitution_token) { nil } 15 | let(:created_refresh_token) { RefreshToken.last } 16 | 17 | describe ".call" do 18 | context "with valid refresh token" do 19 | it_behaves_like "success interactor" 20 | 21 | it "creates new access token" do 22 | interactor.run 23 | 24 | expect(context.access_token).to be_present 25 | end 26 | 27 | it "creates new refresh token" do 28 | expect { interactor.run }.to change(RefreshToken, :count).by(1) 29 | end 30 | 31 | it "creates refresh token with correct attributes" do 32 | interactor.run 33 | 34 | expect(created_refresh_token).to have_attributes( 35 | user_id: user.id, 36 | expires_at: 30.days.from_now, 37 | jti: refresh_token.jti 38 | ) 39 | end 40 | end 41 | 42 | context "when refresh token has substitution token" do 43 | let(:substitution_token) { create(:refresh_token, token: "substitution_token") } 44 | 45 | it_behaves_like "success interactor" 46 | 47 | it "creates new access token" do 48 | interactor.run 49 | 50 | expect(context.access_token).to be_present 51 | end 52 | 53 | it "provides substitution token as a new refresh token" do 54 | interactor.run 55 | 56 | expect(context.refresh_token).to eq("substitution_token") 57 | end 58 | 59 | it "does not create new refresh token" do 60 | expect { interactor.run }.not_to change(RefreshToken, :count) 61 | end 62 | end 63 | end 64 | end 65 | -------------------------------------------------------------------------------- /spec/interactors/update_user_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe UpdateUser do 4 | describe ".call" do 5 | include_context "with interactor" 6 | 7 | let(:user) { create(:user, password: "123456") } 8 | let(:initial_context) { { user: user, user_params: user_params } } 9 | 10 | context "with valid data" do 11 | let(:user_params) { { email: "dent@gmail.com", first_name: "Arthur", last_name: "Dent" } } 12 | let(:user_id) { user.id } 13 | let(:event) { :user_updated } 14 | 15 | it_behaves_like "success interactor" 16 | 17 | it "updates user" do 18 | interactor.run 19 | 20 | expect(user).to have_attributes( 21 | email: "dent@gmail.com", 22 | first_name: "Arthur", 23 | last_name: "Dent" 24 | ) 25 | end 26 | 27 | it_behaves_like "activity source" 28 | end 29 | 30 | context "when updating password" do 31 | let(:user_params) { { current_password: "123456", password: "qwerty" } } 32 | 33 | it_behaves_like "success interactor" 34 | 35 | it "updates password" do 36 | interactor.run 37 | 38 | expect(user.authenticate("qwerty")).to be_truthy 39 | end 40 | end 41 | 42 | context "when no old password provided" do 43 | let(:user_params) { { password: "qwerty" } } 44 | let(:error_data) do 45 | { 46 | message: "Record Invalid", 47 | detail: ["Current password is incorrect", "Current password can't be blank"] 48 | } 49 | end 50 | 51 | it_behaves_like "failed interactor" 52 | end 53 | 54 | context "when wrong old password provided" do 55 | let(:user_params) { { current_password: "123457", password: "qwerty" } } 56 | let(:error_data) { { message: "Record Invalid", detail: ["Current password is incorrect"] } } 57 | 58 | it_behaves_like "failed interactor" 59 | end 60 | end 61 | end 62 | -------------------------------------------------------------------------------- /spec/jobs/register_activity_job_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe RegisterActivityJob do 4 | let(:user_id) { 570_242 } 5 | 6 | context "when user exists" do 7 | let!(:user) { create(:user, id: user_id) } 8 | 9 | it "calls interactor to create activity" do 10 | expect(CreateUserActivity).to receive(:call!).with(user: user, event: :user_registered) 11 | 12 | described_class.perform_now(user_id, :user_registered) 13 | end 14 | end 15 | 16 | context "when user does not exist" do 17 | it "raises" do 18 | expect { described_class.perform_now(user_id, :user_registered) }.to raise_error(ActiveRecord::RecordNotFound) 19 | end 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /spec/mailers/application_mailer_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe ApplicationMailer do 4 | describe "#password_recovery" do 5 | subject(:email) { described_class.password_recovery(user) } 6 | 7 | let(:user) { build(:user, password_reset_token: "1234") } 8 | 9 | it { is_expected.to deliver_to(user.email) } 10 | 11 | it "delivers the token" do 12 | expect(email.html).to include(user.password_reset_token) 13 | end 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /spec/mailers/previews/application_mailer_preview.rb: -------------------------------------------------------------------------------- 1 | class ApplicationMailerPreview < ActionMailer::Preview 2 | def password_recovery 3 | ApplicationMailer.password_recovery( 4 | FactoryBot.build(:user, password_reset_token: "1234") 5 | ) 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /spec/policies/activity_policy_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe ActivityPolicy do 4 | let(:context) { { user: user } } 5 | let(:user) { create(:user) } 6 | 7 | describe "#relation_scope" do 8 | subject { policy.apply_scope(Activity.all, type: :active_record_relation) } 9 | 10 | let!(:own_private_event) { create(:activity, :private, user: user) } 11 | 12 | before do 13 | create(:activity, :public) 14 | create(:activity, :private) 15 | end 16 | 17 | it { is_expected.to contain_exactly(own_private_event) } 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /spec/query_objects/filtered_activities_query_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "rails_helper" 4 | 5 | describe FilteredActivitiesQuery do 6 | subject(:query) { described_class.new(Activity.all, filter_params) } 7 | 8 | let!(:first_activity) { create(:activity) } 9 | let!(:second_activity) { create(:activity, event: :user_updated) } 10 | 11 | let(:filter_params) { {} } 12 | 13 | describe "#all" do 14 | subject(:all) { query.all } 15 | 16 | it { is_expected.to contain_exactly(first_activity, second_activity) } 17 | 18 | context "when param is user_updated" do 19 | let(:filter_params) { { events: [:user_updated] } } 20 | 21 | it { is_expected.to contain_exactly(second_activity) } 22 | end 23 | 24 | context "when param is empty" do 25 | let(:filter_params) { { events: [] } } 26 | 27 | it { is_expected.to be_empty } 28 | end 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /spec/rails_helper.rb: -------------------------------------------------------------------------------- 1 | ENV["RAILS_ENV"] ||= "test" 2 | 3 | require File.expand_path("../config/environment", __dir__) 4 | require "rspec/rails" 5 | require "simplecov" 6 | require "spec_helper" 7 | require "email_spec" 8 | require "email_spec/rspec" 9 | 10 | SimpleCov.start "rails" 11 | 12 | Dir[Rails.root.join("spec/support/**/*.rb")].sort.each { |f| require f } 13 | 14 | RSpec.configure do |config| 15 | config.fixture_path = Rails.root.join("spec/fixtures") 16 | end 17 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration 2 | require "active_support/testing/time_helpers" 3 | require "action_policy/rspec/dsl" 4 | require "n_plus_one_control/rspec" 5 | 6 | RSpec.configure do |config| 7 | config.include ActiveSupport::Testing::TimeHelpers 8 | end 9 | -------------------------------------------------------------------------------- /spec/support/active_job.rb: -------------------------------------------------------------------------------- 1 | RSpec.configure do |config| 2 | config.include ActiveJob::TestHelper 3 | 4 | config.before do 5 | ActiveJob::Base.queue_adapter.enqueued_jobs.clear 6 | ActiveJob::Base.queue_adapter.performed_jobs.clear 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /spec/support/database_cleaner.rb: -------------------------------------------------------------------------------- 1 | RSpec.configure do |config| 2 | config.before(:suite) do 3 | DatabaseCleaner.strategy = :transaction 4 | DatabaseCleaner.clean_with(:truncation) 5 | end 6 | 7 | config.around do |example| 8 | DatabaseCleaner.cleaning do 9 | example.run 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /spec/support/factory_bot.rb: -------------------------------------------------------------------------------- 1 | RSpec.configure do |config| 2 | config.include FactoryBot::Syntax::Methods 3 | end 4 | -------------------------------------------------------------------------------- /spec/support/matchers/have_jwt_token_payload.rb: -------------------------------------------------------------------------------- 1 | RSpec::Matchers.define :have_jwt_token_payload do |expected_payload| 2 | match do |token| 3 | token_payload = JWT.decode(token, nil, false, algorithm: "HS256").first 4 | 5 | expect(token_payload.size).to eq(expected_payload.size) 6 | expect(token_payload).to include(expected_payload) 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /spec/support/n_plus_one_control.rb: -------------------------------------------------------------------------------- 1 | # Default scale factors to use. 2 | # We use the smallest possible but representative scale factors by default. 3 | NPlusOneControl.default_scale_factors = [2, 3] 4 | 5 | # Print performed queries if true in the case of failure 6 | # You can activate verbosity through env variable NPLUSONE_VERBOSE=1 7 | NPlusOneControl.verbose = false 8 | 9 | # Print table hits difference, for example: 10 | # 11 | # Unmatched query numbers by tables: 12 | # users (SELECT): 2 != 3 13 | # events (INSERT): 1 != 2 14 | # 15 | NPlusOneControl.show_table_stats = true 16 | 17 | # Ignore matching queries 18 | NPlusOneControl.ignore = /^(BEGIN|COMMIT|SAVEPOINT|RELEASE)/ 19 | 20 | # ActiveSupport notifications event to track queries. 21 | # We track ActiveRecord event by default, 22 | # but can also track rom-rb events ('sql.rom') as well. 23 | NPlusOneControl.event = "sql.active_record" 24 | 25 | # configure transactional behavour for populate method 26 | # in case of use multiple database connections 27 | NPlusOneControl::Executor.tap do |executor| 28 | connections = ActiveRecord::Base.connection_handler.connection_pool_list.map(&:connection) 29 | 30 | executor.transaction_begin = lambda do 31 | connections.each { |connection| connection.begin_transaction(joinable: false) } 32 | end 33 | executor.transaction_rollback = lambda do 34 | connections.each(&:rollback_transaction) 35 | end 36 | end 37 | 38 | # Provide a backtrace cleaner callable object used to filter SQL caller location to display in the verbose mode 39 | # Set it to nil to disable tracing. 40 | # 41 | # In Rails apps, we use Rails.backtrace_cleaner by default. 42 | # NPlusOneControl.backtrace_cleaner = ->(locations_array) { do_some_filtering(locations_array) } 43 | 44 | # You can also specify the number of backtrace lines to show. 45 | # MOTE: It could be specified via NPLUSONE_BACKTRACE env var 46 | NPlusOneControl.backtrace_length = 1 47 | 48 | # Sometime queries could be too large to provide any meaningful insight. 49 | # You can configure an output length limit for quries in verbose mode by setting the follwing option 50 | # NOTE: It could be specified via NPLUSONE_TRUNCATE env var 51 | NPlusOneControl.truncate_query_size = 100 52 | -------------------------------------------------------------------------------- /spec/support/shared_contexts/when_time_is_frozen.rb: -------------------------------------------------------------------------------- 1 | shared_context "when time is frozen" do 2 | let(:current_time) { Time.zone.local(2020, 5, 10, 12, 30) } 3 | 4 | before { travel_to(current_time) } 5 | end 6 | -------------------------------------------------------------------------------- /spec/support/shared_contexts/with_interactor.rb: -------------------------------------------------------------------------------- 1 | shared_context "with interactor" do 2 | let(:interactor) { described_class.new(initial_context) } 3 | let(:executed_context) { described_class.call(initial_context) } 4 | let(:context) { interactor.context } 5 | end 6 | -------------------------------------------------------------------------------- /spec/support/shared_contexts/with_mail_delivery_stubbed.rb: -------------------------------------------------------------------------------- 1 | shared_context "with mail delivery stubbed" do 2 | let(:delivery) { instance_double(ActionMailer::MessageDelivery) } 3 | 4 | before do 5 | allow(delivery).to receive(:deliver_later) 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /spec/support/shared_contexts/with_stubbed_organizer.rb: -------------------------------------------------------------------------------- 1 | shared_context "with stubbed organizer" do |options = {}| 2 | include_context "with interactor" 3 | 4 | before do 5 | allow(described_class).to receive(:organized).and_return([]) 6 | allow(interactor).to receive(:context).and_call_original 7 | allow(interactor).to(receive(:run!).and_raise(Interactor::Failure)) if options[:failure] 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /spec/support/shared_examples/activity_source.rb: -------------------------------------------------------------------------------- 1 | shared_examples "activity source" do 2 | it "schedules activity job" do 3 | expect { interactor.run }.to have_enqueued_job(RegisterActivityJob) 4 | .with(user_id, event) 5 | .on_queue("events") 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /spec/support/shared_examples/failed_interactor.rb: -------------------------------------------------------------------------------- 1 | shared_examples "failed interactor" do 2 | it "failures" do 3 | interactor.run 4 | 5 | expect(context).to be_failure 6 | expect(context.error_data).to eq(error_data) 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /spec/support/shared_examples/full_graphql_request.rb: -------------------------------------------------------------------------------- 1 | shared_examples "full graphql request" do |spec_name| 2 | let(:fixture_file) { File.read(File.join(RSpec.configuration.fixture_path, fixture_path)) } 3 | let(:parsed_fixture_file) do 4 | JSON.parse(respond_to?(:prepared_fixture_file) ? prepared_fixture_file : fixture_file) 5 | end 6 | 7 | it spec_name do 8 | expect(JSON.parse(response.body)).to eq(parsed_fixture_file) 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /spec/support/shared_examples/graphql_request.rb: -------------------------------------------------------------------------------- 1 | shared_examples "graphql request" do |spec_name| 2 | let(:fixture_file) { File.read(File.join(RSpec.configuration.fixture_path, fixture_path)) } 3 | let(:parsed_fixture_file) do 4 | JSON.parse(respond_to?(:prepared_fixture_file) ? prepared_fixture_file : fixture_file) 5 | end 6 | let(:schema_options) do 7 | { 8 | context: respond_to?(:schema_context) ? schema_context : {} 9 | } 10 | end 11 | 12 | let(:response) { ApplicationSchema.execute(query, **schema_options).as_json } 13 | 14 | it spec_name do 15 | expect(response).to eql(parsed_fixture_file) 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /spec/support/shared_examples/performs_constant_number_of_queries_request.rb: -------------------------------------------------------------------------------- 1 | shared_examples "performs constant number of queries request" do 2 | specify do 3 | expect { ApplicationSchema.execute(query).as_json } 4 | .to perform_constant_number_of_queries 5 | end 6 | end 7 | -------------------------------------------------------------------------------- /spec/support/shared_examples/success_interactor.rb: -------------------------------------------------------------------------------- 1 | shared_examples "success interactor" do 2 | it "succeeds" do 3 | interactor.run 4 | 5 | expect(context).to be_success 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /spec/uploaders/image_uploader_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe ImageUploader do 4 | let(:user) { build(:user) } 5 | 6 | before do 7 | user.avatar = File.open(Rails.root.join(image_path), "rb") 8 | user.save 9 | end 10 | 11 | context "with valid data" do 12 | let(:image_path) { "spec/fixtures/images/avatar.jpg" } 13 | let(:avatar) { user.avatar } 14 | 15 | it "saves avatar data" do 16 | expect(user).to be_persisted 17 | expect(avatar.mime_type).to eq("image/jpeg") 18 | expect(avatar.extension).to eq("jpg") 19 | expect(avatar.size).to be_instance_of(Integer) 20 | end 21 | end 22 | 23 | context "with wrong extension and mime type" do 24 | let(:image_path) { "spec/fixtures/files/test.txt" } 25 | let(:error_messages) do 26 | { 27 | avatar: [ 28 | "type must be one of: image/jpeg, image/png, image/webp", 29 | "extension must be one of: jpg, jpeg, png, webp" 30 | ] 31 | } 32 | end 33 | 34 | it "raises error" do 35 | expect(user).not_to be_persisted 36 | expect(user.errors.messages).to eq(error_messages) 37 | end 38 | end 39 | 40 | context "with wrong mime type" do 41 | let(:image_path) { "spec/fixtures/files/fake_image.png" } 42 | let(:error_messages) do 43 | { 44 | avatar: [ 45 | "type must be one of: image/jpeg, image/png, image/webp" 46 | ] 47 | } 48 | end 49 | 50 | it "raises error" do 51 | expect(user).not_to be_persisted 52 | expect(user.errors.messages).to eq(error_messages) 53 | end 54 | end 55 | end 56 | -------------------------------------------------------------------------------- /spec/validators/existing_password_validator_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe ExistingPasswordValidator do 4 | let(:form) { UpdateUserForm.new(user) } 5 | let(:user) { build(:user, password: "123456") } 6 | 7 | before do 8 | form.assign_attributes({ password: "qwerty", current_password: current_password }) 9 | form.validate 10 | end 11 | 12 | describe "existing password valiadation" do 13 | context "when current_password is invalid" do 14 | let(:current_password) { "1234_56" } 15 | 16 | it "fails and adds error" do 17 | expect(form.errors[:current_password]).to include("is incorrect") 18 | end 19 | end 20 | 21 | context "when current_password is valid" do 22 | let(:current_password) { "123456" } 23 | 24 | it "succeeds" do 25 | expect(form.errors).to be_empty 26 | end 27 | end 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /spec/validators/expiration_validator_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | describe ExpirationValidator do 4 | include_context "when time is frozen" 5 | 6 | let(:form) { UpdateUserPasswordForm.new(user) } 7 | let(:user) { build(:user, :with_reset_token) } 8 | let(:expiration_time) { user.password_reset_sent_at + 15.minutes } 9 | 10 | before do 11 | form.assign_attributes({ password: "qwerty" }) 12 | form.validate 13 | end 14 | 15 | describe "active reset token validation" do 16 | context "when reset token is invalid" do 17 | let(:current_time) { expiration_time + 1 } 18 | 19 | it "fails and adds error" do 20 | expect(form.errors[:password_reset_sent_at]).to include("has expired") 21 | end 22 | end 23 | 24 | context "when reset token is valid" do 25 | let(:current_time) { expiration_time - 1 } 26 | 27 | it "succeeds" do 28 | expect(form.errors).to be_empty 29 | end 30 | end 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /storage/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fs/rails-base-graphql-api/dc1f74ea2ffdb4f8632ba627dc85df216bc332e3/storage/.keep -------------------------------------------------------------------------------- /tmp/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fs/rails-base-graphql-api/dc1f74ea2ffdb4f8632ba627dc85df216bc332e3/tmp/.keep -------------------------------------------------------------------------------- /vendor/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fs/rails-base-graphql-api/dc1f74ea2ffdb4f8632ba627dc85df216bc332e3/vendor/.keep --------------------------------------------------------------------------------