|
| 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 |
0 commit comments