Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Initial comment for Devise related changes. There are tests that stil…

…l need to be fixed and cruft to clean up...
  • Loading branch information...
commit e8e6391a88fa764072402c761178753d3dfd370b 1 parent 30b3cde
Mark Steckel authored
Showing with 769 additions and 138 deletions.
  1. +1 −0  Gemfile
  2. +9 −0 Gemfile.lock
  3. +1 −1  app/assets/stylesheets/login_signup.css.scss
  4. +10 −5 app/controllers/application_controller.rb
  5. +2 −1  app/controllers/users_controller.rb
  6. +33 −13 app/models/user.rb
  7. +2 −1  app/validators/old_password_validator.rb
  8. +9 −0 app/views/devise/confirmations/new.html.haml
  9. +4 −0 app/views/devise/mailer/confirmation_instructions.html.haml
  10. +6 −0 app/views/devise/mailer/reset_password_instructions.html.haml
  11. +5 −0 app/views/devise/mailer/unlock_instructions.html.haml
  12. +12 −0 app/views/devise/passwords/edit.html.haml
  13. +8 −0 app/views/devise/passwords/new.html.haml
  14. +18 −0 app/views/devise/registrations/edit.html.haml
  15. +10 −0 app/views/devise/registrations/new.html.haml
  16. +24 −0 app/views/devise/sessions/new.html.haml
  17. +19 −0 app/views/devise/shared/_links.haml
  18. +9 −0 app/views/devise/unlocks/new.html.haml
  19. +2 −2 app/views/layouts/application.html.haml
  20. +1 −1  app/views/shared/_navigation.html.haml
  21. +1 −1  app/views/users/edit.html.haml
  22. +252 −0 config/initializers/devise.rb
  23. +59 −0 config/locales/devise.en.yml
  24. +12 −5 config/routes.rb
  25. +98 −0 db/migrate/20130821005215_add_devise_to_users.rb
  26. +38 −11 db/structure.sql
  27. +2 −2 spec/controllers/application_controller_spec.rb
  28. +5 −1 spec/controllers/petitions_controller_spec.rb
  29. +63 −58 spec/controllers/sessions_controller_spec.rb
  30. +6 −6 spec/controllers/users_controller_spec.rb
  31. +10 −10 spec/models/user_spec.rb
  32. +18 −10 spec/spec_helper.rb
  33. +3 −0  spec/support/devise.rb
  34. +1 −1  spec/support/request_flows.rb
  35. +16 −9 spec/support/shared_examples.rb
View
1  Gemfile
@@ -61,6 +61,7 @@ gem 'activerecord-postgres-hstore'
# To use ActiveModel has_secure_password
gem 'bcrypt-ruby', '~> 3.0.0'
+gem 'devise'
# for whiplash
gem 'redis'
View
9 Gemfile.lock
@@ -123,6 +123,11 @@ GEM
debugger-ruby_core_source (~> 1.2.3)
debugger-linecache (1.2.0)
debugger-ruby_core_source (1.2.3)
+ devise (3.0.3)
+ bcrypt-ruby (~> 3.0)
+ orm_adapter (~> 0.1)
+ railties (>= 3.2.6, < 5)
+ warden (~> 1.2.3)
diff-lcs (1.1.3)
dkim (1.0.0)
dotenv (0.8.0)
@@ -199,6 +204,7 @@ GEM
newrelic_rpm (3.6.6.147)
nokogiri (1.5.6)
oauth (0.4.7)
+ orm_adapter (0.4.0)
pg (0.14.1)
pg-hstore (1.2.0)
polyglot (0.3.3)
@@ -349,6 +355,8 @@ GEM
rack
raindrops (~> 0.7)
uuidtools (2.1.3)
+ warden (1.2.3)
+ rack (>= 1.0)
websocket (1.0.7)
will_paginate (3.0.4)
xml-simple (1.1.2)
@@ -373,6 +381,7 @@ DEPENDENCIES
capybara-webkit
carmen-rails
dalli
+ devise
dkim
factory_girl_rails (~> 3.0)
faker (~> 1.0)
View
2  app/assets/stylesheets/login_signup.css.scss
@@ -1,4 +1,4 @@
-body.users.new {
+body.users.new, body.sessions.new {
background-image: image-url('protests.jpg');
background-position: 0 0;
background-repeat: repeat-y;
View
15 app/controllers/application_controller.rb
@@ -1,4 +1,5 @@
class ApplicationController < ActionController::Base
+
include Whiplash
extend Memoist
helper_method :win!, :spin!, :spin_if_cool_browser!, :measure!, :is_admin
@@ -41,17 +42,21 @@ def streaming_csv_export(export)
self.response_body = export.as_csv_stream
end
+ def after_sign_in_path_for(resource)
+ sign_in_url = url_for(:action => 'new', :controller => 'sessions', :only_path => false, :protocol => 'http')
+ if request.referer == sign_in_url
+ super
+ else
+ stored_location_for(resource) || root_path
+ end
+ end
+
private
def browser_is_cool?
browser.firefox? || browser.chrome? || browser.safari?
end
- def current_user
- @current_user ||= User.find_by_id(session[:user_id]) if session[:user_id]
- end
- helper_method :current_user
-
def require_login
if current_user.nil?
session['redirect_url'] = request.url
View
3  app/controllers/users_controller.rb
@@ -19,7 +19,8 @@ def create
def update
@user = current_user
if @user.update_attributes(params[:user])
- flash.notice = "Password was successfully updated"
+ flash.notice = "Password was successfully updated."
+ sign_in @user, :bypass => true
redirect_to root_url
else
render action: "edit"
View
46 app/models/user.rb
@@ -1,20 +1,40 @@
-require "old_password_validator"
-
class User < ActiveRecord::Base
- attr_accessor :old_password
+ # Include default devise modules. Others available are:
+ # :token_authenticatable, :confirmable,
+ # :lockable, :timeoutable and :omniauthable
+ devise :database_authenticatable, :registerable,
+ :recoverable, :rememberable, :trackable, :validatable #, :lockable
+
+ attr_accessor :current_password
attr_accessor :skip_validation
+
+ # Setup accessible (or protected) attributes for your model
+ attr_accessible :email, :password, :password_confirmation, :current_password, :remember_me
+ attr_accessible :is_super_user, :is_admin, :as => :admin
+
validates_presence_of :password, :unless => :skip_validation
validates_presence_of :password_confirmation, :unless => :skip_validation
- validates :old_password, :old_password => true, :presence => true, :on => :update, :if => :password_digest_changed?
- attr_accessible :email, :password, :old_password, :password_confirmation
- attr_accessible :email, :is_super_user, :is_admin, :as => :admin
-
- has_secure_password
- validates :email, :presence => true, :uniqueness => true , :email => true
-
- after_validation :remove_password_digest_errors
+ validate :check_current_password, :on => :update, :if => :encrypted_password_changed?
+
+ after_validation :remove_encrypted_password_errors
- def remove_password_digest_errors
- errors.delete :password_digest if errors.include? :password
+ def remove_encrypted_password_errors
+ errors.delete :encrypted_password if errors.include? :password
+ end
+
+ private
+
+ def check_current_password
+ # old_user = User.find(self.id)
+ if self.current_password.blank?
+ self.errors[:current_password] << " current password can not be blank"
+ else
+ u = User.find(self.id)
+ if ! u.valid_password? current_password
+ self.errors[:current_password] << " is not your previous password"
+ end
+ end
end
+
+
end
View
3  app/validators/old_password_validator.rb
@@ -1,7 +1,8 @@
class OldPasswordValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
old_user = User.find(object.id)
- unless old_user.authenticate value
+# unless old_user.authenticate value
+ unless sign_in old_user, attribute => value
object.errors[attribute] << (options[:message] || " is not your previous password")
end
end
View
9 app/views/devise/confirmations/new.html.haml
@@ -0,0 +1,9 @@
+%h2 Resend confirmation instructions
+= simple_form_for(resource, :as => resource_name, :url => confirmation_path(resource_name), :html => { :method => :post }) do |f|
+ = f.error_notification
+ = f.full_error :confirmation_token
+ .form-inputs
+ = f.input :email, :required => true, :autofocus => true
+ .form-actions
+ = f.button :submit, "Resend confirmation instructions"
+= render "devise/shared/links"
View
4 app/views/devise/mailer/confirmation_instructions.html.haml
@@ -0,0 +1,4 @@
+%p
+ Welcome #{@email}!
+%p You can confirm your account email through the link below:
+%p= link_to 'Confirm my account', confirmation_url(@resource, :confirmation_token => @resource.confirmation_token)
View
6 app/views/devise/mailer/reset_password_instructions.html.haml
@@ -0,0 +1,6 @@
+%p
+ Hello #{@resource.email}!
+%p Someone has requested a link to change your password. You can do this through the link below.
+%p= link_to 'Change my password', edit_password_url(@resource, :reset_password_token => @resource.reset_password_token)
+%p If you didn't request this, please ignore this email.
+%p Your password won't change until you access the link above and create a new one.
View
5 app/views/devise/mailer/unlock_instructions.html.haml
@@ -0,0 +1,5 @@
+%p
+ Hello #{@resource.email}!
+%p Your account has been locked due to an excessive number of unsuccessful sign in attempts.
+%p Click the link below to unlock your account:
+%p= link_to 'Unlock my account', unlock_url(@resource, :unlock_token => @resource.unlock_token)
View
12 app/views/devise/passwords/edit.html.haml
@@ -0,0 +1,12 @@
+%h2 Change your password
+= simple_form_for(resource, :as => resource_name, :url => password_path(resource_name), :html => { :method => :put }) do |f|
+ = f.error_notification
+ = f.input :reset_password_token, :as => :hidden
+ = f.full_error :reset_password_token
+ .form-inputs
+ = f.input :current_password, :label => "Current password", :required => true, :autofocus => true
+ = f.input :password, :label => "New password", :required => true
+ = f.input :password_confirmation, :label => "Confirm your new password", :required => true
+ .form-actions
+ = f.button :submit, "Change my password"
+/= render "devise/shared/links"
View
8 app/views/devise/passwords/new.html.haml
@@ -0,0 +1,8 @@
+%h2 Forgot your password?
+= simple_form_for(resource, :as => resource_name, :url => password_path(resource_name), :html => { :method => :post }) do |f|
+ = f.error_notification
+ .form-inputs
+ = f.input :email, :required => true, :autofocus => true
+ .form-actions
+ = f.button :submit, "Send me reset password instructions"
+= render "devise/shared/links"
View
18 app/views/devise/registrations/edit.html.haml
@@ -0,0 +1,18 @@
+%h2
+ Edit #{resource_name.to_s.humanize}
+= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put }) do |f|
+ = f.error_notification
+ .form-inputs
+ = f.input :email, :required => true, :autofocus => true
+ - if devise_mapping.confirmable? && resource.pending_reconfirmation?
+ %p
+ Currently waiting confirmation for: #{resource.unconfirmed_email}
+ = f.input :password, :autocomplete => "off", :hint => "leave it blank if you don't want to change it", :required => false
+ = f.input :password_confirmation, :required => false
+ = f.input :current_password, :hint => "we need your current password to confirm your changes", :required => true
+ .form-actions
+ = f.button :submit, "Update"
+/ %h3 Cancel my account
+/ %p
+/ Unhappy? #{link_to "Cancel my account", registration_path(resource_name), :data => { :confirm => "Are you sure?" }, :method => :delete}
+= link_to "Back", :back
View
10 app/views/devise/registrations/new.html.haml
@@ -0,0 +1,10 @@
+%h2 Sign up
+= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f|
+ = f.error_notification
+ .form-inputs
+ = f.input :email, :required => true, :autofocus => true
+ = f.input :password, :required => true
+ = f.input :password_confirmation, :required => true
+ .form-actions
+ = f.button :submit, "Sign up"
+= render "devise/shared/links"
View
24 app/views/devise/sessions/new.html.haml
@@ -0,0 +1,24 @@
+.row
+ .span12
+ .signup_login
+ %h1.title Win your campaign for change.
+ .row
+ .span6.offset2
+ = simple_form_for(resource, :as => resource_name, :url => session_path(resource_name), :html => {:class => 'form-horizontal'}) do |f|
+ .form-inputs
+ = f.input :email, :required => true, :autofocus => true, :input_html => { :class => "span4" }
+ = f.input :password, :required => true, :input_html => { :class => "span4" }
+ / = f.input :remember_me, :as => :boolean if devise_mapping.rememberable?
+ .control-group
+ .controls
+ = f.button :submit, :class => 'btn btn-primary', :id => 'login-submit', :value => 'Log in'
+ %br/
+ %br/
+ = render "devise/shared/links"
+ %p.privacypolicy= t 'site.privacy_policy'
+ %small.photo_credit
+ Photo credit:
+ %a{href: "http://www.flickr.com/photos/ramyraoof/5405707930"} RamyRaoof
+
+ .row
+ .span6.offset3
View
19 app/views/devise/shared/_links.haml
@@ -0,0 +1,19 @@
+- if controller_name != 'sessions'
+ = link_to "Sign in", new_session_path(resource_name)
+ %br/
+/ - if devise_mapping.registerable? && controller_name != 'registrations'
+/ = link_to "Sign up", new_registration_path(resource_name)
+/ %br/
+- if devise_mapping.recoverable? && controller_name != 'passwords'
+ = link_to "Forgot your password?", new_password_path(resource_name)
+ %br/
+- if devise_mapping.confirmable? && controller_name != 'confirmations'
+ = link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name)
+ %br/
+/ - if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks'
+/ = link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name)
+/ %br/
+/ - if devise_mapping.omniauthable?
+/ - resource_class.omniauth_providers.each do |provider|
+/ = link_to "Sign in with #{provider.to_s.titleize}", omniauth_authorize_path(resource_name, provider)
+/ %br/
View
9 app/views/devise/unlocks/new.html.haml
@@ -0,0 +1,9 @@
+%h2 Resend unlock instructions
+= simple_form_for(resource, :as => resource_name, :url => unlock_path(resource_name), :html => { :method => :post }) do |f|
+ = f.error_notification
+ = f.full_error :unlock_token
+ .form-inputs
+ = f.input :email, :required => true, :autofocus => true
+ .form-actions
+ = f.button :submit, "Resend unlock instructions"
+= render "devise/shared/links"
View
4 app/views/layouts/application.html.haml
@@ -7,7 +7,7 @@
- if browser.ie?
%link{:href => "/assets/application_ie.css", :media => "screen", :rel => "stylesheet", :type => "text/css"}
- else
- = stylesheet_link_tag :application
+ = stylesheet_link_tag :application, :debug => false
%title= content_for?(:title) ? yield(:title) : @title
= csrf_meta_tags
= yield :meta_tags
@@ -37,6 +37,6 @@
- org_name = AppSettings.require_keys!('organization.name')
© 2013 #{org_name} (<a href="#{@contact_url}">contact us</a>)
- = javascript_include_tag :application
+ = javascript_include_tag :application, :debug => false
%script{type: "text/javascript"}
= yield :javascripts
View
2  app/views/shared/_navigation.html.haml
@@ -40,6 +40,6 @@
%b.caret
%ul.dropdown-menu
%li= link_to('Change Password', edit_user_path(current_user))
- %li= link_to('Log Out', logout_path, :class => 'nodivider', :id => 'logout')
+ %li= link_to('Log Out', destroy_user_session_path, :method => :delete, :class => 'nodivider', :id => 'logout')
- elsif controller_name == 'petitions' && action_name == 'show'
.nodivider
View
2  app/views/users/edit.html.haml
@@ -2,7 +2,7 @@
%h1 Change Password
= simple_form_for current_user do |f|
- = f.input :old_password, :input_html => { :autocomplete => "off" }
+ = f.input :current_password, :input_html => { :autocomplete => "off" }
= f.input :password, :input_html => { :autocomplete => "off" }
= f.input :password_confirmation, :input_html => { :autocomplete => "off" }
= f.button :submit, :class => 'btn btn-primary', :value => 'Update Password'
View
252 config/initializers/devise.rb
@@ -0,0 +1,252 @@
+# Use this hook to configure devise mailer, warden hooks and so forth.
+# Many of these configuration options can be set straight in your model.
+Devise.setup do |config|
+ # ==> 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-at-config-initializers-devise@example.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. The 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 a hash where the value is a boolean determining whether
+ # or not authentication should be aborted when the value is not present.
+ # 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 the
+ # 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.
+ # It can be set to an array that will enable params authentication only for the
+ # given strategies, for example, `config.params_authenticatable = [:database]` will
+ # enable it only for database (email + password) authentication.
+ # config.params_authenticatable = true
+
+ # Tell if authentication through HTTP Auth is enabled. False by default.
+ # It can be set to an array that will enable http authentication only for the
+ # given strategies, for example, `config.http_authenticatable = [:token]` will
+ # enable it only for token authentication. The supported strategies are:
+ # :database = Support basic authentication with authentication key + password
+ # :token = Support basic authentication with token authentication key
+ # :token_options = Support token authentication with options as defined in
+ # http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html
+ # config.http_authenticatable = false
+
+ # 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"
+
+ # It will change confirmation, password recovery and other workflows
+ # to behave the same regardless if the e-mail provided was right or wrong.
+ # Does not affect registerable.
+ # config.paranoid = true
+
+ # By default Devise will store the user in session. You can skip storage for
+ # :http_auth and :token_auth by adding those symbols to the array below.
+ # Notice that if you are skipping storage for all authentication paths, you
+ # may want to disable generating routes to Devise's sessions controller by
+ # passing :skip => :sessions to `devise_for` in your config/routes.rb
+ config.skip_session_storage = [:http_auth]
+
+ # By default, Devise cleans up the CSRF token on authentication to
+ # avoid CSRF token fixation attacks. This means that, when using AJAX
+ # requests for sign in and sign up, you need to get a new CSRF token
+ # from the server. You can disable this option at your own risk.
+ # config.clean_up_csrf_token_on_authentication = true
+
+ # ==> 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.
+ #
+ # Limiting the stretches to just one in testing will increase the performance of
+ # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
+ # a value less than 10 in other environments.
+ config.stretches = Rails.env.test? ? 1 : 10
+
+ # Setup a pepper to generate the encrypted password.
+ # config.pepper = "d326d30e9436183be3fdd5a90fe3dfc4dfa7e236ac51984dd3f9aa3ee136ccfb79d86416f8196161e800b1227047f85c0e0b06911501d593273f08337f23c6cc"
+
+ # ==> Configuration for :confirmable
+ # A period that the user is allowed to access the website even without
+ # confirming his account. For instance, if set to 2.days, the user will be
+ # able to access the website for two days without confirming his account,
+ # access will be blocked just in the third day. Default is 0.days, meaning
+ # the user cannot access the website without confirming his account.
+ # config.allow_unconfirmed_access_for = 2.days
+
+ # A period that the user is allowed to confirm their account before their
+ # token becomes invalid. For example, if set to 3.days, the user can confirm
+ # their account within 3 days after the mail was sent, but on the fourth day
+ # their account can't be confirmed with the token any more.
+ # Default is nil, meaning there is no restriction on how long a user can take
+ # before confirming their account.
+ # config.confirm_within = 3.days
+
+ # If true, requires any email changes to be confirmed (exactly the same way as
+ # initial account confirmation) to be applied. Requires additional unconfirmed_email
+ # db field (see migrations). Until confirmed new email is stored in
+ # unconfirmed email column, and copied to email column on successful confirmation.
+ config.reconfirmable = true
+
+ # 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, extends the user's remember period when remembered via cookie.
+ # config.extend_remember_period = false
+
+ # Options to be passed to the created cookie. For instance, you can set
+ # :secure => true in order to force SSL only cookies.
+ # config.rememberable_options = {}
+
+ # ==> Configuration for :validatable
+ # Range for password length. Default is 8..128.
+ config.password_length = 8..128
+
+ # Email regex used to validate email formats. It simply asserts that
+ # one (and only one) @ exists in the given string. This is mainly
+ # to give user feedback and not to assert the e-mail validity.
+ # config.email_regexp = /\A[^@]+@[^@]+\z/
+
+ # ==> 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
+
+ # If true, expires auth token on session timeout.
+ # config.expire_auth_token_on_timeout = false
+
+ # ==> 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 = 6.hours
+
+ # ==> Configuration for :encryptable
+ # Allow you to use another encryption algorithm besides bcrypt (default). You can use
+ # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
+ # :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
+ # and :restful_authentication_sha1 (then you should set stretches to 10, and copy
+ # REST_AUTH_SITE_KEY to pepper).
+ #
+ # Require the `devise-encryptable` gem when using anything other than bcrypt
+ # config.encryptor = :sha512
+
+ # ==> 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
+
+ # Set this configuration to false if you want /users/sign_out to sign out
+ # only the current scope. By default, Devise signs out all 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.
+ #
+ # The "*/*" below is required to match Internet Explorer requests.
+ # config.navigational_formats = ["*/*", :html]
+
+ # The default HTTP method used to sign out a resource. Default is :delete.
+ config.sign_out_via = :delete
+
+ # ==> OmniAuth
+ # Add a new OmniAuth provider. Check the wiki for more information on setting
+ # up on your models and hooks.
+ # config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo'
+
+ # ==> 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.intercept_401 = false
+ # manager.default_strategies(:scope => :user).unshift :some_external_strategy
+ # end
+
+ # ==> Mountable engine configurations
+ # When using Devise inside an engine, let's call it `MyEngine`, and this engine
+ # is mountable, there are some extra configurations to be taken into account.
+ # The following options are available, assuming the engine is mounted as:
+ #
+ # mount MyEngine, at: "/my_engine"
+ #
+ # The router that invoked `devise_for`, in the example above, would be:
+ # config.router_name = :my_engine
+ #
+ # When using omniauth, Devise cannot automatically set Omniauth path,
+ # so you need to do it manually. For the users scope, it would be:
+ # config.omniauth_path_prefix = "/my_engine/users/auth"
+end
View
59 config/locales/devise.en.yml
@@ -0,0 +1,59 @@
+# Additional translations at https://github.com/plataformatec/devise/wiki/I18n
+
+en:
+ devise:
+ confirmations:
+ confirmed: "Your account was successfully confirmed. You are now signed in."
+ send_instructions: "You will receive an email with instructions about how to confirm your account in a few minutes."
+ send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes."
+ failure:
+ already_authenticated: "You are already signed in."
+ inactive: "Your account was not activated yet."
+ invalid: "Invalid email or password."
+ invalid_token: "Invalid authentication token."
+ locked: "Your account is locked."
+ not_found_in_database: "Invalid email or password."
+ timeout: "Your session expired, please sign in again to continue."
+ unauthenticated: "You need to sign in or sign up before continuing."
+ unconfirmed: "You have to confirm your account before continuing."
+ mailer:
+ confirmation_instructions:
+ subject: "Confirmation instructions"
+ reset_password_instructions:
+ subject: "Reset password instructions"
+ unlock_instructions:
+ subject: "Unlock Instructions"
+ omniauth_callbacks:
+ failure: "Could not authenticate you from %{kind} because \"%{reason}\"."
+ success: "Successfully authenticated from %{kind} account."
+ passwords:
+ 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."
+ send_instructions: "You will receive an email with instructions about how to reset your password in a few minutes."
+ 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."
+ updated: "Your password was changed successfully. You are now signed in."
+ updated_not_active: "Your password was changed successfully."
+ registrations:
+ destroyed: "Bye! Your account was successfully cancelled. We hope to see you again soon."
+ signed_up: "Welcome! You have signed up successfully."
+ signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated."
+ signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked."
+ signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please open the link to activate your account."
+ update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and click on the confirm link to finalize confirming your new email address."
+ updated: "You updated your account successfully."
+ sessions:
+ signed_in: "Signed in successfully."
+ signed_out: "Signed out successfully."
+ unlocks:
+ send_instructions: "You will receive an email with instructions about how to unlock your account in a few minutes."
+ send_paranoid_instructions: "If your account exists, you will receive an email with instructions about how to unlock it in a few minutes."
+ unlocked: "Your account has been unlocked successfully. Please sign in to continue."
+ errors:
+ messages:
+ already_confirmed: "was already confirmed, please try signing in"
+ confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one"
+ expired: "has expired, please request a new one"
+ not_found: "not found"
+ not_locked: "was not locked"
+ not_saved:
+ one: "1 error prohibited this %{resource} from being saved:"
+ other: "%{count} errors prohibited this %{resource} from being saved:"
View
17 config/routes.rb
@@ -2,6 +2,13 @@
Victorykit::Application.routes.draw do
+ devise_for :users
+
+ devise_scope :user do
+ get "/login" => "devise/sessions#new"
+ delete "/logout" => "devise/sessions#destroy"
+ end
+
mount Sidekiq::Web => '/admin/sidekiq', :constraints => lambda {|req| AdminConstraint.new.matches?(req) }
get "privacy/index"
@@ -10,7 +17,7 @@
resources :users
resources :bounces
- resources :sessions
+# resources :sessions
resources :whiplash_sessions
resources :unsubscribes
resources :pixel_tracking
@@ -28,10 +35,10 @@
post 'donation_tracking', to: 'donation_tracking#create', as: 'donation_tracking'
post 'paypal', to: 'donation_tracking#paypal', as: 'paypal'
- get 'login', to: 'users#new', as: 'login'
- get 'subscribe', to: 'members#new', as: 'subscribe'
- get 'unsubscribe', to: 'unsubscribes#new', as: 'subscribe'
- get 'logout', to: 'sessions#destroy', as: 'logout'
+ # get 'login', to: 'users#new', as: 'login'
+ # get 'subscribe', to: 'members#new', as: 'subscribe'
+ # get 'unsubscribe', to: 'unsubscribes#new', as: 'subscribe'
+ # get 'logout', to: 'sessions#destroy', as: 'logout'
get 'contact', to: 'user_feedbacks#new', as: 'contact'
namespace(:admin) do
View
98 db/migrate/20130821005215_add_devise_to_users.rb
@@ -0,0 +1,98 @@
+class AddDeviseToUsers < ActiveRecord::Migration
+ def self.up
+
+ execute 'ALTER TABLE users rename password_digest TO encrypted_password'
+ change_table(:users, :bulk => true) do |t|
+ ## Database authenticatable
+ t.change_default :email, ""
+ t.change_default :encrypted_password, ""
+ #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
+
+
+ # Uncomment below if timestamps were not included in your original model.
+ # t.timestamps
+ end
+
+ add_index :users, :email, :unique => true
+ add_index :users, :reset_password_token, :unique => true
+
+ # add_index :users, :confirmation_token, :unique => true
+ add_index :users, :unlock_token, :unique => true
+ # add_index :users, :authentication_token, :unique => true
+ end
+
+ def self.down
+ # By default, we don't want to make any assumption about how to roll back a migration when your
+ # model already existed. Please edit below which fields you would like to remove in this migration.
+
+ execute 'ALTER TABLE users rename encrypted_password to password_digest'
+ change_table(:users, :bulk => true) do |t|
+
+ t.change_default :email, nil
+ t.change_default :password_digest, nil
+
+ ## Recoverable
+ t.remove :reset_password_token
+ t.remove :reset_password_sent_at
+
+ ## Rememberable
+ t.remove :remember_created_at
+
+ ## Trackable
+ t.remove :sign_in_count
+ t.remove :current_sign_in_at
+ t.remove :last_sign_in_at
+ t.remove :current_sign_in_ip
+ t.remove :last_sign_in_ip
+
+ ## Confirmable
+ # t.remove :confirmation_token
+ # t.remove :confirmed_at
+ # t.remove :confirmation_sent_at
+ # t.remove :unconfirmed_email # Only if using reconfirmable
+
+ ## Lockable
+ t.remove :failed_attempts
+ t.remove :unlock_token
+ t.remove :locked_at
+
+ ## Token authenticatable
+ # t.remove :authentication_token
+
+ # Uncomment below if timestamps were not included in your original model.
+ # t.timestamps
+ end
+
+ # Want to keep this index as it should have existed in the first place!
+ # remove_index :users, :email
+
+ end
+end
View
49 db/structure.sql
@@ -973,12 +973,23 @@ ALTER SEQUENCE user_feedbacks_id_seq OWNED BY user_feedbacks.id;
CREATE TABLE users (
id integer NOT NULL,
- email character varying(255) NOT NULL,
- password_digest character varying(255) NOT NULL,
+ email character varying(255) DEFAULT ''::character varying NOT NULL,
+ encrypted_password character varying(255) DEFAULT ''::character varying NOT NULL,
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL,
is_super_user boolean DEFAULT false NOT NULL,
- is_admin boolean DEFAULT false NOT NULL
+ is_admin boolean DEFAULT false NOT NULL,
+ reset_password_token character varying(255),
+ reset_password_sent_at timestamp without time zone,
+ remember_created_at timestamp without time zone,
+ sign_in_count integer DEFAULT 0,
+ current_sign_in_at timestamp without time zone,
+ last_sign_in_at timestamp without time zone,
+ current_sign_in_ip character varying(255),
+ last_sign_in_ip character varying(255),
+ failed_attempts integer DEFAULT 0,
+ unlock_token character varying(255),
+ locked_at timestamp without time zone
);
@@ -1721,13 +1732,6 @@ CREATE INDEX index_sent_emails_on_clicked_at ON sent_emails USING btree (clicked
--
--- Name: index_sent_emails_on_created_at_and_type; Type: INDEX; Schema: public; Owner: -; Tablespace:
---
-
-CREATE INDEX index_sent_emails_on_created_at_and_type ON sent_emails USING btree (created_at, type);
-
-
---
-- Name: index_sent_emails_on_member_id; Type: INDEX; Schema: public; Owner: -; Tablespace:
--
@@ -1812,6 +1816,27 @@ CREATE INDEX index_unsubscribes_on_sent_email_id ON unsubscribes USING btree (se
--
+-- Name: index_users_on_email; Type: INDEX; Schema: public; Owner: -; Tablespace:
+--
+
+CREATE UNIQUE INDEX index_users_on_email ON users USING btree (email);
+
+
+--
+-- Name: index_users_on_reset_password_token; Type: INDEX; Schema: public; Owner: -; Tablespace:
+--
+
+CREATE UNIQUE INDEX index_users_on_reset_password_token ON users USING btree (reset_password_token);
+
+
+--
+-- Name: index_users_on_unlock_token; Type: INDEX; Schema: public; Owner: -; Tablespace:
+--
+
+CREATE UNIQUE INDEX index_users_on_unlock_token ON users USING btree (unlock_token);
+
+
+--
-- Name: unique_facebook_friend; Type: INDEX; Schema: public; Owner: -; Tablespace:
--
@@ -2198,4 +2223,6 @@ INSERT INTO schema_migrations (version) VALUES ('20130813205234');
INSERT INTO schema_migrations (version) VALUES ('20130815221806');
-INSERT INTO schema_migrations (version) VALUES ('20130820193236');
+INSERT INTO schema_migrations (version) VALUES ('20130820193236');
+
+INSERT INTO schema_migrations (version) VALUES ('20130821005215');
View
4 spec/controllers/application_controller_spec.rb
@@ -2,8 +2,8 @@
describe "Current User" do
context "user is in session" do
before(:each) do
- @user = create(:user)
- session[:user_id] = @user.id
+ @user = create(:user)
+ sign_in @user
end
its(:current_user) { should == @user }
end
View
6 spec/controllers/petitions_controller_spec.rb
@@ -235,6 +235,7 @@ def valid_attributes
describe "with valid params" do
before(:each) do
@logged_in_user = create(:user)
+ sign_in @logged_in_user
post :create, {petition: valid_attributes}, {user_id: @logged_in_user.id}
end
describe "the newly created petition" do
@@ -261,7 +262,10 @@ def valid_attributes
end
describe "with petition images" do
- before { @logged_in_user = create(:user) }
+ before(:each) do
+ @logged_in_user = create(:user)
+ sign_in @logged_in_user
+ end
it "persists images" do
image_attributes = { "petition_images_attributes" => { "1354739331381" => {"url" => "image.jpg"} } }
View
121 spec/controllers/sessions_controller_spec.rb
@@ -1,62 +1,67 @@
describe SessionsController do
- describe "POST 'create'" do
- context "user logs in with valid credentials" do
- before(:each) do
- @user = create(:user, password:"opensesame", email: "bob@here.com")
- post :create, new_session: { email: "bob@here.com", password:"opensesame"}
- end
- it "adds the user id to the session" do
- session[:user_id].should == @user.id
- end
- it { should redirect_to admin_dashboard_path }
- end
- context "user attempts to login with wrong password" do
- before(:each) do
- @user = create(:user, email: "bob@here.com", password: "supersecret")
- post :create, new_session: {email: "bob@here.com", password:"closesesame"}
- end
- it "redirects to the login page" do
- response.should redirect_to login_path
- end
- it "does not add user id to the session" do
- session[:user_id].should be_nil
- end
- it "displays message to user" do
- flash.now[:error].should == "Invalid username or password"
- end
- end
- context "user attempts to login with wrong email" do
- before(:each) do
- @user = create(:user, email:"bob@ajob.com", password: "opensesame")
- post :create, new_session: {email: "jim@here.com", password:"opensesame"}
- end
- it "redirects to the login page" do
- response.should redirect_to login_path
- end
- it "does not add user id to the session" do
- session[:user_id].should be_nil
- end
- it "displays message to user" do
- flash.now[:error].should == "Invalid username or password"
- end
- end
- end
+ pending "Disabled after switching to Devise. Should be deleted or fixed..."
- describe "DELETE 'destroy'" do
- context "user logs out" do
- before(:each) do
- @user = create(:user)
- session[:user_id] = @user.id
- delete "destroy", :id => @user.id
- end
- it "resets session" do
- session[:user_id].should be_nil
- end
- it { should redirect_to root_path }
- it "displays message logged out message to user" do
- flash.now[:notice].should == "Logged out!"
- end
- end
- end
+# describe "POST 'create'" do
+# context "user logs in with valid credentials" do
+# before(:each) do
+# @user = create(:user, password:"opensesame", email: "bob@here.com")
+# post :create, user_session: { email: "bob@here.com", password:"opensesame"}
+# end
+# it "adds the user id to the session" do
+# # session[:user_id].should == @user.id
+# current_user.id.should == @user.id
+# end
+# it { should redirect_to admin_dashboard_path }
+# end
+# context "user attempts to login with wrong password" do
+# before(:each) do
+# @user = create(:user, email: "bob@here.com", password: "supersecret")
+# post :create, new_session: {email: "bob@here.com", password:"closesesame"}
+# end
+# it "redirects to the login page" do
+# response.should redirect_to login_path
+# end
+# it "does not add user id to the session" do
+# # session[:user_id].should be_nil
+# current_user.should be_nil
+# end
+# it "displays message to user" do
+# flash.now[:error].should == "Invalid username or password"
+# end
+# end
+# context "user attempts to login with wrong email" do
+# before(:each) do
+# @user = create(:user, email:"bob@ajob.com", password: "opensesame")
+# post :create, new_session: {email: "jim@here.com", password:"opensesame"}
+# end
+# it "redirects to the login page" do
+# response.should redirect_to login_path
+# end
+# it "does not add user id to the session" do
+# # session[:user_id].should be_nil
+# current_user.should be_nil
+# end
+# it "displays message to user" do
+# flash.now[:error].should == "Invalid username or password"
+# end
+# end
+# end
+
+# describe "DELETE 'destroy'" do
+# context "user logs out" do
+# before(:each) do
+# @user = create(:user)
+# session[:user_id] = @user.id
+# delete "destroy", :id => @user.id
+# end
+# it "resets session" do
+# session[:user_id].should be_nil
+# end
+# it { should redirect_to root_path }
+# it "displays message logged out message to user" do
+# flash.now[:notice].should == "Logged out!"
+# end
+# end
+# end
end
View
12 spec/controllers/users_controller_spec.rb
@@ -1,11 +1,11 @@
describe UsersController do
- describe "GET new" do
- it "assigns a new user" do
- get :new
- assigns(:user).should be_a_new(User)
- end
- end
+ # describe "GET new" do
+ # it "assigns a new user" do
+ # get :new
+ # assigns(:user).should be_a_new(User)
+ # end
+ # end
describe "Sign up new user" do
it "logs the user in after signing up" do
View
20 spec/models/user_spec.rb
@@ -4,7 +4,7 @@
it { should validate_presence_of :email }
it { should validate_presence_of :password}
it { should validate_presence_of :password_confirmation}
- it { should_not validate_presence_of :old_password}
+ it { should_not validate_presence_of :current_password}
it_behaves_like 'email validator'
it 'should not allow mass assignment of user roles by default' do
@@ -39,16 +39,16 @@
end
it 'should validate the old password if the user is changing her password' do
- subject.password = 'banana'
- subject.password_confirmation = 'banana'
- subject.old_password = old_pass + 'cupcake'
+ subject.password = 'banana123'
+ subject.password_confirmation = 'banana123'
+ subject.current_password = old_pass + 'cupcake'
subject.should_not be_valid(:update)
end
it 'should let the user change her password if she correctly gives the old password' do
- subject.password = 'banana'
- subject.password_confirmation = 'banana'
- subject.old_password = old_pass
+ subject.password = 'banana123'
+ subject.password_confirmation = 'banana123'
+ subject.current_password = old_pass
subject.should be_valid(:update)
end
end
@@ -58,13 +58,13 @@
context 'when there is a password error' do
before do
subject.errors.add :password
- subject.remove_password_digest_errors
+ subject.remove_encrypted_password_errors
end
- its(:errors) { should_not include :password_digest }
+ its(:errors) { should_not include :encrypted_password }
end
context 'when there is no password error' do
- before { subject.remove_password_digest_errors }
+ before { subject.remove_encrypted_password_errors }
its(:errors) { should be_empty }
end
end
View
28 spec/spec_helper.rb
@@ -92,23 +92,31 @@ def self.connection
# Capybara because it starts the web server in a thread.
ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection
-def valid_session
- user = create(:user)
- valid_session_for user
+def valid_session_for user
+ sign_in user
+ session[:user_id] = @user.id
+ nil
end
-def valid_admin_session
- user = create(:admin_user)
- valid_session_for user
+def valid_session
+ @user = create(:user)
+ session[:user_id] = @user.id
+ sign_in @user
+ nil
end
-def valid_session_for user
- {:user_id => user.id}
+def valid_admin_session
+ @user = create(:admin_user)
+ session[:user_id] = @user.id
+ sign_in @user
+ nil
end
def valid_super_user_session
- user = create(:super_user)
- valid_session_for user
+ @user = create(:super_user)
+ session[:user_id] = @user.id
+ sign_in @user
+ nil
end
# redefines a bandit instance to strip out randomness and redis
View
3  spec/support/devise.rb
@@ -0,0 +1,3 @@
+RSpec.configure do |config|
+ config.include Devise::TestHelpers, :type => :controller
+end
View
2  spec/support/request_flows.rb
@@ -14,7 +14,7 @@ def signin email, pass
def login email, pass
visit '/login'
- within 'form[action="/sessions"]' do
+ within 'form[action="/users/sign_in"]' do
fill_in 'Email', with: email
fill_in 'Password', with: pass
click_button 'Log in'
View
25 spec/support/shared_examples.rb
@@ -1,6 +1,7 @@
shared_examples_for "a login protected page" do
it "allows valid users to carry out the action" do
- session[:user_id] = create(:user).id
+ @user = create(:user)
+ sign_in @user
action
should_not redirect_to login_path
end
@@ -12,12 +13,14 @@
shared_examples_for "an admin only resource page" do
it "allows valid users to carry out the action" do
- session[:user_id] = create(:admin_user).id
+ @user = create(:admin_user)
+ sign_in @user
action
should_not redirect_to login_path
end
it "disallows non admin users to carry out the action" do
- session[:user_id] = create(:user).id
+ @user = create(:user)
+ sign_in @user
action
should_not redirect_to login_path
response.status.should == 403
@@ -30,18 +33,20 @@
shared_examples_for "a user with edit permissions resource page" do
it "allows valid users to carry out the action" do
- user = create(:user)
- session[:user_id] = user.id
+ @user = create(:user)
+ sign_in @user
action
should_not redirect_to login_path
end
it "disallows users who did not create the petition to carry out the action" do
- session[:user_id] = create(:user).id
+ @user = create(:user)
+ sign_in @user
action
response.status.should == 403
end
it "disallows non super users and non admins to carry out the action" do
- session[:user_id] = create(:user).id
+ @user = create(:user)
+ sign_in @user
action
response.status.should == 403
end
@@ -75,13 +80,15 @@
shared_examples_for "a super-user only resource page" do
it "allows super users to carry out the action" do
- session[:user_id] = create(:super_user).id
+ @user = create(:super_user)
+ sign_in @user
action
response.status.should_not == 403
should_not redirect_to login_path
end
it "disallows non super users to carry out the action" do
- session[:user_id] = create(:user).id
+ @user = create(:user)
+ sign_in @user
action
response.status.should == 403
end
Please sign in to comment.
Something went wrong with that request. Please try again.