Skip to content

Commit

Permalink
Revert "moving to URLComponents for serialization"
Browse files Browse the repository at this point in the history
This reverts commit 7e44d55.
  • Loading branch information
edjiang committed Sep 6, 2016
1 parent 5d61691 commit 81cc72d
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 76 deletions.
15 changes: 4 additions & 11 deletions Sources/TurnstileWeb/Facebook.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
//
//

import Foundation
import Turnstile
import HTTP
import JSON
Expand All @@ -20,8 +19,8 @@ public class Facebook: OAuth2, Realm {
Facebook Developers Console.
*/
public init(clientID: String, clientSecret: String) {
let tokenURL = URL(string: "https://graph.facebook.com/v2.3/oauth/access_token")!
let authorizationURL = URL(string: "https://www.facebook.com/dialog/oauth")!
let tokenURL = "https://graph.facebook.com/v2.3/oauth/access_token"
let authorizationURL = "https://www.facebook.com/dialog/oauth"
super.init(clientID: clientID, clientSecret: clientSecret, authorizationURL: authorizationURL, tokenURL: tokenURL)
}

Expand All @@ -41,14 +40,8 @@ public class Facebook: OAuth2, Realm {
Authenticates a Facebook access token.
*/
public func authenticate(credentials: AccessToken) throws -> FacebookAccount {
var urlComponents = URLComponents(string: "https://graph.facebook.com/debug_token")!
urlComponents.setQueryItems(dict: ["input_token": credentials.string,
"access_token": appAccessToken])

guard let url = urlComponents.url else {
throw FacebookError(json: JSON([]))
}
let request = try! Request(method: .get, url: url)
let url = "https://graph.facebook.com/debug_token?input_token=" + credentials.string + "&access_token=" + appAccessToken
let request = try! Request(method: .get, uri: url)
request.headers["Accept"] = "application/json"

guard let response = try? HTTPClient.respond(to: request) else { throw APIConnectionError() }
Expand Down
6 changes: 3 additions & 3 deletions Sources/TurnstileWeb/Google.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ public class Google: OAuth2, Realm {
Google Developers Console.
*/
public init(clientID: String, clientSecret: String) {
let tokenURL = URL(string: "https://www.googleapis.com/oauth2/v4/token")!
let authorizationURL = URL(string: "https://accounts.google.com/o/oauth2/auth")!
let tokenURL = "https://www.googleapis.com/oauth2/v4/token"
let authorizationURL = "https://accounts.google.com/o/oauth2/auth"
super.init(clientID: clientID, clientSecret: clientSecret, authorizationURL: authorizationURL, tokenURL: tokenURL)
}

Expand Down Expand Up @@ -59,7 +59,7 @@ public class Google: OAuth2, Realm {
throw IncorrectCredentialsError()
}

public override func getLoginLink(redirectURL: String, state: String, scopes: [String] = ["profile"]) -> URL {
public override func getLoginLink(redirectURL: String, state: String, scopes: [String] = ["profile"]) -> String {
return super.getLoginLink(redirectURL: redirectURL, state: state, scopes: scopes)
}
}
Expand Down
56 changes: 16 additions & 40 deletions Sources/TurnstileWeb/OAuth2.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,16 @@ public class OAuth2 {
public let clientSecret: String

/// The Authorization Endpoint of the OAuth 2 Server
public let authorizationURL: URL
public let authorizationURL: String

/// The Token Endpoint of the OAuth 2 Server
public let tokenURL: URL
public let tokenURL: String

let HTTPClient = TempHTTPClient()


/// Creates the OAuth 2 client
public init(clientID: String, clientSecret: String, authorizationURL: URL, tokenURL: URL) {
public init(clientID: String, clientSecret: String, authorizationURL: String, tokenURL: String) {
self.clientID = clientID
self.clientSecret = clientSecret
self.authorizationURL = authorizationURL
Expand All @@ -51,21 +51,17 @@ public class OAuth2 {
/// You will need to configure this in the admin console for the OAuth provider's site.
/// - parameter state: A randomly generated string to prevent CSRF attacks.
/// Verify this when validating the Authorization Code
/// - parameter scopes: A list of OAuth scopes you'd like the user to grant
public func getLoginLink(redirectURL: String, state: String, scopes: [String] = []) -> URL {
let queryItems = ["response_type": "code",
"client_id": clientID,
"redirect_uri": redirectURL,
"state": state,
"scope": scopes.joined(separator: " ")]
var urlComponents = URLComponents(url: authorizationURL, resolvingAgainstBaseURL: false)
urlComponents?.setQueryItems(dict: queryItems)
/// - parameter scopes: A list of OAuth scopes you'd like the user to grant.
public func getLoginLink(redirectURL: String, state: String, scopes: [String] = []) -> String {
// TODO: serialize these better
var loginLink = authorizationURL + "?"
loginLink += "response_type=code"
loginLink += "&client_id=" + clientID
loginLink += "&redirect_uri=" + redirectURL
loginLink += "&state=" + state
loginLink += "&scope=" + scopes.joined(separator: "%20")

if let result = urlComponents?.url {
return result
} else {
preconditionFailure() // TODO: replace with a better error
}
return loginLink
}


Expand All @@ -74,18 +70,10 @@ public class OAuth2 {
/// - throws: APIConnectionError() if we cannot connect to the OAuth server
/// - throws: InvalidAPIResponse() if the server does not respond in a way we expect
public func exchange(authorizationCode: AuthorizationCode) throws -> OAuth2Token {
let queryItems = ["client_id": clientID,
"client_secret": clientSecret,
"redirect_uri": authorizationCode.redirectURL,
"code": authorizationCode.code]
var urlComponents = URLComponents(url: tokenURL, resolvingAgainstBaseURL: false)
urlComponents?.setQueryItems(dict: queryItems)

guard let url = urlComponents?.url else {
preconditionFailure() // TODO: replace with a better error
}
// TODO: serialize these better
let url = tokenURL + "?grant_type=authorization_code&client_id=\(clientID)&redirect_uri=\(authorizationCode.redirectURL)&client_secret=\(clientSecret)&code=\(authorizationCode.code)"
let request = try! Request(method: .post, uri: url)

let request = try Request(method: .get, url: url)
request.headers["Accept"] = "application/json"

guard let response = try? HTTPClient.respond(to: request) else {
Expand Down Expand Up @@ -151,15 +139,3 @@ private extension URI {
return result
}
}

extension Request {
convenience init(method: HTTP.Method, url: URL) throws {
try self.init(method: method, uri: url.absoluteString)
}
}

extension URLComponents {
mutating func setQueryItems(dict: [String: String]) {
self.queryItems = dict.map({URLQueryItem(name: $0, value: $1)})
}
}
26 changes: 4 additions & 22 deletions Tests/TurnstileWebTests/OAuth2Tests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ class OAuth2Tests: XCTestCase {
var oauth2: OAuth2!
let validClientID = "validClientID"
let validClientSecret = "validClientSecret"
let authorizationURL = URL(string: "https://example.com/oauth/authorize")!
let tokenURL = URL(string: "https://example.com/oauth/token")!
let authorizationURL = "https://example.com/oauth/authorize"
let tokenURL = "https://example.com/oauth/token"
let redirectURL = "https://example.com/callback"
let state = "12345"
let scopes = ["email", "profile"]
Expand All @@ -26,27 +26,9 @@ class OAuth2Tests: XCTestCase {
}

func testThatCorrectLoginLinkIsGenerated() {
guard let urlComponents = URLComponents(url: oauth2.getLoginLink(redirectURL: redirectURL, state: state, scopes: scopes), resolvingAgainstBaseURL: false) else {
XCTFail()
return
}
let url = oauth2.getLoginLink(redirectURL: redirectURL, state: state, scopes: scopes)

//XCTAssertEqual(url, URL(string: "https://example.com/oauth/authorize?response_type=code&client_id=validClientID&redirect_uri=https://example.com/callback&state=12345&scope=email%20profile")!)

XCTAssertEqual(urlComponents.scheme, "https")
XCTAssertEqual(urlComponents.host, "example.com")
XCTAssertEqual(urlComponents.path, "/oauth/authorize")

guard let queryItems = urlComponents.queryItems else {
XCTFail("No query parameters found in the generated URL")
return
}

XCTAssert(queryItems.contains(URLQueryItem(name: "response_type", value: "code")))
XCTAssert(queryItems.contains(URLQueryItem(name: "client_id", value: "validClientID")))
XCTAssert(queryItems.contains(URLQueryItem(name: "redirect_uri", value: "https://example.com/callback")))
XCTAssert(queryItems.contains(URLQueryItem(name: "state", value: "12345")))
XCTAssert(queryItems.contains(URLQueryItem(name: "scope", value: "email profile")))
XCTAssertEqual(url, "https://example.com/oauth/authorize?response_type=code&client_id=validClientID&redirect_uri=https://example.com/callback&state=12345&scope=email%20profile")
}

func testThatAuthorizationCodeIsExchangedForToken() {
Expand Down

0 comments on commit 81cc72d

Please sign in to comment.