├── storage └── .keep ├── vendor └── .keep ├── lib ├── tasks │ └── .keep └── json_web_token.rb ├── .ruby-version ├── app ├── models │ ├── concerns │ │ └── .keep │ ├── application_record.rb │ ├── user_verification.rb │ ├── session.rb │ └── user.rb ├── controllers │ ├── concerns │ │ ├── .keep │ │ ├── create_session.rb │ │ └── authenticate_request.rb │ ├── application_controller.rb │ └── auth │ │ ├── registrations_controller.rb │ │ ├── confirmations_controller.rb │ │ ├── sessions_controller.rb │ │ └── passwords_controller.rb ├── views │ ├── layouts │ │ ├── mailer.text.erb │ │ └── mailer.html.erb │ ├── users │ │ └── _self.json.jbuilder │ └── auth │ │ └── auth.json.jbuilder ├── channels │ └── application_cable │ │ ├── channel.rb │ │ └── connection.rb ├── mailers │ └── application_mailer.rb └── jobs │ └── application_job.rb ├── Procfile ├── public └── robots.txt ├── config ├── spring.rb ├── environment.rb ├── initializers │ ├── mime_types.rb │ ├── application_controller_renderer.rb │ ├── filter_parameter_logging.rb │ ├── wrap_parameters.rb │ ├── cors.rb │ ├── backtrace_silencers.rb │ └── inflections.rb ├── boot.rb ├── cable.yml ├── credentials.yml.enc ├── application.yml ├── routes.rb ├── storage.yml ├── application.rb ├── puma.rb ├── locales │ └── en.yml ├── environments │ ├── test.rb │ ├── development.rb │ └── production.rb └── database.yml ├── bin ├── rake ├── rails ├── spring ├── setup └── bundle ├── config.ru ├── Rakefile ├── .gitattributes ├── Dockerfile ├── db ├── seeds.rb ├── migrate │ ├── 20210514180401_create_users.rb │ ├── 20210514182045_create_sessions.rb │ └── 20210514182639_create_user_verifications.rb └── schema.rb ├── docker-compose.yml ├── LICENSE ├── Gemfile ├── README.md ├── Gemfile.lock └── .gitignore /storage/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /vendor/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lib/tasks/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | ruby-2.7.3 2 | -------------------------------------------------------------------------------- /app/models/concerns/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /app/controllers/concerns/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.text.erb: -------------------------------------------------------------------------------- 1 | <%= yield %> 2 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: bundle exec rails s -b 0.0.0.0 -p ${PORT} 2 | logger: tail -f log/development.log -------------------------------------------------------------------------------- /app/models/application_record.rb: -------------------------------------------------------------------------------- 1 | class ApplicationRecord < ActiveRecord::Base 2 | self.abstract_class = true 3 | end 4 | -------------------------------------------------------------------------------- /app/views/users/_self.json.jbuilder: -------------------------------------------------------------------------------- 1 | json.extract! user, :id, :email, :name, :created_at 2 | json.confirmed user.confirmed? -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | -------------------------------------------------------------------------------- /app/views/auth/auth.json.jbuilder: -------------------------------------------------------------------------------- 1 | json.Authorization @token 2 | json.user do 3 | json.partial! "users/self", user: @user 4 | end -------------------------------------------------------------------------------- /app/channels/application_cable/channel.rb: -------------------------------------------------------------------------------- 1 | module ApplicationCable 2 | class Channel < ActionCable::Channel::Base 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /config/spring.rb: -------------------------------------------------------------------------------- 1 | Spring.watch( 2 | ".ruby-version", 3 | ".rbenv-vars", 4 | "tmp/restart.txt", 5 | "tmp/caching-dev.txt" 6 | ) 7 | -------------------------------------------------------------------------------- /app/channels/application_cable/connection.rb: -------------------------------------------------------------------------------- 1 | module ApplicationCable 2 | class Connection < ActionCable::Connection::Base 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/mailers/application_mailer.rb: -------------------------------------------------------------------------------- 1 | class ApplicationMailer < ActionMailer::Base 2 | default from: 'from@example.com' 3 | layout 'mailer' 4 | end 5 | -------------------------------------------------------------------------------- /bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | load File.expand_path("spring", __dir__) 3 | require_relative "../config/boot" 4 | require "rake" 5 | Rake.application.run 6 | -------------------------------------------------------------------------------- /config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the Rails application. 2 | require_relative "application" 3 | 4 | # Initialize the Rails application. 5 | Rails.application.initialize! 6 | -------------------------------------------------------------------------------- /config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require_relative "config/environment" 4 | 5 | run Rails.application 6 | Rails.application.load_server 7 | -------------------------------------------------------------------------------- /config/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 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | load File.expand_path("spring", __dir__) 3 | APP_PATH = File.expand_path('../config/application', __dir__) 4 | require_relative "../config/boot" 5 | require "rails/commands" 6 | -------------------------------------------------------------------------------- /app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::API 2 | ## ENTITIES 3 | include AuthenticateRequest 4 | 5 | ## MIDDLEWARE 6 | before_action :current_user 7 | end 8 | -------------------------------------------------------------------------------- /config/boot.rb: -------------------------------------------------------------------------------- 1 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) 2 | 3 | require "bundler/setup" # Set up gems listed in the Gemfile. 4 | require "bootsnap/setup" # Speed up boot time by caching expensive operations. 5 | -------------------------------------------------------------------------------- /config/cable.yml: -------------------------------------------------------------------------------- 1 | development: 2 | adapter: async 3 | 4 | test: 5 | adapter: test 6 | 7 | production: 8 | adapter: redis 9 | url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> 10 | channel_prefix: myapp_production 11 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # See https://git-scm.com/docs/gitattributes for more about git attribute files. 2 | 3 | # Mark the database schema as having been generated. 4 | db/schema.rb linguist-generated 5 | 6 | 7 | # Mark any vendored files as having been vendored. 8 | vendor/* linguist-vendored 9 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /app/jobs/application_job.rb: -------------------------------------------------------------------------------- 1 | class ApplicationJob < ActiveJob::Base 2 | # Automatically retry jobs that encountered a deadlock 3 | # retry_on ActiveRecord::Deadlocked 4 | 5 | # Most jobs are safe to ignore if the underlying records are no longer available 6 | # discard_on ActiveJob::DeserializationError 7 | end 8 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | -------------------------------------------------------------------------------- /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 += [ 5 | :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn 6 | ] 7 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ruby:2.7.3 2 | RUN apt-get update -qq && apt-get install -y postgresql-client 3 | RUN mkdir /myapp 4 | WORKDIR /myapp 5 | COPY Gemfile /myapp/Gemfile 6 | COPY Gemfile.lock /myapp/Gemfile.lock 7 | RUN mkdir -p /myapp/log && touch /myapp/log/development.log 8 | RUN gem install bundler 9 | RUN bundle install 10 | COPY . /myapp 11 | RUN gem install foreman -------------------------------------------------------------------------------- /db/seeds.rb: -------------------------------------------------------------------------------- 1 | # This file should contain all the record creation needed to seed the database with its default values. 2 | # The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). 3 | # 4 | # Examples: 5 | # 6 | # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) 7 | # Character.create(name: 'Luke', movie: movies.first) 8 | -------------------------------------------------------------------------------- /app/controllers/concerns/create_session.rb: -------------------------------------------------------------------------------- 1 | module CreateSession 2 | extend ActiveSupport::Concern 3 | require 'json_web_token' 4 | 5 | def jwt_session_create user_id 6 | user = User.find_by(id: user_id) 7 | session = user.sessions.build 8 | if user && session.save 9 | return JsonWebToken.encode({user_id: user_id, token: session.token}) 10 | else 11 | return nil 12 | end 13 | end 14 | end -------------------------------------------------------------------------------- /db/migrate/20210514180401_create_users.rb: -------------------------------------------------------------------------------- 1 | class CreateUsers < ActiveRecord::Migration[6.1] 2 | def change 3 | create_table :users do |t| 4 | t.string :name 5 | t.string :email 6 | t.string :password_digest 7 | t.datetime :email_confirmed_at 8 | 9 | t.timestamps 10 | end 11 | add_index :users, :email, unique: true 12 | add_index :users, :email_confirmed_at 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /config/credentials.yml.enc: -------------------------------------------------------------------------------- 1 | cP6/xwCtrPPrd87GVDS6qCq4pbHZJ90+3QMdNKjTSgLCyykCqn718JSiwBwuN4m51TFUv5jTCAryImPZGjlfgkHrmAUWeKej0e42z9GsxN06IKs4GojrqeXmL0JzbTEam58feilOLzAybnyHAAHhR8dMjQgP4mm7jRMlVePPIBvWU+zNmyY0MIvsluW6Vwh8Sol1Yi1xTVEVrAkRWS2jAFy51HN38nRRdSMSIBkoxd6BAeJueNIMcll6xxTvDksa3EKgqSkC3k3eKMjqCuEkZa8Z9fU+NO3G6P6Ps01vjQWeXz4896mwxq8N9CJKmiTl2HkvOPMzNLqEcW1hwe/ylffxNQMwIPy85ty2xaIDd2qd9XydSKAQ7bGwx8REJbbpKVP1DDmOzwTcr5VQHB41/i/d8Rod8Z8TTAQ8--GKVxzn/ucHPx1ocI--SggGRNRWHOtWBtqtRWG/vg== -------------------------------------------------------------------------------- /config/application.yml: -------------------------------------------------------------------------------- 1 | # Add configuration values here, as shown below. 2 | # 3 | # pusher_app_id: "2954" 4 | # pusher_key: 7381a978f7dd7f9a1117 5 | # pusher_secret: abdc3b896a0ffb85d373 6 | # stripe_api_key: sk_test_2J0l093xOyW72XUYJHE4Dv2r 7 | # stripe_publishable_key: pk_test_ro9jV5SNwGb1yYlQfzG17LHK 8 | # 9 | # production: 10 | # stripe_api_key: sk_live_EeHnL644i6zo4Iyq4v1KdV9H 11 | # stripe_publishable_key: pk_live_9lcthxpSIHbGwmdO941O1XVU 12 | JWT_SECRET: "somegreatsecret" 13 | -------------------------------------------------------------------------------- /db/migrate/20210514182045_create_sessions.rb: -------------------------------------------------------------------------------- 1 | class CreateSessions < ActiveRecord::Migration[6.1] 2 | def change 3 | create_table :sessions do |t| 4 | t.references :user, null: false, foreign_key: true 5 | t.datetime :last_used_at 6 | t.boolean :status, default: true 7 | t.string :token 8 | 9 | t.timestamps 10 | end 11 | add_index :sessions, :last_used_at 12 | add_index :sessions, :status 13 | add_index :sessions, :token, unique: true 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /bin/spring: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | if !defined?(Spring) && [nil, "development", "test"].include?(ENV["RAILS_ENV"]) 3 | gem "bundler" 4 | require "bundler" 5 | 6 | # Load Spring without loading other gems in the Gemfile, for speed. 7 | Bundler.locked_gems&.specs&.find { |spec| spec.name == "spring" }&.tap do |spring| 8 | Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path 9 | gem "spring", spring.version 10 | require "spring/binstub" 11 | rescue Gem::LoadError 12 | # Ignore when Spring is not installed. 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /db/migrate/20210514182639_create_user_verifications.rb: -------------------------------------------------------------------------------- 1 | class CreateUserVerifications < ActiveRecord::Migration[6.1] 2 | def change 3 | create_table :user_verifications do |t| 4 | t.references :user, null: false, foreign_key: true 5 | t.string :status, default: 'pending' 6 | t.string :token 7 | t.string :verify_type 8 | 9 | t.timestamps 10 | end 11 | add_index :user_verifications, :status 12 | add_index :user_verifications, :token, unique: true 13 | add_index :user_verifications, :verify_type 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /lib/json_web_token.rb: -------------------------------------------------------------------------------- 1 | class JsonWebToken 2 | require 'jwt' 3 | SECRET_KEY = ENV['JWT_SECRET'] 4 | JWT_EXPIRY = 1.day 5 | 6 | def self.encode(payload, exp = JWT_EXPIRY.from_now) 7 | payload[:exp] = exp.to_i 8 | JWT.encode(payload, SECRET_KEY, 'HS512') 9 | end 10 | 11 | def self.decode(token) 12 | decoded = JWT.decode(token, SECRET_KEY, true, {algorithm: 'HS512'})[0] 13 | res = HashWithIndifferentAccess.new decoded 14 | if Time.at(res[:exp]) > Time.now 15 | res 16 | else 17 | nil 18 | end 19 | rescue 20 | return nil 21 | end 22 | end -------------------------------------------------------------------------------- /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 | # Rails.application.config.middleware.insert_before 0, Rack::Cors do 9 | # allow do 10 | # origins 'example.com' 11 | # 12 | # resource '*', 13 | # headers: :any, 14 | # methods: [:get, :post, :put, :patch, :delete, :options, :head] 15 | # end 16 | # end 17 | -------------------------------------------------------------------------------- /config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| /my_noisy_library/.match?(line) } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code 7 | # by setting BACKTRACE=1 before calling your invocation, like "BACKTRACE=1 ./bin/rails runner 'MyClass.perform'". 8 | Rails.backtrace_cleaner.remove_silencers! if ENV["BACKTRACE"] 9 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | services: 3 | 4 | db: 5 | image: postgres 6 | volumes: 7 | - db:/var/lib/postgresql/data 8 | ports: 9 | - "5432:5432" # use port that you want to in your local instead of 5432 10 | environment: 11 | - POSTGRES_HOST_AUTH_METHOD=trust 12 | 13 | web: 14 | build: . 15 | command: bash -c "rm -f tmp/pids/server.pid && foreman start -f Procfile" 16 | environment: 17 | - PORT=3000 18 | volumes: 19 | - .:/myapp 20 | - rails_log:/myapp/log 21 | ports: 22 | - "3000:3000" # use port that you want to in your local instead of 3091 23 | depends_on: 24 | - db 25 | 26 | volumes: 27 | db: 28 | rails_log: -------------------------------------------------------------------------------- /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/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html 3 | namespace :auth do 4 | post "sign_up", to: "registrations#create" 5 | delete "destroy", to: "registrations#destroy" 6 | post "sign_in", to: "sessions#create" 7 | get "validate_token", to: "sessions#validate_token" 8 | delete "sign_out", to: "sessions#destroy" 9 | get "confirm_email", to: "confirmations#confirm_email" 10 | put "resend_confirm_email", to: "confirmations#resend_confirm_email" 11 | post "forgot_password_email", to: "passwords#create_reset_email" 12 | get "verify_reset_password_email", to: "passwords#verify_reset_email_token" 13 | put "reset_password", to: "passwords#reset_password" 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /app/models/user_verification.rb: -------------------------------------------------------------------------------- 1 | class UserVerification < ApplicationRecord 2 | TOKEN_LENGTH = 32 3 | TOKEN_LIFETIME = 6.hours 4 | 5 | validates :status, presence: true, inclusion: %w[pending done failed] 6 | validates :verify_type, presence: true, inclusion: %w[confirm_email reset_email] 7 | 8 | validates :token, presence: true, uniqueness: {case_sensitive: true} 9 | 10 | belongs_to :user 11 | before_validation :generate_token, on: :create 12 | 13 | def self.search status='pending', verify_type='confirm_email', token 14 | UserVerification.where(status: status, verify_type: verify_type).find_by(token: token) 15 | end 16 | 17 | def generate_token 18 | self.token = loop do 19 | random_token = SecureRandom.base58(TOKEN_LENGTH) 20 | break random_token unless UserVerification.exists?(token: random_token) 21 | end 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /app/models/session.rb: -------------------------------------------------------------------------------- 1 | class Session < ApplicationRecord 2 | TOKEN_LENGTH = 32 3 | TOKEN_LIFETIME = 1.hour 4 | 5 | validates :token, presence: true, uniqueness: {case_sensitive: true} 6 | 7 | belongs_to :user 8 | 9 | before_validation :generate_token, on: :create 10 | after_create :used 11 | 12 | def is_late? 13 | if (last_used_at + TOKEN_LIFETIME) >= Time.now 14 | false 15 | else 16 | update(status: false) 17 | true 18 | end 19 | end 20 | 21 | def self.search user_id, token 22 | Session.find_by(token: token, status: true, user_id: user_id) 23 | end 24 | 25 | def used 26 | update(last_used_at: Time.now) 27 | end 28 | 29 | def close 30 | update(status: false) 31 | end 32 | 33 | def generate_token 34 | self.token = loop do 35 | random_token = SecureRandom.base58(TOKEN_LENGTH) 36 | break random_token unless Session.exists?(token: random_token) 37 | end 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /app/controllers/concerns/authenticate_request.rb: -------------------------------------------------------------------------------- 1 | module AuthenticateRequest 2 | extend ActiveSupport::Concern 3 | require 'json_web_token' 4 | 5 | def authenticate_user 6 | return render status: :unauthorized, json: {errors: [I18n.t('errors.controllers.auth.unauthenticated')]} unless current_user 7 | end 8 | 9 | def current_user 10 | @current_user = nil 11 | if decoded_token 12 | data = decoded_token 13 | user = User.find_by(id: data[:user_id]) 14 | session = Session.search(data[:user_id], data[:token]) 15 | if user && session && !session.is_late? 16 | session.used 17 | @current_user ||= user 18 | end 19 | end 20 | end 21 | 22 | def decoded_token 23 | header = request.headers['Authorization'] 24 | header = header.split(' ').last if header 25 | if header 26 | begin 27 | @decoded_token ||= JsonWebToken.decode(header) 28 | rescue Error => e 29 | return render json: {errors: [e.message]}, status: :unauthorized 30 | end 31 | end 32 | end 33 | end -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Sulman Baig 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require "fileutils" 3 | 4 | # path to your application root. 5 | APP_ROOT = File.expand_path('..', __dir__) 6 | 7 | def system!(*args) 8 | system(*args) || abort("\n== Command #{args} failed ==") 9 | end 10 | 11 | FileUtils.chdir APP_ROOT do 12 | # This script is a way to set up or update your development environment automatically. 13 | # This script is idempotent, so that you can run it at any time and get an expectable outcome. 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 | # FileUtils.cp 'config/database.yml.sample', 'config/database.yml' 23 | # end 24 | 25 | puts "\n== Preparing database ==" 26 | system! 'bin/rails db:prepare' 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /app/controllers/auth/registrations_controller.rb: -------------------------------------------------------------------------------- 1 | class Auth::RegistrationsController < ApplicationController 2 | include CreateSession 3 | before_action :authenticate_user, only: :destroy 4 | 5 | def create 6 | @user = User.new(registration_params) 7 | 8 | if @user.save 9 | @token = jwt_session_create @user.id 10 | if @token 11 | @token = "Bearer #{@token}" 12 | return success_user_created 13 | else 14 | return error_token_create 15 | end 16 | else 17 | error_user_save 18 | end 19 | end 20 | 21 | def destroy 22 | current_user.destroy 23 | success_user_destroy 24 | end 25 | 26 | protected 27 | 28 | def success_user_created 29 | response.headers['Authorization'] = "Bearer #{@token}" 30 | render status: :created, template: "auth/auth" 31 | end 32 | 33 | def success_user_destroy 34 | render status: :no_content, json: {} 35 | end 36 | 37 | def error_token_create 38 | render status: :unprocessable_entity, json: { errors: [I18n.t('errors.controllers.auth.token_not_created')] } 39 | end 40 | 41 | def error_user_save 42 | render status: :unprocessable_entity, json: { errors: @user.errors.full_messages } 43 | end 44 | 45 | private 46 | 47 | def registration_params 48 | params.permit(:name, :email, :password) 49 | end 50 | end -------------------------------------------------------------------------------- /config/application.rb: -------------------------------------------------------------------------------- 1 | require_relative "boot" 2 | 3 | require "rails" 4 | # Pick the frameworks you want: 5 | require "active_model/railtie" 6 | require "active_job/railtie" 7 | require "active_record/railtie" 8 | require "active_storage/engine" 9 | require "action_controller/railtie" 10 | require "action_mailer/railtie" 11 | require "action_mailbox/engine" 12 | require "action_text/engine" 13 | require "action_view/railtie" 14 | require "action_cable/engine" 15 | # require "sprockets/railtie" 16 | # require "rails/test_unit/railtie" 17 | 18 | # Require the gems listed in Gemfile, including any gems 19 | # you've limited to :test, :development, or :production. 20 | Bundler.require(*Rails.groups) 21 | 22 | module Myapp 23 | class Application < Rails::Application 24 | # Initialize configuration defaults for originally generated Rails version. 25 | config.load_defaults 6.1 26 | 27 | # Configuration for the application, engines, and railties goes here. 28 | # 29 | # These settings can be overridden in specific environments using the files 30 | # in config/environments, which are processed later. 31 | # 32 | # config.time_zone = "Central Time (US & Canada)" 33 | # config.eager_load_paths << Rails.root.join("extras") 34 | 35 | # Only loads a smaller set of middleware suitable for API only apps. 36 | # Middleware like session, flash, cookies can be added back manually. 37 | # Skip views, helpers and assets when generating a new resource. 38 | config.api_only = true 39 | config.eager_load_paths << Rails.root.join('lib') 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | git_source(:github) { |repo| "https://github.com/#{repo}.git" } 3 | 4 | ruby '2.7.3' 5 | 6 | # Bundle edge Rails instead: gem 'rails', github: 'rails/rails', branch: 'main' 7 | gem 'rails', '~> 6.1.3', '>= 6.1.3.2' 8 | # Use postgresql as the database for Active Record 9 | gem 'pg', '~> 1.1' 10 | # Use Puma as the app server 11 | gem 'puma', '~> 5.0' 12 | # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder 13 | gem 'jbuilder', '~> 2.7' 14 | # Use Redis adapter to run Action Cable in production 15 | # gem 'redis', '~> 4.0' 16 | # Use Active Model has_secure_password 17 | gem 'bcrypt', '~> 3.1.7' 18 | 19 | gem 'jwt', '~> 2.2', '>= 2.2.3' 20 | gem 'figaro', '~> 1.2' 21 | 22 | # Use Active Storage variant 23 | # gem 'image_processing', '~> 1.2' 24 | 25 | # Reduces boot times through caching; required in config/boot.rb 26 | gem 'bootsnap', '>= 1.4.4', require: false 27 | 28 | # Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible 29 | # gem 'rack-cors' 30 | 31 | group :development, :test do 32 | # Call 'byebug' anywhere in the code to stop execution and get a debugger console 33 | gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] 34 | end 35 | 36 | group :development do 37 | gem 'listen', '~> 3.3' 38 | # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring 39 | gem 'spring' 40 | end 41 | 42 | # Windows does not include zoneinfo files, so bundle the tzinfo-data gem 43 | gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] 44 | -------------------------------------------------------------------------------- /app/controllers/auth/confirmations_controller.rb: -------------------------------------------------------------------------------- 1 | class Auth::ConfirmationsController < ApplicationController 2 | include CreateSession 3 | 4 | before_action :authenticate_user, only: :resend_confirm_email 5 | 6 | def confirm_email 7 | return error_insufficient_params unless params[:token] 8 | 9 | verification = UserVerification.search(:pending, :confirm_email, params[:token]) 10 | return error_invalid_token if verification.nil? 11 | if (verification.created_at + UserVerification::TOKEN_LIFETIME) > Time.now 12 | verification.user.confirm 13 | verification.update(status: :done) 14 | @token = jwt_session_create verification.user_id 15 | # Redirect to the page that says the email is confirmed successfully or can be redirected to the app 16 | redirect_to "#{ENV['REDIRECT_CONFIRM_EMAIL']}?token=#{@token}" 17 | else 18 | error_confirm_email_late 19 | end 20 | end 21 | 22 | def resend_confirm_email 23 | current_user.send_confirm_email 24 | success_resend_confirm_email 25 | end 26 | 27 | protected 28 | 29 | def success_resend_confirm_email 30 | render status: :ok, json: {message: I18n.t('messages.resend_confirm_email')} 31 | end 32 | 33 | def error_insufficient_params 34 | render status: :unprocessable_entity, json: {errors: [I18n.t('errors.controllers.insufficient_params')]} 35 | end 36 | 37 | def error_confirm_email_late 38 | render status: :unauthorized, json: {errors: [I18n.t('errors.controllers.verifications.late')]} 39 | end 40 | 41 | def error_invalid_token 42 | render status: :unauthorized, json: {errors: [I18n.t('errors.controllers.verifications.invalid_token')]} 43 | end 44 | end -------------------------------------------------------------------------------- /app/models/user.rb: -------------------------------------------------------------------------------- 1 | class User < ApplicationRecord 2 | has_secure_password 3 | 4 | validates :name, presence: true 5 | validates :email, presence: true, uniqueness: { case_sensitive: false }, format: { with: /\A([\w+\-]\.?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/, message: I18n.t("errors.models.user.format_email") } 6 | validates :password, format: { with: /\A(?=.*).{8,72}\z/, message: I18n.t("errors.models.user.format_password") }, if: :password_required? 7 | 8 | before_save :downcase_email! 9 | after_create :send_confirm_email 10 | 11 | has_many :sessions, dependent: :destroy 12 | has_many :user_verifications, dependent: :destroy 13 | 14 | def confirmed? 15 | !email_confirmed_at.nil? 16 | end 17 | 18 | def confirm 19 | update(email_confirmed_at: Time.now) 20 | end 21 | 22 | def unconfirm 23 | update(email_confirmed_at: nil) 24 | end 25 | 26 | def send_confirm_email 27 | unless confirmed? 28 | verification = UserVerification.create(user_id: id, verify_type: :confirm_email) 29 | url = Rails.application.routes.url_helpers.auth_confirm_email_url(host: "localhost:3000", token: verification.token) 30 | # ADD Email Job with `url` added in "CONFIRM EMAIL" button 31 | end 32 | end 33 | 34 | def send_reset_email 35 | if confirmed? 36 | verification = UserVerification.create(user_id: id, verify_type: :reset_email) 37 | url = Rails.application.routes.url_helpers.auth_verify_reset_password_email_url(host: "localhost:3000", token: verification.token) 38 | # ADD Email Job with `url` added in "RESET YOUR EMAIL" button 39 | end 40 | end 41 | 42 | private 43 | 44 | # is password required for user? 45 | def password_required? 46 | password_digest.nil? || !password.blank? 47 | end 48 | 49 | # downcase email 50 | def downcase_email! 51 | email&.downcase! 52 | end 53 | end 54 | -------------------------------------------------------------------------------- /config/puma.rb: -------------------------------------------------------------------------------- 1 | # Puma can serve each request in a thread from an internal thread pool. 2 | # The `threads` method setting takes two numbers: a minimum and maximum. 3 | # Any libraries that use thread pools should be configured to match 4 | # the maximum value specified for Puma. Default is set to 5 threads for minimum 5 | # and maximum; this matches the default thread size of Active Record. 6 | # 7 | max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } 8 | min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } 9 | threads min_threads_count, max_threads_count 10 | 11 | # Specifies the `worker_timeout` threshold that Puma will use to wait before 12 | # terminating a worker in development environments. 13 | # 14 | worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development" 15 | 16 | # Specifies the `port` that Puma will listen on to receive requests; default is 3000. 17 | # 18 | port ENV.fetch("PORT") { 3000 } 19 | 20 | # Specifies the `environment` that Puma will run in. 21 | # 22 | environment ENV.fetch("RAILS_ENV") { "development" } 23 | 24 | # Specifies the `pidfile` that Puma will use. 25 | pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } 26 | 27 | # Specifies the number of `workers` to boot in clustered mode. 28 | # Workers are forked web server processes. If using threads and workers together 29 | # the concurrency of the application would be max `threads` * `workers`. 30 | # Workers do not work on JRuby or Windows (both of which do not support 31 | # processes). 32 | # 33 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 } 34 | 35 | # Use the `preload_app!` method when specifying a `workers` number. 36 | # This directive tells Puma to first boot the application and load code 37 | # before forking the application. This takes advantage of Copy On Write 38 | # process behavior so workers use less memory. 39 | # 40 | # preload_app! 41 | 42 | # Allow puma to be restarted by `rails restart` command. 43 | plugin :tmp_restart 44 | -------------------------------------------------------------------------------- /config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Files in the config/locales directory are used for internationalization 2 | # and are automatically loaded by Rails. If you want to use locales other 3 | # than English, add the necessary files in this directory. 4 | # 5 | # To use the locales, use `I18n.t`: 6 | # 7 | # I18n.t 'hello' 8 | # 9 | # In views, this is aliased to just `t`: 10 | # 11 | # <%= t('hello') %> 12 | # 13 | # To use a different locale, set it with `I18n.locale`: 14 | # 15 | # I18n.locale = :es 16 | # 17 | # This would use the information in config/locales/es.yml. 18 | # 19 | # The following keys must be escaped otherwise they will not be retrieved by 20 | # the default I18n backend: 21 | # 22 | # true, false, on, off, yes, no 23 | # 24 | # Instead, surround them with single quotes. 25 | # 26 | # en: 27 | # 'true': 'foo' 28 | # 29 | # To learn more, please read the Rails Internationalization guide 30 | # available at https://guides.rubyonrails.org/i18n.html. 31 | 32 | en: 33 | messages: 34 | resend_confirm_email: "An email is on its way with instructions to confirm your account." 35 | reset_password_email_sent: "An email is on its way with instructions to reset your password." 36 | email_reset_success: "Your password has been changed successfully." 37 | 38 | errors: 39 | models: 40 | user: 41 | format_email: "is not valid. Please provide valid email to continue." 42 | format_password: "is not valid. Password must be 8 to 72 characters long." 43 | 44 | controllers: 45 | insufficient_params: "All required parameters are not provided to perform this action." 46 | auth: 47 | token_not_created: "There was some error creating auth token. Please try again." 48 | unauthenticated: "You need to be signed into app to perform this action." 49 | invalid_credentials: "Email/Password is not correct. Please try again." 50 | password_mismatch: "Password and Confirm Password don't match. Please try again." 51 | verifications: 52 | late: "This token is expired. Please try again later." 53 | invalid_token: "This token is invalid. Please try again." 54 | -------------------------------------------------------------------------------- /app/controllers/auth/sessions_controller.rb: -------------------------------------------------------------------------------- 1 | class Auth::SessionsController < ApplicationController 2 | include CreateSession 3 | 4 | before_action :authenticate_user, only: [:validate_token, :destroy] 5 | 6 | def create 7 | return error_insufficient_params unless params[:email].present? && params[:password].present? 8 | @user = User.find_by(email: params[:email]) 9 | if @user 10 | if @user.authenticate(params[:password]) 11 | @token = jwt_session_create @user.id 12 | if @token 13 | @token = "Bearer #{@token}" 14 | return success_session_created 15 | else 16 | return error_token_create 17 | end 18 | else 19 | return error_invalid_credentials 20 | end 21 | else 22 | return error_invalid_credentials 23 | end 24 | end 25 | 26 | def validate_token 27 | @token = request.headers['Authorization'] 28 | @user = current_user 29 | success_valid_token 30 | end 31 | 32 | def destroy 33 | headers = request.headers['Authorization'].split(' ').last 34 | session = Session.find_by(token: JsonWebToken.decode(headers)[:token]) 35 | session.close 36 | success_session_destroy 37 | end 38 | 39 | protected 40 | 41 | def success_session_created 42 | response.headers['Authorization'] = "Bearer #{@token}" 43 | render status: :created, template: "auth/auth" 44 | end 45 | 46 | def success_valid_token 47 | response.headers['Authorization'] = "Bearer #{@token}" 48 | render status: :ok, template: "auth/auth" 49 | end 50 | 51 | def success_session_destroy 52 | render status: :no_content, json: {} 53 | end 54 | 55 | def error_invalid_credentials 56 | render status: :unauthorized, json: {errors: [I18n.t('errors.controllers.auth.invalid_credentials')]} 57 | end 58 | 59 | def error_token_create 60 | render status: :unprocessable_entity, json: {errors: [I18n.t('errors.controllers.auth.token_not_created')]} 61 | end 62 | 63 | def error_insufficient_params 64 | render status: :unprocessable_entity, json: {errors: [I18n.t('errors.controllers.insufficient_params')]} 65 | end 66 | end -------------------------------------------------------------------------------- /config/environments/test.rb: -------------------------------------------------------------------------------- 1 | require "active_support/core_ext/integer/time" 2 | 3 | # The test environment is used exclusively to run your application's 4 | # test suite. You never need to work with it otherwise. Remember that 5 | # your test database is "scratch space" for the test suite and is wiped 6 | # and recreated between test runs. Don't rely on the data there! 7 | 8 | Rails.application.configure do 9 | # Settings specified here will take precedence over those in config/application.rb. 10 | 11 | config.cache_classes = false 12 | config.action_view.cache_template_loading = true 13 | 14 | # Do not eager load code on boot. This avoids loading your whole application 15 | # just for the purpose of running a single test. If you are using a tool that 16 | # preloads Rails for running tests, you may have to set it to true. 17 | config.eager_load = false 18 | 19 | # Configure public file server for tests with Cache-Control for performance. 20 | config.public_file_server.enabled = true 21 | config.public_file_server.headers = { 22 | 'Cache-Control' => "public, max-age=#{1.hour.to_i}" 23 | } 24 | 25 | # Show full error reports and disable caching. 26 | config.consider_all_requests_local = true 27 | config.action_controller.perform_caching = false 28 | config.cache_store = :null_store 29 | 30 | # Raise exceptions instead of rendering exception templates. 31 | config.action_dispatch.show_exceptions = false 32 | 33 | # Disable request forgery protection in test environment. 34 | config.action_controller.allow_forgery_protection = false 35 | 36 | # Store uploaded files on the local file system in a temporary directory. 37 | config.active_storage.service = :test 38 | 39 | config.action_mailer.perform_caching = false 40 | 41 | # Tell Action Mailer not to deliver emails to the real world. 42 | # The :test delivery method accumulates sent emails in the 43 | # ActionMailer::Base.deliveries array. 44 | config.action_mailer.delivery_method = :test 45 | 46 | # Print deprecation notices to the stderr. 47 | config.active_support.deprecation = :stderr 48 | 49 | # Raise exceptions for disallowed deprecations. 50 | config.active_support.disallowed_deprecation = :raise 51 | 52 | # Tell Active Support which deprecation messages to disallow. 53 | config.active_support.disallowed_deprecation_warnings = [] 54 | 55 | # Raises error for missing translations. 56 | # config.i18n.raise_on_missing_translations = true 57 | 58 | # Annotate rendered view with file names. 59 | # config.action_view.annotate_rendered_view_with_filenames = true 60 | end 61 | -------------------------------------------------------------------------------- /app/controllers/auth/passwords_controller.rb: -------------------------------------------------------------------------------- 1 | class Auth::PasswordsController < ApplicationController 2 | include CreateSession 3 | 4 | before_action :authenticate_user, only: [:reset_password] 5 | 6 | def create_reset_email 7 | return error_insufficient_params unless params[:email].present? 8 | user = User.find_by(email: params[:email]) 9 | user.send_reset_email unless user.nil? 10 | success_send_reset_email 11 | end 12 | 13 | def verify_reset_email_token 14 | return error_insufficient_params unless params[:token] 15 | verification = UserVerification.search(:pending, :reset_email, params[:token]) 16 | return error_invalid_token if verification.nil? 17 | if (verification.created_at + UserVerification::TOKEN_LIFETIME) > Time.now 18 | verification.update(status: :done) 19 | verification.user.confirm unless verification.user.confirmed? 20 | token = jwt_session_create verification.user_id 21 | # Redirect to the page where a logged in user can change its password 22 | redirect_to "#{ENV['REDIRECT_RESET_EMAIL']}?token=#{token}" 23 | else 24 | error_reset_email_late 25 | end 26 | end 27 | 28 | def reset_password 29 | @user = current_user 30 | return error_insufficient_params unless params[:password].present? && params[:confirm_password].present? 31 | return error_password_mismatch if params[:password] != params[:confirm_password] 32 | if @user.update(password: params[:password]) 33 | return success_password_reset 34 | else 35 | return error_user_save 36 | end 37 | end 38 | 39 | protected 40 | 41 | def error_insufficient_params 42 | render status: :unprocessable_entity, json: {errors: [I18n.t('errors.controllers.insufficient_params')]} 43 | end 44 | 45 | def success_send_reset_email 46 | render status: :created, json: {message: I18n.t('messages.reset_password_email_sent')} 47 | end 48 | 49 | def success_password_reset 50 | render status: :ok, json: {message: I18n.t('messages.email_reset_success')} 51 | end 52 | 53 | def error_reset_email_late 54 | render status: :unauthorized, json: {errors: [I18n.t('errors.controllers.verifications.late')]} 55 | end 56 | 57 | def error_invalid_token 58 | render status: :unauthorized, json: {errors: [I18n.t('errors.controllers.verifications.invalid_token')]} 59 | end 60 | 61 | def error_user_save 62 | render status: :unprocessable_entity, json: {errors: @user.errors.full_messages} 63 | end 64 | 65 | def error_password_mismatch 66 | render status: :unprocessable_entity, json: {errors: [I18n.t('errors.controllers.auth.password_mismatch')]} 67 | end 68 | end -------------------------------------------------------------------------------- /config/environments/development.rb: -------------------------------------------------------------------------------- 1 | require "active_support/core_ext/integer/time" 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # In the development environment your application's code is reloaded any time 7 | # it changes. This slows down response time but is perfect for development 8 | # since you don't have to restart the web server when you make code changes. 9 | config.cache_classes = false 10 | 11 | # Do not eager load code on boot. 12 | config.eager_load = false 13 | 14 | # Show full error reports. 15 | config.consider_all_requests_local = true 16 | 17 | # Enable/disable caching. By default caching is disabled. 18 | # Run rails dev:cache to toggle caching. 19 | if Rails.root.join('tmp', 'caching-dev.txt').exist? 20 | config.cache_store = :memory_store 21 | config.public_file_server.headers = { 22 | 'Cache-Control' => "public, max-age=#{2.days.to_i}" 23 | } 24 | else 25 | config.action_controller.perform_caching = false 26 | 27 | config.cache_store = :null_store 28 | end 29 | 30 | # Store uploaded files on the local file system (see config/storage.yml for options). 31 | config.active_storage.service = :local 32 | 33 | # Don't care if the mailer can't send. 34 | config.action_mailer.raise_delivery_errors = false 35 | 36 | config.action_mailer.perform_caching = false 37 | 38 | # Print deprecation notices to the Rails logger. 39 | config.active_support.deprecation = :log 40 | 41 | # Raise exceptions for disallowed deprecations. 42 | config.active_support.disallowed_deprecation = :raise 43 | 44 | # Tell Active Support which deprecation messages to disallow. 45 | config.active_support.disallowed_deprecation_warnings = [] 46 | 47 | # Raise an error on page load if there are pending migrations. 48 | config.active_record.migration_error = :page_load 49 | 50 | # Highlight code that triggered database queries in logs. 51 | config.active_record.verbose_query_logs = true 52 | 53 | 54 | # Raises error for missing translations. 55 | # config.i18n.raise_on_missing_translations = true 56 | 57 | # Annotate rendered view with file names. 58 | # config.action_view.annotate_rendered_view_with_filenames = true 59 | 60 | # Use an evented file watcher to asynchronously detect changes in source code, 61 | # routes, locales, etc. This feature depends on the listen gem. 62 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker 63 | 64 | # Uncomment if you wish to allow Action Cable access from any origin. 65 | # config.action_cable.disable_request_forgery_protection = true 66 | end 67 | -------------------------------------------------------------------------------- /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 | # This file is the source Rails uses to define your schema when running `bin/rails 6 | # db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to 7 | # be faster and is potentially less error prone than running all of your 8 | # migrations from scratch. Old migrations may fail to apply correctly if those 9 | # migrations use external dependencies or application code. 10 | # 11 | # It's strongly recommended that you check this file into your version control system. 12 | 13 | ActiveRecord::Schema.define(version: 2021_05_14_182639) do 14 | 15 | # These are extensions that must be enabled in order to support this database 16 | enable_extension "plpgsql" 17 | 18 | create_table "sessions", force: :cascade do |t| 19 | t.bigint "user_id", null: false 20 | t.datetime "last_used_at" 21 | t.boolean "status", default: true 22 | t.string "token" 23 | t.datetime "created_at", precision: 6, null: false 24 | t.datetime "updated_at", precision: 6, null: false 25 | t.index ["last_used_at"], name: "index_sessions_on_last_used_at" 26 | t.index ["status"], name: "index_sessions_on_status" 27 | t.index ["token"], name: "index_sessions_on_token", unique: true 28 | t.index ["user_id"], name: "index_sessions_on_user_id" 29 | end 30 | 31 | create_table "user_verifications", force: :cascade do |t| 32 | t.bigint "user_id", null: false 33 | t.string "status", default: "pending" 34 | t.string "token" 35 | t.string "verify_type" 36 | t.datetime "created_at", precision: 6, null: false 37 | t.datetime "updated_at", precision: 6, null: false 38 | t.index ["status"], name: "index_user_verifications_on_status" 39 | t.index ["token"], name: "index_user_verifications_on_token", unique: true 40 | t.index ["user_id"], name: "index_user_verifications_on_user_id" 41 | t.index ["verify_type"], name: "index_user_verifications_on_verify_type" 42 | end 43 | 44 | create_table "users", force: :cascade do |t| 45 | t.string "name" 46 | t.string "email" 47 | t.string "password_digest" 48 | t.datetime "email_confirmed_at" 49 | t.datetime "created_at", precision: 6, null: false 50 | t.datetime "updated_at", precision: 6, null: false 51 | t.index ["email"], name: "index_users_on_email", unique: true 52 | t.index ["email_confirmed_at"], name: "index_users_on_email_confirmed_at" 53 | end 54 | 55 | add_foreign_key "sessions", "users" 56 | add_foreign_key "user_verifications", "users" 57 | end 58 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # README 2 | 3 | created by @[sulmanweb](https://sulmanweb.com) 4 | 5 | ### Built With 6 | 7 | - Docker 8 | - Ruby 2.7.3 9 | - Postgresql 10 | --- 11 | 12 | ## How To Run 13 | 14 | 1. Install [Docker](https://www.docker.com/) 15 | 16 | 2. In terminal run 17 | ```bash 18 | docker compose up -d --build 19 | ``` 20 | 21 | 3. After operation completes, run: 22 | ```bash 23 | docker compose run web rails db:create 24 | ``` 25 | 26 | 4. Finally run: 27 | ```bash 28 | docker compose run web rails db:migrate 29 | ``` 30 | 31 | 5. The app is available now at [http://localhost:3000](http://localhost:3000) 32 | 33 | 6. To run the console run: 34 | ```bash 35 | docker compose run web rails console 36 | ``` 37 | --- 38 | 39 | ## Services 40 | 41 | **Sign Up** 42 | 43 | `POST` [http://localhost:3000/auth/sign_up](http://localhost:3000/auth/sign_up) 44 | ```json 45 | { 46 | "email": "hello@hello.com", 47 | "password": "abcd@1234", 48 | "name": "Hello World" 49 | } 50 | ``` 51 | 52 | **Destroy Self User** 53 | 54 | `DELETE` [http://localhost:3000/auth/destroy](http://localhost:3000/auth/destroy) 55 | 56 | `headers` 57 | 58 | ``` 59 | Authorization: Bearer xxxxxxxxx 60 | ``` 61 | Empty Body 62 | 63 | **Sign In** 64 | 65 | `POST` [http://localhost:3000/auth/sign_in](http://localhost:3000/auth/sign_in) 66 | ```json 67 | { 68 | "email": "hello@hello.com", 69 | "password": "abcd@1234" 70 | } 71 | ``` 72 | 73 | **Validate Token** 74 | 75 | `GET` [http://localhost:3000/auth/validate_token](http://localhost:3000/auth/validate_token) 76 | 77 | `headers` 78 | 79 | ``` 80 | Authorization: Bearer xxxxxxxxx 81 | ``` 82 | 83 | **Sign Out** 84 | 85 | `DELETE` [http://localhost:3000/auth/sign_out](http://localhost:3000/auth/sign_out) 86 | 87 | `headers` 88 | 89 | ``` 90 | Authorization: Bearer xxxxxxxxx 91 | ``` 92 | 93 | **Confirm Email** 94 | 95 | `GET` [http://localhost:3000/auth/confirm_email](http://localhost:3000/auth/confirm_email) 96 | 97 | `query params` 98 | 99 | ``` 100 | token: xxxxxxxxx 101 | ``` 102 | 103 | **Resend Confirmation Email** 104 | 105 | `PUT` [http://localhost:3000/auth/resend_confirm_email](http://localhost:3000/auth/resend_confirm_email) 106 | 107 | `headers` 108 | 109 | ``` 110 | Authorization: Bearer xxxxxxxxx 111 | ``` 112 | Empty Body 113 | 114 | **Forgot Password Request** 115 | 116 | `POST` [http://localhost:3000/auth/forgot_password_email](http://localhost:3000/auth/forgot_password_email) 117 | 118 | ```json 119 | { 120 | "email": "hello@world.com" 121 | } 122 | ``` 123 | 124 | **Verify Forgot Password Token Received In Email** 125 | 126 | `GET` [http://localhost:3000/auth/verify_reset_password_email](http://localhost:3000/auth/verify_reset_password_email) 127 | 128 | `query params` 129 | 130 | ``` 131 | token: xxxxxxxxx 132 | ``` 133 | 134 | **Change Password For Logged In User** 135 | 136 | `PUT` [http://localhost:3000/auth/reset_password](http://localhost:3000/auth/reset_password) 137 | 138 | `headers` 139 | 140 | ``` 141 | Authorization: Bearer xxxxxxxxx 142 | ``` 143 | 144 | OR `query params` 145 | 146 | ``` 147 | token: xxxxxxxxx 148 | ``` 149 | 150 | ```json 151 | { 152 | "password": "abcd@1234", 153 | "confirm_password": "abcd@1234" 154 | } 155 | ``` 156 | --- 157 | ## License 158 | 159 | **MIT** -------------------------------------------------------------------------------- /config/database.yml: -------------------------------------------------------------------------------- 1 | # PostgreSQL. Versions 9.3 and up are supported. 2 | # 3 | # Install the pg driver: 4 | # gem install pg 5 | # On macOS with Homebrew: 6 | # gem install pg -- --with-pg-config=/usr/local/bin/pg_config 7 | # On macOS 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 | host: db 21 | username: postgres 22 | password: 23 | # For details on connection pooling, see Rails configuration guide 24 | # https://guides.rubyonrails.org/configuring.html#database-pooling 25 | pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> 26 | 27 | development: 28 | <<: *default 29 | database: myapp_development 30 | 31 | # The specified database role being used to connect to postgres. 32 | # To create additional roles in postgres see `$ createuser --help`. 33 | # When left blank, postgres will use the default role. This is 34 | # the same name as the operating system user running Rails. 35 | #username: myapp 36 | 37 | # The password associated with the postgres role (username). 38 | #password: 39 | 40 | # Connect on a TCP socket. Omitted by default since the client uses a 41 | # domain socket that doesn't need configuration. Windows does not have 42 | # domain sockets, so uncomment these lines. 43 | #host: localhost 44 | 45 | # The TCP port the server listens on. Defaults to 5432. 46 | # If your server runs on a different port number, change accordingly. 47 | #port: 5432 48 | 49 | # Schema search path. The server defaults to $user,public 50 | #schema_search_path: myapp,sharedapp,public 51 | 52 | # Minimum log levels, in increasing order: 53 | # debug5, debug4, debug3, debug2, debug1, 54 | # log, notice, warning, error, fatal, and panic 55 | # Defaults to warning. 56 | #min_messages: notice 57 | 58 | # Warning: The database defined as "test" will be erased and 59 | # re-generated from your development database when you run "rake". 60 | # Do not set this db to the same as development or production. 61 | test: 62 | <<: *default 63 | database: myapp_test 64 | 65 | # As with config/credentials.yml, you never want to store sensitive information, 66 | # like your database password, in your source code. If your source code is 67 | # ever seen by anyone, they now have access to your database. 68 | # 69 | # Instead, provide the password or a full connection URL as an environment 70 | # variable when you boot the app. For example: 71 | # 72 | # DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" 73 | # 74 | # If the connection URL is provided in the special DATABASE_URL environment 75 | # variable, Rails will automatically merge its configuration values on top of 76 | # the values provided in this file. Alternatively, you can specify a connection 77 | # URL environment variable explicitly: 78 | # 79 | # production: 80 | # url: <%= ENV['MY_APP_DATABASE_URL'] %> 81 | # 82 | # Read https://guides.rubyonrails.org/configuring.html#configuring-a-database 83 | # for a full overview on how database connection configuration can be specified. 84 | # 85 | production: 86 | <<: *default 87 | database: myapp_production 88 | username: myapp 89 | password: <%= ENV['MYAPP_DATABASE_PASSWORD'] %> 90 | -------------------------------------------------------------------------------- /bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | # 5 | # This file was generated by Bundler. 6 | # 7 | # The application 'bundle' is installed as part of a gem, and 8 | # this file is here to facilitate running it. 9 | # 10 | 11 | require "rubygems" 12 | 13 | m = Module.new do 14 | module_function 15 | 16 | def invoked_as_script? 17 | File.expand_path($0) == File.expand_path(__FILE__) 18 | end 19 | 20 | def env_var_version 21 | ENV["BUNDLER_VERSION"] 22 | end 23 | 24 | def cli_arg_version 25 | return unless invoked_as_script? # don't want to hijack other binstubs 26 | return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` 27 | bundler_version = nil 28 | update_index = nil 29 | ARGV.each_with_index do |a, i| 30 | if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN 31 | bundler_version = a 32 | end 33 | next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ 34 | bundler_version = $1 35 | update_index = i 36 | end 37 | bundler_version 38 | end 39 | 40 | def gemfile 41 | gemfile = ENV["BUNDLE_GEMFILE"] 42 | return gemfile if gemfile && !gemfile.empty? 43 | 44 | File.expand_path("../../Gemfile", __FILE__) 45 | end 46 | 47 | def lockfile 48 | lockfile = 49 | case File.basename(gemfile) 50 | when "gems.rb" then gemfile.sub(/\.rb$/, gemfile) 51 | else "#{gemfile}.lock" 52 | end 53 | File.expand_path(lockfile) 54 | end 55 | 56 | def lockfile_version 57 | return unless File.file?(lockfile) 58 | lockfile_contents = File.read(lockfile) 59 | return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ 60 | Regexp.last_match(1) 61 | end 62 | 63 | def bundler_version 64 | @bundler_version ||= 65 | env_var_version || cli_arg_version || 66 | lockfile_version 67 | end 68 | 69 | def bundler_requirement 70 | return "#{Gem::Requirement.default}.a" unless bundler_version 71 | 72 | bundler_gem_version = Gem::Version.new(bundler_version) 73 | 74 | requirement = bundler_gem_version.approximate_recommendation 75 | 76 | return requirement unless Gem::Version.new(Gem::VERSION) < Gem::Version.new("2.7.0") 77 | 78 | requirement += ".a" if bundler_gem_version.prerelease? 79 | 80 | requirement 81 | end 82 | 83 | def load_bundler! 84 | ENV["BUNDLE_GEMFILE"] ||= gemfile 85 | 86 | activate_bundler 87 | end 88 | 89 | def activate_bundler 90 | gem_error = activation_error_handling do 91 | gem "bundler", bundler_requirement 92 | end 93 | return if gem_error.nil? 94 | require_error = activation_error_handling do 95 | require "bundler/version" 96 | end 97 | return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) 98 | warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" 99 | exit 42 100 | end 101 | 102 | def activation_error_handling 103 | yield 104 | nil 105 | rescue StandardError, LoadError => e 106 | e 107 | end 108 | end 109 | 110 | m.load_bundler! 111 | 112 | if m.invoked_as_script? 113 | load Gem.bin_path("bundler", "bundle") 114 | end 115 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | actioncable (6.1.3.2) 5 | actionpack (= 6.1.3.2) 6 | activesupport (= 6.1.3.2) 7 | nio4r (~> 2.0) 8 | websocket-driver (>= 0.6.1) 9 | actionmailbox (6.1.3.2) 10 | actionpack (= 6.1.3.2) 11 | activejob (= 6.1.3.2) 12 | activerecord (= 6.1.3.2) 13 | activestorage (= 6.1.3.2) 14 | activesupport (= 6.1.3.2) 15 | mail (>= 2.7.1) 16 | actionmailer (6.1.3.2) 17 | actionpack (= 6.1.3.2) 18 | actionview (= 6.1.3.2) 19 | activejob (= 6.1.3.2) 20 | activesupport (= 6.1.3.2) 21 | mail (~> 2.5, >= 2.5.4) 22 | rails-dom-testing (~> 2.0) 23 | actionpack (6.1.3.2) 24 | actionview (= 6.1.3.2) 25 | activesupport (= 6.1.3.2) 26 | rack (~> 2.0, >= 2.0.9) 27 | rack-test (>= 0.6.3) 28 | rails-dom-testing (~> 2.0) 29 | rails-html-sanitizer (~> 1.0, >= 1.2.0) 30 | actiontext (6.1.3.2) 31 | actionpack (= 6.1.3.2) 32 | activerecord (= 6.1.3.2) 33 | activestorage (= 6.1.3.2) 34 | activesupport (= 6.1.3.2) 35 | nokogiri (>= 1.8.5) 36 | actionview (6.1.3.2) 37 | activesupport (= 6.1.3.2) 38 | builder (~> 3.1) 39 | erubi (~> 1.4) 40 | rails-dom-testing (~> 2.0) 41 | rails-html-sanitizer (~> 1.1, >= 1.2.0) 42 | activejob (6.1.3.2) 43 | activesupport (= 6.1.3.2) 44 | globalid (>= 0.3.6) 45 | activemodel (6.1.3.2) 46 | activesupport (= 6.1.3.2) 47 | activerecord (6.1.3.2) 48 | activemodel (= 6.1.3.2) 49 | activesupport (= 6.1.3.2) 50 | activestorage (6.1.3.2) 51 | actionpack (= 6.1.3.2) 52 | activejob (= 6.1.3.2) 53 | activerecord (= 6.1.3.2) 54 | activesupport (= 6.1.3.2) 55 | marcel (~> 1.0.0) 56 | mini_mime (~> 1.0.2) 57 | activesupport (6.1.3.2) 58 | concurrent-ruby (~> 1.0, >= 1.0.2) 59 | i18n (>= 1.6, < 2) 60 | minitest (>= 5.1) 61 | tzinfo (~> 2.0) 62 | zeitwerk (~> 2.3) 63 | bcrypt (3.1.16) 64 | bootsnap (1.7.5) 65 | msgpack (~> 1.0) 66 | builder (3.2.4) 67 | byebug (11.1.3) 68 | concurrent-ruby (1.1.8) 69 | crass (1.0.6) 70 | erubi (1.10.0) 71 | ffi (1.15.0) 72 | figaro (1.2.0) 73 | thor (>= 0.14.0, < 2) 74 | globalid (0.4.2) 75 | activesupport (>= 4.2.0) 76 | i18n (1.8.10) 77 | concurrent-ruby (~> 1.0) 78 | jbuilder (2.11.2) 79 | activesupport (>= 5.0.0) 80 | jwt (2.2.3) 81 | listen (3.5.1) 82 | rb-fsevent (~> 0.10, >= 0.10.3) 83 | rb-inotify (~> 0.9, >= 0.9.10) 84 | loofah (2.9.1) 85 | crass (~> 1.0.2) 86 | nokogiri (>= 1.5.9) 87 | mail (2.7.1) 88 | mini_mime (>= 0.1.1) 89 | marcel (1.0.1) 90 | method_source (1.0.0) 91 | mini_mime (1.0.3) 92 | mini_portile2 (2.5.1) 93 | minitest (5.14.4) 94 | msgpack (1.4.2) 95 | nio4r (2.5.7) 96 | nokogiri (1.11.3) 97 | mini_portile2 (~> 2.5.0) 98 | racc (~> 1.4) 99 | nokogiri (1.11.3-x86_64-linux) 100 | racc (~> 1.4) 101 | pg (1.2.3) 102 | puma (5.3.1) 103 | nio4r (~> 2.0) 104 | racc (1.5.2) 105 | rack (2.2.3) 106 | rack-test (1.1.0) 107 | rack (>= 1.0, < 3) 108 | rails (6.1.3.2) 109 | actioncable (= 6.1.3.2) 110 | actionmailbox (= 6.1.3.2) 111 | actionmailer (= 6.1.3.2) 112 | actionpack (= 6.1.3.2) 113 | actiontext (= 6.1.3.2) 114 | actionview (= 6.1.3.2) 115 | activejob (= 6.1.3.2) 116 | activemodel (= 6.1.3.2) 117 | activerecord (= 6.1.3.2) 118 | activestorage (= 6.1.3.2) 119 | activesupport (= 6.1.3.2) 120 | bundler (>= 1.15.0) 121 | railties (= 6.1.3.2) 122 | sprockets-rails (>= 2.0.0) 123 | rails-dom-testing (2.0.3) 124 | activesupport (>= 4.2.0) 125 | nokogiri (>= 1.6) 126 | rails-html-sanitizer (1.3.0) 127 | loofah (~> 2.3) 128 | railties (6.1.3.2) 129 | actionpack (= 6.1.3.2) 130 | activesupport (= 6.1.3.2) 131 | method_source 132 | rake (>= 0.8.7) 133 | thor (~> 1.0) 134 | rake (13.0.3) 135 | rb-fsevent (0.11.0) 136 | rb-inotify (0.10.1) 137 | ffi (~> 1.0) 138 | spring (2.1.1) 139 | sprockets (4.0.2) 140 | concurrent-ruby (~> 1.0) 141 | rack (> 1, < 3) 142 | sprockets-rails (3.2.2) 143 | actionpack (>= 4.0) 144 | activesupport (>= 4.0) 145 | sprockets (>= 3.0.0) 146 | thor (1.1.0) 147 | tzinfo (2.0.4) 148 | concurrent-ruby (~> 1.0) 149 | websocket-driver (0.7.3) 150 | websocket-extensions (>= 0.1.0) 151 | websocket-extensions (0.1.5) 152 | zeitwerk (2.4.2) 153 | 154 | PLATFORMS 155 | aarch64-linux 156 | x86_64-linux 157 | 158 | DEPENDENCIES 159 | bcrypt (~> 3.1.7) 160 | bootsnap (>= 1.4.4) 161 | byebug 162 | figaro (~> 1.2) 163 | jbuilder (~> 2.7) 164 | jwt (~> 2.2, >= 2.2.3) 165 | listen (~> 3.3) 166 | pg (~> 1.1) 167 | puma (~> 5.0) 168 | rails (~> 6.1.3, >= 6.1.3.2) 169 | spring 170 | tzinfo-data 171 | 172 | RUBY VERSION 173 | ruby 2.7.3p183 174 | 175 | BUNDLED WITH 176 | 2.2.17 177 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.toptal.com/developers/gitignore/api/ruby,rails,visualstudiocode,macos,linux,windows 3 | # Edit at https://www.toptal.com/developers/gitignore?templates=ruby,rails,visualstudiocode,macos,linux,windows 4 | 5 | ### Linux ### 6 | *~ 7 | 8 | # temporary files which can be created if a process still has a handle open of a deleted file 9 | .fuse_hidden* 10 | 11 | # KDE directory preferences 12 | .directory 13 | 14 | # Linux trash folder which might appear on any partition or disk 15 | .Trash-* 16 | 17 | # .nfs files are created when an open file is removed but is still being accessed 18 | .nfs* 19 | 20 | ### macOS ### 21 | # General 22 | .DS_Store 23 | .AppleDouble 24 | .LSOverride 25 | 26 | # Icon must end with two \r 27 | Icon 28 | 29 | 30 | # Thumbnails 31 | ._* 32 | 33 | # Files that might appear in the root of a volume 34 | .DocumentRevisions-V100 35 | .fseventsd 36 | .Spotlight-V100 37 | .TemporaryItems 38 | .Trashes 39 | .VolumeIcon.icns 40 | .com.apple.timemachine.donotpresent 41 | 42 | # Directories potentially created on remote AFP share 43 | .AppleDB 44 | .AppleDesktop 45 | Network Trash Folder 46 | Temporary Items 47 | .apdisk 48 | 49 | ### Rails ### 50 | *.rbc 51 | capybara-*.html 52 | .rspec 53 | /db/*.sqlite3 54 | /db/*.sqlite3-journal 55 | /db/*.sqlite3-[0-9]* 56 | /public/system 57 | /coverage/ 58 | /spec/tmp 59 | *.orig 60 | rerun.txt 61 | pickle-email-*.html 62 | 63 | # Ignore all logfiles and tempfiles. 64 | /log/* 65 | /tmp/* 66 | !/log/.keep 67 | !/tmp/.keep 68 | 69 | # TODO Comment out this rule if you are OK with secrets being uploaded to the repo 70 | config/initializers/secret_token.rb 71 | config/master.key 72 | 73 | # Only include if you have production secrets in this file, which is no longer a Rails default 74 | # config/secrets.yml 75 | 76 | # dotenv, dotenv-rails 77 | # TODO Comment out these rules if environment variables can be committed 78 | .env 79 | .env.* 80 | 81 | ## Environment normalization: 82 | /.bundle 83 | /vendor/bundle 84 | 85 | # these should all be checked in to normalize the environment: 86 | # Gemfile.lock, .ruby-version, .ruby-gemset 87 | 88 | # unless supporting rvm < 1.11.0 or doing something fancy, ignore this: 89 | .rvmrc 90 | 91 | # if using bower-rails ignore default bower_components path bower.json files 92 | /vendor/assets/bower_components 93 | *.bowerrc 94 | bower.json 95 | 96 | # Ignore pow environment settings 97 | .powenv 98 | 99 | # Ignore Byebug command history file. 100 | .byebug_history 101 | 102 | # Ignore node_modules 103 | node_modules/ 104 | 105 | # Ignore precompiled javascript packs 106 | /public/packs 107 | /public/packs-test 108 | /public/assets 109 | 110 | # Ignore yarn files 111 | /yarn-error.log 112 | yarn-debug.log* 113 | .yarn-integrity 114 | 115 | # Ignore uploaded files in development 116 | /storage/* 117 | !/storage/.keep 118 | 119 | ### Ruby ### 120 | *.gem 121 | /.config 122 | /InstalledFiles 123 | /pkg/ 124 | /spec/reports/ 125 | /spec/examples.txt 126 | /test/tmp/ 127 | /test/version_tmp/ 128 | /tmp/ 129 | 130 | # Used by dotenv library to load environment variables. 131 | # .env 132 | 133 | # Ignore Byebug command history file. 134 | 135 | ## Specific to RubyMotion: 136 | .dat* 137 | .repl_history 138 | build/ 139 | *.bridgesupport 140 | build-iPhoneOS/ 141 | build-iPhoneSimulator/ 142 | 143 | ## Specific to RubyMotion (use of CocoaPods): 144 | # 145 | # We recommend against adding the Pods directory to your .gitignore. However 146 | # you should judge for yourself, the pros and cons are mentioned at: 147 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 148 | # vendor/Pods/ 149 | 150 | ## Documentation cache and generated files: 151 | /.yardoc/ 152 | /_yardoc/ 153 | /doc/ 154 | /rdoc/ 155 | 156 | /.bundle/ 157 | /lib/bundler/man/ 158 | 159 | # for a library or gem, you might want to ignore these files since the code is 160 | # intended to run in multiple environments; otherwise, check them in: 161 | # Gemfile.lock 162 | # .ruby-version 163 | # .ruby-gemset 164 | 165 | # unless supporting rvm < 1.11.0 or doing something fancy, ignore this: 166 | 167 | # Used by RuboCop. Remote config files pulled in from inherit_from directive. 168 | # .rubocop-https?--* 169 | 170 | ### VisualStudioCode ### 171 | .vscode/* 172 | !.vscode/settings.json 173 | !.vscode/tasks.json 174 | !.vscode/launch.json 175 | !.vscode/extensions.json 176 | *.code-workspace 177 | 178 | ### VisualStudioCode Patch ### 179 | # Ignore all local history of files 180 | .history 181 | .ionide 182 | 183 | ### Windows ### 184 | # Windows thumbnail cache files 185 | Thumbs.db 186 | Thumbs.db:encryptable 187 | ehthumbs.db 188 | ehthumbs_vista.db 189 | 190 | # Dump file 191 | *.stackdump 192 | 193 | # Folder config file 194 | [Dd]esktop.ini 195 | 196 | # Recycle Bin used on file shares 197 | $RECYCLE.BIN/ 198 | 199 | # Windows Installer files 200 | *.cab 201 | *.msi 202 | *.msix 203 | *.msm 204 | *.msp 205 | 206 | # Windows shortcuts 207 | *.lnk 208 | 209 | # End of https://www.toptal.com/developers/gitignore/api/ruby,rails,visualstudiocode,macos,linux,windows 210 | # Ignore application configuration 211 | # /config/application.yml 212 | -------------------------------------------------------------------------------- /config/environments/production.rb: -------------------------------------------------------------------------------- 1 | require "active_support/core_ext/integer/time" 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # Code is not reloaded between requests. 7 | config.cache_classes = true 8 | 9 | # Eager load code on boot. This eager loads most of Rails and 10 | # your application in memory, allowing both threaded web servers 11 | # and those relying on copy on write to perform better. 12 | # Rake tasks automatically ignore this option for performance. 13 | config.eager_load = true 14 | 15 | # Full error reports are disabled and caching is turned on. 16 | config.consider_all_requests_local = false 17 | 18 | # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] 19 | # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). 20 | # config.require_master_key = true 21 | 22 | # Disable serving static files from the `/public` folder by default since 23 | # Apache or NGINX already handles this. 24 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? 25 | 26 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 27 | # config.asset_host = 'http://assets.example.com' 28 | 29 | # Specifies the header that your server uses for sending files. 30 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 31 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 32 | 33 | # Store uploaded files on the local file system (see config/storage.yml for options). 34 | config.active_storage.service = :local 35 | 36 | # Mount Action Cable outside main process or domain. 37 | # config.action_cable.mount_path = nil 38 | # config.action_cable.url = 'wss://example.com/cable' 39 | # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] 40 | 41 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 42 | # config.force_ssl = true 43 | 44 | # Include generic and useful information about system operation, but avoid logging too much 45 | # information to avoid inadvertent exposure of personally identifiable information (PII). 46 | config.log_level = :info 47 | 48 | # Prepend all log lines with the following tags. 49 | config.log_tags = [ :request_id ] 50 | 51 | # Use a different cache store in production. 52 | # config.cache_store = :mem_cache_store 53 | 54 | # Use a real queuing backend for Active Job (and separate queues per environment). 55 | # config.active_job.queue_adapter = :resque 56 | # config.active_job.queue_name_prefix = "myapp_production" 57 | 58 | config.action_mailer.perform_caching = false 59 | 60 | # Ignore bad email addresses and do not raise email delivery errors. 61 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 62 | # config.action_mailer.raise_delivery_errors = false 63 | 64 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 65 | # the I18n.default_locale when a translation cannot be found). 66 | config.i18n.fallbacks = true 67 | 68 | # Send deprecation notices to registered listeners. 69 | config.active_support.deprecation = :notify 70 | 71 | # Log disallowed deprecations. 72 | config.active_support.disallowed_deprecation = :log 73 | 74 | # Tell Active Support which deprecation messages to disallow. 75 | config.active_support.disallowed_deprecation_warnings = [] 76 | 77 | # Use default logging formatter so that PID and timestamp are not suppressed. 78 | config.log_formatter = ::Logger::Formatter.new 79 | 80 | # Use a different logger for distributed setups. 81 | # require "syslog/logger" 82 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') 83 | 84 | if ENV["RAILS_LOG_TO_STDOUT"].present? 85 | logger = ActiveSupport::Logger.new(STDOUT) 86 | logger.formatter = config.log_formatter 87 | config.logger = ActiveSupport::TaggedLogging.new(logger) 88 | end 89 | 90 | # Do not dump schema after migrations. 91 | config.active_record.dump_schema_after_migration = false 92 | 93 | # Inserts middleware to perform automatic connection switching. 94 | # The `database_selector` hash is used to pass options to the DatabaseSelector 95 | # middleware. The `delay` is used to determine how long to wait after a write 96 | # to send a subsequent read to the primary. 97 | # 98 | # The `database_resolver` class is used by the middleware to determine which 99 | # database is appropriate to use based on the time delay. 100 | # 101 | # The `database_resolver_context` class is used by the middleware to set 102 | # timestamps for the last write to the primary. The resolver uses the context 103 | # class timestamps to determine how long to wait before reading from the 104 | # replica. 105 | # 106 | # By default Rails will store a last write timestamp in the session. The 107 | # DatabaseSelector middleware is designed as such you can define your own 108 | # strategy for connection switching and pass that into the middleware through 109 | # these configuration options. 110 | # config.active_record.database_selector = { delay: 2.seconds } 111 | # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver 112 | # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session 113 | end 114 | --------------------------------------------------------------------------------