aboutsummaryrefslogtreecommitdiff
path: root/src/actions/mixins/api/auth/helpers.cr
blob: 6b51cb5a2d9e557c09e5d13d1ef91c68e096e490 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
module Api::Auth::Helpers
  # The 'memoize' macro makes sure only one query is issued to find the user
  memoize def current_user? : User?
    auth_token.try do |value|
      user_from_auth_token(value)
    end
  end

  private def auth_token : String?
    bearer_token || token_param
  end

  private def bearer_token : String?
    context.request.headers["Authorization"]?
      .try(&.gsub("Bearer", ""))
      .try(&.strip)
  end

  private def token_param : String?
    params.get?(:auth_token)
  end

  private def user_from_auth_token(token : String) : User?
    UserToken.decode_user_id(token).try do |user_id|
      UserQuery.new.id(user_id).first?
    end
  end
end