diff --git a/Gemfile b/Gemfile index 6e9abb1..b7f5aa3 100644 --- a/Gemfile +++ b/Gemfile @@ -24,6 +24,10 @@ 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' +# omniauth-github gem for social signin +gem 'omniauth-github', '~> 1.1.2' # Use ActiveModel has_secure_password # gem 'bcrypt', '~> 3.1.7' @@ -53,4 +57,7 @@ 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' + gem "pry-byebug" end diff --git a/Gemfile.lock b/Gemfile.lock index 0afe943..33c7d7f 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -40,13 +40,15 @@ 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) 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) @@ -61,8 +63,16 @@ 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) + 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) @@ -77,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) @@ -101,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) @@ -111,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) @@ -124,17 +138,40 @@ 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.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) rack-test (0.6.3) rack (>= 1.0) @@ -167,6 +204,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 +256,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 +275,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) @@ -241,7 +283,10 @@ DEPENDENCIES guard-rspec jbuilder (~> 2.0) jquery-rails + omniauth-github (~> 1.1.2) pg + pry-byebug + pry-rails rails (= 4.2.3) rspec-rails sass-rails (~> 5.0) 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/README.md b/README.md index 146dcd1..a5377d3 100644 --- a/README.md +++ b/README.md @@ -20,3 +20,14 @@ _If you *do not* want to use the project default database names, then you'll wan config/database.yml before runnig the last command._ $ rake db:setup + +To be able to use social login with Github, make sure to add your consumer key +and consumer secret in your config/secrets.yml. For example: + +development:
+  github_consumer_key: 123456........
+  github_consumer_secret: 123456.........
+ +test:
+  github_consumer_key: 123456........
+  github_consumer_secret: 123456.........
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/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/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/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/achievements_controller.rb b/app/controllers/achievements_controller.rb new file mode 100644 index 0000000..0f316c2 --- /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(achievement_params) + redirect_to @achievement + else + render 'edit' + end + end + + def destroy + @achievement.destroy + redirect_to achievements_path + end + + private + + def find_achievement + @achievement = Achievement.find(params[:id]) + end + + def achievement_params + params.require(:achievement).permit(:title, :description, :points) + end +end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index d83690e..b8915c3 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -2,4 +2,19 @@ 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) + } + + devise_parameter_sanitizer.for(:account_update) { + |user| user.permit(:username, :email, :biography, :password, + :password_confirmation, :current_password) + } + end end diff --git a/app/controllers/omniauth_callbacks_controller.rb b/app/controllers/omniauth_callbacks_controller.rb new file mode 100644 index 0000000..e522d3e --- /dev/null +++ b/app/controllers/omniauth_callbacks_controller.rb @@ -0,0 +1,36 @@ +class OmniauthCallbacksController < Devise::OmniauthCallbacksController + def all + @identity = Identity.find_or_create_from_oauth(auth) + if @identity.user.nil? + create_identity_user_from_oauth + signin_and_redirect_user + elsif @identity.user.persisted? + signin_and_redirect_user + else + session["devise.#{provider}_data"] = request.env["omniauth.auth"] + redirect_to new_user_registration_url + end + end + + alias_method :github, :all + + private + + def auth + @auth ||= request.env["omniauth.auth"] + end + + def provider + @provider ||= auth.provider + end + + def create_identity_user_from_oauth + @identity.user = User.create_from_oauth(auth) + @identity.save + end + + def signin_and_redirect_user + sign_in_and_redirect @identity.user, event: :authentication + set_flash_message(:notice, :success, kind: provider.to_sym) + 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..d7673b0 --- /dev/null +++ b/app/controllers/users_controller.rb @@ -0,0 +1,9 @@ +class UsersController < ApplicationController + def show + if params[:id] + @user = User.find(params[:id]) + else + @user = current_user + end + 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/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/identity.rb b/app/models/identity.rb new file mode 100644 index 0000000..278d255 --- /dev/null +++ b/app/models/identity.rb @@ -0,0 +1,9 @@ +class Identity < ActiveRecord::Base + belongs_to :user + validates :uid, presence: true, uniqueness: { scope: :provider } + validates :provider, presence: true, uniqueness: { scope: :user_id } + + def self.find_or_create_from_oauth(auth) + first_or_create(provider: auth.provider, uid: auth.uid) + end +end diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 0000000..9fc7952 --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,15 @@ +class User < ActiveRecord::Base + # Include default devise modules. Others available are: + # :confirmable, :lockable, :timeoutable and :omniauthable + devise :database_authenticatable, :registerable, + :recoverable, :rememberable, :trackable, :validatable, + :omniauthable, omniauth_providers: [:github] + has_many :identities + validates :username, presence: true + + def self.create_from_oauth(auth) + create(username: auth.info.nickname, + email: auth.info.email, + password: Devise.friendly_token[0, 20]) + 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 new file mode 100644 index 0000000..d276772 --- /dev/null +++ b/app/views/achievements/edit.html.erb @@ -0,0 +1,7 @@ +

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 new file mode 100644 index 0000000..00cb605 --- /dev/null +++ b/app/views/achievements/index.html.erb @@ -0,0 +1,13 @@ +

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 new file mode 100644 index 0000000..87f81df --- /dev/null +++ b/app/views/achievements/new.html.erb @@ -0,0 +1,3 @@ +

New Achievement

+ + <%= render 'form' %> diff --git a/app/views/achievements/show.html.erb b/app/views/achievements/show.html.erb new file mode 100644 index 0000000..8e4a3fa --- /dev/null +++ b/app/views/achievements/show.html.erb @@ -0,0 +1,12 @@ +

<%= @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/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..4a88c96 --- /dev/null +++ b/app/views/devise/registrations/edit.html.erb @@ -0,0 +1,45 @@ +

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 %> +
+ +
+ <%= f.label :biography %>
+ <%= f.text_area :biography %> +
+ + <% 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 %> + +<%= 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..fae14cb --- /dev/null +++ b/app/views/devise/registrations/new.html.erb @@ -0,0 +1,34 @@ +

Sign up

+ +<%= 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 %> +
+ +
+ <%= 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/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 3618437..ef049b3 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -28,13 +28,27 @@ - <%= yield %> +
+
+

<%= notice %>

+

<%= alert %>

+ + <%= yield %> +
+
diff --git a/app/views/users/show.html.erb b/app/views/users/show.html.erb new file mode 100644 index 0000000..aeb647f --- /dev/null +++ b/app/views/users/show.html.erb @@ -0,0 +1,16 @@ +
+
+

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

+

Email: <%= @user.email %>

+

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

+
+
+ +
+ +
+
+ <%= link_to "Edit Profile", edit_user_registration_path(@user), id: "edit_user_link", class: "btn btn-primary" %> + <%= link_to "View Achievements", achievements_path, class: "btn btn-primary" %> +
+
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..0fa01be --- /dev/null +++ b/config/initializers/devise.rb @@ -0,0 +1,264 @@ +# 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' + 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 + # 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:" diff --git a/config/routes.rb b/config/routes.rb index 11383db..1dc78ee 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,58 +1,26 @@ Rails.application.routes.draw do - 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 + devise_for :users, skip: :registrations, + controllers: { omniauth_callbacks: "omniauth_callbacks" } + 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 + + resources :users, only: [:show] + resources :achievements + #get 'users/show' + #get 'users/edit' + #get 'users/update' - # 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 + root 'static_pages#index' end 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/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 78a7481..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: 20151010160137) do +ActiveRecord::Schema.define(version: 20151018081925) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -23,4 +23,36 @@ t.datetime "created_at", null: false 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 + 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 + + add_foreign_key "identities", "users" end diff --git a/db/seeds.rb b/db/seeds.rb index 4edb1e8..417cb67 100644 --- a/db/seeds.rb +++ b/db/seeds.rb @@ -5,3 +5,14 @@ # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) + + +Achievement.create(title: "Welcome to Commited", + description: "Sign up and begin your coding journey.", + points: 10) + +10.times do |achievement| + Achievement.create(title: Faker::Book.title, + description: Faker::Lorem.sentence(5), + points: 5 * Random.rand(2..20)) +end diff --git a/spec/controllers/achievements_controller_spec.rb b/spec/controllers/achievements_controller_spec.rb new file mode 100644 index 0000000..124677b --- /dev/null +++ b/spec/controllers/achievements_controller_spec.rb @@ -0,0 +1,83 @@ +require 'rails_helper' + +RSpec.describe AchievementsController, type: :controller do + + before(:example) do + @user = create(:user) + sign_in(@user) + end + + 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/controllers/omniauth_callbacks_controller_spec.rb b/spec/controllers/omniauth_callbacks_controller_spec.rb new file mode 100644 index 0000000..d0156af --- /dev/null +++ b/spec/controllers/omniauth_callbacks_controller_spec.rb @@ -0,0 +1,86 @@ +require "rails_helper" + +RSpec.describe OmniauthCallbacksController, type: :controller do + describe "POST #github" do + before(:example) do + request.env["devise.mapping"] = Devise.mappings[:user] + request.env["omniauth.auth"] = mock_provider_auth_hash("github") + end + + context "first time social sign in" do + it "assigns @identity" do + get :github + expect(assigns(:identity)).to be_a(Identity) + expect(assigns(:identity).provider).to eq("github") + expect(assigns(:identity).uid).to eq("12345") + end + + it "creates a user" do + expect(User).to receive(:create_from_oauth).and_return( + create(:user, username: request.env["omniauth.auth"].info.nickname, + email: request.env["omniauth.auth"].info.email)) + get :github + end + + it "redirects to authenticated_root_path" do + get :github + expect(response).to redirect_to("/") + end + end + + context "user already exists" do + before(:example) do + @user = create(:user, + username: request.env["omniauth.auth"].info.nickname, + email: request.env["omniauth.auth"].info.email) + @identity = create(:identity, + provider: request.env["omniauth.auth"].provider, + uid: request.env["omniauth.auth"].uid, + user: @user) + end + + it "assigns @identity" do + get :github + expect(assigns(:identity)).to eq(@identity) + expect(assigns(:identity).user).to eq(@user) + expect(assigns(:identity).provider).to eq("github") + expect(assigns(:identity).uid).to eq("12345") + end + + it "does not create a new user" do + expect(User).not_to receive(:create_from_oauth) + get :github + end + + it "redirects to authenticated_root_path" do + get :github + expect(response).to redirect_to("/") + end + end + + context "invalid credintials" do + before(:example) do + @user = build(:user, + username: request.env["omniauth.auth"].info.nickname, + email: request.env["omniauth.auth"].info.email) + @identity = create(:identity, + provider: request.env["omniauth.auth"].provider, + uid: request.env["omniauth.auth"].uid) + @identity.user = @user + allow(Identity).to \ + receive(:find_or_create_from_oauth).and_return(@identity) + end + + it "assigns session" do + get :github + expect(session["devise.github_data"]).to \ + eq(request.env["omniauth.auth"]) + end + + it "redirects to new_user_registration_url" do + get :github + expect(response).to redirect_to(new_user_registration_url) + end + end + end +end diff --git a/spec/controllers/users_controller_spec.rb b/spec/controllers/users_controller_spec.rb new file mode 100644 index 0000000..04bdc50 --- /dev/null +++ b/spec/controllers/users_controller_spec.rb @@ -0,0 +1,19 @@ +require 'rails_helper' + +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 +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/factories/identities.rb b/spec/factories/identities.rb new file mode 100644 index 0000000..fbc064c --- /dev/null +++ b/spec/factories/identities.rb @@ -0,0 +1,8 @@ +require "faker" + +FactoryGirl.define do + factory :identity do + provider { %w(github twitter).sample } + uid { Faker::Number.number(6) } + end +end diff --git a/spec/factories/users.rb b/spec/factories/users.rb new file mode 100644 index 0000000..3a81c80 --- /dev/null +++ b/spec/factories/users.rb @@ -0,0 +1,8 @@ +FactoryGirl.define do + factory :user do + email { Faker::Internet.email } + password { Faker::Internet.password } + username { Faker::Internet.user_name } + biography { Faker::Lorem.paragraphs(3) } + 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_show_profile_spec.rb b/spec/features/user_show_profile_spec.rb new file mode 100644 index 0000000..0929f42 --- /dev/null +++ b/spec/features/user_show_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_signin_signout_spec.rb b/spec/features/user_signup_signin_signout_spec.rb new file mode 100644 index 0000000..d32d1ae --- /dev/null +++ b/spec/features/user_signup_signin_signout_spec.rb @@ -0,0 +1,101 @@ +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) } + + context "regular signin/signout" do + 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 + expect(current_path).to eq(root_path) + end + end + end + + describe "social signin/signout" do + describe "singin/signout with github" do + before(:example) { mock_provider_auth_hash("github") } + after(:example) { OmniAuth.config.mock_auth[:github] = nil } + + it "with valid credentials" do + github_social_signin + expect(current_path).to eq(authenticated_root_path) + end + + it "with invalid credentials" do + OmniAuth.config.mock_auth[:github] = :invalid_credentials + github_social_signin + expect(current_path).to eq(new_user_session_path) + end + + it "signout successfully" do + github_social_signin + expect(current_path).to eq(authenticated_root_path) + signout + expect(current_path).to eq(root_path) + end + 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/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 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/identity_spec.rb b/spec/models/identity_spec.rb new file mode 100644 index 0000000..25cb5ee --- /dev/null +++ b/spec/models/identity_spec.rb @@ -0,0 +1,74 @@ +require 'rails_helper' + +RSpec.describe Identity, type: :model do + context "validations" do + 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, user: user, provider: "github", uid: "123") + identity = build(:identity, user: create(:user), 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 + + context "omniauth" do + before(:example) do + @auth = OmniAuth::AuthHash.new({ + provider: :github, + uid: "12345", + info: { + nickname: "moeabdol", + email: "moeabdol@committed.com", + } + }) + end + + it "creates a new social identity if identity is not found" do + expect(Identity.count).to eq(0) + identity = Identity.find_or_create_from_oauth(@auth) + expect(Identity.count).to eq(1) + expect(identity.provider).to eq("github") + expect(identity.uid).to eq("12345") + end + + it "finds an already created social identity" do + create(:identity, provider: "github", uid: "12345") + expect(Identity.count).to eq(1) + identity = Identity.find_or_create_from_oauth(@auth) + expect(Identity.count).to eq(1) + expect(identity.provider).to eq("github") + expect(identity.uid).to eq("12345") + end + end +end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb new file mode 100644 index 0000000..695ecb3 --- /dev/null +++ b/spec/models/user_spec.rb @@ -0,0 +1,28 @@ +require 'rails_helper' + +RSpec.describe User, type: :model do + context "validations" do + it "has a username" do + user = build(:user, username: nil) + expect(user).not_to be_valid + end + end + + context "omniauth" do + it "creates user from ominauth hash" do + expect { + auth = OmniAuth::AuthHash.new({ + provider: :github, + uid: "12345", + info: { + nickname: "moeabdol", + email: "moeabdol@committed.com", + } + }) + User.create_from_oauth(auth) + }.to change{ User.count }.from(0).to(1) + expect(User.first.username).to eq("moeabdol") + expect(User.first.email).to eq("moeabdol@committed.com") + end + end +end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb index 722e843..9f536d0 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 @@ -57,8 +59,8 @@ # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. - config.use_transactional_fixtures = false - + config.use_transactional_fixtures = false + # Use database_cleaner in place of transactional fixtures config.before(:suite) do DatabaseCleaner.clean_with(:truncation) @@ -80,4 +82,13 @@ DatabaseCleaner.clean end + # include Devise test helpers + config.include Devise::TestHelpers, type: :controller + + # include our SessionHelpers to signup/login/logout + config.include SessionHelpers, type: :feature + config.include SessionHelpers, type: :controller + + # turn on test mode for omniauth + OmniAuth.config.test_mode = true end diff --git a/spec/support/session_helpers.rb b/spec/support/session_helpers.rb new file mode 100644 index 0000000..e1f12b8 --- /dev/null +++ b/spec/support/session_helpers.rb @@ -0,0 +1,38 @@ +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 + click_on "Sign Out" + end + + def github_social_signin + visit root_path + click_on "Sign In" + click_on "Sign in with Github" + end + + def mock_provider_auth_hash(provider) + OmniAuth.config.mock_auth[provider.to_sym] = OmniAuth::AuthHash.new({ + provider: provider.to_sym, + uid: "12345", + info: { + nickname: "moeabdol", + email: "moeabdol@committed.com", + } + }) + end +end