File: authorization.rb

package info (click to toggle)
ruby-protocol-http 0.55.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 840 kB
  • sloc: ruby: 6,904; makefile: 4
file content (46 lines) | stat: -rw-r--r-- 1,281 bytes parent folder | download
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2019-2025, by Samuel Williams.
# Copyright, 2024, by Earlopain.

module Protocol
	module HTTP
		module Header
			# Used for basic authorization.
			#
			# ~~~ ruby
			# headers.add('authorization', Authorization.basic("my_username", "my_password"))
			# ~~~
			#
			# TODO Support other authorization mechanisms, e.g. bearer token.
			class Authorization < String
				# Splits the header into the credentials.
				#
				# @returns [Tuple(String, String)] The username and password.
				def credentials
					self.split(/\s+/, 2)
				end
				
				# Generate a new basic authorization header, encoding the given username and password.
				#
				# @parameter username [String] The username.
				# @parameter password [String] The password.
				# @returns [Authorization] The basic authorization header.
				def self.basic(username, password)
					strict_base64_encoded = ["#{username}:#{password}"].pack("m0")
					
					self.new(
						"Basic #{strict_base64_encoded}"
					)
				end
				
				# Whether this header is acceptable in HTTP trailers.
				# @returns [Boolean] `false`, as authorization headers are used for request authentication.
				def self.trailer?
					false
				end
			end
		end
	end
end