Skip to content

Commit

Permalink
fix: add an error when trying to generate twitch http headers without…
Browse files Browse the repository at this point in the history
… client ID
  • Loading branch information
LosFarmosCTL committed Jan 22, 2024
1 parent 206b9fa commit 05c4e56
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 9 deletions.
2 changes: 1 addition & 1 deletion Sources/Twitch/API/Helix.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public final class Helix {

var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = method
urlRequest.allHTTPHeaderFields = authentication.httpHeaders()
urlRequest.allHTTPHeaderFields = try? authentication.httpHeaders()

return try await self.send(urlRequest)
}
Expand Down
15 changes: 10 additions & 5 deletions Sources/Twitch/TwitchCredentials.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ public struct TwitchCredentials {
internal let clientID: String?

public init(oAuth: String, clientID: String? = nil) {
// assure that the stored token always starts with "oauth:"
if !oAuth.starts(with: oAuthPrefix) {
self.oAuth = oAuthPrefix + oAuth
} else {
Expand All @@ -18,14 +19,18 @@ public struct TwitchCredentials {
return String(oAuth.dropFirst(oAuthPrefix.count))
}

internal func httpHeaders() -> [String: String] {
internal func httpHeaders() throws -> [String: String] {
guard let clientID = self.clientID else {
throw CredentialError.missingClientID
}

var headers: [String: String] = [:]
headers.updateValue("Bearer " + self.cleanOAuth, forKey: "Authorization")

if let clientID = self.clientID {
headers.updateValue(clientID, forKey: "Client-Id")
}
headers.updateValue(clientID, forKey: "Client-Id")
headers.updateValue("Bearer \(self.cleanOAuth)", forKey: "Authorization")

return headers
}
}

public enum CredentialError: Error { case missingClientID }
13 changes: 10 additions & 3 deletions Tests/TwitchTests/AuthenticationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,19 +26,26 @@ class AuthenticationTests: XCTestCase {
XCTAssertEqual(auth.oAuth, "oauth:" + oAuth)
}

func testHTTPHeaders() {
func testHTTPHeaders() throws {
let oAuth = "abcdefghijklmnop"
let clientID = "1234567890"
let auth = TwitchCredentials(oAuth: oAuth, clientID: clientID)

let headers = auth.httpHeaders()
let headers = try auth.httpHeaders()

XCTAssert(
headers.contains(where: {
$0.key == "Authorization" && $0.value == "Bearer " + oAuth
$0.key == "Authorization" && $0.value == "Bearer \(oAuth)"
}))
XCTAssert(
headers.contains(where: { $0.key == "Client-Id" && $0.value == clientID })
)
}

func testHTTPHeadersWithoutClientId() {
let oAuth = "abcdefghijklmnop"
let auth = TwitchCredentials(oAuth: oAuth)

XCTAssertThrowsError(try auth.httpHeaders())
}
}

0 comments on commit 05c4e56

Please sign in to comment.