├── log
└── .keep
├── app
├── mailers
│ └── .keep
├── models
│ ├── .keep
│ ├── concerns
│ │ └── .keep
│ ├── post.rb
│ └── user.rb
├── assets
│ ├── images
│ │ └── .keep
│ ├── stylesheets
│ │ ├── posts.scss
│ │ ├── application.css
│ │ └── scaffolds.scss
│ └── javascripts
│ │ ├── posts.coffee
│ │ └── application.js
├── controllers
│ ├── concerns
│ │ └── .keep
│ ├── application_controller.rb
│ └── posts_controller.rb
├── helpers
│ ├── posts_helper.rb
│ └── application_helper.rb
└── views
│ ├── posts
│ ├── show.json.jbuilder
│ ├── new.html.erb
│ ├── _post.json.jbuilder
│ ├── edit.html.erb
│ ├── show.html.erb
│ ├── _form.html.erb
│ ├── index.html.erb
│ └── index.json.jbuilder
│ └── layouts
│ └── application.html.erb
├── lib
├── assets
│ └── .keep
└── tasks
│ └── .keep
├── public
├── favicon.ico
├── robots.txt
├── 500.html
├── 422.html
├── 404.html
└── login.json
├── test
├── helpers
│ └── .keep
├── mailers
│ └── .keep
├── models
│ ├── .keep
│ ├── post_test.rb
│ └── user_test.rb
├── controllers
│ ├── .keep
│ └── posts_controller_test.rb
├── fixtures
│ ├── .keep
│ ├── posts.yml
│ └── users.yml
├── integration
│ └── .keep
└── test_helper.rb
├── vendor
└── assets
│ ├── javascripts
│ └── .keep
│ └── stylesheets
│ └── .keep
├── signed_in.png
├── signed_out.png
├── bin
├── bundle
├── rake
├── rails
├── spring
└── setup
├── config
├── boot.rb
├── initializers
│ ├── cookies_serializer.rb
│ ├── session_store.rb
│ ├── mime_types.rb
│ ├── filter_parameter_logging.rb
│ ├── backtrace_silencers.rb
│ ├── assets.rb
│ ├── wrap_parameters.rb
│ ├── inflections.rb
│ └── devise.rb
├── environment.rb
├── database.yml
├── locales
│ ├── en.yml
│ └── devise.en.yml
├── secrets.yml
├── application.rb
├── environments
│ ├── development.rb
│ ├── test.rb
│ └── production.rb
└── routes.rb
├── config.ru
├── db
├── migrate
│ ├── 20161014035933_create_posts.rb
│ ├── 20161014040023_add_authentication_token_to_users.rb
│ └── 20161014040015_devise_create_users.rb
├── seeds.rb
└── schema.rb
├── Rakefile
├── .gitignore
├── README.rdoc
├── LICENSE
├── Gemfile
├── Gemfile.lock
└── README.md
/log/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/mailers/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/models/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/lib/assets/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/lib/tasks/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/helpers/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/mailers/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/models/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/assets/images/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/controllers/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/fixtures/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/integration/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/models/concerns/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/controllers/concerns/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/vendor/assets/javascripts/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/vendor/assets/stylesheets/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/helpers/posts_helper.rb:
--------------------------------------------------------------------------------
1 | module PostsHelper
2 | end
3 |
--------------------------------------------------------------------------------
/app/helpers/application_helper.rb:
--------------------------------------------------------------------------------
1 | module ApplicationHelper
2 | end
3 |
--------------------------------------------------------------------------------
/app/views/posts/show.json.jbuilder:
--------------------------------------------------------------------------------
1 | json.partial! "posts/post", post: @post
--------------------------------------------------------------------------------
/app/models/post.rb:
--------------------------------------------------------------------------------
1 | class Post < ActiveRecord::Base
2 | belongs_to :user
3 | end
4 |
--------------------------------------------------------------------------------
/signed_in.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Jasonette/token-authentication-example/HEAD/signed_in.png
--------------------------------------------------------------------------------
/signed_out.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Jasonette/token-authentication-example/HEAD/signed_out.png
--------------------------------------------------------------------------------
/app/views/posts/new.html.erb:
--------------------------------------------------------------------------------
1 |
New Post
2 |
3 | <%= render 'form' %>
4 |
5 | <%= link_to 'Back', posts_path %>
6 |
--------------------------------------------------------------------------------
/app/views/posts/_post.json.jbuilder:
--------------------------------------------------------------------------------
1 | json.extract! post, :id, :content, :user_id, :created_at, :updated_at
2 | json.url post_url(post, format: :json)
--------------------------------------------------------------------------------
/bin/bundle:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
3 | load Gem.bin_path('bundler', 'bundle')
4 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/app/views/posts/edit.html.erb:
--------------------------------------------------------------------------------
1 | Editing Post
2 |
3 | <%= render 'form' %>
4 |
5 | <%= link_to 'Show', @post %> |
6 | <%= link_to 'Back', posts_path %>
7 |
--------------------------------------------------------------------------------
/test/models/post_test.rb:
--------------------------------------------------------------------------------
1 | require 'test_helper'
2 |
3 | class PostTest < ActiveSupport::TestCase
4 | # test "the truth" do
5 | # assert true
6 | # end
7 | end
8 |
--------------------------------------------------------------------------------
/test/models/user_test.rb:
--------------------------------------------------------------------------------
1 | require 'test_helper'
2 |
3 | class UserTest < ActiveSupport::TestCase
4 | # test "the truth" do
5 | # assert true
6 | # end
7 | end
8 |
--------------------------------------------------------------------------------
/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/initializers/cookies_serializer.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | Rails.application.config.action_dispatch.cookies_serializer = :json
4 |
--------------------------------------------------------------------------------
/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/initializers/session_store.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | Rails.application.config.session_store :cookie_store, key: '_jasonserver_session'
4 |
--------------------------------------------------------------------------------
/config/initializers/mime_types.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Add new mime types for use in respond_to blocks:
4 | # Mime::Type.register "text/richtext", :rtf
5 |
--------------------------------------------------------------------------------
/app/assets/stylesheets/posts.scss:
--------------------------------------------------------------------------------
1 | // Place all the styles related to the Posts controller here.
2 | // They will automatically be included in application.css.
3 | // You can use Sass (SCSS) here: http://sass-lang.com/
4 |
--------------------------------------------------------------------------------
/test/fixtures/posts.yml:
--------------------------------------------------------------------------------
1 | # Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html
2 |
3 | one:
4 | content: MyText
5 | user_id: 1
6 |
7 | two:
8 | content: MyText
9 | user_id: 1
10 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/app/assets/javascripts/posts.coffee:
--------------------------------------------------------------------------------
1 | # Place all the behaviors and hooks related to the matching controller here.
2 | # All this logic will automatically be available in application.js.
3 | # You can use CoffeeScript in this file: http://coffeescript.org/
4 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/bin/rake:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | begin
3 | load File.expand_path('../spring', __FILE__)
4 | rescue LoadError => e
5 | raise unless e.message.include?('spring')
6 | end
7 | require_relative '../config/boot'
8 | require 'rake'
9 | Rake.application.run
10 |
--------------------------------------------------------------------------------
/db/migrate/20161014035933_create_posts.rb:
--------------------------------------------------------------------------------
1 | class CreatePosts < ActiveRecord::Migration
2 | def change
3 | create_table :posts do |t|
4 | t.text :content
5 | t.integer :user_id
6 |
7 | t.timestamps null: false
8 | end
9 | end
10 | end
11 |
--------------------------------------------------------------------------------
/Rakefile:
--------------------------------------------------------------------------------
1 | # Add your own tasks in files placed in lib/tasks ending in .rake,
2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
3 |
4 | require File.expand_path('../config/application', __FILE__)
5 |
6 | Rails.application.load_tasks
7 |
--------------------------------------------------------------------------------
/db/migrate/20161014040023_add_authentication_token_to_users.rb:
--------------------------------------------------------------------------------
1 | class AddAuthenticationTokenToUsers < ActiveRecord::Migration
2 | def change
3 | add_column :users, :authentication_token, :string, limit: 30
4 | add_index :users, :authentication_token, unique: true
5 | end
6 | end
7 |
--------------------------------------------------------------------------------
/bin/rails:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | begin
3 | load File.expand_path('../spring', __FILE__)
4 | rescue LoadError => e
5 | raise unless e.message.include?('spring')
6 | end
7 | APP_PATH = File.expand_path('../../config/application', __FILE__)
8 | require_relative '../config/boot'
9 | require 'rails/commands'
10 |
--------------------------------------------------------------------------------
/app/views/posts/show.html.erb:
--------------------------------------------------------------------------------
1 | <%= notice %>
2 |
3 |
4 | Content:
5 | <%= @post.content %>
6 |
7 |
8 |
9 | User:
10 | <%= @post.user_id %>
11 |
12 |
13 | <%= link_to 'Edit', edit_post_path(@post) %> |
14 | <%= link_to 'Back', posts_path %>
15 |
--------------------------------------------------------------------------------
/app/models/user.rb:
--------------------------------------------------------------------------------
1 | class User < ActiveRecord::Base
2 | acts_as_token_authenticatable
3 | has_many :posts
4 |
5 | # Include default devise modules. Others available are:
6 | # :confirmable, :lockable, :timeoutable and :omniauthable
7 | devise :database_authenticatable, :registerable,
8 | :recoverable, :rememberable, :trackable, :validatable
9 | end
10 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/app/views/layouts/application.html.erb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Jasonserver
5 | <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
6 | <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
7 | <%= csrf_meta_tags %>
8 |
9 |
10 |
11 | <%= yield %>
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/test/fixtures/users.yml:
--------------------------------------------------------------------------------
1 | # Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html
2 |
3 | # This model initially had no columns defined. If you add columns to the
4 | # model remove the '{}' from the fixture names and add the columns immediately
5 | # below each fixture, per the syntax in the comments below
6 | #
7 | one: {}
8 | # column: value
9 | #
10 | two: {}
11 | # column: value
12 |
--------------------------------------------------------------------------------
/config/initializers/backtrace_silencers.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
5 |
6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
7 | # Rails.backtrace_cleaner.remove_silencers!
8 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files for more about ignoring files.
2 | #
3 | # If you find yourself ignoring temporary files generated by your text editor
4 | # or operating system, you probably want to add a global ignore instead:
5 | # git config --global core.excludesfile '~/.gitignore_global'
6 |
7 | # Ignore bundler config.
8 | /.bundle
9 |
10 | # Ignore the default SQLite database.
11 | /db/*.sqlite3
12 | /db/*.sqlite3-journal
13 |
14 | # Ignore all logfiles and tempfiles.
15 | /log/*
16 | !/log/.keep
17 | /tmp
18 |
--------------------------------------------------------------------------------
/config/initializers/assets.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Version of your assets, change this if you want to expire all your assets.
4 | Rails.application.config.assets.version = '1.0'
5 |
6 | # Add additional assets to the asset load path
7 | # Rails.application.config.assets.paths << Emoji.images_path
8 |
9 | # Precompile additional assets.
10 | # application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
11 | # Rails.application.config.assets.precompile += %w( search.js )
12 |
--------------------------------------------------------------------------------
/bin/spring:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 |
3 | # This file loads spring without using Bundler, in order to be fast.
4 | # It gets overwritten when you run the `spring binstub` command.
5 |
6 | unless defined?(Spring)
7 | require 'rubygems'
8 | require 'bundler'
9 |
10 | lockfile = Bundler::LockfileParser.new(Bundler.default_lockfile.read)
11 | if spring = lockfile.specs.detect { |spec| spec.name == "spring" }
12 | Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path
13 | gem 'spring', spring.version
14 | require 'spring/binstub'
15 | end
16 | end
17 |
--------------------------------------------------------------------------------
/config/initializers/wrap_parameters.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # This file contains settings for ActionController::ParamsWrapper which
4 | # is enabled by default.
5 |
6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
7 | ActiveSupport.on_load(:action_controller) do
8 | wrap_parameters format: [:json] if respond_to?(:wrap_parameters)
9 | end
10 |
11 | # To enable root element in JSON for ActiveRecord objects.
12 | # ActiveSupport.on_load(:active_record) do
13 | # self.include_root_in_json = true
14 | # end
15 |
--------------------------------------------------------------------------------
/README.rdoc:
--------------------------------------------------------------------------------
1 | == README
2 |
3 | This README would normally document whatever steps are necessary to get the
4 | application up and running.
5 |
6 | Things you may want to cover:
7 |
8 | * Ruby version
9 |
10 | * System dependencies
11 |
12 | * Configuration
13 |
14 | * Database creation
15 |
16 | * Database initialization
17 |
18 | * How to run the test suite
19 |
20 | * Services (job queues, cache servers, search engines, etc.)
21 |
22 | * Deployment instructions
23 |
24 | * ...
25 |
26 |
27 | Please feel free to use a different markup language if you do not plan to run
28 | rake doc:app.
29 |
--------------------------------------------------------------------------------
/config/database.yml:
--------------------------------------------------------------------------------
1 | # SQLite version 3.x
2 | # gem install sqlite3
3 | #
4 | # Ensure the SQLite 3 gem is defined in your Gemfile
5 | # gem 'sqlite3'
6 | #
7 | default: &default
8 | adapter: sqlite3
9 | pool: 5
10 | timeout: 5000
11 |
12 | development:
13 | <<: *default
14 | database: db/development.sqlite3
15 |
16 | # Warning: The database defined as "test" will be erased and
17 | # re-generated from your development database when you run "rake".
18 | # Do not set this db to the same as development or production.
19 | test:
20 | <<: *default
21 | database: db/test.sqlite3
22 |
23 | production:
24 | <<: *default
25 | database: db/production.sqlite3
26 |
--------------------------------------------------------------------------------
/app/views/posts/_form.html.erb:
--------------------------------------------------------------------------------
1 | <%= form_for(@post) do |f| %>
2 | <% if @post.errors.any? %>
3 |
4 |
<%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:
5 |
6 |
7 | <% @post.errors.full_messages.each do |message| %>
8 | - <%= message %>
9 | <% end %>
10 |
11 |
12 | <% end %>
13 |
14 |
15 | <%= f.label :content %>
16 | <%= f.text_area :content %>
17 |
18 |
19 | <%= f.label :user_id %>
20 | <%= f.number_field :user_id %>
21 |
22 |
23 | <%= f.submit %>
24 |
25 | <% end %>
26 |
--------------------------------------------------------------------------------
/config/initializers/inflections.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Add new inflection rules using the following format. Inflections
4 | # are locale specific, and you may define rules for as many different
5 | # locales as you wish. All of these examples are active by default:
6 | # ActiveSupport::Inflector.inflections(:en) do |inflect|
7 | # inflect.plural /^(ox)$/i, '\1en'
8 | # inflect.singular /^(ox)en/i, '\1'
9 | # inflect.irregular 'person', 'people'
10 | # inflect.uncountable %w( fish sheep )
11 | # end
12 |
13 | # These inflection rules are supported but not enabled by default:
14 | # ActiveSupport::Inflector.inflections(:en) do |inflect|
15 | # inflect.acronym 'RESTful'
16 | # end
17 |
--------------------------------------------------------------------------------
/config/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 |
--------------------------------------------------------------------------------
/app/assets/javascripts/application.js:
--------------------------------------------------------------------------------
1 | // This is a manifest file that'll be compiled into application.js, which will include all the files
2 | // listed below.
3 | //
4 | // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
5 | // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
6 | //
7 | // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
8 | // compiled file.
9 | //
10 | // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
11 | // about supported directives.
12 | //
13 | //= require jquery
14 | //= require jquery_ujs
15 | //= require turbolinks
16 | //= require_tree .
17 |
--------------------------------------------------------------------------------
/app/views/posts/index.html.erb:
--------------------------------------------------------------------------------
1 | <%= notice %>
2 |
3 | Listing Posts
4 |
5 |
6 |
7 |
8 | | Content |
9 | User |
10 | |
11 |
12 |
13 |
14 |
15 | <% @posts.each do |post| %>
16 |
17 | | <%= post.content %> |
18 | <%= post.user_id %> |
19 | <%= link_to 'Show', post %> |
20 | <%= link_to 'Edit', edit_post_path(post) %> |
21 | <%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %> |
22 |
23 | <% end %>
24 |
25 |
26 |
27 |
28 |
29 | <%= link_to 'New Post', new_post_path %>
30 |
--------------------------------------------------------------------------------
/app/assets/stylesheets/application.css:
--------------------------------------------------------------------------------
1 | /*
2 | * This is a manifest file that'll be compiled into application.css, which will include all the files
3 | * listed below.
4 | *
5 | * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
6 | * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
7 | *
8 | * You're free to add application-wide styles to this file and they'll appear at the bottom of the
9 | * compiled file so the styles you add here take precedence over styles defined in any styles
10 | * defined in the other CSS/SCSS files in this directory. It is generally better to create a new
11 | * file per style scope.
12 | *
13 | *= require_tree .
14 | *= require_self
15 | */
16 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/app/controllers/application_controller.rb:
--------------------------------------------------------------------------------
1 | class ApplicationController < ActionController::Base
2 | # Prevent CSRF attacks by raising an exception.
3 | # For APIs, you may want to use :null_session instead.
4 | acts_as_token_authentication_handler_for User
5 | respond_to :html, :json
6 | protect_from_forgery with: :null_session
7 |
8 | protected
9 | def authenticate_user!
10 | if self.request.format.html?
11 | super
12 | elsif self.request.format.json?
13 | if self.request.parameters["controller"].start_with?("devise")
14 | # use the default if session related
15 | super
16 | else
17 | # others
18 | if user_signed_in?
19 | # use the default if already signed in
20 | super
21 | else
22 | # serve the static login page if not signed in
23 | @data = File.read("#{Rails.root}/public/login.json")
24 | @data = @data.gsub(/ROOT/, root_url)
25 | render :json => @data
26 | end
27 | end
28 | end
29 | end
30 | end
31 |
--------------------------------------------------------------------------------
/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: b22df0e7e48c3a1d0d4d81f9aac50f86834ca68777c94e14075928edac3b2bda7d5e9654722ea017f1df869996ca073d5dc7074444cfcd64a79243ff7c4aa71f
15 |
16 | test:
17 | secret_key_base: 785e305917edd8391e239a80da3a7b7f1f1e98f075a5ea832f565287cdc883fbfe8410836f64d00698069fd6eedf18574f7e9691a43c726ae0fc38707f578373
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 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2016 gliechtenstein
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/config/application.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../boot', __FILE__)
2 |
3 | require 'rails/all'
4 |
5 | # Require the gems listed in Gemfile, including any gems
6 | # you've limited to :test, :development, or :production.
7 | Bundler.require(*Rails.groups)
8 |
9 | module Jasonserver
10 | class Application < Rails::Application
11 | # Settings in config/environments/* take precedence over those specified here.
12 | # Application configuration should go into files in config/initializers
13 | # -- all .rb files in that directory are automatically loaded.
14 |
15 | # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
16 | # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
17 | # config.time_zone = 'Central Time (US & Canada)'
18 |
19 | # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
20 | # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
21 | # config.i18n.default_locale = :de
22 |
23 | # Do not swallow errors in after_commit/after_rollback callbacks.
24 | config.active_record.raise_in_transactional_callbacks = true
25 | end
26 | end
27 |
--------------------------------------------------------------------------------
/test/controllers/posts_controller_test.rb:
--------------------------------------------------------------------------------
1 | require 'test_helper'
2 |
3 | class PostsControllerTest < ActionController::TestCase
4 | setup do
5 | @post = posts(:one)
6 | end
7 |
8 | test "should get index" do
9 | get :index
10 | assert_response :success
11 | assert_not_nil assigns(:posts)
12 | end
13 |
14 | test "should get new" do
15 | get :new
16 | assert_response :success
17 | end
18 |
19 | test "should create post" do
20 | assert_difference('Post.count') do
21 | post :create, post: { content: @post.content, user_id: @post.user_id }
22 | end
23 |
24 | assert_redirected_to post_path(assigns(:post))
25 | end
26 |
27 | test "should show post" do
28 | get :show, id: @post
29 | assert_response :success
30 | end
31 |
32 | test "should get edit" do
33 | get :edit, id: @post
34 | assert_response :success
35 | end
36 |
37 | test "should update post" do
38 | patch :update, id: @post, post: { content: @post.content, user_id: @post.user_id }
39 | assert_redirected_to post_path(assigns(:post))
40 | end
41 |
42 | test "should destroy post" do
43 | assert_difference('Post.count', -1) do
44 | delete :destroy, id: @post
45 | end
46 |
47 | assert_redirected_to posts_path
48 | end
49 | end
50 |
--------------------------------------------------------------------------------
/app/assets/stylesheets/scaffolds.scss:
--------------------------------------------------------------------------------
1 | body {
2 | background-color: #fff;
3 | color: #333;
4 | font-family: verdana, arial, helvetica, sans-serif;
5 | font-size: 13px;
6 | line-height: 18px;
7 | }
8 |
9 | p, ol, ul, td {
10 | font-family: verdana, arial, helvetica, sans-serif;
11 | font-size: 13px;
12 | line-height: 18px;
13 | }
14 |
15 | pre {
16 | background-color: #eee;
17 | padding: 10px;
18 | font-size: 11px;
19 | }
20 |
21 | a {
22 | color: #000;
23 |
24 | &:visited {
25 | color: #666;
26 | }
27 |
28 | &:hover {
29 | color: #fff;
30 | background-color: #000;
31 | }
32 | }
33 |
34 | div {
35 | &.field, &.actions {
36 | margin-bottom: 10px;
37 | }
38 | }
39 |
40 | #notice {
41 | color: green;
42 | }
43 |
44 | .field_with_errors {
45 | padding: 2px;
46 | background-color: red;
47 | display: table;
48 | }
49 |
50 | #error_explanation {
51 | width: 450px;
52 | border: 2px solid red;
53 | padding: 7px;
54 | padding-bottom: 0;
55 | margin-bottom: 20px;
56 | background-color: #f0f0f0;
57 |
58 | h2 {
59 | text-align: left;
60 | font-weight: bold;
61 | padding: 5px 5px 5px 15px;
62 | font-size: 12px;
63 | margin: -7px;
64 | margin-bottom: 0px;
65 | background-color: #c00;
66 | color: #fff;
67 | }
68 |
69 | ul li {
70 | font-size: 12px;
71 | list-style: square;
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/db/migrate/20161014040015_devise_create_users.rb:
--------------------------------------------------------------------------------
1 | class DeviseCreateUsers < ActiveRecord::Migration
2 | def change
3 | create_table :users do |t|
4 | ## Database authenticatable
5 | t.string :email, null: false, default: ""
6 | t.string :encrypted_password, null: false, default: ""
7 |
8 | ## Recoverable
9 | t.string :reset_password_token
10 | t.datetime :reset_password_sent_at
11 |
12 | ## Rememberable
13 | t.datetime :remember_created_at
14 |
15 | ## Trackable
16 | t.integer :sign_in_count, default: 0, null: false
17 | t.datetime :current_sign_in_at
18 | t.datetime :last_sign_in_at
19 | t.string :current_sign_in_ip
20 | t.string :last_sign_in_ip
21 |
22 | ## Confirmable
23 | # t.string :confirmation_token
24 | # t.datetime :confirmed_at
25 | # t.datetime :confirmation_sent_at
26 | # t.string :unconfirmed_email # Only if using reconfirmable
27 |
28 | ## Lockable
29 | # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
30 | # t.string :unlock_token # Only if unlock strategy is :email or :both
31 | # t.datetime :locked_at
32 |
33 |
34 | t.timestamps null: false
35 | end
36 |
37 | add_index :users, :email, unique: true
38 | add_index :users, :reset_password_token, unique: true
39 | # add_index :users, :confirmation_token, unique: true
40 | # add_index :users, :unlock_token, unique: true
41 | end
42 | end
43 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 | # Debug mode disables concatenation and preprocessing of assets.
26 | # This option may cause significant delays in view rendering with a large
27 | # number of complex assets.
28 | config.assets.debug = true
29 |
30 | # Asset digests allow you to set far-future HTTP expiration dates on all assets,
31 | # yet still be able to expire them through the digest params.
32 | config.assets.digest = true
33 |
34 | # Adds additional error checking when serving assets at runtime.
35 | # Checks for improperly declared sprockets dependencies.
36 | # Raises helpful error messages.
37 | config.assets.raise_runtime_errors = true
38 |
39 | # Raises error for missing translations
40 | # config.action_view.raise_on_missing_translations = true
41 | end
42 |
--------------------------------------------------------------------------------
/Gemfile:
--------------------------------------------------------------------------------
1 | source 'http://rubygems.org'
2 |
3 | gem 'devise'
4 | gem 'simple_token_authentication', '~> 1.0'
5 | gem 'sqlite3', group: :development
6 | gem 'pg', group: :production
7 |
8 | gem 'rails_12factor', group: :production
9 |
10 |
11 | # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
12 | gem 'rails', '4.2.4'
13 | # Use SCSS for stylesheets
14 | gem 'sass-rails', '~> 5.0'
15 | # Use Uglifier as compressor for JavaScript assets
16 | gem 'uglifier', '>= 1.3.0'
17 | # Use CoffeeScript for .coffee assets and views
18 | gem 'coffee-rails', '~> 4.1.0'
19 | # See https://github.com/rails/execjs#readme for more supported runtimes
20 | # gem 'therubyracer', platforms: :ruby
21 |
22 | # Use jquery as the JavaScript library
23 | gem 'jquery-rails'
24 | # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
25 | gem 'turbolinks'
26 | # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
27 | gem 'jbuilder', '~> 2.0'
28 | # bundle exec rake doc:rails generates the API under doc/api.
29 | gem 'sdoc', '~> 0.4.0', group: :doc
30 |
31 | # Use ActiveModel has_secure_password
32 | # gem 'bcrypt', '~> 3.1.7'
33 |
34 | # Use Unicorn as the app server
35 | # gem 'unicorn'
36 |
37 | # Use Capistrano for deployment
38 | # gem 'capistrano-rails', group: :development
39 |
40 | group :development, :test do
41 | # Call 'byebug' anywhere in the code to stop execution and get a debugger console
42 | gem 'byebug'
43 | end
44 |
45 | group :development do
46 | # Access an IRB console on exception pages or by using <%= console %> in views
47 | gem 'web-console', '~> 2.0'
48 |
49 | # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
50 | gem 'spring'
51 | end
52 |
53 |
--------------------------------------------------------------------------------
/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/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 |
--------------------------------------------------------------------------------
/config/routes.rb:
--------------------------------------------------------------------------------
1 | Rails.application.routes.draw do
2 | devise_for :users
3 | resources :posts
4 | root "posts#index"
5 |
6 |
7 | # The priority is based upon order of creation: first created -> highest priority.
8 | # See how all your routes lay out with "rake routes".
9 |
10 | # You can have the root of your site routed with "root"
11 | # root 'welcome#index'
12 |
13 | # Example of regular route:
14 | # get 'products/:id' => 'catalog#view'
15 |
16 | # Example of named route that can be invoked with purchase_url(id: product.id)
17 | # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
18 |
19 | # Example resource route (maps HTTP verbs to controller actions automatically):
20 | # resources :products
21 |
22 | # Example resource route with options:
23 | # resources :products do
24 | # member do
25 | # get 'short'
26 | # post 'toggle'
27 | # end
28 | #
29 | # collection do
30 | # get 'sold'
31 | # end
32 | # end
33 |
34 | # Example resource route with sub-resources:
35 | # resources :products do
36 | # resources :comments, :sales
37 | # resource :seller
38 | # end
39 |
40 | # Example resource route with more complex sub-resources:
41 | # resources :products do
42 | # resources :comments
43 | # resources :sales do
44 | # get 'recent', on: :collection
45 | # end
46 | # end
47 |
48 | # Example resource route with concerns:
49 | # concern :toggleable do
50 | # post 'toggle'
51 | # end
52 | # resources :posts, concerns: :toggleable
53 | # resources :photos, concerns: :toggleable
54 |
55 | # Example resource route within a namespace:
56 | # namespace :admin do
57 | # # Directs /admin/products/* to Admin::ProductsController
58 | # # (app/controllers/admin/products_controller.rb)
59 | # resources :products
60 | # end
61 | end
62 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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: 20161014040023) do
15 |
16 | create_table "posts", force: :cascade do |t|
17 | t.text "content"
18 | t.integer "user_id"
19 | t.datetime "created_at", null: false
20 | t.datetime "updated_at", null: false
21 | end
22 |
23 | create_table "users", force: :cascade do |t|
24 | t.string "email", default: "", null: false
25 | t.string "encrypted_password", default: "", null: false
26 | t.string "reset_password_token"
27 | t.datetime "reset_password_sent_at"
28 | t.datetime "remember_created_at"
29 | t.integer "sign_in_count", default: 0, null: false
30 | t.datetime "current_sign_in_at"
31 | t.datetime "last_sign_in_at"
32 | t.string "current_sign_in_ip"
33 | t.string "last_sign_in_ip"
34 | t.datetime "created_at", null: false
35 | t.datetime "updated_at", null: false
36 | t.string "authentication_token", limit: 30
37 | end
38 |
39 | add_index "users", ["authentication_token"], name: "index_users_on_authentication_token", unique: true
40 | add_index "users", ["email"], name: "index_users_on_email", unique: true
41 | add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
42 |
43 | end
44 |
--------------------------------------------------------------------------------
/app/controllers/posts_controller.rb:
--------------------------------------------------------------------------------
1 | class PostsController < ApplicationController
2 | before_action :authenticate_user!
3 |
4 | before_action :set_post, only: [:show, :edit, :update, :destroy]
5 |
6 | # GET /posts
7 | # GET /posts.json
8 | def index
9 | @posts = Post.all.order("created_at DESC")
10 | end
11 |
12 | # GET /posts/1
13 | # GET /posts/1.json
14 | def show
15 | end
16 |
17 | # GET /posts/new
18 | def new
19 | @post = current_user.posts.build
20 | end
21 |
22 | # GET /posts/1/edit
23 | def edit
24 | end
25 |
26 | # POST /posts
27 | # POST /posts.json
28 | def create
29 | @post = current_user.posts.build(post_params)
30 |
31 | respond_to do |format|
32 | if @post.save
33 | format.html { redirect_to @post, notice: 'Post was successfully created.' }
34 | format.json { render :show, status: :created, location: @post }
35 | else
36 | format.html { render :new }
37 | format.json { render json: @post.errors, status: :unprocessable_entity }
38 | end
39 | end
40 | end
41 |
42 | # PATCH/PUT /posts/1
43 | # PATCH/PUT /posts/1.json
44 | def update
45 | respond_to do |format|
46 | if @post.update(post_params)
47 | format.html { redirect_to @post, notice: 'Post was successfully updated.' }
48 | format.json { render :show, status: :ok, location: @post }
49 | else
50 | format.html { render :edit }
51 | format.json { render json: @post.errors, status: :unprocessable_entity }
52 | end
53 | end
54 | end
55 |
56 | # DELETE /posts/1
57 | # DELETE /posts/1.json
58 | def destroy
59 | @post.destroy
60 | respond_to do |format|
61 | format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }
62 | format.json { head :no_content }
63 | end
64 | end
65 |
66 | private
67 | # Use callbacks to share common setup or constraints between actions.
68 | def set_post
69 | @post = Post.find(params[:id])
70 | end
71 |
72 | # Never trust parameters from the scary internet, only allow the white list through.
73 | def post_params
74 | params.require(:post).permit(:content, :user_id)
75 | end
76 | end
77 |
--------------------------------------------------------------------------------
/app/views/posts/index.json.jbuilder:
--------------------------------------------------------------------------------
1 | json.set! "$jason" do
2 | json.head do
3 | json.title "Posts"
4 | json.actions do
5 | json.set! "$pull" do
6 | json.type "$util.alert"
7 | json.options do
8 | json.title "Post"
9 | json.description "Post something"
10 | json.form do
11 | json.child! do
12 | json.name "post"
13 | json.placeholder "new message"
14 | end
15 | end
16 | end
17 | json.success do
18 | json.type "$network.request"
19 | json.options do
20 | json.method "post"
21 | json.url posts_url(format: :json)
22 | json.data do
23 | json.set! "post[content]", "{{$jason.post}}"
24 | end
25 | end
26 | json.success do
27 | json.type "$reload"
28 | end
29 | end
30 | end
31 | end
32 | end
33 | json.body do
34 | json.style do
35 | json.border "none"
36 | json.background "#646464"
37 | end
38 | json.header do
39 | json.title "Posts"
40 | json.style do
41 | json.background "#646464"
42 | json.color "#ffffff"
43 | end
44 | json.menu do
45 | json.text "Sign out"
46 | json.action do
47 | json.type "$session.reset"
48 | json.options do
49 | json.domain "sessionjason.herokuapp.com"
50 | end
51 | json.success do
52 | json.type "$reload"
53 | end
54 | end
55 | end
56 | end
57 | json.sections do
58 | json.child! do
59 | json.items do
60 | json.array!(@posts) do |post|
61 | json.type "vertical"
62 | json.components do
63 | json.child! do
64 | json.type "label"
65 | json.text post.content
66 | json.style do
67 | json.color "#ffffff"
68 | json.size "15"
69 | json.font "HelveticaNeue"
70 | end
71 | end
72 | json.child! do
73 | json.type "label"
74 | json.text "#{post.user.email.split(/@/)[0]} : #{time_ago_in_words(post.created_at)} ago"
75 | json.style do
76 | json.color "#ebebeb"
77 | json.size "12"
78 | json.font "HelveticaNeue"
79 | end
80 | end
81 | end
82 | end
83 | end
84 | end
85 | end
86 | end
87 | end
88 |
--------------------------------------------------------------------------------
/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 | # Compress JavaScripts and CSS.
28 | config.assets.js_compressor = :uglifier
29 | # config.assets.css_compressor = :sass
30 |
31 | # Do not fallback to assets pipeline if a precompiled asset is missed.
32 | config.assets.compile = false
33 |
34 | # Asset digests allow you to set far-future HTTP expiration dates on all assets,
35 | # yet still be able to expire them through the digest params.
36 | config.assets.digest = true
37 |
38 | # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
39 |
40 | # Specifies the header that your server uses for sending files.
41 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
42 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
43 |
44 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
45 | # config.force_ssl = true
46 |
47 | # Use the lowest log level to ensure availability of diagnostic information
48 | # when problems arise.
49 | config.log_level = :debug
50 |
51 | # Prepend all log lines with the following tags.
52 | # config.log_tags = [ :subdomain, :uuid ]
53 |
54 | # Use a different logger for distributed setups.
55 | # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
56 |
57 | # Use a different cache store in production.
58 | # config.cache_store = :mem_cache_store
59 |
60 | # Enable serving of images, stylesheets, and JavaScripts from an asset server.
61 | # config.action_controller.asset_host = 'http://assets.example.com'
62 |
63 | # Ignore bad email addresses and do not raise email delivery errors.
64 | # Set this to true and configure the email server for immediate delivery to raise delivery errors.
65 | # config.action_mailer.raise_delivery_errors = false
66 |
67 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
68 | # the I18n.default_locale when a translation cannot be found).
69 | config.i18n.fallbacks = true
70 |
71 | # Send deprecation notices to registered listeners.
72 | config.active_support.deprecation = :notify
73 |
74 | # Use default logging formatter so that PID and timestamp are not suppressed.
75 | config.log_formatter = ::Logger::Formatter.new
76 |
77 | # Do not dump schema after migrations.
78 | config.active_record.dump_schema_after_migration = false
79 | end
80 |
--------------------------------------------------------------------------------
/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 | password_change:
27 | subject: "Password Changed"
28 | omniauth_callbacks:
29 | failure: "Could not authenticate you from %{kind} because \"%{reason}\"."
30 | success: "Successfully authenticated from %{kind} account."
31 | passwords:
32 | 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."
33 | send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes."
34 | 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."
35 | updated: "Your password has been changed successfully. You are now signed in."
36 | updated_not_active: "Your password has been changed successfully."
37 | registrations:
38 | destroyed: "Bye! Your account has been successfully cancelled. We hope to see you again soon."
39 | signed_up: "Welcome! You have signed up successfully."
40 | signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated."
41 | signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked."
42 | 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."
43 | 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."
44 | updated: "Your account has been updated successfully."
45 | sessions:
46 | signed_in: "Signed in successfully."
47 | signed_out: "Signed out successfully."
48 | already_signed_out: "Signed out successfully."
49 | unlocks:
50 | send_instructions: "You will receive an email with instructions for how to unlock your account in a few minutes."
51 | send_paranoid_instructions: "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes."
52 | unlocked: "Your account has been unlocked successfully. Please sign in to continue."
53 | errors:
54 | messages:
55 | already_confirmed: "was already confirmed, please try signing in"
56 | confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one"
57 | expired: "has expired, please request a new one"
58 | not_found: "not found"
59 | not_locked: "was not locked"
60 | not_saved:
61 | one: "1 error prohibited this %{resource} from being saved:"
62 | other: "%{count} errors prohibited this %{resource} from being saved:"
63 |
--------------------------------------------------------------------------------
/public/login.json:
--------------------------------------------------------------------------------
1 | {
2 | "$jason": {
3 | "head": {
4 | "title": "login"
5 | },
6 | "body": {
7 | "style": {
8 | "border": "none",
9 | "background": "#646464"
10 | },
11 | "header": {
12 | "title": "Sign in",
13 | "style": {
14 | "background": "#646464",
15 | "color": "#ffffff"
16 | }
17 | },
18 | "sections": [{
19 | "items": [{
20 | "type": "space",
21 | "height": "10"
22 | }, {
23 | "type": "textfield",
24 | "name": "email",
25 | "style": {
26 | "size": "20",
27 | "color": "#8bb92d",
28 | "font": "HelveticaNeue-Bold",
29 | "background": "#575757",
30 | "padding": "20"
31 | },
32 | "placeholder": "enter email"
33 | }, {
34 | "type": "space",
35 | "height": "5"
36 | }, {
37 | "type": "textfield",
38 | "name": "password",
39 | "placeholder": "enter password",
40 | "style": {
41 | "size": "20",
42 | "color": "#8bb92d",
43 | "font": "HelveticaNeue-Bold",
44 | "background": "#575757",
45 | "padding": "20",
46 | "secure": "true"
47 | }
48 | }, {
49 | "type": "space",
50 | "height": "5"
51 | }, {
52 | "type": "label",
53 | "style": {
54 | "width": "100%",
55 | "align": "right",
56 | "font": "HelveticaNeue-Bold",
57 | "size": "20",
58 | "padding": "10",
59 | "background": "#8bb92d",
60 | "color": "#ffffff"
61 | },
62 | "text": "Sign in >",
63 | "action": {
64 | "type": "$network.request",
65 | "options": {
66 | "url": "ROOT/users/sign_in.json",
67 | "method": "post",
68 | "data": {
69 | "user[email]": "{{$get.email}}",
70 | "user[password]": "{{$get.password}}"
71 | }
72 | },
73 | "success": {
74 | "type": "$session.set",
75 | "options": {
76 | "domain": "ROOT",
77 | "header": {
78 | "X-User-Email": "{{$jason.email}}",
79 | "X-User-Token": "{{$jason.authentication_token}}"
80 | }
81 | },
82 | "success": {
83 | "type": "$href",
84 | "options": {
85 | "url": "ROOT/posts.json",
86 | "transition": "replace"
87 | }
88 | }
89 | },
90 | "error": {
91 | "type": "$util.banner",
92 | "options": {
93 | "title": "Error",
94 | "description": "Something went wrong. Please check if you entered your email and password correctly"
95 | }
96 | }
97 | }
98 | }, {
99 | "type": "label",
100 | "style": {
101 | "size": "16",
102 | "font": "HelveticaNeue-Bold",
103 | "text": "or",
104 | "padding": "10",
105 | "align": "center"
106 | }
107 | }, {
108 | "type": "label",
109 | "text": "Sign up >",
110 | "style": {
111 | "align": "right",
112 | "size": "20",
113 | "padding": "10",
114 | "font": "HelveticaNeue-Bold",
115 | "color": "#ffffff"
116 | },
117 | "action": {
118 | "type": "$network.request",
119 | "options": {
120 | "url": "ROOT/users.json",
121 | "method": "post",
122 | "data": {
123 | "user[email]": "{{$get.email}}",
124 | "user[password]": "{{$get.password}}"
125 | }
126 | },
127 | "success": {
128 | "type": "$session.set",
129 | "options": {
130 | "domain": "ROOT",
131 | "header": {
132 | "X-User-Email": "{{$jason.email}}",
133 | "X-User-Token": "{{$jason.authentication_token}}"
134 | }
135 | },
136 | "success": {
137 | "type": "$href",
138 | "options": {
139 | "url": "ROOT/posts.json",
140 | "transition": "replace"
141 | }
142 | }
143 | },
144 | "error": {
145 | "type": "$util.banner",
146 | "options": {
147 | "title": "Enter credentials",
148 | "description": "Please enter both email and password"
149 | }
150 | }
151 | }
152 | }]
153 | }]
154 | }
155 | }
156 | }
157 |
--------------------------------------------------------------------------------
/Gemfile.lock:
--------------------------------------------------------------------------------
1 | GEM
2 | remote: http://rubygems.org/
3 | specs:
4 | actionmailer (4.2.4)
5 | actionpack (= 4.2.4)
6 | actionview (= 4.2.4)
7 | activejob (= 4.2.4)
8 | mail (~> 2.5, >= 2.5.4)
9 | rails-dom-testing (~> 1.0, >= 1.0.5)
10 | actionpack (4.2.4)
11 | actionview (= 4.2.4)
12 | activesupport (= 4.2.4)
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.4)
18 | activesupport (= 4.2.4)
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 | activejob (4.2.4)
24 | activesupport (= 4.2.4)
25 | globalid (>= 0.3.0)
26 | activemodel (4.2.4)
27 | activesupport (= 4.2.4)
28 | builder (~> 3.1)
29 | activerecord (4.2.4)
30 | activemodel (= 4.2.4)
31 | activesupport (= 4.2.4)
32 | arel (~> 6.0)
33 | activesupport (4.2.4)
34 | i18n (~> 0.7)
35 | json (~> 1.7, >= 1.7.7)
36 | minitest (~> 5.1)
37 | thread_safe (~> 0.3, >= 0.3.4)
38 | tzinfo (~> 1.1)
39 | arel (6.0.3)
40 | bcrypt (3.1.11)
41 | binding_of_caller (0.7.2)
42 | debug_inspector (>= 0.0.1)
43 | builder (3.2.2)
44 | byebug (9.0.6)
45 | coffee-rails (4.1.1)
46 | coffee-script (>= 2.2.0)
47 | railties (>= 4.0.0, < 5.1.x)
48 | coffee-script (2.4.1)
49 | coffee-script-source
50 | execjs
51 | coffee-script-source (1.10.0)
52 | concurrent-ruby (1.0.2)
53 | debug_inspector (0.0.2)
54 | devise (4.2.0)
55 | bcrypt (~> 3.0)
56 | orm_adapter (~> 0.1)
57 | railties (>= 4.1.0, < 5.1)
58 | responders
59 | warden (~> 1.2.3)
60 | erubis (2.7.0)
61 | execjs (2.7.0)
62 | globalid (0.3.7)
63 | activesupport (>= 4.1.0)
64 | i18n (0.7.0)
65 | jbuilder (2.6.0)
66 | activesupport (>= 3.0.0, < 5.1)
67 | multi_json (~> 1.2)
68 | jquery-rails (4.2.1)
69 | rails-dom-testing (>= 1, < 3)
70 | railties (>= 4.2.0)
71 | thor (>= 0.14, < 2.0)
72 | json (1.8.3)
73 | loofah (2.0.3)
74 | nokogiri (>= 1.5.9)
75 | mail (2.6.4)
76 | mime-types (>= 1.16, < 4)
77 | mime-types (3.1)
78 | mime-types-data (~> 3.2015)
79 | mime-types-data (3.2016.0521)
80 | mini_portile2 (2.1.0)
81 | minitest (5.9.1)
82 | multi_json (1.12.1)
83 | nokogiri (1.6.8.1)
84 | mini_portile2 (~> 2.1.0)
85 | orm_adapter (0.5.0)
86 | pg (0.18.3)
87 | rack (1.6.4)
88 | rack-test (0.6.3)
89 | rack (>= 1.0)
90 | rails (4.2.4)
91 | actionmailer (= 4.2.4)
92 | actionpack (= 4.2.4)
93 | actionview (= 4.2.4)
94 | activejob (= 4.2.4)
95 | activemodel (= 4.2.4)
96 | activerecord (= 4.2.4)
97 | activesupport (= 4.2.4)
98 | bundler (>= 1.3.0, < 2.0)
99 | railties (= 4.2.4)
100 | sprockets-rails
101 | rails-deprecated_sanitizer (1.0.3)
102 | activesupport (>= 4.2.0.alpha)
103 | rails-dom-testing (1.0.7)
104 | activesupport (>= 4.2.0.beta, < 5.0)
105 | nokogiri (~> 1.6.0)
106 | rails-deprecated_sanitizer (>= 1.0.1)
107 | rails-html-sanitizer (1.0.3)
108 | loofah (~> 2.0)
109 | rails_12factor (0.0.3)
110 | rails_serve_static_assets
111 | rails_stdout_logging
112 | rails_serve_static_assets (0.0.4)
113 | rails_stdout_logging (0.0.4)
114 | railties (4.2.4)
115 | actionpack (= 4.2.4)
116 | activesupport (= 4.2.4)
117 | rake (>= 0.8.7)
118 | thor (>= 0.18.1, < 2.0)
119 | rake (11.3.0)
120 | rdoc (4.2.2)
121 | json (~> 1.4)
122 | responders (2.3.0)
123 | railties (>= 4.2.0, < 5.1)
124 | sass (3.4.22)
125 | sass-rails (5.0.6)
126 | railties (>= 4.0.0, < 6)
127 | sass (~> 3.1)
128 | sprockets (>= 2.8, < 4.0)
129 | sprockets-rails (>= 2.0, < 4.0)
130 | tilt (>= 1.1, < 3)
131 | sdoc (0.4.2)
132 | json (~> 1.7, >= 1.7.7)
133 | rdoc (~> 4.0)
134 | simple_token_authentication (1.14.0)
135 | actionmailer (>= 3.2.6, < 6)
136 | actionpack (>= 3.2.6, < 6)
137 | devise (>= 3.2, < 6)
138 | spring (2.0.0)
139 | activesupport (>= 4.2)
140 | sprockets (3.7.0)
141 | concurrent-ruby (~> 1.0)
142 | rack (> 1, < 3)
143 | sprockets-rails (3.2.0)
144 | actionpack (>= 4.0)
145 | activesupport (>= 4.0)
146 | sprockets (>= 3.0.0)
147 | sqlite3 (1.3.12)
148 | thor (0.19.1)
149 | thread_safe (0.3.5)
150 | tilt (2.0.5)
151 | turbolinks (5.0.1)
152 | turbolinks-source (~> 5)
153 | turbolinks-source (5.0.0)
154 | tzinfo (1.2.2)
155 | thread_safe (~> 0.1)
156 | uglifier (3.0.2)
157 | execjs (>= 0.3.0, < 3)
158 | warden (1.2.6)
159 | rack (>= 1.0)
160 | web-console (2.3.0)
161 | activemodel (>= 4.0)
162 | binding_of_caller (>= 0.7.2)
163 | railties (>= 4.0)
164 | sprockets-rails (>= 2.0, < 4.0)
165 |
166 | PLATFORMS
167 | ruby
168 |
169 | DEPENDENCIES
170 | byebug
171 | coffee-rails (~> 4.1.0)
172 | devise
173 | jbuilder (~> 2.0)
174 | jquery-rails
175 | pg
176 | rails (= 4.2.4)
177 | rails_12factor
178 | sass-rails (~> 5.0)
179 | sdoc (~> 0.4.0)
180 | simple_token_authentication (~> 1.0)
181 | spring
182 | sqlite3
183 | turbolinks
184 | uglifier (>= 1.3.0)
185 | web-console (~> 2.0)
186 |
187 | BUNDLED WITH
188 | 1.10.6
189 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Introduction
2 | A simple microblog app for Jasonette.
3 |
4 | ---
5 |
6 | # Features
7 | Includes both backend / frontend code.
8 |
9 | The backend is just a simple rails app with devise-powered account system.
10 |
11 | The frontend code is just two JSON files:
12 |
13 | - [Display posts](app/views/posts/index.json.jbuilder)
14 | - [Login screen](public/login.json)
15 |
16 | These two JSON files turn into a native iOS app, powered by [Jasonette](http://www.jasonette.com/beta)
17 |
18 | Signed out | Signed in
19 | -----------|--------------------
20 |  | 
21 |
22 | ---
23 |
24 | # Demo
25 | 1. Get [Jasonette](http://www.jasonette.com/beta)
26 | 2. Set the URL to [http://sessionjason.herokuapp.com/posts.json](http://sessionjason.herokuapp.com/posts.json)
27 |
28 | If you don't know how to use Jasonette, [check out the tutorial](https://jasonette.github.io/documentation)
29 |
30 | ---
31 |
32 | # How this was built
33 | ## Backend
34 | The backend is built with ruby on rails.
35 |
36 | Follow the steps below to recreate this project on your own:
37 |
38 | ### 1. Create a project
39 |
40 | $ rails new jasonserver
41 |
42 | ### 2. Generate scaffold
43 | It's going to be just a simple app with a post, and each post belongs_to a user.
44 |
45 | $ rails generate scaffold Post content:text user_id:integer
46 |
47 | ### 3. Implement Devise and token authentication
48 | We will use [devise](https://github.com/plataformatec/devise) for authentication.
49 |
50 | Also, we will use [simple_token_authentication gem](https://github.com/gonzalo-bulnes/simple_token_authentication) for implementing token authentication on top of devise.
51 |
52 | ```ruby
53 | # in Gemfile
54 | gem 'devise'
55 | gem 'simple_token_authentication', '~> 1.0'
56 | ```
57 |
58 | Then we run the usual devise install commands, creating a `User` model and letting devise take over.
59 |
60 | $ rails generate devise:install
61 |
62 | $ rails generate devise User
63 |
64 | Then we add an `authentication_token` field to `User`.
65 |
66 | $ rails g migration add_authentication_token_to_users "authentication_token:string{30}:uniq"
67 |
68 | To integrate the [simple_token_authentication gem](https://github.com/gonzalo-bulnes/simple_token_authentication), we add the line **acts_as_token_authenticatable**, like below:
69 |
70 | ```ruby
71 | # in User.rb
72 | class User < ActiveRecord::Base
73 | acts_as_token_authenticatable
74 | devise :database_authenticatable, :registerable,
75 | :recoverable, :rememberable, :trackable, :validatable
76 | end
77 | ```
78 |
79 | Notice we've removed `:confirmable` devise attribute from the second line, which devise generated for us, since we won't use email confirmation for sign up.
80 |
81 | Lastly, migrate.
82 |
83 | $ rake db:migrate
84 |
85 | ### 4. Add authentication to controllers
86 |
87 | Add the `:authenticate_user!` line to `posts_controller.rb` so that it authenticates before calling any actions.
88 |
89 | ```ruby
90 | # in posts_controller.rb
91 | class PostsController < ApplicationController
92 |
93 | before_action :authenticate_user!
94 | ...
95 |
96 | end
97 | ```
98 |
99 | Also make `application_controller.rb` token authenticatable:
100 |
101 | ```ruby
102 | # in application_controller.rb
103 | class ApplicationController < ActionController::Base
104 | acts_as_token_authentication_handler_for User
105 | respond_to :html, :json
106 | protect_from_forgery with: :null_session
107 | end
108 | ```
109 |
110 | ### 5. Set up associations
111 |
112 | Add `has_many :posts` to `User` model, and `belongs_to :user` to `Post` model.
113 |
114 | ```ruby
115 | # in User.rb
116 | class User < ActiveRecord::Base
117 | has_many :posts
118 | acts_as_token_authenticatable
119 | devise :database_authenticatable, :registerable,
120 | :recoverable, :rememberable, :trackable, :validatable
121 | end
122 |
123 | # in Post.rb
124 | class Post < ActiveRecord::Base
125 | belongs_to :user
126 | end
127 | ```
128 |
129 | Also don't forget to update `new` and `create` actions so they tie each post with user accounts.
130 |
131 | ```ruby
132 | # in posts_controller.rb
133 | class PostsController < ApplicationController
134 |
135 | ...
136 |
137 | def new
138 | @post = current_user.posts.build
139 | end
140 |
141 | def create
142 | @post = current_user.posts.build(post_params)
143 | end
144 |
145 | ...
146 |
147 | end
148 | ```
149 |
150 | ### 6. Update route
151 |
152 | We want the root route to map to `posts#index`. Update `config/routes.rb`
153 |
154 | ```ruby
155 | # in config/routes.rb
156 |
157 | root "posts#index"
158 | ```
159 |
160 | ### 7. Override `authenticate_user!` to handle html and json separately
161 |
162 | ```ruby
163 | class ApplicationController < ActionController::Base
164 | acts_as_token_authentication_handler_for User
165 | respond_to :html, :json
166 | protect_from_forgery with: :null_session
167 |
168 | protected
169 | def authenticate_user!
170 | if self.request.format.html?
171 | super
172 | elsif self.request.format.json?
173 | if self.request.parameters["controller"].start_with?("devise")
174 | # use the default if session related
175 | super
176 | else
177 | # others
178 | if user_signed_in?
179 | # use the default if already signed in
180 | super
181 | else
182 | # serve the static login page if not signed in
183 | @data = File.read("#{Rails.root}/public/login.json")
184 | @data = @data.gsub(/ROOT/, root_url)
185 | render :json => @data
186 | end
187 | end
188 | end
189 | end
190 | end
191 | ```
192 |
193 | ### 8. If deploying to Heroku (optional)
194 |
195 | Don't forget to add these to your Gemfile if you're deploying to heroku:
196 |
197 | ```ruby
198 | # in Gemfile
199 | gem 'sqlite3', group: :development
200 | gem 'pg', group: :production
201 | gem 'rails_12factor', group: :production
202 | ```
203 |
204 | Now the backend API is ready!
205 |
206 | ---
207 |
208 | ## JSON Frontend
209 |
210 | Now that our backend is ready, let's write the JSON that will power our iOS app.
211 |
212 | If you look at the `authenticate_user!` logic above, it renders a json content located at [public/login.json](public/login.json) if a user is not signed in.
213 |
214 | That's the JSON markup for a login page. The sign in button part looks like this:
215 |
216 | ```json
217 | ...
218 | "text": "Sign in >",
219 | "action": {
220 | "type": "$network.request",
221 | "options": {
222 | "url": "ROOT/users/sign_in.json",
223 | "method": "post",
224 | "data": {
225 | "user[email]": "{{$get.email}}",
226 | "user[password]": "{{$get.password}}"
227 | }
228 | },
229 | "success": {
230 | "type": "$session.set",
231 | "options": {
232 | "domain": "ROOT",
233 | "header": {
234 | "X-User-Email": "{{$jason.email}}",
235 | "X-User-Token": "{{$jason.authentication_token}}"
236 | }
237 | },
238 | "success": {
239 | "type": "$href",
240 | "options": {
241 | "url": "ROOT/posts.json",
242 | "transition": "replace"
243 | }
244 | }
245 | },
246 | "error": {
247 | "type": "$util.banner",
248 | "options": {
249 | "title": "Error",
250 | "description": "Something went wrong. Please check if you entered your email and password correctly"
251 | }
252 | }
253 | }
254 | ...
255 | ```
256 |
257 | If you scroll up to the `authenticate_user!` code, you'll see that it replaces `ROOT` with `root_url`, before returning the response:
258 |
259 | ```ruby
260 | @data = @data.gsub(/ROOT/, root_url)
261 | ```
262 |
263 | So here's what will happen when a user taps **Sign in**.
264 |
265 | #### 1. It first makes a `$network.request` to the sign in url, to which the server returns a response that looks something like this:
266 |
267 | ```json
268 | {
269 | "id":2,
270 | "email":"ethan@ethan.fm",
271 | "created_at":"2016-10-14T22:55:00.664Z",
272 | "updated_at":"2016-10-15T05:22:41.730Z",
273 | "authentication_token":"fnekz4hf7ghw95m6ks0rf01j"
274 | }
275 | ```
276 |
277 | #### 2. Then it goes on to the next action which is `$session.set`. This stores the session using the response from the preceding $network.request action.
278 |
279 | #### 3. Then it reloads ROOT/posts.json. This time the session is set and is automatically attached to the request, therefore successfully loading the posts JSON.
280 |
--------------------------------------------------------------------------------
/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 | # The secret key used by Devise. Devise uses this key to generate
5 | # random tokens. Changing this key will render invalid all existing
6 | # confirmation, reset password and unlock tokens in the database.
7 | # Devise will use the `secret_key_base` as its `secret_key`
8 | # by default. You can change it below and use your own secret key.
9 | # config.secret_key = 'a9043df960791c6897a126e8e9c1fd1d20e80c9c0eaf1b548345c368dfcd5f5ee3c820e01d73bb0e645227ea316c94682e4b5da509343b7a22e4be47fbc94a32'
10 |
11 | # ==> Mailer Configuration
12 | # Configure the e-mail address which will be shown in Devise::Mailer,
13 | # note that it will be overwritten if you use your own mailer class
14 | # with default "from" parameter.
15 | config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com'
16 |
17 | # Configure the class responsible to send e-mails.
18 | # config.mailer = 'Devise::Mailer'
19 |
20 | # Configure the parent class responsible to send e-mails.
21 | # config.parent_mailer = 'ActionMailer::Base'
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 | # When false, Devise will not attempt to reload routes on eager load.
94 | # This can reduce the time taken to boot the app but if your application
95 | # requires the Devise mappings to be loaded during boot time the application
96 | # won't boot properly.
97 | # config.reload_routes = true
98 |
99 | # ==> Configuration for :database_authenticatable
100 | # For bcrypt, this is the cost for hashing the password and defaults to 11. If
101 | # using other algorithms, it sets how many times you want the password to be hashed.
102 | #
103 | # Limiting the stretches to just one in testing will increase the performance of
104 | # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
105 | # a value less than 10 in other environments. Note that, for bcrypt (the default
106 | # algorithm), the cost increases exponentially with the number of stretches (e.g.
107 | # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
108 | config.stretches = Rails.env.test? ? 1 : 11
109 |
110 | # Set up a pepper to generate the hashed password.
111 | # config.pepper = '1cd5f02343371dfa46cc75febf4b9224ce6d42f0a2329fd3f4e0042389111d888f9df2cd7250f3c4bcec5d407989dc1c1156b1685ca077469b74a0e79f16f130'
112 |
113 | # Send a notification email when the user's password is changed
114 | # config.send_password_change_notification = false
115 |
116 | # ==> Configuration for :confirmable
117 | # A period that the user is allowed to access the website even without
118 | # confirming their account. For instance, if set to 2.days, the user will be
119 | # able to access the website for two days without confirming their account,
120 | # access will be blocked just in the third day. Default is 0.days, meaning
121 | # the user cannot access the website without confirming their account.
122 | # config.allow_unconfirmed_access_for = 2.days
123 |
124 | # A period that the user is allowed to confirm their account before their
125 | # token becomes invalid. For example, if set to 3.days, the user can confirm
126 | # their account within 3 days after the mail was sent, but on the fourth day
127 | # their account can't be confirmed with the token any more.
128 | # Default is nil, meaning there is no restriction on how long a user can take
129 | # before confirming their account.
130 | # config.confirm_within = 3.days
131 |
132 | # If true, requires any email changes to be confirmed (exactly the same way as
133 | # initial account confirmation) to be applied. Requires additional unconfirmed_email
134 | # db field (see migrations). Until confirmed, new email is stored in
135 | # unconfirmed_email column, and copied to email column on successful confirmation.
136 | config.reconfirmable = true
137 |
138 | # Defines which key will be used when confirming an account
139 | # config.confirmation_keys = [:email]
140 |
141 | # ==> Configuration for :rememberable
142 | # The time the user will be remembered without asking for credentials again.
143 | # config.remember_for = 2.weeks
144 |
145 | # Invalidates all the remember me tokens when the user signs out.
146 | config.expire_all_remember_me_on_sign_out = true
147 |
148 | # If true, extends the user's remember period when remembered via cookie.
149 | # config.extend_remember_period = false
150 |
151 | # Options to be passed to the created cookie. For instance, you can set
152 | # secure: true in order to force SSL only cookies.
153 | # config.rememberable_options = {}
154 |
155 | # ==> Configuration for :validatable
156 | # Range for password length.
157 | config.password_length = 6..128
158 |
159 | # Email regex used to validate email formats. It simply asserts that
160 | # one (and only one) @ exists in the given string. This is mainly
161 | # to give user feedback and not to assert the e-mail validity.
162 | config.email_regexp = /\A[^@\s]+@[^@\s]+\z/
163 |
164 | # ==> Configuration for :timeoutable
165 | # The time you want to timeout the user session without activity. After this
166 | # time the user will be asked for credentials again. Default is 30 minutes.
167 | # config.timeout_in = 30.minutes
168 |
169 | # ==> Configuration for :lockable
170 | # Defines which strategy will be used to lock an account.
171 | # :failed_attempts = Locks an account after a number of failed attempts to sign in.
172 | # :none = No lock strategy. You should handle locking by yourself.
173 | # config.lock_strategy = :failed_attempts
174 |
175 | # Defines which key will be used when locking and unlocking an account
176 | # config.unlock_keys = [:email]
177 |
178 | # Defines which strategy will be used to unlock an account.
179 | # :email = Sends an unlock link to the user email
180 | # :time = Re-enables login after a certain amount of time (see :unlock_in below)
181 | # :both = Enables both strategies
182 | # :none = No unlock strategy. You should handle unlocking by yourself.
183 | # config.unlock_strategy = :both
184 |
185 | # Number of authentication tries before locking an account if lock_strategy
186 | # is failed attempts.
187 | # config.maximum_attempts = 20
188 |
189 | # Time interval to unlock the account if :time is enabled as unlock_strategy.
190 | # config.unlock_in = 1.hour
191 |
192 | # Warn on the last attempt before the account is locked.
193 | # config.last_attempt_warning = true
194 |
195 | # ==> Configuration for :recoverable
196 | #
197 | # Defines which key will be used when recovering the password for an account
198 | # config.reset_password_keys = [:email]
199 |
200 | # Time interval you can reset your password with a reset password key.
201 | # Don't put a too small interval or your users won't have the time to
202 | # change their passwords.
203 | config.reset_password_within = 6.hours
204 |
205 | # When set to false, does not sign a user in automatically after their password is
206 | # reset. Defaults to true, so a user is signed in automatically after a reset.
207 | # config.sign_in_after_reset_password = true
208 |
209 | # ==> Configuration for :encryptable
210 | # Allow you to use another hashing or encryption algorithm besides bcrypt (default).
211 | # You can use :sha1, :sha512 or algorithms from others authentication tools as
212 | # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20
213 | # for default behavior) and :restful_authentication_sha1 (then you should set
214 | # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper).
215 | #
216 | # Require the `devise-encryptable` gem when using anything other than bcrypt
217 | # config.encryptor = :sha512
218 |
219 | # ==> Scopes configuration
220 | # Turn scoped views on. Before rendering "sessions/new", it will first check for
221 | # "users/sessions/new". It's turned off by default because it's slower if you
222 | # are using only default views.
223 | # config.scoped_views = false
224 |
225 | # Configure the default scope given to Warden. By default it's the first
226 | # devise role declared in your routes (usually :user).
227 | # config.default_scope = :user
228 |
229 | # Set this configuration to false if you want /users/sign_out to sign out
230 | # only the current scope. By default, Devise signs out all scopes.
231 | # config.sign_out_all_scopes = true
232 |
233 | # ==> Navigation configuration
234 | # Lists the formats that should be treated as navigational. Formats like
235 | # :html, should redirect to the sign in page when the user does not have
236 | # access, but formats like :xml or :json, should return 401.
237 | #
238 | # If you have any extra navigational formats, like :iphone or :mobile, you
239 | # should add them to the navigational formats lists.
240 | #
241 | # The "*/*" below is required to match Internet Explorer requests.
242 | # config.navigational_formats = ['*/*', :html]
243 |
244 | # The default HTTP method used to sign out a resource. Default is :delete.
245 | config.sign_out_via = :delete
246 |
247 | # ==> OmniAuth
248 | # Add a new OmniAuth provider. Check the wiki for more information on setting
249 | # up on your models and hooks.
250 | # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
251 |
252 | # ==> Warden configuration
253 | # If you want to use other strategies, that are not supported by Devise, or
254 | # change the failure app, you can configure them inside the config.warden block.
255 | #
256 | # config.warden do |manager|
257 | # manager.intercept_401 = false
258 | # manager.default_strategies(scope: :user).unshift :some_external_strategy
259 | # end
260 |
261 | # ==> Mountable engine configurations
262 | # When using Devise inside an engine, let's call it `MyEngine`, and this engine
263 | # is mountable, there are some extra configurations to be taken into account.
264 | # The following options are available, assuming the engine is mounted as:
265 | #
266 | # mount MyEngine, at: '/my_engine'
267 | #
268 | # The router that invoked `devise_for`, in the example above, would be:
269 | # config.router_name = :my_engine
270 | #
271 | # When using OmniAuth, Devise cannot automatically set OmniAuth path,
272 | # so you need to do it manually. For the users scope, it would be:
273 | # config.omniauth_path_prefix = '/my_engine/users/auth'
274 | end
275 |
--------------------------------------------------------------------------------