Implement sessions/create in JSON API

This commit is contained in:
Thibault Jouan 2012-02-26 11:16:52 +00:00
parent 499b06c9e5
commit 5dfafdcc46
6 changed files with 103 additions and 0 deletions

View File

@ -1,4 +1,7 @@
class Api::ApplicationController < ApplicationController class Api::ApplicationController < ApplicationController
skip_before_filter :verify_authenticity_token
skip_before_filter :authenticate!, :only => [:cor_preflight]
before_filter :cor_filter before_filter :cor_filter
def cor_filter def cor_filter
@ -12,4 +15,8 @@ class Api::ApplicationController < ApplicationController
head :ok head :ok
end end
def authenticate!
head :unauthorized if current_user.nil?
end
end end

View File

@ -0,0 +1,14 @@
class Api::V0::SessionsController < Api::ApplicationController
skip_before_filter :authenticate!, :only => [:create]
def create
user = User.find_by_email(params[:session][:email])
if ! user.try(:authenticate?, params[:session][:password])
return render :json => '', :status => :not_found
end
@user = user
self.current_user = @user
end
end

View File

@ -0,0 +1,3 @@
object @user
attribute :id

View File

@ -2,6 +2,7 @@ Scube::Application.routes.draw do
namespace :api do namespace :api do
namespace :v0 do namespace :v0 do
resources :playlists, :only => [:index] resources :playlists, :only => [:index]
resources :sessions, :only => [:create]
end end
match '*all' => 'application#cor_preflight', :via => :options match '*all' => 'application#cor_preflight', :via => :options

View File

@ -0,0 +1,49 @@
require 'spec_helper'
describe Api::V0::SessionsController do
describe 'POST create' do
let(:user) { Factory.create(:user) }
def do_create
post :create, :format => :json, :session => {
:email => user.email,
:password => user.password
}
end
context 'with valid credentials' do
before do
do_create
end
it 'signs the user in' do
controller.current_user.should == user
end
it 'assigns the user' do
assigns[:user].should == user
end
end
[:email, :password].each do |attr|
context "with invalid credentials (#{attr})" do
before do
user.stub(attr => user.send(attr) + '_INVALID')
do_create
end
it 'returns a not found response' do
response.should be_not_found
end
it 'returns an empty body' do
response.body.should be_empty
end
it 'assigns no user' do
assigns[:user].should be_nil
end
end
end
end
end

View File

@ -0,0 +1,29 @@
require 'spec_helper'
feature 'API sign in' do
let(:user) { Factory.create(:user) }
def do_create
post api_v0_sessions_path, :format => :json, :session => {
:email => user.email,
:password => user.password
}
end
scenario 'signs the user in with valid credentials' do
do_create
response.should be_success
(JSON response.body).should include 'id'
end
[:email, :password].each do |attr|
scenario "rejects authentication with invalid credentials (#{attr})" do
user.stub(attr => user.send(attr) + '_INVALID')
do_create
response.should be_not_found
response.body.should be_empty
end
end
end