devise-token_authenticatable-0.5.2/0000755000004100000410000000000012745444056017373 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/Rakefile0000644000004100000410000000003412745444056021035 0ustar www-datawww-datarequire "bundler/gem_tasks" devise-token_authenticatable-0.5.2/Gemfile0000644000004100000410000000016112745444056020664 0ustar www-datawww-datasource 'https://rubygems.org' # Specify your gem's dependencies in devise-token_authenticatable.gemspec gemspec devise-token_authenticatable-0.5.2/spec/0000755000004100000410000000000012745444056020325 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/factories/0000755000004100000410000000000012745444056022304 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/factories/admin.rb0000644000004100000410000000102112745444056023713 0ustar www-datawww-dataFactoryGirl.define do factory :admin do sequence(:email) { |n| "admin#{n}@domain.com" } password 'some_password' password_confirmation 'some_password' ignore do confirm_account true end after(:create) do |u, evaluator| u.confirm if evaluator.confirm_account end trait :with_reset_password_token do reset_password_token { SecureRandom.hex } end trait :with_authentication_token do authentication_token { SecureRandom.hex } end end end devise-token_authenticatable-0.5.2/spec/factories/user.rb0000644000004100000410000000145312745444056023612 0ustar www-datawww-dataFactoryGirl.define do factory :user do username 'testuser' sequence(:email) { |n| "user#{n}@domain.com" } password 'some_password' password_confirmation 'some_password' facebook_token { SecureRandom.hex } ignore do confirm_account true end after(:create) do |u, evaluator| u.confirm if evaluator.confirm_account end trait :with_reset_password_token do reset_password_token { SecureRandom.hex } end trait :with_authentication_token do authentication_token { SecureRandom.hex } authentication_token_created_at { Time.now } end trait :with_day_old_token do authentication_token { SecureRandom.hex } authentication_token_created_at { Time.now - 1.day } end end end devise-token_authenticatable-0.5.2/spec/spec_helper.rb0000644000004100000410000000202012745444056023135 0ustar www-datawww-dataENV["RAILS_ENV"] ||= 'test' # Required modules require 'rails/all' require 'devise' require 'devise/token_authenticatable' require 'rspec/rails' require 'timecop' require 'pry' # Required spec helper files require 'support/rails_app/config/environment' require 'support/helpers' require 'support/integration' require 'support/session_helper' # factory_girl_rails has to be required after the test rails app # as it sets the right application root path require 'factory_girl_rails' # Do not show migration output ActiveRecord::Migration.verbose = false # RSpec configuration # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| config.use_transactional_fixtures = true config.run_all_when_everything_filtered = true config.include FactoryGirl::Syntax::Methods config.infer_spec_type_from_file_location! config.before(:suite) do # Do initial migration ActiveRecord::Migrator.migrate(File.expand_path("support/rails_app/db/migrate/", File.dirname(__FILE__))) end end devise-token_authenticatable-0.5.2/spec/requests/0000755000004100000410000000000012745444056022200 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/requests/devise/0000755000004100000410000000000012745444056023457 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/requests/devise/token_authenticatable/0000755000004100000410000000000012745444056030014 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/requests/devise/token_authenticatable/strategy_spec.rb0000644000004100000410000003303112745444056033215 0ustar www-datawww-datarequire 'spec_helper' describe Devise::Strategies::TokenAuthenticatable do context "with valid authentication token key and value" do context "through params" do it "should be a success" do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do sign_in_as_new_user_with_token expect(response).to be_success end end it "should set the auth_token parameter" do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do user = sign_in_as_new_user_with_token expect(@request.fullpath).to eq("/users?secret_token=#{user.authentication_token}") end end it "should authenticate user" do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do sign_in_as_new_user_with_token expect(warden).to be_authenticated(:user) end end context "when params with the same key as scope exist" do let(:user) { create(:user, :with_authentication_token) } it 'should be a success' do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do post exhibit_user_path(user), Devise::TokenAuthenticatable.token_authentication_key => user.authentication_token, user: { some: "data" } expect(response).to be_success end end it 'should return proper data' do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do post exhibit_user_path(user), Devise::TokenAuthenticatable.token_authentication_key => user.authentication_token, user: { some: "data" } expect(response.body).to eq('User is authenticated') end end it 'should authenticate user' do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do post exhibit_user_path(user), Devise::TokenAuthenticatable.token_authentication_key => user.authentication_token, user: { some: "data" } expect(warden).to be_authenticated(:user) end end end context "when request is stateless" do it 'should authenticate the user with use of authentication token' do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, skip_session_storage: [:token_auth] do sign_in_as_new_user_with_token expect(warden).to be_authenticated(:user) end end end it 'should redirect to the sign in page' do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, skip_session_storage: [:token_auth] do sign_in_as_new_user_with_token # Try to access a resource that requires authentication get users_path expect(response).to redirect_to new_user_session_path end end end it 'should not store the session' do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, skip_session_storage: [:token_auth] do sign_in_as_new_user_with_token # Try to access a resource that requires authentication get users_path expect(warden).to_not be_authenticated(:user) end end end end context "when request is stateless and timeoutable" do context "on sign in" do it 'should authenticate the user' do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, skip_session_storage: [:token_auth], timeout_in: (0.1).second do sign_in_as_new_user_with_token expect(warden).to be_authenticated(:user) end end end end context "on delayed access" do it 'should authenticate the user' do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, skip_session_storage: [:token_auth], timeout_in: (0.1).second do user = sign_in_as_new_user_with_token # Expiring does not work because we are setting the session value when accessing the resource Timecop.travel(Time.now + (0.3).second) sign_in_as_new_user_with_token(user: user) expect(warden).to be_authenticated(:user) Timecop.return end end end end end context "when not configured" do it "should redirect to sign in page" do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, params_authenticatable: [:database] do sign_in_as_new_user_with_token expect(response).to redirect_to new_user_session_path end end end it "should not authenticate user" do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, params_authenticatable: [:database] do sign_in_as_new_user_with_token expect(warden).to_not be_authenticated(:user) end end end end end context "through http" do it "should be a success" do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, http_authenticatable: true do sign_in_as_new_user_with_token(http_auth: true) expect(response).to be_success end end end it "should authenticate user" do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, http_authenticatable: true do sign_in_as_new_user_with_token(http_auth: true) expect(warden).to be_authenticated(:user) end end end context "when not configured" do it "should be an unauthorized" do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, http_authenticatable: [:database] do sign_in_as_new_user_with_token(http_auth: true) expect(response.status).to eq(401) end end end it "should not authenticate user" do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, http_authenticatable: [:database] do sign_in_as_new_user_with_token(http_auth: true) expect(warden).to_not be_authenticated(:user) end end end end end context "through http header" do it "should redirect to root path" do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, http_authenticatable: true do sign_in_as_new_user_with_token(token_auth: true) expect(response).to be_success end end end it "should not set any token options for Devise" do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, http_authenticatable: true do sign_in_as_new_user_with_token(token_auth: true) expect(request.env['devise.token_options']).to eq({}) end end end it "should authenticate user" do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, http_authenticatable: true do sign_in_as_new_user_with_token(token_auth: true) expect(warden).to be_authenticated(:user) end end end context "with options" do let(:signature) { "**TESTSIGNATURE**" } it "should redirect to root path" do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, http_authenticatable: [:token_options] do sign_in_as_new_user_with_token(token_auth: true, token_options: { signature: signature, nonce: 'def' }) expect(response).to be_success end end end it "should set the signature option" do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, http_authenticatable: [:token_options] do sign_in_as_new_user_with_token(token_auth: true, token_options: { signature: signature, nonce: 'def' }) expect(request.env['devise.token_options'][:signature]).to eq(signature) end end end it "should set the nonce option" do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, http_authenticatable: [:token_options] do sign_in_as_new_user_with_token(token_auth: true, token_options: { signature: signature, nonce: 'def' }) expect(request.env['devise.token_options'][:nonce]).to eq('def') end end end it "should authenticate user" do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, http_authenticatable: [:token_options] do sign_in_as_new_user_with_token(token_auth: true, token_options: { signature: signature, nonce: 'def' }) expect(warden).to be_authenticated(:user) end end end end context "with denied token authorization" do it "should be an unauthorized" do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, http_authenticatable: false do sign_in_as_new_user_with_token(token_auth: true) expect(response.status).to eq(401) end end end it "should not authenticate user" do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do swap Devise, http_authenticatable: false do sign_in_as_new_user_with_token(token_auth: true) expect(warden).to_not be_authenticated(:user) end end end end end end context "with improper authentication token key" do it "should redirect to the sign in page" do swap Devise::TokenAuthenticatable, token_authentication_key: :donald_duck_token do sign_in_as_new_user_with_token(auth_token_key: :secret_token) expect(response).to redirect_to new_user_session_path end end it "should not authenticate user" do swap Devise::TokenAuthenticatable, token_authentication_key: :donald_duck_token do sign_in_as_new_user_with_token(auth_token_key: :secret_token) expect(warden).to_not be_authenticated(:user) end end it "should not be subject to injection" do swap Devise::TokenAuthenticatable, token_authentication_key: :secret_token do user1 = create(:user, :with_authentication_token) create(:user, :with_authentication_token) get users_path(Devise::TokenAuthenticatable.token_authentication_key.to_s + '[$ne]' => user1.authentication_token) expect(warden).to_not be_authenticated(:user) end end end context "with improper authentication token value" do context "through params" do before { sign_in_as_new_user_with_token(auth_token: '*** INVALID TOKEN ***') } it "should redirect to the sign in page" do expect(response).to redirect_to new_user_session_path end it "should not authenticate user" do expect(warden).to_not be_authenticated(:user) end end context "through http header" do before { sign_in_as_new_user_with_token(token_auth: true, auth_token: '*** INVALID TOKEN ***') } it "should be an unauthorized" do expect(response.status).to eq(401) end it "does not authenticate with improper authentication token value in header" do expect(warden).to_not be_authenticated(:user) end end end context "with expired authentication token value" do context "through params" do it "should redirect to the sign in page" do swap Devise::TokenAuthenticatable, token_expires_in: 1.hour do sign_in_as_new_user_with_token(use: :with_day_old_token) expect(response).to redirect_to new_user_session_path end end it "should not authenticate user" do swap Devise::TokenAuthenticatable, token_expires_in: 1.hour do sign_in_as_new_user_with_token(use: :with_day_old_token) expect(warden).to_not be_authenticated(:user) end end context "through http header" do it "should redirect to the sign in page" do swap Devise::TokenAuthenticatable, token_expires_in: 1.hour do swap Devise, http_authenticatable: true do sign_in_as_new_user_with_token(http_auth: true, use: :with_day_old_token) expect(response.status).to eq(401) end end end it "does not authenticate with expired authentication token value in header" do swap Devise::TokenAuthenticatable, token_expires_in: 1.hour do swap Devise, http_authenticatable: true do sign_in_as_new_user_with_token(http_auth: true, use: :with_day_old_token) expect(warden).to_not be_authenticated(:user) end end end end end end end devise-token_authenticatable-0.5.2/spec/token_authenticatable_spec.rb0000644000004100000410000000316512745444056026226 0ustar www-datawww-datarequire 'spec_helper' describe Devise::TokenAuthenticatable do context "configuring the token_expires_in" do let(:expire_time) { 1.hour } it "should set the configuration" do expect { Devise::TokenAuthenticatable.setup do |config| config.token_expires_in = expire_time end }.to change { Devise::TokenAuthenticatable.token_expires_in }.from(nil).to(expire_time) end end context "configuring the token_authentication_key" do let(:new_key) { :other_key } it "should set the configuration" do expect { Devise::TokenAuthenticatable.setup do |config| config.token_authentication_key = new_key end }.to change { Devise::TokenAuthenticatable.token_authentication_key }.from(:auth_token).to(new_key) end end context "configuring the should_reset_authentication_token" do let(:should_reset) { true } it "should set the configuration" do expect { Devise::TokenAuthenticatable.setup do |config| config.should_reset_authentication_token = should_reset end }.to change { Devise::TokenAuthenticatable.should_reset_authentication_token }.from(false).to(should_reset) end end context "configuring the should_ensure_authentication_token" do let(:should_ensure) { true } it "should set the configuration" do expect { Devise::TokenAuthenticatable.setup do |config| config.should_ensure_authentication_token = should_ensure end }.to change { Devise::TokenAuthenticatable.should_ensure_authentication_token }.from(false).to(should_ensure) end end end devise-token_authenticatable-0.5.2/spec/models/0000755000004100000410000000000012745444056021610 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/models/devise/0000755000004100000410000000000012745444056023067 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/models/devise/token_authenticatable/0000755000004100000410000000000012745444056027424 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/models/devise/token_authenticatable/model_spec.rb0000644000004100000410000001502712745444056032070 0ustar www-datawww-datarequire 'spec_helper' ## # If a model that is token authenticatable should be tested with # this shared example the corresponding factory has to provide a trait # +:with_authentication_token+ that sets the attribute +authentication_token+. # # See spec/factories/user.rb for an example. # shared_examples "token authenticatable" do context "instance methods" do describe "#reset_authentication_token" do let(:entity) { create(described_class.name.underscore.to_sym, :with_authentication_token) } subject { entity.reset_authentication_token } it "should reset authentication token" do expect { subject }.to change { entity.authentication_token } end context "token created at" do it "should reset" do swap Devise::TokenAuthenticatable, token_expires_in: 1.hour do expect { subject }.to change { entity.authentication_token_created_at } end end it "should not reset when token expires in not set" do expect { subject }.to_not change { entity.authentication_token_created_at } end end end describe "#ensure_authentication_token" do subject { entity.ensure_authentication_token } context "with existing authentication token" do let(:entity) { create(described_class.name.underscore.to_sym, :with_authentication_token) } it "should not change the authentication token" do expect { subject }.to_not change { entity.authentication_token } end it "should not change the authentication token created at" do expect { subject }.to_not change { entity.authentication_token_created_at } end end context "without existing authentication token and authentication token created at" do let(:entity) { create(described_class.name.underscore.to_sym) } before :each do entity.authentication_token = nil entity.authentication_token_created_at = nil end it "should set an authentication token" do expect { subject }.to change { entity.authentication_token } end context "token created at" do it "should set" do swap Devise::TokenAuthenticatable, token_expires_in: 1.hour do expect { subject }.to change { entity.authentication_token_created_at } end end it "should not set when token expires in disabled" do expect { subject }.to_not change { entity.authentication_token_created_at } end end end end end context "class methods" do describe "#find_for_authentication_token" do let(:entity) { create(described_class.name.underscore.to_sym, :with_authentication_token) } it "should authenticate a valid entity with authentication token and return it" do authenticated_entity = described_class.find_for_token_authentication(auth_token: entity.authentication_token) expect(entity.authentication_token).to eq(authenticated_entity.authentication_token) end it "should authenticate with all the options passed in, not just the auth_token" do conditions = {facebook_token: entity.facebook_token, auth_token: entity.authentication_token} expected_conditions = {facebook_token: entity.facebook_token, authentication_token: entity.authentication_token} expect(described_class).to receive(:find_for_authentication).with(expected_conditions).and_call_original described_class.find_for_token_authentication(conditions) end it "should return nil when authenticating an invalid entity by authentication token" do authenticated_entity = described_class.find_for_token_authentication(auth_token: entity.authentication_token.reverse) expect(authenticated_entity).to be_nil end it "should not be subject to injection" do create(described_class.name.underscore.to_sym, :with_authentication_token) authenticated_entity = described_class.find_for_token_authentication(auth_token: { '$ne' => entity.authentication_token }) expect(authenticated_entity).to be_nil end end describe "#required_fields" do it "should contain the fields that Devise uses when token expires in disabled" do expect(Devise::Models::TokenAuthenticatable.required_fields(described_class)).to eq([ :authentication_token ]) end it "should contain the fields that Devise uses" do swap Devise::TokenAuthenticatable, token_expires_in: 1.hour do expect(Devise::Models::TokenAuthenticatable.required_fields(described_class)).to eq([ :authentication_token, :authentication_token_created_at ]) end end end end context "before_save" do let(:entity) { create(described_class.name.underscore.to_sym, :with_authentication_token) } context "when the authentication token should be reset" do before :each do Devise::TokenAuthenticatable.setup do |config| config.should_reset_authentication_token = true end end after :each do Devise::TokenAuthenticatable.setup do |config| config.should_reset_authentication_token = false end end it "resets the authentication token" do expect(entity).to receive(:reset_authentication_token).once entity.update_attributes(created_at: Time.now) end end context "when the authentication token should not be reset" do it "does not reset the authentication token" do expect(entity).to_not receive(:reset_authentication_token) entity.update_attributes(created_at: Time.now) end end context "when the authentication token should be ensured" do before :each do Devise::TokenAuthenticatable.setup do |config| config.should_ensure_authentication_token = true end end after :each do Devise::TokenAuthenticatable.setup do |config| config.should_ensure_authentication_token = false end end it "sets the authentication token" do expect(entity).to receive(:ensure_authentication_token).once entity.update_attributes(created_at: Time.now) end end context "when the authentication token should not be ensured" do it "does not set the authentication token" do expect(entity).to_not receive(:ensure_authentication_token) entity.update_attributes(created_at: Time.now) end end end end describe User do it_behaves_like "token authenticatable" end devise-token_authenticatable-0.5.2/spec/support/0000755000004100000410000000000012745444056022041 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/support/integration.rb0000644000004100000410000000016612745444056024714 0ustar www-datawww-data# Helpers used in integration testing. # # Shortcut to the warden instance. # def warden request.env['warden'] end devise-token_authenticatable-0.5.2/spec/support/helpers.rb0000644000004100000410000000135112745444056024030 0ustar www-datawww-data# Helpers used for devise testing. # # Execute the block setting the given values in # +new_values+ and restoring the old values # after the block was executed. # def swap(object, new_values) old_values = {} new_values.each do |key, value| old_values[key] = object.send key object.send(:"#{key}=", value) end clear_cached_variables(new_values) yield ensure clear_cached_variables(new_values) old_values.each do |key, value| object.send(:"#{key}=", value) end end def clear_cached_variables(options) if options.key?(:case_insensitive_keys) || options.key?(:strip_whitespace_keys) Devise.mappings.each do |_, mapping| mapping.to.instance_variable_set(:@devise_parameter_filter, nil) end end end devise-token_authenticatable-0.5.2/spec/support/session_helper.rb0000644000004100000410000000203512745444056025410 0ustar www-datawww-data# Helper methods for user sign in with # authentication token. # # Signs in a user via different methods (i.e., HTTP AUTH, # Token Auth, plain). If no user is given with the +options+ # a new one is created. # def sign_in_as_new_user_with_token(options = {}) trait = options[:use] ? options[:use] : :with_authentication_token user = options.delete(:user) || create(:user, trait) options[:auth_token_key] ||= Devise::TokenAuthenticatable.token_authentication_key options[:auth_token] ||= user.authentication_token if options[:http_auth] header = "Basic #{Base64.encode64("#{options[:auth_token]}:X")}" get users_path(format: :xml), {}, "HTTP_AUTHORIZATION" => header elsif options[:token_auth] token_options = options[:token_options] || {} header = ActionController::HttpAuthentication::Token.encode_credentials(options[:auth_token], token_options) get users_path(format: :xml), {}, "HTTP_AUTHORIZATION" => header else get users_path(options[:auth_token_key].to_sym => options[:auth_token]) end user end devise-token_authenticatable-0.5.2/spec/support/rails_app/0000755000004100000410000000000012745444056024013 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/support/rails_app/Rakefile0000644000004100000410000000037112745444056025461 0ustar www-datawww-data# Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require File.expand_path('../config/application', __FILE__) Rails.application.load_tasks devise-token_authenticatable-0.5.2/spec/support/rails_app/db/0000755000004100000410000000000012745444056024400 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/support/rails_app/db/schema.rb0000644000004100000410000000416412745444056026172 0ustar www-datawww-data# This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. ActiveRecord::Schema.define(:version => 20100401102949) do create_table "admins", :force => true do |t| t.string "email" t.string "encrypted_password", :limit => 128 t.string "password_salt" t.string "remember_token" t.datetime "remember_created_at" t.string "reset_password_token" t.integer "failed_attempts", :default => 0 t.string "unlock_token" t.datetime "locked_at" t.datetime "created_at" t.datetime "updated_at" end create_table "users", :force => true do |t| t.string "username" t.string "facebook_token" t.string "email", :default => "", :null => false t.string "encrypted_password", :limit => 128, :default => "", :null => false t.string "confirmation_token" t.datetime "confirmed_at" t.datetime "confirmation_sent_at" t.string "reset_password_token" t.datetime "remember_created_at" t.integer "sign_in_count", :default => 0 t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.integer "failed_attempts", :default => 0 t.string "unlock_token" t.datetime "locked_at" t.string "authentication_token" t.datetime "authentication_token_created_at" t.datetime "created_at" t.datetime "updated_at" end end devise-token_authenticatable-0.5.2/spec/support/rails_app/db/migrate/0000755000004100000410000000000012745444056026030 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/support/rails_app/db/migrate/20100401102949_create_tables.rb0000644000004100000410000000371612745444056032621 0ustar www-datawww-dataclass CreateTables < ActiveRecord::Migration def self.up create_table :users do |t| t.string :username t.string :facebook_token ## Database authenticatable t.string :email, null: false, default: "" t.string :encrypted_password, null: false, default: "" ## Recoverable t.string :reset_password_token t.datetime :reset_password_sent_at ## Rememberable t.datetime :remember_created_at ## Trackable t.integer :sign_in_count, default: 0 t.datetime :current_sign_in_at t.datetime :last_sign_in_at t.string :current_sign_in_ip t.string :last_sign_in_ip ## Confirmable t.string :confirmation_token t.datetime :confirmed_at t.datetime :confirmation_sent_at # t.string :unconfirmed_email # Only if using reconfirmable ## Lockable t.integer :failed_attempts, default: 0 # Only if lock strategy is :failed_attempts t.string :unlock_token # Only if unlock strategy is :email or :both t.datetime :locked_at ## Token authenticatable t.string :authentication_token t.datetime :authentication_token_created_at, null: true t.timestamps end create_table :admins do |t| ## Database authenticatable t.string :email, null: true t.string :encrypted_password, null: true ## Recoverable t.string :reset_password_token t.datetime :reset_password_sent_at ## Rememberable t.datetime :remember_created_at ## Confirmable t.string :confirmation_token t.datetime :confirmed_at t.datetime :confirmation_sent_at t.string :unconfirmed_email # Only if using reconfirmable ## Lockable t.datetime :locked_at ## Attribute for testing route blocks t.boolean :active, default: false t.timestamps end end def self.down drop_table :users drop_table :admins end end devise-token_authenticatable-0.5.2/spec/support/rails_app/public/0000755000004100000410000000000012745444056025271 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/support/rails_app/public/422.html0000644000004100000410000000130712745444056026467 0ustar www-datawww-data The change you wanted was rejected (422)

The change you wanted was rejected.

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

devise-token_authenticatable-0.5.2/spec/support/rails_app/public/favicon.ico0000644000004100000410000000000012745444056027400 0ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/support/rails_app/public/404.html0000644000004100000410000000133012745444056026463 0ustar www-datawww-data The page you were looking for doesn't exist (404)

The page you were looking for doesn't exist.

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

devise-token_authenticatable-0.5.2/spec/support/rails_app/public/500.html0000644000004100000410000000133012745444056026460 0ustar www-datawww-data We're sorry, but something went wrong (500)

We're sorry, but something went wrong.

We've been notified about this issue and we'll take a look at it shortly.

devise-token_authenticatable-0.5.2/spec/support/rails_app/config/0000755000004100000410000000000012745444056025260 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/support/rails_app/config/application.rb0000644000004100000410000000071012745444056030106 0ustar www-datawww-datarequire File.expand_path('../boot', __FILE__) module Devise module TokenAuthenticatable class RailsApp < Rails::Application config.active_support.deprecation = :log config.action_mailer.default_url_options = { host: "localhost", port: 3000 } config.action_mailer.delivery_method = :test config.i18n.enforce_available_locales = false config.eager_load = false end end end devise-token_authenticatable-0.5.2/spec/support/rails_app/config/initializers/0000755000004100000410000000000012745444056027766 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/support/rails_app/config/initializers/secret_token.rb0000644000004100000410000000060612745444056033002 0ustar www-datawww-dataconfig = Rails.application.config if Rails.version.start_with? '4' config.secret_key_base = 'd588e99efff13a86461fd6ab82327823ad2f8feb5dc217ce652cdd9f0dfc5eb4b5a62a92d24d2574d7d51dfb1ea8dd453ea54e00cf672159a13104a135422a10' else config.secret_token = 'ea942c41850d502f2c8283e26bdc57829f471bb18224ddff0a192c4f32cdf6cb5aa0d82b3a7a7adbeb640c4b06f3aa1cd5f098162d8240f669b39d6b49680571' end devise-token_authenticatable-0.5.2/spec/support/rails_app/config/initializers/session_store.rb0000644000004100000410000000013212745444056033206 0ustar www-datawww-dataDevise::TokenAuthenticatable::RailsApp.config.session_store :cookie_store, key: '_my_app' devise-token_authenticatable-0.5.2/spec/support/rails_app/config/initializers/backtrace_silencers.rb0000644000004100000410000000062212745444056034301 0ustar www-datawww-data# Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. Rails.backtrace_cleaner.remove_silencers! devise-token_authenticatable-0.5.2/spec/support/rails_app/config/initializers/devise.rb0000644000004100000410000002000412745444056031566 0ustar www-datawww-data# Use this hook to configure devise mailer, warden hooks and so forth. The first # four configuration values can also be set straight in your models. Devise.setup do |config| config.secret_key = "d9eb5171c59a4c817f68b0de27b8c1e340c2341b52cdbc60d3083d4e8958532" \ "18dcc5f589cafde048faec956b61f864b9b5513ff9ce29bf9e5d58b0f234f8e3b" # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use your own mailer class with default "from" parameter. config.mailer_sender = "please-change-me@config-initializers-devise.com" # Configure the class responsible to send e-mails. # config.mailer = "Devise::Mailer" # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require "devise/orm/active_record" # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. By default is # just :email. You can configure it to use [:username, :subdomain], so for # authenticating a user, both parameters are required. Remember that those # parameters are used only when authenticating and not when retrieving from # session. If you need permissions, you should implement that in a before filter. # You can also supply hash where the value is a boolean expliciting if authentication # should be aborted or not if the value is not present. By default is empty. # config.authentication_keys = [ :email ] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to # find_for_authentication method and considered in your model lookup. For instance, # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. # The same considerations mentioned for authentication_keys also apply to request_keys. # config.request_keys = [] # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [ :email ] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. config.strip_whitespace_keys = [ :email ] # Tell if authentication through request.params is enabled. True by default. # config.params_authenticatable = true # Tell if authentication through HTTP Basic Auth is enabled. False by default. config.http_authenticatable = true # If http headers should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true # The realm used in Http Basic Authentication. "Application" by default. # config.http_authentication_realm = "Application" # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 10. If # using other encryptors, it sets how many times you want the password re-encrypted. config.stretches = Rails.env.test? ? 1 : 10 # ==> Configuration for :confirmable # The time you want to give your user to confirm his account. During this time # he will be able to access your application without confirming. Default is nil. # When allow_unconfirmed_access_for is zero, the user won't be able to sign in without confirming. # You can use this to let your user access some features of your application # without confirming the account, but blocking it after a certain period # (ie 2 days). # config.allow_unconfirmed_access_for = 2.days # Defines which key will be used when confirming an account # config.confirmation_keys = [ :email ] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks # If true, a valid remember token can be re-used between multiple browsers. # config.remember_across_browsers = true # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # ==> Configuration for :validatable # Range for password length. Default is 8..128. # config.password_length = 8..128 # Regex to use to validate the email address # config.email_regexp = /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. # config.timeout_in = 30.minutes # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. # :none = No lock strategy. You should handle locking by yourself. # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account # config.unlock_keys = [ :email ] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email # :time = Re-enables login after a certain amount of time (see :unlock_in below) # :both = Enables both strategies # :none = No unlock strategy. You should handle unlocking by yourself. # config.unlock_strategy = :both # Number of authentication tries before locking an account if lock_strategy # is failed attempts. # config.maximum_attempts = 20 # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account # config.reset_password_keys = [ :email ] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = 2.hours # Setup a pepper to generate the encrypted password. config.pepper = "d142367154e5beacca404b1a6a4f8bc52c6fdcfa3ccc3cf8eb49f3458a688ee6ac3b9fae488432a3bfca863b8a90008368a9f3a3dfbe5a962e64b6ab8f3a3a1a" # ==> Configuration for :token_authenticatable # Defines name of the authentication token params key # config.token_authentication_key = :auth_token # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for # "users/sessions/new". It's turned off by default because it's slower if you # are using only default views. # config.scoped_views = false # Configure the default scope given to Warden. By default it's the first # devise role declared in your routes (usually :user). # config.default_scope = :user # Configure sign_out behavior. # Sign_out action can be scoped (i.e. /users/sign_out affects only :user scope). # The default is true, which means any logout action will sign out all active scopes. # config.sign_out_all_scopes = true # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like # :html, should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. Default is [:html] # config.navigational_formats = [:html, :iphone] # The default HTTP method used to sign out a resource. Default is :get. # config.sign_out_via = :get # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # # config.warden do |manager| # manager.failure_app = AnotherApp # manager.default_strategies(:scope => :user).unshift :some_external_strategy # end end devise-token_authenticatable-0.5.2/spec/support/rails_app/config/initializers/inflections.rb0000644000004100000410000000006612745444056032632 0ustar www-datawww-dataActiveSupport::Inflector.inflections do |inflect| end devise-token_authenticatable-0.5.2/spec/support/rails_app/config/boot.rb0000644000004100000410000000026012745444056026546 0ustar www-datawww-data# Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__) require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE']) devise-token_authenticatable-0.5.2/spec/support/rails_app/config/database.yml0000644000004100000410000000034012745444056027544 0ustar www-datawww-data# SQLite version 3.x # gem install sqlite3-ruby (not necessary on OS X Leopard) development: adapter: sqlite3 database: db/development.sqlite3 pool: 5 timeout: 5000 test: adapter: sqlite3 database: ":memory:" devise-token_authenticatable-0.5.2/spec/support/rails_app/config/routes.rb0000644000004100000410000000710512745444056027131 0ustar www-datawww-dataRails.application.routes.draw do # Resources for testing resources :users, only: [:index] do member do get :expire get :accept get :edit_form put :update_form end authenticate do post :exhibit, on: :member end end resources :admins, only: [:index] do get :expire, on: :member end # Users scope devise_for :users as :user do get "/as/sign_in", to: "devise/sessions#new" end get "/sign_in", to: "devise/sessions#new" # Admin scope devise_for :admin, path: "admin_area", controllers: { sessions: "admins/sessions" }, skip: :passwords get "/admin_area/home", to: "admins#index", as: :admin_root get "/anywhere", to: "foo#bar", as: :new_admin_password authenticate(:admin) do get "/private", to: "home#private", as: :private end authenticate(:admin, lambda { |admin| admin.active? }) do get "/private/active", to: "home#private", as: :private_active end authenticated :admin do get "/dashboard", to: "home#admin_dashboard" end authenticated :admin, lambda { |admin| admin.active? } do get "/dashboard/active", to: "home#admin_dashboard" end authenticated do get "/dashboard", to: "home#user_dashboard" end unauthenticated do get "/join", to: "home#join" end # Routes for constraints testing devise_for :headquarters_admin, class_name: "Admin", path: "headquarters", constraints: { host: /192\.168\.1\.\d\d\d/ } constraints(host: /192\.168\.1\.\d\d\d/) do devise_for :homebase_admin, class_name: "Admin", path: "homebase" end devise_for :skip_admin, class_name: "Admin", skip: :all # Routes for format=false testing devise_for :htmlonly_admin, class_name: "Admin", skip: [:confirmations, :unlocks], path: "htmlonly_admin", format: false, skip_helpers: [:confirmations, :unlocks] devise_for :htmlonly_users, class_name: "User", only: [:confirmations, :unlocks], path: "htmlonly_users", format: false, skip_helpers: true # Other routes for routing_test.rb devise_for :reader, class_name: "User", only: :passwords scope host: "sub.example.com" do devise_for :sub_admin, class_name: "Admin" end namespace :publisher, path_names: { sign_in: "i_dont_care", sign_out: "get_out" } do devise_for :accounts, class_name: "Admin", path_names: { sign_in: "get_in" } end scope ":locale", module: :invalid do devise_for :accounts, singular: "manager", class_name: "Admin", path_names: { sign_in: "login", sign_out: "logout", password: "secret", confirmation: "verification", unlock: "unblock", sign_up: "register", registration: "management", cancel: "giveup" }, failure_app: lambda { |env| [404, { "Content-Type" => "text/plain" }, ["Oops, not found"]] }, module: :devise end namespace :sign_out_via, module: "devise" do devise_for :deletes, sign_out_via: :delete, class_name: "Admin" devise_for :posts, sign_out_via: :post, class_name: "Admin" devise_for :delete_or_posts, sign_out_via: [:delete, :post], class_name: "Admin" end get "/set", to: "home#set" get "/unauthenticated", to: "home#unauthenticated" get "/custom_strategy/new" root to: "home#index", via: [:get, :post] end devise-token_authenticatable-0.5.2/spec/support/rails_app/config/environment.rb0000644000004100000410000000025312745444056030151 0ustar www-datawww-data# Load the rails application. require File.expand_path('../application', __FILE__) # Initialize the rails application. Devise::TokenAuthenticatable::RailsApp.initialize! devise-token_authenticatable-0.5.2/spec/support/rails_app/app/0000755000004100000410000000000012745444056024573 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/support/rails_app/app/views/0000755000004100000410000000000012745444056025730 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/support/rails_app/app/views/users/0000755000004100000410000000000012745444056027071 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/support/rails_app/app/views/users/index.html.erb0000644000004100000410000000004612745444056031635 0ustar www-datawww-dataWelcome User #<%= current_user.id %>! devise-token_authenticatable-0.5.2/spec/support/rails_app/app/controllers/0000755000004100000410000000000012745444056027141 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/support/rails_app/app/controllers/admins/0000755000004100000410000000000012745444056030414 5ustar www-datawww-data././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootdevise-token_authenticatable-0.5.2/spec/support/rails_app/app/controllers/admins/sessions_controller.rbdevise-token_authenticatable-0.5.2/spec/support/rails_app/app/controllers/admins/sessions_controller0000644000004100000410000000024512745444056034451 0ustar www-datawww-dataclass Admins::SessionsController < Devise::SessionsController def new flash[:special] = "Welcome to #{controller_path.inspect} controller!" super end enddevise-token_authenticatable-0.5.2/spec/support/rails_app/app/controllers/users_controller.rb0000644000004100000410000000132012745444056033066 0ustar www-datawww-dataclass UsersController < ApplicationController prepend_before_filter :current_user, only: :exhibit before_filter :authenticate_user!, except: [:accept, :exhibit] respond_to :html, :xml def index user_session[:cart] = "Cart" respond_with(current_user) end def edit_form user_session['last_request_at'] = 31.minutes.ago.utc end def update_form render text: 'Update' end def accept @current_user = current_user end def exhibit render text: current_user ? "User is authenticated" : "User is not authenticated" end def expire user_session['last_request_at'] = 31.minutes.ago.utc render text: 'User will be expired on next request' end end devise-token_authenticatable-0.5.2/spec/support/rails_app/app/controllers/publisher/0000755000004100000410000000000012745444056031136 5ustar www-datawww-data././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootdevise-token_authenticatable-0.5.2/spec/support/rails_app/app/controllers/publisher/registrations_controller.rbdevise-token_authenticatable-0.5.2/spec/support/rails_app/app/controllers/publisher/registrations_co0000644000004100000410000000010412745444056034432 0ustar www-datawww-dataclass Publisher::RegistrationsController < ApplicationController end././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootdevise-token_authenticatable-0.5.2/spec/support/rails_app/app/controllers/publisher/sessions_controller.rbdevise-token_authenticatable-0.5.2/spec/support/rails_app/app/controllers/publisher/sessions_control0000644000004100000410000000007712745444056034473 0ustar www-datawww-dataclass Publisher::SessionsController < ApplicationController enddevise-token_authenticatable-0.5.2/spec/support/rails_app/app/controllers/home_controller.rb0000644000004100000410000000050412745444056032660 0ustar www-datawww-dataclass HomeController < ApplicationController def index end def private end def user_dashboard end def admin_dashboard end def join end def set session["devise.foo_bar"] = "something" head :ok end def unauthenticated render text: "unauthenticated", status: :unauthorized end end devise-token_authenticatable-0.5.2/spec/support/rails_app/app/controllers/application_controller.rb0000644000004100000410000000062412745444056034236 0ustar www-datawww-data# Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base protect_from_forgery before_filter :current_user, unless: :devise_controller? before_filter :authenticate_user!, if: :devise_controller? respond_to *Mime::SET.map(&:to_sym) end devise-token_authenticatable-0.5.2/spec/support/rails_app/app/controllers/admins_controller.rb0000644000004100000410000000036212745444056033205 0ustar www-datawww-dataclass AdminsController < ApplicationController before_filter :authenticate_admin! def index end def expire admin_session['last_request_at'] = 31.minutes.ago.utc render text: 'Admin will be expired on next request' end end devise-token_authenticatable-0.5.2/spec/support/rails_app/app/mailers/0000755000004100000410000000000012745444056026227 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/support/rails_app/app/mailers/users/0000755000004100000410000000000012745444056027370 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/support/rails_app/app/mailers/users/mailer.rb0000644000004100000410000000050212745444056031163 0ustar www-datawww-dataclass Users::Mailer < Devise::Mailer default from: 'custom@example.com' end class Users::ReplyToMailer < Devise::Mailer default from: 'custom@example.com' default reply_to: 'custom_reply_to@example.com' end class Users::FromProcMailer < Devise::Mailer default from: proc { 'custom@example.com' } end devise-token_authenticatable-0.5.2/spec/support/rails_app/app/models/0000755000004100000410000000000012745444056026056 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/spec/support/rails_app/app/models/admin.rb0000644000004100000410000000067712745444056027505 0ustar www-datawww-dataclass Admin < ActiveRecord::Base devise :database_authenticatable, :registerable, :timeoutable, :recoverable, :lockable, :confirmable, unlock_strategy: :time, lock_strategy: :none, allow_unconfirmed_access_for: 2.weeks, reconfirmable: true validates_length_of :reset_password_token, minimum: 3, allow_blank: true validates_uniqueness_of :email, allow_blank: true, if: :email_changed? end devise-token_authenticatable-0.5.2/spec/support/rails_app/app/models/user.rb0000644000004100000410000000123612745444056027363 0ustar www-datawww-dataclass User < ActiveRecord::Base devise :database_authenticatable, :confirmable, :lockable, :recoverable, :registerable, :rememberable, :timeoutable, :token_authenticatable, :trackable, :validatable, reconfirmable: false attr_accessor :other_key def raw_confirmation_token @raw_confirmation_token end module ExtendMethods def new_with_session(params, session) super.tap do |user| if data = session["devise.facebook_data"] user.email = data["email"] user.confirmed_at = Time.now end end end end # They need to be included after Devise is called. extend ExtendMethods end devise-token_authenticatable-0.5.2/spec/support/rails_app/config.ru0000644000004100000410000000023612745444056025631 0ustar www-datawww-data# This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) run RailsApp::Application devise-token_authenticatable-0.5.2/.travis.yml0000644000004100000410000000017612745444056021510 0ustar www-datawww-datalanguage: ruby rvm: - 2.1.9 - 2.2.5 - 2.3.1 before_install: - gem install bundler -v 1.11 script: bundle exec rspec devise-token_authenticatable-0.5.2/lib/0000755000004100000410000000000012745444056020141 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/lib/devise-token_authenticatable.rb0000644000004100000410000000004712745444056026301 0ustar www-datawww-datarequire 'devise/token_authenticatable' devise-token_authenticatable-0.5.2/lib/devise/0000755000004100000410000000000012745444056021420 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/lib/devise/token_authenticatable.rb0000644000004100000410000000236512745444056026310 0ustar www-datawww-datarequire "devise/token_authenticatable/strategy" module Devise module TokenAuthenticatable # Authentication token params key name of choice. E.g. /users/sign_in?some_key=... mattr_accessor :token_authentication_key @@token_authentication_key = :auth_token # Token expiration period. E.g. 1.day mattr_accessor :token_expires_in @@token_expires_in = nil # Defines if the authentication token is reset before the model is saved. mattr_accessor :should_reset_authentication_token @@should_reset_authentication_token = false # Defines if the authentication token is set - if not already - before the model is saved. mattr_accessor :should_ensure_authentication_token @@should_ensure_authentication_token = false # Enable the configuration of the TokenAuthenticatable # strategy with a block: # # Devise::TokenAuthenticatable.setup do |config| # config.token_authentication_key = :other_key # end # def self.setup yield self end end end # Register TokenAuthenticatable module in Devise. Devise::add_module :token_authenticatable, model: 'devise/token_authenticatable/model', strategy: true, no_input: true devise-token_authenticatable-0.5.2/lib/devise/token_authenticatable/0000755000004100000410000000000012745444056025755 5ustar www-datawww-datadevise-token_authenticatable-0.5.2/lib/devise/token_authenticatable/model.rb0000644000004100000410000000653412745444056027412 0ustar www-datawww-datamodule Devise module Models # The +TokenAuthenticatable+ module is responsible for generating an authentication token and # validating the authenticity of the same while signing in. # # This module only provides a few helpers to help you manage the token, but it is up to you # to choose how to use it. # # If you want to delete the token after it is used, you can do so in the # after_token_authentication callback. # # == APIs # # If you are using token authentication with APIs and using trackable. Every # request will be considered as a new sign in (since there is no session in # APIs). You can disable this by creating a before filter as follow: # # before_filter :skip_trackable # # def skip_trackable # request.env['devise.skip_trackable'] = true # end # module TokenAuthenticatable extend ActiveSupport::Concern included do before_save :reset_authentication_token_before_save before_save :ensure_authentication_token_before_save attr_writer :token_expires_in end module ClassMethods def find_for_token_authentication(conditions) auth_conditions = conditions.dup authentication_token = auth_conditions.delete(Devise::TokenAuthenticatable.token_authentication_key) find_for_authentication( auth_conditions.merge(authentication_token: authentication_token) ) end # Generate a token checking if one does not already exist in the database. def authentication_token loop do token = Devise.friendly_token break token unless to_adapter.find_first({ authentication_token: token }) end end end def self.required_fields(klass) fields = [:authentication_token] unless Devise::TokenAuthenticatable.token_expires_in.blank? fields.push(:authentication_token_created_at) end fields end # Generate new authentication token (a.k.a. "single access token"). def reset_authentication_token self.authentication_token = self.class.authentication_token self.authentication_token_created_at = Time.now unless token_expires_in.blank? end # Generate new authentication token and save the record. def reset_authentication_token! reset_authentication_token save(validate: false) end # Generate authentication token unless already exists. def ensure_authentication_token reset_authentication_token if authentication_token.blank? end # Generate authentication token unless already exists and save the record. def ensure_authentication_token! reset_authentication_token! if authentication_token.blank? end # Hook called after token authentication. def after_token_authentication end def token_expires_in Devise::TokenAuthenticatable.token_expires_in end private def reset_authentication_token_before_save reset_authentication_token if Devise::TokenAuthenticatable.should_reset_authentication_token end def ensure_authentication_token_before_save ensure_authentication_token if Devise::TokenAuthenticatable.should_ensure_authentication_token end end end end devise-token_authenticatable-0.5.2/lib/devise/token_authenticatable/strategy.rb0000644000004100000410000000713212745444056030147 0ustar www-datawww-datarequire 'devise/strategies/base' module Devise module Strategies # # The +TokenAuthenticatable+ strategy was extracted from Devise 3.1.0. Its purpose is # to provide the deprecated functionality of the +TokenAuthenticatable+ strategy. The # following description was adapted accordingly. # # See: https://github.com/plataformatec/devise/blob/v3.1/lib/devise/strategies/token_authenticatable.rb # # # Strategy for signing in a user, based on a authenticatable token. This works for both params # and http. For the former, all you need to do is to pass the params in the URL: # # http://myapp.example.com/?user_token=SECRET # # For headers, you can use basic authentication passing the token as username and # blank password. Since some clients may require a password, you can pass "X" as # password and it will simply be ignored. # # You may also pass the token using the Token authentication mechanism provided # by Rails: http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html # The token options are stored in request.env['devise.token_options'] # class TokenAuthenticatable < Authenticatable def store? super && !mapping.to.skip_session_storage.include?(:token_auth) end def valid? super || valid_for_token_auth? end def authenticate! resource = mapping.to.find_for_token_authentication(authentication_hash) return fail(:invalid_token) unless resource unless token_expires_in.blank? if Time.now > (resource.authentication_token_created_at + token_expires_in.to_i) return fail(:expired_token) end end if validate(resource) resource.after_token_authentication success!(resource) end end private # Token Authenticatable can be authenticated with params in any controller and any verb. def valid_params_request? true end # Check if the model accepts this strategy as token authenticatable. def token_authenticatable? mapping.to.http_authenticatable?(:token_options) end # Check if this is strategy is valid for token authentication by: # # * Validating if the model allows http token authentication; # * If the http auth token exists; # * If all authentication keys are present; # def valid_for_token_auth? token_authenticatable? && auth_token.present? && with_authentication_hash(:token_auth, token_auth_hash) end # Extract the auth token from the request def auth_token @auth_token ||= ActionController::HttpAuthentication::Token.token_and_options(request) end # Extract a hash with attributes:values from the auth_token def token_auth_hash request.env['devise.token_options'] = auth_token.last { authentication_keys.first => auth_token.first } end # Try both scoped and non scoped keys def params_auth_hash if params[scope].kind_of?(Hash) && params[scope].has_key?(authentication_keys.first) params[scope] else params end end # Overwrite authentication keys to use token_authentication_key. def authentication_keys @authentication_keys ||= [Devise::TokenAuthenticatable.token_authentication_key] end def token_expires_in @token_expires_in ||= Devise::TokenAuthenticatable.token_expires_in end end end end Warden::Strategies.add(:token_authenticatable, Devise::Strategies::TokenAuthenticatable) devise-token_authenticatable-0.5.2/lib/devise/token_authenticatable/version.rb0000644000004100000410000000012312745444056027763 0ustar www-datawww-datamodule Devise module TokenAuthenticatable VERSION = '0.5.2'.freeze end end devise-token_authenticatable-0.5.2/.gitignore0000644000004100000410000000030212745444056021356 0ustar www-datawww-data*.gem *.rbc *.log .bundle .config .rspec .rspec-local .ruby-version .yardoc Gemfile.lock InstalledFiles _yardoc coverage doc/ lib/bundler/man pkg rdoc spec/reports test/tmp test/version_tmp tmp devise-token_authenticatable-0.5.2/devise-token_authenticatable.gemspec0000644000004100000410000000355112745444056026556 0ustar www-datawww-data# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'devise/token_authenticatable/version' Gem::Specification.new do |spec| spec.name = "devise-token_authenticatable" spec.version = Devise::TokenAuthenticatable::VERSION.dup spec.platform = Gem::Platform::RUBY spec.authors = ["Sebastian Oelke"] spec.email = ["dev@soelke.de"] spec.description = %q{This gem provides the extracted Token Authenticatable module of devise. It enables the user to sign in via an authentication token. This token can be given via a query string or HTTP Basic Authentication.} spec.summary = %q{Provides authentication based on an authentication token for devise 3.2 and up.} spec.homepage = "https://github.com/baschtl/devise-token_authenticatable" spec.license = "MIT" spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_dependency "devise", ">= 4.0.0", "< 4.3.0" spec.add_development_dependency "rails", "~> 4.2" spec.add_development_dependency "rspec-rails", "~> 3.0" spec.add_development_dependency "pry", "~> 0.10" spec.add_development_dependency "factory_girl_rails", "~> 4.4" spec.add_development_dependency "timecop", "~> 0.7" spec.add_development_dependency "bundler", "~> 1.11" # Fix database connection with sqlite3 and jruby if RUBY_ENGINE == 'ruby' spec.add_development_dependency "sqlite3", "~> 1.3" elsif RUBY_ENGINE == 'jruby' spec.add_development_dependency "activerecord-jdbcsqlite3-adapter" end end devise-token_authenticatable-0.5.2/LICENSE0000644000004100000410000000207212745444056020401 0ustar www-datawww-dataThe MIT License (MIT) Copyright (c) 2013 Sebastian Oelke Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. devise-token_authenticatable-0.5.2/README.md0000644000004100000410000000702712745444056020660 0ustar www-datawww-data# Devise::TokenAuthenticatable [![Tag](https://img.shields.io/github/tag/baschtl/devise-token_authenticatable.svg?style=flat-square)](https://github.com/baschtl/devise-token_authenticatable/releases) [![Build Status](https://img.shields.io/travis/baschtl/devise-token_authenticatable.svg?style=flat-square)](https://travis-ci.org/baschtl/devise-token_authenticatable) [![Code Climate](https://img.shields.io/codeclimate/github/baschtl/devise-token_authenticatable.svg?style=flat-square)](https://codeclimate.com/github/baschtl/devise-token_authenticatable) This gem provides the extracted Token Authenticatable module of devise. It includes the functionality that was also in [version 3.1.2](https://github.com/plataformatec/devise/tree/v3.1.2) of devise. With the inclusion of this module a user is able to sign in via an authentication token. This token can be given via a query string or HTTP Basic Authentication. See the hint below to understand which version of this gem supports which version of devise. Use this gem as a starting point for your own token authentication mechanism for devise. Furthermore, if you need token authentication in connection with newer devise releases this gem might be an appropriate solution, too. ## Installation Add this line to your application's Gemfile: gem 'devise-token_authenticatable' And then execute: $ bundle Or install it yourself as: $ gem install devise-token_authenticatable ### Which version to use for which version of devise? *devise-token_authenticatable* | *devise* -------------------------------:|--------- `~> 0.1` | `~> 3.2.0` `~> 0.2` | `~> 3.3.0` `~> 0.3` | `~> 3.4.0` `~> 0.4.0`, `< 0.4.9` | `~> 3.5.0`, `< 3.5.2` `~> 0.4.9` | `~> 3.5.2` `~> 0.5.0` | `>= 4.0.0`, `< 4.3.0` ## Usage Add `:token_authenticatable` to your devise model: ```ruby class User < ActiveRecord::Base devise :database_authenticatable, :token_authenticatable end ``` ## Configuration This gem can be configured as shown in the following: ```ruby Devise::TokenAuthenticatable.setup do |config| # enables the expiration of a token after a specified amount of time, # requires an additional field on the model: `authentication_token_created_at` # defaults to nil config.token_expires_in = 1.day # set the authentication key name used by this module, # defaults to :auth_token config.token_authentication_key = :other_key_name # enable reset of the authentication token before the model is saved, # defaults to false config.should_reset_authentication_token = true # enables the setting of the authentication token - if not already - before the model is saved, # defaults to false config.should_ensure_authentication_token = true end ``` ## Troubleshooting ##### Using a new user's auth token does not result in invalidating an old users session. How can I ignore session storage when using token authentication? Add `:token_auth` to your devise configuration: ```ruby Devise.setup do |config| config.skip_session_storage = [:http_auth, :token_auth] end ``` ## Documentation For your convenience there is also a [source code documentation](http://rubydoc.info/github/baschtl/devise-token_authenticatable/master/frames). ## Contributing 1. Fork it. 2. Create your feature branch (`git checkout -b my-new-feature`). 3. Commit your changes (`git commit -am 'Add some feature'`). 4. Push to the branch (`git push origin my-new-feature`). 5. Create new Pull Request. 6. Get a thank you!