Commit 7476be2
Changed files (7)
app
controllers
models
services
db
spec
controllers
models
app/controllers/logins_controller.rb
@@ -1,12 +1,14 @@
class LoginsController < ApplicationController
before_filter :load_dependencies
+ skip_before_filter :ensure_valid_session, only: [:new, :create]
layout 'public'
def new
end
def create
- if @login_command.run(params)
+ if @session = @login_command.run(self)
+ session[:session_id] = @session.id
redirect_to dashboard_path
else
flash[:error] = I18n.translate(:invalid_credentials)
app/models/services/login_command.rb
@@ -3,7 +3,10 @@ class LoginCommand
@users = users
end
- def run(params)
- @users.find_by(email: params[:email]).authenticate(params[:password])
+ def run(context)
+ user = @users.find_by(email: context.params[:email])
+ if user.authenticate(context.params[:password])
+ Session.create!(user_id: user.id, ip_address: context.request.remote_ip)
+ end
end
end
app/models/session.rb
@@ -1,2 +1,2 @@
-class Session
+class Session < ActiveRecord::Base
end
db/migrate/20140410032614_create_sessions.rb
@@ -0,0 +1,9 @@
+class CreateSessions < ActiveRecord::Migration
+ def change
+ create_table :sessions do |t|
+ t.integer :user_id
+ t.string :ip_address
+ t.timestamps
+ end
+ end
+end
db/schema.rb
@@ -11,11 +11,18 @@
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema.define(version: 20140409034211) do
+ActiveRecord::Schema.define(version: 20140410032614) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
+ create_table "sessions", force: true do |t|
+ t.integer "user_id"
+ t.string "ip_address"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
create_table "users", force: true do |t|
t.string "email"
t.string "password_digest"
spec/controllers/logins_controller_spec.rb
@@ -9,7 +9,7 @@ describe LoginsController do
end
describe "#create" do
- let(:user) { double(authenticate: false) }
+ let(:user) { double(id: 1, authenticate: false) }
before :each do
User.stub(:find_by).with(email: 'email@example.com').and_return(user)
@@ -25,10 +25,20 @@ describe LoginsController do
end
context "when the email and password is correct" do
- it "redirects to the dashboard" do
+ before :each do
post :create, email: 'email@example.com', password: 'password'
+ end
+
+ it "redirects to the dashboard" do
response.should redirect_to(dashboard_path)
end
+
+ it "creates a new session" do
+ session[:session_id].should_not be_nil
+ last_session = Session.last
+ session[:session_id].should == last_session.id
+ last_session.ip_address.should == "0.0.0.0"
+ end
end
end
end
spec/models/session_spec.rb
@@ -0,0 +1,12 @@
+require "spec_helper"
+
+describe Session do
+ context "#save" do
+ it "creates a new session" do
+ Session.create!(user_id: 1, ip_address: '127.0.0.1')
+ session = Session.last
+ session.user_id.should == 1
+ session.ip_address.should == "127.0.0.1"
+ end
+ end
+end