tok 0.0.1.pre

Sign up to get free protection for your applications and to get access to all the features.
Files changed (68) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +20 -0
  3. data/.rspec +3 -0
  4. data/.travis.yml +10 -0
  5. data/Gemfile +3 -0
  6. data/LICENSE.txt +22 -0
  7. data/README.md +62 -0
  8. data/Rakefile +22 -0
  9. data/app/controllers/tok/base_controller.rb +11 -0
  10. data/app/controllers/tok/sessions_controller.rb +21 -0
  11. data/app/controllers/tok/users_controller.rb +14 -0
  12. data/config/routes.rb +5 -0
  13. data/db/migrate/20141011022222_create_users.rb +13 -0
  14. data/lib/generators/tok/install_generator.rb +55 -0
  15. data/lib/generators/tok/templates/migration/create_model.rb +13 -0
  16. data/lib/generators/tok/templates/model.rb +3 -0
  17. data/lib/generators/tok/templates/tok.rb +38 -0
  18. data/lib/tok.rb +19 -0
  19. data/lib/tok/authentication.rb +53 -0
  20. data/lib/tok/configuration.rb +41 -0
  21. data/lib/tok/controller.rb +64 -0
  22. data/lib/tok/engine.rb +26 -0
  23. data/lib/tok/version.rb +3 -0
  24. data/spec/controllers/sessions_controller_spec.rb +62 -0
  25. data/spec/controllers/users_controller_spec.rb +28 -0
  26. data/spec/dummy/README.rdoc +28 -0
  27. data/spec/dummy/Rakefile +6 -0
  28. data/spec/dummy/app/assets/images/.keep +0 -0
  29. data/spec/dummy/app/controllers/application_controller.rb +2 -0
  30. data/spec/dummy/app/controllers/concerns/.keep +0 -0
  31. data/spec/dummy/app/mailers/.keep +0 -0
  32. data/spec/dummy/app/models/.keep +0 -0
  33. data/spec/dummy/app/models/concerns/.keep +0 -0
  34. data/spec/dummy/bin/bundle +3 -0
  35. data/spec/dummy/bin/rails +4 -0
  36. data/spec/dummy/bin/rake +4 -0
  37. data/spec/dummy/config.ru +4 -0
  38. data/spec/dummy/config/application.rb +30 -0
  39. data/spec/dummy/config/boot.rb +4 -0
  40. data/spec/dummy/config/database.yml +85 -0
  41. data/spec/dummy/config/environment.rb +5 -0
  42. data/spec/dummy/config/environments/development.rb +28 -0
  43. data/spec/dummy/config/environments/production.rb +67 -0
  44. data/spec/dummy/config/environments/test.rb +39 -0
  45. data/spec/dummy/config/initializers/secret_token.rb +19 -0
  46. data/spec/dummy/config/initializers/wrap_parameters.rb +13 -0
  47. data/spec/dummy/config/locales/en.yml +23 -0
  48. data/spec/dummy/config/routes.rb +56 -0
  49. data/spec/dummy/config/secrets.yml +22 -0
  50. data/spec/dummy/db/schema.rb +29 -0
  51. data/spec/dummy/lib/assets/.keep +0 -0
  52. data/spec/dummy/lib/tasks/.keep +0 -0
  53. data/spec/dummy/log/.keep +0 -0
  54. data/spec/dummy/public/404.html +67 -0
  55. data/spec/dummy/public/422.html +67 -0
  56. data/spec/dummy/public/500.html +66 -0
  57. data/spec/dummy/public/favicon.ico +0 -0
  58. data/spec/dummy/public/robots.txt +5 -0
  59. data/spec/factories/users.rb +6 -0
  60. data/spec/generators/install_generator_spec.rb +30 -0
  61. data/spec/routing/routes_spec.rb +57 -0
  62. data/spec/spec_helper.rb +30 -0
  63. data/spec/support/generator_helpers.rb +21 -0
  64. data/spec/support/json_helpers.rb +7 -0
  65. data/spec/tok/configuration_spec.rb +103 -0
  66. data/spec/tok/controller_spec.rb +24 -0
  67. data/tok.gemspec +32 -0
  68. metadata +279 -0
@@ -0,0 +1,64 @@
1
+ module Tok
2
+ module Controller
3
+ extend ActiveSupport::Concern
4
+
5
+ helpers = %w(authenticate! current_user model model_name model_class)
6
+
7
+ included do
8
+ helper_method(*helpers)
9
+ hide_action(*helpers)
10
+ end
11
+
12
+ def authenticate!
13
+ authentication_required unless authorized?
14
+ end
15
+
16
+ def current_user
17
+ model_class.where(authentication_token: token).first
18
+ end
19
+
20
+ def model
21
+ Tok.configuration.model.to_s
22
+ end
23
+
24
+ def model_name
25
+ model.downcase
26
+ end
27
+
28
+ def model_class
29
+ model.constantize
30
+ end
31
+
32
+ private
33
+
34
+ def authentication_required
35
+ self.headers["WWW-Authenticate"] = 'Token realm="Application"'
36
+ render json: {error: "Access denied."}, status: :unauthorized
37
+ end
38
+
39
+ def authorized?
40
+ model = model_class.where(authentication_token: token).first
41
+ model && secure_compare(model.authentication_token, token)
42
+ end
43
+
44
+ def token
45
+ token_header || params[:token]
46
+ end
47
+
48
+ def token_header
49
+ request.headers["HTTP_AUTHORIZATION"].tr('"', '').split('=')[1] if request.headers["HTTP_AUTHORIZATION"]
50
+ end
51
+
52
+ # Adopted from Devise, licensed under MIT.
53
+ # Copyrights 2009 - 2014 Plataformatec.
54
+ def secure_compare(a, b)
55
+ return false if a.blank? || b.blank? || a.bytesize != b.bytesize
56
+
57
+ l = a.unpack "C#{a.bytesize}"
58
+
59
+ res = 0
60
+ b.each_byte { |byte| res |= byte ^ l.shift }
61
+ res == 0
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,26 @@
1
+ require 'tok'
2
+ require 'rails'
3
+
4
+ module Tok
5
+ class Engine < Rails::Engine
6
+ isolate_namespace Tok
7
+
8
+ initializer :append_migrations do |app|
9
+ if model_exist?
10
+ config.paths["db/migrate"].expanded.each do |expanded_path|
11
+ app.config.paths["db/migrate"] << expanded_path
12
+ end
13
+ end
14
+ end
15
+
16
+ initializer :filter_params do |app|
17
+ app.config.filter_parameters += [:encrypted_password, :password, :authentication_token, :token]
18
+ end
19
+
20
+ private
21
+
22
+ def model_exist?
23
+ Rails.env.test? ? true : File.exist?(File.expand_path('app/models/user.rb', Rails.root))
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,3 @@
1
+ module Tok
2
+ VERSION = "0.0.1.pre"
3
+ end
@@ -0,0 +1,62 @@
1
+ describe Tok::SessionsController do
2
+ before do
3
+ class User < ActiveRecord::Base
4
+ include Tok::Authentication
5
+ end
6
+ end
7
+
8
+ describe "#create" do
9
+ context "with valid credentials" do
10
+ subject { attributes_for(:user) }
11
+
12
+ before do
13
+ @user = create(:user)
14
+
15
+ post :create, {user: subject}, {"Accept" => "application/json", "Content-Type" => "application/json"}
16
+ end
17
+
18
+ it { expect(response).to be_success }
19
+ it { expect(response).to have_http_status :created }
20
+ it { expect(response.body).to eq ({token: @user.authentication_token}.to_json) }
21
+ end
22
+
23
+ context "with invalid credentials" do
24
+ subject { attributes_for(:user) }
25
+
26
+ before do
27
+ post :create, {user: subject}, {"Accept" => "application/json", "Content-Type" => "application/json"}
28
+ end
29
+
30
+ it { expect(response).to_not be_success }
31
+ it { expect(response).to have_http_status :unprocessable_entity }
32
+ it { expect(json).to have_key("error") }
33
+ it { expect(json["error"]).to eq "Invalid email or password!" }
34
+ end
35
+ end
36
+
37
+ describe "#destroy" do
38
+ context "when logged in" do
39
+ let(:user_params) { attributes_for(:user) }
40
+
41
+ before do
42
+ @user = create(:user)
43
+ @user.class.authenticate(user_params)
44
+
45
+ delete :destroy, {token: @user.authentication_token}, {"Accept" => "application/json", "Content-Type" => "application/json"}
46
+ end
47
+
48
+ it { expect(response).to be_success }
49
+ it { expect(response).to have_http_status :no_content }
50
+ it { expect{@user.reload}.to change{@user.authentication_token} }
51
+ end
52
+
53
+ context "when not logged in" do
54
+ before do
55
+ delete :destroy, {token: "not-valid"}, {"Accept" => "application/json", "Content-Type" => "application/json"}
56
+ end
57
+
58
+ it { expect(response).to be_success }
59
+ it { expect(response).to have_http_status :no_content }
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,28 @@
1
+ describe Tok::UsersController do
2
+ before do
3
+ class User < ActiveRecord::Base
4
+ include Tok::Authentication
5
+ end
6
+ end
7
+
8
+ describe "#create" do
9
+ context "with valid parameters" do
10
+ subject { attributes_for(:user) }
11
+
12
+ before do
13
+ post :create, {user: subject}, {"Accept" => "application/json", "Content-Type" => "application/json"}
14
+ end
15
+
16
+ it { expect(response).to be_success }
17
+ it { expect(response).to have_http_status(:created) }
18
+ it { expect(response.body).to eq User.last.to_json }
19
+
20
+ it { expect(assigns(:model)).to be_persisted }
21
+ it { expect(assigns(:model)).to eq User.last }
22
+
23
+ it "should increase users count" do
24
+ change(User, :count).by(1)
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,28 @@
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
+ <tt>rake doc:app</tt>.
@@ -0,0 +1,6 @@
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
File without changes
@@ -0,0 +1,2 @@
1
+ class ApplicationController < ActionController::API
2
+ end
File without changes
File without changes
File without changes
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env ruby
2
+ ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
3
+ load Gem.bin_path('bundler', 'bundle')
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env ruby
2
+ APP_PATH = File.expand_path('../../config/application', __FILE__)
3
+ require_relative '../config/boot'
4
+ require 'rails/commands'
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env ruby
2
+ require_relative '../config/boot'
3
+ require 'rake'
4
+ Rake.application.run
@@ -0,0 +1,4 @@
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
@@ -0,0 +1,30 @@
1
+ require File.expand_path('../boot', __FILE__)
2
+
3
+ # Pick the frameworks you want:
4
+ require "active_model/railtie"
5
+ require "active_record/railtie"
6
+ require "action_controller/railtie"
7
+ require "action_mailer/railtie"
8
+ # require "action_view/railtie"
9
+ # require "sprockets/railtie"
10
+ # require "rails/test_unit/railtie"
11
+
12
+ # Require the gems listed in Gemfile, including any gems
13
+ # you've limited to :test, :development, or :production.
14
+ Bundler.require(*Rails.groups)
15
+
16
+ module Dummy
17
+ class Application < Rails::Application
18
+ # Settings in config/environments/* take precedence over those specified here.
19
+ # Application configuration should go into files in config/initializers
20
+ # -- all .rb files in that directory are automatically loaded.
21
+
22
+ # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
23
+ # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
24
+ # config.time_zone = 'Central Time (US & Canada)'
25
+
26
+ # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
27
+ # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
28
+ # config.i18n.default_locale = :de
29
+ end
30
+ end
@@ -0,0 +1,4 @@
1
+ # Set up gems listed in the Gemfile.
2
+ ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
3
+
4
+ require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
@@ -0,0 +1,85 @@
1
+ # PostgreSQL. Versions 8.2 and up are supported.
2
+ #
3
+ # Install the pg driver:
4
+ # gem install pg
5
+ # On OS X with Homebrew:
6
+ # gem install pg -- --with-pg-config=/usr/local/bin/pg_config
7
+ # On OS X with MacPorts:
8
+ # gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config
9
+ # On Windows:
10
+ # gem install pg
11
+ # Choose the win32 build.
12
+ # Install PostgreSQL and put its /bin directory on your path.
13
+ #
14
+ # Configure Using Gemfile
15
+ # gem 'pg'
16
+ #
17
+ default: &default
18
+ adapter: postgresql
19
+ encoding: unicode
20
+ # For details on connection pooling, see rails configuration guide
21
+ # http://guides.rubyonrails.org/configuring.html#database-pooling
22
+ pool: 5
23
+
24
+ development:
25
+ <<: *default
26
+ database: dummy_development
27
+
28
+ # The specified database role being used to connect to postgres.
29
+ # To create additional roles in postgres see `$ createuser --help`.
30
+ # When left blank, postgres will use the default role. This is
31
+ # the same name as the operating system user that initialized the database.
32
+ #username: dummy
33
+
34
+ # The password associated with the postgres role (username).
35
+ #password:
36
+
37
+ # Connect on a TCP socket. Omitted by default since the client uses a
38
+ # domain socket that doesn't need configuration. Windows does not have
39
+ # domain sockets, so uncomment these lines.
40
+ #host: localhost
41
+
42
+ # The TCP port the server listens on. Defaults to 5432.
43
+ # If your server runs on a different port number, change accordingly.
44
+ #port: 5432
45
+
46
+ # Schema search path. The server defaults to $user,public
47
+ #schema_search_path: myapp,sharedapp,public
48
+
49
+ # Minimum log levels, in increasing order:
50
+ # debug5, debug4, debug3, debug2, debug1,
51
+ # log, notice, warning, error, fatal, and panic
52
+ # Defaults to warning.
53
+ #min_messages: notice
54
+
55
+ # Warning: The database defined as "test" will be erased and
56
+ # re-generated from your development database when you run "rake".
57
+ # Do not set this db to the same as development or production.
58
+ test:
59
+ <<: *default
60
+ database: dummy_test
61
+
62
+ # As with config/secrets.yml, you never want to store sensitive information,
63
+ # like your database password, in your source code. If your source code is
64
+ # ever seen by anyone, they now have access to your database.
65
+ #
66
+ # Instead, provide the password as a unix environment variable when you boot
67
+ # the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database
68
+ # for a full rundown on how to provide these environment variables in a
69
+ # production deployment.
70
+ #
71
+ # On Heroku and other platform providers, you may have a full connection URL
72
+ # available as an environment variable. For example:
73
+ #
74
+ # DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase"
75
+ #
76
+ # You can use this database configuration with:
77
+ #
78
+ # production:
79
+ # url: <%= ENV['DATABASE_URL'] %>
80
+ #
81
+ production:
82
+ <<: *default
83
+ database: dummy_production
84
+ username: dummy
85
+ password: <%= ENV['DUMMY_DATABASE_PASSWORD'] %>
@@ -0,0 +1,5 @@
1
+ # Load the Rails application.
2
+ require File.expand_path('../application', __FILE__)
3
+
4
+ # Initialize the Rails application.
5
+ Rails.application.initialize!
@@ -0,0 +1,28 @@
1
+ Rails.application.configure do
2
+ # Settings specified here will take precedence over those in config/application.rb.
3
+
4
+ # In the development environment your application's code is reloaded on
5
+ # every request. This slows down response time but is perfect for development
6
+ # since you don't have to restart the web server when you make code changes.
7
+ config.cache_classes = false
8
+
9
+ # Do not eager load code on boot.
10
+ config.eager_load = false
11
+
12
+ # Show full error reports and disable caching.
13
+ config.consider_all_requests_local = true
14
+ config.action_controller.perform_caching = false
15
+
16
+ # Don't care if the mailer can't send.
17
+ config.action_mailer.raise_delivery_errors = false
18
+
19
+ # Print deprecation notices to the Rails logger.
20
+ config.active_support.deprecation = :log
21
+
22
+ # Raise an error on page load if there are pending migrations.
23
+ config.active_record.migration_error = :page_load
24
+
25
+
26
+ # Raises error for missing translations
27
+ # config.action_view.raise_on_missing_translations = true
28
+ end
@@ -0,0 +1,67 @@
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 nginx, varnish or squid.
20
+ # config.action_dispatch.rack_cache = true
21
+
22
+ # Disable Rails's static asset server (Apache or nginx will already do this).
23
+ config.serve_static_assets = false
24
+
25
+
26
+ # Specifies the header that your server uses for sending files.
27
+ # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
28
+ # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
29
+
30
+ # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
31
+ # config.force_ssl = true
32
+
33
+ # Set to :debug to see everything in the log.
34
+ config.log_level = :info
35
+
36
+ # Prepend all log lines with the following tags.
37
+ # config.log_tags = [ :subdomain, :uuid ]
38
+
39
+ # Use a different logger for distributed setups.
40
+ # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
41
+
42
+ # Use a different cache store in production.
43
+ # config.cache_store = :mem_cache_store
44
+
45
+ # Enable serving of images, stylesheets, and JavaScripts from an asset server.
46
+ # config.action_controller.asset_host = "http://assets.example.com"
47
+
48
+ # Ignore bad email addresses and do not raise email delivery errors.
49
+ # Set this to true and configure the email server for immediate delivery to raise delivery errors.
50
+ # config.action_mailer.raise_delivery_errors = false
51
+
52
+ # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
53
+ # the I18n.default_locale when a translation cannot be found).
54
+ config.i18n.fallbacks = true
55
+
56
+ # Send deprecation notices to registered listeners.
57
+ config.active_support.deprecation = :notify
58
+
59
+ # Disable automatic flushing of the log to improve performance.
60
+ # config.autoflush_log = false
61
+
62
+ # Use default logging formatter so that PID and timestamp are not suppressed.
63
+ config.log_formatter = ::Logger::Formatter.new
64
+
65
+ # Do not dump schema after migrations.
66
+ config.active_record.dump_schema_after_migration = false
67
+ end