From f4b1b84142ba19fed63134c54da1dce3368fec31 Mon Sep 17 00:00:00 2001 From: Jason Draper Date: Sat, 17 Nov 2012 16:50:22 -0500 Subject: [PATCH] Switch to devise and allow user invitations --- Gemfile | 7 +- Gemfile.lock | 33 ++- README.md | 48 +++- app/controllers/application_controller.rb | 2 +- .../users/invitations_controller.rb | 21 ++ app/controllers/users_controller.rb | 5 + app/models/user.rb | 7 +- app/views/devise/invitations/edit.html.erb | 12 + app/views/devise/invitations/new.html.erb | 11 + .../mailer/invitation_instructions.html.erb | 8 + app/views/layouts/application.html.erb | 5 +- app/views/pages/home.html.erb | 1 + app/views/users/index.html.erb | 13 + config/application.rb | 2 +- config/environments/development.rb | 4 +- config/environments/production.rb | 2 +- config/environments/staging.rb | 2 +- config/initializers/clearance.rb | 3 - config/initializers/devise.rb | 254 ++++++++++++++++++ config/locales/devise.en.yml | 58 ++++ config/locales/devise_invitable.en.yml | 16 ++ config/routes.rb | 4 +- ...116021557_create_diesel_clearance_users.rb | 19 -- .../20121117215429_devise_create_users.rb | 20 ++ .../20121117222853_add_fields_to_user.rb | 6 + ...117223341_devise_invitable_add_to_users.rb | 23 ++ db/schema.rb | 30 ++- lib/tasks/dev.rake | 4 + spec/factories.rb | 14 + spec/factories/clearance.rb | 12 - spec/helpers/request/sign_in.rb | 24 ++ spec/models/user_spec.rb | 6 + spec/requests/authentication_spec.rb | 20 ++ spec/requests/user_management_spec.rb | 52 ++++ spec/spec_helper.rb | 71 +++-- spec/support/clearance.rb | 1 - 36 files changed, 712 insertions(+), 108 deletions(-) create mode 100644 app/controllers/users/invitations_controller.rb create mode 100644 app/controllers/users_controller.rb create mode 100644 app/views/devise/invitations/edit.html.erb create mode 100644 app/views/devise/invitations/new.html.erb create mode 100644 app/views/devise/mailer/invitation_instructions.html.erb create mode 100644 app/views/pages/home.html.erb create mode 100644 app/views/users/index.html.erb delete mode 100644 config/initializers/clearance.rb create mode 100644 config/initializers/devise.rb create mode 100644 config/locales/devise.en.yml create mode 100644 config/locales/devise_invitable.en.yml delete mode 100644 db/migrate/20121116021557_create_diesel_clearance_users.rb create mode 100644 db/migrate/20121117215429_devise_create_users.rb create mode 100644 db/migrate/20121117222853_add_fields_to_user.rb create mode 100644 db/migrate/20121117223341_devise_invitable_add_to_users.rb create mode 100644 spec/factories.rb delete mode 100644 spec/factories/clearance.rb create mode 100644 spec/helpers/request/sign_in.rb create mode 100644 spec/models/user_spec.rb create mode 100644 spec/requests/authentication_spec.rb create mode 100644 spec/requests/user_management_spec.rb delete mode 100644 spec/support/clearance.rb diff --git a/Gemfile b/Gemfile index 3fae31c..71fcd56 100644 --- a/Gemfile +++ b/Gemfile @@ -5,11 +5,15 @@ ruby '1.9.3' gem 'rails', '3.2.8' gem 'pg' gem 'jquery-rails' -gem 'clearance' gem 'thin' gem 'simple_form' gem 'bourbon' gem 'flutie' +gem 'devise' +gem 'devise_invitable' +gem 'high_voltage' +gem 'strong_parameters' +gem 'pry' group :assets do gem 'sass-rails', '~> 3.2.3' @@ -30,6 +34,7 @@ group :development, :test do end group :test do + gem 'email_spec' gem 'capybara' gem 'capybara-webkit' gem 'factory_girl_rails' diff --git a/Gemfile.lock b/Gemfile.lock index 1b2b5b1..1031fde 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -30,6 +30,7 @@ GEM multi_json (~> 1.0) addressable (2.3.2) arel (3.0.2) + bcrypt-ruby (3.0.1) bootstrap-sass (2.1.1.0) bourbon (2.1.2) sass (>= 3.2) @@ -49,9 +50,6 @@ GEM json childprocess (0.3.6) ffi (~> 1.0, >= 1.0.6) - clearance (0.16.3) - diesel (~> 0.1.5) - rails (>= 3.0) coderay (1.0.8) coffee-rails (3.2.2) coffee-script (>= 2.2.0) @@ -62,9 +60,19 @@ GEM coffee-script-source (1.4.0) daemons (1.1.9) database_cleaner (0.9.1) - diesel (0.1.5) - railties + devise (2.1.2) + bcrypt-ruby (~> 3.0) + orm_adapter (~> 0.1) + railties (~> 3.1) + warden (~> 1.2.1) + devise_invitable (1.1.2) + actionmailer (~> 3.0) + devise (>= 2.1.0) + railties (~> 3.0) diff-lcs (1.1.3) + email_spec (1.4.0) + launchy (~> 2.1) + mail (~> 2.2) erubis (2.7.0) eventmachine (1.0.0) execjs (1.4.0) @@ -88,6 +96,7 @@ GEM guard (>= 1.1) spork (>= 0.8.4) sys-proctable + high_voltage (1.2.1) hike (1.2.1) i18n (0.6.1) journey (1.0.4) @@ -112,6 +121,7 @@ GEM metaclass (~> 0.0.1) multi_json (1.3.7) nokogiri (1.5.5) + orm_adapter (0.4.0) pg (0.14.1) polyglot (0.3.3) pry (0.9.10) @@ -182,6 +192,10 @@ GEM hike (~> 1.2) rack (~> 1.0) tilt (~> 1.1, != 1.3.0) + strong_parameters (0.1.5) + actionpack (~> 3.1) + activemodel (~> 3.1) + railties (~> 3.1) sys-proctable (0.9.2) thin (1.5.0) daemons (>= 1.0.9) @@ -197,6 +211,8 @@ GEM uglifier (1.3.0) execjs (>= 0.3.0) multi_json (~> 1.0, >= 1.0.2) + warden (1.2.1) + rack (>= 1.0) xpath (0.1.4) nokogiri (~> 1.3) @@ -209,17 +225,21 @@ DEPENDENCIES bourne capybara capybara-webkit - clearance coffee-rails (~> 3.2.1) database_cleaner + devise + devise_invitable + email_spec factory_girl_rails flutie foreman guard guard-spork + high_voltage jquery-rails launchy pg + pry rails (= 3.2.8) rspec-rails sass-rails (~> 3.2.3) @@ -227,6 +247,7 @@ DEPENDENCIES shoulda-matchers simple_form simplecov + strong_parameters thin timecop uglifier (>= 1.0.3) diff --git a/README.md b/README.md index 3286cb6..d9eefd1 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,45 @@ -You look great in Suspenders +Campmaster ============================ +Project setup +------------- -Use the following guides for getting things done, programming well, and -programming in style. +Get the code. -* [Protocol](http://github.com/thoughtbot/guides/blob/master/protocol) -* [Best Practices](http://github.com/thoughtbot/guides/blob/master/best-practices) -* [Style](http://github.com/thoughtbot/guides/blob/master/style) + git clone git@github.com:drapergeek/wuzup.git + +Set up the project's dependencies. + + cd project + rake dev:setup + +This will automatically add a heroku remote for staging and production. + +Running tests: + + rake + + +Use [Foreman](http://goo.gl/oy4uw) to run the app locally. + + foreman start + +It uses your `.env` file and `Procfile` to run processes just like Heroku's +[Cedar](https://devcenter.heroku.com/articles/cedar/) stack. + +Anytime any development data is needed, add it to the dev:prime tasks. At any +point you can reset your local development data with: + + rake dev:prime + + +Deploy +------ +After code is commited to the master branch, it is automatically deployed to +heroku if all the tests pass. You can also manually deploy: + + git push staging + +Run migrations (if necessary). + + heroku run rake db:migrate --app campmaster-staging + heroku restart --app campmaster-staging diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index f8a344b..ae953a2 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,4 +1,4 @@ class ApplicationController < ActionController::Base - include Clearance::Authentication protect_from_forgery + before_filter :authenticate_user! end diff --git a/app/controllers/users/invitations_controller.rb b/app/controllers/users/invitations_controller.rb new file mode 100644 index 0000000..d759946 --- /dev/null +++ b/app/controllers/users/invitations_controller.rb @@ -0,0 +1,21 @@ +class Users::InvitationsController < Devise::InvitationsController + + private + def resource_params + if params[:user] + if action_name == 'update' + update_params + else + create_params + end + end + end + + def create_params + params.require(:user).permit(:email, :name, :role) + end + + def update_params + params.require(:user).permit(:name, :password, :password_confirmation, :invitation_token) + end +end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb new file mode 100644 index 0000000..0b39988 --- /dev/null +++ b/app/controllers/users_controller.rb @@ -0,0 +1,5 @@ +class UsersController < ApplicationController + def index + @users = User.all + end +end diff --git a/app/models/user.rb b/app/models/user.rb index e7bd019..7091517 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,4 +1,7 @@ class User < ActiveRecord::Base - include Clearance::User - attr_accessible :email, :password + include ActiveModel::ForbiddenAttributesProtection + devise :invitable, :database_authenticatable, :recoverable, :rememberable + + validates :name, presence: true + validates :role, presence: true end diff --git a/app/views/devise/invitations/edit.html.erb b/app/views/devise/invitations/edit.html.erb new file mode 100644 index 0000000..0ed286f --- /dev/null +++ b/app/views/devise/invitations/edit.html.erb @@ -0,0 +1,12 @@ +

<%= t 'devise.invitations.edit.header' %>

+ +<%= simple_form_for resource, :as => resource_name, :url => invitation_path(resource_name), :html => { :method => :put } do |f| %> + <%= devise_error_messages! %> + <%= f.hidden_field :invitation_token %> + + <%= f.input :name %> + <%= f.input :password %> + <%= f.input :password_confirmation %> + + <%= f.submit t("devise.invitations.edit.submit_button") %> +<% end %> diff --git a/app/views/devise/invitations/new.html.erb b/app/views/devise/invitations/new.html.erb new file mode 100644 index 0000000..244e207 --- /dev/null +++ b/app/views/devise/invitations/new.html.erb @@ -0,0 +1,11 @@ +

<%= t "devise.invitations.new.header" %>

+ +<%= simple_form_for resource, :as => resource_name, :url => invitation_path(resource_name), :html => {:method => :post} do |f| %> + <%= devise_error_messages! %> + + <%= f.input :name %> + <%= f.input :email %> + <%= f.input :role %> + +<%= f.submit t("devise.invitations.new.submit_button") %> +<% end %> diff --git a/app/views/devise/mailer/invitation_instructions.html.erb b/app/views/devise/mailer/invitation_instructions.html.erb new file mode 100644 index 0000000..a3fa4e3 --- /dev/null +++ b/app/views/devise/mailer/invitation_instructions.html.erb @@ -0,0 +1,8 @@ +

Hello <%= @resource.email %>!

+ +

Someone has invited you to <%= root_url %>, you can accept it through the link below.

+ +

<%= link_to 'Accept invitation', accept_invitation_url(@resource, :invitation_token => @resource.invitation_token) %>

+ +

If you don't want to accept the invitation, please ignore this email.
+Your account won't be created until you access the link above and set your password.

diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 58038db..a7b82d4 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -15,7 +15,10 @@ <%= link_to "Campmaster", root_url, class: 'brand' %> diff --git a/app/views/pages/home.html.erb b/app/views/pages/home.html.erb new file mode 100644 index 0000000..6527f53 --- /dev/null +++ b/app/views/pages/home.html.erb @@ -0,0 +1 @@ +This is the home page diff --git a/app/views/users/index.html.erb b/app/views/users/index.html.erb new file mode 100644 index 0000000..f392d79 --- /dev/null +++ b/app/views/users/index.html.erb @@ -0,0 +1,13 @@ + + + + + + <% @users.each do |user| %> + + + + + <% end %> +
EmailRole
<%= user.email %><%= user.role %>
+<%= link_to "Invite New User", new_user_invitation_path %> diff --git a/config/application.rb b/config/application.rb index ceb1c84..775c9a2 100644 --- a/config/application.rb +++ b/config/application.rb @@ -65,7 +65,7 @@ class Application < Rails::Application # This will create an empty whitelist of attributes available for mass-assignment for all models # in your app. As such, your models will need to explicitly whitelist or blacklist accessible # parameters by using an attr_accessible or attr_protected declaration. - config.active_record.whitelist_attributes = true + config.active_record.whitelist_attributes = false # Enable the asset pipeline config.assets.enabled = true diff --git a/config/environments/development.rb b/config/environments/development.rb index 5455ac9..19d9f7c 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -14,7 +14,7 @@ config.action_controller.perform_caching = false # Don't care if the mailer can't send - config.action_mailer.raise_delivery_errors = true + config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger config.active_support.deprecation = :log @@ -35,5 +35,5 @@ # Expands the lines which load the assets config.assets.debug = true - config.action_mailer.default_url_options = { :host => 'campmaster.local' } + config.action_mailer.default_url_options = { :host => 'localhost:3000' } end diff --git a/config/environments/production.rb b/config/environments/production.rb index 4b8d869..86f568b 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -65,5 +65,5 @@ # with SQLite, MySQL, and PostgreSQL) # config.active_record.auto_explain_threshold_in_seconds = 0.5 - config.action_mailer.default_url_options = { :host => 'campmaster.com' } + config.action_mailer.default_url_options = { :host => 'campmaster-production.herokuapp.com' } end diff --git a/config/environments/staging.rb b/config/environments/staging.rb index 3759d97..4fca53a 100644 --- a/config/environments/staging.rb +++ b/config/environments/staging.rb @@ -66,5 +66,5 @@ # with SQLite, MySQL, and PostgreSQL) # config.active_record.auto_explain_threshold_in_seconds = 0.5 - config.action_mailer.default_url_options = { :host => 'staging.campmaster.com' } + config.action_mailer.default_url_options = { :host => 'campmaster-staging.herokuapp.com' } end diff --git a/config/initializers/clearance.rb b/config/initializers/clearance.rb deleted file mode 100644 index f0490ce..0000000 --- a/config/initializers/clearance.rb +++ /dev/null @@ -1,3 +0,0 @@ -Clearance.configure do |config| - config.mailer_sender = 'reply@example.com' -end diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb new file mode 100644 index 0000000..71bd140 --- /dev/null +++ b/config/initializers/devise.rb @@ -0,0 +1,254 @@ +# 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 Basic 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 + + # 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] + + # ==> 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 = "9ec80f43137f30a82cc58f1db4eb00fa4bce88fa8b6d34bbaa8edc418be56fdfe82d8381ac82d2f752ad8755066d664fbcd675615dcc1933a2deade307f92d3f" + + # ==> Configuration for :invitable + # The period the generated invitation token is valid, after + # this period, the invited resource won't be able to accept the invitation. + # When invite_for is 0 (the default), the invitation won't expire. + # config.invite_for = 2.weeks + + # Number of invitations users can send. + # If invitation_limit is nil, users can send unlimited invitations. + # If invitation_limit is 0, users can't send invitations. + # If invitation_limit n > 0, users can send n invitations. + # Default: nil + # config.invitation_limit = 5 + + # The key to be used to check existing users when sending an invitation + # and the regexp used to test it when validate_on_invite is not set. + # config.invite_key = {:email => /A[^@]+@[^@]+z/} + # config.invite_key = {:email => /A[^@]+@[^@]+z/, :username => nil} + + # Flag that force a record to be valid before being actually invited + # Default: false + # config.validate_on_invite = true + + # ==> 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 + + # 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 6..128. + # 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 + # 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) + # 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 \ No newline at end of file diff --git a/config/locales/devise.en.yml b/config/locales/devise.en.yml new file mode 100644 index 0000000..7783a74 --- /dev/null +++ b/config/locales/devise.en.yml @@ -0,0 +1,58 @@ +# Additional translations at https://github.com/plataformatec/devise/wiki/I18n + +en: + errors: + messages: + 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:" + + 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.' + 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/locales/devise_invitable.en.yml b/config/locales/devise_invitable.en.yml new file mode 100644 index 0000000..d9d4912 --- /dev/null +++ b/config/locales/devise_invitable.en.yml @@ -0,0 +1,16 @@ +en: + devise: + invitations: + send_instructions: 'An invitation email has been sent to %{email}.' + invitation_token_invalid: 'The invitation token provided is not valid!' + updated: 'Your password was set successfully. You are now signed in.' + no_invitations_remaining: "No invitations remaining" + new: + header: "Send invitation" + submit_button: "Send an invitation" + edit: + header: "Set your password" + submit_button: "Set my password" + mailer: + invitation_instructions: + subject: 'Invitation instructions' diff --git a/config/routes.rb b/config/routes.rb index 4d3fbb6..dee5aab 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,4 +1,6 @@ Campmaster::Application.routes.draw do - root :to => 'Clearance::Sessions#new' + devise_for :users, controllers: { :invitations => 'users/invitations' } + resources :users, only: [:index] + root to: "high_voltage/pages#show", id: "home" end diff --git a/db/migrate/20121116021557_create_diesel_clearance_users.rb b/db/migrate/20121116021557_create_diesel_clearance_users.rb deleted file mode 100644 index 4e44358..0000000 --- a/db/migrate/20121116021557_create_diesel_clearance_users.rb +++ /dev/null @@ -1,19 +0,0 @@ -class CreateDieselClearanceUsers < ActiveRecord::Migration - def self.up - create_table(:users) do |t| - t.string :email - t.string :encrypted_password, :limit => 128 - t.string :salt, :limit => 128 - t.string :confirmation_token, :limit => 128 - t.string :remember_token, :limit => 128 - t.timestamps - end - - add_index :users, :email - add_index :users, :remember_token - end - - def self.down - drop_table :users - end -end diff --git a/db/migrate/20121117215429_devise_create_users.rb b/db/migrate/20121117215429_devise_create_users.rb new file mode 100644 index 0000000..c433b41 --- /dev/null +++ b/db/migrate/20121117215429_devise_create_users.rb @@ -0,0 +1,20 @@ +class DeviseCreateUsers < ActiveRecord::Migration + def change + create_table(:users) do |t| + ## Database authenticatable + t.string :email, :null => false, :default => "" + t.string :encrypted_password, :null => false, :default => "" + + ## Recoverable + t.string :reset_password_token + t.datetime :reset_password_sent_at + + ## Rememberable + t.datetime :remember_created_at + t.timestamps + end + + add_index :users, :email, :unique => true + add_index :users, :reset_password_token, :unique => true + end +end diff --git a/db/migrate/20121117222853_add_fields_to_user.rb b/db/migrate/20121117222853_add_fields_to_user.rb new file mode 100644 index 0000000..c66151f --- /dev/null +++ b/db/migrate/20121117222853_add_fields_to_user.rb @@ -0,0 +1,6 @@ +class AddFieldsToUser < ActiveRecord::Migration + def change + add_column :users, :name, :string + add_column :users, :role, :string + end +end diff --git a/db/migrate/20121117223341_devise_invitable_add_to_users.rb b/db/migrate/20121117223341_devise_invitable_add_to_users.rb new file mode 100644 index 0000000..fd1373a --- /dev/null +++ b/db/migrate/20121117223341_devise_invitable_add_to_users.rb @@ -0,0 +1,23 @@ +class DeviseInvitableAddToUsers < ActiveRecord::Migration + def up + change_table :users do |t| + t.string :invitation_token, :limit => 60 + t.datetime :invitation_sent_at + t.datetime :invitation_accepted_at + t.integer :invitation_limit + t.references :invited_by, :polymorphic => true + t.index :invitation_token # for invitable + t.index :invited_by_id + end + + # And allow null encrypted_password and password_salt: + change_column_null :users, :encrypted_password, true + end + + def down + change_table :users do |t| + t.remove_references :invited_by, :polymorphic => true + t.remove :invitation_limit, :invitation_sent_at, :invitation_accepted_at, :invitation_token + end + end +end diff --git a/db/schema.rb b/db/schema.rb index a4b3946..6c6c67c 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -11,19 +11,29 @@ # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20121116021557) do +ActiveRecord::Schema.define(:version => 20121117223341) do create_table "users", :force => true do |t| - t.string "email" - t.string "encrypted_password", :limit => 128 - t.string "salt", :limit => 128 - t.string "confirmation_token", :limit => 128 - t.string "remember_token", :limit => 128 - t.datetime "created_at", :null => false - t.datetime "updated_at", :null => false + t.string "email", :default => "", :null => false + t.string "encrypted_password", :default => "" + t.string "reset_password_token" + t.datetime "reset_password_sent_at" + t.datetime "remember_created_at" + t.datetime "created_at", :null => false + t.datetime "updated_at", :null => false + t.string "name" + t.string "role" + t.string "invitation_token", :limit => 60 + t.datetime "invitation_sent_at" + t.datetime "invitation_accepted_at" + t.integer "invitation_limit" + t.integer "invited_by_id" + t.string "invited_by_type" end - add_index "users", ["email"], :name => "index_users_on_email" - add_index "users", ["remember_token"], :name => "index_users_on_remember_token" + add_index "users", ["email"], :name => "index_users_on_email", :unique => true + add_index "users", ["invitation_token"], :name => "index_users_on_invitation_token" + add_index "users", ["invited_by_id"], :name => "index_users_on_invited_by_id" + add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true end diff --git a/lib/tasks/dev.rake b/lib/tasks/dev.rake index 7a9ef14..19a53a9 100644 --- a/lib/tasks/dev.rake +++ b/lib/tasks/dev.rake @@ -12,5 +12,9 @@ namespace :dev do DatabaseCleaner.clean puts "Creating development data..." + + puts "***USERS***" + user = FactoryGirl.create(:user, email: 'user@example.com', password: 'test') + puts "User: #{user.email}/#{user.password}" end end diff --git a/spec/factories.rb b/spec/factories.rb new file mode 100644 index 0000000..6286193 --- /dev/null +++ b/spec/factories.rb @@ -0,0 +1,14 @@ +FactoryGirl.define do + sequence(:email) {|n| "user-#{n}@example.com" } + + factory :user do + email + name 'Peter Parker' + password 'test' + role 'registration' + + factory :admin_user do + role 'admin' + end + end +end diff --git a/spec/factories/clearance.rb b/spec/factories/clearance.rb deleted file mode 100644 index 36144a3..0000000 --- a/spec/factories/clearance.rb +++ /dev/null @@ -1,12 +0,0 @@ -FactoryGirl.define do - - sequence :email do |n| - "user#{n}@example.com" - end - - factory :user do - email - password "password" - end - -end diff --git a/spec/helpers/request/sign_in.rb b/spec/helpers/request/sign_in.rb new file mode 100644 index 0000000..771ccb2 --- /dev/null +++ b/spec/helpers/request/sign_in.rb @@ -0,0 +1,24 @@ +module Helpers + module Request + module SignIn + def sign_in_as(user) + visit root_path + fill_in 'Email', with: user.email + fill_in 'Password', with: user.password + click_button 'Sign in' + end + + def sign_in_as_admin + sign_in_as(create(:admin_user)) + end + + def sign_out + click_link "Sign out" + end + end + end +end + +RSpec.configure do |config| + config.include Helpers::Request::SignIn, type: :request +end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb new file mode 100644 index 0000000..3e68430 --- /dev/null +++ b/spec/models/user_spec.rb @@ -0,0 +1,6 @@ +require 'spec_helper' + +describe User do + it { should validate_presence_of(:name) } + it { should validate_presence_of(:role) } +end diff --git a/spec/requests/authentication_spec.rb b/spec/requests/authentication_spec.rb new file mode 100644 index 0000000..7d83542 --- /dev/null +++ b/spec/requests/authentication_spec.rb @@ -0,0 +1,20 @@ +require 'spec_helper' + +feature 'user login required' do + scenario 'not authenticated user tries to visit home page' do + visit root_path + page.should have_content "You need to sign in" + end + + scenario 'registered user logs in and visits home page' do + user = create(:user) + visit new_user_session_path + fill_in 'Email', with: user.email + fill_in 'Password', with: user.password + click_button 'Sign in' + page.should have_content 'Signed in' + + visit root_path + page.should_not have_content 'You need to sign in' + end +end diff --git a/spec/requests/user_management_spec.rb b/spec/requests/user_management_spec.rb new file mode 100644 index 0000000..a6d6166 --- /dev/null +++ b/spec/requests/user_management_spec.rb @@ -0,0 +1,52 @@ +require 'spec_helper' + +feature 'user management' do + scenario 'view all users' do + sign_in_as_admin + users = create_users + visit users_path + verify_page_shows_information_for(users) + end + + scenario 'invited user accepts invitation' do + sign_in_as_admin + create_user_invitation + sign_out + register_new_user_from_invitation + ensure_new_user_is_signed_in + end + + def ensure_new_user_is_signed_in + page.should have_content("You are now signed in") + end + + def register_new_user_from_invitation + email = open_email("newuser@example.com") + click_email_link_matching(/invitation/) + fill_in 'Password', with: 'example' + fill_in 'Password confirmation', with: 'example' + click_button "Set my password" + end + + def create_user_invitation + click_link "Users" + click_link "Invite New User" + fill_in "Name", with: "John Doe" + fill_in "Email", with: 'newuser@example.com' + fill_in "Role", with: "registration" + click_button "Send an invitation" + end + + def create_users + users = [] + users << user1 = create(:user, email: 'myuser@example.com', role: 'registration') + users << create(:user, email: 'anotheruser@example.com', role: 'admin') + end + + def verify_page_shows_information_for(users) + users.each do |user| + page.should have_content user.email + page.should have_content user.role + end + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index ea7172e..3e03ed7 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,43 +1,34 @@ -require 'simplecov' -SimpleCov.start 'rails' - -# This file is copied to spec/ when you run 'rails generate rspec:install' -ENV["RAILS_ENV"] ||= 'test' -require File.expand_path("../../config/environment", __FILE__) -require 'rspec/rails' -require 'rspec/autorun' - -# Requires supporting ruby files with custom matchers and macros, etc, -# in spec/support/ and its subdirectories. -Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} - -RSpec.configure do |config| - # ## Mock Framework - # - # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: - # - config.mock_with :mocha - # config.mock_with :flexmock - # config.mock_with :rr - - # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures - config.fixture_path = "#{::Rails.root}/spec/fixtures" - - # If you're not using ActiveRecord, or you'd prefer not to run each of your - # examples within a transaction, remove the following line or assign false - # instead of true. - config.use_transactional_fixtures = true +require 'rubygems' +require 'spork' + +Spork.prefork do + unless ENV['DRB'] + require 'simplecov' + SimpleCov.start 'rails' + end + + ENV["RAILS_ENV"] ||= 'test' + require File.expand_path("../../config/environment", __FILE__) + require 'rspec/rails' + require 'rspec/autorun' + require 'email_spec' + + RSpec.configure do |config| + config.infer_base_class_for_anonymous_controllers = false + config.use_transactional_fixtures = true + config.order = "random" + config.include FactoryGirl::Syntax::Methods + config.include EmailSpec::Helpers + config.include EmailSpec::Matchers + end +end - # If true, the base class of anonymous controllers will be inferred - # automatically. This will be the default behavior in future versions of - # rspec-rails. - config.infer_base_class_for_anonymous_controllers = false +Spork.each_run do + if ENV['DRB'] + require 'simplecov' + SimpleCov.start 'rails' + end - # Run specs in random order to surface order dependencies. If you find an - # order dependency and want to debug it, you can fix the order by providing - # the seed, which is printed after each run. - # --seed 1234 - config.order = "random" + Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} + Dir[Rails.root.join("spec/helpers/**/*.rb")].each {|f| require f} end - - Capybara.javascript_driver = :webkit \ No newline at end of file diff --git a/spec/support/clearance.rb b/spec/support/clearance.rb deleted file mode 100644 index 2eda1ea..0000000 --- a/spec/support/clearance.rb +++ /dev/null @@ -1 +0,0 @@ -require 'clearance/testing' \ No newline at end of file