1+ require 'spec_helper'
2+
3+ describe Grape ::Middleware ::Auth ::OAuth2 do
4+ class FakeToken
5+ def self . verify ( token )
6+ FakeToken . new ( token ) if %w( g e ) . include? ( token [ 0 ..0 ] )
7+ end
8+
9+ def initialize ( token )
10+ self . token = token
11+ end
12+
13+ def expired?
14+ self . token [ 0 ..0 ] == 'e'
15+ end
16+
17+ def permission_for? ( env )
18+ env [ 'PATH_INFO' ] == '/forbidden' ? false : true
19+ end
20+
21+ attr_accessor :token
22+ end
23+
24+ def app
25+ Rack ::Builder . app do
26+ use Grape ::Middleware ::Auth ::OAuth2 , :token_class => 'FakeToken'
27+ run lambda { |env | [ 200 , { } , [ ( env [ 'api.token' ] . token rescue '' ) ] ] }
28+ end
29+ end
30+
31+ context 'with the token in the query string' do
32+ context 'and a valid token' do
33+ before { get '/awesome?oauth_token=g123' }
34+
35+ it 'should set env["api.token"]' do
36+ last_response . body . should == 'g123'
37+ end
38+ end
39+
40+ context 'and an invalid token' do
41+ before do
42+ @err = catch :error do
43+ get '/awesome?oauth_token=b123'
44+ end
45+ end
46+
47+ it 'should throw an error' do
48+ @err [ :status ] . should == 401
49+ end
50+
51+ it 'should set the WWW-Authenticate header in the response' do
52+ @err [ :headers ] [ 'WWW-Authenticate' ] . should == "OAuth realm='OAuth API', error='invalid_token'"
53+ end
54+ end
55+ end
56+
57+ context 'with an expired token' do
58+ before do
59+ @err = catch :error do
60+ get '/awesome?oauth_token=e123'
61+ end
62+ end
63+
64+ it { @err [ :status ] . should == 401 }
65+ it { @err [ :headers ] [ 'WWW-Authenticate' ] . should == "OAuth realm='OAuth API', error='expired_token'" }
66+ end
67+
68+ context 'with the token in the header' do
69+ before { get '/awesome' , { } , 'Authorization' => 'OAuth g123' }
70+ it { last_response . body . should == 'g123' }
71+ end
72+
73+ context 'with the token in the POST body' do
74+ before { post '/awesome' , { 'oauth_token' => 'g123' } }
75+ it { last_response . body . should == 'g123' }
76+ end
77+
78+ context 'when accessing something outside its scope' do
79+ before do
80+ @err = catch :error do
81+ get '/forbidden?oauth_token=g123'
82+ end
83+ end
84+
85+ it { @err [ :headers ] [ 'WWW-Authenticate' ] . should == "OAuth realm='OAuth API', error='insufficient_scope'" }
86+ it { @err [ :status ] . should == 403 }
87+ end
88+ end
0 commit comments