Skip to content

Instantly share code, notes, and snippets.

@jamiely
Created October 7, 2011 19:04
Show Gist options
  • Save jamiely/1271102 to your computer and use it in GitHub Desktop.
Save jamiely/1271102 to your computer and use it in GitHub Desktop.
Auth using sorcery gem
diff --git a/.gitignore b/.gitignore
index 2831ed6..70cd85f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,3 +7,4 @@ tmp/**/*
config/database.yml
.rvmrc
.DS_Store
+mysql2
\ No newline at end of file
diff --git a/Gemfile b/Gemfile
index 451bcee..932d662 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,10 +1,11 @@
source 'http://rubygems.org'
+gem "rake", "0.8.7"
gem 'rails', '3.0.10'
gem 'maruku'
gem 'rack-offline'
gem 'memcache-client'
-gem 'devise'
+gem 'sorcery'
if defined?(JRUBY_VERSION)
gem 'jruby-openssl'
@@ -18,3 +19,8 @@ else
gem 'passenger'
gem 'mysql2', '0.2.7'
end
+
+# http clients
+
+gem 'rest-client'
+
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb
index 399bc39..67dabbc 100644
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -14,4 +14,8 @@ class ApplicationController < ActionController::Base
username == 'knowledge' && password == 'worker'
end
end
+
+ def not_authenticated
+ redirect_to login_url, :alert => "First login to access this page."
+ end
end
diff --git a/app/controllers/courses_controller.rb b/app/controllers/courses_controller.rb
index 83964b7..d2ddf80 100644
--- a/app/controllers/courses_controller.rb
+++ b/app/controllers/courses_controller.rb
@@ -1,16 +1,21 @@
class CoursesController < ApplicationController
+ before_filter :require_login
respond_to :json
layout nil
def index
- @courses = Course.all
+ @courses = current_user_courses
respond_with @courses
end
def show
id = params[:id]
- @course = Course.find(id)
+ @course = current_user_courses.where(:id => id).first
respond_with @course
end
+ def current_user_courses
+ current_user.courses
+ end
+
end
diff --git a/app/controllers/sections_controller.rb b/app/controllers/sections_controller.rb
index bc200e2..77066b6 100644
--- a/app/controllers/sections_controller.rb
+++ b/app/controllers/sections_controller.rb
@@ -1,22 +1,23 @@
class SectionsController < ApplicationController
+ before_filter :require_login
respond_to :json, :xml
layout nil
def index
- if params.key?(:course_id)
- @sections = Course.find(params[:course_id]).sections
- else
- @sections = Section.all
- end
-
+ @sections = current_user_sections
+ @sections = @sections.where(:course_id => params[:course_id]) if params.key?(:course_id)
+
respond_with @sections
end
def show
- section_id = params[:id]
- @section = Section.find(section_id)
+ @section = current_user_sections.where(:id => params[:id]).first
respond_with @section
end
+ def current_user_sections
+ current_user.sections
+ end
+
end
diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb
new file mode 100644
index 0000000..528c4fe
--- /dev/null
+++ b/app/controllers/sessions_controller.rb
@@ -0,0 +1,18 @@
+class SessionsController < ApplicationController
+ def create
+ @user = login(params[:email], params[:password], params[:remember_me])
+
+ if @user
+ @message = "Logged in."
+ else
+ @message = "Invalid credentials"
+ response.status = 404
+ end
+ render :json => (response.status == 200) ? {:id => @user.id, :message => @message} : {:message => @message}
+ end
+
+ def destroy
+ logout
+ render :json => {:message => "Logged out"}
+ end
+end
diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb
index c835de1..1a639d3 100644
--- a/app/controllers/users_controller.rb
+++ b/app/controllers/users_controller.rb
@@ -5,5 +5,19 @@ class UsersController < ApplicationController
def index
@users = params[:section_id] ? Section.find(params[:section_id]).users : User.all
respond_with @users
+ end
+
+ def new
+ @user = User.new
+ end
+
+ def create
+ @user = User.new(params[:user])
+ if @user.save
+ redirect_to root_url, :notice => "Signed up!"
+ else
+ render :new
+ end
end
-end
\ No newline at end of file
+end
+
diff --git a/app/helpers/sessions_helper.rb b/app/helpers/sessions_helper.rb
new file mode 100644
index 0000000..309f8b2
--- /dev/null
+++ b/app/helpers/sessions_helper.rb
@@ -0,0 +1,2 @@
+module SessionsHelper
+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/course.rb b/app/models/course.rb
index 4bb6ce7..c16a738 100644
--- a/app/models/course.rb
+++ b/app/models/course.rb
@@ -1,3 +1,11 @@
class Course < ActiveRecord::Base
has_many :sections
+
+ # Use to get all the courses which the passed user
+ # has access to.
+ scope :all_having_user, lambda { |user|
+ joins("join sections on sections.course_id = courses.id
+ join section_users ON sections.id = section_users.section_id").
+ where("section_users.user_id = ?", user.id)
+ }
end
diff --git a/app/models/llgroup_fake.rb b/app/models/llgroup_fake.rb
new file mode 100644
index 0000000..28a11fd
--- /dev/null
+++ b/app/models/llgroup_fake.rb
@@ -0,0 +1,19 @@
+class LLgroupFake
+ # This is hardcoded to a test location. Change to use the location of the llgroup API
+ def self.authenticate(email, password)
+ RestClient.get('http://localhost:3000/tests/json/llgroup_auth.json') do
+ |response, request, result, &block|
+ case response.code
+ when 200
+ data = ActiveSupport::JSON.decode response
+ !!data["AUTH"]
+ when 404
+ false
+ when 423
+ false
+ else
+ raise "Unexpected status code"
+ end
+ end
+ end
+end
diff --git a/app/models/section_user.rb b/app/models/section_user.rb
index 190bd74..a2867ee 100644
--- a/app/models/section_user.rb
+++ b/app/models/section_user.rb
@@ -1,5 +1,6 @@
class SectionUser < ActiveRecord::Base
belongs_to :section
+ has_one :course, :through => :section
belongs_to :user
has_many :comments
diff --git a/app/models/user.rb b/app/models/user.rb
index 79ef7aa..573329c 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -1,6 +1,55 @@
+require 'rest-client'
+require 'logger'
+require 'llgroup_fake'
+
class User < ActiveRecord::Base
+ # relationships
has_many :section_users
has_many :sections, :through => :section_users
- has_many :comments, :through => :section_users
+
+ # auth "sorcery" gem
+ authenticates_with_sorcery!
+
+ # attributes
+ attr_accessible :email, :password, :password_confirmation
+
+ validates_confirmation_of :password
+ validates_presence_of :password, :on => :create
+ validates_presence_of :email
+ validates_uniqueness_of :email
+
+ # Retrieve all the courses the user has access to.
+ def courses
+ Course.all_having_user self
+ end
+
+ # This authentication method will be called by sorcery
+ # when a session is created in order to authenticate the user.
+ def self.authenticate(*credentials)
+ raise ArgumentError, "at least 2 arguments required" if credentials.size < 2
+ if wharton_credentials? credentials
+ authenticate_wharton credentials[0], credentials[1]
+ else
+ # copied from sorcery model.rb
+ user = find_by_credentials credentials
+ _salt = user.send(@sorcery_config.salt_attribute_name) if user && !@sorcery_config.salt_attribute_name.nil? && !@sorcery_config.encryption_provider.nil?
+ user if user && @sorcery_config.before_authenticate.all? {|c| user.send(c)} && credentials_match?(user.send(@sorcery_config.crypted_password_attribute_name),credentials[1],_salt)
+ end
+ end
+
+ # are these wharton credentials?
+ def self.wharton_credentials?(credentials)
+ email = credentials[0]
+ email =~ /@(exchange\.)?wharton\.upenn\.edu/i
+ end
+
+ def self.llgroup_class
+ LLgroupFake
+ end
+
+ # Use LLgroup to authenticate
+ def self.authenticate_wharton(email, password)
+ find_by_email(email) if llgroup_class.authenticate email, password
+ end
end
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
index 0580bf5..b4fd4b3 100644
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -20,6 +20,12 @@
<%= yield :head %>
</head>
<body>
+ <% if current_user %>
+ Logged in as <%= current_user.email %>.
+ <%= link_to "Log out", logout_path %>
+ <% else %>
+ <%= link_to "log in", login_path %>.
+ <% end %>
<%= yield %>
</body>
</html>
diff --git a/app/views/sessions/new.html.erb b/app/views/sessions/new.html.erb
new file mode 100644
index 0000000..9b5920f
--- /dev/null
+++ b/app/views/sessions/new.html.erb
@@ -0,0 +1,15 @@
+<%= form_tag sessions_path do %>
+ <div class="field">
+ <%= label_tag :email %>
+ <%= text_field_tag :email, params[:email] %>
+ </div>
+ <div class="field">
+ <%= label_tag :password %>
+ <%= password_field_tag :password %>
+ </div>
+ <div class="field">
+ <%= check_box_tag :remember_me, 1, params[:remember_me] %>
+ <%= label_tag :remember_me %>
+ </div>
+ <div class="actions"><%= submit_tag "Log in" %></div>
+<% end %>
diff --git a/config/application.rb b/config/application.rb
index 1c6f604..1f28c7b 100644
--- a/config/application.rb
+++ b/config/application.rb
@@ -37,7 +37,7 @@ module Byrd
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
- config.filter_parameters += [:password]
+ config.filter_parameters += [:password, :password_confirmation]
# JSON
config.active_record.include_root_in_json = false
diff --git a/config/initializers/sorcery.rb b/config/initializers/sorcery.rb
new file mode 100644
index 0000000..1126873
--- /dev/null
+++ b/config/initializers/sorcery.rb
@@ -0,0 +1,199 @@
+# The first thing you need to configure is which modules you need in your app.
+# The default is nothing which will include only core features (password encryption, login/logout).
+# Available submodules are: :user_activation, :http_basic_auth, :remember_me,
+# :reset_password, :session_timeout, :brute_force_protection, :activity_logging, :external
+Rails.application.config.sorcery.submodules = [:remember_me]
+
+# Here you can configure each submodule's features.
+Rails.application.config.sorcery.configure do |config|
+ # -- core --
+ # config.not_authenticated_action = :not_authenticated # what controller action to call for
+ # non-authenticated users.
+ # You can also override 'not_authenticated'
+ # instead.
+
+ # config.save_return_to_url = true # when a non logged in user tries to enter
+ # a page that requires login,
+ # save the URL he wanted to reach,
+ # and send him there after login, using
+ # 'redirect_back_or_to'.
+
+ # -- session timeout --
+ # config.session_timeout = 3600 # how long in seconds to keep the session alive.
+ # config.session_timeout_from_last_action = false # use the last action as the beginning of
+ # session timeout.
+
+ # -- http_basic_auth --
+ # config.controller_to_realm_map = {"application" => "Application"} # What realm to display for which controller name.
+ # For example {"My App" => "Application"}
+
+ # -- activity logging --
+ # config.register_login_time = true # will register the time of last user login, every login.
+ # config.register_logout_time = true # will register the time of last user logout, every logout.
+ # config.register_last_activity_time = true # will register the time of last user action, every action.
+
+ # -- external --
+ # config.external_providers = [] # What providers are supported by this app,
+ # i.e. [:twitter, :facebook, :github] .
+ # config.ca_file = 'path/to/ca_file' # Path to ca_file. By default use a internal ca-bundle.crt.
+ # You can change it by your local ca_file.
+ # i.e. '/etc/pki/tls/certs/ca-bundle.crt'
+
+ # config.twitter.key = "eYVNBjBDi33aa9GkA3w"
+ # config.twitter.secret = "XpbeSdCoaKSmQGSeokz5qcUATClRW5u08QWNfv71N8"
+ # config.twitter.callback_url = "http://0.0.0.0:3000/oauth/callback?provider=twitter"
+ # config.twitter.user_info_mapping = {:email => "screen_name"}
+ #
+ # config.facebook.key = "34cebc81c08a521bc66e212f947d73ec"
+ # config.facebook.secret = "5b458d179f61d4f036ee66a497ffbcd0"
+ # config.facebook.callback_url = "http://0.0.0.0:3000/oauth/callback?provider=facebook"
+ # config.facebook.user_info_mapping = {:email => "name"}
+ #
+ # config.github.key = ""
+ # config.github.secret = ""
+ # config.github.callback_url = "http://0.0.0.0:3000/oauth/callback?provider=github"
+ # config.github.user_info_mapping = {:email => "name"}
+
+ # config.sinatra_cookie_secret = 'ch4ng3M3plz' # key used to sign cookies in Sinatra
+ # changing it will invalidate all signed cookies!
+
+ # --- user config ---
+ config.user_config do |user|
+ # -- core --
+ user.username_attribute_names = [:email] # specify username
+ # attributes, for example:
+ # [:username, :email].
+
+ # user.password_attribute_name = :password # change *virtual* password
+ # attribute, the one which is used
+ # until an encrypted one is
+ # generated.
+
+ # user.email_attribute_name = :email # change default email attribute.
+
+ # user.crypted_password_attribute_name = :crypted_password # change default crypted_password
+ # attribute.
+
+ # user.salt_join_token = "" # what pattern to use to join the
+ # password with the salt
+
+ # user.salt_attribute_name = :salt # change default salt attribute.
+
+ # user.stretches = nil # how many times to apply
+ # encryption to the password.
+
+ # user.encryption_key = nil # encryption key used to encrypt
+ # reversible encryptions such as
+ # AES256.
+ #
+ # WARNING:
+ #
+ # If used for users' passwords, changing this key
+ # will leave passwords undecryptable!
+
+ # user.custom_encryption_provider = nil # use an external encryption
+ # class.
+
+ # user.encryption_algorithm = :bcrypt # encryption algorithm name. See
+ # 'encryption_algorithm=' for
+ # available options.
+
+ # user.subclasses_inherit_config = false # make this configuration
+ # inheritable for subclasses.
+ # Useful for ActiveRecord's STI.
+
+ # -- user_activation --
+ # user.activation_state_attribute_name = :activation_state # the attribute name to hold
+ # activation state
+ # (active/pending).
+
+ # user.activation_token_attribute_name = :activation_token # the attribute name to hold
+ # activation code (sent by email).
+
+ # user.activation_token_expires_at_attribute_name = :activation_token_expires_at # the attribute name to hold
+ # activation code expiration date.
+
+ # user.activation_token_expiration_period = nil # how many seconds before the
+ # activation code expires. nil for
+ # never expires.
+
+ # user.user_activation_mailer = nil # your mailer class. Required.
+
+ # user.activation_needed_email_method_name = :activation_needed_email # activation needed email method
+ # on your mailer class.
+
+ # user.activation_success_email_method_name = :activation_success_email # activation success email method
+ # on your mailer class.
+
+ # user.prevent_non_active_users_to_login = true # do you want to prevent or allow
+ # users that did not activate by
+ # email to login?
+
+ # -- reset_password --
+ # user.reset_password_token_attribute_name = :reset_password_token # reset password code
+ # attribute name.
+
+ # user.reset_password_token_expires_at_attribute_name = :reset_password_token_expires_at # expires at attribute
+ # name.
+
+ # user.reset_password_email_sent_at_attribute_name = :reset_password_email_sent_at # when was email sent,
+ # used for hammering
+ # protection.
+
+ # user.reset_password_mailer = nil # mailer class. Needed.
+
+ # user.reset_password_email_method_name = :reset_password_email # reset password email
+ # method on your mailer
+ # class.
+
+ # user.reset_password_expiration_period = nil # how many seconds
+ # before the reset
+ # request expires. nil
+ # for never expires.
+
+ # user.reset_password_time_between_emails = 5 * 60 # hammering protection,
+ # how long to wait
+ # before allowing
+ # another email to be
+ # sent.
+
+ # -- brute_force_protection --
+ # user.failed_logins_count_attribute_name = :failed_logins_count # failed logins attribute name.
+
+ # user.lock_expires_at_attribute_name = :lock_expires_at # this field indicates whether
+ # user is banned and when it will
+ # be active again.
+
+ # user.consecutive_login_retries_amount_limit = 50 # how many failed logins allowed.
+
+ # user.login_lock_time_period = 60 * 60 # how long the user should be
+ # banned. in seconds. 0 for
+ # permanent.
+
+ # -- activity logging --
+ # user.last_login_at_attribute_name = :last_login_at # last login attribute name.
+ # user.last_logout_at_attribute_name = :last_logout_at # last logout attribute name.
+ # user.last_activity_at_attribute_name = :last_activity_at # last activity attribute name.
+ # user.activity_timeout = 10 * 60 # how long since last activity is
+ # the user defined logged out?
+
+ # -- external --
+ # user.authentications_class = nil # class which holds the various
+ # external provider data for this
+ # user.
+
+ # user.authentications_user_id_attribute_name = :user_id # user's identifier in
+ # authentications class.
+
+ # user.provider_attribute_name = :provider # provider's identifier in
+ # authentications class.
+
+ # user.provider_uid_attribute_name = :uid # user's external unique
+ # identifier in authentications
+ # class.
+ end
+
+ # This line must come after the 'user config' block.
+ config.user_class = "User" # define which model authenticates
+ # with sorcery.
+end
diff --git a/config/routes.rb b/config/routes.rb
index 8044971..81098e8 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,4 +1,9 @@
Byrd::Application.routes.draw do
+ get "logout" => "sessions#destroy", :as => "logout"
+ get "login" => "sessions#new", :as => "login"
+
+ resources :users
+ resources :sessions
###selah adding here temporarily for testing
resources :courses do
diff --git a/db/migrate/20110930193127_sorcery_core.rb b/db/migrate/20110930193127_sorcery_core.rb
new file mode 100644
index 0000000..83aa7b3
--- /dev/null
+++ b/db/migrate/20110930193127_sorcery_core.rb
@@ -0,0 +1,16 @@
+class SorceryCore < ActiveRecord::Migration
+ def self.up
+ remove_column :users, :username
+
+ change_table(:users) do |t|
+ t.string :crypted_password, :default => nil
+ t.string :salt, :default => nil
+ end
+ end
+
+ def self.down
+ add_column :users, :username
+ remove_column :users, :crypted_password
+ remove_column :users, :salt
+ end
+end
\ No newline at end of file
diff --git a/db/migrate/20110930193128_sorcery_remember_me.rb b/db/migrate/20110930193128_sorcery_remember_me.rb
new file mode 100644
index 0000000..22d9579
--- /dev/null
+++ b/db/migrate/20110930193128_sorcery_remember_me.rb
@@ -0,0 +1,15 @@
+class SorceryRememberMe < ActiveRecord::Migration
+ def self.up
+ add_column :users, :remember_me_token, :string, :default => nil
+ add_column :users, :remember_me_token_expires_at, :datetime, :default => nil
+
+ add_index :users, :remember_me_token
+ end
+
+ def self.down
+ remove_index :users, :remember_me_token
+
+ remove_column :users, :remember_me_token_expires_at
+ remove_column :users, :remember_me_token
+ end
+end
\ No newline at end of file
diff --git a/db/schema.rb b/db/schema.rb
index c0cb0cd..38c0838 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -63,10 +63,15 @@ ActiveRecord::Schema.define(:version => 20111003201536) do
end
create_table "users", :force => true do |t|
- t.string "username"
t.datetime "created_at"
t.datetime "updated_at"
t.string "email"
+ t.string "crypted_password"
+ t.string "salt"
+ t.string "remember_me_token"
+ t.datetime "remember_me_token_expires_at"
end
+ add_index "users", ["remember_me_token"], :name => "index_users_on_remember_me_token"
+
end
diff --git a/db/seeds.rb b/db/seeds.rb
index 3e24ba1..07ecdc2 100644
--- a/db/seeds.rb
+++ b/db/seeds.rb
@@ -24,8 +24,9 @@ section_users = SectionUser.create([
])
users = User.create([
- {:id => 1, :email => "[email protected]"},
- {:id => 2, :email => "[email protected]"}
+ {:id => 1, :email => "[email protected]", :password => "test"},
+ {:id => 2, :email => "[email protected]", :password => "test"},
+ {:id => 3, :email => "[email protected]", :password => "test"}
])
comments = Comment.create([
diff --git a/public/tests/json/llgroup_auth.json b/public/tests/json/llgroup_auth.json
new file mode 100644
index 0000000..cb4ab7e
--- /dev/null
+++ b/public/tests/json/llgroup_auth.json
@@ -0,0 +1 @@
+{"errors": [], "AUTH": true}
\ No newline at end of file
diff --git a/test/fixtures/section_users.yml b/test/fixtures/section_users.yml
index 55f7eca..575974f 100644
--- a/test/fixtures/section_users.yml
+++ b/test/fixtures/section_users.yml
@@ -8,4 +8,9 @@ one:
two:
id: 2
section_id: 1
- user_id: 1
+ user_id: 2
+
+three:
+ id: 3
+ section_id: 2
+ user_id: 2
diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml
index 83d356b..bc5a27f 100644
--- a/test/fixtures/users.yml
+++ b/test/fixtures/users.yml
@@ -1,7 +1,9 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
one:
- username: MyString
+ id: 1
+ email: [email protected]
two:
- username: MyString
+ id: 2
+ email: [email protected]
diff --git a/test/functional/comments_controller_test.rb b/test/functional/comments_controller_test.rb
index d0dfac4..12b886e 100644
--- a/test/functional/comments_controller_test.rb
+++ b/test/functional/comments_controller_test.rb
@@ -1,4 +1,5 @@
require 'test_helper'
+require 'time'
class CommentsControllerTest < ActionController::TestCase
test "should list comments" do
@@ -47,7 +48,7 @@ class CommentsControllerTest < ActionController::TestCase
assert_response :success
assert_kind_of Array, comments
- comments.each { |comment| assert_equal Date.parse(comment['created_at']), Date.today }
+ comments.each { |comment| assert_equal Date.parse(comment['created_at'].to_s), Date.today }
end
test "should list comments after yesterday" do
@@ -57,7 +58,9 @@ class CommentsControllerTest < ActionController::TestCase
assert_response :success
assert_kind_of Array, comments
- comments.each { |comment| assert Time.parse(comment['created_at']) > (Date.today - 1) }
+ assert comments.length
+
+ comments.each { |comment| assert comment['created_at'] > (Date.today - 1) }
end
test "should only list comments with replies" do
diff --git a/test/functional/courses_controller_test.rb b/test/functional/courses_controller_test.rb
index d04c05d..522824a 100644
--- a/test/functional/courses_controller_test.rb
+++ b/test/functional/courses_controller_test.rb
@@ -1,14 +1,15 @@
require 'test_helper'
class CoursesControllerTest < ActionController::TestCase
- test "should list courses" do
- get :index, :format => 'json'
+ test "should only list courses of logged in user" do
+ user_id = 1
+ get :index, {:format => 'json'}, {:user_id => user_id}
courses = ActiveSupport::JSON.decode(@response.body)
assert_response :success
assert_kind_of Array, courses
-
+ assert_equal User.find(user_id).courses.length, courses.length
end
end
diff --git a/test/functional/documentation_controller_test.rb b/test/functional/documentation_controller_test.rb
index 08253a2..2417f38 100644
--- a/test/functional/documentation_controller_test.rb
+++ b/test/functional/documentation_controller_test.rb
@@ -5,6 +5,6 @@ class DocumentationControllerTest < ActionController::TestCase
get :index
assert_response :success
- assert_select 'h1', 'Byrd Comment API Documentation &#8211; Version 1'
+ assert_select 'h1', 'Byrd Comment API Documentation &#8211; Version 2'
end
end
diff --git a/test/functional/sections_controller_test.rb b/test/functional/sections_controller_test.rb
index 5e75bab..9d7e581 100644
--- a/test/functional/sections_controller_test.rb
+++ b/test/functional/sections_controller_test.rb
@@ -1,18 +1,8 @@
require 'test_helper'
class SectionsControllerTest < ActionController::TestCase
-
- test "should list sections" do
- get :index, :format => 'json'
-
- sections = ActiveSupport::JSON.decode(@response.body)
-
- assert_response :success
- assert_kind_of Array, sections
- end
-
test "should display a section" do
- get :show, :format => 'json', :id => 1
+ get :show, { :format => 'json', :id => 1 }, { :user_id => 1 }
##^ the controller's action
section = ActiveSupport::JSON.decode(@response.body)
@@ -28,4 +18,23 @@ class SectionsControllerTest < ActionController::TestCase
end
+ test "should display a user's available sections" do
+ get :index, { :format => 'json' }, { :user_id => 1 }
+
+ sections = ActiveSupport::JSON.decode(@response.body)
+
+ assert_response :success
+ assert_kind_of Array, sections
+ assert_equal User.find(1).sections.length, sections.length
+ end
+
+ test "should display a user's available sections 2" do
+ get :index, { :format => 'json' }, { :user_id => 2 }
+
+ sections2 = ActiveSupport::JSON.decode(@response.body)
+ assert_response :success
+ assert_kind_of Array, sections2
+ assert_equal User.find(2).sections.length, sections2.length
+ end
+
end
diff --git a/test/functional/sessions_controller_test.rb b/test/functional/sessions_controller_test.rb
new file mode 100644
index 0000000..243a6b3
--- /dev/null
+++ b/test/functional/sessions_controller_test.rb
@@ -0,0 +1,25 @@
+require 'test_helper'
+
+class SessionsControllerTest < ActionController::TestCase
+ # Replace this with your real tests.
+ test "should login with correct email and password" do
+ # Note that password doesn't matter with Wharton e-mail
+ # addresses. See LLgroupFake.
+ post :create, :email => "[email protected]", :password => "test"
+
+ result = ActiveSupport::JSON.decode(@response.body)
+
+ assert_response :success
+ assert_not_nil result["id"]
+ end
+ test "should not login with incorrect email and password" do
+ # password actually doesn't matter, so use a diff email address
+ post :create, :email => "[email protected]", :password => "test2"
+
+ result = ActiveSupport::JSON.decode(@response.body)
+
+ assert_response :missing
+ assert_nil result["id"]
+ end
+
+end
diff --git a/test/functional/users_controller_test.rb b/test/functional/users_controller_test.rb
new file mode 100644
index 0000000..c3db123
--- /dev/null
+++ b/test/functional/users_controller_test.rb
@@ -0,0 +1,8 @@
+require 'test_helper'
+
+class UsersControllerTest < ActionController::TestCase
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+end
diff --git a/test/unit/helpers/sessions_helper_test.rb b/test/unit/helpers/sessions_helper_test.rb
new file mode 100644
index 0000000..7d44e09
--- /dev/null
+++ b/test/unit/helpers/sessions_helper_test.rb
@@ -0,0 +1,4 @@
+require 'test_helper'
+
+class SessionsHelperTest < ActionView::TestCase
+end
diff --git a/test/unit/helpers/users_helper_test.rb b/test/unit/helpers/users_helper_test.rb
new file mode 100644
index 0000000..96af37a
--- /dev/null
+++ b/test/unit/helpers/users_helper_test.rb
@@ -0,0 +1,4 @@
+require 'test_helper'
+
+class UsersHelperTest < ActionView::TestCase
+end
diff --git a/test/unit/user_test.rb b/test/unit/user_test.rb
index a64d2d3..e33e3a2 100644
--- a/test/unit/user_test.rb
+++ b/test/unit/user_test.rb
@@ -2,7 +2,28 @@ require 'test_helper'
class UserTest < ActiveSupport::TestCase
# Replace this with your real tests.
- test "the truth" do
- assert true
+ test "should distinguish between wharton and non-wharton credentials" do
+ assert User.wharton_credentials?( ["[email protected]"])
+ assert User.wharton_credentials?( ["[email protected]"])
+ assert !User.wharton_credentials?( ["[email protected]"])
+ end
+
+ test "should authenticate against llgroup" do
+ # Mock the user object by deriving from it and changing the LLGroup class
+ # we use to perform the authentication
+ class UserMock < User
+ def self.llgroup_class
+ # we're using this class itself as the llgroup class--its pulling
+ # double-duty.
+ UserMock
+ end
+ # this is the authenticate method of the llgroup_class
+ def self.authenticate(email, password)
+ true
+ end
+ end
+
+ assert UserMock.authenticate_wharton("[email protected]", "")
+ assert !UserMock.authenticate_wharton("[email protected]", "")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment