Skip to content

Commit 75deaf2

Browse files
committed
Spec existing token authenticatable behavior
1 parent 02a430b commit 75deaf2

File tree

2 files changed

+72
-1
lines changed

2 files changed

+72
-1
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
require "support/base_controller_double"
2+
3+
module Kracken
4+
class TokenAuthController < BaseControllerDouble
5+
include Kracken::Controllers::TokenAuthenticatable
6+
public :authenticate_user_with_token!
7+
public :current_user
8+
9+
def authenticate_or_request_with_http_token(realm = nil)
10+
/\AToken token="(?<token>.*)"\z/ =~ request.env['HTTP_AUTHORIZATION']
11+
yield token if block_given?
12+
end
13+
end
14+
15+
RSpec.describe Controllers::TokenAuthenticatable do
16+
describe "authenticating via a token" do
17+
before do
18+
allow(Authenticator).to receive(:user_with_token)
19+
end
20+
21+
it "munges the request headers to support parameterized tokens" do
22+
controller = TokenAuthController.new
23+
controller.request.env = {
24+
'HTTP_AUTHORIZATION' => 'Token token="header token"'
25+
}
26+
controller.params = { token: "param token" }
27+
28+
expect {
29+
controller.authenticate_user_with_token!
30+
}.to change {
31+
controller.request.env
32+
}.from(
33+
'HTTP_AUTHORIZATION' => 'Token token="header token"'
34+
).to(
35+
'HTTP_AUTHORIZATION' => 'Token token="param token"'
36+
)
37+
end
38+
39+
it "leaves the request header unchange when with no parameterized token" do
40+
controller = TokenAuthController.new
41+
controller.request.env = {
42+
'HTTP_AUTHORIZATION' => 'Token token="any token"'
43+
}
44+
45+
expect {
46+
controller.authenticate_user_with_token!
47+
}.not_to change { controller.request.env }.from(
48+
'HTTP_AUTHORIZATION' => 'Token token="any token"'
49+
)
50+
end
51+
52+
it "authenticates the current user via the token" do
53+
a_user = instance_double(User)
54+
allow(Authenticator).to receive(:user_with_token).with("any token")
55+
.and_return(a_user)
56+
controller = TokenAuthController.new
57+
controller.request.env = {
58+
'HTTP_AUTHORIZATION' => 'Token token="any token"'
59+
}
60+
61+
expect {
62+
controller.authenticate_user_with_token!
63+
}.to change { controller.current_user }.from(nil).to(a_user)
64+
end
65+
end
66+
end
67+
end

spec/support/base_controller_double.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
module Kracken
22
class BaseControllerDouble
3-
attr_accessor :session, :cookies
3+
Request = Struct.new(:env)
4+
5+
attr_accessor :session, :cookies, :request, :params
46

57
def initialize
68
@session = {}
79
@cookies = {}
10+
@request = Request.new({})
11+
@params = {}
812
end
913

1014
def self.helper_method(*) ; end

0 commit comments

Comments
 (0)