├── .gitignore ├── .ruby-gemset ├── .ruby-version ├── Gemfile ├── Gemfile.lock ├── README.md ├── Rakefile ├── app ├── assets │ └── images │ │ └── .keep ├── controllers │ ├── api │ │ └── v1 │ │ │ ├── comments_controller.rb │ │ │ ├── registrations_controller.rb │ │ │ └── sessions_controller.rb │ ├── application_controller.rb │ └── concerns │ │ └── .keep ├── mailers │ └── .keep ├── models │ ├── .keep │ ├── comment.rb │ ├── concerns │ │ └── .keep │ └── user.rb └── serializers │ ├── comment_serializer.rb │ └── user_serializer.rb ├── bin ├── bundle ├── rails ├── rake └── setup ├── config.ru ├── config ├── application.rb ├── boot.rb ├── database.yml ├── deploy.rb ├── environment.rb ├── environment_variables.yml ├── environments │ ├── development.rb │ ├── production.rb │ └── test.rb ├── initializers │ ├── !environment_variables.rb │ ├── devise.rb │ ├── filter_parameter_logging.rb │ ├── secret_token.rb │ └── wrap_parameters.rb ├── locales │ ├── devise.en.yml │ └── en.yml ├── routes.rb └── secrets.yml ├── db ├── migrate │ ├── 20150719225954_devise_create_users.rb │ └── 20150720105123_create_comments.rb ├── schema.rb └── seeds.rb ├── lib ├── api_constraints.rb ├── assets │ └── .keep ├── mina │ ├── check.rb │ ├── defaults.rb │ ├── docs │ │ ├── .keeper │ │ └── deploy.rb │ ├── env.rb │ ├── helpers │ │ ├── checkers.rb │ │ ├── print.rb │ │ ├── render.rb │ │ └── servers.rb │ ├── log.rb │ ├── nginx.rb │ ├── servers │ │ ├── production.rb │ │ └── staging.rb │ ├── setup.rb │ ├── templates │ │ ├── database.example.yml.erb │ │ ├── environment_variables.example.yml.erb │ │ ├── logrotate.erb │ │ ├── nginx.conf.erb │ │ ├── unicorn.rb.erb │ │ └── unicorn_init.sh.erb │ └── unicorn.rb ├── subdomain_constraints.rb └── tasks │ └── .keep ├── public ├── 404.html ├── 422.html ├── 500.html ├── favicon.ico └── robots.txt ├── spec ├── factories │ ├── comments.rb │ └── users.rb ├── models │ ├── comment_spec.rb │ └── user_spec.rb ├── rails_helper.rb ├── requests │ └── api │ │ └── v1 │ │ ├── comments_spec.rb │ │ ├── registrations_spec.rb │ │ └── sessions_spec.rb ├── routing │ └── api_constraints_spec.rb ├── spec_helper.rb └── support │ ├── request_helpers.rb │ └── unauthorized_shared_examples.rb └── test ├── controllers └── .keep ├── fixtures └── .keep ├── helpers └── .keep ├── integration └── .keep ├── mailers └── .keep ├── models └── .keep └── test_helper.rb /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io 2 | 3 | 4 | ### Ruby ### 5 | *.gem 6 | *.rbc 7 | /.config 8 | /coverage/ 9 | /InstalledFiles 10 | /pkg/ 11 | /spec/reports/ 12 | /test/tmp/ 13 | /test/version_tmp/ 14 | /tmp/ 15 | 16 | 17 | ## Documentation cache and generated files: 18 | /.yardoc/ 19 | /_yardoc/ 20 | /doc/ 21 | /rdoc/ 22 | 23 | ## Environment normalisation: 24 | /.bundle/ 25 | /vendor/bundle 26 | /lib/bundler/man/ 27 | 28 | # for a library or gem, you might want to ignore these files since the code is 29 | # intended to run in multiple environments; otherwise, check them in: 30 | # Gemfile.lock 31 | # .ruby-version 32 | # .ruby-gemset 33 | 34 | # unless supporting rvm < 1.11.0 or doing something fancy, ignore this: 35 | .rvmrc 36 | 37 | 38 | 39 | ### Rails ### 40 | *.rbc 41 | capybara-*.html 42 | .rspec 43 | /log 44 | !/log/.keep 45 | /tmp 46 | /db/*.sqlite3 47 | /db/*.sqlite3-journal 48 | /public/system 49 | /coverage/ 50 | /spec/tmp 51 | **.orig 52 | rerun.txt 53 | pickle-email-*.html 54 | 55 | # Comment out these rules if you are OK with secrets being uploaded to the repo 56 | # config/initializers/secret_token.rb 57 | # config/secrets.yml 58 | 59 | ## Environment normalisation: 60 | /.bundle 61 | /vendor/bundle 62 | 63 | # these should all be checked in to normalise the environment: 64 | # Gemfile.lock, .ruby-version, .ruby-gemset 65 | 66 | # unless supporting rvm < 1.11.0 or doing something fancy, ignore this: 67 | .rvmrc 68 | 69 | # if using bower-rails ignore default bower_components path bower.json files 70 | /vendor/assets/bower_components 71 | *.bowerrc 72 | bower.json 73 | 74 | # Ignore pow environment settings 75 | .powenv 76 | 77 | 78 | 79 | ### Node ### 80 | # Logs 81 | logs 82 | *.log 83 | 84 | # Runtime data 85 | pids 86 | *.pid 87 | *.seed 88 | 89 | # Directory for instrumented libs generated by jscoverage/JSCover 90 | lib-cov 91 | 92 | # Coverage directory used by tools like istanbul 93 | coverage 94 | 95 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 96 | .grunt 97 | 98 | # node-waf configuration 99 | .lock-wscript 100 | 101 | # Compiled binary addons (http://nodejs.org/api/addons.html) 102 | build/Release 103 | 104 | # Dependency directory 105 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git 106 | node_modules 107 | 108 | 109 | 110 | ### Bower ### 111 | bower_components 112 | .bower-cache 113 | .bower-registry 114 | .bower-tmp 115 | 116 | 117 | 118 | ### JetBrains ### 119 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm 120 | 121 | *.iml 122 | 123 | ## Directory-based project format: 124 | .idea/ 125 | # if you remove the above rule, at least ignore the following: 126 | 127 | # User-specific stuff: 128 | # .idea/workspace.xml 129 | # .idea/tasks.xml 130 | # .idea/dictionaries 131 | 132 | # Sensitive or high-churn files: 133 | # .idea/dataSources.ids 134 | # .idea/dataSources.xml 135 | # .idea/sqlDataSources.xml 136 | # .idea/dynamic.xml 137 | # .idea/uiDesigner.xml 138 | 139 | # Gradle: 140 | # .idea/gradle.xml 141 | # .idea/libraries 142 | 143 | # Mongo Explorer plugin: 144 | # .idea/mongoSettings.xml 145 | 146 | ## File-based project format: 147 | *.ipr 148 | *.iws 149 | 150 | ## Plugin-specific files: 151 | 152 | # IntelliJ 153 | /out/ 154 | 155 | # mpeltonen/sbt-idea plugin 156 | .idea_modules/ 157 | 158 | # JIRA plugin 159 | atlassian-ide-plugin.xml 160 | 161 | # Crashlytics plugin (for Android Studio and IntelliJ) 162 | com_crashlytics_export_strings.xml 163 | crashlytics.properties 164 | crashlytics-build.properties 165 | 166 | 167 | 168 | ### OSX ### 169 | .DS_Store 170 | .AppleDouble 171 | .LSOverride 172 | 173 | # Icon must end with two \r 174 | Icon 175 | 176 | 177 | # Thumbnails 178 | ._* 179 | 180 | # Files that might appear in the root of a volume 181 | .DocumentRevisions-V100 182 | .fseventsd 183 | .Spotlight-V100 184 | .TemporaryItems 185 | .Trashes 186 | .VolumeIcon.icns 187 | 188 | # Directories potentially created on remote AFP share 189 | .AppleDB 190 | .AppleDesktop 191 | Network Trash Folder 192 | Temporary Items 193 | .apdisk 194 | 195 | 196 | 197 | ### Windows ### 198 | # Windows image file caches 199 | Thumbs.db 200 | ehthumbs.db 201 | 202 | # Folder config file 203 | Desktop.ini 204 | 205 | # Recycle Bin used on file shares 206 | $RECYCLE.BIN/ 207 | 208 | # Windows Installer files 209 | *.cab 210 | *.msi 211 | *.msm 212 | *.msp 213 | 214 | # Windows shortcuts 215 | *.lnk 216 | -------------------------------------------------------------------------------- /.ruby-gemset: -------------------------------------------------------------------------------- 1 | isomorphic-comments 2 | -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | ruby-2.2.1 2 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | gem 'rails', '4.2.3' 4 | gem 'rails-api' 5 | gem 'active_model_serializers', '~> 0.8.3' 6 | gem 'responders' 7 | 8 | gem 'annotate', '~> 2.6.5' 9 | gem 'exception_notification' 10 | 11 | gem 'pg' 12 | 13 | gem 'devise' 14 | gem 'simple_token_authentication' 15 | 16 | gem 'unicorn' 17 | 18 | group :development do 19 | gem 'mina' 20 | end 21 | 22 | group :development, :test do 23 | 24 | gem 'byebug' 25 | gem 'spring' 26 | 27 | gem 'rspec-rails' 28 | gem 'factory_girl_rails' 29 | gem 'faker' 30 | gem 'shoulda-matchers' 31 | gem 'database_cleaner' 32 | 33 | end 34 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | actionmailer (4.2.3) 5 | actionpack (= 4.2.3) 6 | actionview (= 4.2.3) 7 | activejob (= 4.2.3) 8 | mail (~> 2.5, >= 2.5.4) 9 | rails-dom-testing (~> 1.0, >= 1.0.5) 10 | actionpack (4.2.3) 11 | actionview (= 4.2.3) 12 | activesupport (= 4.2.3) 13 | rack (~> 1.6) 14 | rack-test (~> 0.6.2) 15 | rails-dom-testing (~> 1.0, >= 1.0.5) 16 | rails-html-sanitizer (~> 1.0, >= 1.0.2) 17 | actionview (4.2.3) 18 | activesupport (= 4.2.3) 19 | builder (~> 3.1) 20 | erubis (~> 2.7.0) 21 | rails-dom-testing (~> 1.0, >= 1.0.5) 22 | rails-html-sanitizer (~> 1.0, >= 1.0.2) 23 | active_model_serializers (0.8.3) 24 | activemodel (>= 3.0) 25 | activejob (4.2.3) 26 | activesupport (= 4.2.3) 27 | globalid (>= 0.3.0) 28 | activemodel (4.2.3) 29 | activesupport (= 4.2.3) 30 | builder (~> 3.1) 31 | activerecord (4.2.3) 32 | activemodel (= 4.2.3) 33 | activesupport (= 4.2.3) 34 | arel (~> 6.0) 35 | activesupport (4.2.3) 36 | i18n (~> 0.7) 37 | json (~> 1.7, >= 1.7.7) 38 | minitest (~> 5.1) 39 | thread_safe (~> 0.3, >= 0.3.4) 40 | tzinfo (~> 1.1) 41 | annotate (2.6.10) 42 | activerecord (>= 3.2, <= 4.3) 43 | rake (~> 10.4) 44 | arel (6.0.2) 45 | bcrypt (3.1.10) 46 | builder (3.2.2) 47 | byebug (5.0.0) 48 | columnize (= 0.9.0) 49 | columnize (0.9.0) 50 | database_cleaner (1.4.1) 51 | devise (3.5.1) 52 | bcrypt (~> 3.0) 53 | orm_adapter (~> 0.1) 54 | railties (>= 3.2.6, < 5) 55 | responders 56 | thread_safe (~> 0.1) 57 | warden (~> 1.2.3) 58 | diff-lcs (1.2.5) 59 | erubis (2.7.0) 60 | exception_notification (4.1.1) 61 | actionmailer (>= 3.0.4) 62 | activesupport (>= 3.0.4) 63 | factory_girl (4.5.0) 64 | activesupport (>= 3.0.0) 65 | factory_girl_rails (4.5.0) 66 | factory_girl (~> 4.5.0) 67 | railties (>= 3.0.0) 68 | faker (1.4.3) 69 | i18n (~> 0.5) 70 | globalid (0.3.5) 71 | activesupport (>= 4.1.0) 72 | i18n (0.7.0) 73 | json (1.8.3) 74 | kgio (2.9.3) 75 | loofah (2.0.2) 76 | nokogiri (>= 1.5.9) 77 | mail (2.6.3) 78 | mime-types (>= 1.16, < 3) 79 | mime-types (2.6.1) 80 | mina (0.3.7) 81 | open4 (~> 1.3.4) 82 | rake 83 | mini_portile (0.6.2) 84 | minitest (5.7.0) 85 | nokogiri (1.6.6.2) 86 | mini_portile (~> 0.6.0) 87 | open4 (1.3.4) 88 | orm_adapter (0.5.0) 89 | pg (0.18.2) 90 | rack (1.6.4) 91 | rack-test (0.6.3) 92 | rack (>= 1.0) 93 | rails (4.2.3) 94 | actionmailer (= 4.2.3) 95 | actionpack (= 4.2.3) 96 | actionview (= 4.2.3) 97 | activejob (= 4.2.3) 98 | activemodel (= 4.2.3) 99 | activerecord (= 4.2.3) 100 | activesupport (= 4.2.3) 101 | bundler (>= 1.3.0, < 2.0) 102 | railties (= 4.2.3) 103 | sprockets-rails 104 | rails-api (0.4.0) 105 | actionpack (>= 3.2.11) 106 | railties (>= 3.2.11) 107 | rails-deprecated_sanitizer (1.0.3) 108 | activesupport (>= 4.2.0.alpha) 109 | rails-dom-testing (1.0.6) 110 | activesupport (>= 4.2.0.beta, < 5.0) 111 | nokogiri (~> 1.6.0) 112 | rails-deprecated_sanitizer (>= 1.0.1) 113 | rails-html-sanitizer (1.0.2) 114 | loofah (~> 2.0) 115 | railties (4.2.3) 116 | actionpack (= 4.2.3) 117 | activesupport (= 4.2.3) 118 | rake (>= 0.8.7) 119 | thor (>= 0.18.1, < 2.0) 120 | raindrops (0.14.0) 121 | rake (10.4.2) 122 | responders (2.1.0) 123 | railties (>= 4.2.0, < 5) 124 | rspec-core (3.3.2) 125 | rspec-support (~> 3.3.0) 126 | rspec-expectations (3.3.1) 127 | diff-lcs (>= 1.2.0, < 2.0) 128 | rspec-support (~> 3.3.0) 129 | rspec-mocks (3.3.2) 130 | diff-lcs (>= 1.2.0, < 2.0) 131 | rspec-support (~> 3.3.0) 132 | rspec-rails (3.3.3) 133 | actionpack (>= 3.0, < 4.3) 134 | activesupport (>= 3.0, < 4.3) 135 | railties (>= 3.0, < 4.3) 136 | rspec-core (~> 3.3.0) 137 | rspec-expectations (~> 3.3.0) 138 | rspec-mocks (~> 3.3.0) 139 | rspec-support (~> 3.3.0) 140 | rspec-support (3.3.0) 141 | shoulda-matchers (2.8.0) 142 | activesupport (>= 3.0.0) 143 | simple_token_authentication (1.10.0) 144 | actionmailer (>= 3.2.6, < 5) 145 | actionpack (>= 3.2.6, < 5) 146 | devise (~> 3.2) 147 | spring (1.3.6) 148 | sprockets (3.2.0) 149 | rack (~> 1.0) 150 | sprockets-rails (2.3.2) 151 | actionpack (>= 3.0) 152 | activesupport (>= 3.0) 153 | sprockets (>= 2.8, < 4.0) 154 | thor (0.19.1) 155 | thread_safe (0.3.5) 156 | tzinfo (1.2.2) 157 | thread_safe (~> 0.1) 158 | unicorn (4.9.0) 159 | kgio (~> 2.6) 160 | rack 161 | raindrops (~> 0.7) 162 | warden (1.2.3) 163 | rack (>= 1.0) 164 | 165 | PLATFORMS 166 | ruby 167 | 168 | DEPENDENCIES 169 | active_model_serializers (~> 0.8.3) 170 | annotate (~> 2.6.5) 171 | byebug 172 | database_cleaner 173 | devise 174 | exception_notification 175 | factory_girl_rails 176 | faker 177 | mina 178 | pg 179 | rails (= 4.2.3) 180 | rails-api 181 | responders 182 | rspec-rails 183 | shoulda-matchers 184 | simple_token_authentication 185 | spring 186 | unicorn 187 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Isomorphic comments 2 | 3 | Isomorphic / universal Flux app, backed by Rails API. 4 | 5 | Live demo: http://isomorphic-comments.alexfedoseev.com 6 | Details: https://github.com/alexfedoseev/generator-flux-on-rails 7 | -------------------------------------------------------------------------------- /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 File.expand_path('../config/application', __FILE__) 5 | 6 | Rails.application.load_tasks 7 | -------------------------------------------------------------------------------- /app/assets/images/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alex35mil/isomorphic-comments-api/1cbd63133d58fc801db6c694ad9ffdd43215172b/app/assets/images/.keep -------------------------------------------------------------------------------- /app/controllers/api/v1/comments_controller.rb: -------------------------------------------------------------------------------- 1 | class Api::V1::CommentsController < ApplicationController 2 | 3 | skip_before_action :authenticate_api_user!, only: [:index, :show, :create] 4 | before_action :get_comment, only: [:show, :destroy] 5 | 6 | def index 7 | @comments = Comment.all.order(:id).reverse 8 | respond_with @comments 9 | end 10 | 11 | def show 12 | respond_with @comment 13 | end 14 | 15 | def create 16 | @comment = Comment.new(comment_params) 17 | if @comment.save 18 | render json: @comment, status: 201 19 | else 20 | render json: { errors: @comment.errors.full_messages }, status: 422 21 | end 22 | end 23 | 24 | def destroy 25 | @comment.destroy if Rails.env.development? 26 | head 204 27 | end 28 | 29 | 30 | private 31 | 32 | def get_comment 33 | @comment = Comment.find(params[:id]) 34 | end 35 | 36 | def comment_params 37 | params.require(:comment).permit(:author, :comment) 38 | end 39 | 40 | end 41 | -------------------------------------------------------------------------------- /app/controllers/api/v1/registrations_controller.rb: -------------------------------------------------------------------------------- 1 | class Api::V1::RegistrationsController < Devise::RegistrationsController 2 | 3 | include ActionController::ImplicitRender 4 | 5 | respond_to :json 6 | 7 | end -------------------------------------------------------------------------------- /app/controllers/api/v1/sessions_controller.rb: -------------------------------------------------------------------------------- 1 | class Api::V1::SessionsController < Devise::SessionsController 2 | 3 | include ActionController::ImplicitRender 4 | 5 | respond_to :json 6 | 7 | end -------------------------------------------------------------------------------- /app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::API 2 | 3 | include ActionController::ImplicitRender 4 | 5 | acts_as_token_authentication_handler_for User, fallback_to_devise: false 6 | before_action :authenticate_api_user! 7 | 8 | respond_to :json 9 | 10 | 11 | def auth_preflight 12 | head 200 13 | end 14 | 15 | end 16 | -------------------------------------------------------------------------------- /app/controllers/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alex35mil/isomorphic-comments-api/1cbd63133d58fc801db6c694ad9ffdd43215172b/app/controllers/concerns/.keep -------------------------------------------------------------------------------- /app/mailers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alex35mil/isomorphic-comments-api/1cbd63133d58fc801db6c694ad9ffdd43215172b/app/mailers/.keep -------------------------------------------------------------------------------- /app/models/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alex35mil/isomorphic-comments-api/1cbd63133d58fc801db6c694ad9ffdd43215172b/app/models/.keep -------------------------------------------------------------------------------- /app/models/comment.rb: -------------------------------------------------------------------------------- 1 | # == Schema Information 2 | # 3 | # Table name: comments 4 | # 5 | # id :integer not null, primary key 6 | # author :string not null 7 | # comment :text not null 8 | # created_at :datetime not null 9 | # updated_at :datetime not null 10 | # 11 | 12 | class Comment < ActiveRecord::Base 13 | 14 | validates_presence_of :author, :comment 15 | 16 | end 17 | -------------------------------------------------------------------------------- /app/models/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alex35mil/isomorphic-comments-api/1cbd63133d58fc801db6c694ad9ffdd43215172b/app/models/concerns/.keep -------------------------------------------------------------------------------- /app/models/user.rb: -------------------------------------------------------------------------------- 1 | # == Schema Information 2 | # 3 | # Table name: users 4 | # 5 | # id :integer not null, primary key 6 | # email :string default(""), not null 7 | # encrypted_password :string default(""), not null 8 | # authentication_token :string default(""), not null 9 | # created_at :datetime not null 10 | # updated_at :datetime not null 11 | # 12 | 13 | class User < ActiveRecord::Base 14 | 15 | devise :database_authenticatable, :registerable, :validatable 16 | 17 | acts_as_token_authenticatable 18 | 19 | end 20 | -------------------------------------------------------------------------------- /app/serializers/comment_serializer.rb: -------------------------------------------------------------------------------- 1 | # == Schema Information 2 | # 3 | # Table name: comments 4 | # 5 | # id :integer not null, primary key 6 | # author :string not null 7 | # comment :text not null 8 | # created_at :datetime not null 9 | # updated_at :datetime not null 10 | # 11 | 12 | class CommentSerializer < ActiveModel::Serializer 13 | 14 | attributes :id, :author, :comment 15 | 16 | end 17 | -------------------------------------------------------------------------------- /app/serializers/user_serializer.rb: -------------------------------------------------------------------------------- 1 | # == Schema Information 2 | # 3 | # Table name: users 4 | # 5 | # id :integer not null, primary key 6 | # email :string default(""), not null 7 | # encrypted_password :string default(""), not null 8 | # authentication_token :string default(""), not null 9 | # created_at :datetime not null 10 | # updated_at :datetime not null 11 | # 12 | 13 | class UserSerializer < ActiveModel::Serializer 14 | 15 | attributes :id, :email, :authentication_token 16 | 17 | end 18 | -------------------------------------------------------------------------------- /bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) 3 | load Gem.bin_path('bundler', 'bundle') 4 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | APP_PATH = File.expand_path('../../config/application', __FILE__) 3 | require_relative '../config/boot' 4 | require 'rails/commands' 5 | -------------------------------------------------------------------------------- /bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require_relative '../config/boot' 3 | require 'rake' 4 | Rake.application.run 5 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'pathname' 3 | 4 | # path to your application root. 5 | APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) 6 | 7 | Dir.chdir APP_ROOT do 8 | # This script is a starting point to setup your application. 9 | # Add necessary setup steps to this file: 10 | 11 | puts "== Installing dependencies ==" 12 | system "gem install bundler --conservative" 13 | system "bundle check || bundle install" 14 | 15 | # puts "\n== Copying sample files ==" 16 | # unless File.exist?("config/database.yml") 17 | # system "cp config/database.yml.sample config/database.yml" 18 | # end 19 | 20 | puts "\n== Preparing database ==" 21 | system "bin/rake db:setup" 22 | 23 | puts "\n== Removing old logs and tempfiles ==" 24 | system "rm -f log/*" 25 | system "rm -rf tmp/cache" 26 | 27 | puts "\n== Restarting application server ==" 28 | system "touch tmp/restart.txt" 29 | end 30 | -------------------------------------------------------------------------------- /config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require ::File.expand_path('../config/environment', __FILE__) 4 | run Rails.application 5 | -------------------------------------------------------------------------------- /config/application.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path('../boot', __FILE__) 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 "action_controller/railtie" 9 | require "action_mailer/railtie" 10 | require "action_view/railtie" 11 | # require "sprockets/railtie" 12 | require "rails/test_unit/railtie" 13 | 14 | # Require the gems listed in Gemfile, including any gems 15 | # you've limited to :test, :development, or :production. 16 | Bundler.require(*Rails.groups) 17 | 18 | module IsomorphicCommentsApi 19 | class Application < Rails::Application 20 | 21 | config.middleware.use Rack::Deflater 22 | 23 | # Settings in config/environments/* take precedence over those specified here. 24 | # Application configuration should go into files in config/initializers 25 | # -- all .rb files in that directory are automatically loaded. 26 | 27 | # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. 28 | # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. 29 | # config.time_zone = 'Central Time (US & Canada)' 30 | 31 | # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. 32 | # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] 33 | # config.i18n.default_locale = :de 34 | 35 | # Do not swallow errors in after_commit/after_rollback callbacks. 36 | config.active_record.raise_in_transactional_callbacks = true 37 | end 38 | end 39 | -------------------------------------------------------------------------------- /config/boot.rb: -------------------------------------------------------------------------------- 1 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) 2 | 3 | require 'bundler/setup' # Set up gems listed in the Gemfile. 4 | -------------------------------------------------------------------------------- /config/database.yml: -------------------------------------------------------------------------------- 1 | default: &default 2 | adapter: postgresql 3 | encoding: unicode 4 | pool: 5 5 | host: localhost 6 | port: 5432 7 | 8 | development: 9 | <<: *default 10 | database: isomorphic_comments_api_dev 11 | 12 | test: 13 | <<: *default 14 | database: isomorphic_comments_api_test 15 | 16 | production: 17 | <<: *default 18 | -------------------------------------------------------------------------------- /config/deploy.rb: -------------------------------------------------------------------------------- 1 | $:.unshift './lib' 2 | 3 | require 'mina/bundler' 4 | require 'mina/rails' 5 | require 'mina/git' 6 | require 'mina/rvm' 7 | 8 | require 'mina/defaults' 9 | require 'mina/check' 10 | require 'mina/setup' 11 | require 'mina/env' 12 | require 'mina/nginx' 13 | require 'mina/unicorn' 14 | require 'mina/log' 15 | 16 | require 'mina/helpers/servers' 17 | require 'mina/helpers/checkers' 18 | require 'mina/helpers/print' 19 | require 'mina/helpers/render' 20 | 21 | require 'mina/docs/deploy' 22 | 23 | 24 | Dir['lib/mina/servers/*.rb'].each { |s| load s } 25 | 26 | 27 | set :app, 'isomorphic-comments' 28 | set :app_part, 'api' 29 | 30 | set :default_server, :production 31 | set :server, all_servers.include?(ARGV.first) ? ARGV.first : default_server 32 | 33 | invoke :"#{server}" 34 | invoke :set_defaults 35 | 36 | 37 | desc "Using the right Ruby." 38 | task :environment do 39 | invoke :"rvm:use[#{RUBY_VERSION}@#{app_rails}]" 40 | end 41 | 42 | 43 | desc "Deploys the current version to the server." 44 | task :deploy => :environment do 45 | deploy do 46 | 47 | invoke :'check:revision' 48 | invoke :'git:clone' 49 | invoke :'deploy:link_shared_paths' 50 | invoke :'bundle:install' 51 | invoke :'rails:db_migrate' 52 | invoke :'deploy:cleanup' 53 | 54 | to :launch do 55 | invoke :'unicorn:restart' 56 | end 57 | 58 | end 59 | end 60 | -------------------------------------------------------------------------------- /config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the Rails application. 2 | require File.expand_path('../application', __FILE__) 3 | 4 | # Initialize the Rails application. 5 | Rails.application.initialize! 6 | -------------------------------------------------------------------------------- /config/environment_variables.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alex35mil/isomorphic-comments-api/1cbd63133d58fc801db6c694ad9ffdd43215172b/config/environment_variables.yml -------------------------------------------------------------------------------- /config/environments/development.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # In the development environment your application's code is reloaded on 5 | # every request. This slows down response time but is perfect for development 6 | # since you don't have to restart the web server when you make code changes. 7 | config.cache_classes = false 8 | 9 | # Do not eager load code on boot. 10 | config.eager_load = false 11 | 12 | # Show full error reports and disable caching. 13 | config.consider_all_requests_local = true 14 | config.action_controller.perform_caching = false 15 | 16 | # Don't care if the mailer can't send. 17 | config.action_mailer.raise_delivery_errors = false 18 | 19 | # Print deprecation notices to the Rails logger. 20 | config.active_support.deprecation = :log 21 | 22 | # Raise an error on page load if there are pending migrations. 23 | config.active_record.migration_error = :page_load 24 | 25 | 26 | # Raises error for missing translations 27 | # config.action_view.raise_on_missing_translations = true 28 | end 29 | -------------------------------------------------------------------------------- /config/environments/production.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # Code is not reloaded between requests. 5 | config.cache_classes = true 6 | 7 | # Eager load code on boot. This eager loads most of Rails and 8 | # your application in memory, allowing both threaded web servers 9 | # and those relying on copy on write to perform better. 10 | # Rake tasks automatically ignore this option for performance. 11 | config.eager_load = true 12 | 13 | # Full error reports are disabled and caching is turned on. 14 | config.consider_all_requests_local = false 15 | config.action_controller.perform_caching = true 16 | 17 | # Enable Rack::Cache to put a simple HTTP cache in front of your application 18 | # Add `rack-cache` to your Gemfile before enabling this. 19 | # For large-scale production use, consider using a caching reverse proxy like 20 | # NGINX, varnish or squid. 21 | # config.action_dispatch.rack_cache = true 22 | 23 | # Disable serving static files from the `/public` folder by default since 24 | # Apache or NGINX already handles this. 25 | config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? 26 | 27 | 28 | # Specifies the header that your server uses for sending files. 29 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 30 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 31 | 32 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 33 | # config.force_ssl = true 34 | 35 | # Use the lowest log level to ensure availability of diagnostic information 36 | # when problems arise. 37 | config.log_level = :debug 38 | 39 | # Prepend all log lines with the following tags. 40 | # config.log_tags = [ :subdomain, :uuid ] 41 | 42 | # Use a different logger for distributed setups. 43 | # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) 44 | 45 | # Use a different cache store in production. 46 | # config.cache_store = :mem_cache_store 47 | 48 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 49 | # config.action_controller.asset_host = 'http://assets.example.com' 50 | 51 | # Ignore bad email addresses and do not raise email delivery errors. 52 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 53 | # config.action_mailer.raise_delivery_errors = false 54 | 55 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 56 | # the I18n.default_locale when a translation cannot be found). 57 | config.i18n.fallbacks = true 58 | 59 | # Send deprecation notices to registered listeners. 60 | config.active_support.deprecation = :notify 61 | 62 | # Use default logging formatter so that PID and timestamp are not suppressed. 63 | config.log_formatter = ::Logger::Formatter.new 64 | 65 | # Do not dump schema after migrations. 66 | config.active_record.dump_schema_after_migration = false 67 | end 68 | -------------------------------------------------------------------------------- /config/environments/test.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # The test environment is used exclusively to run your application's 5 | # test suite. You never need to work with it otherwise. Remember that 6 | # your test database is "scratch space" for the test suite and is wiped 7 | # and recreated between test runs. Don't rely on the data there! 8 | config.cache_classes = true 9 | 10 | # Do not eager load code on boot. This avoids loading your whole application 11 | # just for the purpose of running a single test. If you are using a tool that 12 | # preloads Rails for running tests, you may have to set it to true. 13 | config.eager_load = false 14 | 15 | # Configure static file server for tests with Cache-Control for performance. 16 | config.serve_static_files = true 17 | config.static_cache_control = 'public, max-age=3600' 18 | 19 | # Show full error reports and disable caching. 20 | config.consider_all_requests_local = true 21 | config.action_controller.perform_caching = false 22 | 23 | # Raise exceptions instead of rendering exception templates. 24 | config.action_dispatch.show_exceptions = false 25 | 26 | # Disable request forgery protection in test environment. 27 | config.action_controller.allow_forgery_protection = false 28 | 29 | # Tell Action Mailer not to deliver emails to the real world. 30 | # The :test delivery method accumulates sent emails in the 31 | # ActionMailer::Base.deliveries array. 32 | config.action_mailer.delivery_method = :test 33 | 34 | # Randomize the order test cases are executed. 35 | config.active_support.test_order = :random 36 | 37 | # Print deprecation notices to the stderr. 38 | config.active_support.deprecation = :stderr 39 | 40 | # Raises error for missing translations 41 | # config.action_view.raise_on_missing_translations = true 42 | end 43 | -------------------------------------------------------------------------------- /config/initializers/!environment_variables.rb: -------------------------------------------------------------------------------- 1 | require 'yaml' 2 | 3 | module EnvironmentVariablesInit 4 | class Application < Rails::Application 5 | config.before_configuration do 6 | env_file = Rails.root.join('config', 'environment_variables.yml').to_s 7 | 8 | if File.exists?(env_file) && YAML.load_file(env_file) 9 | YAML.load_file(env_file)[Rails.env].each do |key, value| 10 | ENV[key.to_s] = value 11 | end 12 | end 13 | end 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /config/initializers/devise.rb: -------------------------------------------------------------------------------- 1 | # Use this hook to configure devise mailer, warden hooks and so forth. 2 | # Many of these configuration options can be set straight in your model. 3 | Devise.setup do |config| 4 | 5 | config.secret_key = ENV['DEVISE_SECRET_KEY'] if Rails.env.production? 6 | 7 | # The secret key used by Devise. Devise uses this key to generate 8 | # random tokens. Changing this key will render invalid all existing 9 | # confirmation, reset password and unlock tokens in the database. 10 | # Devise will use the `secret_key_base` on Rails 4+ applications as its `secret_key` 11 | # by default. You can change it below and use your own secret key. 12 | # config.secret_key = '56382ecc5c4d7236f290e5e2ed8335ef7759314f0cd7ab138cc1b9addc498b073492a13caa9593f24b2b82acbc5a3ca39f7fc92638ecdd44043809c8b69cfae5' 13 | 14 | # ==> Mailer Configuration 15 | # Configure the e-mail address which will be shown in Devise::Mailer, 16 | # note that it will be overwritten if you use your own mailer class 17 | # with default "from" parameter. 18 | config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' 19 | 20 | # Configure the class responsible to send e-mails. 21 | # config.mailer = 'Devise::Mailer' 22 | 23 | # ==> ORM configuration 24 | # Load and configure the ORM. Supports :active_record (default) and 25 | # :mongoid (bson_ext recommended) by default. Other ORMs may be 26 | # available as additional gems. 27 | require 'devise/orm/active_record' 28 | 29 | # ==> Configuration for any authentication mechanism 30 | # Configure which keys are used when authenticating a user. The default is 31 | # just :email. You can configure it to use [:username, :subdomain], so for 32 | # authenticating a user, both parameters are required. Remember that those 33 | # parameters are used only when authenticating and not when retrieving from 34 | # session. If you need permissions, you should implement that in a before filter. 35 | # You can also supply a hash where the value is a boolean determining whether 36 | # or not authentication should be aborted when the value is not present. 37 | # config.authentication_keys = [:email] 38 | 39 | # Configure parameters from the request object used for authentication. Each entry 40 | # given should be a request method and it will automatically be passed to the 41 | # find_for_authentication method and considered in your model lookup. For instance, 42 | # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. 43 | # The same considerations mentioned for authentication_keys also apply to request_keys. 44 | # config.request_keys = [] 45 | 46 | # Configure which authentication keys should be case-insensitive. 47 | # These keys will be downcased upon creating or modifying a user and when used 48 | # to authenticate or find a user. Default is :email. 49 | config.case_insensitive_keys = [:email] 50 | 51 | # Configure which authentication keys should have whitespace stripped. 52 | # These keys will have whitespace before and after removed upon creating or 53 | # modifying a user and when used to authenticate or find a user. Default is :email. 54 | config.strip_whitespace_keys = [:email] 55 | 56 | # Tell if authentication through request.params is enabled. True by default. 57 | # It can be set to an array that will enable params authentication only for the 58 | # given strategies, for example, `config.params_authenticatable = [:database]` will 59 | # enable it only for database (email + password) authentication. 60 | # config.params_authenticatable = true 61 | 62 | # Tell if authentication through HTTP Auth is enabled. False by default. 63 | # It can be set to an array that will enable http authentication only for the 64 | # given strategies, for example, `config.http_authenticatable = [:database]` will 65 | # enable it only for database authentication. The supported strategies are: 66 | # :database = Support basic authentication with authentication key + password 67 | # config.http_authenticatable = false 68 | 69 | # If 401 status code should be returned for AJAX requests. True by default. 70 | # config.http_authenticatable_on_xhr = true 71 | 72 | # The realm used in Http Basic Authentication. 'Application' by default. 73 | # config.http_authentication_realm = 'Application' 74 | 75 | # It will change confirmation, password recovery and other workflows 76 | # to behave the same regardless if the e-mail provided was right or wrong. 77 | # Does not affect registerable. 78 | # config.paranoid = true 79 | 80 | # By default Devise will store the user in session. You can skip storage for 81 | # particular strategies by setting this option. 82 | # Notice that if you are skipping storage for all authentication paths, you 83 | # may want to disable generating routes to Devise's sessions controller by 84 | # passing skip: :sessions to `devise_for` in your config/routes.rb 85 | config.skip_session_storage = [:http_auth] 86 | 87 | # By default, Devise cleans up the CSRF token on authentication to 88 | # avoid CSRF token fixation attacks. This means that, when using AJAX 89 | # requests for sign in and sign up, you need to get a new CSRF token 90 | # from the server. You can disable this option at your own risk. 91 | # config.clean_up_csrf_token_on_authentication = true 92 | 93 | # ==> Configuration for :database_authenticatable 94 | # For bcrypt, this is the cost for hashing the password and defaults to 10. If 95 | # using other encryptors, it sets how many times you want the password re-encrypted. 96 | # 97 | # Limiting the stretches to just one in testing will increase the performance of 98 | # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use 99 | # a value less than 10 in other environments. Note that, for bcrypt (the default 100 | # encryptor), the cost increases exponentially with the number of stretches (e.g. 101 | # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). 102 | config.stretches = Rails.env.test? ? 1 : 10 103 | 104 | # Setup a pepper to generate the encrypted password. 105 | # config.pepper = '6bf2bc4504a2a8e6531ea7ca7c77e9b441a9dd21646cb069bfdb318e9ef29d4a2425bdd1a8b8247e7e3e1d28815442fa9b4ea96d47dff2347deb417e7ce6a9af' 106 | 107 | # ==> Configuration for :confirmable 108 | # A period that the user is allowed to access the website even without 109 | # confirming their account. For instance, if set to 2.days, the user will be 110 | # able to access the website for two days without confirming their account, 111 | # access will be blocked just in the third day. Default is 0.days, meaning 112 | # the user cannot access the website without confirming their account. 113 | # config.allow_unconfirmed_access_for = 2.days 114 | 115 | # A period that the user is allowed to confirm their account before their 116 | # token becomes invalid. For example, if set to 3.days, the user can confirm 117 | # their account within 3 days after the mail was sent, but on the fourth day 118 | # their account can't be confirmed with the token any more. 119 | # Default is nil, meaning there is no restriction on how long a user can take 120 | # before confirming their account. 121 | # config.confirm_within = 3.days 122 | 123 | # If true, requires any email changes to be confirmed (exactly the same way as 124 | # initial account confirmation) to be applied. Requires additional unconfirmed_email 125 | # db field (see migrations). Until confirmed, new email is stored in 126 | # unconfirmed_email column, and copied to email column on successful confirmation. 127 | config.reconfirmable = true 128 | 129 | # Defines which key will be used when confirming an account 130 | # config.confirmation_keys = [:email] 131 | 132 | # ==> Configuration for :rememberable 133 | # The time the user will be remembered without asking for credentials again. 134 | # config.remember_for = 2.weeks 135 | 136 | # Invalidates all the remember me tokens when the user signs out. 137 | config.expire_all_remember_me_on_sign_out = true 138 | 139 | # If true, extends the user's remember period when remembered via cookie. 140 | # config.extend_remember_period = false 141 | 142 | # Options to be passed to the created cookie. For instance, you can set 143 | # secure: true in order to force SSL only cookies. 144 | # config.rememberable_options = {} 145 | 146 | # ==> Configuration for :validatable 147 | # Range for password length. 148 | config.password_length = 8..72 149 | 150 | # Email regex used to validate email formats. It simply asserts that 151 | # one (and only one) @ exists in the given string. This is mainly 152 | # to give user feedback and not to assert the e-mail validity. 153 | # config.email_regexp = /\A[^@]+@[^@]+\z/ 154 | 155 | # ==> Configuration for :timeoutable 156 | # The time you want to timeout the user session without activity. After this 157 | # time the user will be asked for credentials again. Default is 30 minutes. 158 | # config.timeout_in = 30.minutes 159 | 160 | # If true, expires auth token on session timeout. 161 | # config.expire_auth_token_on_timeout = false 162 | 163 | # ==> Configuration for :lockable 164 | # Defines which strategy will be used to lock an account. 165 | # :failed_attempts = Locks an account after a number of failed attempts to sign in. 166 | # :none = No lock strategy. You should handle locking by yourself. 167 | # config.lock_strategy = :failed_attempts 168 | 169 | # Defines which key will be used when locking and unlocking an account 170 | # config.unlock_keys = [:email] 171 | 172 | # Defines which strategy will be used to unlock an account. 173 | # :email = Sends an unlock link to the user email 174 | # :time = Re-enables login after a certain amount of time (see :unlock_in below) 175 | # :both = Enables both strategies 176 | # :none = No unlock strategy. You should handle unlocking by yourself. 177 | # config.unlock_strategy = :both 178 | 179 | # Number of authentication tries before locking an account if lock_strategy 180 | # is failed attempts. 181 | # config.maximum_attempts = 20 182 | 183 | # Time interval to unlock the account if :time is enabled as unlock_strategy. 184 | # config.unlock_in = 1.hour 185 | 186 | # Warn on the last attempt before the account is locked. 187 | # config.last_attempt_warning = true 188 | 189 | # ==> Configuration for :recoverable 190 | # 191 | # Defines which key will be used when recovering the password for an account 192 | # config.reset_password_keys = [:email] 193 | 194 | # Time interval you can reset your password with a reset password key. 195 | # Don't put a too small interval or your users won't have the time to 196 | # change their passwords. 197 | config.reset_password_within = 6.hours 198 | 199 | # When set to false, does not sign a user in automatically after their password is 200 | # reset. Defaults to true, so a user is signed in automatically after a reset. 201 | # config.sign_in_after_reset_password = true 202 | 203 | # ==> Configuration for :encryptable 204 | # Allow you to use another encryption algorithm besides bcrypt (default). You can use 205 | # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1, 206 | # :authlogic_sha512 (then you should set stretches above to 20 for default behavior) 207 | # and :restful_authentication_sha1 (then you should set stretches to 10, and copy 208 | # REST_AUTH_SITE_KEY to pepper). 209 | # 210 | # Require the `devise-encryptable` gem when using anything other than bcrypt 211 | # config.encryptor = :sha512 212 | 213 | # ==> Scopes configuration 214 | # Turn scoped views on. Before rendering "sessions/new", it will first check for 215 | # "users/sessions/new". It's turned off by default because it's slower if you 216 | # are using only default views. 217 | # config.scoped_views = false 218 | 219 | # Configure the default scope given to Warden. By default it's the first 220 | # devise role declared in your routes (usually :user). 221 | # config.default_scope = :user 222 | 223 | # Set this configuration to false if you want /users/sign_out to sign out 224 | # only the current scope. By default, Devise signs out all scopes. 225 | # config.sign_out_all_scopes = true 226 | 227 | # ==> Navigation configuration 228 | # Lists the formats that should be treated as navigational. Formats like 229 | # :html, should redirect to the sign in page when the user does not have 230 | # access, but formats like :xml or :json, should return 401. 231 | # 232 | # If you have any extra navigational formats, like :iphone or :mobile, you 233 | # should add them to the navigational formats lists. 234 | # 235 | # The "*/*" below is required to match Internet Explorer requests. 236 | # config.navigational_formats = ['*/*', :html] 237 | 238 | # The default HTTP method used to sign out a resource. Default is :delete. 239 | config.sign_out_via = :delete 240 | 241 | # ==> OmniAuth 242 | # Add a new OmniAuth provider. Check the wiki for more information on setting 243 | # up on your models and hooks. 244 | # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' 245 | 246 | # ==> Warden configuration 247 | # If you want to use other strategies, that are not supported by Devise, or 248 | # change the failure app, you can configure them inside the config.warden block. 249 | # 250 | # config.warden do |manager| 251 | # manager.intercept_401 = false 252 | # manager.default_strategies(scope: :user).unshift :some_external_strategy 253 | # end 254 | 255 | # ==> Mountable engine configurations 256 | # When using Devise inside an engine, let's call it `MyEngine`, and this engine 257 | # is mountable, there are some extra configurations to be taken into account. 258 | # The following options are available, assuming the engine is mounted as: 259 | # 260 | # mount MyEngine, at: '/my_engine' 261 | # 262 | # The router that invoked `devise_for`, in the example above, would be: 263 | # config.router_name = :my_engine 264 | # 265 | # When using OmniAuth, Devise cannot automatically set OmniAuth path, 266 | # so you need to do it manually. For the users scope, it would be: 267 | # config.omniauth_path_prefix = '/my_engine/users/auth' 268 | end 269 | -------------------------------------------------------------------------------- /config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Configure sensitive parameters which will be filtered from the log file. 4 | Rails.application.config.filter_parameters += [:password] 5 | -------------------------------------------------------------------------------- /config/initializers/secret_token.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Your secret key for verifying the integrity of signed cookies. 4 | # If you change this key, all old signed cookies will become invalid! 5 | 6 | # Make sure the secret is at least 30 characters and all random, 7 | # no regular words or you'll be exposed to dictionary attacks. 8 | # You can use `rake secret` to generate a secure secret key. 9 | 10 | # Make sure your secret_key_base is kept private 11 | # if you're sharing your code publicly. 12 | 13 | # Although this is not needed for an api-only application, rails4 14 | # requires secret_key_base or secret_token to be defined, otherwise an 15 | # error is raised. 16 | # Using secret_token for rails3 compatibility. Change to secret_key_base 17 | # to avoid deprecation warning. 18 | # Can be safely removed in a rails3 api-only application. 19 | IsomorphicCommentsApi::Application.config.secret_token = '3332b1906998854ac437484b4efaaaae0974158d6f422c677f707a3260968cfd5a88830d67fc04130ae7684594d2cf652726c2bd481d4a75ed77c7f2ee72b157' 20 | -------------------------------------------------------------------------------- /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 4 | 5 | # Enable parameter wrapping for JSON. 6 | # ActiveSupport.on_load(:action_controller) do 7 | # wrap_parameters format: [:json] if respond_to?(:wrap_parameters) 8 | # end 9 | 10 | # To enable root element in JSON for ActiveRecord objects. 11 | # ActiveSupport.on_load(:active_record) do 12 | # self.include_root_in_json = true 13 | # end 14 | -------------------------------------------------------------------------------- /config/locales/devise.en.yml: -------------------------------------------------------------------------------- 1 | # Additional translations at https://github.com/plataformatec/devise/wiki/I18n 2 | 3 | en: 4 | devise: 5 | confirmations: 6 | confirmed: "Your email address has been successfully confirmed." 7 | send_instructions: "You will receive an email with instructions for how to confirm your email address in a few minutes." 8 | send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes." 9 | failure: 10 | already_authenticated: "You are already signed in." 11 | inactive: "Your account is not activated yet." 12 | invalid: "Invalid %{authentication_keys} or password." 13 | locked: "Your account is locked." 14 | last_attempt: "You have one more attempt before your account is locked." 15 | not_found_in_database: "Invalid %{authentication_keys} or password." 16 | timeout: "Your session expired. Please sign in again to continue." 17 | unauthenticated: "You need to sign in or sign up before continuing." 18 | unconfirmed: "You have to confirm your email address before continuing." 19 | mailer: 20 | confirmation_instructions: 21 | subject: "Confirmation instructions" 22 | reset_password_instructions: 23 | subject: "Reset password instructions" 24 | unlock_instructions: 25 | subject: "Unlock instructions" 26 | omniauth_callbacks: 27 | failure: "Could not authenticate you from %{kind} because \"%{reason}\"." 28 | success: "Successfully authenticated from %{kind} account." 29 | passwords: 30 | no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided." 31 | send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes." 32 | send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." 33 | updated: "Your password has been changed successfully. You are now signed in." 34 | updated_not_active: "Your password has been changed successfully." 35 | registrations: 36 | destroyed: "Bye! Your account has been successfully cancelled. We hope to see you again soon." 37 | signed_up: "Welcome! You have signed up successfully." 38 | signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated." 39 | signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked." 40 | signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please follow the link to activate your account." 41 | update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and follow the confirm link to confirm your new email address." 42 | updated: "Your account has been updated successfully." 43 | sessions: 44 | signed_in: "Signed in successfully." 45 | signed_out: "Signed out successfully." 46 | already_signed_out: "Signed out successfully." 47 | unlocks: 48 | send_instructions: "You will receive an email with instructions for how to unlock your account in a few minutes." 49 | send_paranoid_instructions: "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes." 50 | unlocked: "Your account has been unlocked successfully. Please sign in to continue." 51 | errors: 52 | messages: 53 | already_confirmed: "was already confirmed, please try signing in" 54 | confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" 55 | expired: "has expired, please request a new one" 56 | not_found: "not found" 57 | not_locked: "was not locked" 58 | not_saved: 59 | one: "1 error prohibited this %{resource} from being saved:" 60 | other: "%{count} errors prohibited this %{resource} from being saved:" 61 | -------------------------------------------------------------------------------- /config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Files in the config/locales directory are used for internationalization 2 | # and are automatically loaded by Rails. If you want to use locales other 3 | # than English, add the necessary files in this directory. 4 | # 5 | # To use the locales, use `I18n.t`: 6 | # 7 | # I18n.t 'hello' 8 | # 9 | # In views, this is aliased to just `t`: 10 | # 11 | # <%= t('hello') %> 12 | # 13 | # To use a different locale, set it with `I18n.locale`: 14 | # 15 | # I18n.locale = :es 16 | # 17 | # This would use the information in config/locales/es.yml. 18 | # 19 | # To learn more, please read the Rails Internationalization guide 20 | # available at http://guides.rubyonrails.org/i18n.html. 21 | 22 | en: 23 | hello: "Hello world" 24 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | require 'api_constraints' 2 | require 'subdomain_constraints' 3 | 4 | Rails.application.routes.draw do 5 | 6 | get '/auth/preflight', to: 'application#auth_preflight' 7 | 8 | # with subdomain (not sub-sub domain) just use `constraints: { subdomain: 'api' }` 9 | namespace :api, defaults: { format: :json }, constraints: SubdomainConstraints.new(subdomain: 'api'), path: '/' do 10 | 11 | scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do 12 | 13 | devise_for :users, skip: :all 14 | devise_scope :api_user do 15 | # post '/signup', to: 'registrations#create' 16 | post '/login', to: 'sessions#create' 17 | delete '/logout', to: 'sessions#destroy' 18 | end 19 | 20 | resources :comments, only: [:index, :show, :create, :destroy] 21 | 22 | end 23 | 24 | end 25 | 26 | end 27 | -------------------------------------------------------------------------------- /config/secrets.yml: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Your secret key is used for verifying the integrity of signed cookies. 4 | # If you change this key, all old signed cookies will become invalid! 5 | 6 | # Make sure the secret is at least 30 characters and all random, 7 | # no regular words or you'll be exposed to dictionary attacks. 8 | # You can use `rake secret` to generate a secure secret key. 9 | 10 | # Make sure the secrets in this file are kept private 11 | # if you're sharing your code publicly. 12 | 13 | development: 14 | secret_key_base: 7c40b6c65835adbe7bda873296de11b7cd8da91f74b7e27daa3e1580ab23bdcc4877a2f0983431e39fb66116f34042981ee74dbec180a2c0d0f84f1cc8acf2ae 15 | 16 | test: 17 | secret_key_base: d01767079b50fea383c8d9de3edca4fed2f98f9fc933f6718d35cd22a644cff3ab429a95ed2aa9abf08d8dc1705f1c96fe481f56a665e20ce12ef85861ff8ae1 18 | 19 | # Do not keep production secrets in the repository, 20 | # instead read values from the environment. 21 | production: 22 | secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> 23 | -------------------------------------------------------------------------------- /db/migrate/20150719225954_devise_create_users.rb: -------------------------------------------------------------------------------- 1 | class DeviseCreateUsers < ActiveRecord::Migration 2 | def change 3 | create_table(:users) do |t| 4 | 5 | ## Database authenticatable 6 | t.string :email, null: false, default: '' 7 | t.string :encrypted_password, null: false, default: '' 8 | t.string :authentication_token, null: false, default: '' 9 | 10 | 11 | ## Recoverable 12 | # t.string :reset_password_token 13 | # t.datetime :reset_password_sent_at 14 | 15 | ## Rememberable 16 | # t.datetime :remember_created_at 17 | 18 | ## Trackable 19 | # t.integer :sign_in_count, default: 0, null: false 20 | # t.datetime :current_sign_in_at 21 | # t.datetime :last_sign_in_at 22 | # t.inet :current_sign_in_ip 23 | # t.inet :last_sign_in_ip 24 | 25 | ## Confirmable 26 | # t.string :confirmation_token 27 | # t.datetime :confirmed_at 28 | # t.datetime :confirmation_sent_at 29 | # t.string :unconfirmed_email # Only if using reconfirmable 30 | 31 | ## Lockable 32 | # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts 33 | # t.string :unlock_token # Only if unlock strategy is :email or :both 34 | # t.datetime :locked_at 35 | 36 | 37 | t.timestamps null: false 38 | end 39 | 40 | add_index :users, :email, unique: true 41 | add_index :users, :authentication_token, unique: true 42 | 43 | # add_index :users, :confirmation_token, unique: true 44 | # add_index :users, :unlock_token, unique: true 45 | # add_index :users, :reset_password_token, unique: true 46 | 47 | end 48 | end 49 | -------------------------------------------------------------------------------- /db/migrate/20150720105123_create_comments.rb: -------------------------------------------------------------------------------- 1 | class CreateComments < ActiveRecord::Migration 2 | def change 3 | create_table :comments do |t| 4 | t.string :author, null: false 5 | t.text :comment, null: false 6 | 7 | t.timestamps null: false 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /db/schema.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # This file is auto-generated from the current state of the database. Instead 3 | # of editing this file, please use the migrations feature of Active Record to 4 | # incrementally modify your database, and then regenerate this schema definition. 5 | # 6 | # Note that this schema.rb definition is the authoritative source for your 7 | # database schema. If you need to create the application database on another 8 | # system, you should be using db:schema:load, not running all the migrations 9 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 10 | # you'll amass, the slower it'll run and the greater likelihood for issues). 11 | # 12 | # It's strongly recommended that you check this file into your version control system. 13 | 14 | ActiveRecord::Schema.define(version: 20150720105123) do 15 | 16 | # These are extensions that must be enabled in order to support this database 17 | enable_extension "plpgsql" 18 | 19 | create_table "comments", force: :cascade do |t| 20 | t.string "author", null: false 21 | t.text "comment", null: false 22 | t.datetime "created_at", null: false 23 | t.datetime "updated_at", null: false 24 | end 25 | 26 | create_table "users", force: :cascade do |t| 27 | t.string "email", default: "", null: false 28 | t.string "encrypted_password", default: "", null: false 29 | t.string "authentication_token", default: "", null: false 30 | t.datetime "created_at", null: false 31 | t.datetime "updated_at", null: false 32 | end 33 | 34 | add_index "users", ["authentication_token"], name: "index_users_on_authentication_token", unique: true, using: :btree 35 | add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree 36 | 37 | end 38 | -------------------------------------------------------------------------------- /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 rake db:seed (or created alongside the db with db:setup). 3 | # 4 | # Examples: 5 | # 6 | # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) 7 | # Mayor.create(name: 'Emanuel', city: cities.first) 8 | 9 | User.create(email: 'demo@demo.me', password: 'demopass') 10 | 11 | Comment.create([ 12 | { author: 'Alex', comment: 'Yay! It works!' }, 13 | { author: 'Guest', comment: 'True! Isomorphic awesomeness!' } 14 | ]) 15 | -------------------------------------------------------------------------------- /lib/api_constraints.rb: -------------------------------------------------------------------------------- 1 | class ApiConstraints 2 | 3 | def initialize(options) 4 | @version = options[:version] 5 | @default = options[:default] 6 | end 7 | 8 | def matches?(req) 9 | @default || req.headers['Accept'].include?("application/vnd.isomorphic-comments.v#{@version}+json") 10 | end 11 | 12 | end 13 | -------------------------------------------------------------------------------- /lib/assets/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alex35mil/isomorphic-comments-api/1cbd63133d58fc801db6c694ad9ffdd43215172b/lib/assets/.keep -------------------------------------------------------------------------------- /lib/mina/check.rb: -------------------------------------------------------------------------------- 1 | namespace :check do 2 | 3 | task :access do 4 | 5 | print_start %[Checking access to project dir on #{server} server...] 6 | 7 | if check("[ -w #{deploy_to} ]") 8 | print_success %[#{app_rails} is writable on #{server} server] 9 | else 10 | print_fail %[#{app_rails} is not writable or doesn't even exist on #{server} server] 11 | print_str %[Do the following on remote:] 12 | print_command %[sudo mkdir -p #{deploy_to}] 13 | print_command %[sudo chmod 755 /home/#{user}/apps] 14 | print_command %[sudo chown -R #{user}:sudo /home/#{user}/apps/#{app_server_name}] 15 | print_command %[sudo chown -R #{user}:sudo #{deploy_to}] 16 | die 17 | end 18 | 19 | end 20 | 21 | 22 | task :revision do 23 | 24 | unless `git rev-parse HEAD` == `git rev-parse origin/#{branch}` 25 | 26 | print_error "WARNING: HEAD is not the same as origin/#{branch}" 27 | print_stdout "Run `git push` to sync changes or make sure you've" 28 | print_stdout "checked out the branch: #{branch} as you can only deploy" 29 | print_stdout "if you've got the target branch checked out" 30 | die 31 | 32 | end 33 | 34 | end 35 | 36 | 37 | end -------------------------------------------------------------------------------- /lib/mina/defaults.rb: -------------------------------------------------------------------------------- 1 | task :set_defaults do 2 | 3 | set_default :app_rails, "#{app}-#{app_part}" 4 | set_default :keep_releases, 5 5 | set_default :forward_agent, true 6 | 7 | set_default :repository, 'git@github.com:alexfedoseev/isomorphic-comments-api.git' 8 | set_default :branch, 'master' 9 | 10 | set_default :user, 'deployer' 11 | set_default :group, 'deployer' 12 | set_default :deploy_to, "/home/#{user}/apps/#{app_server_name}/#{app_rails}" 13 | set_default :shared_paths, ['config/database.yml', 'config/environment_variables.yml', 'tmp', 'log'] 14 | set_default :term_mode, :system # `sudo` don't like :pretty 15 | set_default :rails_env, :production 16 | set_default :enable_ssl, false 17 | 18 | set_default :current_release, "#{deploy_to}/current" 19 | set_default :config_path, "#{deploy_to}/#{shared_path}/config" 20 | set_default :logs_path, "#{deploy_to}/#{shared_path}/log" 21 | set_default :sockets_path, "#{deploy_to}/#{shared_path}/tmp/sockets" 22 | set_default :pids_path, "#{deploy_to}/#{shared_path}/tmp/pids" 23 | 24 | set_default :erb_templates, 'lib/mina/templates' 25 | set_default :configs_tmp_path, 'tmp/deploy_configs' 26 | 27 | set_default :unicorn_workers, 3 28 | set_default :unicorn_timeout, 30 29 | set_default :unicorn_symlink, "unicorn_#{app_sys_id!}" 30 | set_default :unicorn_script, "/etc/init.d/#{unicorn_symlink}" 31 | 32 | set_default :nginx_port, 80 33 | set_default :nginx_config, "/etc/nginx/sites-enabled/#{app_sys_id!}" 34 | set_default :nginx_log, "/var/log/nginx/#{app_sys_id!}.log" 35 | set_default :nginx_error_log, "/var/log/nginx/#{app_sys_id!}.error.log" 36 | 37 | set_default :logrotate_path, "/etc/logrotate.d/#{app_sys_id!}_rails" 38 | 39 | end -------------------------------------------------------------------------------- /lib/mina/docs/.keeper: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alex35mil/isomorphic-comments-api/1cbd63133d58fc801db6c694ad9ffdd43215172b/lib/mina/docs/.keeper -------------------------------------------------------------------------------- /lib/mina/docs/deploy.rb: -------------------------------------------------------------------------------- 1 | namespace :docs do 2 | 3 | task :responses do 4 | print_stdout %[200 :ok] 5 | print_stdout %[201 :created] 6 | print_stdout %[204 :no_content] 7 | print_stdout %[401 :unauthorized] 8 | print_stdout %[403 :forbidden] 9 | print_stdout %[404 :not_found] 10 | print_stdout %[422 :unprocessable_entity] 11 | print_stdout %[500 :internal_server_error] 12 | print_stdout %[502 :bad_gateway] 13 | print_stdout %[503 :service_unavailable] 14 | end 15 | 16 | task :deploy do 17 | 18 | print_title %[Add items to sudoers on #{server} server], 'remote' 19 | print_command %[sudo visudo] 20 | print_stdout %[] 21 | print_stdout %[# Common] 22 | print_stdout %[deployer ALL=(ALL) NOPASSWD:/bin/ln -nfs /home/#{user}/* /etc/nginx/sites-enabled/*] 23 | print_stdout %[deployer ALL=(ALL) NOPASSWD:/bin/ln -nfs /home/#{user}/* /etc/init.d/*] 24 | print_stdout %[deployer ALL=(ALL) NOPASSWD:/bin/ln -nfs /home/#{user}/* /etc/logrotate.d/*] 25 | print_stdout %[deployer ALL=(ALL) NOPASSWD:/bin/ln -nfs /home/#{user}/* /etc/systemd/system/*] 26 | print_stdout %[deployer ALL=(ALL) NOPASSWD:/bin/ln -nfs /home/#{user}/* /etc/init/*] 27 | print_stdout %[deployer ALL=(ALL) NOPASSWD:/usr/bin/tail /var/log/*] 28 | print_stdout %[deployer ALL=(ALL) NOPASSWD:/bin/rm /etc/nginx/sites-enabled/default] 29 | print_stdout %[deployer ALL=(ALL) NOPASSWD:/etc/init.d/nginx reload] 30 | print_stdout %[deployer ALL=(ALL) NOPASSWD:/etc/sbin/service nginx reload] 31 | print_stdout %[deployer ALL=(ALL) NOPASSWD:/sbin/initctl reload-configuration] 32 | print_stdout %[deployer ALL=(ALL) NOPASSWD:/usr/bin/systemctl daemon-reload] 33 | print_stdout %[] 34 | print_stdout %[# #{app_sys_id}] 35 | print_stdout %[deployer ALL=(ALL) NOPASSWD:/usr/sbin/update-rc.d #{unicorn_symlink} defaults] 36 | print_stdout %[deployer ALL=(ALL) NOPASSWD:/etc/init.d/#{unicorn_symlink} restart] 37 | print_stdout %[deployer ALL=(ALL) NOPASSWD:/usr/sbin/service #{unicorn_symlink} restart] 38 | 39 | print_title %[Create project dirs on #{server} server], 'remote' 40 | print_command %[sudo mkdir -p #{deploy_to}] 41 | print_command %[sudo chmod 755 /home/#{user}/apps] 42 | print_command %[sudo chown -R #{user}:sudo /home/#{user}/apps/#{app_server_name}] 43 | print_command %[sudo chown -R #{user}:sudo #{deploy_to}] 44 | 45 | print_title %[Check access to project dir on #{server} server], 'local' 46 | print_command %[mina check:access] 47 | 48 | print_title %[Setup project dir on #{server} server], 'local' 49 | print_command %[mina setup] 50 | 51 | print_title %[Setup environment configs on #{server} server], 'local' 52 | print_command %[mina env:setup] 53 | 54 | print_title %[Setup database on #{server} server], 'remote' 55 | print_command %[sudo -u postgres psql] 56 | print_command %[create user #{app_server_name.gsub('-', '_')} with password 'PASSWORD_GOES_HERE';] 57 | print_command %[create database #{app_server_name.gsub('-', '_')} owner #{app_server_name.gsub('-', '_')};] 58 | print_command %[\\q] 59 | 60 | print_title %[Edit `database.yml` on #{server} server], 'remote' 61 | print_command %[nano #{config_path}/database.example.yml] 62 | print_stdout %[# And save it as `database.yml`] 63 | 64 | print_title %[Deploy app on #{server} server], 'local' 65 | print_command %[mina deploy] 66 | 67 | print_title %[Everytime you update configs for #{server} server], 'local' 68 | print_command %[mina env:update] 69 | print_command %[mina env:update only=nginx] 70 | print_command %[mina env:update only=unicorn] 71 | 72 | print_str %[] 73 | 74 | end 75 | 76 | end 77 | -------------------------------------------------------------------------------- /lib/mina/env.rb: -------------------------------------------------------------------------------- 1 | require 'fileutils' 2 | 3 | set(:config_files, %w( 4 | nginx.conf 5 | database.example.yml 6 | environment_variables.example.yml 7 | unicorn.rb 8 | unicorn_init.sh 9 | logrotate 10 | )) 11 | 12 | set(:executable_config_files, %w( 13 | unicorn_init.sh 14 | )) 15 | 16 | set(:symlinks, [ 17 | { 18 | source: 'nginx.conf', 19 | link: '{{nginx_config}}' 20 | }, 21 | { 22 | source: 'unicorn_init.sh', 23 | link: '{{unicorn_script}}' 24 | }, 25 | { 26 | source: 'logrotate', 27 | link: '{{logrotate_path}}' 28 | }, 29 | ] 30 | ) 31 | 32 | namespace :env do 33 | 34 | task :setup => ['configs:render', 'configs:upload', 'configs:cleanup'] do 35 | 36 | invoke :'configs:chmod_x' 37 | invoke :'configs:symlink' 38 | invoke :'configs:autoload' 39 | invoke :'nginx:reload' 40 | invoke :'nginx:remove_default_vhost' 41 | 42 | print_status 'Done.' 43 | 44 | end 45 | 46 | task :update => ['configs:render', 'configs:upload', 'configs:cleanup'] do 47 | 48 | if ENV['only'] == 'nginx' 49 | invoke :'nginx:reload' 50 | elsif ENV['only'] == 'unicorn' 51 | invoke :'unicorn:restart' 52 | else 53 | invoke :'nginx:reload' 54 | invoke :'unicorn:restart' 55 | end 56 | print_status 'Done.' 57 | 58 | end 59 | 60 | end 61 | 62 | 63 | namespace :configs do 64 | 65 | task :render do 66 | print_status %[Rendering configs locally...] 67 | config_files.each do |file| 68 | render_config file 69 | end 70 | end 71 | 72 | task :upload do 73 | print_status %[Uploading configs to #{server} server...] 74 | %x[scp -r #{configs_tmp_path}/. #{user}@#{domain}:#{config_path}] 75 | end 76 | 77 | task :cleanup do 78 | print_status %[Cleaning up...] 79 | FileUtils.rm_r configs_tmp_path 80 | end 81 | 82 | task :chmod_x do 83 | executable_config_files.each do |file| 84 | queue! %[chmod +x "#{deploy_to}/#{shared_path}/config/#{file}"] 85 | end 86 | end 87 | 88 | task :symlink do 89 | symlinks.each do |symlink| 90 | queue! %[sudo ln -nfs #{config_path}/#{symlink[:source]} #{render_string symlink[:link]}] 91 | end 92 | end 93 | 94 | task :autoload do 95 | queue! %[sudo update-rc.d #{unicorn_symlink} defaults] 96 | end 97 | 98 | end 99 | -------------------------------------------------------------------------------- /lib/mina/helpers/checkers.rb: -------------------------------------------------------------------------------- 1 | def check(condition) 2 | !capture("if #{condition} ; then echo '#{status_success}' ; fi").empty? 3 | end 4 | -------------------------------------------------------------------------------- /lib/mina/helpers/print.rb: -------------------------------------------------------------------------------- 1 | def print_start(msg) 2 | print_stdout color("[START]: #{msg}", 33) 3 | end 4 | 5 | def print_success(msg) 6 | print_status color("[#{status_success}]: #{msg}", 32) 7 | end 8 | 9 | def print_fail(msg) 10 | print_error "[#{status_fail}]: #{msg}" 11 | end 12 | 13 | def print_title(title, location) 14 | server = location == 'remote' ? '[REMOTE]' : '[LOCAL]' 15 | print_str "\n" 16 | print_status "#{server}: #{title}" 17 | end 18 | 19 | def status_success 20 | 'SUCCESS' 21 | end 22 | 23 | def status_fail 24 | 'FAILED' 25 | end 26 | -------------------------------------------------------------------------------- /lib/mina/helpers/render.rb: -------------------------------------------------------------------------------- 1 | require 'fileutils' 2 | 3 | def render_config(from, to = nil) 4 | 5 | to ||= from 6 | src = "#{erb_templates}/#{from}.erb" 7 | dest = "#{configs_tmp_path}/#{to}" 8 | 9 | if File.exist?(src) 10 | 11 | render = erb(src) 12 | 13 | FileUtils.mkdir_p(configs_tmp_path) 14 | 15 | file = File.new(dest, 'w') 16 | file.write(render) 17 | file.close 18 | 19 | else 20 | 21 | print_fail %[#{from} not found] 22 | 23 | end 24 | 25 | end 26 | 27 | def render_string(inp) 28 | str = inp 29 | inp.scan(/{{(\w*)}}/).each do |var| 30 | str.gsub!("{{#{var[0]}}}", fetch(var[0].to_sym)) 31 | end 32 | str 33 | end 34 | -------------------------------------------------------------------------------- /lib/mina/helpers/servers.rb: -------------------------------------------------------------------------------- 1 | def all_servers 2 | Dir['lib/mina/servers/*.rb'].reduce([]) do |servers, file| 3 | servers << File.basename(file, '.rb') 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /lib/mina/log.rb: -------------------------------------------------------------------------------- 1 | namespace :log do 2 | 3 | desc 'Nginx Log' 4 | task 'nginx' do 5 | lines = ENV['l'] || 20 6 | if ENV['only'] == 'error' 7 | queue! %[sudo tail #{nginx_error_log} --lines=#{lines}] 8 | else 9 | queue! %[sudo tail #{nginx_log} --lines=#{lines}] 10 | end 11 | end 12 | 13 | desc 'Rails Log' 14 | task 'rails' do 15 | lines = ENV['l'] || 20 16 | queue! %[tail #{logs_path}/production.log --lines=#{lines}] 17 | end 18 | 19 | desc 'Unicorn Log' 20 | task 'unicorn' do 21 | lines = ENV['l'] || 20 22 | queue! %[tail #{logs_path}/unicorn.log --lines=#{lines}] 23 | end 24 | 25 | end -------------------------------------------------------------------------------- /lib/mina/nginx.rb: -------------------------------------------------------------------------------- 1 | namespace :nginx do 2 | 3 | %w(stop start restart reload status).each do |action| 4 | desc "#{action.capitalize} Nginx" 5 | task action.to_sym do 6 | queue! %[sudo /etc/init.d/nginx #{action}] 7 | end 8 | end 9 | 10 | desc 'Remove default Nginx Virtual host' 11 | task 'remove_default_vhost' do 12 | if check("[ -f /etc/nginx/sites-enabled/default ]") 13 | queue! %[sudo rm /etc/nginx/sites-enabled/default] 14 | print_success %[Removed default Nginx Virtual host] 15 | end 16 | 17 | end 18 | 19 | end -------------------------------------------------------------------------------- /lib/mina/servers/production.rb: -------------------------------------------------------------------------------- 1 | task :production do 2 | 3 | set :domain, 'do_sbjs' 4 | set :public_domain, 'api.isomorphic-comments.alexfedoseev.com' 5 | set :app_server_name, "#{app}" 6 | set :app_sys_id, "#{app}-#{app_part}" 7 | 8 | end 9 | -------------------------------------------------------------------------------- /lib/mina/servers/staging.rb: -------------------------------------------------------------------------------- 1 | task :staging do 2 | 3 | set :domain, 'ssh.your-app.com' 4 | set :public_domain, 'api.dev.your-app.com' 5 | set :app_server_name, "#{app}-#{server}" 6 | set :app_sys_id, "#{app}-#{app_part}-#{server}" 7 | 8 | end 9 | -------------------------------------------------------------------------------- /lib/mina/setup.rb: -------------------------------------------------------------------------------- 1 | task :setup => :environment do 2 | 3 | # Creating config folder on server... 4 | queue! %[mkdir -p "#{config_path}"] 5 | queue! %[chmod g+rx,u+rwx "#{config_path}"] 6 | 7 | # Creating log folder on server... 8 | queue! %[mkdir -p "#{logs_path}"] 9 | queue! %[chmod g+rx,u+rwx "#{logs_path}"] 10 | 11 | # Creating pids folder on server... 12 | queue! %[mkdir -p "#{pids_path}"] 13 | queue! %[chmod g+rx,u+rwx "#{pids_path}"] 14 | 15 | # Creating sockets folder on server... 16 | queue! %[mkdir -p "#{sockets_path}"] 17 | queue! %[chmod g+rx,u+rwx "#{sockets_path}"] 18 | 19 | end 20 | -------------------------------------------------------------------------------- /lib/mina/templates/database.example.yml.erb: -------------------------------------------------------------------------------- 1 | <%= rails_env %>: 2 | adapter: postgresql 3 | encoding: unicode 4 | database: <%= app_server_name.gsub('-', '_') %> 5 | pool: 5 6 | username: <%= app_server_name.gsub('-', '_') %> 7 | password: 8 | host: localhost 9 | port: 5432 10 | -------------------------------------------------------------------------------- /lib/mina/templates/environment_variables.example.yml.erb: -------------------------------------------------------------------------------- 1 | production: 2 | SECRET_KEY_BASE: 3 | DEVISE_SECRET_KEY: -------------------------------------------------------------------------------- /lib/mina/templates/logrotate.erb: -------------------------------------------------------------------------------- 1 | <%= "#{logs_path}/*.log" %> { 2 | weekly 3 | missingok 4 | rotate 52 5 | compress 6 | delaycompress 7 | notifempty 8 | copytruncate 9 | } 10 | -------------------------------------------------------------------------------- /lib/mina/templates/nginx.conf.erb: -------------------------------------------------------------------------------- 1 | upstream unicorn_<%= app_sys_id %> { 2 | server unix:/tmp/unicorn.<%= app_sys_id %>.sock fail_timeout=0; 3 | } 4 | 5 | server { 6 | server_name www.<%= public_domain %>; 7 | rewrite ^(.*) http://<%= public_domain %>$1 permanent; 8 | } 9 | 10 | server { 11 | listen <%= nginx_port %>; 12 | server_name <%= public_domain %>; 13 | root <%= deploy_to %>/current/public; 14 | 15 | rewrite ^/(.*)/$ /$1 permanent; 16 | 17 | access_log /var/log/nginx/<%= app_sys_id %>.log; 18 | error_log /var/log/nginx/<%= app_sys_id %>.error.log; 19 | 20 | try_files $uri/index.html $uri @unicorn; 21 | location @unicorn { 22 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 23 | proxy_set_header Host $http_host; 24 | proxy_pass http://unicorn_<%= app_sys_id %>; 25 | proxy_redirect off; 26 | } 27 | 28 | error_page 500 502 503 504 /500.html; 29 | client_max_body_size 4G; 30 | keepalive_timeout 10; 31 | } 32 | -------------------------------------------------------------------------------- /lib/mina/templates/unicorn.rb.erb: -------------------------------------------------------------------------------- 1 | root = "<%= current_release %>" 2 | working_directory root 3 | pid "#{root}/tmp/pids/unicorn.pid" 4 | stderr_path "#{root}/log/unicorn.log" 5 | stdout_path "#{root}/log/unicorn.log" 6 | 7 | listen "/tmp/unicorn.<%= app_sys_id %>.sock" 8 | worker_processes <%= unicorn_workers %> 9 | timeout <%= unicorn_timeout %> 10 | preload_app true 11 | 12 | # Force unicorn to look at the Gemfile in the current_path 13 | # otherwise once we've first started a master process, it 14 | # will always point to the first one it started. 15 | before_exec do |server| 16 | ENV['BUNDLE_GEMFILE'] = "<%= current_release %>/Gemfile" 17 | end 18 | 19 | before_fork do |server, worker| 20 | defined?(ActiveRecord::Base) and 21 | ActiveRecord::Base.connection.disconnect! 22 | # Quit the old unicorn process 23 | old_pid = "#{server.config[:pid]}.oldbin" 24 | if File.exists?(old_pid) && server.pid != old_pid 25 | puts "We've got an old pid and server pid is not the old pid" 26 | begin 27 | Process.kill("QUIT", File.read(old_pid).to_i) 28 | puts "killing master process (good thing tm)" 29 | rescue Errno::ENOENT, Errno::ESRCH 30 | puts "unicorn master already killed" 31 | end 32 | end 33 | end 34 | 35 | after_fork do |server, worker| 36 | port = 5000 + worker.nr 37 | child_pid = server.config[:pid].sub('.pid', ".#{port}.pid") 38 | system("echo #{Process.pid} > #{child_pid}") 39 | defined?(ActiveRecord::Base) and 40 | ActiveRecord::Base.establish_connection 41 | end 42 | -------------------------------------------------------------------------------- /lib/mina/templates/unicorn_init.sh.erb: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | 4 | TIMEOUT=${TIMEOUT-60} 5 | APP_ROOT=<%= current_release %> 6 | PID_DIR=$APP_ROOT/tmp/pids 7 | PID=$PID_DIR/unicorn.pid 8 | CMD="cd $APP_ROOT; bundle exec unicorn -D -c <%= "#{config_path}/unicorn.rb" %> -E <%= rails_env %>" 9 | AS_USER=<%= user %> 10 | set -u 11 | 12 | OLD_PIN="$PID.oldbin" 13 | 14 | sig () { 15 | test -s "$PID" && kill -$1 `cat $PID` 16 | } 17 | 18 | oldsig () { 19 | test -s $OLD_PIN && kill -$1 `cat $OLD_PIN` 20 | } 21 | 22 | workersig () { 23 | workerpid="$APP_ROOT/tmp/pids/unicorn.$2.pid" 24 | 25 | test -s "$workerpid" && kill -$1 `cat $workerpid` 26 | } 27 | 28 | run () { 29 | if [ "$(id -un)" = "$AS_USER" ]; then 30 | eval $1 31 | else 32 | su -c "$1" - $AS_USER 33 | fi 34 | } 35 | 36 | case "$1" in 37 | start) 38 | sig 0 && echo >&2 "Already running" && exit 0 39 | run "$CMD" 40 | ;; 41 | stop) 42 | sig QUIT && exit 0 43 | echo >&2 "Not running" 44 | ;; 45 | force-stop) 46 | sig TERM && exit 0 47 | echo >&2 "Not running" 48 | ;; 49 | kill_worker) 50 | workersig QUIT $2 && exit 0 51 | echo >&2 "Worker not running" 52 | ;; 53 | restart|reload) 54 | sig USR2 && echo reloaded OK && exit 0 55 | echo >&2 "Couldn't reload, starting '$CMD' instead" 56 | run "$CMD" 57 | ;; 58 | upgrade) 59 | if sig USR2 && sleep 2 && sig 0 && oldsig QUIT 60 | then 61 | n=$TIMEOUT 62 | while test -s $OLD_PIN && test $n -ge 0 63 | do 64 | printf '.' && sleep 1 && n=$(( $n - 1 )) 65 | done 66 | echo 67 | 68 | if test $n -lt 0 && test -s $OLD_PIN 69 | then 70 | echo >&2 "$OLD_PIN still exists after $TIMEOUT seconds" 71 | exit 1 72 | fi 73 | exit 0 74 | fi 75 | echo >&2 "Couldn't upgrade, starting '$CMD' instead" 76 | run "$CMD" 77 | ;; 78 | reopen-logs) 79 | sig USR1 80 | ;; 81 | *) 82 | echo >&2 "Usage: $0 " 83 | exit 1 84 | ;; 85 | esac 86 | -------------------------------------------------------------------------------- /lib/mina/unicorn.rb: -------------------------------------------------------------------------------- 1 | namespace :unicorn do 2 | 3 | %w(start stop force-stop restart upgrade reopen-logs).each do |action| 4 | desc "#{action.capitalize} Unicorn" 5 | task action.to_sym do 6 | queue! %[sudo #{unicorn_script} #{action}] 7 | end 8 | end 9 | 10 | end -------------------------------------------------------------------------------- /lib/subdomain_constraints.rb: -------------------------------------------------------------------------------- 1 | class SubdomainConstraints 2 | 3 | def initialize(options) 4 | @subdomain = options[:subdomain] 5 | end 6 | 7 | def matches?(req) 8 | req.subdomains.include?(@subdomain) 9 | end 10 | 11 | end 12 | -------------------------------------------------------------------------------- /lib/tasks/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alex35mil/isomorphic-comments-api/1cbd63133d58fc801db6c694ad9ffdd43215172b/lib/tasks/.keep -------------------------------------------------------------------------------- /public/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The page you were looking for doesn't exist (404) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The page you were looking for doesn't exist.

62 |

You may have mistyped the address or the page may have moved.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /public/422.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The change you wanted was rejected (422) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The change you wanted was rejected.

62 |

Maybe you tried to change something you didn't have access to.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /public/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | We're sorry, but something went wrong (500) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

We're sorry, but something went wrong.

62 |
63 |

If you are the application owner check the logs for more information.

64 |
65 | 66 | 67 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alex35mil/isomorphic-comments-api/1cbd63133d58fc801db6c694ad9ffdd43215172b/public/favicon.ico -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | # 3 | # To ban all spiders from the entire site uncomment the next two lines: 4 | # User-agent: * 5 | # Disallow: / 6 | -------------------------------------------------------------------------------- /spec/factories/comments.rb: -------------------------------------------------------------------------------- 1 | # == Schema Information 2 | # 3 | # Table name: comments 4 | # 5 | # id :integer not null, primary key 6 | # author :string not null 7 | # comment :text not null 8 | # created_at :datetime not null 9 | # updated_at :datetime not null 10 | # 11 | 12 | FactoryGirl.define do 13 | 14 | factory :comment do 15 | author 'Author' 16 | comment 'Comment' 17 | end 18 | 19 | end 20 | -------------------------------------------------------------------------------- /spec/factories/users.rb: -------------------------------------------------------------------------------- 1 | # == Schema Information 2 | # 3 | # Table name: users 4 | # 5 | # id :integer not null, primary key 6 | # email :string default(""), not null 7 | # encrypted_password :string default(""), not null 8 | # authentication_token :string default(""), not null 9 | # created_at :datetime not null 10 | # updated_at :datetime not null 11 | # 12 | 13 | FactoryGirl.define do 14 | 15 | factory :user do 16 | email { Faker::Internet.email } 17 | password '123456789' 18 | password_confirmation '123456789' 19 | end 20 | 21 | end 22 | -------------------------------------------------------------------------------- /spec/models/comment_spec.rb: -------------------------------------------------------------------------------- 1 | # == Schema Information 2 | # 3 | # Table name: comments 4 | # 5 | # id :integer not null, primary key 6 | # author :string not null 7 | # comment :text not null 8 | # created_at :datetime not null 9 | # updated_at :datetime not null 10 | # 11 | 12 | require 'rails_helper' 13 | 14 | RSpec.describe Comment, type: :model do 15 | 16 | subject(:comment) { FactoryGirl.create :comment } 17 | 18 | it { is_expected.to be_valid } 19 | 20 | it { is_expected.to respond_to :author } 21 | it { is_expected.to respond_to :comment } 22 | 23 | it { is_expected.to validate_presence_of :author } 24 | it { is_expected.to validate_presence_of :comment } 25 | 26 | end 27 | -------------------------------------------------------------------------------- /spec/models/user_spec.rb: -------------------------------------------------------------------------------- 1 | # == Schema Information 2 | # 3 | # Table name: users 4 | # 5 | # id :integer not null, primary key 6 | # email :string default(""), not null 7 | # encrypted_password :string default(""), not null 8 | # authentication_token :string default(""), not null 9 | # created_at :datetime not null 10 | # updated_at :datetime not null 11 | # 12 | 13 | require 'rails_helper' 14 | 15 | RSpec.describe User, type: :model do 16 | 17 | subject(:user) { FactoryGirl.create :user } 18 | 19 | it { is_expected.to be_valid } 20 | 21 | it { is_expected.to respond_to :email } 22 | it { is_expected.to respond_to :password } 23 | it { is_expected.to respond_to :password_confirmation } 24 | 25 | it { is_expected.to validate_presence_of :email } 26 | it { is_expected.to validate_uniqueness_of(:email).case_insensitive } 27 | it { is_expected.to allow_value('foo@bar.com').for(:email) } 28 | it { is_expected.not_to allow_value('foo', 'foo@bar', 'bar.com' ).for(:email) } 29 | 30 | it { is_expected.to validate_presence_of :password } 31 | it { is_expected.to validate_confirmation_of :password } 32 | 33 | it 'has encrypted_password' do 34 | expect(user.encrypted_password).not_to be_blank 35 | end 36 | 37 | it 'has authentication_token' do 38 | expect(user.authentication_token).not_to be_blank 39 | end 40 | 41 | context 'when email has capital letters' do 42 | subject(:user) { FactoryGirl.create :user, email: 'FOO@BAR.COM' } 43 | it 'saves email downcased' do 44 | expect(user.email).to eq user.email.downcase 45 | end 46 | end 47 | 48 | end 49 | -------------------------------------------------------------------------------- /spec/rails_helper.rb: -------------------------------------------------------------------------------- 1 | # This file is copied to spec/ when you run 'rails generate rspec:install' 2 | ENV['RAILS_ENV'] ||= 'test' 3 | require File.expand_path('../../config/environment', __FILE__) 4 | # Prevent database truncation if the environment is production 5 | abort("The Rails environment is running in production mode!") if Rails.env.production? 6 | require 'spec_helper' 7 | require 'rspec/rails' 8 | # Add additional requires below this line. Rails is not loaded until this point! 9 | 10 | # Requires supporting ruby files with custom matchers and macros, etc, in 11 | # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are 12 | # run as spec files by default. This means that files in spec/support that end 13 | # in _spec.rb will both be required and run as specs, causing the specs to be 14 | # run twice. It is recommended that you do not name files matching this glob to 15 | # end with _spec.rb. You can configure this pattern with the --pattern 16 | # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. 17 | # 18 | # The following line is provided for convenience purposes. It has the downside 19 | # of increasing the boot-up time by auto-requiring all files in the support 20 | # directory. Alternatively, in the individual `*_spec.rb` files, manually 21 | # require only the support files necessary. 22 | # 23 | # Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } 24 | 25 | # Checks for pending migrations before tests are run. 26 | # If you are not using ActiveRecord, you can remove this line. 27 | ActiveRecord::Migration.maintain_test_schema! 28 | 29 | RSpec.configure do |config| 30 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 31 | config.fixture_path = "#{::Rails.root}/spec/fixtures" 32 | 33 | # If you're not using ActiveRecord, or you'd prefer not to run each of your 34 | # examples within a transaction, remove the following line or assign false 35 | # instead of true. 36 | config.use_transactional_fixtures = true 37 | 38 | # RSpec Rails can automatically mix in different behaviours to your tests 39 | # based on their file location, for example enabling you to call `get` and 40 | # `post` in specs under `spec/controllers`. 41 | # 42 | # You can disable this behaviour by removing the line below, and instead 43 | # explicitly tag your specs with their type, e.g.: 44 | # 45 | # RSpec.describe UsersController, :type => :controller do 46 | # # ... 47 | # end 48 | # 49 | # The different available types are documented in the features, such as in 50 | # https://relishapp.com/rspec/rspec-rails/docs 51 | config.infer_spec_type_from_file_location! 52 | end 53 | -------------------------------------------------------------------------------- /spec/requests/api/v1/comments_spec.rb: -------------------------------------------------------------------------------- 1 | RSpec.describe Api::V1::CommentsController do 2 | 3 | let(:user) { FactoryGirl.create :user } 4 | let(:base_url) { public_url '/comments' } 5 | 6 | 7 | describe 'GET #index' do 8 | 9 | let(:url) { base_url } 10 | 11 | before(:all) { FactoryGirl.create_list :comment, 10 } 12 | before(:each) { get! url, headers } 13 | 14 | it 'lists all comments' do 15 | expect(json[:comments].length).to eq 10 16 | end 17 | it { expect(response).to have_http_status(200) } 18 | 19 | end 20 | 21 | 22 | describe 'POST #create' do 23 | 24 | let(:url) { base_url } 25 | let(:comment_params) { FactoryGirl.attributes_for :comment } 26 | 27 | context 'when comment params are invalid' do 28 | before(:each) { post! url, { comment: {nothing: :here} }, headers } 29 | it 'responds with errors' do 30 | expect(json[:errors]).to be_truthy 31 | end 32 | it { expect(response).to have_http_status(422) } 33 | end 34 | 35 | context 'when comment params are valid' do 36 | before(:each) { post! url, { comment: comment_params }, headers } 37 | 38 | it 'creates comment and responds with it' do 39 | expect(json[:comment][:author]).to eq comment_params[:author] 40 | expect(json[:comment][:comment]).to eq comment_params[:comment] 41 | end 42 | 43 | it { expect(response).to have_http_status(201) } 44 | end 45 | end 46 | 47 | 48 | describe 'GET #show' do 49 | 50 | let(:comment) { FactoryGirl.create :comment } 51 | let(:url) { "#{base_url}/#{comment.id}" } 52 | 53 | before(:each) { get! url, headers } 54 | 55 | it 'responds with comment and title' do 56 | expect(json[:comment][:author]).to eq comment.author 57 | expect(json[:comment][:comment]).to eq comment.comment 58 | end 59 | 60 | it { expect(response).to have_http_status(200) } 61 | 62 | end 63 | 64 | 65 | describe 'DELETE #destroy' do 66 | 67 | let(:comment) { FactoryGirl.create :comment } 68 | let(:url) { "#{base_url}/#{comment.id}" } 69 | 70 | it_behaves_like 'unauthorized DELETE request' 71 | 72 | context 'when authorized' do 73 | before(:each) { delete! url, auth_headers(user) } 74 | it { expect(response).to have_http_status(204) } 75 | end 76 | 77 | end 78 | 79 | end 80 | -------------------------------------------------------------------------------- /spec/requests/api/v1/registrations_spec.rb: -------------------------------------------------------------------------------- 1 | RSpec.describe Api::V1::RegistrationsController do 2 | 3 | describe '#create' do 4 | 5 | let(:user_params) { FactoryGirl.attributes_for :user } 6 | 7 | context 'when signin up' do 8 | it 'raises error' do 9 | expect { 10 | post! "#{public_url}/signup", { api_user: user_params }, headers 11 | }.to raise_error ActionController::RoutingError 12 | end 13 | end 14 | end 15 | 16 | end 17 | -------------------------------------------------------------------------------- /spec/requests/api/v1/sessions_spec.rb: -------------------------------------------------------------------------------- 1 | describe Api::V1::SessionsController do 2 | 3 | let(:user) { FactoryGirl.create :user } 4 | 5 | describe '#create' do 6 | 7 | context 'when password is correct' do 8 | before(:each) do 9 | post! "#{public_url}/login", { api_user: { email: user.email, password: user.password } }, headers 10 | end 11 | it 'logins user' do 12 | expect(json[:user][:email]).to eq user.email 13 | expect(json[:user][:authentication_token]).to eq user.authentication_token 14 | end 15 | it { expect(response).to have_http_status(201) } 16 | end 17 | 18 | context 'when password is incorrect' do 19 | before(:each) do 20 | post! "#{public_url}/login", { api_user: { email: user.email, password: 'wrong!' } }, headers 21 | end 22 | it 'responds with error' do 23 | expect(json[:error]).to be_truthy 24 | end 25 | it { expect(response).to have_http_status(401) } 26 | end 27 | 28 | end 29 | 30 | end 31 | -------------------------------------------------------------------------------- /spec/routing/api_constraints_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | require 'api_constraints' 3 | 4 | describe ApiConstraints do 5 | 6 | 7 | let(:api_constraints_v1) { ApiConstraints.new version: 1 } 8 | let(:api_constraints_v2) { ApiConstraints.new version: 2, default: true } 9 | 10 | 11 | describe '#matches?' do 12 | 13 | context 'when version contains Accept header with API version' do 14 | it 'matches API version from header' do 15 | req = double( host: public_url, 16 | headers: { 'Accept' => "application/vnd.isomorphic-comments.v1+json" }) 17 | expect(api_constraints_v1.matches?(req)).to be true 18 | end 19 | end 20 | 21 | context 'when no Accept header present' do 22 | it 'matches default API version' do 23 | req = double(host: public_url) 24 | expect(api_constraints_v2.matches?(req)).to be true 25 | end 26 | end 27 | 28 | end 29 | 30 | 31 | end 32 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # This file was generated by the `rails generate rspec:install` command. Conventionally, all 2 | # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. 3 | # The generated `.rspec` file contains `--require spec_helper` which will cause 4 | # this file to always be loaded, without a need to explicitly require it in any 5 | # files. 6 | # 7 | # Given that it is always loaded, you are encouraged to keep this file as 8 | # light-weight as possible. Requiring heavyweight dependencies from this file 9 | # will add to the boot time of your test suite on EVERY test run, even for an 10 | # individual file that may not need all of that loaded. Instead, consider making 11 | # a separate helper file that requires the additional dependencies and performs 12 | # the additional setup, and require it from the spec files that actually need 13 | # it. 14 | # 15 | # The `.rspec` file also contains a few flags that are not defaults but that 16 | # users commonly want. 17 | # 18 | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration 19 | RSpec.configure do |config| 20 | 21 | Dir['./spec/support/**/*.rb'].each { |f| require f } 22 | 23 | config.include Requests::JsonHelpers, type: :request 24 | config.include Requests::RequestHelpers, type: :request 25 | config.include Requests::URIHelpers 26 | 27 | config.before(:suite) do 28 | DatabaseCleaner.clean_with :truncation 29 | DatabaseCleaner.strategy = :transaction 30 | end 31 | 32 | config.before(:each) do 33 | DatabaseCleaner.start 34 | end 35 | 36 | config.after(:each) do 37 | DatabaseCleaner.clean 38 | end 39 | 40 | config.after(:each) do 41 | FileUtils.rm_rf(Dir["#{Rails.root}/spec/uploads"]) if File.directory?("#{Rails.root}/spec/uploads") 42 | end 43 | 44 | # rspec-expectations config goes here. You can use an alternate 45 | # assertion/expectation library such as wrong or the stdlib/minitest 46 | # assertions if you prefer. 47 | config.expect_with :rspec do |expectations| 48 | # This option will default to `true` in RSpec 4. It makes the `description` 49 | # and `failure_message` of custom matchers include text for helper methods 50 | # defined using `chain`, e.g.: 51 | # be_bigger_than(2).and_smaller_than(4).description 52 | # # => "be bigger than 2 and smaller than 4" 53 | # ...rather than: 54 | # # => "be bigger than 2" 55 | expectations.include_chain_clauses_in_custom_matcher_descriptions = true 56 | end 57 | 58 | # rspec-mocks config goes here. You can use an alternate test double 59 | # library (such as bogus or mocha) by changing the `mock_with` option here. 60 | config.mock_with :rspec do |mocks| 61 | # Prevents you from mocking or stubbing a method that does not exist on 62 | # a real object. This is generally recommended, and will default to 63 | # `true` in RSpec 4. 64 | mocks.verify_partial_doubles = true 65 | end 66 | 67 | # The settings below are suggested to provide a good initial experience 68 | # with RSpec, but feel free to customize to your heart's content. 69 | =begin 70 | # These two settings work together to allow you to limit a spec run 71 | # to individual examples or groups you care about by tagging them with 72 | # `:focus` metadata. When nothing is tagged with `:focus`, all examples 73 | # get run. 74 | config.filter_run :focus 75 | config.run_all_when_everything_filtered = true 76 | 77 | # Allows RSpec to persist some state between runs in order to support 78 | # the `--only-failures` and `--next-failure` CLI options. We recommend 79 | # you configure your source control system to ignore this file. 80 | config.example_status_persistence_file_path = "spec/examples.txt" 81 | 82 | # Limits the available syntax to the non-monkey patched syntax that is 83 | # recommended. For more details, see: 84 | # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax 85 | # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ 86 | # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching 87 | config.disable_monkey_patching! 88 | 89 | # Many RSpec users commonly either run the entire suite or an individual 90 | # file, and it's useful to allow more verbose output when running an 91 | # individual spec file. 92 | if config.files_to_run.one? 93 | # Use the documentation formatter for detailed output, 94 | # unless a formatter has already been configured 95 | # (e.g. via a command-line flag). 96 | config.default_formatter = 'doc' 97 | end 98 | 99 | # Print the 10 slowest examples and example groups at the 100 | # end of the spec run, to help surface which specs are running 101 | # particularly slow. 102 | config.profile_examples = 10 103 | 104 | # Run specs in random order to surface order dependencies. If you find an 105 | # order dependency and want to debug it, you can fix the order by providing 106 | # the seed, which is printed after each run. 107 | # --seed 1234 108 | config.order = :random 109 | 110 | # Seed global randomization in this process using the `--seed` CLI option. 111 | # Setting this allows you to use `--seed` to deterministically reproduce 112 | # test failures related to randomization by passing the same `--seed` value 113 | # as the one that triggered the failure. 114 | Kernel.srand config.seed 115 | =end 116 | end 117 | -------------------------------------------------------------------------------- /spec/support/request_helpers.rb: -------------------------------------------------------------------------------- 1 | module Requests 2 | 3 | module JsonHelpers 4 | def json 5 | @json ||= JSON.parse(response.body, symbolize_names: true) 6 | end 7 | end 8 | 9 | module URIHelpers 10 | def public_url(path = nil) 11 | "http://api.lvh.me#{path}" 12 | end 13 | end 14 | 15 | module RequestHelpers 16 | 17 | def get!(url, params) 18 | get url, nil, params 19 | end 20 | def post!(url, data, params) 21 | post url, data.to_json, params 22 | end 23 | def patch!(url, data, params) 24 | patch url, data.to_json, params 25 | end 26 | def delete!(url, params) 27 | delete url, nil, params 28 | end 29 | 30 | def headers(api_version = 1) 31 | { 32 | 'Accept' => "application/vnd.isomorphic-comments.v#{api_version}+json", 33 | 'Content-Type' => 'application/json' 34 | } 35 | end 36 | def auth_headers(user, api_version = 1) 37 | headers(api_version).merge({ 38 | 'X-User-Email' => user.email, 39 | 'X-User-Token' => user.authentication_token 40 | }) 41 | end 42 | def bad_auth_headers(user, api_version = 1) 43 | headers = auth_headers(user, api_version) 44 | headers['X-User-Token'].upcase! 45 | headers 46 | end 47 | 48 | end 49 | 50 | end 51 | -------------------------------------------------------------------------------- /spec/support/unauthorized_shared_examples.rb: -------------------------------------------------------------------------------- 1 | RSpec.shared_examples_for 'unauthorized GET request' do 2 | 3 | context 'when no credentials given' do 4 | before { get! url, headers } 5 | it { expect(response).to have_http_status(401) } 6 | end 7 | 8 | context 'when bad credentials given' do 9 | before { get! url, bad_auth_headers(user) } 10 | it { expect(response).to have_http_status(401) } 11 | end 12 | 13 | end 14 | 15 | RSpec.shared_examples_for 'unauthorized POST request' do 16 | 17 | context 'when no credentials given' do 18 | before { post! url, {sample: :data}, headers } 19 | it { expect(response).to have_http_status(401) } 20 | end 21 | 22 | context 'when bad credentials given' do 23 | before { post! url, {sample: :data}, bad_auth_headers(user) } 24 | it { expect(response).to have_http_status(401) } 25 | end 26 | 27 | end 28 | 29 | RSpec.shared_examples_for 'unauthorized PATCH request' do 30 | 31 | context 'when no credentials given' do 32 | before { patch! url, {sample: :data}, headers } 33 | it { expect(response).to have_http_status(401) } 34 | end 35 | 36 | context 'when bad credentials given' do 37 | before { patch! url, {sample: :data}, bad_auth_headers(user) } 38 | it { expect(response).to have_http_status(401) } 39 | end 40 | 41 | end 42 | 43 | RSpec.shared_examples_for 'unauthorized DELETE request' do 44 | 45 | context 'when no credentials given' do 46 | before { delete! url, headers } 47 | it { expect(response).to have_http_status(401) } 48 | end 49 | 50 | context 'when bad credentials given' do 51 | before { delete! url, bad_auth_headers(user) } 52 | it { expect(response).to have_http_status(401) } 53 | end 54 | 55 | end 56 | -------------------------------------------------------------------------------- /test/controllers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alex35mil/isomorphic-comments-api/1cbd63133d58fc801db6c694ad9ffdd43215172b/test/controllers/.keep -------------------------------------------------------------------------------- /test/fixtures/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alex35mil/isomorphic-comments-api/1cbd63133d58fc801db6c694ad9ffdd43215172b/test/fixtures/.keep -------------------------------------------------------------------------------- /test/helpers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alex35mil/isomorphic-comments-api/1cbd63133d58fc801db6c694ad9ffdd43215172b/test/helpers/.keep -------------------------------------------------------------------------------- /test/integration/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alex35mil/isomorphic-comments-api/1cbd63133d58fc801db6c694ad9ffdd43215172b/test/integration/.keep -------------------------------------------------------------------------------- /test/mailers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alex35mil/isomorphic-comments-api/1cbd63133d58fc801db6c694ad9ffdd43215172b/test/mailers/.keep -------------------------------------------------------------------------------- /test/models/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alex35mil/isomorphic-comments-api/1cbd63133d58fc801db6c694ad9ffdd43215172b/test/models/.keep -------------------------------------------------------------------------------- /test/test_helper.rb: -------------------------------------------------------------------------------- 1 | ENV['RAILS_ENV'] ||= 'test' 2 | require File.expand_path('../../config/environment', __FILE__) 3 | require 'rails/test_help' 4 | 5 | class ActiveSupport::TestCase 6 | # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. 7 | fixtures :all 8 | 9 | # Add more helper methods to be used by all tests here... 10 | end 11 | --------------------------------------------------------------------------------