From 4e533e1b59c45bb798614a5d2a24e679ad3c4731 Mon Sep 17 00:00:00 2001 From: Thomas von Deyen Date: Thu, 1 Jan 2015 18:02:58 +0100 Subject: [PATCH] Upgrades to Devise 3.4 This includes a new `alchemy:devise:install` generator to improve security and transparency in the host app. NOTE: If you are upgrading from Alchemy::Devise 2.0 or older and have overwritten the mailer views, you need to upgrade them! See: https://github.com/plataformatec/devise/blob/master/CHANGELOG.md#310---2013-09-05 --- README.md | 23 +- Rakefile | 3 +- alchemy-devise.gemspec | 15 +- .../alchemy/user_sessions_controller.rb | 12 +- app/mailers/alchemy/notifications.rb | 4 +- app/models/alchemy/user.rb | 3 +- .../reset_password_instructions.de.text.erb | 2 +- .../reset_password_instructions.en.text.erb | 2 +- .../reset_password_instructions.es.text.erb | 2 +- .../reset_password_instructions.ru.text.erb | 2 +- config/locales/devise.en.yml | 98 +++---- config/routes.rb | 27 +- lib/alchemy/devise/version.rb | 2 +- .../devise/install/install_generator.rb | 22 ++ .../devise/install/templates/devise.rb.tt | 261 ++++++++++++++++++ .../user_sessions_controller_spec.rb | 34 ++- .../dummy/config}/initializers/devise.rb | 87 +++--- spec/dummy/config/routes.rb | 55 ---- spec/features/password_reset_feature_spec.rb | 36 +++ spec/mailers/notifications_spec.rb | 27 +- spec/routing/password_routing_spec.rb | 43 +++ spec/routing/session_routing_spec.rb | 32 +++ spec/routing/user_routing_spec.rb | 23 ++ 23 files changed, 629 insertions(+), 186 deletions(-) create mode 100644 lib/generators/alchemy/devise/install/install_generator.rb create mode 100644 lib/generators/alchemy/devise/install/templates/devise.rb.tt rename {config => spec/dummy/config}/initializers/devise.rb (76%) create mode 100644 spec/features/password_reset_feature_spec.rb create mode 100644 spec/routing/password_routing_spec.rb create mode 100644 spec/routing/session_routing_spec.rb create mode 100644 spec/routing/user_routing_spec.rb diff --git a/README.md b/README.md index 3f7a29c..926c934 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Devise based authentication for Alchemy 3.0 +## Devise based authentication for Alchemy 3.1 [![Build Status](https://secure.travis-ci.org/magiclabs/alchemy-devise.svg?branch=master)](http://travis-ci.org/magiclabs/alchemy-devise) [![Coverage Status](https://coveralls.io/repos/magiclabs/alchemy-devise/badge.png?branch=master)](https://coveralls.io/r/magiclabs/alchemy-devise?branch=master) [![Code Climate](https://codeclimate.com/github/magiclabs/alchemy-devise.svg)](https://codeclimate.com/github/magiclabs/alchemy-devise) @@ -21,26 +21,19 @@ gem 'alchemy-devise', github: 'magiclabs/alchemy-devise', branch: 'master' and run `bundle install`. -Migrate the database: +Then run the installer: ```shell -$ bin/rake alchemy_devise:install:migrations -$ bin/rake db:migrate +$ bin/rails g alchemy_devise:install ``` ## Upgrading -After updating the gem, please also check if new migrations have been added. +After updating the gem, please run the installer again. ```shell $ bundle update alchemy-devise -$ bin/rake alchemy_devise:install:migrations -``` - -and if new migrations have been added then migrate your database: - -```shell -$ bin/rake db:migrate +$ bin/rails g alchemy_devise:install ``` ## Testing @@ -55,19 +48,19 @@ Clone the repo to your local harddrive. Then ```shell $ bundle install -$ rake alchemy:spec:prepare +$ bin/rake alchemy:spec:prepare ``` ### 2. Run the tests with: ```shell -$ rspec +$ bundle exec rspec ``` _Optional:_ Even shorter ```shell -$ rake +$ bin/rake ``` That prepares the database and runs the Rspec task in one step. diff --git a/Rakefile b/Rakefile index b443cc4..2e005a3 100644 --- a/Rakefile +++ b/Rakefile @@ -31,8 +31,7 @@ namespace :alchemy do desc "Prepares database for testing Alchemy" task :prepare do - system 'cd spec/dummy && RAILS_ENV=test bundle exec rake db:migrate:reset && cd -' + system 'cd spec/dummy && RAILS_ENV=test bundle exec rake db:migrate:reset && RAILS_ENV=test bundle exec rails g alchemy:devise:install --force && cd -' end - end end diff --git a/alchemy-devise.gemspec b/alchemy-devise.gemspec index 7e5241a..16e1755 100644 --- a/alchemy-devise.gemspec +++ b/alchemy-devise.gemspec @@ -13,13 +13,24 @@ Gem::Specification.new do |s| s.summary = "Devise based user authentication for Alchemy CMS." s.description = "Devise based user authentication for Alchemy CMS." - s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] + s.files = Dir["{app,config,db,lib}/**/*", "LICENSE", "Rakefile", "README.md"] + s.test_files = Dir["spec/**/*"] s.add_dependency "alchemy_cms", [">= 3.1.0.beta2", "< 3.2"] - s.add_dependency "devise", "~> 3.0.0" + s.add_dependency "devise", ["~> 3.4"] s.add_development_dependency "capybara" s.add_development_dependency "factory_girl_rails" s.add_development_dependency "rspec-activemodel-mocks", "~> 1.0" s.add_development_dependency "rspec-rails", "~> 3.1" + + s.post_install_message =<<-MSG +In order to complete the installation or the upgrade of Alchemy::Devise run: + + $ bin/rails g alchemy:devise:install + +NOTE: If you are upgrading from Alchemy::Devise 2.0 or older and have overwritten the mailer views, you need to upgrade them! +See: https://github.com/plataformatec/devise/blob/master/CHANGELOG.md#310---2013-09-05 + + MSG end diff --git a/app/controllers/alchemy/user_sessions_controller.rb b/app/controllers/alchemy/user_sessions_controller.rb index e514f06..c131546 100644 --- a/app/controllers/alchemy/user_sessions_controller.rb +++ b/app/controllers/alchemy/user_sessions_controller.rb @@ -1,8 +1,11 @@ module Alchemy class UserSessionsController < ::Devise::SessionsController - include Locale + include Alchemy::Locale + + before_action except: 'destroy' do + enforce_ssl if ssl_required? && !request.ssl? + end - before_action(except: 'destroy') { enforce_ssl if ssl_required? && !request.ssl? } before_action :check_user_count, :only => :new helper 'Alchemy::Admin::Base', 'Alchemy::Pages' @@ -15,6 +18,7 @@ def new def create authenticate_user! + if user_signed_in? store_screen_size if session[:redirect_path].blank? @@ -23,7 +27,8 @@ def create # We have to strip double slashes from beginning of path, because of strange rails/rack bug. redirect_path = session[:redirect_path].gsub(/\A\/{2,}/, '/') end - redirect_to redirect_path, :notice => t(:signed_in, :scope => 'devise.sessions') + redirect_to redirect_path, + notice: t(:signed_in, scope: 'devise.sessions') else super end @@ -56,6 +61,5 @@ def after_sign_out_path_for(resource_or_scope) request.referer end end - end end diff --git a/app/mailers/alchemy/notifications.rb b/app/mailers/alchemy/notifications.rb index 6a98d85..ac0dee5 100644 --- a/app/mailers/alchemy/notifications.rb +++ b/app/mailers/alchemy/notifications.rb @@ -21,13 +21,13 @@ def alchemy_user_created(user) ) end - def reset_password_instructions(user, opts={}) + def reset_password_instructions(user, token, opts={}) @user = user + @token = token mail( to: user.email, subject: I18n.t("Reset password instructions") ) end - end end diff --git a/app/models/alchemy/user.rb b/app/models/alchemy/user.rb index 950f00f..455a531 100644 --- a/app/models/alchemy/user.rb +++ b/app/models/alchemy/user.rb @@ -1,5 +1,6 @@ -require 'userstamp' +require 'devise/orm/active_record' require 'acts-as-taggable-on' +require 'userstamp' module Alchemy class User < ActiveRecord::Base diff --git a/app/views/alchemy/notifications/reset_password_instructions.de.text.erb b/app/views/alchemy/notifications/reset_password_instructions.de.text.erb index 2c1e473..f306fa0 100644 --- a/app/views/alchemy/notifications/reset_password_instructions.de.text.erb +++ b/app/views/alchemy/notifications/reset_password_instructions.de.text.erb @@ -2,7 +2,7 @@ Hallo <%= @user.fullname %>. Sie haben angefordert Ihr Passwort zurückzusetzen. Dies kann durch anklicken des nachfolgenden Links bestätigt werden. -<%= alchemy.edit_password_url(@user, reset_password_token: @user.reset_password_token) %> +<%= alchemy.edit_password_url(@user, reset_password_token: @token) %> Wenn Sie diese Zurücksetzung nicht angefragt haben, dann können Sie diese E-Mail einfach ignorieren. Ihr Passwort wird erst dann zurückgesetzt, wenn Sie den Link anklicken. diff --git a/app/views/alchemy/notifications/reset_password_instructions.en.text.erb b/app/views/alchemy/notifications/reset_password_instructions.en.text.erb index 63fdb82..e1150cb 100644 --- a/app/views/alchemy/notifications/reset_password_instructions.en.text.erb +++ b/app/views/alchemy/notifications/reset_password_instructions.en.text.erb @@ -2,7 +2,7 @@ Hello <%= @user.name %>. You have requested to change your password. Please confirm this by clicking the link below. -<%= alchemy.edit_password_url(@user, reset_password_token: @user.reset_password_token) %> +<%= alchemy.edit_password_url(@user, reset_password_token: @token) %> If you didn't request this, please ignore this email. Your password won't change until you access the link above and create a new one. diff --git a/app/views/alchemy/notifications/reset_password_instructions.es.text.erb b/app/views/alchemy/notifications/reset_password_instructions.es.text.erb index 6a277ef..55d62af 100644 --- a/app/views/alchemy/notifications/reset_password_instructions.es.text.erb +++ b/app/views/alchemy/notifications/reset_password_instructions.es.text.erb @@ -2,7 +2,7 @@ Hola <%= @user.name %>. Has solicitado modificar tu contraseña. Por favor, confírmalo pulsando en el siguiente enlace. -<%= alchemy.edit_password_url(@user, reset_password_token: @user.reset_password_token) %> +<%= alchemy.edit_password_url(@user, reset_password_token: @token) %> Si no has sido tu el que ha hecho la solicitud, ignora este correo. Tu contraseña no cambiará hasta que no accedas al enlace de arriba y generes una nueva. diff --git a/app/views/alchemy/notifications/reset_password_instructions.ru.text.erb b/app/views/alchemy/notifications/reset_password_instructions.ru.text.erb index 7dfe1dd..c4ecfdc 100644 --- a/app/views/alchemy/notifications/reset_password_instructions.ru.text.erb +++ b/app/views/alchemy/notifications/reset_password_instructions.ru.text.erb @@ -2,7 +2,7 @@ Вы сделали запрос на смену пароля. Пожалуйста подтвердите это, нажав на ссылку ниже. -<%= alchemy.edit_password_url(@user, reset_password_token: @user.reset_password_token) %> +<%= alchemy.edit_password_url(@user, reset_password_token: @token) %> Если вы не делали запрос, просто проигнорируйте это письмо. Ваш пароль не изменится до тех пор, пока вы не перейдете по ссылке и сами не измените его. diff --git a/config/locales/devise.en.yml b/config/locales/devise.en.yml index 4572f2e..26a10f2 100644 --- a/config/locales/devise.en.yml +++ b/config/locales/devise.en.yml @@ -1,60 +1,60 @@ # Additional translations at https://github.com/plataformatec/devise/wiki/I18n en: + devise: + confirmations: + confirmed: "Your email address has been successfully confirmed." + send_instructions: "You will receive an email with instructions for how to confirm your email address in a few minutes." + send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes." + failure: + already_authenticated: "You are already signed in." + inactive: "Your account is not activated yet." + invalid: "Invalid %{authentication_keys} or password." + locked: "Your account is locked." + last_attempt: "You have one more attempt before your account is locked." + not_found_in_database: "Invalid %{authentication_keys} 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 email address 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 on 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 has been changed successfully. You are now signed in." + updated_not_active: "Your password has been changed successfully." + registrations: + destroyed: "Bye! Your account has been 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 follow 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 follow the confirm link to confirm your new email address." + updated: "Your account has been updated successfully." + sessions: + signed_in: "Signed in successfully." + signed_out: "Signed out successfully." + already_signed_out: "Signed out successfully." + unlocks: + send_instructions: "You will receive an email with instructions for how to unlock your account in a few minutes." + send_paranoid_instructions: "If your account exists, you will receive an email with instructions for 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" - already_confirmed: "was already confirmed, please try signing in" 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:" - confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" - - devise: - failure: - already_authenticated: 'You are already signed in.' - unauthenticated: 'You need to sign in or sign up before continuing.' - unconfirmed: 'You have to confirm your account before continuing.' - locked: 'Your account is locked.' - not_found_in_database: 'Invalid email or password.' - invalid: 'Invalid email or password.' - invalid_token: 'Invalid authentication token.' - timeout: 'Your session expired, please sign in again to continue.' - inactive: 'Your account was not activated yet.' - sessions: - signed_in: 'Signed in successfully.' - signed_out: 'Signed out successfully.' - passwords: - send_instructions: 'You will receive an email with instructions about how to reset your password in a few minutes.' - updated: 'Your password was changed successfully. You are now signed in.' - updated_not_active: 'Your password was changed successfully.' - 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." - 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." - confirmations: - 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.' - confirmed: 'Your account was successfully confirmed. You are now signed in.' - registrations: - signed_up: 'Welcome! You have signed up successfully.' - 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.' - 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.' - updated: 'You updated your account successfully.' - 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." - destroyed: 'Bye! Your account was successfully cancelled. We hope to see you again soon.' - unlocks: - send_instructions: 'You will receive an email with instructions about how to unlock your account in a few minutes.' - unlocked: 'Your account has been unlocked successfully. Please sign in to continue.' - send_paranoid_instructions: 'If your account exists, you will receive an email with instructions about how to unlock it in a few minutes.' - omniauth_callbacks: - success: 'Successfully authenticated from %{kind} account.' - failure: 'Could not authenticate you from %{kind} because "%{reason}".' - mailer: - confirmation_instructions: - subject: 'Confirmation instructions' - reset_password_instructions: - subject: 'Reset password instructions' - unlock_instructions: - subject: 'Unlock Instructions' diff --git a/config/routes.rb b/config/routes.rb index d6058bd..aa90de7 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -9,15 +9,26 @@ resources :users, only: [:create] devise_scope :user do - get '/admin/signup' => 'users#new', :as => :signup - get '/admin/login' => 'user_sessions#new', :as => :login + get '/admin/dashboard' => 'admin/dashboard#index', + :as => :user_root + + get '/admin/signup' => 'users#new', + :as => :signup + + get '/admin/login' => 'user_sessions#new', + :as => :login post '/admin/login' => 'user_sessions#create' - delete '/admin/logout' => 'user_sessions#destroy', :as => :logout - get '/admin/dashboard' => 'admin/dashboard#index', :as => :user_root - get '/admin/passwords' => 'passwords#new', :as => :new_password - get '/admin/passwords/:id/edit/:reset_password_token' => 'passwords#edit', :as => :edit_password - post '/admin/passwords' => 'passwords#create', :as => :reset_password - patch '/admin/passwords' => 'passwords#update', :as => :update_password + delete '/admin/logout' => 'user_sessions#destroy', + :as => :logout + + get '/admin/passwords' => 'passwords#new', + :as => :new_password + get '/admin/passwords/:id/edit/:reset_password_token' => 'passwords#edit', + :as => :edit_password + post '/admin/passwords' => 'passwords#create', + :as => :reset_password + patch '/admin/passwords' => 'passwords#update', + :as => :update_password end namespace :admin do diff --git a/lib/alchemy/devise/version.rb b/lib/alchemy/devise/version.rb index d84c986..2190e01 100644 --- a/lib/alchemy/devise/version.rb +++ b/lib/alchemy/devise/version.rb @@ -1,5 +1,5 @@ module Alchemy module Devise - VERSION = "2.1.0.beta2" + VERSION = "2.1.0.beta3" end end diff --git a/lib/generators/alchemy/devise/install/install_generator.rb b/lib/generators/alchemy/devise/install/install_generator.rb new file mode 100644 index 0000000..b8e86d9 --- /dev/null +++ b/lib/generators/alchemy/devise/install/install_generator.rb @@ -0,0 +1,22 @@ +module Alchemy + module Devise + module Generators + class InstallGenerator < Rails::Generators::Base + desc "Installs Alchemy Devise based authentication into your app." + source_root File.expand_path('templates', File.dirname(__FILE__)) + + def copy_devise_config + template 'devise.rb.tt', 'config/initializers/devise.rb' + end + + def add_migrations + run 'bundle exec rake alchemy_devise:install:migrations' + end + + def run_migrations + run 'bundle exec rake db:migrate' + end + end + end + end +end diff --git a/lib/generators/alchemy/devise/install/templates/devise.rb.tt b/lib/generators/alchemy/devise/install/templates/devise.rb.tt new file mode 100644 index 0000000..1026830 --- /dev/null +++ b/lib/generators/alchemy/devise/install/templates/devise.rb.tt @@ -0,0 +1,261 @@ +# 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| + # The secret key used by Devise. Devise uses this key to generate + # random tokens. Changing this key will render invalid all existing + # confirmation, reset password and unlock tokens in the database. + config.secret_key = <%= SecureRandom.hex(50).inspect %> + + # ==> 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 = Alchemy::Config.get(:mailer)['mail_from'] + + # Configure the class responsible to send e-mails. + config.mailer = "Alchemy::Notifications" + + # ==> 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' + + config.parent_controller = "Alchemy::BaseController" + + # ==> 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 = [:login] + + # 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 = [:login] + + # 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 = [:login] + + # 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 = [:database]` will + # enable it only for database authentication. The supported strategies are: + # :database = Support basic authentication with authentication key + password + config.http_authenticatable = true + + # If 401 status code 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 = 'Alchemy CMS' + + # 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 + # particular strategies by setting this option. + # 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. Note that, for bcrypt (the default + # encryptor), the cost increases exponentially with the number of stretches (e.g. + # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). + config.stretches = Rails.env.test? ? 1 : 10 + + # Setup a pepper to generate the encrypted password. + config.pepper = <%= SecureRandom.hex(50).inspect %> + + # ==> Configuration for :confirmable + # A period that the user is allowed to access the website even without + # confirming their account. For instance, if set to 2.days, the user will be + # able to access the website for two days without confirming their account, + # access will be blocked just in the third day. Default is 0.days, meaning + # the user cannot access the website without confirming their 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 = false + + # 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 + + # Invalidates all the remember me tokens when the user signs out. + config.expire_all_remember_me_on_sign_out = true + + # 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. + config.password_length = 6..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 = Rails.env.development? ? nil : Alchemy::Config.get(:auto_logout_time).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 + + # Warn on the last attempt before the account is locked. + config.last_attempt_warning = true + + # ==> 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 + + # ==> 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 diff --git a/spec/controllers/user_sessions_controller_spec.rb b/spec/controllers/user_sessions_controller_spec.rb index f973234..9740336 100644 --- a/spec/controllers/user_sessions_controller_spec.rb +++ b/spec/controllers/user_sessions_controller_spec.rb @@ -11,6 +11,19 @@ get :new is_expected.to redirect_to(signup_path) end + + context 'with ssl enforced' do + before do + allow(controller).to receive(:ssl_required?).and_return(true) + end + + it 'redirects to https' do + get :new + is_expected.to redirect_to( + login_url(protocol: 'https', host: "test.host") + ) + end + end end end @@ -56,6 +69,9 @@ describe "#destroy" do before do allow(controller).to receive(:store_user_request_time) + allow(controller) + .to receive(:all_signed_out?) + .and_return(false) sign_in(user) end @@ -65,7 +81,11 @@ end context 'comming from admin area' do - before { allow(controller.request).to receive(:referer).and_return('/admin_users') } + before do + allow(controller.request) + .to receive(:referer) + .and_return('/admin_users') + end it "redirects to root" do delete :destroy @@ -74,7 +94,11 @@ end context 'no referer present' do - before { allow(controller.request).to receive(:referer) } + before do + allow(controller.request) + .to receive(:referer) + .and_return(nil) + end it "redirects to root" do delete :destroy @@ -83,7 +107,11 @@ end context 'referer not from admin area' do - before { allow(controller.request).to receive(:referer).and_return('/imprint') } + before do + allow(controller.request) + .to receive(:referer) + .and_return('/imprint') + end it "redirects to root" do delete :destroy diff --git a/config/initializers/devise.rb b/spec/dummy/config/initializers/devise.rb similarity index 76% rename from config/initializers/devise.rb rename to spec/dummy/config/initializers/devise.rb index 976723b..5f4c373 100644 --- a/config/initializers/devise.rb +++ b/spec/dummy/config/initializers/devise.rb @@ -1,9 +1,15 @@ # 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| + # The secret key used by Devise. Devise uses this key to generate + # random tokens. Changing this key will render invalid all existing + # confirmation, reset password and unlock tokens in the database. + config.secret_key = "f4d245592bb1f8501f3d0fb20790bcb49082e523dd43fbc556ead5a7131f7d52eb8d28d1c6e1ad59f937832707fcff605e4c" + # ==> 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. + # note that it will be overwritten if you use your own mailer class + # with default "from" parameter. config.mailer_sender = Alchemy::Config.get(:mailer)['mail_from'] # Configure the class responsible to send e-mails. @@ -50,17 +56,18 @@ # enable it only for database (email + password) authentication. # config.params_authenticatable = true - # Tell if authentication through HTTP Basic Auth is enabled. False by default. + # 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. - # config.http_authenticatable = false + # given strategies, for example, `config.http_authenticatable = [:database]` will + # enable it only for database authentication. The supported strategies are: + # :database = Support basic authentication with authentication key + password + config.http_authenticatable = true - # If http headers should be returned for AJAX requests. True by default. - # config.http_authenticatable_on_xhr = true + # If 401 status code 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" + # The realm used in Http Basic Authentication. 'Application' by default. + config.http_authentication_realm = 'Alchemy CMS' # It will change confirmation, password recovery and other workflows # to behave the same regardless if the e-mail provided was right or wrong. @@ -68,30 +75,38 @@ # 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. + # particular strategies by setting this option. # 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 + # 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. + # a value less than 10 in other environments. Note that, for bcrypt (the default + # encryptor), the cost increases exponentially with the number of stretches (e.g. + # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). config.stretches = Rails.env.test? ? 1 : 10 # Setup a pepper to generate the encrypted password. - config.pepper = Rails.configuration.secret_token + config.pepper = "38beed042ea23cd991c94acaf30351fbc0d98995bfccb77682b6c196e08a381b3496fd8a219de477b443d8a085ed82638c7a" # ==> 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, + # confirming their account. For instance, if set to 2.days, the user will be + # able to access the website for two days without confirming their 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. + # the user cannot access the website without confirming their account. # config.allow_unconfirmed_access_for = 2.days # A period that the user is allowed to confirm their account before their @@ -104,9 +119,9 @@ # 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 = false + # db field (see migrations). Until confirmed, new email is stored in + # unconfirmed_email column, and copied to email column on successful confirmation. + config.reconfirmable = false # Defines which key will be used when confirming an account # config.confirmation_keys = [ :email ] @@ -115,19 +130,22 @@ # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks + # Invalidates all the remember me tokens when the user signs out. + config.expire_all_remember_me_on_sign_out = true + # 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. + # secure: true in order to force SSL only cookies. # config.rememberable_options = {} # ==> Configuration for :validatable - # Range for password length. Default is 8..128. + # Range for password length. config.password_length = 6..128 # Email regex used to validate email formats. It simply asserts that - # an one (and only one) @ exists in the given string. This is mainly + # 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/ @@ -162,6 +180,9 @@ # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour + # Warn on the last attempt before the account is locked. + config.last_attempt_warning = true + # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account @@ -177,12 +198,10 @@ # :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) - # config.encryptor = :authlogic_sha512 - - # ==> Configuration for :token_authenticatable - # Defines name of the authentication token params key - # config.token_authentication_key = :auth_token + # REST_AUTH_SITE_KEY to pepper). + # + # Require the `devise-encryptable` gem when using anything other than bcrypt + # config.encryptor = :sha512 # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for @@ -207,15 +226,15 @@ # should add them to the navigational formats lists. # # The "*/*" below is required to match Internet Explorer requests. - # config.navigational_formats = ["*/*", :html] + # config.navigational_formats = ['*/*', :html] # The default HTTP method used to sign out a resource. Default is :delete. - # config.sign_out_via = :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' + # 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 @@ -223,7 +242,7 @@ # # config.warden do |manager| # manager.intercept_401 = false - # manager.default_strategies(:scope => :user).unshift :some_external_strategy + # manager.default_strategies(scope: :user).unshift :some_external_strategy # end # ==> Mountable engine configurations @@ -231,12 +250,12 @@ # 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" + # 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" + # config.omniauth_path_prefix = '/my_engine/users/auth' end diff --git a/spec/dummy/config/routes.rb b/spec/dummy/config/routes.rb index 7194c1c..e982f9c 100644 --- a/spec/dummy/config/routes.rb +++ b/spec/dummy/config/routes.rb @@ -1,58 +1,3 @@ Dummy::Application.routes.draw do mount Alchemy::Engine => '/' - - # The priority is based upon order of creation: first created -> highest priority. - # See how all your routes lay out with "rake routes". - - # You can have the root of your site routed with "root" - # root 'welcome#index' - - # Example of regular route: - # get 'products/:id' => 'catalog#view' - - # Example of named route that can be invoked with purchase_url(id: product.id) - # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase - - # Example resource route (maps HTTP verbs to controller actions automatically): - # resources :products - - # Example resource route with options: - # resources :products do - # member do - # get 'short' - # post 'toggle' - # end - # - # collection do - # get 'sold' - # end - # end - - # Example resource route with sub-resources: - # resources :products do - # resources :comments, :sales - # resource :seller - # end - - # Example resource route with more complex sub-resources: - # resources :products do - # resources :comments - # resources :sales do - # get 'recent', on: :collection - # end - # end - - # Example resource route with concerns: - # concern :toggleable do - # post 'toggle' - # end - # resources :posts, concerns: :toggleable - # resources :photos, concerns: :toggleable - - # Example resource route within a namespace: - # namespace :admin do - # # Directs /admin/products/* to Admin::ProductsController - # # (app/controllers/admin/products_controller.rb) - # resources :products - # end end diff --git a/spec/features/password_reset_feature_spec.rb b/spec/features/password_reset_feature_spec.rb new file mode 100644 index 0000000..2bd49b9 --- /dev/null +++ b/spec/features/password_reset_feature_spec.rb @@ -0,0 +1,36 @@ +require 'spec_helper' + +describe "Password reset feature." do + let(:user) { create(:alchemy_admin_user) } + + it "User can visit password reset form." do + visit new_password_path + + expect(page).to have_content('Password reset') + end + + it "User can request password reset." do + visit new_password_path + + fill_in :user_email, with: user.email + click_button 'Send reset instructions' + + expect(page) + .to have_content('You will receive an email with instructions on how to reset your password in a few minutes.') + end + + it "User can change password." do + allow(Alchemy::User) + .to receive(:reset_password_by_token) + .and_return(user) + + visit edit_password_path(id: user.id, reset_password_token: '1234') + + fill_in :user_password, with: 'secret123' + fill_in :user_password_confirmation, with: 'secret123' + click_button 'Change password' + + expect(page) + .to have_content('Your password has been changed successfully.') + end +end diff --git a/spec/mailers/notifications_spec.rb b/spec/mailers/notifications_spec.rb index b539233..e2c8c4f 100644 --- a/spec/mailers/notifications_spec.rb +++ b/spec/mailers/notifications_spec.rb @@ -4,7 +4,13 @@ module Alchemy describe Notifications do context "when a member user was created" do - let(:user) { mock_model('User', alchemy_roles: %w(member), email: 'jon@doe.com', name: 'John Doe', login: 'jon.doe') } + let(:user) do + mock_model 'User', + alchemy_roles: %w(member), + email: 'jon@doe.com', + name: 'John Doe', + login: 'jon.doe' + end let(:mail) { Notifications.member_created(user) } it "delivers a mail to user" do @@ -44,10 +50,20 @@ module Alchemy end describe '#reset_password_instructions' do - let(:user) { mock_model('User', alchemy_roles: %w(member), email: 'jon@doe.com', name: 'John Doe', login: 'jon.doe', fullname: 'John Doe') } - let(:mail) { Notifications.reset_password_instructions(user) } + let(:user) do + mock_model 'User', + alchemy_roles: %w(member), + email: 'jon@doe.com', + name: 'John Doe', + login: 'jon.doe', + fullname: 'John Doe' + end - before { allow(user).to receive(:reset_password_token).and_return('123') } + let(:token) { '123456789' } + + let(:mail) do + Notifications.reset_password_instructions(user, token) + end it "delivers a mail to user" do expect(mail.to).to eq([user.email]) @@ -59,9 +75,8 @@ module Alchemy end it "mail body includes reset instructions" do - expect(mail.body).to match /#{Regexp.escape(edit_password_url(user, reset_password_token: user.reset_password_token, use_route: 'alchemy', only_path: true))}/ + expect(mail.body).to match /#{Regexp.escape(edit_password_url(user, reset_password_token: token, use_route: 'alchemy', only_path: true))}/ end end - end end diff --git a/spec/routing/password_routing_spec.rb b/spec/routing/password_routing_spec.rb new file mode 100644 index 0000000..00d2ffe --- /dev/null +++ b/spec/routing/password_routing_spec.rb @@ -0,0 +1,43 @@ +require 'spec_helper' + +describe "Password Routing" do + routes { Alchemy::Engine.routes } + + it "routes to new password" do + expect({ + get: "/admin/passwords" + }).to route_to( + controller: "alchemy/passwords", + action: "new" + ) + end + + it "routes to reset password" do + expect({ + post: "/admin/passwords" + }).to route_to( + controller: "alchemy/passwords", + action: "create" + ) + end + + it "routes to edit password" do + expect({ + get: "/admin/passwords/123/edit/12345" + }).to route_to( + controller: "alchemy/passwords", + action: "edit", + id: "123", + reset_password_token: "12345" + ) + end + + it "routes to update password" do + expect({ + patch: "/admin/passwords" + }).to route_to( + controller: "alchemy/passwords", + action: "update" + ) + end +end diff --git a/spec/routing/session_routing_spec.rb b/spec/routing/session_routing_spec.rb new file mode 100644 index 0000000..f694203 --- /dev/null +++ b/spec/routing/session_routing_spec.rb @@ -0,0 +1,32 @@ +require 'spec_helper' + +describe "Session Routing" do + routes { Alchemy::Engine.routes } + + it "routes to login" do + expect({ + get: "/admin/login" + }).to route_to( + controller: "alchemy/user_sessions", + action: "new" + ) + end + + it "routes to create session" do + expect({ + post: "/admin/login" + }).to route_to( + controller: "alchemy/user_sessions", + action: "create" + ) + end + + it "routes to logout" do + expect({ + delete: "/admin/logout" + }).to route_to( + controller: "alchemy/user_sessions", + action: "destroy" + ) + end +end diff --git a/spec/routing/user_routing_spec.rb b/spec/routing/user_routing_spec.rb new file mode 100644 index 0000000..3b520f8 --- /dev/null +++ b/spec/routing/user_routing_spec.rb @@ -0,0 +1,23 @@ +require 'spec_helper' + +describe "User Routing" do + routes { Alchemy::Engine.routes } + + it "routes to signup" do + expect({ + get: "/admin/signup" + }).to route_to( + controller: "alchemy/users", + action: "new" + ) + end + + it "routes to create user" do + expect({ + post: "/users" + }).to route_to( + controller: "alchemy/users", + action: "create" + ) + end +end