├── log └── .keep ├── storage └── .keep ├── tmp ├── .keep └── pids │ └── .keep ├── vendor └── .keep ├── lib ├── tasks │ ├── .keep │ └── auto_annotate_models.rake └── devise_custom_failure.rb ├── .ruby-version ├── app ├── models │ ├── concerns │ │ ├── .keep │ │ ├── posts │ │ │ ├── associations.rb │ │ │ ├── hooks.rb │ │ │ ├── validations.rb │ │ │ ├── scopes.rb │ │ │ └── logic.rb │ │ ├── users │ │ │ ├── associations.rb │ │ │ ├── logic.rb │ │ │ ├── validations.rb │ │ │ └── allowlist.rb │ │ ├── comments │ │ │ ├── validations.rb │ │ │ ├── associations.rb │ │ │ └── logic.rb │ │ └── abilities │ │ │ └── commentable.rb │ ├── application_record.rb │ ├── allowlisted_jwt.rb │ ├── post.rb │ ├── comment.rb │ └── user.rb ├── controllers │ ├── concerns │ │ └── .keep │ ├── ping_controller.rb │ ├── registrations_controller.rb │ ├── confirmations_controller.rb │ ├── api │ │ └── v1 │ │ │ ├── users_controller.rb │ │ │ ├── posts_controller.rb │ │ │ └── comments_controller.rb │ ├── passwords_controller.rb │ ├── application_controller.rb │ └── sessions_controller.rb ├── views │ ├── layouts │ │ ├── mailer.text.erb │ │ └── mailer.html.erb │ └── devise │ │ └── mailer │ │ └── confirmation_instructions.html.erb ├── channels │ └── application_cable │ │ ├── channel.rb │ │ └── connection.rb ├── mailers │ └── application_mailer.rb ├── serializers │ ├── user_show_serializer.rb │ ├── comment_for_post_show_serializer.rb │ ├── post_index_serializer.rb │ ├── comment_index_serializer.rb │ ├── comment_show_serializer.rb │ └── post_show_serializer.rb ├── jobs │ └── application_job.rb └── policies │ ├── comment_policy.rb │ ├── application_policy.rb │ └── post_policy.rb ├── config ├── initializers │ ├── redis.rb │ ├── mime_types.rb │ ├── application_controller_renderer.rb │ ├── sidekiq.rb │ ├── filter_parameter_logging.rb │ ├── wrap_parameters.rb │ ├── backtrace_silencers.rb │ ├── inflections.rb │ ├── cors.rb │ ├── friendly_id.rb │ └── devise.rb ├── spring.rb ├── environment.rb ├── boot.rb ├── cable.yml ├── credentials.yml.enc ├── routes.rb ├── sitemap.rb ├── storage.yml ├── locales │ ├── en.yml │ └── devise.en.yml ├── application.rb ├── puma.rb ├── environments │ ├── test.rb │ ├── development.rb │ ├── production.rb │ └── staging.rb └── database.yml ├── public ├── robots.txt └── sitemap.xml ├── Procfile ├── bin ├── rake ├── rails ├── spring ├── setup └── bundle ├── db ├── migrate │ ├── 20210414181412_add_slug_to_users.rb │ ├── 20210422212211_add_slug_to_posts.rb │ ├── 20210403204805_create_posts.rb │ ├── 20210324003543_add_names_themes_to_user.rb │ ├── 20210422213742_create_comments.rb │ ├── 20210224032349_create_allowlisted_jwts.rb │ └── 20210224031229_devise_create_users.rb ├── seeds.rb └── schema.rb ├── config.ru ├── Rakefile ├── .gitattributes ├── spec ├── requests │ ├── ping_request_spec.rb │ ├── users_request_spec.rb │ ├── comments_request_spec.rb │ └── posts_request_spec.rb ├── support │ └── object_creators.rb ├── rails_helper.rb └── spec_helper.rb ├── .gitignore ├── .github └── workflows │ └── run_specs.yml ├── Gemfile ├── Gemfile.lock └── README.md /log/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /storage/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tmp/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /vendor/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lib/tasks/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tmp/pids/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | ruby-3.0.0 2 | -------------------------------------------------------------------------------- /app/models/concerns/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /app/controllers/concerns/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.text.erb: -------------------------------------------------------------------------------- 1 | <%= yield %> 2 | -------------------------------------------------------------------------------- /config/initializers/redis.rb: -------------------------------------------------------------------------------- 1 | if ENV['REDIS_URL'] 2 | $redis = Redis.new(url: ENV['REDIS_URL']) 3 | end 4 | -------------------------------------------------------------------------------- /app/models/application_record.rb: -------------------------------------------------------------------------------- 1 | class ApplicationRecord < ActiveRecord::Base 2 | self.abstract_class = true 3 | end 4 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: bundle exec rails server -p $PORT 2 | worker: bundle exec sidekiq -c 1 -q $REDIS_QUEUE_DEFAULT -q $REDIS_QUEUE_MAILERS 3 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /app/models/concerns/posts/associations.rb: -------------------------------------------------------------------------------- 1 | module Posts::Associations 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | belongs_to :user 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /db/migrate/20210414181412_add_slug_to_users.rb: -------------------------------------------------------------------------------- 1 | class AddSlugToUsers < ActiveRecord::Migration[6.1] 2 | def change 3 | add_index :users, :slug, unique: true 4 | end 5 | end 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 | -------------------------------------------------------------------------------- /db/migrate/20210422212211_add_slug_to_posts.rb: -------------------------------------------------------------------------------- 1 | class AddSlugToPosts < ActiveRecord::Migration[6.1] 2 | def change 3 | add_column :posts, :slug, :string, index: true, unique: true 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /app/serializers/user_show_serializer.rb: -------------------------------------------------------------------------------- 1 | class UserShowSerializer 2 | include FastJsonapi::ObjectSerializer 3 | 4 | set_key_transform :camel_lower 5 | 6 | attributes :id, 7 | :display_name, 8 | :slug 9 | end 10 | -------------------------------------------------------------------------------- /app/models/concerns/users/associations.rb: -------------------------------------------------------------------------------- 1 | module Users::Associations 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | has_many :comments, dependent: :nullify 6 | has_many :posts, dependent: :destroy 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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: programmingtil_rails_1_production 11 | -------------------------------------------------------------------------------- /app/models/concerns/posts/hooks.rb: -------------------------------------------------------------------------------- 1 | module Posts::Hooks 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | before_create :set_comments_cache 6 | 7 | def set_comments_cache 8 | self.comments_count = 0 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /app/models/concerns/posts/validations.rb: -------------------------------------------------------------------------------- 1 | module Posts::Validations 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | validates :title, presence: true, allow_blank: false 6 | validates :content, presence: true, allow_blank: false 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /config/initializers/sidekiq.rb: -------------------------------------------------------------------------------- 1 | if ENV['REDIS_URL'] 2 | Sidekiq.configure_client do |config| 3 | config.redis = { url: ENV['REDIS_URL'], network_timeout: 5 } 4 | end 5 | Sidekiq.configure_server do |config| 6 | config.redis = { url: ENV['REDIS_URL'], network_timeout: 5 } 7 | end 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 | -------------------------------------------------------------------------------- /app/views/devise/mailer/confirmation_instructions.html.erb: -------------------------------------------------------------------------------- 1 |2 | Welcome <%= @resource.username %>! 3 |
4 |5 | You can confirm your account email through the link below: 6 |
7 |8 | <%= link_to 'Confirm my account', "#{users_sign_in_url}/?confirmation_token=#{@token}" %> 9 |
10 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /app/models/concerns/comments/validations.rb: -------------------------------------------------------------------------------- 1 | module Comments::Validations 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | validates :body, presence: true 6 | validates :commentable, presence: true 7 | validates :commentable_type, inclusion: { in: Comment::CLASSES.map(&:name) } 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /app/models/concerns/abilities/commentable.rb: -------------------------------------------------------------------------------- 1 | module Abilities::Commentable 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | has_many :comments, as: :commentable 6 | 7 | def create_comment!(params) 8 | comment = comments.build(params) 9 | save 10 | comment 11 | end 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /app/controllers/ping_controller.rb: -------------------------------------------------------------------------------- 1 | class PingController < ApplicationController 2 | before_action :authenticate_user!, only: [:auth] 3 | 4 | # GET /ping 5 | def index 6 | render body: nil, status: 200 7 | end 8 | 9 | # GET /ping/auth 10 | def auth 11 | render body: nil, status: 200 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /app/serializers/comment_for_post_show_serializer.rb: -------------------------------------------------------------------------------- 1 | class CommentForPostShowSerializer 2 | include FastJsonapi::ObjectSerializer 3 | 4 | set_key_transform :camel_lower 5 | 6 | attributes :id, 7 | :body, 8 | :updated_at 9 | 10 | attribute :user do |comment| 11 | comment.user.for_others 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /db/migrate/20210403204805_create_posts.rb: -------------------------------------------------------------------------------- 1 | class CreatePosts < ActiveRecord::Migration[6.1] 2 | def change 3 | create_table :posts do |t| 4 | t.references :user, null: false, index: true 5 | t.string :title, null: false 6 | t.text :content, null: false 7 | t.timestamp :published_at 8 | t.timestamps 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /app/serializers/post_index_serializer.rb: -------------------------------------------------------------------------------- 1 | class PostIndexSerializer 2 | include FastJsonapi::ObjectSerializer 3 | 4 | set_key_transform :camel_lower 5 | 6 | attributes :id, 7 | :comments_count, 8 | :content, 9 | :published_at, 10 | :slug, 11 | :title 12 | 13 | attribute :user do |post| 14 | post.user.for_others 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /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/policies/comment_policy.rb: -------------------------------------------------------------------------------- 1 | class CommentPolicy < ApplicationPolicy 2 | class Scope < Scope 3 | def resolve 4 | scope.all 5 | end 6 | end 7 | 8 | def create? 9 | true 10 | end 11 | 12 | # Only an user can destroy their own 13 | def destroy? 14 | record.user == user 15 | end 16 | 17 | # Only an user can update their own 18 | def update? 19 | record.user == user 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /db/migrate/20210324003543_add_names_themes_to_user.rb: -------------------------------------------------------------------------------- 1 | class AddNamesThemesToUser < ActiveRecord::Migration[6.1] 2 | def change 3 | add_column :users, :username, :string, index: true, unique: true 4 | add_column :users, :display_name, :string, index: true 5 | add_column :users, :slug, :string, index: true 6 | add_column :users, :theme, :integer, default: 0 7 | add_column :users, :theme_color, :integer, default: 0 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /app/controllers/registrations_controller.rb: -------------------------------------------------------------------------------- 1 | class RegistrationsController < Devise::RegistrationsController 2 | respond_to :json 3 | 4 | # POST /users 5 | # Specs No 6 | def create 7 | build_resource(sign_up_params) 8 | 9 | resource.save 10 | if resource.persisted? 11 | render json: { message: I18n.t('controllers.registrations.confirm') } 12 | else 13 | render json: resource.errors, status: 401 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /app/policies/application_policy.rb: -------------------------------------------------------------------------------- 1 | class ApplicationPolicy 2 | attr_reader :user, :record 3 | 4 | def initialize(user, record) 5 | @user = user 6 | @record = record 7 | end 8 | 9 | class Scope 10 | attr_reader :user, :scope, :params 11 | 12 | def initialize(user, scope) 13 | @user = user&.user 14 | @params = user&.params 15 | @scope = scope 16 | end 17 | 18 | def resolve 19 | scope.all 20 | end 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /app/models/concerns/users/logic.rb: -------------------------------------------------------------------------------- 1 | module Users::Logic 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | def for_display 6 | { 7 | displayName: display_name, 8 | email: email, 9 | id: id, 10 | username: username, 11 | } 12 | end 13 | 14 | def for_others 15 | { 16 | displayName: display_name.presence || id, 17 | id: id, 18 | slug: slug, 19 | } 20 | end 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /app/models/concerns/posts/scopes.rb: -------------------------------------------------------------------------------- 1 | module Posts::Scopes 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | scope :for_index, ->(params) { 6 | query = includes(:user).order(id: :desc) 7 | query = query.published if params[:published].present? 8 | if params[:rss].present? 9 | query = query.published.limit(5) 10 | end 11 | query 12 | } 13 | scope :published, ->() { 14 | where.not(published_at: nil) 15 | } 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /app/policies/post_policy.rb: -------------------------------------------------------------------------------- 1 | class PostPolicy < ApplicationPolicy 2 | class Scope < Scope 3 | def resolve 4 | scope.all 5 | end 6 | end 7 | 8 | # Users can only create up to 3 posts 9 | def create? 10 | # user.posts.size < 3 11 | true 12 | end 13 | 14 | # Only an user can destroy their own 15 | def destroy? 16 | record.user == user 17 | end 18 | 19 | # Only an user can update their own 20 | def update? 21 | record.user == user 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /app/models/concerns/posts/logic.rb: -------------------------------------------------------------------------------- 1 | module Posts::Logic 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | def self.create_post!(params, user) 6 | post = Post.new(params.merge({ 7 | user_id: user.id, 8 | })) 9 | post.save! 10 | post 11 | end 12 | 13 | def self.delete_post!(post) 14 | post.destroy! 15 | post 16 | end 17 | 18 | def self.update_post!(post, params) 19 | post.update!(params) 20 | post 21 | end 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /db/migrate/20210422213742_create_comments.rb: -------------------------------------------------------------------------------- 1 | class CreateComments < ActiveRecord::Migration[6.1] 2 | def change 3 | create_table :comments do |t| 4 | t.references :commentable, null: :false, polymorphic: true 5 | t.references :user, index: true 6 | t.references :thread, index: true 7 | t.references :parent, index: true 8 | t.text :body, null: false 9 | t.datetime :deleted_at 10 | t.timestamps null: false 11 | end 12 | 13 | add_column :posts, :comments_count, :bigint 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /config/credentials.yml.enc: -------------------------------------------------------------------------------- 1 | Y2ALOEnuToZqQvnGcpXmehmTDatOmu9mW5rnbYPs6EeGHYTHsy35uRJKOlZrZnAudq654u9ZDHJcKAz78XtzW/Hn7BZuSMxfBhcRwESS6MMAGAbJDxe3W3ChpuJpgawp2UuHM8TLmk+PsFXSBVZ9DtVD9GggIYbSM9eFFQz4OQWzvkoxSvI361uPM0vlsl9ucIJUrQsCHE8yTxhtHv3mj4heRHRh0zAXWCyIVwjMFFGpL+l6NCUgqMwgU4QH5CakOkqlsr8B04uMODUV2PjfQRc9WA2TSJLRfmIrHwmsbCWh9A8xRaBYWDbOHJ172YQPgmvnFyRPnQ3zNpTeu0BevSsOayi1MVMsiMifasf2hgtbhZ069FPtLyVAKAq6s1e0dnPs1fPD3YY6YqH1noyphGxr4zC432y/IfoTA6XKGl4YHry8yBUOaQZXj8HSWVc4NhG9Vh/wlOMB2354vbqUatGZ8OgNT8n1put4+00T6UIuDZCD--NUABWWfgGiVaeZQs--p6Y1wPBoXfZoCGwMcJcgzw== -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /app/models/concerns/comments/associations.rb: -------------------------------------------------------------------------------- 1 | module Comments::Associations 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | belongs_to :commentable, polymorphic: true, counter_cache: true 6 | belongs_to :parent, class_name: 'Comment', optional: true 7 | belongs_to :thread, class_name: 'Comment', optional: true 8 | belongs_to :user, optional: true 9 | has_many :children, class_name: 'Comment', foreign_key: :parent_id, dependent: :destroy 10 | has_many :descendents, class_name: 'Comment', foreign_key: :thread_id, dependent: :destroy 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /app/serializers/comment_index_serializer.rb: -------------------------------------------------------------------------------- 1 | class CommentIndexSerializer 2 | include FastJsonapi::ObjectSerializer 3 | 4 | set_key_transform :camel_lower 5 | 6 | attributes :id, 7 | :body, 8 | :updated_at 9 | 10 | attribute :commentable do |comment| 11 | { 12 | id: comment.commentable_id, 13 | type: comment.commentable_type, 14 | title: comment.commentable.title, 15 | } 16 | end 17 | 18 | attribute :user, if: Proc.new { |comment| comment.user.present? } do |comment| 19 | comment.user.for_others 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /app/serializers/comment_show_serializer.rb: -------------------------------------------------------------------------------- 1 | class CommentShowSerializer 2 | include FastJsonapi::ObjectSerializer 3 | 4 | set_key_transform :camel_lower 5 | 6 | attributes :id, 7 | :body, 8 | :updated_at 9 | 10 | attribute :commentable do |comment| 11 | { 12 | id: comment.commentable_id, 13 | type: comment.commentable_type, 14 | title: comment.commentable.title, 15 | } 16 | end 17 | 18 | attribute :user, if: Proc.new { |comment| comment.user.present? } do |comment| 19 | comment.user.for_others 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /db/migrate/20210224032349_create_allowlisted_jwts.rb: -------------------------------------------------------------------------------- 1 | class CreateAllowlistedJwts < ActiveRecord::Migration[6.1] 2 | def change 3 | create_table :allowlisted_jwts do |t| 4 | t.references :user, foreign_key: { on_delete: :cascade }, null: false 5 | t.string :jti, null: false 6 | t.string :aud, null: false 7 | t.datetime :exp, null: false 8 | t.string :remote_ip 9 | t.string :os_data 10 | t.string :browser_data 11 | t.string :device_data 12 | t.timestamps null: false 13 | end 14 | 15 | add_index :allowlisted_jwts, :jti, unique: true 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /spec/requests/ping_request_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe "Pings", type: :request do 4 | it 'Returns a status of 200' do 5 | get '/ping/' 6 | expect(response).to have_http_status(200) 7 | end 8 | 9 | it 'Returns a status of 401 if not logged in' do 10 | get '/ping/auth/' 11 | expect(response).to have_http_status(401) 12 | end 13 | 14 | it 'Returns a status of 200 if logged in' do 15 | user = create_user 16 | headers = get_headers(user.username) 17 | get '/ping/auth/', headers: headers 18 | expect(response).to have_http_status(200) 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /app/models/concerns/users/validations.rb: -------------------------------------------------------------------------------- 1 | module Users::Validations 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | validates :email, 6 | presence: true, 7 | uniqueness: { case_sensitive: false } 8 | validates :slug, 9 | format: { without: /\A\d+\Z/, message: I18n.t('models.users.slug_numbers') } 10 | validates :username, 11 | presence: true, 12 | length: { minimum: 2 }, 13 | uniqueness: { case_sensitive: false } 14 | validates :username, 15 | format: { with: /\A[a-zA-Z0-9_-]+\z/, message: I18n.t('models.users.username') } 16 | validates :username, 17 | format: { without: /\A\d+\Z/, message: I18n.t('models.users.username_numbers') } 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /app/models/allowlisted_jwt.rb: -------------------------------------------------------------------------------- 1 | # == Schema Information 2 | # 3 | # Table name: allowlisted_jwts 4 | # 5 | # id :bigint not null, primary key 6 | # user_id :bigint not null 7 | # jti :string not null 8 | # aud :string not null 9 | # exp :datetime not null 10 | # remote_ip :string 11 | # os_data :string 12 | # browser_data :string 13 | # device_data :string 14 | # created_at :datetime not null 15 | # updated_at :datetime not null 16 | # 17 | # Indexes 18 | # 19 | # index_allowlisted_jwts_on_jti (jti) UNIQUE 20 | # index_allowlisted_jwts_on_user_id (user_id) 21 | # 22 | # Foreign Keys 23 | # 24 | # fk_rails_... (user_id => users.id) ON DELETE => cascade 25 | # 26 | class AllowlistedJwt < ApplicationRecord 27 | end 28 | -------------------------------------------------------------------------------- /app/models/post.rb: -------------------------------------------------------------------------------- 1 | # == Schema Information 2 | # 3 | # Table name: posts 4 | # 5 | # id :bigint not null, primary key 6 | # user_id :bigint not null 7 | # title :string not null 8 | # content :text not null 9 | # published_at :datetime 10 | # created_at :datetime not null 11 | # updated_at :datetime not null 12 | # slug :string 13 | # comments_count :bigint 14 | # 15 | # Indexes 16 | # 17 | # index_posts_on_user_id (user_id) 18 | # 19 | class Post < ApplicationRecord 20 | include Abilities::Commentable 21 | include Posts::Associations 22 | include Posts::Hooks 23 | include Posts::Logic 24 | include Posts::Scopes 25 | include Posts::Validations 26 | 27 | extend FriendlyId 28 | friendly_id :title, use: [:slugged] 29 | end 30 | -------------------------------------------------------------------------------- /app/serializers/post_show_serializer.rb: -------------------------------------------------------------------------------- 1 | class PostShowSerializer 2 | include FastJsonapi::ObjectSerializer 3 | 4 | set_key_transform :camel_lower 5 | 6 | attributes :id, 7 | :comments_count, 8 | :content, 9 | :published_at, 10 | :slug, 11 | :title 12 | 13 | # 14 | # Show the most recent 5 comments with the users 15 | # 16 | attribute :comments do |post, params| 17 | comments = post.comments.includes(:user).order(id: :desc) 18 | if params[:all].blank? 19 | comments = comments.limit(5) 20 | end 21 | CommentForPostShowSerializer.new(comments, { is_collection: true }) 22 | end 23 | 24 | attribute :user do |post| 25 | { 26 | displayName: post.user.display_name.presence || post.user_id, 27 | id: post.user_id, 28 | slug: post.user.slug, 29 | } 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | devise_for :users, 3 | controllers: { 4 | confirmations: 'confirmations', 5 | passwords: 'passwords', 6 | registrations: 'registrations', 7 | sessions: 'sessions', 8 | } 9 | 10 | # Ping to ensure site is up 11 | resources :ping, only: [:index] do 12 | collection do 13 | get :auth 14 | end 15 | end 16 | 17 | # APIs 18 | namespace :api do 19 | namespace :v1 do 20 | resources :comments, only: [:create, :destroy, :index, :show, :update] 21 | resources :posts, only: [:create, :destroy, :index, :show, :update] 22 | resources :users, only: [:show, :update] do 23 | collection do 24 | get :available 25 | end 26 | end 27 | end 28 | end 29 | 30 | namespace :users do 31 | get "sign-in", to: "sessions#new" 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /.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 | /public/assets 21 | .byebug_history 22 | 23 | # Ignore master key for decrypting credentials and more. 24 | /config/master.key 25 | 26 | /public/packs 27 | /public/packs-test 28 | /node_modules 29 | /yarn-error.log 30 | yarn-debug.log* 31 | .yarn-integrity 32 | 33 | /coverage/* 34 | /.env 35 | 36 | # Ignore redis 37 | *.rdb 38 | 39 | /config/credentials/production.key 40 | -------------------------------------------------------------------------------- /app/models/comment.rb: -------------------------------------------------------------------------------- 1 | # == Schema Information 2 | # 3 | # Table name: comments 4 | # 5 | # id :bigint not null, primary key 6 | # commentable_type :string 7 | # commentable_id :bigint 8 | # user_id :bigint 9 | # thread_id :bigint 10 | # parent_id :bigint 11 | # body :text not null 12 | # deleted_at :datetime 13 | # created_at :datetime not null 14 | # updated_at :datetime not null 15 | # 16 | # Indexes 17 | # 18 | # index_comments_on_commentable (commentable_type,commentable_id) 19 | # index_comments_on_parent_id (parent_id) 20 | # index_comments_on_thread_id (thread_id) 21 | # index_comments_on_user_id (user_id) 22 | # 23 | class Comment < ApplicationRecord 24 | CLASSES = [ 25 | Post, 26 | ].freeze 27 | 28 | include Comments::Associations 29 | include Comments::Logic 30 | include Comments::Validations 31 | end 32 | -------------------------------------------------------------------------------- /app/controllers/confirmations_controller.rb: -------------------------------------------------------------------------------- 1 | class ConfirmationsController < Devise::ConfirmationsController 2 | # POST /resource/confirmation 3 | def create 4 | self.resource = resource_class.send_confirmation_instructions(resource_params) 5 | yield resource if block_given? 6 | 7 | if successfully_sent?(resource) 8 | render json: { message: I18n.t('controllers.confirmations.resent') }, status: 200 9 | else 10 | render json: resource.errors, status: 401 11 | end 12 | end 13 | 14 | # GET /resource/confirmation?confirmation_token=abcdef 15 | def show 16 | self.resource = resource_class.confirm_by_token(params[:confirmation_token]) 17 | yield resource if block_given? 18 | 19 | if resource.errors.empty? 20 | render json: { message: I18n.t('controllers.confirmations.success') }, status: 200 21 | else 22 | render json: resource.errors, status: 401 23 | end 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /app/models/concerns/comments/logic.rb: -------------------------------------------------------------------------------- 1 | module Comments::Logic 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | def self.create_comment!(user, params) 6 | klass = from_class_name(params.delete(:commentable_type)) 7 | raise 'Not Commentable' if klass.blank? 8 | klass.find(params.delete(:commentable_id)) 9 | .create_comment!(params.merge({ user_id: user.id})) 10 | end 11 | 12 | def self.delete_comment!(comment) 13 | comment.update!( 14 | body: '[deleted]', 15 | user_id: nil, 16 | deleted_at: Time.now, 17 | ) 18 | comment 19 | end 20 | 21 | def self.update_comment!(comment, params) 22 | comment.update!(body: params[:body]) 23 | comment 24 | end 25 | 26 | def self.from_class_name(klass_name) 27 | ret_class = nil 28 | Comment::CLASSES.detect do |klass| 29 | ret_class = klass if klass.name == klass_name 30 | end 31 | ret_class 32 | end 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /config/sitemap.rb: -------------------------------------------------------------------------------- 1 | require 'aws-sdk-s3' 2 | 3 | # Set the host name for URL creation 4 | SitemapGenerator::Sitemap.default_host = "https://ptil-rails-staging-api.herokuapp.com" 5 | SitemapGenerator::Sitemap.public_path = 'tmp/' 6 | SitemapGenerator::Sitemap.sitemaps_path = 'sitemaps/' 7 | SitemapGenerator::Sitemap.compress = false 8 | SitemapGenerator::Sitemap.adapter = SitemapGenerator::AwsSdkAdapter.new( 9 | "programmingtil-rails-#{Rails.env}", 10 | aws_access_key_id: Rails.application.credentials.dig(:aws, :access_key_id), 11 | aws_secret_access_key: Rails.application.credentials.dig(:aws, :secret_access_key), 12 | aws_region: 'us-west-1' 13 | ) 14 | 15 | SitemapGenerator::Sitemap.create do 16 | add "/about", 17 | changefreq: 'yearly', 18 | lastmod: '2021-05-13T09:19:54-06:00', 19 | priority: 0.4 20 | Post.published.order(id: :desc).each do |post| 21 | add "/posts/#{post.slug}", 22 | changefreq: 'weekly', 23 | lastmod: post.published_at, 24 | priority: 0.6 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /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 | if Rails.env.development? 10 | origins = [ 11 | 'localhost:3000', 'localhost:3001', 'localhost:5000', 12 | 'staging.xyz.com', 'www.xyz.com', 13 | ].freeze 14 | allow do 15 | origins origins 16 | resource '*', 17 | headers: :any, 18 | methods: %i(get post put patch delete options head) 19 | end 20 | else 21 | origins = [ 22 | 'staging.xyz.com', 'www.xyz.com', 23 | ].freeze 24 | allow do 25 | origins origins 26 | resource '*', 27 | headers: :any, 28 | methods: %i(get post put patch delete options head) 29 | end 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /lib/devise_custom_failure.rb: -------------------------------------------------------------------------------- 1 | # https://github.com/heartcombo/devise/blob/master/lib/devise/failure_app.rb 2 | class DeviseCustomFailure < Devise::FailureApp 3 | def respond 4 | # If fails on certain actions, then ignore and make request as if no user. 5 | # Basically, any with `authenticate_user_if_needed!` needs to use this as a fallback 6 | path_params = request.path_parameters 7 | control = path_params[:controller] 8 | act = path_params[:action] 9 | if (control == 'api/v1/ping' && act == 'index') 10 | # HACK! Rails converts 'api/v1/people'.classify => API::V1::Person 11 | # So we pluralize it and get People or Talks, etc 12 | classify = control.classify.pluralize 13 | 14 | warden_options[:recall] = "#{classify}##{act}" 15 | request.headers['auth_failure'] = true 16 | request.headers['auth_failure_message'] = i18n_message 17 | recall 18 | else 19 | http_auth 20 | end 21 | end 22 | 23 | # Override failure to always return JSON. 24 | # This is needed because Devise will attempt to redirect otherwise 25 | def http_auth_body 26 | { 27 | authFailure: true, 28 | error: i18n_message, 29 | }.to_json 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /app/controllers/api/v1/users_controller.rb: -------------------------------------------------------------------------------- 1 | class Api::V1::UsersController < ApplicationController 2 | before_action :authenticate_user!, only: [:update] 3 | 4 | # GET /api/v1/users/available 5 | def available 6 | free = if params[:email].present? 7 | !User.where(email: params[:email].downcase).exists? 8 | elsif params[:username].present? 9 | !User.where(username: params[:username].downcase).exists? 10 | else 11 | true 12 | end 13 | render json: { data: free } 14 | end 15 | 16 | # GET /api/v1/users/#{slug} 17 | def show 18 | user = User.friendly.find(params[:id]) 19 | render json: UserShowSerializer.new(user, show_options).serializable_hash.to_json 20 | rescue ActiveRecord::RecordNotFound 21 | render json: { error: I18n.t('api.not_found') }, status: 404 22 | end 23 | 24 | # authenticate_user! 25 | # PUT /api/v1/users/#{id} 26 | def update 27 | current_user.update(user_params) 28 | render json: { 29 | message: I18n.t('controllers.users.updated'), 30 | user: current_user.for_display 31 | } 32 | rescue => error 33 | render json: { error: I18n.t('api.oops') }, status: 500 34 | end 35 | 36 | private 37 | 38 | def user_params 39 | params.require(:user).permit( 40 | :display_name, 41 | :username 42 | ) 43 | end 44 | end 45 | -------------------------------------------------------------------------------- /.github/workflows/run_specs.yml: -------------------------------------------------------------------------------- 1 | env: 2 | RUBY_VERSION: 3.0.0 3 | POSTGRES_USER: postgres 4 | POSTGRES_PASSWORD: postgres 5 | POSTGRES_DB: programmingtil_rails_1_test 6 | DEVISE_JWT_SECRET_KEY: ${{ secrets.DEVISE_JWT_SECRET_KEY }} 7 | 8 | name: Rails Specs 9 | on: [pull_request] 10 | jobs: 11 | rspec-test: 12 | name: RSpec 13 | runs-on: ubuntu-20.04 14 | services: 15 | postgres: 16 | image: postgres:latest 17 | ports: 18 | - 5432:5432 19 | env: 20 | POSTGRES_USER: ${{ env.POSTGRES_USER }} 21 | POSTGRES_PASSWORD: ${{ env.POSTGRES_PASSWORD }} 22 | steps: 23 | - uses: actions/checkout@v1 24 | - uses: ruby/setup-ruby@v1 25 | with: 26 | ruby-version: ${{ env.RUBY_VERSION }} 27 | - name: Install postgres client 28 | run: sudo apt-get install libpq-dev 29 | - name: Install dependencies 30 | run: | 31 | gem install bundler 32 | bundler install 33 | - name: Create database 34 | run: | 35 | bundler exec rails db:create RAILS_ENV=test 36 | bundler exec rails db:migrate RAILS_ENV=test 37 | - name: Run tests 38 | run: bundler exec rspec spec/* 39 | - name: Upload coverage results 40 | uses: actions/upload-artifact@master 41 | if: always() 42 | with: 43 | name: coverage-report 44 | path: coverage 45 | -------------------------------------------------------------------------------- /app/models/concerns/users/allowlist.rb: -------------------------------------------------------------------------------- 1 | module Users::Allowlist 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | has_many :allowlisted_jwts, dependent: :destroy 6 | 7 | # @see Warden::JWTAuth::Interfaces::RevocationStrategy#jwt_revoked? 8 | def self.jwt_revoked?(payload, user) 9 | !user.allowlisted_jwts.exists?(payload.slice('jti', 'aud')) 10 | end 11 | 12 | # @see Warden::JWTAuth::Interfaces::RevocationStrategy#revoke_jwt 13 | def self.revoke_jwt(payload, user) 14 | jwt = user.allowlisted_jwts.find_by(payload.slice('jti', 'aud')) 15 | jwt.destroy! if jwt 16 | end 17 | end 18 | 19 | # Warden::JWTAuth::Interfaces::User#on_jwt_dispatch 20 | def on_jwt_dispatch(_token, payload) 21 | prev_token = allowlisted_jwts.where(aud: payload['aud']).where.not(exp: ..Time.now).last 22 | token = allowlisted_jwts.create!( 23 | jti: payload['jti'], 24 | aud: payload['aud'], 25 | exp: Time.at(payload['exp'].to_i) 26 | ) 27 | if token.present? && prev_token.present? 28 | token.update_columns({ 29 | browser_data: prev_token.browser_data, 30 | os_data: prev_token.os_data, 31 | remote_ip: prev_token.remote_ip, 32 | }) 33 | # NOTE: don't destroy the previous token right away in case 34 | # user opens new tab, or whatever and needs to do something... 35 | # prev_token.destroy! 36 | end 37 | token 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /config/locales/en.yml: -------------------------------------------------------------------------------- 1 | en: 2 | api: 3 | bad_request: "Bad Request" 4 | error: "API error: %{error} at LOC: %{loc}" 5 | not_found: "Not Found" 6 | ok: "ok" 7 | oops: "Oops! There was an error." 8 | unauthorized: "Unauthorized" 9 | controllers: 10 | comments: 11 | created: "Comment created successfully." 12 | deleted: "Comment deleted successfully." 13 | updated: "Comment updated successfully." 14 | confirmations: 15 | resent: "Confirmation email sent successfully." 16 | success: "Email confirmed successfully." 17 | passwords: 18 | email_required: "Email is required." 19 | email_sent: "Email sent. Please check your inbox." 20 | success: "Password updated successfully. You may need to sign in again." 21 | posts: 22 | created: "Post created successfully." 23 | deleted: "Post deleted successfully." 24 | updated: "Post updated successfully." 25 | registrations: 26 | confirm: "Please confirm your email address." 27 | sessions: 28 | sign_out: "Signed out successfully." 29 | users: 30 | updated: "Update successfully." 31 | models: 32 | users: 33 | slug_numbers: "cannot be only numbers, please add at least one character." 34 | username: "must be alphanumeric or underscore/dash only and must contain at least one character." 35 | username_numbers: "cannot be only numbers, please add at least one character." 36 | 37 | -------------------------------------------------------------------------------- /db/migrate/20210224031229_devise_create_users.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class DeviseCreateUsers < ActiveRecord::Migration[6.1] 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.string :current_sign_in_ip 22 | # t.string :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 | 36 | t.timestamps null: false 37 | end 38 | 39 | add_index :users, :email, unique: true 40 | add_index :users, :reset_password_token, unique: true 41 | add_index :users, :confirmation_token, unique: true 42 | # add_index :users, :unlock_token, unique: true 43 | end 44 | end 45 | -------------------------------------------------------------------------------- /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 ProgrammingtilRails1 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 | config.autoload_paths << Rails.root.join('lib') 29 | # 30 | # These settings can be overridden in specific environments using the files 31 | # in config/environments, which are processed later. 32 | # 33 | # config.time_zone = "Central Time (US & Canada)" 34 | # config.eager_load_paths << Rails.root.join("extras") 35 | 36 | # Only loads a smaller set of middleware suitable for API only apps. 37 | # Middleware like session, flash, cookies can be added back manually. 38 | # Skip views, helpers and assets when generating a new resource. 39 | config.api_only = true 40 | 41 | # Queues 42 | config.active_job.queue_adapter = :sidekiq 43 | end 44 | end 45 | -------------------------------------------------------------------------------- /app/controllers/passwords_controller.rb: -------------------------------------------------------------------------------- 1 | class PasswordsController < Devise::PasswordsController 2 | respond_to :json 3 | 4 | # POST /users/password 5 | # Specs No 6 | def create 7 | if params[:user] && params[:user][:email].blank? 8 | render json: { error: I18n.t('controllers.passwords.email_required') }, status: 406 9 | else 10 | self.resource = resource_class.send_reset_password_instructions(resource_params) 11 | if successfully_sent?(resource) 12 | render json: { message: I18n.t('controllers.passwords.email_sent') } 13 | else 14 | respond_with_error(resource) 15 | end 16 | end 17 | end 18 | 19 | # PUT /users/password 20 | # Specs No 21 | def update 22 | self.resource = resource_class.reset_password_by_token(resource_params) 23 | 24 | if resource.errors.empty? 25 | if Devise.sign_in_after_reset_password 26 | resource.after_database_authentication 27 | sign_in(resource_name, resource) 28 | if user_signed_in? 29 | respond_with(resource) 30 | else 31 | respond_with_error(resource) 32 | end 33 | else 34 | respond_with(resource) 35 | end 36 | else 37 | set_minimum_password_length 38 | respond_with_error(resource) 39 | end 40 | end 41 | 42 | private 43 | 44 | def current_token 45 | # NOTE: this is technically nil at this point, and user still must login again 46 | request.env['warden-jwt_auth.token'] 47 | end 48 | 49 | def respond_with(resource, _opts = {}) 50 | render json: { 51 | message: I18n.t('controllers.passwords.success'), 52 | user: resource.for_display, 53 | jwt: current_token, 54 | } 55 | end 56 | 57 | def respond_with_error(resource) 58 | render json: resource.errors, status: 401 59 | end 60 | end 61 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /app/controllers/api/v1/posts_controller.rb: -------------------------------------------------------------------------------- 1 | class Api::V1::PostsController < ApplicationController 2 | before_action :authenticate_user!, only: [:create, :update, :destroy] 3 | 4 | # POST /api/v1/posts 5 | def create 6 | authorize Post 7 | post = Post.create_post!(create_params, current_user) 8 | render json: post_show(post, { message: I18n.t('controllers.posts.created') }) 9 | end 10 | 11 | # DELETE /api/v1/posts/:id 12 | def destroy 13 | post = Post.find(params[:id]) 14 | authorize post 15 | post = Post.delete_post!(post) 16 | render json: post_show(post, { message: I18n.t('controllers.posts.deleted') }) 17 | end 18 | 19 | # GET /api/v1/posts 20 | def index 21 | posts = policy_scope(Post) 22 | posts = posts.for_index(params) 23 | render json: PostIndexSerializer.new(posts, list_options).serializable_hash.to_json 24 | end 25 | 26 | # GET /api/v1/posts/:slug 27 | def show 28 | post = Post.friendly.find(params[:id]) 29 | options = show_options 30 | options[:params] = options[:params].merge({ all: params[:all] }) if params[:all].present? 31 | render json: PostShowSerializer.new(post, options).serializable_hash.to_json 32 | rescue ActiveRecord::RecordNotFound 33 | render json: { error: I18n.t('api.not_found') }, status: 404 34 | end 35 | 36 | # PUT /api/v1/posts/:id 37 | def update 38 | post = Post.find(params[:id]) 39 | authorize post 40 | post = Post.update_post!(post, update_params) 41 | render json: post_show(post, { message: I18n.t('controllers.posts.updated') }) 42 | end 43 | 44 | private 45 | 46 | def create_params 47 | params.require(:post).permit(:title, :content, :published_at) 48 | end 49 | 50 | def update_params 51 | params.require(:post).permit(:id, :title, :content, :published_at) 52 | end 53 | 54 | def post_show(post, meta = {}) 55 | PostShowSerializer.new(post, show_options(meta)).serializable_hash.to_json 56 | end 57 | end 58 | -------------------------------------------------------------------------------- /app/controllers/api/v1/comments_controller.rb: -------------------------------------------------------------------------------- 1 | class Api::V1::CommentsController < ApplicationController 2 | before_action :authenticate_user!, only: [:create, :update, :destroy] 3 | 4 | # POST /api/v1/comments 5 | def create 6 | authorize Comment 7 | comment = Comment.create_comment!(current_user, create_params) 8 | render json: comment_show(comment, { message: I18n.t('controllers.comments.created') }) 9 | end 10 | 11 | # DELETE /api/v1/comments/:id 12 | def destroy 13 | comment = Comment.find(params[:id]) 14 | authorize comment 15 | comment = Comment.delete_comment!(comment) 16 | render json: comment_show(comment, { message: I18n.t('controllers.comments.deleted') }) 17 | end 18 | 19 | # GET /api/v1/comments 20 | def index 21 | comments = policy_scope(Comment) 22 | comments = comments 23 | .where(commentable_id: params[:commentable_id], commentable_type: params[:commentable_type]) 24 | .includes(:commentable, :user) 25 | render json: CommentIndexSerializer.new(comments, list_options).serializable_hash.to_json 26 | end 27 | 28 | # GET /api/v1/comments/:id 29 | def show 30 | comment = Comment.find(params[:id]) 31 | render json: comment_show(comment) 32 | rescue ActiveRecord::RecordNotFound 33 | render json: { error: I18n.t('api.not_found') }, status: 404 34 | end 35 | 36 | # PUT /api/v1/comments/:id 37 | def update 38 | comment = Comment.find(params[:id]) 39 | authorize comment 40 | comment = Comment.update_comment!(comment, update_params) 41 | render json: comment_show(comment, { message: I18n.t('controllers.comments.updated') }) 42 | end 43 | 44 | private 45 | 46 | def create_params 47 | params.require(:comment).permit(:body, :commentable_id, :commentable_type) 48 | end 49 | 50 | def update_params 51 | params.require(:comment).permit(:body, :id, :commentable_id, :commentable_type) 52 | end 53 | 54 | def comment_show(comment, meta = {}) 55 | CommentShowSerializer.new(comment, show_options(meta)).serializable_hash.to_json 56 | end 57 | end 58 | -------------------------------------------------------------------------------- /app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::API 2 | include Pundit 3 | 4 | rescue_from ActiveRecord::RecordInvalid, with: :record_invalid 5 | rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized 6 | 7 | before_action :configure_permitted_parameters, if: :devise_controller? 8 | 9 | # Helper methods 10 | # Return an options object for lists for jsonapi-serializer 11 | def list_options(meta = {}) 12 | opts = { is_collection: true } 13 | opts[:meta] = get_meta_data(meta) 14 | opts[:params] = get_params_data 15 | opts 16 | end 17 | 18 | # Return an options object for single objects for jsonapi-serializer 19 | def show_options(meta = {}) 20 | opts = { is_collection: false } 21 | opts[:meta] = get_meta_data(meta) 22 | opts[:params] = get_params_data 23 | opts 24 | end 25 | 26 | # Set any kind of meta data needed for the options 27 | def get_meta_data(meta = {}) 28 | ret_meta = meta 29 | if request.headers['auth_failure'] 30 | ret_meta[:authFailure] = true 31 | else 32 | if current_token.present? 33 | ret_meta[:jwt] = current_token 34 | end 35 | end 36 | ret_meta 37 | end 38 | 39 | # Set any kind of params data needed for the options 40 | def get_params_data 41 | if current_user.present? 42 | { user: current_user, } 43 | else 44 | {} 45 | end 46 | end 47 | 48 | protected 49 | 50 | def current_token 51 | request.env['warden-jwt_auth.token'] 52 | end 53 | 54 | def configure_permitted_parameters 55 | devise_parameter_sanitizer.permit(:sign_in, keys: [:login]) 56 | devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :email]) 57 | end 58 | 59 | private 60 | 61 | def record_invalid(exception) 62 | message = exception.message.partition('Validation failed: ').last 63 | render json: { meta: { message: message } }, status: 401 64 | return 65 | end 66 | 67 | def user_not_authorized 68 | render json: { message: I18n.t('api.unauthorized') }, status: 404 69 | return 70 | end 71 | end 72 | -------------------------------------------------------------------------------- /app/controllers/sessions_controller.rb: -------------------------------------------------------------------------------- 1 | require 'digest' 2 | 3 | class SessionsController < Devise::SessionsController 4 | respond_to :json 5 | 6 | # POST /users/sign_in 7 | # Specs No 8 | def create 9 | # Check both because rspec vs normal server requests .... do different things? WTF. 10 | possible_aud = request.headers['HTTP_JWT_AUD'].presence || request.headers['JWT_AUD'].presence 11 | if params[:browser].present? 12 | browser, version = params[:browser].split("||") 13 | digest = Digest::SHA256.hexdigest("#{params[:os]}||||#{browser}||#{version.to_i}") 14 | if digest != possible_aud 15 | raise "Unmatched AUD" 16 | end 17 | end 18 | self.resource = warden.authenticate!(auth_options) 19 | sign_in(resource_name, resource) 20 | if user_signed_in? 21 | # TODO: resource.blocked? 22 | # 23 | # For the initial login, we need to manually update IP / metadata for JWT here as no hooks 24 | # And we'll want this data for all subsequent requests 25 | last = resource.allowlisted_jwts.where(aud: possible_aud).last 26 | aud = possible_aud 27 | if last.present? 28 | last.update_columns({ 29 | browser_data: params[:browser], 30 | os_data: params[:os], 31 | remote_ip: params[:ip], 32 | }) 33 | aud = last.aud 34 | end 35 | respond_with(resource, { aud: aud }) 36 | else 37 | render json: resource.errors, status: 401 38 | end 39 | rescue => e 40 | render json: { error: I18n.t('api.oops') }, status: 500 41 | end 42 | 43 | private 44 | 45 | def current_token 46 | request.env['warden-jwt_auth.token'] 47 | end 48 | 49 | # What we respond with for signing in. 50 | # Add token in with body as fetch+CORS cannot read Authorization header 51 | def respond_with(resource, opts = {}) 52 | # NOTE: the current_token _should_ be the last AllowlistedJwt, but it might not 53 | # be, in case of race conditions and such 54 | render json: { 55 | user: resource.for_display, 56 | jwt: current_token, 57 | # aud: opts[:aud], 58 | } 59 | end 60 | 61 | # Required for sign out 62 | def respond_to_on_destroy 63 | render json: { message: I18n.t('controllers.sessions.sign_out') } 64 | end 65 | end 66 | -------------------------------------------------------------------------------- /app/models/user.rb: -------------------------------------------------------------------------------- 1 | # == Schema Information 2 | # 3 | # Table name: users 4 | # 5 | # id :bigint not null, primary key 6 | # email :string default(""), not null 7 | # encrypted_password :string default(""), not null 8 | # reset_password_token :string 9 | # reset_password_sent_at :datetime 10 | # remember_created_at :datetime 11 | # confirmation_token :string 12 | # confirmed_at :datetime 13 | # confirmation_sent_at :datetime 14 | # unconfirmed_email :string 15 | # created_at :datetime not null 16 | # updated_at :datetime not null 17 | # username :string 18 | # display_name :string 19 | # slug :string 20 | # theme :integer default(0) 21 | # theme_color :integer default(0) 22 | # 23 | # Indexes 24 | # 25 | # index_users_on_confirmation_token (confirmation_token) UNIQUE 26 | # index_users_on_email (email) UNIQUE 27 | # index_users_on_reset_password_token (reset_password_token) UNIQUE 28 | # index_users_on_slug (slug) UNIQUE 29 | # 30 | class User < ApplicationRecord 31 | include Users::Allowlist 32 | include Users::Associations 33 | include Users::Logic 34 | include Users::Validations 35 | 36 | devise :database_authenticatable, 37 | :confirmable, 38 | :registerable, 39 | :recoverable, 40 | :rememberable, 41 | :validatable, 42 | :jwt_authenticatable, 43 | jwt_revocation_strategy: self 44 | 45 | extend FriendlyId 46 | friendly_id :username, use: [:slugged] 47 | 48 | # DEVISE-specific things 49 | # Devise override for logging in with username or email 50 | attr_writer :login 51 | 52 | def login 53 | @login || username || email 54 | end 55 | 56 | # Use :login for searching username and email 57 | def self.find_for_database_authentication(warden_conditions) 58 | conditions = warden_conditions.dup 59 | login = conditions.delete(:login) 60 | where(conditions).where([ 61 | "lower(username) = :value OR lower(email) = :value", 62 | { value: login.strip.downcase }, 63 | ]).first 64 | end 65 | 66 | # Make sure to send the devise emails via async 67 | def send_devise_notification(notification, *args) 68 | devise_mailer.send(notification, self, *args).deliver_later 69 | end 70 | end 71 | -------------------------------------------------------------------------------- /config/environments/test.rb: -------------------------------------------------------------------------------- 1 | require "active_support/core_ext/integer/time" 2 | 3 | # The test environment is used exclusively to run your application's 4 | # test suite. You never need to work with it otherwise. Remember that 5 | # your test database is "scratch space" for the test suite and is wiped 6 | # and recreated between test runs. Don't rely on the data there! 7 | 8 | Rails.application.configure do 9 | # Settings specified here will take precedence over those in config/application.rb. 10 | 11 | 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 | -------------------------------------------------------------------------------- /spec/support/object_creators.rb: -------------------------------------------------------------------------------- 1 | module ObjectCreators 2 | def create_allowlisted_jwts(params = {}) 3 | user = params[:user].presence || create_user 4 | user.allowlisted_jwts.create!( 5 | jti: params['jti'].presence || 'TEST', 6 | aud: params['aud'].presence || 'TEST', 7 | exp: Time.at(params['exp'].presence.to_i || Time.now.to_i) 8 | ) 9 | end 10 | 11 | def create_comment(params = {}) 12 | user = params[:user].presence || create_user 13 | commentable = params[:commentable].presence || create_post 14 | last_id = Comment.limit(1).order(id: :desc).pluck(:id).first || 0 15 | Comment.create_comment!(user, { 16 | body: params[:body].presence || "Comment #{last_id+1}", 17 | commentable_id: commentable.id, 18 | commentable_type: commentable.class.name, 19 | }) 20 | end 21 | 22 | def create_post(params = {}) 23 | user = params[:user].presence || create_user 24 | last_id = Post.limit(1).order(id: :desc).pluck(:id).first || 0 25 | Post.create!({ 26 | title: params[:title].presence || "Post #{last_id+1}", 27 | content: params[:content].presence || "Post content #{last_id+1}", 28 | user_id: user.id 29 | }) 30 | end 31 | 32 | def create_user(params = {}) 33 | last_id = User.limit(1).order(id: :desc).pluck(:id).first || 0 34 | user = User.new( 35 | email: params[:name].present? ? "#{params[:name]}@test.com" : "testtest#{last_id+1}@test.com", 36 | username: params[:name].present? ? "#{params[:name]}" : "testtest#{last_id+1}", 37 | password: 'testtest', 38 | password_confirmation: 'testtest' 39 | ) 40 | user.skip_confirmation! 41 | user.save! 42 | user 43 | end 44 | 45 | # CONVENIENCE methods 46 | def get_aud 47 | Digest::SHA256.hexdigest("#{get_os}||||#{get_browser}") 48 | end 49 | 50 | def get_browser 51 | 'Chrome||89' 52 | end 53 | 54 | def get_os 55 | 'Linux||5.0' 56 | end 57 | 58 | def get_headers(login) 59 | jwt = get_jwt(login) 60 | { 61 | "Accept": "application/json", 62 | "Content-Type": "application/json", 63 | 'HTTP_JWT_AUD': get_aud, 64 | 'Authorization': "Bearer #{jwt}" 65 | } 66 | end 67 | 68 | def get_jwt(login) 69 | # NOTE: RSPEC sucks (uses HTTP_ because WTF) 70 | headers = { 'HTTP_JWT_AUD': get_aud } 71 | post '/users/sign_in', params: { 72 | user: { login: login, password: 'testtest' }, 73 | browser: get_browser, 74 | os: get_os 75 | }, headers: headers 76 | JSON.parse(response.body, object_class: OpenStruct).jwt 77 | end 78 | end 79 | 80 | RSpec.configure do |config| 81 | config.include ObjectCreators 82 | end 83 | -------------------------------------------------------------------------------- /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.default_url_options = { host: 'localhost', port: 5000 } 35 | config.action_mailer.delivery_method = :letter_opener 36 | config.action_mailer.raise_delivery_errors = false 37 | config.action_mailer.perform_caching = false 38 | config.action_mailer.perform_deliveries = true 39 | 40 | # Print deprecation notices to the Rails logger. 41 | config.active_support.deprecation = :log 42 | 43 | # Raise exceptions for disallowed deprecations. 44 | config.active_support.disallowed_deprecation = :raise 45 | 46 | # Tell Active Support which deprecation messages to disallow. 47 | config.active_support.disallowed_deprecation_warnings = [] 48 | 49 | # Raise an error on page load if there are pending migrations. 50 | config.active_record.migration_error = :page_load 51 | 52 | # Highlight code that triggered database queries in logs. 53 | config.active_record.verbose_query_logs = true 54 | 55 | 56 | # Raises error for missing translations. 57 | # config.i18n.raise_on_missing_translations = true 58 | 59 | # Annotate rendered view with file names. 60 | # config.action_view.annotate_rendered_view_with_filenames = true 61 | 62 | # Use an evented file watcher to asynchronously detect changes in source code, 63 | # routes, locales, etc. This feature depends on the listen gem. 64 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker 65 | 66 | # Uncomment if you wish to allow Action Cable access from any origin. 67 | # config.action_cable.disable_request_forgery_protection = true 68 | end 69 | -------------------------------------------------------------------------------- /lib/tasks/auto_annotate_models.rake: -------------------------------------------------------------------------------- 1 | # NOTE: only doing this in development as some production environments (Heroku) 2 | # NOTE: are sensitive to local FS writes, and besides -- it's just not proper 3 | # NOTE: to have a dev-mode tool do its thing in production. 4 | if Rails.env.development? 5 | require 'annotate' 6 | task :set_annotation_options do 7 | # You can override any of these by setting an environment variable of the 8 | # same name. 9 | Annotate.set_defaults( 10 | 'active_admin' => 'false', 11 | 'additional_file_patterns' => [], 12 | 'routes' => 'false', 13 | 'models' => 'true', 14 | 'position_in_routes' => 'before', 15 | 'position_in_class' => 'before', 16 | 'position_in_test' => 'before', 17 | 'position_in_fixture' => 'before', 18 | 'position_in_factory' => 'before', 19 | 'position_in_serializer' => 'before', 20 | 'show_foreign_keys' => 'true', 21 | 'show_complete_foreign_keys' => 'false', 22 | 'show_indexes' => 'true', 23 | 'simple_indexes' => 'false', 24 | 'model_dir' => 'app/models', 25 | 'root_dir' => '', 26 | 'include_version' => 'false', 27 | 'require' => '', 28 | 'exclude_tests' => 'false', 29 | 'exclude_fixtures' => 'true', 30 | 'exclude_factories' => 'true', 31 | 'exclude_serializers' => 'true', 32 | 'exclude_scaffolds' => 'true', 33 | 'exclude_controllers' => 'true', 34 | 'exclude_helpers' => 'true', 35 | 'exclude_sti_subclasses' => 'false', 36 | 'ignore_model_sub_dir' => 'false', 37 | 'ignore_columns' => nil, 38 | 'ignore_routes' => nil, 39 | 'ignore_unknown_models' => 'false', 40 | 'hide_limit_column_types' => 'integer,bigint,boolean', 41 | 'hide_default_column_types' => 'json,jsonb,hstore', 42 | 'skip_on_db_migrate' => 'false', 43 | 'format_bare' => 'true', 44 | 'format_rdoc' => 'false', 45 | 'format_yard' => 'false', 46 | 'format_markdown' => 'false', 47 | 'sort' => 'false', 48 | 'force' => 'false', 49 | 'frozen' => 'false', 50 | 'classified_sort' => 'false', 51 | 'trace' => 'false', 52 | 'wrapper_open' => nil, 53 | 'wrapper_close' => nil, 54 | 'with_comment' => 'true' 55 | ) 56 | end 57 | 58 | Annotate.load_tasks 59 | end 60 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | # For details on connection pooling, see Rails configuration guide 21 | # https://guides.rubyonrails.org/configuring.html#database-pooling 22 | pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> 23 | 24 | development: 25 | <<: *default 26 | database: programmingtil_rails_1_development 27 | host: 127.0.0.1 28 | 29 | # The specified database role being used to connect to postgres. 30 | # To create additional roles in postgres see `$ createuser --help`. 31 | # When left blank, postgres will use the default role. This is 32 | # the same name as the operating system user running Rails. 33 | #username: programmingtil_rails_1 34 | 35 | # The password associated with the postgres role (username). 36 | #password: 37 | 38 | # Connect on a TCP socket. Omitted by default since the client uses a 39 | # domain socket that doesn't need configuration. Windows does not have 40 | # domain sockets, so uncomment these lines. 41 | #host: localhost 42 | 43 | # The TCP port the server listens on. Defaults to 5432. 44 | # If your server runs on a different port number, change accordingly. 45 | #port: 5432 46 | 47 | # Schema search path. The server defaults to $user,public 48 | #schema_search_path: myapp,sharedapp,public 49 | 50 | # Minimum log levels, in increasing order: 51 | # debug5, debug4, debug3, debug2, debug1, 52 | # log, notice, warning, error, fatal, and panic 53 | # Defaults to warning. 54 | #min_messages: notice 55 | 56 | # Warning: The database defined as "test" will be erased and 57 | # re-generated from your development database when you run "rake". 58 | # Do not set this db to the same as development or production. 59 | test: 60 | <<: *default 61 | database: programmingtil_rails_1_test 62 | password: <%= ENV['POSTGRES_PASSWORD'] %> 63 | username: <%= ENV['POSTGRES_USER'] %> 64 | host: 127.0.0.1 65 | 66 | # As with config/credentials.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 or a full connection URL as an environment 71 | # variable when you boot the app. For example: 72 | # 73 | # DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" 74 | # 75 | # If the connection URL is provided in the special DATABASE_URL environment 76 | # variable, Rails will automatically merge its configuration values on top of 77 | # the values provided in this file. Alternatively, you can specify a connection 78 | # URL environment variable explicitly: 79 | # 80 | # production: 81 | # url: <%= ENV['MY_APP_DATABASE_URL'] %> 82 | # 83 | # Read https://guides.rubyonrails.org/configuring.html#configuring-a-database 84 | # for a full overview on how database connection configuration can be specified. 85 | # 86 | production: 87 | <<: *default 88 | database: programmingtil_rails_1_production 89 | username: programmingtil_rails_1 90 | password: <%= ENV['PROGRAMMINGTIL_RAILS_1_DATABASE_PASSWORD'] %> 91 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | git_source(:github) { |repo| "https://github.com/#{repo}.git" } 3 | 4 | ruby '3.0.0' 5 | 6 | # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' 7 | gem 'rails', '~> 6.1.1' 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 | # Use Active Storage variant 20 | gem 'image_processing', '~> 1.2' 21 | 22 | # Reduces boot times through caching; required in config/boot.rb 23 | gem 'bootsnap', '>= 1.4.4', require: false 24 | 25 | # Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible 26 | # https://github.com/cyu/rack-cors 27 | gem 'rack-cors' 28 | 29 | # Authentication 30 | # https://github.com/heartcombo/devise 31 | gem 'devise', github: 'heartcombo/devise' 32 | 33 | # JWT devise for API 34 | # https://github.com/waiting-for-dev/devise-jwt 35 | gem 'devise-jwt' 36 | 37 | # Authorization 38 | # https://github.com/varvet/pundit 39 | gem 'pundit' 40 | 41 | # JSON API 42 | # Previously known as FastJson API 43 | # https://github.com/jsonapi-serializer/jsonapi-serializer 44 | gem 'jsonapi-serializer' 45 | 46 | # Friendly IDs 47 | # https://github.com/norman/friendly_id 48 | gem 'friendly_id', '~> 5.4.0' 49 | 50 | # Perform background queue jobs 51 | # https://github.com/mperham/sidekiq 52 | gem 'sidekiq' 53 | 54 | # Create our sitemap 55 | # https://github.com/kjvarga/sitemap_generator 56 | gem 'sitemap_generator' 57 | 58 | # AWS for storage 59 | # https://github.com/aws/aws-sdk-ruby 60 | gem 'aws-sdk-s3' 61 | 62 | group :development, :test do 63 | # Call 'byebug' anywhere in the code to stop execution and get a debugger console 64 | gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] 65 | 66 | # RSpec for testing 67 | # https://github.com/rspec/rspec-rails 68 | gem 'rspec-rails' 69 | # Needed for rspec 70 | gem 'rexml' 71 | gem 'spring-commands-rspec' 72 | # https://github.com/grosser/parallel_tests 73 | gem 'parallel_tests' 74 | 75 | # .env environment variable 76 | # https://github.com/bkeepers/dotenv 77 | gem 'dotenv-rails' 78 | end 79 | 80 | group :development do 81 | gem 'listen', '~> 3.3' 82 | # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring 83 | gem 'spring' 84 | 85 | # Annotate models and more 86 | # https://github.com/ctran/annotate_models 87 | gem 'annotate' 88 | 89 | # Local Emails 90 | # https://github.com/ryanb/letter_opener 91 | gem 'letter_opener' 92 | end 93 | 94 | group :test do 95 | # Adds support for Capybara system testing and selenium driver 96 | gem 'capybara', '>= 2.15' 97 | gem 'selenium-webdriver' 98 | # Easy installation and use of web drivers to run system tests with browsers 99 | gem 'webdrivers' 100 | 101 | # Code coverage 102 | # https://github.com/colszowka/simplecov 103 | gem 'simplecov', require: false 104 | 105 | # Clear out database between runs 106 | # https://github.com/DatabaseCleaner/database_cleaner 107 | gem 'database_cleaner-active_record' 108 | end 109 | 110 | # Windows does not include zoneinfo files, so bundle the tzinfo-data gem 111 | gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] 112 | -------------------------------------------------------------------------------- /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_04_22_213742) do 14 | 15 | # These are extensions that must be enabled in order to support this database 16 | enable_extension "plpgsql" 17 | 18 | create_table "allowlisted_jwts", force: :cascade do |t| 19 | t.bigint "user_id", null: false 20 | t.string "jti", null: false 21 | t.string "aud", null: false 22 | t.datetime "exp", null: false 23 | t.string "remote_ip" 24 | t.string "os_data" 25 | t.string "browser_data" 26 | t.string "device_data" 27 | t.datetime "created_at", precision: 6, null: false 28 | t.datetime "updated_at", precision: 6, null: false 29 | t.index ["jti"], name: "index_allowlisted_jwts_on_jti", unique: true 30 | t.index ["user_id"], name: "index_allowlisted_jwts_on_user_id" 31 | end 32 | 33 | create_table "comments", force: :cascade do |t| 34 | t.string "commentable_type" 35 | t.bigint "commentable_id" 36 | t.bigint "user_id" 37 | t.bigint "thread_id" 38 | t.bigint "parent_id" 39 | t.text "body", null: false 40 | t.datetime "deleted_at" 41 | t.datetime "created_at", precision: 6, null: false 42 | t.datetime "updated_at", precision: 6, null: false 43 | t.index ["commentable_type", "commentable_id"], name: "index_comments_on_commentable" 44 | t.index ["parent_id"], name: "index_comments_on_parent_id" 45 | t.index ["thread_id"], name: "index_comments_on_thread_id" 46 | t.index ["user_id"], name: "index_comments_on_user_id" 47 | end 48 | 49 | create_table "posts", force: :cascade do |t| 50 | t.bigint "user_id", null: false 51 | t.string "title", null: false 52 | t.text "content", null: false 53 | t.datetime "published_at" 54 | t.datetime "created_at", precision: 6, null: false 55 | t.datetime "updated_at", precision: 6, null: false 56 | t.string "slug" 57 | t.bigint "comments_count" 58 | t.index ["user_id"], name: "index_posts_on_user_id" 59 | end 60 | 61 | create_table "users", force: :cascade do |t| 62 | t.string "email", default: "", null: false 63 | t.string "encrypted_password", default: "", null: false 64 | t.string "reset_password_token" 65 | t.datetime "reset_password_sent_at" 66 | t.datetime "remember_created_at" 67 | t.string "confirmation_token" 68 | t.datetime "confirmed_at" 69 | t.datetime "confirmation_sent_at" 70 | t.string "unconfirmed_email" 71 | t.datetime "created_at", precision: 6, null: false 72 | t.datetime "updated_at", precision: 6, null: false 73 | t.string "username" 74 | t.string "display_name" 75 | t.string "slug" 76 | t.integer "theme", default: 0 77 | t.integer "theme_color", default: 0 78 | t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true 79 | t.index ["email"], name: "index_users_on_email", unique: true 80 | t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true 81 | t.index ["slug"], name: "index_users_on_slug", unique: true 82 | end 83 | 84 | add_foreign_key "allowlisted_jwts", "users", on_delete: :cascade 85 | end 86 | -------------------------------------------------------------------------------- /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', __dir__) 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 'devise' 10 | # require 'devise/jwt/test_helpers' 11 | 12 | # Requires supporting ruby files with custom matchers and macros, etc, in 13 | # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are 14 | # run as spec files by default. This means that files in spec/support that end 15 | # in _spec.rb will both be required and run as specs, causing the specs to be 16 | # run twice. It is recommended that you do not name files matching this glob to 17 | # end with _spec.rb. You can configure this pattern with the --pattern 18 | # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. 19 | # 20 | # The following line is provided for convenience purposes. It has the downside 21 | # of increasing the boot-up time by auto-requiring all files in the support 22 | # directory. Alternatively, in the individual `*_spec.rb` files, manually 23 | # require only the support files necessary. 24 | # 25 | Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f } 26 | 27 | # Checks for pending migrations and applies them before tests are run. 28 | # If you are not using ActiveRecord, you can remove these lines. 29 | begin 30 | ActiveRecord::Migration.maintain_test_schema! 31 | rescue ActiveRecord::PendingMigrationError => e 32 | puts e.to_s.strip 33 | exit 1 34 | end 35 | 36 | RSpec.configure do |config| 37 | # config.include Devise::Test::IntegrationHelpers, type: :request 38 | 39 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 40 | config.fixture_path = "#{::Rails.root}/spec/fixtures" 41 | 42 | # If you're not using ActiveRecord, or you'd prefer not to run each of your 43 | # examples within a transaction, remove the following line or assign false 44 | # instead of true. 45 | config.use_transactional_fixtures = true 46 | 47 | config.before(:suite) do 48 | DatabaseCleaner.strategy = :transaction 49 | DatabaseCleaner.clean_with(:truncation) 50 | end 51 | 52 | # config.around(:each) do |example| 53 | # DatabaseCleaner.cleaning do 54 | # example.run 55 | # end 56 | # end 57 | config.before(:each) do 58 | DatabaseCleaner.strategy = :transaction 59 | # DatabaseCleaner.start 60 | end 61 | 62 | config.after(:each) do 63 | DatabaseCleaner.clean 64 | end 65 | 66 | # config.append_after(:each) do 67 | # DatabaseCleaner.clean 68 | # end 69 | 70 | # You can uncomment this line to turn off ActiveRecord support entirely. 71 | # config.use_active_record = false 72 | 73 | # RSpec Rails can automatically mix in different behaviours to your tests 74 | # based on their file location, for example enabling you to call `get` and 75 | # `post` in specs under `spec/controllers`. 76 | # 77 | # You can disable this behaviour by removing the line below, and instead 78 | # explicitly tag your specs with their type, e.g.: 79 | # 80 | # RSpec.describe UsersController, type: :controller do 81 | # # ... 82 | # end 83 | # 84 | # The different available types are documented in the features, such as in 85 | # https://relishapp.com/rspec/rspec-rails/docs 86 | config.infer_spec_type_from_file_location! 87 | 88 | # Filter lines from Rails gems in backtraces. 89 | config.filter_rails_from_backtrace! 90 | # arbitrary gems may also be filtered via: 91 | # config.filter_gems_from_backtrace("gem name") 92 | end 93 | -------------------------------------------------------------------------------- /public/sitemap.xml: -------------------------------------------------------------------------------- 1 |