From c23c630969c6163c95812fd343e9338c5aaf9373 Mon Sep 17 00:00:00 2001 From: moeabdol Date: Thu, 15 Oct 2015 09:32:47 +0300 Subject: [PATCH 01/21] configure guard to watch controllers and scss files --- Guardfile | 5 +++-- db/schema.rb | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Guardfile b/Guardfile index 6a0ea2c..fc9b54e 100644 --- a/Guardfile +++ b/Guardfile @@ -26,11 +26,12 @@ guard 'livereload' do watch(%r{app/views/.+\.(erb|haml|slim)$}) + watch(%r{app/controllers/.+\.(rb)$}) watch(%r{app/helpers/.+\.rb}) - watch(%r{public/.+\.(css|js|html)}) + watch(%r{public/.+\.(css|scss|js|html)}) watch(%r{config/locales/.+\.yml}) # Rails Assets Pipeline - watch(%r{(app|vendor)(/assets/\w+/(.+\.(css|js|html|png|jpg))).*}) { |m| "/assets/#{m[3]}" } + watch(%r{(app|vendor)(/assets/\w+/(.+\.(css|scss|js|html|png|jpg))).*}) { |m| "/assets/#{m[3]}" } end guard :rspec, cmd: "bundle exec rspec" do diff --git a/db/schema.rb b/db/schema.rb index 78a7481..d8db3a0 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -23,4 +23,5 @@ t.datetime "created_at", null: false t.datetime "updated_at", null: false end + end From 031f462bfb476da5d36675a7bf6aeab2a787304d Mon Sep 17 00:00:00 2001 From: moeabdol Date: Thu, 15 Oct 2015 09:43:42 +0300 Subject: [PATCH 02/21] add devise gem --- Gemfile | 2 + Gemfile.lock | 14 ++ app/views/layouts/application.html.erb | 3 + config/environments/development.rb | 2 + config/initializers/devise.rb | 262 +++++++++++++++++++++++++ config/locales/devise.en.yml | 60 ++++++ 6 files changed, 343 insertions(+) create mode 100644 config/initializers/devise.rb create mode 100644 config/locales/devise.en.yml diff --git a/Gemfile b/Gemfile index 6e9abb1..d97ea1e 100644 --- a/Gemfile +++ b/Gemfile @@ -24,6 +24,8 @@ gem 'turbolinks' gem 'jbuilder', '~> 2.0' # bundle exec rake doc:rails generates the API under doc/api. gem 'sdoc', '~> 0.4.0', group: :doc +# Devise gem for authentication +gem 'devise', '~> 3.5.2' # Use ActiveModel has_secure_password # gem 'bcrypt', '~> 3.1.7' diff --git a/Gemfile.lock b/Gemfile.lock index 0afe943..df7071d 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -40,6 +40,7 @@ GEM autoprefixer-rails (6.0.3) execjs json + bcrypt (3.1.10) binding_of_caller (0.7.2) debug_inspector (>= 0.0.1) bootstrap-sass (3.3.5.1) @@ -63,6 +64,13 @@ GEM coffee-script-source (1.9.1.1) database_cleaner (1.5.0) debug_inspector (0.0.2) + devise (3.5.2) + bcrypt (~> 3.0) + orm_adapter (~> 0.1) + railties (>= 3.2.6, < 5) + responders + thread_safe (~> 0.1) + warden (~> 1.2.3) diff-lcs (1.2.5) em-websocket (0.5.1) eventmachine (>= 0.12.9) @@ -130,6 +138,7 @@ GEM notiffany (0.0.8) nenv (~> 0.1) shellany (~> 0.0) + orm_adapter (0.5.0) pg (0.18.3) pry (0.10.2) coderay (~> 1.1.0) @@ -167,6 +176,8 @@ GEM rb-inotify (0.9.5) ffi (>= 0.5.0) rdoc (4.2.0) + responders (2.1.0) + railties (>= 4.2.0, < 5) rspec (3.3.0) rspec-core (~> 3.3.0) rspec-expectations (~> 3.3.0) @@ -217,6 +228,8 @@ GEM uglifier (2.7.2) execjs (>= 0.3.0) json (>= 1.8.0) + warden (1.2.3) + rack (>= 1.0) web-console (2.2.1) activemodel (>= 4.0) binding_of_caller (>= 0.7.2) @@ -234,6 +247,7 @@ DEPENDENCIES capybara coffee-rails (~> 4.1.0) database_cleaner + devise (~> 3.5.2) factory_girl_rails faker font-awesome-rails (~> 4.4.0.0) diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 3618437..942b27d 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -34,6 +34,9 @@ +

<%= notice %>

+

<%= alert %>

+ <%= yield %> diff --git a/config/environments/development.rb b/config/environments/development.rb index b55e214..769dee3 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -16,6 +16,8 @@ # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false + config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } + # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb new file mode 100644 index 0000000..741766c --- /dev/null +++ b/config/initializers/devise.rb @@ -0,0 +1,262 @@ +# 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. + # Devise will use the `secret_key_base` on Rails 4+ applications as its `secret_key` + # by default. You can change it below and use your own secret key. + # config.secret_key = 'f57d901def87b4d45e8396d347a50ffad15aa44dbaeda4070a3d014eb930d4fa300945cb93b8b0bb424cd5a1a55c280ba3842f3b9705c69c448ccb2c41fada29' + + # ==> Mailer Configuration + # Configure the e-mail address which will be shown in Devise::Mailer, + # note that it will be overwritten if you use your own mailer class + # with default "from" parameter. + config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' + + # Configure the class responsible to send e-mails. + # config.mailer = 'Devise::Mailer' + + # ==> ORM configuration + # Load and configure the ORM. Supports :active_record (default) and + # :mongoid (bson_ext recommended) by default. Other ORMs may be + # available as additional gems. + require 'devise/orm/active_record' + + # ==> Configuration for any authentication mechanism + # Configure which keys are used when authenticating a user. The default is + # just :email. You can configure it to use [:username, :subdomain], so for + # authenticating a user, both parameters are required. Remember that those + # parameters are used only when authenticating and not when retrieving from + # session. If you need permissions, you should implement that in a before filter. + # You can also supply a hash where the value is a boolean determining whether + # or not authentication should be aborted when the value is not present. + # config.authentication_keys = [:email] + + # Configure parameters from the request object used for authentication. Each entry + # given should be a request method and it will automatically be passed to the + # find_for_authentication method and considered in your model lookup. For instance, + # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. + # The same considerations mentioned for authentication_keys also apply to request_keys. + # config.request_keys = [] + + # Configure which authentication keys should be case-insensitive. + # These keys will be downcased upon creating or modifying a user and when used + # to authenticate or find a user. Default is :email. + config.case_insensitive_keys = [:email] + + # Configure which authentication keys should have whitespace stripped. + # These keys will have whitespace before and after removed upon creating or + # modifying a user and when used to authenticate or find a user. Default is :email. + config.strip_whitespace_keys = [:email] + + # Tell if authentication through request.params is enabled. True by default. + # It can be set to an array that will enable params authentication only for the + # given strategies, for example, `config.params_authenticatable = [:database]` will + # enable it only for database (email + password) authentication. + # config.params_authenticatable = true + + # Tell if authentication through HTTP Auth is enabled. False by default. + # It can be set to an array that will enable http authentication only for the + # given strategies, for example, `config.http_authenticatable = [:database]` will + # enable it only for database authentication. The supported strategies are: + # :database = Support basic authentication with authentication key + password + # config.http_authenticatable = false + + # 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' + + # 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 = '1f9d4338abcb48b6eb34432bdc784bf9f12a51e06f036f0737b815ec573523d93f51782ede7af72dbc4a9c2f9121f41892f478231b3115a3a8771896437ca60d' + + # ==> 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 = 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 + + # 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 = 8..72 + + # Email regex used to validate email formats. It simply asserts that + # one (and only one) @ exists in the given string. This is mainly + # to give user feedback and not to assert the e-mail validity. + # config.email_regexp = /\A[^@]+@[^@]+\z/ + + # ==> Configuration for :timeoutable + # The time you want to timeout the user session without activity. After this + # time the user will be asked for credentials again. Default is 30 minutes. + # config.timeout_in = 30.minutes + + # ==> 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 + + # When set to false, does not sign a user in automatically after their password is + # reset. Defaults to true, so a user is signed in automatically after a reset. + # config.sign_in_after_reset_password = true + + # ==> 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/config/locales/devise.en.yml b/config/locales/devise.en.yml new file mode 100644 index 0000000..26a10f2 --- /dev/null +++ b/config/locales/devise.en.yml @@ -0,0 +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" + 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:" From d822abc8bba24fbc416e0d9eb1bcea023ceecb59 Mon Sep 17 00:00:00 2001 From: moeabdol Date: Thu, 15 Oct 2015 09:53:42 +0300 Subject: [PATCH 03/21] add devise user model --- app/models/user.rb | 6 +++ app/views/devise/confirmations/new.html.erb | 16 +++++++ .../mailer/confirmation_instructions.html.erb | 5 +++ .../reset_password_instructions.html.erb | 8 ++++ .../mailer/unlock_instructions.html.erb | 7 +++ app/views/devise/passwords/edit.html.erb | 25 +++++++++++ app/views/devise/passwords/new.html.erb | 16 +++++++ app/views/devise/registrations/edit.html.erb | 39 ++++++++++++++++ app/views/devise/registrations/new.html.erb | 29 ++++++++++++ app/views/devise/sessions/new.html.erb | 26 +++++++++++ app/views/devise/shared/_links.html.erb | 25 +++++++++++ app/views/devise/unlocks/new.html.erb | 16 +++++++ config/routes.rb | 1 + .../20151015065131_devise_create_users.rb | 44 +++++++++++++++++++ db/schema.rb | 22 +++++++++- spec/factories/users.rb | 6 +++ spec/models/user_spec.rb | 4 ++ 17 files changed, 294 insertions(+), 1 deletion(-) create mode 100644 app/models/user.rb create mode 100644 app/views/devise/confirmations/new.html.erb create mode 100644 app/views/devise/mailer/confirmation_instructions.html.erb create mode 100644 app/views/devise/mailer/reset_password_instructions.html.erb create mode 100644 app/views/devise/mailer/unlock_instructions.html.erb create mode 100644 app/views/devise/passwords/edit.html.erb create mode 100644 app/views/devise/passwords/new.html.erb create mode 100644 app/views/devise/registrations/edit.html.erb create mode 100644 app/views/devise/registrations/new.html.erb create mode 100644 app/views/devise/sessions/new.html.erb create mode 100644 app/views/devise/shared/_links.html.erb create mode 100644 app/views/devise/unlocks/new.html.erb create mode 100644 db/migrate/20151015065131_devise_create_users.rb create mode 100644 spec/factories/users.rb create mode 100644 spec/models/user_spec.rb diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 0000000..c822027 --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,6 @@ +class User < ActiveRecord::Base + # Include default devise modules. Others available are: + # :confirmable, :lockable, :timeoutable and :omniauthable + devise :database_authenticatable, :registerable, + :recoverable, :rememberable, :trackable, :validatable +end diff --git a/app/views/devise/confirmations/new.html.erb b/app/views/devise/confirmations/new.html.erb new file mode 100644 index 0000000..826672f --- /dev/null +++ b/app/views/devise/confirmations/new.html.erb @@ -0,0 +1,16 @@ +

Resend confirmation instructions

+ +<%= form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f| %> + <%= devise_error_messages! %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, value: (resource.pending_reconfirmation? ? resource.unconfirmed_email : resource.email) %> +
+ +
+ <%= f.submit "Resend confirmation instructions" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/mailer/confirmation_instructions.html.erb b/app/views/devise/mailer/confirmation_instructions.html.erb new file mode 100644 index 0000000..dc55f64 --- /dev/null +++ b/app/views/devise/mailer/confirmation_instructions.html.erb @@ -0,0 +1,5 @@ +

Welcome <%= @email %>!

+ +

You can confirm your account email through the link below:

+ +

<%= link_to 'Confirm my account', confirmation_url(@resource, confirmation_token: @token) %>

diff --git a/app/views/devise/mailer/reset_password_instructions.html.erb b/app/views/devise/mailer/reset_password_instructions.html.erb new file mode 100644 index 0000000..f667dc1 --- /dev/null +++ b/app/views/devise/mailer/reset_password_instructions.html.erb @@ -0,0 +1,8 @@ +

Hello <%= @resource.email %>!

+ +

Someone has requested a link to change your password. You can do this through the link below.

+ +

<%= link_to 'Change my password', edit_password_url(@resource, 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/devise/mailer/unlock_instructions.html.erb b/app/views/devise/mailer/unlock_instructions.html.erb new file mode 100644 index 0000000..41e148b --- /dev/null +++ b/app/views/devise/mailer/unlock_instructions.html.erb @@ -0,0 +1,7 @@ +

Hello <%= @resource.email %>!

+ +

Your account has been locked due to an excessive number of unsuccessful sign in attempts.

+ +

Click the link below to unlock your account:

+ +

<%= link_to 'Unlock my account', unlock_url(@resource, unlock_token: @token) %>

diff --git a/app/views/devise/passwords/edit.html.erb b/app/views/devise/passwords/edit.html.erb new file mode 100644 index 0000000..6a796b0 --- /dev/null +++ b/app/views/devise/passwords/edit.html.erb @@ -0,0 +1,25 @@ +

Change your password

+ +<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :put }) do |f| %> + <%= devise_error_messages! %> + <%= f.hidden_field :reset_password_token %> + +
+ <%= f.label :password, "New password" %>
+ <% if @minimum_password_length %> + (<%= @minimum_password_length %> characters minimum)
+ <% end %> + <%= f.password_field :password, autofocus: true, autocomplete: "off" %> +
+ +
+ <%= f.label :password_confirmation, "Confirm new password" %>
+ <%= f.password_field :password_confirmation, autocomplete: "off" %> +
+ +
+ <%= f.submit "Change my password" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/passwords/new.html.erb b/app/views/devise/passwords/new.html.erb new file mode 100644 index 0000000..3d6d11a --- /dev/null +++ b/app/views/devise/passwords/new.html.erb @@ -0,0 +1,16 @@ +

Forgot your password?

+ +<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %> + <%= devise_error_messages! %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true %> +
+ +
+ <%= f.submit "Send me reset password instructions" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/registrations/edit.html.erb b/app/views/devise/registrations/edit.html.erb new file mode 100644 index 0000000..3ea40f0 --- /dev/null +++ b/app/views/devise/registrations/edit.html.erb @@ -0,0 +1,39 @@ +

Edit <%= resource_name.to_s.humanize %>

+ +<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %> + <%= devise_error_messages! %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true %> +
+ + <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %> +
Currently waiting confirmation for: <%= resource.unconfirmed_email %>
+ <% end %> + +
+ <%= f.label :password %> (leave blank if you don't want to change it)
+ <%= f.password_field :password, autocomplete: "off" %> +
+ +
+ <%= f.label :password_confirmation %>
+ <%= f.password_field :password_confirmation, autocomplete: "off" %> +
+ +
+ <%= f.label :current_password %> (we need your current password to confirm your changes)
+ <%= f.password_field :current_password, autocomplete: "off" %> +
+ +
+ <%= f.submit "Update" %> +
+<% end %> + +

Cancel my account

+ +

Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %>

+ +<%= link_to "Back", :back %> diff --git a/app/views/devise/registrations/new.html.erb b/app/views/devise/registrations/new.html.erb new file mode 100644 index 0000000..5a238ce --- /dev/null +++ b/app/views/devise/registrations/new.html.erb @@ -0,0 +1,29 @@ +

Sign up

+ +<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> + <%= devise_error_messages! %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true %> +
+ +
+ <%= f.label :password %> + <% if @minimum_password_length %> + (<%= @minimum_password_length %> characters minimum) + <% end %>
+ <%= f.password_field :password, autocomplete: "off" %> +
+ +
+ <%= f.label :password_confirmation %>
+ <%= f.password_field :password_confirmation, autocomplete: "off" %> +
+ +
+ <%= f.submit "Sign up" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/sessions/new.html.erb b/app/views/devise/sessions/new.html.erb new file mode 100644 index 0000000..b261cfd --- /dev/null +++ b/app/views/devise/sessions/new.html.erb @@ -0,0 +1,26 @@ +

Log in

+ +<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %> +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true %> +
+ +
+ <%= f.label :password %>
+ <%= f.password_field :password, autocomplete: "off" %> +
+ + <% if devise_mapping.rememberable? -%> +
+ <%= f.check_box :remember_me %> + <%= f.label :remember_me %> +
+ <% end -%> + +
+ <%= f.submit "Log in" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/shared/_links.html.erb b/app/views/devise/shared/_links.html.erb new file mode 100644 index 0000000..cd795ad --- /dev/null +++ b/app/views/devise/shared/_links.html.erb @@ -0,0 +1,25 @@ +<%- if controller_name != 'sessions' %> + <%= link_to "Log in", new_session_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.registerable? && controller_name != 'registrations' %> + <%= link_to "Sign up", new_registration_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %> + <%= link_to "Forgot your password?", new_password_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.confirmable? && controller_name != 'confirmations' %> + <%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %> + <%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.omniauthable? %> + <%- resource_class.omniauth_providers.each do |provider| %> + <%= link_to "Sign in with #{provider.to_s.titleize}", omniauth_authorize_path(resource_name, provider) %>
+ <% end -%> +<% end -%> diff --git a/app/views/devise/unlocks/new.html.erb b/app/views/devise/unlocks/new.html.erb new file mode 100644 index 0000000..16586bc --- /dev/null +++ b/app/views/devise/unlocks/new.html.erb @@ -0,0 +1,16 @@ +

Resend unlock instructions

+ +<%= form_for(resource, as: resource_name, url: unlock_path(resource_name), html: { method: :post }) do |f| %> + <%= devise_error_messages! %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true %> +
+ +
+ <%= f.submit "Resend unlock instructions" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/config/routes.rb b/config/routes.rb index 11383db..2d31e75 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,4 +1,5 @@ Rails.application.routes.draw do + devise_for :users root 'static_pages#index' # The priority is based upon order of creation: first created -> highest priority. diff --git a/db/migrate/20151015065131_devise_create_users.rb b/db/migrate/20151015065131_devise_create_users.rb new file mode 100644 index 0000000..98680d7 --- /dev/null +++ b/db/migrate/20151015065131_devise_create_users.rb @@ -0,0 +1,44 @@ +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 + + ## Trackable + t.integer :sign_in_count, default: 0, null: false + t.datetime :current_sign_in_at + t.datetime :last_sign_in_at + t.inet :current_sign_in_ip + t.inet :last_sign_in_ip + + ## Confirmable + # t.string :confirmation_token + # t.datetime :confirmed_at + # t.datetime :confirmation_sent_at + # t.string :unconfirmed_email # Only if using reconfirmable + + ## Lockable + # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts + # t.string :unlock_token # Only if unlock strategy is :email or :both + # t.datetime :locked_at + + t.string :username + t.text :biography + + t.timestamps null: false + end + + add_index :users, :email, unique: true + add_index :users, :reset_password_token, unique: true + # add_index :users, :confirmation_token, unique: true + # add_index :users, :unlock_token, unique: true + end +end diff --git a/db/schema.rb b/db/schema.rb index d8db3a0..575444f 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -11,7 +11,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 20151010160137) do +ActiveRecord::Schema.define(version: 20151015065131) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -24,4 +24,24 @@ t.datetime "updated_at", null: false end + create_table "users", force: :cascade do |t| + t.string "email", default: "", null: false + t.string "encrypted_password", default: "", null: false + t.string "reset_password_token" + t.datetime "reset_password_sent_at" + t.datetime "remember_created_at" + t.integer "sign_in_count", default: 0, null: false + t.datetime "current_sign_in_at" + t.datetime "last_sign_in_at" + t.inet "current_sign_in_ip" + t.inet "last_sign_in_ip" + t.string "username" + t.text "biography" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + + add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree + add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree + end diff --git a/spec/factories/users.rb b/spec/factories/users.rb new file mode 100644 index 0000000..209e6b1 --- /dev/null +++ b/spec/factories/users.rb @@ -0,0 +1,6 @@ +FactoryGirl.define do + factory :user do + + end + +end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb new file mode 100644 index 0000000..ab0da92 --- /dev/null +++ b/spec/models/user_spec.rb @@ -0,0 +1,4 @@ +require 'rails_helper' + +RSpec.describe User, type: :model do +end From b16d59af94b6ed683899e8a48cb29a6d8bd90d2b Mon Sep 17 00:00:00 2001 From: moeabdol Date: Thu, 15 Oct 2015 10:22:07 +0300 Subject: [PATCH 04/21] include devise test helpers --- spec/rails_helper.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb index 722e843..4376675 100644 --- a/spec/rails_helper.rb +++ b/spec/rails_helper.rb @@ -80,4 +80,6 @@ DatabaseCleaner.clean end + # include Devise test helpers + config.include Devise::TestHelpers, type: :controller end From fc13a678a67f406444a79d75c9d94543fa2341fc Mon Sep 17 00:00:00 2001 From: moeabdol Date: Thu, 15 Oct 2015 15:04:44 +0300 Subject: [PATCH 05/21] add pry-rails gem for debugging --- Gemfile | 2 ++ Gemfile.lock | 3 +++ 2 files changed, 5 insertions(+) diff --git a/Gemfile b/Gemfile index d97ea1e..5f399ea 100644 --- a/Gemfile +++ b/Gemfile @@ -55,4 +55,6 @@ group :development, :test do gem 'faker' # Use database_cleaner in place of transactional fixtures gem 'database_cleaner' + # Use pry-rails for debugging + gem 'pry-rails', '~> 0.3.4' end diff --git a/Gemfile.lock b/Gemfile.lock index df7071d..fee3b83 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -144,6 +144,8 @@ GEM coderay (~> 1.1.0) method_source (~> 0.8.1) slop (~> 3.4) + pry-rails (0.3.4) + pry (>= 0.9.10) rack (1.6.4) rack-test (0.6.3) rack (>= 1.0) @@ -256,6 +258,7 @@ DEPENDENCIES jbuilder (~> 2.0) jquery-rails pg + pry-rails (~> 0.3.4) rails (= 4.2.3) rspec-rails sass-rails (~> 5.0) From 958349828b8f9ca512a08d4976c94b791ee9a0ab Mon Sep 17 00:00:00 2001 From: moeabdol Date: Thu, 15 Oct 2015 16:32:27 +0300 Subject: [PATCH 06/21] user signup/login/logout --- app/assets/javascripts/users.coffee | 3 ++ app/assets/stylesheets/users.scss | 3 ++ app/controllers/application_controller.rb | 10 ++++ app/controllers/static_pages_controller.rb | 2 + app/controllers/users_controller.rb | 10 ++++ app/helpers/users_helper.rb | 2 + app/models/user.rb | 1 + app/views/devise/registrations/new.html.erb | 7 ++- app/views/layouts/application.html.erb | 8 ++- app/views/users/edit.html.erb | 2 + app/views/users/show.html.erb | 2 + app/views/users/update.html.erb | 2 + config/routes.rb | 10 ++++ spec/controllers/users_controller_spec.rb | 13 +++++ spec/factories/users.rb | 5 +- spec/features/user_login_spec.rb | 54 +++++++++++++++++++++ spec/features/user_signup_spec.rb | 41 ++++++++++++++++ spec/features/visitor_spec.rb | 14 ++++++ spec/helpers/users_helper_spec.rb | 4 ++ spec/models/user_spec.rb | 6 +++ 20 files changed, 195 insertions(+), 4 deletions(-) create mode 100644 app/assets/javascripts/users.coffee create mode 100644 app/assets/stylesheets/users.scss create mode 100644 app/controllers/users_controller.rb create mode 100644 app/helpers/users_helper.rb create mode 100644 app/views/users/edit.html.erb create mode 100644 app/views/users/show.html.erb create mode 100644 app/views/users/update.html.erb create mode 100644 spec/controllers/users_controller_spec.rb create mode 100644 spec/features/user_login_spec.rb create mode 100644 spec/features/user_signup_spec.rb create mode 100644 spec/features/visitor_spec.rb create mode 100644 spec/helpers/users_helper_spec.rb diff --git a/app/assets/javascripts/users.coffee b/app/assets/javascripts/users.coffee new file mode 100644 index 0000000..24f83d1 --- /dev/null +++ b/app/assets/javascripts/users.coffee @@ -0,0 +1,3 @@ +# Place all the behaviors and hooks related to the matching controller here. +# All this logic will automatically be available in application.js. +# You can use CoffeeScript in this file: http://coffeescript.org/ diff --git a/app/assets/stylesheets/users.scss b/app/assets/stylesheets/users.scss new file mode 100644 index 0000000..1efc835 --- /dev/null +++ b/app/assets/stylesheets/users.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the users controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index d83690e..9e6f29a 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -2,4 +2,14 @@ class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception + before_action :authenticate_user! + before_action :devise_user_params, if: :devise_controller? + + private + + def devise_user_params + devise_parameter_sanitizer.for(:sign_up) { + |user| user.permit(:username, :email, :password, :password_confirmation) + } + end end diff --git a/app/controllers/static_pages_controller.rb b/app/controllers/static_pages_controller.rb index 91da0c2..35cb7ae 100644 --- a/app/controllers/static_pages_controller.rb +++ b/app/controllers/static_pages_controller.rb @@ -1,4 +1,6 @@ class StaticPagesController < ApplicationController + skip_before_action :authenticate_user! + def index end end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb new file mode 100644 index 0000000..d2005ab --- /dev/null +++ b/app/controllers/users_controller.rb @@ -0,0 +1,10 @@ +class UsersController < ApplicationController + def show + end + + def edit + end + + def update + end +end diff --git a/app/helpers/users_helper.rb b/app/helpers/users_helper.rb new file mode 100644 index 0000000..2310a24 --- /dev/null +++ b/app/helpers/users_helper.rb @@ -0,0 +1,2 @@ +module UsersHelper +end diff --git a/app/models/user.rb b/app/models/user.rb index c822027..f5e3336 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -3,4 +3,5 @@ class User < ActiveRecord::Base # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable + validates :username, presence: true end diff --git a/app/views/devise/registrations/new.html.erb b/app/views/devise/registrations/new.html.erb index 5a238ce..ce6ad6a 100644 --- a/app/views/devise/registrations/new.html.erb +++ b/app/views/devise/registrations/new.html.erb @@ -3,9 +3,14 @@ <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> <%= devise_error_messages! %> +
+ <%= f.label :username %>
+ <%= f.text_field :username, autofocus: true %> +
+
<%= f.label :email %>
- <%= f.email_field :email, autofocus: true %> + <%= f.email_field :email, autofocus: false %>
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 942b27d..b16b535 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -28,7 +28,13 @@
diff --git a/app/views/users/edit.html.erb b/app/views/users/edit.html.erb new file mode 100644 index 0000000..1881fbd --- /dev/null +++ b/app/views/users/edit.html.erb @@ -0,0 +1,2 @@ +

Users#edit

+

Find me in app/views/users/edit.html.erb

diff --git a/app/views/users/show.html.erb b/app/views/users/show.html.erb new file mode 100644 index 0000000..e5fa3ad --- /dev/null +++ b/app/views/users/show.html.erb @@ -0,0 +1,2 @@ +

Users#show

+

Find me in app/views/users/show.html.erb

diff --git a/app/views/users/update.html.erb b/app/views/users/update.html.erb new file mode 100644 index 0000000..cabbde1 --- /dev/null +++ b/app/views/users/update.html.erb @@ -0,0 +1,2 @@ +

Users#update

+

Find me in app/views/users/update.html.erb

diff --git a/config/routes.rb b/config/routes.rb index 2d31e75..cea6ac2 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,5 +1,15 @@ Rails.application.routes.draw do + devise_for :users + authenticated :user do + root "users#show", as: :authenticated_root + end + + resources :users, only: [:show, :edit, :update] + #get 'users/show' + #get 'users/edit' + #get 'users/update' + root 'static_pages#index' # The priority is based upon order of creation: first created -> highest priority. diff --git a/spec/controllers/users_controller_spec.rb b/spec/controllers/users_controller_spec.rb new file mode 100644 index 0000000..a46234d --- /dev/null +++ b/spec/controllers/users_controller_spec.rb @@ -0,0 +1,13 @@ +require 'rails_helper' + +RSpec.describe UsersController, type: :controller do + + describe "GET #show" do + end + + describe "GET #edit" do + end + + describe "GET #update" do + end +end diff --git a/spec/factories/users.rb b/spec/factories/users.rb index 209e6b1..0805a93 100644 --- a/spec/factories/users.rb +++ b/spec/factories/users.rb @@ -1,6 +1,7 @@ FactoryGirl.define do factory :user do - + username { Faker::Internet.name } + email { Faker::Internet.email } + password { Faker::Internet.password } end - end diff --git a/spec/features/user_login_spec.rb b/spec/features/user_login_spec.rb new file mode 100644 index 0000000..75b4d4f --- /dev/null +++ b/spec/features/user_login_spec.rb @@ -0,0 +1,54 @@ +require "rails_helper" + +def login(user) + visit new_user_session_path + fill_in "user_email", with: user.email + fill_in "user_password", with: user.password + click_on "Log in" +end + +def logout(user) + click_on "Sign Out" +end + +RSpec.describe "user login/logout" do + let(:user) { create(:user) } + + describe "login" do + context "with valid attributes" do + it "granted access" do + login(user) + expect(current_path).to eq(authenticated_root_path) + end + end + + context "with invalid attributes" do + it "denied access when provided wrong email" do + user.email = "wrong_email@example.com" + login(user) + expect(current_path).to eq(new_user_session_path) + end + + it "denied access when provided wrong password" do + user.password = "wrong password" + login(user) + expect(current_path).to eq(new_user_session_path) + end + end + + it "denied access to unregistered user" do + user = build(:user) + login(user) + expect(current_path).to eq(new_user_session_path) + end + end + + describe "logout" do + it "logged in user can logout" do + login(user) + expect(current_path).to eq(authenticated_root_path) + logout(user) + expect(current_path).to eq(root_path) + end + end +end diff --git a/spec/features/user_signup_spec.rb b/spec/features/user_signup_spec.rb new file mode 100644 index 0000000..d47652f --- /dev/null +++ b/spec/features/user_signup_spec.rb @@ -0,0 +1,41 @@ +require "rails_helper" + +RSpec.describe "user signup" do + def signup(user) + visit new_user_registration_path + fill_in "user_username", with: user.username + fill_in "user_email", with: user.email + fill_in "user_password", with: user.password + fill_in "user_password_confirmation", with: user.password + click_on "Sign up" + end + + let(:user) { build(:user) } + + context "with valid attributes" do + it "registered successfully" do + signup(user) + expect(current_path).to eq(authenticated_root_path) + end + end + + context "with invalid attributes" do + it "failes registrations when user does not provid a username" do + user.username = nil + signup(user) + expect(page).to have_content("Username can't be blank") + end + + it "failes registrations when user does not provid a email" do + user.email = nil + signup(user) + expect(page).to have_content("Email can't be blank") + end + + it "failes registrations when user does not provid a password" do + user.password = nil + signup(user) + expect(page).to have_content("Password can't be blank") + end + end +end diff --git a/spec/features/visitor_spec.rb b/spec/features/visitor_spec.rb new file mode 100644 index 0000000..876dd97 --- /dev/null +++ b/spec/features/visitor_spec.rb @@ -0,0 +1,14 @@ +require "rails_helper" + +RSpec.describe "visitor" do + it "granted access when visiting site root" do + visit root_path + expect(current_path).to eq(root_path) + end + + it "denied access when visiting restricted portion of the site" do + user = create(:user) + visit user_path(user) + expect(current_path).to eq(new_user_session_path) + end +end diff --git a/spec/helpers/users_helper_spec.rb b/spec/helpers/users_helper_spec.rb new file mode 100644 index 0000000..e59c546 --- /dev/null +++ b/spec/helpers/users_helper_spec.rb @@ -0,0 +1,4 @@ +require 'rails_helper' + +RSpec.describe UsersHelper, type: :helper do +end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index ab0da92..b7d907d 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -1,4 +1,10 @@ require 'rails_helper' RSpec.describe User, type: :model do + context "validations" do + it "must have a username" do + user = build(:user, username: nil) + expect(user).not_to be_valid + end + end end From 83ddf8e77bd0e5d4fe1b03da4f6446a6adc28673 Mon Sep 17 00:00:00 2001 From: moeabdol Date: Thu, 15 Oct 2015 16:46:01 +0300 Subject: [PATCH 07/21] cleanup code --- spec/controllers/users_controller_spec.rb | 1 - spec/factories/users.rb | 3 ++- spec/features/user_signup_spec.rb | 18 +++++++++--------- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/spec/controllers/users_controller_spec.rb b/spec/controllers/users_controller_spec.rb index a46234d..5d3ec29 100644 --- a/spec/controllers/users_controller_spec.rb +++ b/spec/controllers/users_controller_spec.rb @@ -1,7 +1,6 @@ require 'rails_helper' RSpec.describe UsersController, type: :controller do - describe "GET #show" do end diff --git a/spec/factories/users.rb b/spec/factories/users.rb index 0805a93..a9111d6 100644 --- a/spec/factories/users.rb +++ b/spec/factories/users.rb @@ -1,7 +1,8 @@ FactoryGirl.define do factory :user do - username { Faker::Internet.name } email { Faker::Internet.email } password { Faker::Internet.password } + username { Faker::Internet.name } + biography { Faker::Lorem.paragraph(3) } end end diff --git a/spec/features/user_signup_spec.rb b/spec/features/user_signup_spec.rb index d47652f..13b5ee9 100644 --- a/spec/features/user_signup_spec.rb +++ b/spec/features/user_signup_spec.rb @@ -1,15 +1,15 @@ require "rails_helper" -RSpec.describe "user signup" do - def signup(user) - visit new_user_registration_path - fill_in "user_username", with: user.username - fill_in "user_email", with: user.email - fill_in "user_password", with: user.password - fill_in "user_password_confirmation", with: user.password - click_on "Sign up" - end +def signup(user) + visit new_user_registration_path + fill_in "user_username", with: user.username + fill_in "user_email", with: user.email + fill_in "user_password", with: user.password + fill_in "user_password_confirmation", with: user.password + click_on "Sign up" +end +RSpec.describe "user signup" do let(:user) { build(:user) } context "with valid attributes" do From b647d73a8de165521515d6792d4e8ff066914a7b Mon Sep 17 00:00:00 2001 From: moeabdol Date: Thu, 15 Oct 2015 20:17:52 +0300 Subject: [PATCH 08/21] user profile --- Gemfile | 3 +- Gemfile.lock | 12 ++- app/controllers/users_controller.rb | 5 ++ app/views/layouts/application.html.erb | 10 ++- app/views/users/show.html.erb | 11 ++- spec/controllers/users_controller_spec.rb | 13 ++++ spec/factories/users.rb | 4 +- spec/features/user_login_spec.rb | 54 -------------- spec/features/user_profile_spec.rb | 14 ++++ .../features/user_signup_login_logout_spec.rb | 74 +++++++++++++++++++ spec/features/user_signup_spec.rb | 41 ---------- spec/rails_helper.rb | 5 ++ spec/support/session_helpers.rb | 21 ++++++ 13 files changed, 161 insertions(+), 106 deletions(-) delete mode 100644 spec/features/user_login_spec.rb create mode 100644 spec/features/user_profile_spec.rb create mode 100644 spec/features/user_signup_login_logout_spec.rb delete mode 100644 spec/features/user_signup_spec.rb create mode 100644 spec/support/session_helpers.rb diff --git a/Gemfile b/Gemfile index 5f399ea..d7ec304 100644 --- a/Gemfile +++ b/Gemfile @@ -56,5 +56,6 @@ group :development, :test do # Use database_cleaner in place of transactional fixtures gem 'database_cleaner' # Use pry-rails for debugging - gem 'pry-rails', '~> 0.3.4' + gem 'pry-rails' + gem "pry-byebug" end diff --git a/Gemfile.lock b/Gemfile.lock index fee3b83..5a49e22 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -47,7 +47,8 @@ GEM autoprefixer-rails (>= 5.0.0.1) sass (>= 3.3.0) builder (3.2.2) - byebug (6.0.2) + byebug (5.0.0) + columnize (= 0.9.0) capybara (2.5.0) mime-types (>= 1.16) nokogiri (>= 1.3.3) @@ -62,6 +63,7 @@ GEM coffee-script-source execjs coffee-script-source (1.9.1.1) + columnize (0.9.0) database_cleaner (1.5.0) debug_inspector (0.0.2) devise (3.5.2) @@ -140,10 +142,13 @@ GEM shellany (~> 0.0) orm_adapter (0.5.0) pg (0.18.3) - pry (0.10.2) + pry (0.10.3) coderay (~> 1.1.0) method_source (~> 0.8.1) slop (~> 3.4) + pry-byebug (3.2.0) + byebug (~> 5.0) + pry (~> 0.10) pry-rails (0.3.4) pry (>= 0.9.10) rack (1.6.4) @@ -258,7 +263,8 @@ DEPENDENCIES jbuilder (~> 2.0) jquery-rails pg - pry-rails (~> 0.3.4) + pry-byebug + pry-rails rails (= 4.2.3) rspec-rails sass-rails (~> 5.0) diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index d2005ab..d24461f 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -1,5 +1,10 @@ class UsersController < ApplicationController def show + if params[:id] + @user = User.find(params[:id]) + else + @user = current_user + end end def edit diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index b16b535..22923b6 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -40,10 +40,14 @@ -

<%= notice %>

-

<%= alert %>

+
+
+

<%= notice %>

+

<%= alert %>

- <%= yield %> + <%= yield %> +
+
diff --git a/app/views/users/show.html.erb b/app/views/users/show.html.erb index e5fa3ad..2c09a4f 100644 --- a/app/views/users/show.html.erb +++ b/app/views/users/show.html.erb @@ -1,2 +1,9 @@ -

Users#show

-

Find me in app/views/users/show.html.erb

+
+
+
+

<%= @user.username %> Profile

+

<%= @user.email %>

+

<%= @user.biography %>

+
+
diff --git a/spec/controllers/users_controller_spec.rb b/spec/controllers/users_controller_spec.rb index 5d3ec29..b69b743 100644 --- a/spec/controllers/users_controller_spec.rb +++ b/spec/controllers/users_controller_spec.rb @@ -2,6 +2,19 @@ RSpec.describe UsersController, type: :controller do describe "GET #show" do + before(:example) do + @user = create(:user) + sign_in(@user) + get :show, id: @user + end + + it "assigns @user" do + expect(assigns(:user)).to eq(@user) + end + + it "renders show template" do + expect(response).to render_template(:show) + end end describe "GET #edit" do diff --git a/spec/factories/users.rb b/spec/factories/users.rb index a9111d6..3a81c80 100644 --- a/spec/factories/users.rb +++ b/spec/factories/users.rb @@ -2,7 +2,7 @@ factory :user do email { Faker::Internet.email } password { Faker::Internet.password } - username { Faker::Internet.name } - biography { Faker::Lorem.paragraph(3) } + username { Faker::Internet.user_name } + biography { Faker::Lorem.paragraphs(3) } end end diff --git a/spec/features/user_login_spec.rb b/spec/features/user_login_spec.rb deleted file mode 100644 index 75b4d4f..0000000 --- a/spec/features/user_login_spec.rb +++ /dev/null @@ -1,54 +0,0 @@ -require "rails_helper" - -def login(user) - visit new_user_session_path - fill_in "user_email", with: user.email - fill_in "user_password", with: user.password - click_on "Log in" -end - -def logout(user) - click_on "Sign Out" -end - -RSpec.describe "user login/logout" do - let(:user) { create(:user) } - - describe "login" do - context "with valid attributes" do - it "granted access" do - login(user) - expect(current_path).to eq(authenticated_root_path) - end - end - - context "with invalid attributes" do - it "denied access when provided wrong email" do - user.email = "wrong_email@example.com" - login(user) - expect(current_path).to eq(new_user_session_path) - end - - it "denied access when provided wrong password" do - user.password = "wrong password" - login(user) - expect(current_path).to eq(new_user_session_path) - end - end - - it "denied access to unregistered user" do - user = build(:user) - login(user) - expect(current_path).to eq(new_user_session_path) - end - end - - describe "logout" do - it "logged in user can logout" do - login(user) - expect(current_path).to eq(authenticated_root_path) - logout(user) - expect(current_path).to eq(root_path) - end - end -end diff --git a/spec/features/user_profile_spec.rb b/spec/features/user_profile_spec.rb new file mode 100644 index 0000000..0929f42 --- /dev/null +++ b/spec/features/user_profile_spec.rb @@ -0,0 +1,14 @@ +require "rails_helper" + +RSpec.describe "user profile" do + before(:example) do + @user = create(:user) + signin(@user) + end + + it "shows user information" do + expect(page).to have_selector("#username", text: @user.username) + expect(page).to have_selector("#email", text: @user.email) + expect(page).to have_selector("#biography", text: @user.biography) + end +end diff --git a/spec/features/user_signup_login_logout_spec.rb b/spec/features/user_signup_login_logout_spec.rb new file mode 100644 index 0000000..d95ee9d --- /dev/null +++ b/spec/features/user_signup_login_logout_spec.rb @@ -0,0 +1,74 @@ +require "rails_helper" + +RSpec.describe "user signup" do + let(:user) { build(:user) } + + context "with valid attributes" do + it "registered successfully" do + signup(user) + expect(current_path).to eq(authenticated_root_path) + end + end + + context "with invalid attributes" do + it "failes registrations when user does not provid a username" do + user.username = nil + signup(user) + expect(page).to have_content("Username can't be blank") + end + + it "failes registrations when user does not provid a email" do + user.email = nil + signup(user) + expect(page).to have_content("Email can't be blank") + end + + it "failes registrations when user does not provid a password" do + user.password = nil + signup(user) + expect(page).to have_content("Password can't be blank") + end + end +end + +RSpec.describe "user signin/signout" do + let(:user) { create(:user) } + + describe "sign in" do + context "with valid attributes" do + it "granted access" do + signin(user) + expect(current_path).to eq(authenticated_root_path) + end + end + + context "with invalid attributes" do + it "denied access when provided wrong email" do + user.email = "wrong_email@example.com" + signin(user) + expect(current_path).to eq(new_user_session_path) + end + + it "denied access when provided wrong password" do + user.password = "wrong password" + signin(user) + expect(current_path).to eq(new_user_session_path) + end + end + + it "denied access to unregistered user" do + user = build(:user) + signin(user) + expect(current_path).to eq(new_user_session_path) + end + end + + describe "sign out" do + it "signed in user can sign out" do + signin(user) + expect(current_path).to eq(authenticated_root_path) + signout(user) + expect(current_path).to eq(root_path) + end + end +end diff --git a/spec/features/user_signup_spec.rb b/spec/features/user_signup_spec.rb deleted file mode 100644 index 13b5ee9..0000000 --- a/spec/features/user_signup_spec.rb +++ /dev/null @@ -1,41 +0,0 @@ -require "rails_helper" - -def signup(user) - visit new_user_registration_path - fill_in "user_username", with: user.username - fill_in "user_email", with: user.email - fill_in "user_password", with: user.password - fill_in "user_password_confirmation", with: user.password - click_on "Sign up" -end - -RSpec.describe "user signup" do - let(:user) { build(:user) } - - context "with valid attributes" do - it "registered successfully" do - signup(user) - expect(current_path).to eq(authenticated_root_path) - end - end - - context "with invalid attributes" do - it "failes registrations when user does not provid a username" do - user.username = nil - signup(user) - expect(page).to have_content("Username can't be blank") - end - - it "failes registrations when user does not provid a email" do - user.email = nil - signup(user) - expect(page).to have_content("Email can't be blank") - end - - it "failes registrations when user does not provid a password" do - user.password = nil - signup(user) - expect(page).to have_content("Password can't be blank") - end - end -end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb index 4376675..962f08c 100644 --- a/spec/rails_helper.rb +++ b/spec/rails_helper.rb @@ -7,6 +7,8 @@ require 'rspec/rails' require 'capybara/rails' +require "support/session_helpers" + # Add additional requires below this line. Rails is not loaded until this point! # Requires supporting ruby files with custom matchers and macros, etc, in @@ -82,4 +84,7 @@ # include Devise test helpers config.include Devise::TestHelpers, type: :controller + + # include our SessionHelpers to signup/login/logout + config.include SessionHelpers, type: :feature end diff --git a/spec/support/session_helpers.rb b/spec/support/session_helpers.rb new file mode 100644 index 0000000..558ff8f --- /dev/null +++ b/spec/support/session_helpers.rb @@ -0,0 +1,21 @@ +module SessionHelpers + def signup(user) + visit new_user_registration_path + fill_in "user_username", with: user.username + fill_in "user_email", with: user.email + fill_in "user_password", with: user.password + fill_in "user_password_confirmation", with: user.password + click_on "Sign up" + end + + def signin(user) + visit new_user_session_path + fill_in "user_email", with: user.email + fill_in "user_password", with: user.password + click_on "Log in" + end + + def signout(user) + click_on "Sign Out" + end +end From dfd13b354a95226e04de9075af9a527d8d0d009e Mon Sep 17 00:00:00 2001 From: moeabdol Date: Thu, 15 Oct 2015 22:09:11 +0300 Subject: [PATCH 09/21] user edit profile --- app/controllers/application_controller.rb | 5 ++ app/controllers/users_controller.rb | 6 -- app/views/devise/registrations/edit.html.erb | 14 +++- app/views/devise/registrations/new.html.erb | 2 +- app/views/users/edit.html.erb | 2 - app/views/users/show.html.erb | 22 ++++-- app/views/users/update.html.erb | 2 - spec/controllers/users_controller_spec.rb | 6 -- spec/features/user_edit_profile_spec.rb | 76 +++++++++++++++++++ ...file_spec.rb => user_show_profile_spec.rb} | 0 .../features/user_signup_login_logout_spec.rb | 2 +- spec/support/session_helpers.rb | 2 +- 12 files changed, 110 insertions(+), 29 deletions(-) delete mode 100644 app/views/users/edit.html.erb delete mode 100644 app/views/users/update.html.erb create mode 100644 spec/features/user_edit_profile_spec.rb rename spec/features/{user_profile_spec.rb => user_show_profile_spec.rb} (100%) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 9e6f29a..b8915c3 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -11,5 +11,10 @@ def devise_user_params devise_parameter_sanitizer.for(:sign_up) { |user| user.permit(:username, :email, :password, :password_confirmation) } + + devise_parameter_sanitizer.for(:account_update) { + |user| user.permit(:username, :email, :biography, :password, + :password_confirmation, :current_password) + } end end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index d24461f..d7673b0 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -6,10 +6,4 @@ def show @user = current_user end end - - def edit - end - - def update - end end diff --git a/app/views/devise/registrations/edit.html.erb b/app/views/devise/registrations/edit.html.erb index 3ea40f0..5002343 100644 --- a/app/views/devise/registrations/edit.html.erb +++ b/app/views/devise/registrations/edit.html.erb @@ -1,11 +1,21 @@ -

Edit <%= resource_name.to_s.humanize %>

+

Edit Profile

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %> <%= devise_error_messages! %> +
+ <%= f.label :username %>
+ <%= f.text_field :username, autofocus: true %> +
+
<%= f.label :email %>
- <%= f.email_field :email, autofocus: true %> + <%= f.email_field :email %> +
+ +
+ <%= f.label :biography %>
+ <%= f.text_area :biography %>
<% if devise_mapping.confirmable? && resource.pending_reconfirmation? %> diff --git a/app/views/devise/registrations/new.html.erb b/app/views/devise/registrations/new.html.erb index ce6ad6a..fae14cb 100644 --- a/app/views/devise/registrations/new.html.erb +++ b/app/views/devise/registrations/new.html.erb @@ -10,7 +10,7 @@
<%= f.label :email %>
- <%= f.email_field :email, autofocus: false %> + <%= f.email_field :email %>
diff --git a/app/views/users/edit.html.erb b/app/views/users/edit.html.erb deleted file mode 100644 index 1881fbd..0000000 --- a/app/views/users/edit.html.erb +++ /dev/null @@ -1,2 +0,0 @@ -

Users#edit

-

Find me in app/views/users/edit.html.erb

diff --git a/app/views/users/show.html.erb b/app/views/users/show.html.erb index 2c09a4f..5353586 100644 --- a/app/views/users/show.html.erb +++ b/app/views/users/show.html.erb @@ -1,9 +1,15 @@ -
-
-
-

<%= @user.username %> Profile

-

<%= @user.email %>

-

<%= @user.biography %>

-
-
+
+

<%= @user.username %>'s Profile

+

Email: <%= @user.email %>

+

Auto-Biography: <%= @user.biography %>

+
+
+ +
+ +
+
+ <%= link_to "Edit Profile", edit_user_registration_path(@user), id: "edit_user_link" %> +
diff --git a/app/views/users/update.html.erb b/app/views/users/update.html.erb deleted file mode 100644 index cabbde1..0000000 --- a/app/views/users/update.html.erb +++ /dev/null @@ -1,2 +0,0 @@ -

Users#update

-

Find me in app/views/users/update.html.erb

diff --git a/spec/controllers/users_controller_spec.rb b/spec/controllers/users_controller_spec.rb index b69b743..04bdc50 100644 --- a/spec/controllers/users_controller_spec.rb +++ b/spec/controllers/users_controller_spec.rb @@ -16,10 +16,4 @@ expect(response).to render_template(:show) end end - - describe "GET #edit" do - end - - describe "GET #update" do - end end diff --git a/spec/features/user_edit_profile_spec.rb b/spec/features/user_edit_profile_spec.rb new file mode 100644 index 0000000..28890e7 --- /dev/null +++ b/spec/features/user_edit_profile_spec.rb @@ -0,0 +1,76 @@ +require "rails_helper" + +RSpec.describe "user edit profile" do + let(:user) { create(:user) } + + before(:example) do + signin(user) + click_on "edit_user_link" + end + + context "with valid attributes" do + it "updates username successfully" do + fill_in "user_username", with: "moeabdol" + fill_in "user_current_password", with: user.password + click_on "Update" + expect(page).to have_selector("#username", text: "moeabdol") + end + + it "updates email successfully" do + fill_in "user_email", with: "moeabdol@example.com" + fill_in "user_current_password", with: user.password + click_on "Update" + expect(page).to have_selector("#email", text: "moeabdol@example.com") + end + + it "updates biography successfully" do + fill_in "user_biography", with: "hello world" + fill_in "user_current_password", with: user.password + click_on "Update" + expect(page).to have_selector("#biography", text: "hello world") + end + + it "updates password successfully" do + fill_in "user_password", with: "new password" + fill_in "user_password_confirmation", with: "new password" + fill_in "user_current_password", with: user.password + click_on "Update" + signout + user.password = "new password" + signin(user) + expect(current_path).to eq(authenticated_root_path) + end + end + + context "with invalid attributes" do + it "fails update when username is blank" do + fill_in "user_username", with: "" + fill_in "user_current_password", with: user.password + click_on "Update" + expect(page).to have_content("Username can't be blank") + end + + it "fails update when email blank" do + fill_in "user_email", with: "" + fill_in "user_current_password", with: user.password + click_on "Update" + expect(page).to have_content("Email can't be blank") + end + + it "fails update when password and confirmation don't match" do + fill_in "user_password", with: "first password" + fill_in "user_password_confirmation", with: "second password" + fill_in "user_current_password", with: user.password + click_on "Update" + expect(page).to have_content("Password confirmation doesn't match " + + "Password") + end + + it "fails update if user forgets current password" do + fill_in "user_username", with: "moeabdol" + fill_in "user_current_password", with: "Oops! I forgot the password" + click_on "Update" + expect(page).to have_content("Current password is invalid") + end + end +end diff --git a/spec/features/user_profile_spec.rb b/spec/features/user_show_profile_spec.rb similarity index 100% rename from spec/features/user_profile_spec.rb rename to spec/features/user_show_profile_spec.rb diff --git a/spec/features/user_signup_login_logout_spec.rb b/spec/features/user_signup_login_logout_spec.rb index d95ee9d..67f8d51 100644 --- a/spec/features/user_signup_login_logout_spec.rb +++ b/spec/features/user_signup_login_logout_spec.rb @@ -67,7 +67,7 @@ it "signed in user can sign out" do signin(user) expect(current_path).to eq(authenticated_root_path) - signout(user) + signout expect(current_path).to eq(root_path) end end diff --git a/spec/support/session_helpers.rb b/spec/support/session_helpers.rb index 558ff8f..d4da793 100644 --- a/spec/support/session_helpers.rb +++ b/spec/support/session_helpers.rb @@ -15,7 +15,7 @@ def signin(user) click_on "Log in" end - def signout(user) + def signout click_on "Sign Out" end end From fdc55a1eda9117e8ac3485b9fcfd750929007f82 Mon Sep 17 00:00:00 2001 From: moeabdol Date: Fri, 16 Oct 2015 03:49:16 +0300 Subject: [PATCH 10/21] disable user from destroying their account --- app/views/devise/registrations/edit.html.erb | 4 ---- config/routes.rb | 12 +++++++++++- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/app/views/devise/registrations/edit.html.erb b/app/views/devise/registrations/edit.html.erb index 5002343..4a88c96 100644 --- a/app/views/devise/registrations/edit.html.erb +++ b/app/views/devise/registrations/edit.html.erb @@ -42,8 +42,4 @@
<% end %> -

Cancel my account

- -

Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %>

- <%= link_to "Back", :back %> diff --git a/config/routes.rb b/config/routes.rb index cea6ac2..044994a 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,6 +1,16 @@ Rails.application.routes.draw do - devise_for :users + devise_for :users, skip: :registrations + devise_scope :user do + resource :registration, + only: [:new, :create, :edit, :update], + path: "users", + path_names: { new: "sign_up" }, + controller: "devise/registrations", + as: :user_registration do + get :cancel + end + end authenticated :user do root "users#show", as: :authenticated_root end From e21b93f5e0f09ec2b6d9fb5ab7afd1a1fb3e2f45 Mon Sep 17 00:00:00 2001 From: moeabdol Date: Fri, 16 Oct 2015 04:08:18 +0300 Subject: [PATCH 11/21] cleanup users routes --- config/routes.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/routes.rb b/config/routes.rb index 044994a..95085b1 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -15,7 +15,7 @@ root "users#show", as: :authenticated_root end - resources :users, only: [:show, :edit, :update] + resources :users, only: [:show] #get 'users/show' #get 'users/edit' #get 'users/update' From dfbf9f05ef046814d88e023d401f52b9409cae05 Mon Sep 17 00:00:00 2001 From: moeabdol Date: Sun, 18 Oct 2015 11:54:46 +0300 Subject: [PATCH 12/21] add omniauth-github gem and identity model * add and configure omniauth-gem with devise * introduce identity model to hold social identites of different users * add omniauth_callback_controller to handle callbacks from different providers --- Gemfile | 2 + Gemfile.lock | 22 +++++++++ .../omniauth_callbacks_controller.rb | 4 ++ app/models/identity.rb | 6 +++ app/models/user.rb | 4 +- config/initializers/devise.rb | 2 + config/routes.rb | 3 +- .../20151018081925_create_identities.rb | 11 +++++ db/schema.rb | 13 ++++- spec/factories/identities.rb | 9 ++++ spec/models/identity_spec.rb | 48 +++++++++++++++++++ 11 files changed, 121 insertions(+), 3 deletions(-) create mode 100644 app/controllers/omniauth_callbacks_controller.rb create mode 100644 app/models/identity.rb create mode 100644 db/migrate/20151018081925_create_identities.rb create mode 100644 spec/factories/identities.rb create mode 100644 spec/models/identity_spec.rb diff --git a/Gemfile b/Gemfile index d7ec304..b7f5aa3 100644 --- a/Gemfile +++ b/Gemfile @@ -26,6 +26,8 @@ gem 'jbuilder', '~> 2.0' gem 'sdoc', '~> 0.4.0', group: :doc # Devise gem for authentication gem 'devise', '~> 3.5.2' +# omniauth-github gem for social signin +gem 'omniauth-github', '~> 1.1.2' # Use ActiveModel has_secure_password # gem 'bcrypt', '~> 3.1.7' diff --git a/Gemfile.lock b/Gemfile.lock index 5a49e22..33c7d7f 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -87,6 +87,8 @@ GEM railties (>= 3.0.0) faker (1.5.0) i18n (~> 0.5) + faraday (0.9.2) + multipart-post (>= 1.2, < 3) ffi (1.9.10) font-awesome-rails (4.4.0.0) railties (>= 3.2, < 5.0) @@ -111,6 +113,7 @@ GEM guard (~> 2.1) guard-compat (~> 1.1) rspec (>= 2.99.0, < 4.0) + hashie (3.4.2) http_parser.rb (0.6.0) i18n (0.7.0) jbuilder (2.3.2) @@ -121,6 +124,7 @@ GEM railties (>= 4.2.0) thor (>= 0.14, < 2.0) json (1.8.3) + jwt (1.5.1) listen (3.0.3) rb-fsevent (>= 0.9.3) rb-inotify (>= 0.9) @@ -134,12 +138,29 @@ GEM mini_portile (0.6.2) minitest (5.8.1) multi_json (1.11.2) + multi_xml (0.5.5) + multipart-post (2.0.0) nenv (0.2.0) nokogiri (1.6.6.2) mini_portile (~> 0.6.0) notiffany (0.0.8) nenv (~> 0.1) shellany (~> 0.0) + oauth2 (1.0.0) + faraday (>= 0.8, < 0.10) + jwt (~> 1.0) + multi_json (~> 1.3) + multi_xml (~> 0.5) + rack (~> 1.2) + omniauth (1.2.2) + hashie (>= 1.2, < 4) + rack (~> 1.0) + omniauth-github (1.1.2) + omniauth (~> 1.0) + omniauth-oauth2 (~> 1.1) + omniauth-oauth2 (1.3.1) + oauth2 (~> 1.0) + omniauth (~> 1.2) orm_adapter (0.5.0) pg (0.18.3) pry (0.10.3) @@ -262,6 +283,7 @@ DEPENDENCIES guard-rspec jbuilder (~> 2.0) jquery-rails + omniauth-github (~> 1.1.2) pg pry-byebug pry-rails diff --git a/app/controllers/omniauth_callbacks_controller.rb b/app/controllers/omniauth_callbacks_controller.rb new file mode 100644 index 0000000..c174d34 --- /dev/null +++ b/app/controllers/omniauth_callbacks_controller.rb @@ -0,0 +1,4 @@ +class OmniauthCallbacksController < Devise::OmniauthCallbacksController + def github + end +end diff --git a/app/models/identity.rb b/app/models/identity.rb new file mode 100644 index 0000000..3f1a1b8 --- /dev/null +++ b/app/models/identity.rb @@ -0,0 +1,6 @@ +class Identity < ActiveRecord::Base + belongs_to :user + validates :user_id, presence: true + validates :uid, presence: true, uniqueness: { scope: :provider } + validates :provider, presence: true, uniqueness: { scope: :user_id } +end diff --git a/app/models/user.rb b/app/models/user.rb index f5e3336..fc377c9 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -2,6 +2,8 @@ class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, - :recoverable, :rememberable, :trackable, :validatable + :recoverable, :rememberable, :trackable, :validatable, + :omniauthable, omniauth_providers: [:github] + has_many :identities validates :username, presence: true end diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb index 741766c..0fa01be 100644 --- a/config/initializers/devise.rb +++ b/config/initializers/devise.rb @@ -236,6 +236,8 @@ # 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, Rails.application.secrets.github_consumer_key, + Rails.application.secrets.github_consumer_secret # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or diff --git a/config/routes.rb b/config/routes.rb index 95085b1..b590591 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,6 +1,7 @@ Rails.application.routes.draw do - devise_for :users, skip: :registrations + devise_for :users, skip: :registrations, + controllers: { omniauth_callbacks: "omniauth_callbacks" } devise_scope :user do resource :registration, only: [:new, :create, :edit, :update], diff --git a/db/migrate/20151018081925_create_identities.rb b/db/migrate/20151018081925_create_identities.rb new file mode 100644 index 0000000..0d3a5a4 --- /dev/null +++ b/db/migrate/20151018081925_create_identities.rb @@ -0,0 +1,11 @@ +class CreateIdentities < ActiveRecord::Migration + def change + create_table :identities do |t| + t.references :user, index: true, foreign_key: true + t.string :provider, null: false + t.string :uid, null: false + + t.timestamps null: false + end + end +end diff --git a/db/schema.rb b/db/schema.rb index 575444f..6b6c816 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -11,7 +11,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 20151015065131) do +ActiveRecord::Schema.define(version: 20151018081925) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -24,6 +24,16 @@ t.datetime "updated_at", null: false end + create_table "identities", force: :cascade do |t| + t.integer "user_id" + t.string "provider", null: false + t.string "uid", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + + add_index "identities", ["user_id"], name: "index_identities_on_user_id", using: :btree + create_table "users", force: :cascade do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false @@ -44,4 +54,5 @@ add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree + add_foreign_key "identities", "users" end diff --git a/spec/factories/identities.rb b/spec/factories/identities.rb new file mode 100644 index 0000000..26f3266 --- /dev/null +++ b/spec/factories/identities.rb @@ -0,0 +1,9 @@ +require "faker" + +FactoryGirl.define do + factory :identity do + user + provider { %w(github twitter).sample } + uid { Faker::Number.number(6) } + end +end diff --git a/spec/models/identity_spec.rb b/spec/models/identity_spec.rb new file mode 100644 index 0000000..a38e032 --- /dev/null +++ b/spec/models/identity_spec.rb @@ -0,0 +1,48 @@ +require 'rails_helper' + +RSpec.describe Identity, type: :model do + context "validations" do + it "belongs to a user" do + identity = build(:identity, user: nil) + expect(identity).not_to be_valid + end + + it "has a uid" do + identity = build(:identity, uid: nil) + expect(identity).not_to be_valid + end + + it "has a provider" do + identity = build(:identity, provider: nil) + expect(identity).not_to be_valid + end + + context "uniquness constraints" do + let(:user) { create(:user) } + + it "different identites cannot have same uid for the same provider" do + create(:identity, user: user, provider: "github", uid: "123") + identity = build(:identity, user: user, provider: "github", uid: "123") + expect(identity).not_to be_valid + end + + it "same user cannot have multiple identites with the same provider" do + create(:identity, user: user, provider: "github") + identity = build(:identity, user: user, provider: "github") + expect(identity).not_to be_valid + end + + it "different identities can have same provider with different uids" do + create(:identity, provider: "github", uid: "123") + identity = build(:identity, provider: "github", uid: "456") + expect(identity).to be_valid + end + + it "different identities can have same uid with different provider" do + create(:identity, provider: "github", uid: "123") + identity = build(:identity, provider: "twitter", uid: "123") + expect(identity).to be_valid + end + end + end +end From 83fb5fdcad4439746c79eacc7bbcdc582531e62e Mon Sep 17 00:00:00 2001 From: whicheverpeady Date: Sun, 18 Oct 2015 11:29:10 -0400 Subject: [PATCH 13/21] Add achievements controller --- app/assets/javascripts/achievements.coffee | 3 + app/assets/stylesheets/achievements.scss | 3 + app/controllers/achievements_controller.rb | 49 ++++++++++++ app/helpers/achievements_helper.rb | 2 + app/views/achievements/edit.html.erb | 2 + app/views/achievements/index.html.erb | 2 + app/views/achievements/new.html.erb | 2 + app/views/achievements/show.html.erb | 2 + config/routes.rb | 56 +------------ .../achievements_controller_spec.rb | 78 +++++++++++++++++++ spec/factories/achievements.rb | 1 + spec/helpers/achievements_helper_spec.rb | 14 ++++ 12 files changed, 159 insertions(+), 55 deletions(-) create mode 100644 app/assets/javascripts/achievements.coffee create mode 100644 app/assets/stylesheets/achievements.scss create mode 100644 app/controllers/achievements_controller.rb create mode 100644 app/helpers/achievements_helper.rb create mode 100644 app/views/achievements/edit.html.erb create mode 100644 app/views/achievements/index.html.erb create mode 100644 app/views/achievements/new.html.erb create mode 100644 app/views/achievements/show.html.erb create mode 100644 spec/controllers/achievements_controller_spec.rb create mode 100644 spec/helpers/achievements_helper_spec.rb diff --git a/app/assets/javascripts/achievements.coffee b/app/assets/javascripts/achievements.coffee new file mode 100644 index 0000000..24f83d1 --- /dev/null +++ b/app/assets/javascripts/achievements.coffee @@ -0,0 +1,3 @@ +# Place all the behaviors and hooks related to the matching controller here. +# All this logic will automatically be available in application.js. +# You can use CoffeeScript in this file: http://coffeescript.org/ diff --git a/app/assets/stylesheets/achievements.scss b/app/assets/stylesheets/achievements.scss new file mode 100644 index 0000000..6185af5 --- /dev/null +++ b/app/assets/stylesheets/achievements.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the achievements controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/app/controllers/achievements_controller.rb b/app/controllers/achievements_controller.rb new file mode 100644 index 0000000..f767002 --- /dev/null +++ b/app/controllers/achievements_controller.rb @@ -0,0 +1,49 @@ +class AchievementsController < ApplicationController + before_action :find_achievement, only: [:show, :edit, :update, :destroy] + + def new + @achievement = Achievement.new + end + + def create + @achievement = Achievement.new(achievement_params) + if @achievement.save + redirect_to @achievement + else + render 'new' + end + end + + def show + end + + def index + @achievements = Achievement.all + end + + def edit + end + + def update + if @achievement.update_attributes(achievement_params) + redirect_to @achievement + else + render 'edit' + end + end + + def destroy + @achievement.destroy + redirect_to root_path + end + + private + + def find_achievement + @achievement = Achievement.find(params[:id]) + end + + def achievement_params + params.require(:achievement).permit(:title, :description, :point) + end +end diff --git a/app/helpers/achievements_helper.rb b/app/helpers/achievements_helper.rb new file mode 100644 index 0000000..26cc28c --- /dev/null +++ b/app/helpers/achievements_helper.rb @@ -0,0 +1,2 @@ +module AchievementsHelper +end diff --git a/app/views/achievements/edit.html.erb b/app/views/achievements/edit.html.erb new file mode 100644 index 0000000..d50c17f --- /dev/null +++ b/app/views/achievements/edit.html.erb @@ -0,0 +1,2 @@ +

Achievements#edit

+

Find me in app/views/achievements/edit.html.erb

diff --git a/app/views/achievements/index.html.erb b/app/views/achievements/index.html.erb new file mode 100644 index 0000000..b29ecb5 --- /dev/null +++ b/app/views/achievements/index.html.erb @@ -0,0 +1,2 @@ +

Achievements#index

+

Find me in app/views/achievements/index.html.erb

diff --git a/app/views/achievements/new.html.erb b/app/views/achievements/new.html.erb new file mode 100644 index 0000000..c387206 --- /dev/null +++ b/app/views/achievements/new.html.erb @@ -0,0 +1,2 @@ +

Achievements#new

+

Find me in app/views/achievements/new.html.erb

diff --git a/app/views/achievements/show.html.erb b/app/views/achievements/show.html.erb new file mode 100644 index 0000000..5f551aa --- /dev/null +++ b/app/views/achievements/show.html.erb @@ -0,0 +1,2 @@ +

Achievements#show

+

Find me in app/views/achievements/show.html.erb

diff --git a/config/routes.rb b/config/routes.rb index 95085b1..bdaa4d0 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -16,64 +16,10 @@ end resources :users, only: [:show] + resources :achievements #get 'users/show' #get 'users/edit' #get 'users/update' root 'static_pages#index' - - # 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/controllers/achievements_controller_spec.rb b/spec/controllers/achievements_controller_spec.rb new file mode 100644 index 0000000..f14da9a --- /dev/null +++ b/spec/controllers/achievements_controller_spec.rb @@ -0,0 +1,78 @@ +require 'rails_helper' + +RSpec.describe AchievementsController, type: :controller do + + let(:achievement) { create(:achievement) } + + describe "GET #new" do + it "returns http success" do + get :new + expect(response).to have_http_status(:success) + expect(response).to render_template(:new) + end + end + + describe "POST #create" do + context "with valid attributes" do + it "creates an achievement" do + post :create, achievement: attributes_for(:achievement) + expect(Achievement.count).to eq(1) + end + + it "redirects to the new achievement" do + post :create, achievement: attributes_for(:achievement) + expect(response).to redirect_to Achievement.first + end + end + + context "with invalid attributes" do + it 'does not save the achievement' do + post :create, achievement: attributes_for(:achievement, title: nil) + expect(Achievement.count).to eq(0) + end + + it "renders the new template" do + post :create, achievement: attributes_for(:achievement, title: nil) + expect(response).to render_template(:new) + end + end + end + + describe "GET #show" do + it "renders the show template" do + get :show, id: achievement + expect(response).to have_http_status(:success) + expect(response).to render_template(:show) + end + end + + describe "GET #index" do + it "renders the index template" do + get :index + expect(response).to have_http_status(:success) + expect(response).to render_template(:index) + end + end + + describe "GET #edit" do + it "renders the edit form" do + get :edit, id: achievement + expect(response).to have_http_status(:success) + expect(response).to render_template(:edit) + end + end + + describe "PUT #update" do + it "returns http success" do + put :update, id: achievement, achievement: attributes_for(:achievement) + expect(Achievement.first.title).to_not eq achievement.title + end + end + + describe "DELETE #destroy" do + it "returns http success" do + delete :destroy, id: achievement + expect(Achievement.count).to eq(0) + end + end +end diff --git a/spec/factories/achievements.rb b/spec/factories/achievements.rb index b6c15b5..9444d10 100644 --- a/spec/factories/achievements.rb +++ b/spec/factories/achievements.rb @@ -2,5 +2,6 @@ factory :achievement do title { Faker::Name.title } description { Faker::Lorem.sentence(5) } + points { Faker::Number.between(1, 100) } end end diff --git a/spec/helpers/achievements_helper_spec.rb b/spec/helpers/achievements_helper_spec.rb new file mode 100644 index 0000000..dffef6c --- /dev/null +++ b/spec/helpers/achievements_helper_spec.rb @@ -0,0 +1,14 @@ +require 'rails_helper' + +# Specs in this file have access to a helper object that includes +# the AchievementsHelper. For example: +# +# describe AchievementsHelper do +# describe "string concat" do +# it "concats two strings with spaces" do +# expect(helper.concat_strings("this","that")).to eq("this that") +# end +# end +# end +RSpec.describe AchievementsHelper, type: :helper do +end From c7263d1a2f2902b064cb77fcea4940ad351cea13 Mon Sep 17 00:00:00 2001 From: whicheverpeady Date: Sun, 18 Oct 2015 11:43:28 -0400 Subject: [PATCH 14/21] Sign in user before achievement controller specs --- spec/controllers/achievements_controller_spec.rb | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/spec/controllers/achievements_controller_spec.rb b/spec/controllers/achievements_controller_spec.rb index f14da9a..124677b 100644 --- a/spec/controllers/achievements_controller_spec.rb +++ b/spec/controllers/achievements_controller_spec.rb @@ -2,6 +2,11 @@ RSpec.describe AchievementsController, type: :controller do + before(:example) do + @user = create(:user) + sign_in(@user) + end + let(:achievement) { create(:achievement) } describe "GET #new" do From 64685e6cbb513e8a0cb7a48df4b887ea4ee68bd9 Mon Sep 17 00:00:00 2001 From: whicheverpeady Date: Sun, 18 Oct 2015 14:44:13 -0400 Subject: [PATCH 15/21] Structure achievement views --- app/controllers/achievements_controller.rb | 6 +++--- app/views/achievements/_form.html.erb | 21 +++++++++++++++++++++ app/views/achievements/edit.html.erb | 9 +++++++-- app/views/achievements/index.html.erb | 15 +++++++++++++-- app/views/achievements/new.html.erb | 5 +++-- app/views/achievements/show.html.erb | 14 ++++++++++++-- app/views/layouts/application.html.erb | 1 + app/views/users/show.html.erb | 3 ++- db/seeds.rb | 11 +++++++++++ 9 files changed, 73 insertions(+), 12 deletions(-) create mode 100644 app/views/achievements/_form.html.erb diff --git a/app/controllers/achievements_controller.rb b/app/controllers/achievements_controller.rb index f767002..0f316c2 100644 --- a/app/controllers/achievements_controller.rb +++ b/app/controllers/achievements_controller.rb @@ -25,7 +25,7 @@ def edit end def update - if @achievement.update_attributes(achievement_params) + if @achievement.update(achievement_params) redirect_to @achievement else render 'edit' @@ -34,7 +34,7 @@ def update def destroy @achievement.destroy - redirect_to root_path + redirect_to achievements_path end private @@ -44,6 +44,6 @@ def find_achievement end def achievement_params - params.require(:achievement).permit(:title, :description, :point) + params.require(:achievement).permit(:title, :description, :points) end end diff --git a/app/views/achievements/_form.html.erb b/app/views/achievements/_form.html.erb new file mode 100644 index 0000000..b5f12a1 --- /dev/null +++ b/app/views/achievements/_form.html.erb @@ -0,0 +1,21 @@ +<%= form_for @achievement do |f| %> + +
+ <%= f.label :title %> + <%= f.text_field :title, class: 'form-control' %> +
+ +
+ <%= f.label :description %> + <%= f.text_field :description, class: 'form-control' %> +
+ +
+ <%= f.label :points %> + <%= f.text_field :points, class: 'form-control' %> +
+ +
+ <%= f.submit "Save Achievement" %> +
+<% end %> diff --git a/app/views/achievements/edit.html.erb b/app/views/achievements/edit.html.erb index d50c17f..d276772 100644 --- a/app/views/achievements/edit.html.erb +++ b/app/views/achievements/edit.html.erb @@ -1,2 +1,7 @@ -

Achievements#edit

-

Find me in app/views/achievements/edit.html.erb

+

Edit Achievement

+ +<%= render 'form' %> + +
+ <%= link_to "Cancel", achievement_path, class: 'btn btn-primary' %> +
diff --git a/app/views/achievements/index.html.erb b/app/views/achievements/index.html.erb index b29ecb5..00cb605 100644 --- a/app/views/achievements/index.html.erb +++ b/app/views/achievements/index.html.erb @@ -1,2 +1,13 @@ -

Achievements#index

-

Find me in app/views/achievements/index.html.erb

+

All Achievements

+ +
+
+ <% @achievements.each do |achievement| %> +

<%= link_to(achievement.title, achievement) %>

+

<%= achievement.description %>

+

Points: <%= achievement.points %>

+ <% end %> +
+
+ + diff --git a/app/views/achievements/new.html.erb b/app/views/achievements/new.html.erb index c387206..87f81df 100644 --- a/app/views/achievements/new.html.erb +++ b/app/views/achievements/new.html.erb @@ -1,2 +1,3 @@ -

Achievements#new

-

Find me in app/views/achievements/new.html.erb

+

New Achievement

+ + <%= render 'form' %> diff --git a/app/views/achievements/show.html.erb b/app/views/achievements/show.html.erb index 5f551aa..8e4a3fa 100644 --- a/app/views/achievements/show.html.erb +++ b/app/views/achievements/show.html.erb @@ -1,2 +1,12 @@ -

Achievements#show

-

Find me in app/views/achievements/show.html.erb

+

<%= @achievement.title %>

+ +
+
+ <%= @achievement.description %>
+

Points: <%= @achievement.points %>

+
+
+ +<%= link_to "Back", achievements_path, class: 'btn btn-primary' %> +<%= link_to "Edit", edit_achievement_path(@achievement), class: 'btn btn-primary' %> +<%= link_to "Delete", achievement_path(@achievement), method: :delete, data: { confirm: "Delete this achievement?" }, class: 'btn btn-primary' %> diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 22923b6..ef049b3 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -29,6 +29,7 @@