├── .dockerignore ├── .gitignore ├── .ruby-version ├── Dockerfile ├── Gemfile ├── Gemfile.lock ├── Procfile ├── README.md ├── Rakefile ├── app ├── auth │ ├── authenticate_user.rb │ └── authorize_api_request.rb ├── channels │ ├── application_cable │ │ ├── channel.rb │ │ └── connection.rb │ ├── chat_channel.rb │ ├── notifications_channel.rb │ └── presence_channel.rb ├── controllers │ ├── application_controller.rb │ ├── authentication_controller.rb │ ├── chat_messages_controller.rb │ ├── chats_controller.rb │ ├── concerns │ │ ├── .keep │ │ ├── exception_handler.rb │ │ └── response.rb │ ├── token_validation_controller.rb │ ├── users_controller.rb │ └── visibility_controller.rb ├── jobs │ └── application_job.rb ├── lib │ ├── json_web_token.rb │ ├── message.rb │ └── user_attributes.rb ├── mailers │ └── application_mailer.rb ├── models │ ├── application_record.rb │ ├── chat.rb │ ├── chat_message.rb │ ├── concerns │ │ └── .keep │ ├── group_chat.rb │ ├── join.rb │ └── user.rb ├── queries │ ├── query_chat_between_users.rb │ └── query_users.rb └── views │ ├── chat_messages │ ├── _chat_message.json.jb │ ├── index.json.jb │ └── show.json.jb │ ├── chats │ ├── _chat.json.jb │ ├── index.json.jb │ ├── notification.json.jb │ └── show.json.jb │ ├── layouts │ ├── mailer.html.erb │ └── mailer.text.erb │ └── users │ ├── _user.json.jb │ └── index.json.jb ├── bin ├── bundle ├── rails ├── rake ├── setup ├── spring └── update ├── config.ru ├── config ├── application.rb ├── boot.rb ├── cable.yml ├── credentials.yml.enc ├── database.yml ├── environment.rb ├── environments │ ├── development.rb │ ├── production.rb │ └── test.rb ├── initializers │ ├── application_controller_renderer.rb │ ├── backtrace_silencers.rb │ ├── cors.rb │ ├── devise.rb │ ├── filter_parameter_logging.rb │ ├── inflections.rb │ ├── mime_types.rb │ └── wrap_parameters.rb ├── locales │ ├── devise.en.yml │ └── en.yml ├── puma.rb ├── routes.rb ├── spring.rb └── storage.yml ├── db ├── migrate │ ├── 20190329051118_devise_create_users.rb │ ├── 20190401105046_create_chats.rb │ ├── 20190401105401_create_group_chats.rb │ ├── 20190401105519_create_joins.rb │ ├── 20190401125543_create_chat_messages.rb │ ├── 20190402111430_add_unique_compound_index_to_joins.rb │ ├── 20190510064246_add_indexes_to_names_in_users.rb │ ├── 20190529032042_add_present_column_to_users.rb │ └── 20190530093346_add_visible_column_to_users.rb ├── schema.rb └── seeds.rb ├── lib └── tasks │ └── .keep ├── log └── .keep ├── public └── robots.txt ├── readme_images ├── D5gvWHTdtB.png ├── auraKt9uh1.gif ├── chrome_YRPamH57aY.png ├── chrome_xZK6xZveKo.png ├── fetDvQDNpT.gif ├── mYmkQQkFRD.gif ├── riZJ8Lphw0.gif └── sTFdGuvNIW.gif ├── spec ├── auth │ ├── authenticate_user_spec.rb │ └── authorize_api_request_spec.rb ├── controllers │ └── application_controller_spec.rb ├── factories │ ├── chat_messages.rb │ ├── chats.rb │ ├── group_chats.rb │ ├── joins.rb │ └── users.rb ├── models │ ├── chat_message_spec.rb │ ├── chat_spec.rb │ ├── group_chat_spec.rb │ ├── join_spec.rb │ └── user_spec.rb ├── queries │ ├── query_chat_between_users_spec.rb │ └── query_users_spec.rb ├── rails_helper.rb ├── requests │ ├── authentication_spec.rb │ ├── chat_messages_spec.rb │ ├── chats_spec.rb │ ├── token_validation_spec.rb │ ├── users_spec.rb │ └── visibility_spec.rb ├── spec_helper.rb └── support │ ├── controller_spec_helper.rb │ └── request_spec_helper.rb ├── storage └── .keep ├── test ├── controllers │ └── .keep ├── fixtures │ ├── .keep │ └── files │ │ └── .keep ├── integration │ └── .keep ├── mailers │ └── .keep ├── models │ └── .keep └── test_helper.rb ├── tmp └── .keep └── vendor └── .keep /.dockerignore: -------------------------------------------------------------------------------- 1 | tmp 2 | !tmp/pids 3 | log 4 | public/assets 5 | public/packs 6 | .bundle 7 | 8 | db/*.sqlite3 9 | db/*.sqlite3-* 10 | 11 | storage 12 | config/master.key 13 | config/credentials/*.key 14 | 15 | node_modules 16 | config/application.yml 17 | docker-compose* 18 | -------------------------------------------------------------------------------- /.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 | 16 | # Ignore uploaded files in development 17 | /storage/* 18 | !/storage/.keep 19 | 20 | .byebug_history 21 | 22 | # Ignore master key for decrypting credentials and more. 23 | /config/master.key 24 | 25 | # Ignore application configuration 26 | /config/application.yml 27 | docker-compose* -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | ruby-2.7.8 -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ruby:2.7.8-alpine AS builder 2 | RUN apk add \ 3 | build-base \ 4 | libpq-dev \ 5 | git 6 | COPY Gemfile* . 7 | RUN gem install bundler:2.2.24 8 | RUN bundle install 9 | 10 | FROM ruby:2.7.8-alpine AS runner 11 | RUN apk add \ 12 | tzdata \ 13 | libpq-dev \ 14 | nodejs \ 15 | git 16 | RUN git config --global core.autocrlf true 17 | WORKDIR /app 18 | COPY . . 19 | COPY --from=builder /usr/local/bundle/ /usr/local/bundle/ 20 | 21 | EXPOSE 3000 22 | CMD ["rails", "server", "-b", "0.0.0.0"] -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | git_source(:github) { |repo| "https://github.com/#{repo}.git" } 3 | 4 | ruby '2.7.8' 5 | 6 | # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' 7 | gem 'rails', '~> 5.2.3' 8 | # Use postgresql as the database for Active Record 9 | gem 'pg', '1.4.1' 10 | # Use Puma as the app server 11 | gem 'puma', '~> 4.3' 12 | gem 'faker' 13 | gem 'devise' 14 | gem 'jwt' 15 | gem 'jb' 16 | gem 'kaminari' 17 | gem 'figaro' 18 | # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder 19 | # gem 'jbuilder', '~> 2.5' 20 | # Use Redis adapter to run Action Cable in production 21 | gem 'redis', '~> 4.0' 22 | # Use ActiveModel has_secure_password 23 | # gem 'bcrypt', '~> 3.1.7' 24 | 25 | # Use ActiveStorage variant 26 | # gem 'mini_magick', '~> 4.8' 27 | 28 | # Use Capistrano for deployment 29 | # gem 'capistrano-rails', group: :development 30 | 31 | # Reduces boot times through caching; required in config/boot.rb 32 | gem 'bootsnap', '>= 1.1.0', require: false 33 | 34 | # Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible 35 | gem 'rack-cors' 36 | 37 | group :development, :test do 38 | # Call 'byebug' anywhere in the code to stop execution and get a debugger console 39 | gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] 40 | gem 'rspec-rails' 41 | gem 'factory_bot_rails' 42 | end 43 | 44 | group :development do 45 | gem 'listen', '>= 3.0.5', '< 3.2' 46 | # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring 47 | gem 'spring' 48 | gem 'spring-watcher-listen', '~> 2.0.0' 49 | end 50 | 51 | group :test do 52 | gem 'shoulda-matchers' 53 | gem 'database_cleaner' 54 | end 55 | 56 | 57 | # Windows does not include zoneinfo files, so bundle the tzinfo-data gem 58 | gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] 59 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | actioncable (5.2.8) 5 | actionpack (= 5.2.8) 6 | nio4r (~> 2.0) 7 | websocket-driver (>= 0.6.1) 8 | actionmailer (5.2.8) 9 | actionpack (= 5.2.8) 10 | actionview (= 5.2.8) 11 | activejob (= 5.2.8) 12 | mail (~> 2.5, >= 2.5.4) 13 | rails-dom-testing (~> 2.0) 14 | actionpack (5.2.8) 15 | actionview (= 5.2.8) 16 | activesupport (= 5.2.8) 17 | rack (~> 2.0, >= 2.0.8) 18 | rack-test (>= 0.6.3) 19 | rails-dom-testing (~> 2.0) 20 | rails-html-sanitizer (~> 1.0, >= 1.0.2) 21 | actionview (5.2.8) 22 | activesupport (= 5.2.8) 23 | builder (~> 3.1) 24 | erubi (~> 1.4) 25 | rails-dom-testing (~> 2.0) 26 | rails-html-sanitizer (~> 1.0, >= 1.0.3) 27 | activejob (5.2.8) 28 | activesupport (= 5.2.8) 29 | globalid (>= 0.3.6) 30 | activemodel (5.2.8) 31 | activesupport (= 5.2.8) 32 | activerecord (5.2.8) 33 | activemodel (= 5.2.8) 34 | activesupport (= 5.2.8) 35 | arel (>= 9.0) 36 | activestorage (5.2.8) 37 | actionpack (= 5.2.8) 38 | activerecord (= 5.2.8) 39 | marcel (~> 1.0.0) 40 | activesupport (5.2.8) 41 | concurrent-ruby (~> 1.0, >= 1.0.2) 42 | i18n (>= 0.7, < 2) 43 | minitest (~> 5.1) 44 | tzinfo (~> 1.1) 45 | arel (9.0.0) 46 | bcrypt (3.1.18) 47 | bootsnap (1.12.0) 48 | msgpack (~> 1.2) 49 | builder (3.2.4) 50 | byebug (11.1.3) 51 | concurrent-ruby (1.1.10) 52 | crass (1.0.6) 53 | database_cleaner (2.0.1) 54 | database_cleaner-active_record (~> 2.0.0) 55 | database_cleaner-active_record (2.0.1) 56 | activerecord (>= 5.a) 57 | database_cleaner-core (~> 2.0.0) 58 | database_cleaner-core (2.0.1) 59 | devise (4.8.1) 60 | bcrypt (~> 3.0) 61 | orm_adapter (~> 0.1) 62 | railties (>= 4.1.0) 63 | responders 64 | warden (~> 1.2.3) 65 | diff-lcs (1.5.0) 66 | erubi (1.10.0) 67 | factory_bot (6.2.1) 68 | activesupport (>= 5.0.0) 69 | factory_bot_rails (6.2.0) 70 | factory_bot (~> 6.2.0) 71 | railties (>= 5.0.0) 72 | faker (2.21.0) 73 | i18n (>= 1.8.11, < 2) 74 | ffi (1.15.5) 75 | figaro (1.2.0) 76 | thor (>= 0.14.0, < 2) 77 | globalid (1.0.0) 78 | activesupport (>= 5.0) 79 | i18n (1.10.0) 80 | concurrent-ruby (~> 1.0) 81 | jb (0.8.0) 82 | jwt (2.4.1) 83 | kaminari (1.2.2) 84 | activesupport (>= 4.1.0) 85 | kaminari-actionview (= 1.2.2) 86 | kaminari-activerecord (= 1.2.2) 87 | kaminari-core (= 1.2.2) 88 | kaminari-actionview (1.2.2) 89 | actionview 90 | kaminari-core (= 1.2.2) 91 | kaminari-activerecord (1.2.2) 92 | activerecord 93 | kaminari-core (= 1.2.2) 94 | kaminari-core (1.2.2) 95 | listen (3.1.5) 96 | rb-fsevent (~> 0.9, >= 0.9.4) 97 | rb-inotify (~> 0.9, >= 0.9.7) 98 | ruby_dep (~> 1.2) 99 | loofah (2.18.0) 100 | crass (~> 1.0.2) 101 | nokogiri (>= 1.5.9) 102 | mail (2.7.1) 103 | mini_mime (>= 0.1.1) 104 | marcel (1.0.2) 105 | method_source (1.0.0) 106 | mini_mime (1.1.2) 107 | minitest (5.16.2) 108 | msgpack (1.5.3) 109 | nio4r (2.5.8) 110 | nokogiri (1.13.6-x86_64-linux) 111 | racc (~> 1.4) 112 | orm_adapter (0.5.0) 113 | pg (1.4.1) 114 | puma (4.3.12) 115 | nio4r (~> 2.0) 116 | racc (1.6.0) 117 | rack (2.2.4) 118 | rack-cors (1.1.1) 119 | rack (>= 2.0.0) 120 | rack-test (2.0.2) 121 | rack (>= 1.3) 122 | rails (5.2.8) 123 | actioncable (= 5.2.8) 124 | actionmailer (= 5.2.8) 125 | actionpack (= 5.2.8) 126 | actionview (= 5.2.8) 127 | activejob (= 5.2.8) 128 | activemodel (= 5.2.8) 129 | activerecord (= 5.2.8) 130 | activestorage (= 5.2.8) 131 | activesupport (= 5.2.8) 132 | bundler (>= 1.3.0) 133 | railties (= 5.2.8) 134 | sprockets-rails (>= 2.0.0) 135 | rails-dom-testing (2.0.3) 136 | activesupport (>= 4.2.0) 137 | nokogiri (>= 1.6) 138 | rails-html-sanitizer (1.4.3) 139 | loofah (~> 2.3) 140 | railties (5.2.8) 141 | actionpack (= 5.2.8) 142 | activesupport (= 5.2.8) 143 | method_source 144 | rake (>= 0.8.7) 145 | thor (>= 0.19.0, < 2.0) 146 | rake (13.0.6) 147 | rb-fsevent (0.11.1) 148 | rb-inotify (0.10.1) 149 | ffi (~> 1.0) 150 | redis (4.7.1) 151 | responders (3.0.1) 152 | actionpack (>= 5.0) 153 | railties (>= 5.0) 154 | rspec-core (3.11.0) 155 | rspec-support (~> 3.11.0) 156 | rspec-expectations (3.11.0) 157 | diff-lcs (>= 1.2.0, < 2.0) 158 | rspec-support (~> 3.11.0) 159 | rspec-mocks (3.11.1) 160 | diff-lcs (>= 1.2.0, < 2.0) 161 | rspec-support (~> 3.11.0) 162 | rspec-rails (5.1.2) 163 | actionpack (>= 5.2) 164 | activesupport (>= 5.2) 165 | railties (>= 5.2) 166 | rspec-core (~> 3.10) 167 | rspec-expectations (~> 3.10) 168 | rspec-mocks (~> 3.10) 169 | rspec-support (~> 3.10) 170 | rspec-support (3.11.0) 171 | ruby_dep (1.5.0) 172 | shoulda-matchers (5.1.0) 173 | activesupport (>= 5.2.0) 174 | spring (2.1.1) 175 | spring-watcher-listen (2.0.1) 176 | listen (>= 2.7, < 4.0) 177 | spring (>= 1.2, < 3.0) 178 | sprockets (4.1.1) 179 | concurrent-ruby (~> 1.0) 180 | rack (> 1, < 3) 181 | sprockets-rails (3.4.2) 182 | actionpack (>= 5.2) 183 | activesupport (>= 5.2) 184 | sprockets (>= 3.0.0) 185 | thor (1.2.1) 186 | thread_safe (0.3.6) 187 | tzinfo (1.2.9) 188 | thread_safe (~> 0.1) 189 | warden (1.2.9) 190 | rack (>= 2.0.9) 191 | websocket-driver (0.7.5) 192 | websocket-extensions (>= 0.1.0) 193 | websocket-extensions (0.1.5) 194 | 195 | PLATFORMS 196 | x86_64-linux 197 | 198 | DEPENDENCIES 199 | bootsnap (>= 1.1.0) 200 | byebug 201 | database_cleaner 202 | devise 203 | factory_bot_rails 204 | faker 205 | figaro 206 | jb 207 | jwt 208 | kaminari 209 | listen (>= 3.0.5, < 3.2) 210 | pg (= 1.4.1) 211 | puma (~> 4.3) 212 | rack-cors 213 | rails (~> 5.2.3) 214 | redis (~> 4.0) 215 | rspec-rails 216 | shoulda-matchers 217 | spring 218 | spring-watcher-listen (~> 2.0.0) 219 | tzinfo-data 220 | 221 | RUBY VERSION 222 | ruby 2.7.4p191 223 | 224 | BUNDLED WITH 225 | 2.2.24 226 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: bundle exec puma -C config/puma.rb -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rails Chat (backend) 2 | 3 | [Link to app](https://nmacawile.github.io/rails-chat) 4 | 5 | [frontend repository](https://github.com/nmacawile/rails-chat) 6 | 7 | A chat app developed with Ruby on Rails API backend and Angular frontend. It uses Rails' ActionCable to maintain a persistent connection between the chat server and the end users. Angular and Angular Material were used create an interactive and nice looking user interface. 8 | 9 | ## Features 10 | 11 | ### Send and receive messages in real-time 12 | 13 |  14 | 15 | ### Receive live notifications for new messages 16 | 17 |  18 | 19 | ### View older messages 20 | 21 |  22 | 23 | ### Appear 'offline ' from other users 24 | 25 |  26 | 27 | > Offline users have a gray dialog icon  next to their name 28 | > 29 | > Online users have a purple dialog icon  next to their name 30 | 31 | ### Security 32 | 33 | Chat instances are protected in the server. 34 | 35 |  36 | 37 | ### Search users 38 | 39 |  40 | 41 | ## Running locally 42 | 43 | It is required to specify the `domain` of the backend server to establish a connection. 44 | 45 | Create a file called `environment.ts` inside the `src/environments` directory with this code: 46 | 47 | ```ts 48 | // environments/environment.ts 49 | 50 | const domain = 'localhost:3000'; 51 | 52 | export const environment = { 53 | production: false, 54 | domain, 55 | url: `http://${domain}`, 56 | cableUrl: `ws://${domain}/cable`, 57 | }; 58 | 59 | ``` 60 | 61 | Replace the `domain` value with the domain of the server. 62 | 63 | For the production build, create `environment.prod.ts` in the `src/environments` directory with this code: 64 | 65 | ```ts 66 | // environments/environment.prod.ts 67 | 68 | const domain = 'rails-chat-api.aaaa.bbb'; 69 | 70 | export const environment = { 71 | production: true, 72 | domain, 73 | url: `https://${domain}`, 74 | cableUrl: `ws://${domain}/cable`, 75 | }; 76 | 77 | ``` 78 | 79 | Replace the `domain` value with the domain of the server. 80 | 81 | ## Docker compose 82 | 83 | Copy the code below, supply the values for environment variables `HOST`, `REDIS_URL`, `SECRET_KEY`, and `POSTGRES_URL` 84 | 85 | ```yml 86 | # docker-compose.yml 87 | 88 | version: '3.8' 89 | name: rails-chat-prod 90 | services: 91 | server: 92 | image: nmacawile/rails-chat-api:1.1 93 | ports: 94 | - 3000:3000 95 | environment: 96 | - HOST=localhost:3000 97 | - LANG=en_US.UTF-8 98 | - RACK_ENV=production 99 | - RAILS_ENV=production 100 | - RAILS_LOG_TO_STDOUT=enabled 101 | - RAILS_SERVE_STATIC_FILES=enabled 102 | - REDIS_URL=redis://username:password@redis.com:12345 103 | - SECRET_KEY_BASE=ABCDEFGHIJKL 104 | - POSTGRES_URL=postgres://username:password@postgresdb.com 105 | 106 | ``` 107 | 108 | To create a container, 109 | ```sh 110 | docker-compose up -d 111 | 112 | ``` 113 | 114 | 115 | `docker-compose` file for dev build 116 | 117 | ```yml 118 | # docker-compose-dev.yml 119 | 120 | version: '3.8' 121 | name: rails-chat 122 | services: 123 | db: 124 | image: postgres:15.0-alpine 125 | ports: 126 | - 54321:5432 127 | volumes: 128 | - db:/var/lib/postgresql/data 129 | environment: 130 | - POSTGRES_DB=postgres 131 | - POSTGRES_USER=postgres 132 | - POSTGRES_PASSWORD=password 133 | redis: 134 | image: redis:alpine3.18 135 | ports: 136 | - 63791:6379 137 | frontend: 138 | image: nmacawile/rails-chat:1.1 139 | ports: 140 | - 4200:4200 141 | volumes: 142 | - frontend:/app 143 | server: 144 | image: nmacawile/rails-chat-api:1.1 145 | ports: 146 | - 3000:3000 147 | volumes: 148 | - server:/app 149 | environment: 150 | - FRONTEND_URL=http://localhost:4200 151 | - HOST=localhost:3000 152 | - LANG=en_US.UTF-8 153 | - RACK_ENV=development 154 | - RAILS_ENV=development 155 | - POSTGRES_USER=postgres 156 | - POSTGRES_PASSWORD=password 157 | volumes: 158 | server: 159 | db: 160 | frontend: 161 | 162 | ``` 163 | -------------------------------------------------------------------------------- /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/auth/authenticate_user.rb: -------------------------------------------------------------------------------- 1 | class AuthenticateUser 2 | def initialize(email, password) 3 | @email = email 4 | @password = password 5 | end 6 | 7 | def call 8 | if user 9 | { 10 | auth_token: JsonWebToken.encode({ user_id: user.id }), 11 | user: UserAttributes.json(user) 12 | } 13 | end 14 | end 15 | 16 | private 17 | 18 | attr_reader :email, :password 19 | 20 | def user 21 | user = User.find_by_email(email) 22 | return user if user && user.valid_password?(password) 23 | raise(ExceptionHandler::AuthenticationError, Message.invalid_credentials) 24 | end 25 | end -------------------------------------------------------------------------------- /app/auth/authorize_api_request.rb: -------------------------------------------------------------------------------- 1 | class AuthorizeApiRequest 2 | attr_reader :headers 3 | 4 | def initialize(headers) 5 | @headers = headers 6 | end 7 | 8 | def call 9 | { user: user } 10 | end 11 | 12 | private 13 | 14 | def user 15 | @user ||= User.find(decoded_token_auth[:user_id]) if decoded_token_auth 16 | rescue ActiveRecord::RecordNotFound => e 17 | raise ExceptionHandler::InvalidToken, 18 | "#{Message.invalid_token} #{e.message}" 19 | end 20 | 21 | def decoded_token_auth 22 | @decoded_token_auth ||= JsonWebToken.decode(http_auth_headers) 23 | end 24 | 25 | def http_auth_headers 26 | if headers['Authorization'].present? 27 | return headers['Authorization'].split(' ').last 28 | end 29 | raise ExceptionHandler::MissingToken, Message.missing_token 30 | end 31 | end -------------------------------------------------------------------------------- /app/channels/application_cable/channel.rb: -------------------------------------------------------------------------------- 1 | module ApplicationCable 2 | class Channel < ActionCable::Channel::Base 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/channels/application_cable/connection.rb: -------------------------------------------------------------------------------- 1 | module ApplicationCable 2 | class Connection < ActionCable::Connection::Base 3 | identified_by :chat_user 4 | 5 | def connect 6 | self.chat_user = find_verified_user 7 | end 8 | 9 | private 10 | 11 | def find_verified_user 12 | (AuthorizeApiRequest.new(request.params).call)[:user] 13 | rescue 14 | reject_unauthorized_connection 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /app/channels/chat_channel.rb: -------------------------------------------------------------------------------- 1 | class ChatChannel < ApplicationCable::Channel 2 | def subscribed 3 | chat = chat_user.chats.find(params['chat_id']) 4 | stream_for chat 5 | end 6 | 7 | def unsubscribed 8 | # Any cleanup needed when channel is unsubscribed 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /app/channels/notifications_channel.rb: -------------------------------------------------------------------------------- 1 | class NotificationsChannel < ApplicationCable::Channel 2 | def subscribed 3 | stream_for chat_user 4 | end 5 | 6 | def unsubscribed 7 | # Any cleanup needed when channel is unsubscribed 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /app/channels/presence_channel.rb: -------------------------------------------------------------------------------- 1 | class PresenceChannel < ApplicationCable::Channel 2 | def subscribed 3 | stream_from 'presence' 4 | update_presence(chat_user, true) 5 | end 6 | 7 | def unsubscribed 8 | update_presence(chat_user, false) 9 | end 10 | 11 | private 12 | 13 | def update_presence(user, presence) 14 | user.update(present: presence) 15 | if user.visible 16 | ActionCable.server.broadcast( 17 | 'presence', 18 | { id: user.id, present: presence }) 19 | end 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::API 2 | include Response 3 | include ExceptionHandler 4 | 5 | before_action :authorize_request 6 | attr_reader :current_user 7 | helper_method :current_user 8 | 9 | def authorize_request 10 | @current_user = (AuthorizeApiRequest.new(request.headers).call)[:user] 11 | end 12 | 13 | protected 14 | 15 | def restrict_chat_access 16 | unless @chat.users.include?(current_user) 17 | raise ExceptionHandler::AccessDenied, Message.access_denied 18 | end 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /app/controllers/authentication_controller.rb: -------------------------------------------------------------------------------- 1 | class AuthenticationController < ApplicationController 2 | skip_before_action :authorize_request, only: :authenticate 3 | 4 | def authenticate 5 | auth_info = 6 | AuthenticateUser.new( 7 | params[:email], 8 | params[:password] 9 | ).call 10 | 11 | json_response(auth_info) 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /app/controllers/chat_messages_controller.rb: -------------------------------------------------------------------------------- 1 | class ChatMessagesController < ApplicationController 2 | before_action :set_chat, only: [:index, :create] 3 | before_action :restrict_chat_access, only: [:index, :create] 4 | after_action :broadcast_message, only: :create 5 | 6 | def index 7 | @messages = @chat.chat_messages 8 | .older_than(params[:before]) 9 | .page.per(20) 10 | end 11 | 12 | def create 13 | @chat_message = @chat.chat_messages 14 | .create!( 15 | user: current_user, 16 | content: params[:content]) 17 | head :no_content 18 | end 19 | 20 | private 21 | 22 | def set_chat 23 | @chat = Chat.find(params[:chat_id]) 24 | end 25 | 26 | def broadcast_message 27 | ChatChannel.broadcast_to( 28 | @chat, 29 | render_to_string(:show, format: :json)) 30 | 31 | user_a, user_b = @chat.users 32 | notify_user(user_a, user_b) 33 | notify_user(user_b, user_a) 34 | end 35 | 36 | def notify_user(notifiable, other_user) 37 | NotificationsChannel.broadcast_to( 38 | notifiable, 39 | render_to_string('chats/notification', format: :json, locals: { other_user: other_user })) 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /app/controllers/chats_controller.rb: -------------------------------------------------------------------------------- 1 | class ChatsController < ApplicationController 2 | before_action :set_chat, only: :show 3 | before_action :restrict_chat_access, only: :show 4 | 5 | def index 6 | @chats = current_user.chats.with_messages 7 | end 8 | 9 | def show;end 10 | 11 | def create 12 | @chat = QueryChatBetweenUsers 13 | .new(current_user.id, params[:user_id]).call 14 | render :show 15 | end 16 | 17 | private 18 | 19 | def set_chat 20 | @chat = Chat.find(params[:id]) 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /app/controllers/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/app/controllers/concerns/.keep -------------------------------------------------------------------------------- /app/controllers/concerns/exception_handler.rb: -------------------------------------------------------------------------------- 1 | module ExceptionHandler 2 | extend ActiveSupport::Concern 3 | 4 | class AuthenticationError < StandardError; end 5 | class MissingToken < StandardError; end 6 | class InvalidToken < StandardError; end 7 | class BadRequest < StandardError; end 8 | class AccessDenied < StandardError; end 9 | 10 | included do 11 | rescue_from ActiveRecord::RecordNotFound, with: :not_found_response 12 | rescue_from ActiveRecord::RecordInvalid, with: :unprocessable_response 13 | rescue_from ExceptionHandler::MissingToken, with: :unprocessable_response 14 | rescue_from ExceptionHandler::InvalidToken, with: :unprocessable_response 15 | rescue_from ExceptionHandler::AuthenticationError, with: :unauthorized_response 16 | rescue_from ExceptionHandler::BadRequest, with: :bad_request_response 17 | rescue_from ExceptionHandler::AccessDenied, with: :access_denied_response 18 | end 19 | 20 | private 21 | 22 | #403 23 | def access_denied_response(e) 24 | json_response({ message: e.message }, :forbidden) 25 | end 26 | 27 | #400 28 | def bad_request_response(e) 29 | json_response({ message: e.message }, :bad_request) 30 | end 31 | 32 | #404 33 | def not_found_response(e) 34 | json_response({ message: e.message }, :not_found) 35 | end 36 | 37 | # 422 38 | def unprocessable_response(e) 39 | json_response({ message: e.message }, :unprocessable_entity) 40 | end 41 | 42 | # 401 43 | def unauthorized_response(e) 44 | json_response({ message: e.message }, :unauthorized) 45 | end 46 | end -------------------------------------------------------------------------------- /app/controllers/concerns/response.rb: -------------------------------------------------------------------------------- 1 | module Response 2 | def json_response(object, status = :ok) 3 | render json: object, status: status 4 | end 5 | end -------------------------------------------------------------------------------- /app/controllers/token_validation_controller.rb: -------------------------------------------------------------------------------- 1 | class TokenValidationController < ApplicationController 2 | def validate 3 | json_response(UserAttributes.json(current_user)) 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /app/controllers/users_controller.rb: -------------------------------------------------------------------------------- 1 | class UsersController < ApplicationController 2 | skip_before_action :authorize_request, only: :create 3 | 4 | def index 5 | @users = QueryUsers 6 | .new(params[:q]).call 7 | .excluding(current_user) 8 | .page(params[:page]).per(10) 9 | end 10 | 11 | def create 12 | @user = User.create!(user_params) 13 | auth_info = AuthenticateUser.new(@user.email, @user.password).call 14 | auth_info[:message] = Message.account_created 15 | json_response(auth_info, :created) 16 | end 17 | 18 | def update 19 | current_user.update!(edit_user_params) 20 | head :no_content 21 | end 22 | 23 | private 24 | 25 | def user_params 26 | params.permit(:email, :password, :password_confirmation, :first_name, :last_name) 27 | end 28 | 29 | def edit_user_params 30 | params.permit(:first_name, :last_name) 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /app/controllers/visibility_controller.rb: -------------------------------------------------------------------------------- 1 | class VisibilityController < ApplicationController 2 | def update 3 | current_user.update!(request_params) 4 | broadcast_visibility 5 | head :no_content 6 | rescue 7 | raise ExceptionHandler::BadRequest 8 | end 9 | 10 | private 11 | 12 | def request_params 13 | params.permit(:visible) 14 | end 15 | 16 | def broadcast_visibility 17 | ActionCable.server.broadcast( 18 | 'presence', 19 | { 20 | id: current_user.id, 21 | present: current_user.visible_and_present? 22 | }) 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /app/jobs/application_job.rb: -------------------------------------------------------------------------------- 1 | class ApplicationJob < ActiveJob::Base 2 | end 3 | -------------------------------------------------------------------------------- /app/lib/json_web_token.rb: -------------------------------------------------------------------------------- 1 | class JsonWebToken 2 | HMAC_SECRET = 3 | Rails.env.production? ? 4 | ENV['SECRET_KEY_BASE'] : 5 | Rails.application.secrets.secret_key_base 6 | 7 | def self.encode(payload, exp = 24.hours.from_now) 8 | payload[:exp] = exp.to_i 9 | JWT.encode(payload, HMAC_SECRET) 10 | end 11 | 12 | def self.decode(token) 13 | decoded_token = JWT.decode(token, HMAC_SECRET)[0] 14 | HashWithIndifferentAccess.new(decoded_token) 15 | rescue JWT::DecodeError => e 16 | raise ExceptionHandler::InvalidToken, e.message 17 | end 18 | end -------------------------------------------------------------------------------- /app/lib/message.rb: -------------------------------------------------------------------------------- 1 | class Message 2 | def self.account_created 3 | 'Account created successfully' 4 | end 5 | 6 | def self.invalid_credentials 7 | 'Invalid credentials' 8 | end 9 | 10 | def self.invalid_token 11 | 'Invalid token' 12 | end 13 | 14 | def self.missing_token 15 | 'Missing token' 16 | end 17 | 18 | def self.bad_request 19 | 'Bad request' 20 | end 21 | 22 | def self.access_denied 23 | 'Access denied' 24 | end 25 | end -------------------------------------------------------------------------------- /app/lib/user_attributes.rb: -------------------------------------------------------------------------------- 1 | class UserAttributes 2 | def self.json(user) 3 | return user.slice(:id, :name, :email, :first_name, :last_name, :visible) 4 | end 5 | end -------------------------------------------------------------------------------- /app/mailers/application_mailer.rb: -------------------------------------------------------------------------------- 1 | class ApplicationMailer < ActionMailer::Base 2 | default from: 'from@example.com' 3 | layout 'mailer' 4 | end 5 | -------------------------------------------------------------------------------- /app/models/application_record.rb: -------------------------------------------------------------------------------- 1 | class ApplicationRecord < ActiveRecord::Base 2 | self.abstract_class = true 3 | end 4 | -------------------------------------------------------------------------------- /app/models/chat.rb: -------------------------------------------------------------------------------- 1 | class Chat < ApplicationRecord 2 | default_scope -> { order(updated_at: :desc) } 3 | scope :with_messages, -> { joins(:chat_messages).uniq } 4 | 5 | has_many :joins, as: :joinable, dependent: :destroy 6 | has_many :users, through: :joins 7 | has_many :chat_messages, as: :messageable, dependent: :destroy 8 | 9 | def latest_message 10 | chat_messages.first 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /app/models/chat_message.rb: -------------------------------------------------------------------------------- 1 | class ChatMessage < ApplicationRecord 2 | default_scope -> { order(id: :desc) } 3 | 4 | scope :older_than, -> id { 5 | id ? where("id < #{id.to_i}") : all 6 | } 7 | 8 | before_save do 9 | self.content = content.strip.gsub(/\R{2,}/, "\r\n\r\n").gsub(/\R/, "\r\n") 10 | end 11 | 12 | belongs_to :messageable, polymorphic: true, touch: true 13 | belongs_to :user 14 | 15 | validates_presence_of :content 16 | validates_length_of :content, maximum: 2000 17 | 18 | def content_preview 19 | content.truncate(50, separator: /\s/) 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /app/models/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/app/models/concerns/.keep -------------------------------------------------------------------------------- /app/models/group_chat.rb: -------------------------------------------------------------------------------- 1 | class GroupChat < ApplicationRecord 2 | belongs_to :creator, class_name: 'User' 3 | has_many :joins, as: :joinable, dependent: :destroy 4 | has_many :users, through: :joins 5 | has_many :chat_messages, as: :messageable, dependent: :destroy 6 | end 7 | -------------------------------------------------------------------------------- /app/models/join.rb: -------------------------------------------------------------------------------- 1 | class Join < ApplicationRecord 2 | belongs_to :joinable, polymorphic: true 3 | belongs_to :user 4 | end 5 | -------------------------------------------------------------------------------- /app/models/user.rb: -------------------------------------------------------------------------------- 1 | class User < ApplicationRecord 2 | scope :excluding, -> (user) { where.not(id: user) } 3 | 4 | before_save do 5 | first_name.squish! 6 | last_name.squish! 7 | end 8 | # Include default devise modules. Others available are: 9 | # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable 10 | devise :database_authenticatable, :registerable, 11 | :recoverable, :rememberable, :validatable 12 | 13 | has_many :group_chats_created, class_name: 'GroupChat', 14 | foreign_key: :creator_id, 15 | dependent: :destroy 16 | 17 | has_many :joins, dependent: :destroy 18 | 19 | has_many :group_chats, through: :joins, 20 | source: :joinable, 21 | source_type: 'GroupChat' 22 | 23 | has_many :chats, through: :joins, 24 | source: :joinable, 25 | source_type: 'Chat' 26 | 27 | has_many :chat_messages 28 | 29 | validates_presence_of :first_name, :last_name 30 | 31 | def name 32 | "#{first_name} #{last_name}" 33 | end 34 | 35 | def visible_and_present? 36 | visible && present 37 | end 38 | end 39 | -------------------------------------------------------------------------------- /app/queries/query_chat_between_users.rb: -------------------------------------------------------------------------------- 1 | class QueryChatBetweenUsers 2 | def initialize(user1, user2) 3 | @users = [user1, user2] 4 | end 5 | 6 | def call 7 | query = Chat 8 | .joins('JOIN "joins" AS "j1"'\ 9 | 'ON "j1"."joinable_id" = "chats"."id"'\ 10 | 'AND "j1"."joinable_type" = \'Chat\'') 11 | .joins('JOIN "joins" AS "j2"'\ 12 | 'ON "j2"."joinable_id" = "chats"."id"'\ 13 | 'AND "j2"."joinable_type" = \'Chat\'') 14 | .where('"j1"."user_id" <> "j2"."user_id"'\ 15 | 'AND "j1"."user_id" = ? AND "j2"."user_id" = ?', *users) 16 | .first 17 | query || create_chat_room 18 | end 19 | 20 | private 21 | 22 | attr_reader :users 23 | 24 | def create_chat_room 25 | users_ = User.where(id: users) 26 | if users_.size == 2 27 | return Chat.create!(users: users_ ) 28 | end 29 | raise ExceptionHandler::BadRequest, Message.bad_request 30 | end 31 | end -------------------------------------------------------------------------------- /app/queries/query_users.rb: -------------------------------------------------------------------------------- 1 | class QueryUsers 2 | def initialize(query) 3 | @query = query 4 | end 5 | 6 | def call 7 | return User.all if @query.blank? 8 | User.where( 9 | "CONCAT_WS(' ', first_name, last_name, first_name) ILIKE ?", 10 | "%#{@query.squish}%") 11 | end 12 | end -------------------------------------------------------------------------------- /app/views/chat_messages/_chat_message.json.jb: -------------------------------------------------------------------------------- 1 | preview ||= preview 2 | { 3 | id: chat_message.id, 4 | type: 'message', 5 | content: preview ? chat_message.content_preview : chat_message.content, 6 | created_at: chat_message.created_at, 7 | user: render(chat_message.user) 8 | } -------------------------------------------------------------------------------- /app/views/chat_messages/index.json.jb: -------------------------------------------------------------------------------- 1 | { 2 | messages: render(partial: 'chat_message', collection: @messages, as: :chat_message), 3 | pages: @messages.total_pages, 4 | count: @messages.total_count 5 | } -------------------------------------------------------------------------------- /app/views/chat_messages/show.json.jb: -------------------------------------------------------------------------------- 1 | render @chat_message -------------------------------------------------------------------------------- /app/views/chats/_chat.json.jb: -------------------------------------------------------------------------------- 1 | hash = { 2 | id: chat.id, 3 | type: 'chat', 4 | user: render(chat.users.excluding(current_user).first) 5 | } 6 | 7 | unless chat.chat_messages.empty? 8 | hash[:latest_message] = render(chat.latest_message, preview: true) 9 | end 10 | 11 | hash -------------------------------------------------------------------------------- /app/views/chats/index.json.jb: -------------------------------------------------------------------------------- 1 | render partial: 'chat', collection: @chats, as: :chat -------------------------------------------------------------------------------- /app/views/chats/notification.json.jb: -------------------------------------------------------------------------------- 1 | hash = render @chat 2 | hash[:user] = render(other_user) 3 | hash -------------------------------------------------------------------------------- /app/views/chats/show.json.jb: -------------------------------------------------------------------------------- 1 | render @chat -------------------------------------------------------------------------------- /app/views/layouts/mailer.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.text.erb: -------------------------------------------------------------------------------- 1 | <%= yield %> 2 | -------------------------------------------------------------------------------- /app/views/users/_user.json.jb: -------------------------------------------------------------------------------- 1 | { 2 | id: user.id, 3 | type: 'user', 4 | name: user.name, 5 | present: user.visible_and_present? 6 | } -------------------------------------------------------------------------------- /app/views/users/index.json.jb: -------------------------------------------------------------------------------- 1 | { 2 | users: (render partial: 'user', collection: @users, as: :user), 3 | pages: @users.total_pages, 4 | count: @users.total_count 5 | } -------------------------------------------------------------------------------- /bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) 3 | load Gem.bin_path('bundler', 'bundle') 4 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | begin 3 | load File.expand_path('../spring', __FILE__) 4 | rescue LoadError => e 5 | raise unless e.message.include?('spring') 6 | end 7 | APP_PATH = File.expand_path('../config/application', __dir__) 8 | require_relative '../config/boot' 9 | require 'rails/commands' 10 | -------------------------------------------------------------------------------- /bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | begin 3 | load File.expand_path('../spring', __FILE__) 4 | rescue LoadError => e 5 | raise unless e.message.include?('spring') 6 | end 7 | require_relative '../config/boot' 8 | require 'rake' 9 | Rake.application.run 10 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'fileutils' 3 | include FileUtils 4 | 5 | # path to your application root. 6 | APP_ROOT = File.expand_path('..', __dir__) 7 | 8 | def system!(*args) 9 | system(*args) || abort("\n== Command #{args} failed ==") 10 | end 11 | 12 | chdir APP_ROOT do 13 | # This script is a starting point to setup your application. 14 | # Add necessary setup steps to this file. 15 | 16 | puts '== Installing dependencies ==' 17 | system! 'gem install bundler --conservative' 18 | system('bundle check') || system!('bundle install') 19 | 20 | # puts "\n== Copying sample files ==" 21 | # unless File.exist?('config/database.yml') 22 | # cp 'config/database.yml.sample', 'config/database.yml' 23 | # end 24 | 25 | puts "\n== Preparing database ==" 26 | system! 'bin/rails db:setup' 27 | 28 | puts "\n== Removing old logs and tempfiles ==" 29 | system! 'bin/rails log:clear tmp:clear' 30 | 31 | puts "\n== Restarting application server ==" 32 | system! 'bin/rails restart' 33 | end 34 | -------------------------------------------------------------------------------- /bin/spring: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | # This file loads spring without using Bundler, in order to be fast. 4 | # It gets overwritten when you run the `spring binstub` command. 5 | 6 | unless defined?(Spring) 7 | require 'rubygems' 8 | require 'bundler' 9 | 10 | lockfile = Bundler::LockfileParser.new(Bundler.default_lockfile.read) 11 | spring = lockfile.specs.detect { |spec| spec.name == "spring" } 12 | if spring 13 | Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path 14 | gem 'spring', spring.version 15 | require 'spring/binstub' 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /bin/update: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'fileutils' 3 | include FileUtils 4 | 5 | # path to your application root. 6 | APP_ROOT = File.expand_path('..', __dir__) 7 | 8 | def system!(*args) 9 | system(*args) || abort("\n== Command #{args} failed ==") 10 | end 11 | 12 | chdir APP_ROOT do 13 | # This script is a way to update your development environment automatically. 14 | # Add necessary update steps to this file. 15 | 16 | puts '== Installing dependencies ==' 17 | system! 'gem install bundler --conservative' 18 | system('bundle check') || system!('bundle install') 19 | 20 | puts "\n== Updating database ==" 21 | system! 'bin/rails db:migrate' 22 | 23 | puts "\n== Removing old logs and tempfiles ==" 24 | system! 'bin/rails log:clear tmp:clear' 25 | 26 | puts "\n== Restarting application server ==" 27 | system! 'bin/rails restart' 28 | end 29 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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_view/railtie" 12 | require "action_cable/engine" 13 | # require "sprockets/railtie" 14 | require "rails/test_unit/railtie" 15 | 16 | # Require the gems listed in Gemfile, including any gems 17 | # you've limited to :test, :development, or :production. 18 | Bundler.require(*Rails.groups) 19 | 20 | module Workspace 21 | class Application < Rails::Application 22 | # Initialize configuration defaults for originally generated Rails version. 23 | config.load_defaults 5.2 24 | 25 | # Settings in config/environments/* take precedence over those specified here. 26 | # Application configuration can go into files in config/initializers 27 | # -- all .rb files in that directory are automatically loaded after loading 28 | # the framework and any gems in your application. 29 | 30 | # Only loads a smaller set of middleware suitable for API only apps. 31 | # Middleware like session, flash, cookies can be added back manually. 32 | # Skip views, helpers and assets when generating a new resource. 33 | config.api_only = true 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /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: redis 3 | url: redis://redis 4 | 5 | test: 6 | adapter: async 7 | 8 | production: 9 | adapter: redis 10 | url: <%= ENV["REDIS_URL"] %> 11 | -------------------------------------------------------------------------------- /config/credentials.yml.enc: -------------------------------------------------------------------------------- 1 | ZKWaz+o3sxEWQWsy0e3Adlllp1rATfYDFC8FDtXWHAhUk1OOD5PM8Q13MMOSBhAhL6aVPASnI7AmBD56iT5Bs7kar9GyssT40Bne81/kR6Od7wW7ey91n3dp8Kt3/gDAxWV5V94mfIPle29yoqfwWpFmxGBECRmYbpCjFBvsy652bH/SgxGSyS3KUgSVBBpINH9HEIWv+tSG4V+mP2JAZhn3wVMrWdgCvmTlrdOsgRk6acHhxPnmGFwDBmfuOmBJ2mvdo5ZZp57iqgIZJzeHRAinuKEDSECsdwI3xvpzZH18Ptd2Ldw33FMdHY+t/RtFI32uSmJMyo1pA7pXlo4HiOyVIaTNsQoqZMO5GBYUC3mQkFzTWkH7CmuSSxnFnW6tvJSEHkZmRUhGOiwGmGIipksmH28j06ykmS7P--VFtGcz9gty5+AVwt--ZZqiDKLCjoUk9zFd4o1Srw== -------------------------------------------------------------------------------- /config/database.yml: -------------------------------------------------------------------------------- 1 | # PostgreSQL. Versions 9.1 and up are supported. 2 | # 3 | # Install the pg driver: 4 | # gem install pg 5 | # On OS X with Homebrew: 6 | # gem install pg -- --with-pg-config=/usr/local/bin/pg_config 7 | # On OS X with MacPorts: 8 | # gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config 9 | # On Windows: 10 | # gem install pg 11 | # Choose the win32 build. 12 | # Install PostgreSQL and put its /bin directory on your path. 13 | # 14 | # Configure Using Gemfile 15 | # gem 'pg' 16 | # 17 | default: &default 18 | adapter: postgresql 19 | encoding: unicode 20 | template: template0 21 | username: <%= ENV['POSTGRES_USER'] %> 22 | password: <%= ENV['POSTGRES_PASSWORD'] %> 23 | host: db 24 | # For details on connection pooling, see Rails configuration guide 25 | # http://guides.rubyonrails.org/configuring.html#database-pooling 26 | pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> 27 | 28 | development: 29 | <<: *default 30 | database: rails_chat_development 31 | 32 | # The specified database role being used to connect to postgres. 33 | # To create additional roles in postgres see `$ createuser --help`. 34 | # When left blank, postgres will use the default role. This is 35 | # the same name as the operating system user that initialized the database. 36 | #username: workspace 37 | 38 | # The password associated with the postgres role (username). 39 | #password: 40 | 41 | # Connect on a TCP socket. Omitted by default since the client uses a 42 | # domain socket that doesn't need configuration. Windows does not have 43 | # domain sockets, so uncomment these lines. 44 | #host: localhost 45 | 46 | # The TCP port the server listens on. Defaults to 5432. 47 | # If your server runs on a different port number, change accordingly. 48 | #port: 5432 49 | 50 | # Schema search path. The server defaults to $user,public 51 | #schema_search_path: myapp,sharedapp,public 52 | 53 | # Minimum log levels, in increasing order: 54 | # debug5, debug4, debug3, debug2, debug1, 55 | # log, notice, warning, error, fatal, and panic 56 | # Defaults to warning. 57 | #min_messages: notice 58 | 59 | # Warning: The database defined as "test" will be erased and 60 | # re-generated from your development database when you run "rake". 61 | # Do not set this db to the same as development or production. 62 | test: 63 | <<: *default 64 | database: rails_chat_test 65 | 66 | # As with config/secrets.yml, you never want to store sensitive information, 67 | # like your database password, in your source code. If your source code is 68 | # ever seen by anyone, they now have access to your database. 69 | # 70 | # Instead, provide the password as a unix environment variable when you boot 71 | # the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database 72 | # for a full rundown on how to provide these environment variables in a 73 | # production deployment. 74 | # 75 | # On Heroku and other platform providers, you may have a full connection URL 76 | # available as an environment variable. For example: 77 | # 78 | # DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" 79 | # 80 | # You can use this database configuration with: 81 | # 82 | # production: 83 | # url: <%= ENV['DATABASE_URL'] %> 84 | # 85 | production: 86 | <<: *default 87 | database: rails_chat_production 88 | url: <%= ENV['POSTGRES_URL'] %> 89 | -------------------------------------------------------------------------------- /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 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | config.action_cable.allowed_request_origins = [/http:\/\/*/, /https:\/\/*/] 4 | 5 | # In the development environment your application's code is reloaded on 6 | # every request. This slows down response time but is perfect for development 7 | # since you don't have to restart the web server when you make code changes. 8 | config.cache_classes = false 9 | 10 | # Do not eager load code on boot. 11 | config.eager_load = false 12 | 13 | # Show full error reports. 14 | config.consider_all_requests_local = true 15 | 16 | # Enable/disable caching. By default caching is disabled. 17 | # Run rails dev:cache to toggle caching. 18 | if Rails.root.join('tmp', 'caching-dev.txt').exist? 19 | config.action_controller.perform_caching = true 20 | 21 | config.cache_store = :memory_store 22 | config.public_file_server.headers = { 23 | 'Cache-Control' => "public, max-age=#{2.days.to_i}" 24 | } 25 | else 26 | config.action_controller.perform_caching = false 27 | 28 | config.cache_store = :null_store 29 | end 30 | 31 | # Store uploaded files on the local file system (see config/storage.yml for options) 32 | config.active_storage.service = :local 33 | 34 | # Don't care if the mailer can't send. 35 | config.action_mailer.raise_delivery_errors = false 36 | 37 | config.action_mailer.perform_caching = false 38 | 39 | # Print deprecation notices to the Rails logger. 40 | config.active_support.deprecation = :log 41 | 42 | # Raise an error on page load if there are pending migrations. 43 | config.active_record.migration_error = :page_load 44 | 45 | # Highlight code that triggered database queries in logs. 46 | config.active_record.verbose_query_logs = true 47 | 48 | 49 | # Raises error for missing translations 50 | # config.action_view.raise_on_missing_translations = true 51 | 52 | # Use an evented file watcher to asynchronously detect changes in source code, 53 | # routes, locales, etc. This feature depends on the listen gem. 54 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker 55 | end 56 | -------------------------------------------------------------------------------- /config/environments/production.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # Code is not reloaded between requests. 5 | config.cache_classes = true 6 | 7 | # Eager load code on boot. This eager loads most of Rails and 8 | # your application in memory, allowing both threaded web servers 9 | # and those relying on copy on write to perform better. 10 | # Rake tasks automatically ignore this option for performance. 11 | config.eager_load = true 12 | 13 | # Full error reports are disabled and caching is turned on. 14 | config.consider_all_requests_local = false 15 | config.action_controller.perform_caching = true 16 | 17 | # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] 18 | # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). 19 | # config.require_master_key = true 20 | 21 | # Disable serving static files from the `/public` folder by default since 22 | # Apache or NGINX already handles this. 23 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? 24 | 25 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 26 | # config.action_controller.asset_host = 'http://assets.example.com' 27 | 28 | # Specifies the header that your server uses for sending files. 29 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 30 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 31 | 32 | # Store uploaded files on the local file system (see config/storage.yml for options) 33 | config.active_storage.service = :local 34 | 35 | # Mount Action Cable outside main process or domain 36 | # config.action_cable.mount_path = nil 37 | config.action_cable.url = "wss://#{ENV['HOST']}/cable" 38 | config.action_cable.allowed_request_origins = [ENV['FRONTEND_URL']] 39 | 40 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 41 | # config.force_ssl = true 42 | 43 | # Use the lowest log level to ensure availability of diagnostic information 44 | # when problems arise. 45 | config.log_level = :debug 46 | 47 | # Prepend all log lines with the following tags. 48 | config.log_tags = [ :request_id ] 49 | 50 | # Use a different cache store in production. 51 | # config.cache_store = :mem_cache_store 52 | 53 | # Use a real queuing backend for Active Job (and separate queues per environment) 54 | # config.active_job.queue_adapter = :resque 55 | # config.active_job.queue_name_prefix = "workspace_#{Rails.env}" 56 | 57 | config.action_mailer.perform_caching = false 58 | 59 | # Ignore bad email addresses and do not raise email delivery errors. 60 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 61 | # config.action_mailer.raise_delivery_errors = false 62 | 63 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 64 | # the I18n.default_locale when a translation cannot be found). 65 | config.i18n.fallbacks = true 66 | 67 | # Send deprecation notices to registered listeners. 68 | config.active_support.deprecation = :notify 69 | 70 | # Use default logging formatter so that PID and timestamp are not suppressed. 71 | config.log_formatter = ::Logger::Formatter.new 72 | 73 | # Use a different logger for distributed setups. 74 | # require 'syslog/logger' 75 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') 76 | 77 | if ENV["RAILS_LOG_TO_STDOUT"].present? 78 | logger = ActiveSupport::Logger.new(STDOUT) 79 | logger.formatter = config.log_formatter 80 | config.logger = ActiveSupport::TaggedLogging.new(logger) 81 | end 82 | 83 | # Do not dump schema after migrations. 84 | config.active_record.dump_schema_after_migration = false 85 | end 86 | -------------------------------------------------------------------------------- /config/environments/test.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # The test environment is used exclusively to run your application's 5 | # test suite. You never need to work with it otherwise. Remember that 6 | # your test database is "scratch space" for the test suite and is wiped 7 | # and recreated between test runs. Don't rely on the data there! 8 | config.cache_classes = true 9 | 10 | # Do not eager load code on boot. This avoids loading your whole application 11 | # just for the purpose of running a single test. If you are using a tool that 12 | # preloads Rails for running tests, you may have to set it to true. 13 | config.eager_load = false 14 | 15 | # Configure public file server for tests with Cache-Control for performance. 16 | config.public_file_server.enabled = true 17 | config.public_file_server.headers = { 18 | 'Cache-Control' => "public, max-age=#{1.hour.to_i}" 19 | } 20 | 21 | # Show full error reports and disable caching. 22 | config.consider_all_requests_local = true 23 | config.action_controller.perform_caching = false 24 | 25 | # Raise exceptions instead of rendering exception templates. 26 | config.action_dispatch.show_exceptions = false 27 | 28 | # Disable request forgery protection in test environment. 29 | config.action_controller.allow_forgery_protection = false 30 | 31 | # Store uploaded files on the local file system in a temporary directory 32 | config.active_storage.service = :test 33 | 34 | config.action_mailer.perform_caching = false 35 | 36 | # Tell Action Mailer not to deliver emails to the real world. 37 | # The :test delivery method accumulates sent emails in the 38 | # ActionMailer::Base.deliveries array. 39 | config.action_mailer.delivery_method = :test 40 | 41 | # Print deprecation notices to the stderr. 42 | config.active_support.deprecation = :stderr 43 | 44 | # Raises error for missing translations 45 | # config.action_view.raise_on_missing_translations = true 46 | end 47 | -------------------------------------------------------------------------------- /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| line =~ /my_noisy_library/ } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 7 | # Rails.backtrace_cleaner.remove_silencers! 8 | -------------------------------------------------------------------------------- /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 | hosts = ['localhost:4200'] 9 | hosts << ENV['FRONTEND_URL'] if ENV['FRONTEND_URL'] 10 | 11 | Rails.application.config.middleware.insert_before 0, Rack::Cors do 12 | allow do 13 | origins hosts 14 | 15 | resource '*', 16 | headers: :any, 17 | methods: [:get, :post, :put, :patch, :delete, :options, :head] 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /config/initializers/devise.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Use this hook to configure devise mailer, warden hooks and so forth. 4 | # Many of these configuration options can be set straight in your model. 5 | Devise.setup do |config| 6 | # The secret key used by Devise. Devise uses this key to generate 7 | # random tokens. Changing this key will render invalid all existing 8 | # confirmation, reset password and unlock tokens in the database. 9 | # Devise will use the `secret_key_base` as its `secret_key` 10 | # by default. You can change it below and use your own secret key. 11 | # config.secret_key = '6a950c4d41b7226b5ae1effa567f9064def41e0905d735f7f3a7c0590ad745541476ac79978ef3e7584178192a1a5909390a52e25e84041650031d5feae8554c' 12 | 13 | # ==> Controller configuration 14 | # Configure the parent class to the devise controllers. 15 | # config.parent_controller = 'DeviseController' 16 | 17 | # ==> Mailer Configuration 18 | # Configure the e-mail address which will be shown in Devise::Mailer, 19 | # note that it will be overwritten if you use your own mailer class 20 | # with default "from" parameter. 21 | config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' 22 | 23 | # Configure the class responsible to send e-mails. 24 | # config.mailer = 'Devise::Mailer' 25 | 26 | # Configure the parent class responsible to send e-mails. 27 | # config.parent_mailer = 'ActionMailer::Base' 28 | 29 | # ==> ORM configuration 30 | # Load and configure the ORM. Supports :active_record (default) and 31 | # :mongoid (bson_ext recommended) by default. Other ORMs may be 32 | # available as additional gems. 33 | require 'devise/orm/active_record' 34 | 35 | # ==> Configuration for any authentication mechanism 36 | # Configure which keys are used when authenticating a user. The default is 37 | # just :email. You can configure it to use [:username, :subdomain], so for 38 | # authenticating a user, both parameters are required. Remember that those 39 | # parameters are used only when authenticating and not when retrieving from 40 | # session. If you need permissions, you should implement that in a before filter. 41 | # You can also supply a hash where the value is a boolean determining whether 42 | # or not authentication should be aborted when the value is not present. 43 | # config.authentication_keys = [:email] 44 | 45 | # Configure parameters from the request object used for authentication. Each entry 46 | # given should be a request method and it will automatically be passed to the 47 | # find_for_authentication method and considered in your model lookup. For instance, 48 | # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. 49 | # The same considerations mentioned for authentication_keys also apply to request_keys. 50 | # config.request_keys = [] 51 | 52 | # Configure which authentication keys should be case-insensitive. 53 | # These keys will be downcased upon creating or modifying a user and when used 54 | # to authenticate or find a user. Default is :email. 55 | config.case_insensitive_keys = [:email] 56 | 57 | # Configure which authentication keys should have whitespace stripped. 58 | # These keys will have whitespace before and after removed upon creating or 59 | # modifying a user and when used to authenticate or find a user. Default is :email. 60 | config.strip_whitespace_keys = [:email] 61 | 62 | # Tell if authentication through request.params is enabled. True by default. 63 | # It can be set to an array that will enable params authentication only for the 64 | # given strategies, for example, `config.params_authenticatable = [:database]` will 65 | # enable it only for database (email + password) authentication. 66 | # config.params_authenticatable = true 67 | 68 | # Tell if authentication through HTTP Auth is enabled. False by default. 69 | # It can be set to an array that will enable http authentication only for the 70 | # given strategies, for example, `config.http_authenticatable = [:database]` will 71 | # enable it only for database authentication. The supported strategies are: 72 | # :database = Support basic authentication with authentication key + password 73 | # config.http_authenticatable = false 74 | 75 | # If 401 status code should be returned for AJAX requests. True by default. 76 | # config.http_authenticatable_on_xhr = true 77 | 78 | # The realm used in Http Basic Authentication. 'Application' by default. 79 | # config.http_authentication_realm = 'Application' 80 | 81 | # It will change confirmation, password recovery and other workflows 82 | # to behave the same regardless if the e-mail provided was right or wrong. 83 | # Does not affect registerable. 84 | # config.paranoid = true 85 | 86 | # By default Devise will store the user in session. You can skip storage for 87 | # particular strategies by setting this option. 88 | # Notice that if you are skipping storage for all authentication paths, you 89 | # may want to disable generating routes to Devise's sessions controller by 90 | # passing skip: :sessions to `devise_for` in your config/routes.rb 91 | config.skip_session_storage = [:http_auth] 92 | 93 | # By default, Devise cleans up the CSRF token on authentication to 94 | # avoid CSRF token fixation attacks. This means that, when using AJAX 95 | # requests for sign in and sign up, you need to get a new CSRF token 96 | # from the server. You can disable this option at your own risk. 97 | # config.clean_up_csrf_token_on_authentication = true 98 | 99 | # When false, Devise will not attempt to reload routes on eager load. 100 | # This can reduce the time taken to boot the app but if your application 101 | # requires the Devise mappings to be loaded during boot time the application 102 | # won't boot properly. 103 | # config.reload_routes = true 104 | 105 | # ==> Configuration for :database_authenticatable 106 | # For bcrypt, this is the cost for hashing the password and defaults to 11. If 107 | # using other algorithms, it sets how many times you want the password to be hashed. 108 | # 109 | # Limiting the stretches to just one in testing will increase the performance of 110 | # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use 111 | # a value less than 10 in other environments. Note that, for bcrypt (the default 112 | # algorithm), the cost increases exponentially with the number of stretches (e.g. 113 | # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). 114 | config.stretches = Rails.env.test? ? 1 : 11 115 | 116 | # Set up a pepper to generate the hashed password. 117 | # config.pepper = '9c90ff863642385aef47c43fa45236011dea8277f0ce2dbe5525c42eea7035762596e742e65f5fc9b682097aaf80c7e2294fc1285265b46990623a6239da8bcd' 118 | 119 | # Send a notification to the original email when the user's email is changed. 120 | # config.send_email_changed_notification = false 121 | 122 | # Send a notification email when the user's password is changed. 123 | # config.send_password_change_notification = false 124 | 125 | # ==> Configuration for :confirmable 126 | # A period that the user is allowed to access the website even without 127 | # confirming their account. For instance, if set to 2.days, the user will be 128 | # able to access the website for two days without confirming their account, 129 | # access will be blocked just in the third day. 130 | # You can also set it to nil, which will allow the user to access the website 131 | # without confirming their account. 132 | # Default is 0.days, meaning the user cannot access the website without 133 | # confirming their account. 134 | # config.allow_unconfirmed_access_for = 2.days 135 | 136 | # A period that the user is allowed to confirm their account before their 137 | # token becomes invalid. For example, if set to 3.days, the user can confirm 138 | # their account within 3 days after the mail was sent, but on the fourth day 139 | # their account can't be confirmed with the token any more. 140 | # Default is nil, meaning there is no restriction on how long a user can take 141 | # before confirming their account. 142 | # config.confirm_within = 3.days 143 | 144 | # If true, requires any email changes to be confirmed (exactly the same way as 145 | # initial account confirmation) to be applied. Requires additional unconfirmed_email 146 | # db field (see migrations). Until confirmed, new email is stored in 147 | # unconfirmed_email column, and copied to email column on successful confirmation. 148 | config.reconfirmable = true 149 | 150 | # Defines which key will be used when confirming an account 151 | # config.confirmation_keys = [:email] 152 | 153 | # ==> Configuration for :rememberable 154 | # The time the user will be remembered without asking for credentials again. 155 | # config.remember_for = 2.weeks 156 | 157 | # Invalidates all the remember me tokens when the user signs out. 158 | config.expire_all_remember_me_on_sign_out = true 159 | 160 | # If true, extends the user's remember period when remembered via cookie. 161 | # config.extend_remember_period = false 162 | 163 | # Options to be passed to the created cookie. For instance, you can set 164 | # secure: true in order to force SSL only cookies. 165 | # config.rememberable_options = {} 166 | 167 | # ==> Configuration for :validatable 168 | # Range for password length. 169 | config.password_length = 6..128 170 | 171 | # Email regex used to validate email formats. It simply asserts that 172 | # one (and only one) @ exists in the given string. This is mainly 173 | # to give user feedback and not to assert the e-mail validity. 174 | config.email_regexp = /\A[^@\s]+@[^@\s]+\z/ 175 | 176 | # ==> Configuration for :timeoutable 177 | # The time you want to timeout the user session without activity. After this 178 | # time the user will be asked for credentials again. Default is 30 minutes. 179 | # config.timeout_in = 30.minutes 180 | 181 | # ==> Configuration for :lockable 182 | # Defines which strategy will be used to lock an account. 183 | # :failed_attempts = Locks an account after a number of failed attempts to sign in. 184 | # :none = No lock strategy. You should handle locking by yourself. 185 | # config.lock_strategy = :failed_attempts 186 | 187 | # Defines which key will be used when locking and unlocking an account 188 | # config.unlock_keys = [:email] 189 | 190 | # Defines which strategy will be used to unlock an account. 191 | # :email = Sends an unlock link to the user email 192 | # :time = Re-enables login after a certain amount of time (see :unlock_in below) 193 | # :both = Enables both strategies 194 | # :none = No unlock strategy. You should handle unlocking by yourself. 195 | # config.unlock_strategy = :both 196 | 197 | # Number of authentication tries before locking an account if lock_strategy 198 | # is failed attempts. 199 | # config.maximum_attempts = 20 200 | 201 | # Time interval to unlock the account if :time is enabled as unlock_strategy. 202 | # config.unlock_in = 1.hour 203 | 204 | # Warn on the last attempt before the account is locked. 205 | # config.last_attempt_warning = true 206 | 207 | # ==> Configuration for :recoverable 208 | # 209 | # Defines which key will be used when recovering the password for an account 210 | # config.reset_password_keys = [:email] 211 | 212 | # Time interval you can reset your password with a reset password key. 213 | # Don't put a too small interval or your users won't have the time to 214 | # change their passwords. 215 | config.reset_password_within = 6.hours 216 | 217 | # When set to false, does not sign a user in automatically after their password is 218 | # reset. Defaults to true, so a user is signed in automatically after a reset. 219 | # config.sign_in_after_reset_password = true 220 | 221 | # ==> Configuration for :encryptable 222 | # Allow you to use another hashing or encryption algorithm besides bcrypt (default). 223 | # You can use :sha1, :sha512 or algorithms from others authentication tools as 224 | # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20 225 | # for default behavior) and :restful_authentication_sha1 (then you should set 226 | # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper). 227 | # 228 | # Require the `devise-encryptable` gem when using anything other than bcrypt 229 | # config.encryptor = :sha512 230 | 231 | # ==> Scopes configuration 232 | # Turn scoped views on. Before rendering "sessions/new", it will first check for 233 | # "users/sessions/new". It's turned off by default because it's slower if you 234 | # are using only default views. 235 | # config.scoped_views = false 236 | 237 | # Configure the default scope given to Warden. By default it's the first 238 | # devise role declared in your routes (usually :user). 239 | # config.default_scope = :user 240 | 241 | # Set this configuration to false if you want /users/sign_out to sign out 242 | # only the current scope. By default, Devise signs out all scopes. 243 | # config.sign_out_all_scopes = true 244 | 245 | # ==> Navigation configuration 246 | # Lists the formats that should be treated as navigational. Formats like 247 | # :html, should redirect to the sign in page when the user does not have 248 | # access, but formats like :xml or :json, should return 401. 249 | # 250 | # If you have any extra navigational formats, like :iphone or :mobile, you 251 | # should add them to the navigational formats lists. 252 | # 253 | # The "*/*" below is required to match Internet Explorer requests. 254 | # config.navigational_formats = ['*/*', :html] 255 | 256 | # The default HTTP method used to sign out a resource. Default is :delete. 257 | config.sign_out_via = :delete 258 | 259 | # ==> OmniAuth 260 | # Add a new OmniAuth provider. Check the wiki for more information on setting 261 | # up on your models and hooks. 262 | # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' 263 | 264 | # ==> Warden configuration 265 | # If you want to use other strategies, that are not supported by Devise, or 266 | # change the failure app, you can configure them inside the config.warden block. 267 | # 268 | # config.warden do |manager| 269 | # manager.intercept_401 = false 270 | # manager.default_strategies(scope: :user).unshift :some_external_strategy 271 | # end 272 | 273 | # ==> Mountable engine configurations 274 | # When using Devise inside an engine, let's call it `MyEngine`, and this engine 275 | # is mountable, there are some extra configurations to be taken into account. 276 | # The following options are available, assuming the engine is mounted as: 277 | # 278 | # mount MyEngine, at: '/my_engine' 279 | # 280 | # The router that invoked `devise_for`, in the example above, would be: 281 | # config.router_name = :my_engine 282 | # 283 | # When using OmniAuth, Devise cannot automatically set OmniAuth path, 284 | # so you need to do it manually. For the users scope, it would be: 285 | # config.omniauth_path_prefix = '/my_engine/users/auth' 286 | 287 | # ==> Turbolinks configuration 288 | # If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly: 289 | # 290 | # ActiveSupport.on_load(:devise_failure_app) do 291 | # include Turbolinks::Controller 292 | # end 293 | 294 | # ==> Configuration for :registerable 295 | 296 | # When set to false, does not sign a user in automatically after their password is 297 | # changed. Defaults to true, so a user is signed in automatically after changing a password. 298 | # config.sign_in_after_change_password = true 299 | end 300 | -------------------------------------------------------------------------------- /config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Configure sensitive parameters which will be filtered from the log file. 4 | Rails.application.config.filter_parameters += [:password] 5 | -------------------------------------------------------------------------------- /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 'RESTful' 16 | # end 17 | -------------------------------------------------------------------------------- /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/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/devise.en.yml: -------------------------------------------------------------------------------- 1 | # Additional translations at https://github.com/plataformatec/devise/wiki/I18n 2 | 3 | en: 4 | devise: 5 | confirmations: 6 | confirmed: "Your email address has been successfully confirmed." 7 | send_instructions: "You will receive an email with instructions for how to confirm your email address in a few minutes." 8 | send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes." 9 | failure: 10 | already_authenticated: "You are already signed in." 11 | inactive: "Your account is not activated yet." 12 | invalid: "Invalid %{authentication_keys} or password." 13 | locked: "Your account is locked." 14 | last_attempt: "You have one more attempt before your account is locked." 15 | not_found_in_database: "Invalid %{authentication_keys} or password." 16 | timeout: "Your session expired. Please sign in again to continue." 17 | unauthenticated: "You need to sign in or sign up before continuing." 18 | unconfirmed: "You have to confirm your email address before continuing." 19 | mailer: 20 | confirmation_instructions: 21 | subject: "Confirmation instructions" 22 | reset_password_instructions: 23 | subject: "Reset password instructions" 24 | unlock_instructions: 25 | subject: "Unlock instructions" 26 | email_changed: 27 | subject: "Email Changed" 28 | password_change: 29 | subject: "Password Changed" 30 | omniauth_callbacks: 31 | failure: "Could not authenticate you from %{kind} because \"%{reason}\"." 32 | success: "Successfully authenticated from %{kind} account." 33 | passwords: 34 | no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided." 35 | send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes." 36 | send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." 37 | updated: "Your password has been changed successfully. You are now signed in." 38 | updated_not_active: "Your password has been changed successfully." 39 | registrations: 40 | destroyed: "Bye! Your account has been successfully cancelled. We hope to see you again soon." 41 | signed_up: "Welcome! You have signed up successfully." 42 | signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated." 43 | signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked." 44 | signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please follow the link to activate your account." 45 | update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and follow the confirm link to confirm your new email address." 46 | updated: "Your account has been updated successfully." 47 | updated_but_not_signed_in: "Your account has been updated successfully, but since your password was changed, you need to sign in again" 48 | sessions: 49 | signed_in: "Signed in successfully." 50 | signed_out: "Signed out successfully." 51 | already_signed_out: "Signed out successfully." 52 | unlocks: 53 | send_instructions: "You will receive an email with instructions for how to unlock your account in a few minutes." 54 | send_paranoid_instructions: "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes." 55 | unlocked: "Your account has been unlocked successfully. Please sign in to continue." 56 | errors: 57 | messages: 58 | already_confirmed: "was already confirmed, please try signing in" 59 | confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" 60 | expired: "has expired, please request a new one" 61 | not_found: "not found" 62 | not_locked: "was not locked" 63 | not_saved: 64 | one: "1 error prohibited this %{resource} from being saved:" 65 | other: "%{count} errors prohibited this %{resource} from being saved:" 66 | -------------------------------------------------------------------------------- /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 http://guides.rubyonrails.org/i18n.html. 31 | 32 | en: 33 | hello: "Hello world" 34 | -------------------------------------------------------------------------------- /config/puma.rb: -------------------------------------------------------------------------------- 1 | workers Integer(ENV['WEB_CONCURRENCY'] || 2) 2 | threads_count = Integer(ENV['RAILS_MAX_THREADS'] || 5) 3 | threads threads_count, threads_count 4 | 5 | preload_app! 6 | 7 | rackup DefaultRackup 8 | port ENV['PORT'] || 3000 9 | environment ENV['RACK_ENV'] || 'development' 10 | 11 | on_worker_boot do 12 | # Worker specific setup for Rails 4.1+ 13 | # See: https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server#on-worker-boot 14 | ActiveRecord::Base.establish_connection 15 | end -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | post 'signup' => 'users#create' 3 | get 'users' => 'users#index' 4 | post 'auth/login' => 'authentication#authenticate' 5 | get 'auth/validate' => 'token_validation#validate' 6 | patch 'edit/profile' => 'users#update' 7 | patch 'visibility' => 'visibility#update' 8 | resources :chats, only: [:index, :show, :create] do 9 | resources :messages, controller: 'chat_messages', only: [:index, :create] 10 | end 11 | mount ActionCable.server => '/cable' 12 | # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html 13 | end 14 | -------------------------------------------------------------------------------- /config/spring.rb: -------------------------------------------------------------------------------- 1 | %w[ 2 | .ruby-version 3 | .rbenv-vars 4 | tmp/restart.txt 5 | tmp/caching-dev.txt 6 | ].each { |path| Spring.watch(path) } 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/20190329051118_devise_create_users.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class DeviseCreateUsers < ActiveRecord::Migration[5.2] 4 | def change 5 | create_table :users do |t| 6 | ## Database authenticatable 7 | t.string :email, null: false, default: "" 8 | t.string :encrypted_password, null: false, default: "" 9 | 10 | ## Recoverable 11 | t.string :reset_password_token 12 | t.datetime :reset_password_sent_at 13 | 14 | ## Rememberable 15 | t.datetime :remember_created_at 16 | 17 | ## Trackable 18 | # t.integer :sign_in_count, default: 0, null: false 19 | # t.datetime :current_sign_in_at 20 | # t.datetime :last_sign_in_at 21 | # t.inet :current_sign_in_ip 22 | # t.inet :last_sign_in_ip 23 | 24 | ## Confirmable 25 | # t.string :confirmation_token 26 | # t.datetime :confirmed_at 27 | # t.datetime :confirmation_sent_at 28 | # t.string :unconfirmed_email # Only if using reconfirmable 29 | 30 | ## Lockable 31 | # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts 32 | # t.string :unlock_token # Only if unlock strategy is :email or :both 33 | # t.datetime :locked_at 34 | 35 | t.string :first_name, null: false, default: "" 36 | t.string :last_name, null: false, default: "" 37 | 38 | t.timestamps null: false 39 | end 40 | 41 | add_index :users, :email, unique: true 42 | add_index :users, :reset_password_token, unique: true 43 | # add_index :users, :confirmation_token, unique: true 44 | # add_index :users, :unlock_token, unique: true 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /db/migrate/20190401105046_create_chats.rb: -------------------------------------------------------------------------------- 1 | class CreateChats < ActiveRecord::Migration[5.2] 2 | def change 3 | create_table :chats do |t| 4 | 5 | t.timestamps 6 | end 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /db/migrate/20190401105401_create_group_chats.rb: -------------------------------------------------------------------------------- 1 | class CreateGroupChats < ActiveRecord::Migration[5.2] 2 | def change 3 | create_table :group_chats do |t| 4 | t.references :creator, foreign_key: { to_table: :users } 5 | t.string :name, null: false, default: "" 6 | 7 | t.timestamps 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /db/migrate/20190401105519_create_joins.rb: -------------------------------------------------------------------------------- 1 | class CreateJoins < ActiveRecord::Migration[5.2] 2 | def change 3 | create_table :joins do |t| 4 | t.references :joinable, polymorphic: true 5 | t.references :user, foreign_key: true 6 | 7 | t.timestamps 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /db/migrate/20190401125543_create_chat_messages.rb: -------------------------------------------------------------------------------- 1 | class CreateChatMessages < ActiveRecord::Migration[5.2] 2 | def change 3 | create_table :chat_messages do |t| 4 | t.references :messageable, polymorphic: true 5 | t.references :user 6 | t.text :content 7 | 8 | t.timestamps 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /db/migrate/20190402111430_add_unique_compound_index_to_joins.rb: -------------------------------------------------------------------------------- 1 | class AddUniqueCompoundIndexToJoins < ActiveRecord::Migration[5.2] 2 | def change 3 | add_index :joins, [:user_id, :joinable_type, :joinable_id], unique: true 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /db/migrate/20190510064246_add_indexes_to_names_in_users.rb: -------------------------------------------------------------------------------- 1 | class AddIndexesToNamesInUsers < ActiveRecord::Migration[5.2] 2 | def change 3 | add_index :users, :first_name 4 | add_index :users, :last_name 5 | end 6 | end 7 | -------------------------------------------------------------------------------- /db/migrate/20190529032042_add_present_column_to_users.rb: -------------------------------------------------------------------------------- 1 | class AddPresentColumnToUsers < ActiveRecord::Migration[5.2] 2 | def change 3 | add_column :users, :present, :boolean, null: false, default: false 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /db/migrate/20190530093346_add_visible_column_to_users.rb: -------------------------------------------------------------------------------- 1 | class AddVisibleColumnToUsers < ActiveRecord::Migration[5.2] 2 | def change 3 | add_column :users, :visible, :boolean, null: false, default: true 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /db/schema.rb: -------------------------------------------------------------------------------- 1 | # This file is auto-generated from the current state of the database. Instead 2 | # of editing this file, please use the migrations feature of Active Record to 3 | # incrementally modify your database, and then regenerate this schema definition. 4 | # 5 | # Note that this schema.rb definition is the authoritative source for your 6 | # database schema. If you need to create the application database on another 7 | # system, you should be using db:schema:load, not running all the migrations 8 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 9 | # you'll amass, the slower it'll run and the greater likelihood for issues). 10 | # 11 | # It's strongly recommended that you check this file into your version control system. 12 | 13 | ActiveRecord::Schema.define(version: 2019_05_30_093346) do 14 | 15 | # These are extensions that must be enabled in order to support this database 16 | enable_extension "plpgsql" 17 | 18 | create_table "chat_messages", force: :cascade do |t| 19 | t.string "messageable_type" 20 | t.bigint "messageable_id" 21 | t.bigint "user_id" 22 | t.text "content" 23 | t.datetime "created_at", null: false 24 | t.datetime "updated_at", null: false 25 | t.index ["messageable_type", "messageable_id"], name: "index_chat_messages_on_messageable_type_and_messageable_id" 26 | t.index ["user_id"], name: "index_chat_messages_on_user_id" 27 | end 28 | 29 | create_table "chats", force: :cascade do |t| 30 | t.datetime "created_at", null: false 31 | t.datetime "updated_at", null: false 32 | end 33 | 34 | create_table "group_chats", force: :cascade do |t| 35 | t.bigint "creator_id" 36 | t.string "name", default: "", null: false 37 | t.datetime "created_at", null: false 38 | t.datetime "updated_at", null: false 39 | t.index ["creator_id"], name: "index_group_chats_on_creator_id" 40 | end 41 | 42 | create_table "joins", force: :cascade do |t| 43 | t.string "joinable_type" 44 | t.bigint "joinable_id" 45 | t.bigint "user_id" 46 | t.datetime "created_at", null: false 47 | t.datetime "updated_at", null: false 48 | t.index ["joinable_type", "joinable_id"], name: "index_joins_on_joinable_type_and_joinable_id" 49 | t.index ["user_id", "joinable_type", "joinable_id"], name: "index_joins_on_user_id_and_joinable_type_and_joinable_id", unique: true 50 | t.index ["user_id"], name: "index_joins_on_user_id" 51 | end 52 | 53 | create_table "users", force: :cascade do |t| 54 | t.string "email", default: "", null: false 55 | t.string "encrypted_password", default: "", null: false 56 | t.string "reset_password_token" 57 | t.datetime "reset_password_sent_at" 58 | t.datetime "remember_created_at" 59 | t.string "first_name", default: "", null: false 60 | t.string "last_name", default: "", null: false 61 | t.datetime "created_at", null: false 62 | t.datetime "updated_at", null: false 63 | t.boolean "present", default: false, null: false 64 | t.boolean "visible", default: true, null: false 65 | t.index ["email"], name: "index_users_on_email", unique: true 66 | t.index ["first_name"], name: "index_users_on_first_name" 67 | t.index ["last_name"], name: "index_users_on_last_name" 68 | t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true 69 | end 70 | 71 | add_foreign_key "group_chats", "users", column: "creator_id" 72 | add_foreign_key "joins", "users" 73 | end 74 | -------------------------------------------------------------------------------- /db/seeds.rb: -------------------------------------------------------------------------------- 1 | 30.times do |n| 2 | User.create!(first_name: Faker::Name.first_name, 3 | last_name: Faker::Name.last_name, 4 | email: "user#{n}@email.com", 5 | password: 'password1234') 6 | end 7 | 8 | c = Chat.create! 9 | 10 | u1 = User.first 11 | u2 = User.second 12 | 13 | Join.create!(user: u1, joinable: c) 14 | Join.create!(user: u2, joinable: c) 15 | 16 | u1.chat_messages.create!(messageable: c, content: Faker::Lorem.paragraph) 17 | u2.chat_messages.create!(messageable: c, content: Faker::Lorem.paragraph) 18 | 19 | c2 = Chat.create! 20 | u3 = User.find(3) 21 | Join.create!(user: u1, joinable: c2) 22 | Join.create!(user: u3, joinable: c2) 23 | 24 | u1.chat_messages.create!(messageable: c2, content: Faker::Lorem.paragraph) 25 | u3.chat_messages.create!(messageable: c2, content: Faker::Lorem.paragraph) 26 | 27 | c3 = Chat.create! 28 | u4 = User.find(4) 29 | Join.create!(user: u1, joinable: c3) 30 | Join.create!(user: u4, joinable: c3) 31 | -------------------------------------------------------------------------------- /lib/tasks/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/lib/tasks/.keep -------------------------------------------------------------------------------- /log/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/log/.keep -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | -------------------------------------------------------------------------------- /readme_images/D5gvWHTdtB.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/readme_images/D5gvWHTdtB.png -------------------------------------------------------------------------------- /readme_images/auraKt9uh1.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/readme_images/auraKt9uh1.gif -------------------------------------------------------------------------------- /readme_images/chrome_YRPamH57aY.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/readme_images/chrome_YRPamH57aY.png -------------------------------------------------------------------------------- /readme_images/chrome_xZK6xZveKo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/readme_images/chrome_xZK6xZveKo.png -------------------------------------------------------------------------------- /readme_images/fetDvQDNpT.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/readme_images/fetDvQDNpT.gif -------------------------------------------------------------------------------- /readme_images/mYmkQQkFRD.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/readme_images/mYmkQQkFRD.gif -------------------------------------------------------------------------------- /readme_images/riZJ8Lphw0.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/readme_images/riZJ8Lphw0.gif -------------------------------------------------------------------------------- /readme_images/sTFdGuvNIW.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/readme_images/sTFdGuvNIW.gif -------------------------------------------------------------------------------- /spec/auth/authenticate_user_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe AuthenticateUser do 4 | let(:user) { create :user } 5 | let(:valid_auth_object) { described_class.new(user.email, user.password) } 6 | let(:invalid_auth_object) { described_class.new('invalid_user@email.com', 'foobar1234') } 7 | 8 | describe '#call' do 9 | context 'when valid credentials' do 10 | it 'returns an auth token' do 11 | token = valid_auth_object.call[:auth_token] 12 | expect(token).not_to be_nil 13 | end 14 | 15 | it 'include user info' do 16 | user = valid_auth_object.call[:user] 17 | expect(user).not_to be_nil 18 | end 19 | end 20 | 21 | context 'when invalid credentials' do 22 | it 'raises an authentication error' do 23 | expect { invalid_auth_object.call } 24 | .to raise_error( 25 | ExceptionHandler::AuthenticationError, 26 | /Invalid credentials/ 27 | ) 28 | end 29 | end 30 | end 31 | end -------------------------------------------------------------------------------- /spec/auth/authorize_api_request_spec.rb: -------------------------------------------------------------------------------- 1 | RSpec.describe AuthorizeApiRequest do 2 | let(:user) { create :user } 3 | let(:headers) { { 'Authorization' => token_generator(user.id) } } 4 | let(:invalid_headers) { { 'Authorization' => token_generator(100) } } 5 | subject(:request_object) { described_class.new(headers) } 6 | subject(:invalid_request_object) { described_class.new(invalid_headers) } 7 | 8 | describe '#call' do 9 | context 'when valid request' do 10 | it 'returns the user object' do 11 | result = request_object.call 12 | expect(result[:user]).to eq(user) 13 | end 14 | end 15 | 16 | context 'when expired token' do 17 | subject(:headers) do 18 | { 'Authorization' => expired_token_generator(user.id) } 19 | end 20 | 21 | it 'raises an ExpiredToken error' do 22 | expect { request_object.call } 23 | .to raise_error(ExceptionHandler::InvalidToken, 'Signature has expired') 24 | end 25 | end 26 | 27 | context 'when invalid request' do 28 | it 'raises an InvalidToken error' do 29 | expect { invalid_request_object.call } 30 | .to raise_error(ExceptionHandler::InvalidToken, /Invalid token/) 31 | end 32 | end 33 | 34 | context 'when fake token' do 35 | let(:invalid_headers) { { 'Authorization' => 'foobar' } } 36 | 37 | it 'raises a InvalidToken error' do 38 | expect { invalid_request_object.call } 39 | .to raise_error(ExceptionHandler::InvalidToken, 'Not enough or too many segments') 40 | end 41 | end 42 | 43 | context 'when missing token' do 44 | subject(:invalid_request_object) { described_class.new({}) } 45 | 46 | it 'raises a MissingToken error' do 47 | expect { invalid_request_object.call } 48 | .to raise_error(ExceptionHandler::MissingToken, 'Missing token') 49 | end 50 | end 51 | end 52 | end -------------------------------------------------------------------------------- /spec/controllers/application_controller_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe ApplicationController, type: :controller do 4 | let(:user) { create :user } 5 | let(:headers) { { 'Authorization' => token_generator(user.id) } } 6 | let(:invalid_headers) { { 'Authorization' => nil } } 7 | 8 | describe '#authorize_request' do 9 | context 'when auth token is passed' do 10 | before do 11 | allow(request).to receive(:headers).and_return(headers) 12 | end 13 | 14 | it 'sets the current user' do 15 | expect(subject.instance_eval { authorize_request }).to eq(user) 16 | end 17 | end 18 | 19 | context 'when auth token is not passed' do 20 | before do 21 | allow(request).to receive(:headers).and_return(invalid_headers) 22 | end 23 | 24 | it 'raises MissingToken error' do 25 | expect { subject.instance_eval { authorize_request } } 26 | .to raise_error(ExceptionHandler::MissingToken, 'Missing token') 27 | end 28 | end 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /spec/factories/chat_messages.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :chat_message do 3 | association(:user, factory: :user) 4 | content { Faker::Lorem.paragraph } 5 | 6 | trait :group_chat do 7 | association(:messageable, factory: :group_chat) 8 | end 9 | 10 | trait :chat do 11 | association(:messageable, factory: :chat) 12 | end 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /spec/factories/chats.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :chat 3 | end 4 | -------------------------------------------------------------------------------- /spec/factories/group_chats.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :group_chat do 3 | association(:creator, factory: :user) 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /spec/factories/joins.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :join do 3 | association(:user, factory: :user) 4 | 5 | trait :chat do 6 | association(:joinable, factory: :chat) 7 | end 8 | 9 | trait :group_chat do 10 | association(:joinable, factory: :group_chat) 11 | end 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /spec/factories/users.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :user do 3 | email { Faker::Internet.email } 4 | password { Faker::Internet.password } 5 | first_name { Faker::Name.first_name } 6 | last_name { Faker::Name.last_name } 7 | end 8 | end -------------------------------------------------------------------------------- /spec/models/chat_message_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe ChatMessage, type: :model do 4 | it { is_expected.to belong_to(:user) } 5 | it { is_expected.to belong_to(:messageable) } 6 | it { is_expected.to validate_presence_of :content } 7 | it { is_expected.to validate_length_of(:content).is_at_most(2000) } 8 | 9 | describe 'orphaned by user' do 10 | subject { create(:chat_message, :chat) } 11 | let(:user) { subject.user } 12 | 13 | before { user.destroy } 14 | 15 | it 'doesn\'t get deleted' do 16 | is_expected.not_to be_nil 17 | end 18 | 19 | it 'does not have a user' do 20 | expect(user.persisted?).to be false 21 | end 22 | 23 | it 'cleans up line breaks and spaces before saving' do 24 | new_message = 25 | build(:chat_message, :chat, content: "\n\n\nHello\n\n\n\nWorld!\n\n\n"); 26 | new_message.save 27 | expect(new_message.content).to match(/Hello\R{2}World/) 28 | end 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /spec/models/chat_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe Chat, type: :model do 4 | it { is_expected.to have_many(:joins).dependent(:destroy) } 5 | it { is_expected.to have_many(:users) } 6 | it { is_expected.to have_many(:chat_messages).dependent(:destroy) } 7 | end 8 | -------------------------------------------------------------------------------- /spec/models/group_chat_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe GroupChat, type: :model do 4 | it { is_expected.to belong_to(:creator) } 5 | it { is_expected.to have_many(:joins).dependent(:destroy) } 6 | it { is_expected.to have_many(:users) } 7 | it { is_expected.to have_many(:chat_messages).dependent(:destroy) } 8 | end 9 | -------------------------------------------------------------------------------- /spec/models/join_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe Join, type: :model do 4 | it { is_expected.to belong_to(:user) } 5 | it { is_expected.to belong_to(:joinable) } 6 | 7 | describe 'joining a chat' do 8 | let(:user) { create :user } 9 | let(:chat) { create :chat } 10 | let(:join_chat) { create :join, joinable: chat, user: user } 11 | 12 | context 'when user has not yet joined the chat' do 13 | it 'joins the chat' do 14 | expect { join_chat } 15 | .to change { chat.users.count }.by(1) 16 | end 17 | end 18 | 19 | context 'when user has already joined the chat' do 20 | before do 21 | create :join, joinable: chat, user: user 22 | end 23 | 24 | it 'throws an error' do 25 | expect { join_chat } 26 | .to raise_error(ActiveRecord::RecordNotUnique) 27 | end 28 | end 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /spec/models/user_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe User, type: :model do 4 | it { is_expected.to validate_presence_of :first_name } 5 | it { is_expected.to validate_presence_of :last_name } 6 | 7 | describe "#name" do 8 | let(:first_name) { subject.first_name } 9 | let(:last_name) { subject.last_name } 10 | 11 | it "returns the full name" do 12 | expect(subject.name).to eq "#{first_name} #{last_name}" 13 | end 14 | end 15 | 16 | it do 17 | is_expected.to( 18 | have_many(:group_chats_created) 19 | .with_foreign_key(:creator_id) 20 | .dependent(:destroy)) 21 | end 22 | 23 | it { is_expected.to have_many(:joins).dependent(:destroy) } 24 | it { is_expected.to have_many(:group_chats) } 25 | it { is_expected.to have_many(:chats) } 26 | it { is_expected.to have_many(:chat_messages) } 27 | 28 | it 'cleans up spaces before saving' do 29 | new_user = build(:user, first_name: " Foo\n\n\n\nBar ", last_name: " Baz\n\n\n\n ") 30 | new_user.save 31 | expect(new_user.name).to eq('Foo Bar Baz') 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /spec/queries/query_chat_between_users_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe QueryChatBetweenUsers do 4 | let(:user1) { create :user } 5 | let(:user2) { create :user } 6 | 7 | describe '#call' do 8 | context 'when chat between users already exists' do 9 | let(:chat) { create :chat } 10 | 11 | before do 12 | create :join, joinable: chat, user: user1 13 | create :join, joinable: chat, user: user2 14 | end 15 | 16 | it 'returns the chat object' do 17 | chat_between_users = described_class.new(user1.id, user2.id).call 18 | expect(chat_between_users).to eq(chat) 19 | end 20 | end 21 | 22 | context 'when chat between users doesn\'t exist' do 23 | it 'creates a new chat object' do 24 | expect { described_class.new(user1.id, user2.id).call } 25 | .to change { Chat.count }.by(1) 26 | end 27 | end 28 | 29 | context 'raises a RecordNotFound error' do 30 | it 'doesn\'t create a new chat' do 31 | expect { described_class.new(user1.id, 200).call } 32 | .to raise_error(ExceptionHandler::BadRequest, 'Bad request') 33 | end 34 | end 35 | 36 | context 'raises a BadRequest error' do 37 | it 'doesn\'t create a new chat' do 38 | expect { described_class.new(user1.id, user1.id).call } 39 | .to raise_error(ExceptionHandler::BadRequest, 'Bad request') 40 | end 41 | end 42 | end 43 | end -------------------------------------------------------------------------------- /spec/queries/query_users_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe QueryUsers do 4 | describe '#call' do 5 | before { 6 | create_list(:user, 5, first_name: 'Baz', 7 | last_name: 'Biz') 8 | create_list(:user, 5, first_name: 'Foobar') 9 | create_list(:user, 5, last_name: 'Foobar') 10 | } 11 | subject { described_class.new(query) } 12 | 13 | context 'when query matches some users' do 14 | context 'with perfect matching letter cases' do 15 | let(:query) { 'Foobar' } 16 | 17 | it 'returns the query results' do 18 | expect(subject.call.count).to eq(10) 19 | end 20 | end 21 | 22 | context 'with partial match' do 23 | let(:query) { 'Foo' } 24 | 25 | it 'returns the query results' do 26 | expect(subject.call.count).to eq(10) 27 | end 28 | end 29 | 30 | context 'with full name match' do 31 | let(:query) { 'Baz Biz' } 32 | 33 | it 'returns the query results' do 34 | expect(subject.call.count).to eq(5) 35 | end 36 | end 37 | 38 | context 'with full name match, last name first' do 39 | let(:query) { 'Biz Baz' } 40 | 41 | it 'returns the query results' do 42 | expect(subject.call.count).to eq(5) 43 | end 44 | end 45 | 46 | context 'with full name match, having multiple spaces in between' do 47 | let(:query) { 'Baz Biz' } 48 | 49 | it 'returns the query results' do 50 | expect(subject.call.count).to eq(5) 51 | end 52 | end 53 | 54 | context 'with unmatching letter cases' do 55 | let(:query) { 'fooBar' } 56 | 57 | it 'returns the query results' do 58 | expect(subject.call.count).to eq(10) 59 | end 60 | end 61 | 62 | context 'with null query' do 63 | let(:query) {} 64 | 65 | it 'returns all users' do 66 | expect(subject.call.count).to eq(15) 67 | end 68 | end 69 | end 70 | 71 | context 'when query doesn\'t find a match' do 72 | let(:query) { 'Houdini' } 73 | 74 | it 'returns an empty ActiveRecord object' do 75 | expect(subject.call).to be_empty 76 | end 77 | end 78 | end 79 | end -------------------------------------------------------------------------------- /spec/rails_helper.rb: -------------------------------------------------------------------------------- 1 | # This file is copied to spec/ when you run 'rails generate rspec:install' 2 | require 'spec_helper' 3 | ENV['RAILS_ENV'] ||= 'test' 4 | require File.expand_path('../../config/environment', __FILE__) 5 | # Prevent database truncation if the environment is production 6 | abort("The Rails environment is running in production mode!") if Rails.env.production? 7 | require 'rspec/rails' 8 | # Add additional requires below this line. Rails is not loaded until this point! 9 | require 'database_cleaner' 10 | Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } 11 | 12 | Shoulda::Matchers.configure do |config| 13 | config.integrate do |with| 14 | with.test_framework :rspec 15 | with.library :rails 16 | end 17 | end 18 | # Requires supporting ruby files with custom matchers and macros, etc, in 19 | # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are 20 | # run as spec files by default. This means that files in spec/support that end 21 | # in _spec.rb will both be required and run as specs, causing the specs to be 22 | # run twice. It is recommended that you do not name files matching this glob to 23 | # end with _spec.rb. You can configure this pattern with the --pattern 24 | # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. 25 | # 26 | # The following line is provided for convenience purposes. It has the downside 27 | # of increasing the boot-up time by auto-requiring all files in the support 28 | # directory. Alternatively, in the individual `*_spec.rb` files, manually 29 | # require only the support files necessary. 30 | # 31 | # Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f } 32 | 33 | # Checks for pending migrations and applies them before tests are run. 34 | # If you are not using ActiveRecord, you can remove these lines. 35 | begin 36 | ActiveRecord::Migration.maintain_test_schema! 37 | rescue ActiveRecord::PendingMigrationError => e 38 | puts e.to_s.strip 39 | exit 1 40 | end 41 | RSpec.configure do |config| 42 | config.include FactoryBot::Syntax::Methods 43 | config.include RequestSpecHelper 44 | config.include ControllerSpecHelper 45 | 46 | config.before(:suite) do 47 | DatabaseCleaner.clean_with(:truncation) 48 | DatabaseCleaner.strategy = :transaction 49 | end 50 | 51 | config.around(:each) do |example| 52 | DatabaseCleaner.cleaning do 53 | example.run 54 | end 55 | end 56 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 57 | # config.fixture_path = "#{::Rails.root}/spec/fixtures" 58 | 59 | # If you're not using ActiveRecord, or you'd prefer not to run each of your 60 | # examples within a transaction, remove the following line or assign false 61 | # instead of true. 62 | # config.use_transactional_fixtures = true 63 | 64 | # RSpec Rails can automatically mix in different behaviours to your tests 65 | # based on their file location, for example enabling you to call `get` and 66 | # `post` in specs under `spec/controllers`. 67 | # 68 | # You can disable this behaviour by removing the line below, and instead 69 | # explicitly tag your specs with their type, e.g.: 70 | # 71 | # RSpec.describe UsersController, :type => :controller do 72 | # # ... 73 | # end 74 | # 75 | # The different available types are documented in the features, such as in 76 | # https://relishapp.com/rspec/rspec-rails/docs 77 | config.infer_spec_type_from_file_location! 78 | 79 | # Filter lines from Rails gems in backtraces. 80 | config.filter_rails_from_backtrace! 81 | # arbitrary gems may also be filtered via: 82 | # config.filter_gems_from_backtrace("gem name") 83 | end 84 | -------------------------------------------------------------------------------- /spec/requests/authentication_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'Authentication', type: :request do 4 | describe 'POST /auth/login' do 5 | let!(:user) { create :user } 6 | let(:valid_credentials) do 7 | { 8 | email: user.email, 9 | password: user.password 10 | }.to_json 11 | end 12 | 13 | let(:invalid_credentials) do 14 | { 15 | email: Faker::Internet.email, 16 | password: Faker::Internet.password 17 | }.to_json 18 | end 19 | 20 | context 'when request is valid' do 21 | before do 22 | post '/auth/login', params: valid_credentials, headers: request_headers 23 | end 24 | 25 | it 'returns an authentication token' do 26 | expect(json['auth_token']).not_to be_nil 27 | end 28 | end 29 | 30 | context 'when request is invalid' do 31 | before do 32 | post '/auth/login', 33 | params: invalid_credentials, 34 | headers: request_headers 35 | end 36 | 37 | it 'returns a failure message' do 38 | expect(json['message']).to match(/Invalid credentials/) 39 | end 40 | end 41 | end 42 | end -------------------------------------------------------------------------------- /spec/requests/chat_messages_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'ChatMessages API', type: :request do 4 | let(:user1) { create :user } 5 | let(:user2) { create :user } 6 | let(:third_party) { create :user } 7 | let(:chat) { create :chat } 8 | let(:chat_id) { chat.id } 9 | 10 | before do 11 | create :join, joinable: chat, user: user1 12 | create :join, joinable: chat, user: user2 13 | end 14 | 15 | describe 'GET /chats/:chat_id/messages' do 16 | let!(:chat_messages) { create_list :chat_message, 50, messageable: chat, user: user1 } 17 | 18 | context 'when user belongs in the chat' do 19 | before do 20 | get "/chats/#{chat_id}/messages", headers: request_headers(user1.id) 21 | end 22 | 23 | it 'returns status code 200' do 24 | expect(response).to have_http_status(200) 25 | end 26 | 27 | it 'returns the paginated chat messages' do 28 | expect(json['messages'].size).to eq(20) 29 | end 30 | 31 | it 'returns the pagination data' do 32 | expect(json['pages']).not_to be_nil 33 | expect(json['count']).not_to be_nil 34 | end 35 | end 36 | 37 | context 'when user doesn\'t belong in the chat' do 38 | before do 39 | get "/chats/#{chat_id}/messages", headers: request_headers(third_party.id) 40 | end 41 | 42 | it 'returns status code 403' do 43 | expect(response).to have_http_status(403) 44 | end 45 | 46 | it 'returns an Unauthorized error message' do 47 | expect(json['message']).to match 'Access denied' 48 | end 49 | end 50 | 51 | context 'when querying messages created before a given message' do 52 | let(:latest_message_id) { chat_messages.last.id } 53 | 54 | before do 55 | get "/chats/#{chat_id}/messages", params: { before: latest_message_id }, 56 | headers: request_headers(user1.id) 57 | end 58 | 59 | it 'returns status code 200' do 60 | expect(response).to have_http_status(200) 61 | end 62 | 63 | it 'returns the paginated messages' do 64 | expect(json['messages'].count).to eq(20) 65 | end 66 | 67 | it 'returns the pagination data' do 68 | expect(json['pages']).not_to be_nil 69 | expect(json['count']).not_to be_nil 70 | end 71 | 72 | it 'doesn\'t include the queried message in the results' do 73 | expect(json['messages'].first['id']).to be < latest_message_id 74 | end 75 | end 76 | end 77 | 78 | describe 'POST /chats/:chat_id/messages' do 79 | context 'when valid request' do 80 | before do 81 | post("/chats/#{chat_id}/messages", 82 | params: { content: 'Hello world!!!' }.to_json, 83 | headers: request_headers(user1.id)) 84 | end 85 | 86 | it 'returns status code 204' do 87 | expect(response).to have_http_status(204) 88 | end 89 | end 90 | 91 | context 'when invalid request' do 92 | before do 93 | post("/chats/#{chat_id}/messages", 94 | params: {}, 95 | headers: request_headers(user1.id)) 96 | end 97 | 98 | it 'returns status code 422' do 99 | expect(response).to have_http_status(422) 100 | end 101 | 102 | it 'returns an Unauthorized error message' do 103 | expect(json['message']).to match(/Validation failed/) 104 | end 105 | end 106 | 107 | context 'when user doesn\'t belong in the chat' do 108 | before do 109 | post("/chats/#{chat_id}/messages", 110 | params: { content: 'Hello world!!!' }.to_json, 111 | headers: request_headers(third_party.id)) 112 | end 113 | 114 | it 'returns status code 403' do 115 | expect(response).to have_http_status(403) 116 | end 117 | 118 | it 'returns an Unauthorized error message' do 119 | expect(json['message']).to match 'Access denied' 120 | end 121 | end 122 | end 123 | end -------------------------------------------------------------------------------- /spec/requests/chats_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'Chats API', type: :request do 4 | let(:user) { create :user } 5 | let(:user2) { create :user } 6 | let(:chat) do 7 | chat = create :chat 8 | create :join, joinable: chat, user: user 9 | create :join, joinable: chat, user: user2 10 | chat 11 | end 12 | let(:chat_id) { chat.id } 13 | let(:users) { create_list :user, 4 } 14 | 15 | before do 16 | users[0..1].each do |other_user| 17 | c = create :chat 18 | create :join, joinable: c, user: user 19 | create :join, joinable: c, user: other_user 20 | user.chat_messages 21 | .create!(messageable: c, content: Faker::Lorem.paragraph) 22 | end 23 | 24 | users[2..3].each do |other_user| 25 | c = create :chat 26 | create :join, joinable: c, user: user2 27 | create :join, joinable: c, user: other_user 28 | user2.chat_messages 29 | .create!(messageable: c, content: Faker::Lorem.paragraph) 30 | end 31 | end 32 | 33 | describe 'GET /chats' do 34 | before { get '/chats', headers: request_headers(user.id) } 35 | 36 | it 'returns all chats with messages linked to user' do 37 | expect(json.size).to eq(2) 38 | end 39 | 40 | it 'returns status code 200' do 41 | expect(response).to have_http_status(200) 42 | end 43 | end 44 | 45 | describe 'GET /chats/:id' do 46 | context 'when chat exists' do 47 | before { get "/chats/#{chat_id}", headers: request_headers(user.id) } 48 | 49 | it 'returns the chat object' do 50 | expect(json['id']).to eq(chat.id) 51 | end 52 | 53 | it 'returns status code 200' do 54 | expect(response).to have_http_status(200) 55 | end 56 | end 57 | 58 | context 'when chat doesn\'t exist' do 59 | let(:chat_id) { 0 } 60 | before { get "/chats/#{chat_id}", headers: request_headers(user.id) } 61 | 62 | it 'returns a NotFound error message' do 63 | expect(json['message']).to match(/Couldn't find Chat/) 64 | end 65 | 66 | it 'returns status code 404' do 67 | expect(response).to have_http_status(404) 68 | end 69 | end 70 | 71 | context 'when user doesn\'t belong in the chat' do 72 | before { get "/chats/#{chat_id}", headers: request_headers(users[0].id) } 73 | 74 | it 'returns an AccessDenied message' do 75 | expect(json['message']).to match(/Access denied/) 76 | end 77 | 78 | it 'returns status code 403' do 79 | expect(response).to have_http_status(403) 80 | end 81 | end 82 | end 83 | 84 | describe 'POST /chats' do 85 | context 'when user exists (valid request)' do 86 | before do 87 | post '/chats', params: { user_id: users[3].id }.to_json, 88 | headers: request_headers(user.id) 89 | end 90 | 91 | it 'returns status code 200' do 92 | expect(response).to have_http_status(200) 93 | end 94 | end 95 | 96 | context 'when user doesn\'t exist (invalid request)' do 97 | before do 98 | post '/chats', params: { user_id: 0 }.to_json, 99 | headers: request_headers(user.id) 100 | end 101 | 102 | it 'returns status code 400' do 103 | expect(response).to have_http_status(400) 104 | end 105 | 106 | it 'returns a BadRequest error message' do 107 | expect(json['message']).to match 'Bad request' 108 | end 109 | end 110 | 111 | context 'when no parameter is given' do 112 | before do 113 | post '/chats', params: {}, 114 | headers: request_headers(user.id) 115 | end 116 | 117 | it 'returns status code 400' do 118 | expect(response).to have_http_status(400) 119 | end 120 | 121 | it 'returns a BadRequest error message' do 122 | expect(json['message']).to match 'Bad request' 123 | end 124 | end 125 | end 126 | end -------------------------------------------------------------------------------- /spec/requests/token_validation_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'TokenValidation', type: :request do 4 | let(:user) { create :user } 5 | 6 | before do 7 | get '/auth/validate', headers: request_headers(user.id) 8 | end 9 | 10 | describe 'GET /auth/validate' do 11 | it 'returns the user attributes' do 12 | expect(json).to eq user_attributes(user) 13 | end 14 | 15 | it 'returns status code 200' do 16 | expect(response).to have_http_status(200) 17 | end 18 | end 19 | end -------------------------------------------------------------------------------- /spec/requests/users_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'Users API', type: :request do 4 | let(:user) { build :user } 5 | let(:valid_attributes) do 6 | attributes_for :user, password: user.password, 7 | password_confirmation: user.password 8 | end 9 | 10 | describe 'POST /signup' do 11 | context 'when valid request' do 12 | before { post '/signup', params: valid_attributes.to_json, headers: request_headers } 13 | 14 | it 'creates a user' do 15 | expect(response).to have_http_status 201 16 | end 17 | 18 | it 'returns an authentication token' do 19 | expect(json['auth_token']).not_to be_nil 20 | end 21 | 22 | it 'returns a success message' do 23 | expect(json['message']).to match(/Account created successfully/) 24 | end 25 | end 26 | 27 | context 'when invalid request' do 28 | before { post '/signup', params: {}, headers: request_headers } 29 | 30 | it 'does not create a user' do 31 | expect(response).to have_http_status 422 32 | end 33 | 34 | it 'returns failure message' do 35 | expect(json['message']).to match(/Validation failed/) 36 | end 37 | end 38 | end 39 | 40 | describe 'GET /users' do 41 | let(:users) { create_list(:user, 30, first_name: 'Baz', last_name: 'Biz') } 42 | 43 | context 'without a query parameter' do 44 | before { get '/users', headers: request_headers(users.first.id) } 45 | 46 | it 'returns a paginated list of users' do 47 | expect(json['users'].count).to eq(10) 48 | end 49 | 50 | it 'includes the total number of pages' do 51 | expect(json['pages']).to eq(3) 52 | end 53 | 54 | it 'includes the total number of users, excluding logged in user' do 55 | expect(json['count']).to eq(29) 56 | end 57 | 58 | it 'returns status code 200' do 59 | expect(response).to have_http_status(200) 60 | end 61 | end 62 | 63 | context 'with a query parameter' do 64 | before do 65 | create(:user, first_name: 'Foobar') 66 | get '/users', params: { q: 'Foobar' }, headers: request_headers(users.first.id) 67 | end 68 | 69 | it 'returns a paginated list of users' do 70 | expect(json['users'].count).to eq(1) 71 | end 72 | 73 | it 'includes the total number of pages' do 74 | expect(json['pages']).to eq(1) 75 | end 76 | 77 | it 'includes the total number of users' do 78 | expect(json['count']).to eq(1) 79 | end 80 | 81 | it 'returns status code 200' do 82 | expect(response).to have_http_status(200) 83 | end 84 | end 85 | end 86 | 87 | describe 'PATCH /edit/profile' do 88 | before { user.save } 89 | 90 | context 'when valid request' do 91 | before do 92 | patch('/edit/profile', 93 | params: { first_name: 'Foo', last_name: 'Bar' }.to_json, 94 | headers: request_headers(user.id)) 95 | end 96 | 97 | it 'updates the user' do 98 | user.reload 99 | expect(user.name).to eq('Foo Bar') 100 | end 101 | 102 | it 'returns a 204 status code' do 103 | expect(response).to have_http_status(204) 104 | end 105 | end 106 | 107 | context 'when invalid request' do 108 | before do 109 | patch('/edit/profile', 110 | params: { first_name: 'Foo', last_name: '' }.to_json, 111 | headers: request_headers(user.id)) 112 | end 113 | 114 | it 'doesn\'t update the user' do 115 | user.reload 116 | expect(user.first_name).not_to eq('Foo') 117 | expect(user.last_name).not_to eq('') 118 | end 119 | 120 | it 'returns a 422 status code' do 121 | expect(response).to have_http_status(422) 122 | end 123 | 124 | it 'returns a failure message' do 125 | expect(json['message']).to match(/Validation failed/) 126 | end 127 | end 128 | end 129 | end 130 | -------------------------------------------------------------------------------- /spec/requests/visibility_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'Visibility API', type: :request do 4 | describe 'PATCH /visibility' do 5 | let(:user) { create :user } 6 | 7 | context 'when valid request' do 8 | context 'setting to false' do 9 | before do 10 | patch '/visibility', params: { visible: 0 }.to_json, 11 | headers: request_headers(user.id) 12 | end 13 | 14 | it 'returns 204 status code' do 15 | expect(response).to have_http_status(204) 16 | end 17 | 18 | it 'updates the user\'s visibility to false' do 19 | user.reload 20 | expect(user.visible).to be false 21 | end 22 | end 23 | 24 | context 'setting to true' do 25 | let(:user) { create :user, visible: false } 26 | 27 | before do 28 | patch '/visibility', params: { visible: 1 }.to_json, 29 | headers: request_headers(user.id) 30 | end 31 | 32 | it 'returns 204 status code' do 33 | expect(response).to have_http_status(204) 34 | end 35 | 36 | it 'updates the user\'s visibility to true' do 37 | user.reload 38 | expect(user.visible).to be true 39 | end 40 | end 41 | end 42 | 43 | context 'when invalid request' do 44 | before do 45 | patch '/visibility', params: { visible: nil }.to_json, 46 | headers: request_headers(user.id) 47 | end 48 | 49 | it 'returns 400 status code' do 50 | expect(response).to have_http_status(400) 51 | end 52 | 53 | it 'returns a BadRequest error message' do 54 | expect(json['message']).to match(/BadRequest/) 55 | end 56 | end 57 | end 58 | end -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # This file was generated by the `rails generate rspec:install` command. Conventionally, all 2 | # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. 3 | # The generated `.rspec` file contains `--require spec_helper` which will cause 4 | # this file to always be loaded, without a need to explicitly require it in any 5 | # files. 6 | # 7 | # Given that it is always loaded, you are encouraged to keep this file as 8 | # light-weight as possible. Requiring heavyweight dependencies from this file 9 | # will add to the boot time of your test suite on EVERY test run, even for an 10 | # individual file that may not need all of that loaded. Instead, consider making 11 | # a separate helper file that requires the additional dependencies and performs 12 | # the additional setup, and require it from the spec files that actually need 13 | # it. 14 | # 15 | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration 16 | RSpec.configure do |config| 17 | # rspec-expectations config goes here. You can use an alternate 18 | # assertion/expectation library such as wrong or the stdlib/minitest 19 | # assertions if you prefer. 20 | config.expect_with :rspec do |expectations| 21 | # This option will default to `true` in RSpec 4. It makes the `description` 22 | # and `failure_message` of custom matchers include text for helper methods 23 | # defined using `chain`, e.g.: 24 | # be_bigger_than(2).and_smaller_than(4).description 25 | # # => "be bigger than 2 and smaller than 4" 26 | # ...rather than: 27 | # # => "be bigger than 2" 28 | expectations.include_chain_clauses_in_custom_matcher_descriptions = true 29 | end 30 | 31 | # rspec-mocks config goes here. You can use an alternate test double 32 | # library (such as bogus or mocha) by changing the `mock_with` option here. 33 | config.mock_with :rspec do |mocks| 34 | # Prevents you from mocking or stubbing a method that does not exist on 35 | # a real object. This is generally recommended, and will default to 36 | # `true` in RSpec 4. 37 | mocks.verify_partial_doubles = true 38 | end 39 | 40 | # This option will default to `:apply_to_host_groups` in RSpec 4 (and will 41 | # have no way to turn it off -- the option exists only for backwards 42 | # compatibility in RSpec 3). It causes shared context metadata to be 43 | # inherited by the metadata hash of host groups and examples, rather than 44 | # triggering implicit auto-inclusion in groups with matching metadata. 45 | config.shared_context_metadata_behavior = :apply_to_host_groups 46 | 47 | # The settings below are suggested to provide a good initial experience 48 | # with RSpec, but feel free to customize to your heart's content. 49 | =begin 50 | # This allows you to limit a spec run to individual examples or groups 51 | # you care about by tagging them with `:focus` metadata. When nothing 52 | # is tagged with `:focus`, all examples get run. RSpec also provides 53 | # aliases for `it`, `describe`, and `context` that include `:focus` 54 | # metadata: `fit`, `fdescribe` and `fcontext`, respectively. 55 | config.filter_run_when_matching :focus 56 | 57 | # Allows RSpec to persist some state between runs in order to support 58 | # the `--only-failures` and `--next-failure` CLI options. We recommend 59 | # you configure your source control system to ignore this file. 60 | config.example_status_persistence_file_path = "spec/examples.txt" 61 | 62 | # Limits the available syntax to the non-monkey patched syntax that is 63 | # recommended. For more details, see: 64 | # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ 65 | # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ 66 | # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode 67 | config.disable_monkey_patching! 68 | 69 | # Many RSpec users commonly either run the entire suite or an individual 70 | # file, and it's useful to allow more verbose output when running an 71 | # individual spec file. 72 | if config.files_to_run.one? 73 | # Use the documentation formatter for detailed output, 74 | # unless a formatter has already been configured 75 | # (e.g. via a command-line flag). 76 | config.default_formatter = "doc" 77 | end 78 | 79 | # Print the 10 slowest examples and example groups at the 80 | # end of the spec run, to help surface which specs are running 81 | # particularly slow. 82 | config.profile_examples = 10 83 | 84 | # Run specs in random order to surface order dependencies. If you find an 85 | # order dependency and want to debug it, you can fix the order by providing 86 | # the seed, which is printed after each run. 87 | # --seed 1234 88 | config.order = :random 89 | 90 | # Seed global randomization in this process using the `--seed` CLI option. 91 | # Setting this allows you to use `--seed` to deterministically reproduce 92 | # test failures related to randomization by passing the same `--seed` value 93 | # as the one that triggered the failure. 94 | Kernel.srand config.seed 95 | =end 96 | end 97 | -------------------------------------------------------------------------------- /spec/support/controller_spec_helper.rb: -------------------------------------------------------------------------------- 1 | module ControllerSpecHelper 2 | def token_generator(user_id) 3 | JsonWebToken.encode(user_id: user_id) 4 | end 5 | 6 | def expired_token_generator(user_id) 7 | JsonWebToken.encode({ user_id: user_id }, 10.seconds.ago) 8 | end 9 | 10 | def request_headers(user_id = nil) 11 | headers = { 12 | 'Content-Type' => 'application/json', 13 | 'Accept' => 'json' 14 | } 15 | headers['Authorization'] = token_generator(user_id) if user_id 16 | headers 17 | end 18 | 19 | def user_attributes(user) 20 | user.slice(:id, :name, :email, :first_name, :last_name, :visible) 21 | end 22 | end -------------------------------------------------------------------------------- /spec/support/request_spec_helper.rb: -------------------------------------------------------------------------------- 1 | module RequestSpecHelper 2 | def json 3 | JSON.parse(response.body) 4 | end 5 | end -------------------------------------------------------------------------------- /storage/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/storage/.keep -------------------------------------------------------------------------------- /test/controllers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/test/controllers/.keep -------------------------------------------------------------------------------- /test/fixtures/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/test/fixtures/.keep -------------------------------------------------------------------------------- /test/fixtures/files/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/test/fixtures/files/.keep -------------------------------------------------------------------------------- /test/integration/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/test/integration/.keep -------------------------------------------------------------------------------- /test/mailers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/test/mailers/.keep -------------------------------------------------------------------------------- /test/models/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/test/models/.keep -------------------------------------------------------------------------------- /test/test_helper.rb: -------------------------------------------------------------------------------- 1 | ENV['RAILS_ENV'] ||= 'test' 2 | require_relative '../config/environment' 3 | require 'rails/test_help' 4 | 5 | class ActiveSupport::TestCase 6 | # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. 7 | fixtures :all 8 | 9 | # Add more helper methods to be used by all tests here... 10 | end 11 | -------------------------------------------------------------------------------- /tmp/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/tmp/.keep -------------------------------------------------------------------------------- /vendor/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nmacawile/rails-chat-api/b39beefb1427ba1d4e382aed090391bfab9bb826/vendor/.keep --------------------------------------------------------------------------------