Skip to content

Commit

Permalink
validate authorize url
Browse files Browse the repository at this point in the history
  • Loading branch information
noppoMan committed May 31, 2017
1 parent 749f759 commit 098a80d
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 8 deletions.
4 changes: 2 additions & 2 deletions Sources/HexavilleAuth/HexaviileAuth.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ public struct HexavilleAuth: Middleware {

public func respond(to request: Request, context: ApplicationContext) throws -> Chainer {
let currentPath = request.path ?? "/"

for provider in providers {
if provider.path == currentPath {
let response = Response(
status: .found,
headers: [
"Location": provider.createAuthorizeURL().absoluteString
"Location": try provider.createAuthorizeURL().absoluteString
]
)
return .respond(to: response)
Expand Down
14 changes: 10 additions & 4 deletions Sources/HexavilleAuth/OAuth/OAuth2.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
import Foundation
import HexavilleFramework

public enum OAuth2Error: Error {
case invalidAuthrozeURL(String)
}

public class OAuth2 {
let consumerKey: String
let consumerSecret: String
Expand All @@ -32,7 +36,7 @@ public class OAuth2 {
return dict.map({ "\($0.key)=\($0.value)" }).joined(separator: "&")
}

public func createAuthorizeURL() -> URL {
public func createAuthorizeURL() throws -> URL {
let params = [
"client_id": consumerKey,
"redirect_uri": callbackURL,
Expand All @@ -42,7 +46,11 @@ public class OAuth2 {

let queryString = dictionary2Query(params)

return URL(string: "\(authorizeURL)?\(queryString)")!
guard let url = URL(string: "\(authorizeURL)?\(queryString)") else {
throw OAuth2Error.invalidAuthrozeURL("\(authorizeURL)?\(queryString)")
}

return url
}

public func getAccessToken(request: Request) throws -> Credential {
Expand All @@ -60,8 +68,6 @@ public class OAuth2 {
"redirect_uri=\(self.callbackURL)"
]

print(body)

let client = try HTTPClient(url: url)
try client.open()
let response = try client.request(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ public protocol OAuth2AuthentitionProvidable {
}

extension OAuth2AuthentitionProvidable {
public func createAuthorizeURL() -> URL {
return oauth.createAuthorizeURL()
public func createAuthorizeURL() throws -> URL {
return try oauth.createAuthorizeURL()
}

public func getAccessToken(request: Request) throws -> Credential {
Expand Down
4 changes: 4 additions & 0 deletions Sources/HexavilleAuthExample/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ app.use(middleware)

let router = Router()

router.use(.get, "/") { _ in
return Response(body: "Welcome to Hexaville Auth")
}

app.use(router)

app.catch { error in
Expand Down

0 comments on commit 098a80d

Please sign in to comment.