Skip to content

Commit

Permalink
Use URLSession instead of Prorosum.HTTPClient to avoid ssl verify set…
Browse files Browse the repository at this point in the history
…up failure
  • Loading branch information
noppoMan committed May 31, 2017
1 parent c7ca427 commit 7f27b36
Showing 1 changed file with 50 additions and 11 deletions.
61 changes: 50 additions & 11 deletions Sources/HexavilleAuth/OAuth/OAuth2.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,37 @@ public enum OAuth2Error: Error {
case invalidAuthrozeURL(String)
}

#if os(Linux)
let _urlSessionShared = URLSession(configuration: URLSessionConfiguration(), delegate: nil, delegateQueue: nil)
extension URLSession {
static var shared: URLSession {
return _urlSessionShared
}
}
#endif

extension URLSession {
func resumeSync(with request: URLRequest) throws -> (HTTPURLResponse, Data) {
let chan = Channel<(Error?, (HTTPURLResponse, Data)?)>.make(capacity: 1)

let task = self.dataTask(with: request) { data, response, error in
if let error = error {
try! chan.send((error, nil))
return
}
try! chan.send((nil, (response as! HTTPURLResponse, data!)))
}

task.resume()

let (err, tupple) = try chan.receive()
if let error = err {
throw error
}
return (tupple!.0, tupple!.1)
}
}

public class OAuth2 {
let consumerKey: String
let consumerSecret: String
Expand Down Expand Up @@ -68,23 +99,31 @@ public class OAuth2 {
"redirect_uri=\(self.callbackURL.absoluteURL()!.absoluteString)"
]

let client = try HTTPClient(url: url)
try client.open()
let response = try client.request(
method: .post,
headers: [
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
],
body: body.joined(separator: "&").data
)
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpBody = body.joined(separator: "&").data

let (response, bodyData) = try URLSession.shared.resumeSync(with: request)

guard (200..<300).contains(response.statusCode) else {
var headers: Headers = [:]
for el in response.allHeaderFields {
headers[el.key.description] = "\(el.value)"
}

let response = Response(
status: Response.Status(statusCode: response.statusCode),
headers: headers,
body: bodyData
)

throw HexavilleAuthError.responseError(response)
}

do {
let bodyDictionary = try JSONSerialization.jsonObject(with: response.body.asData(), options: []) as! [String: Any]
let bodyDictionary = try JSONSerialization.jsonObject(with: bodyData, options: []) as! [String: Any]
return try Credential(withDictionary: bodyDictionary)
} catch {
throw error
Expand Down

0 comments on commit 7f27b36

Please sign in to comment.