Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rework errors handling #26

Merged
merged 7 commits into from
Jun 20, 2016
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Refactor error handling & reporting in API & Web
Now instead of an Enum, an ErrorType is supplied on each failure.

The ErrorType could be either a OS error (e.g. Foundation errors)
or Auth0 errors either returned by the API or it's components because a
configuration issue.
  • Loading branch information
hzalaz committed Jun 20, 2016
commit 02d071713bba71aed726687f9e2d2b42e1a9db6f
2 changes: 1 addition & 1 deletion App/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import Auth0

class ViewController: UIViewController {

var onAuth: (Result<Credentials, Authentication.Error> -> ())!
var onAuth: (Result<Credentials> -> ())!

@IBOutlet weak var oauth2: UIButton!

Expand Down
6 changes: 6 additions & 0 deletions Auth0.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@
5FD255AF1D14A4A300387ECB /* AuthenticationError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FD255AD1D14A4A300387ECB /* AuthenticationError.swift */; };
5FD255B11D14A9E000387ECB /* AuthenticationErrorSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FD255B01D14A9E000387ECB /* AuthenticationErrorSpec.swift */; };
5FD255B21D14A9E000387ECB /* AuthenticationErrorSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FD255B01D14A9E000387ECB /* AuthenticationErrorSpec.swift */; };
5FD255B41D14DD2600387ECB /* ManagementError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FD255B31D14DD2600387ECB /* ManagementError.swift */; };
5FD255B51D14DD2600387ECB /* ManagementError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FD255B31D14DD2600387ECB /* ManagementError.swift */; };
5FE2F8A61CCA9C17003628F4 /* CredentialsSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FE2F8A51CCA9C17003628F4 /* CredentialsSpec.swift */; };
5FE2F8A71CCA9C17003628F4 /* CredentialsSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FE2F8A51CCA9C17003628F4 /* CredentialsSpec.swift */; };
5FE2F8A91CCE54F1003628F4 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FE2F8A81CCE54F1003628F4 /* Result.swift */; };
Expand Down Expand Up @@ -237,6 +239,7 @@
5FCCC31B1CF51DF300901E2E /* _ObjectiveManagementAPI.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _ObjectiveManagementAPI.swift; sourceTree = "<group>"; };
5FD255AD1D14A4A300387ECB /* AuthenticationError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AuthenticationError.swift; sourceTree = "<group>"; };
5FD255B01D14A9E000387ECB /* AuthenticationErrorSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AuthenticationErrorSpec.swift; sourceTree = "<group>"; };
5FD255B31D14DD2600387ECB /* ManagementError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ManagementError.swift; sourceTree = "<group>"; };
5FE2F8A51CCA9C17003628F4 /* CredentialsSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CredentialsSpec.swift; sourceTree = "<group>"; };
5FE2F8A81CCE54F1003628F4 /* Result.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Result.swift; sourceTree = "<group>"; };
5FE2F8B11CCEAED8003628F4 /* Requestable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Requestable.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -558,6 +561,7 @@
5FF465BB1CE2AC4500F7ED8C /* Management.swift */,
5FADB60B1CED7E0800D4BB50 /* UserPatchAttributes.swift */,
5FADB6051CED27FB00D4BB50 /* Users.swift */,
5FD255B31D14DD2600387ECB /* ManagementError.swift */,
);
path = Management;
sourceTree = "<group>";
Expand Down Expand Up @@ -814,6 +818,7 @@
5FCAB1791D09124D00331C84 /* NSURL+Auth0.swift in Sources */,
5F7989511CF13A20009E8A10 /* _ObjectiveAuthenticationAPI.swift in Sources */,
5F74CB401CEFD5E600226823 /* JSONObjectPayload.swift in Sources */,
5FD255B41D14DD2600387ECB /* ManagementError.swift in Sources */,
5FE2F8B81CD0E910003628F4 /* Request.swift in Sources */,
5FE2F8A91CCE54F1003628F4 /* Result.swift in Sources */,
5F3965C21CF67CF000CDE7C0 /* WebAuth.swift in Sources */,
Expand All @@ -836,6 +841,7 @@
5F6FAC641D09E98000D5B4EA /* Logger.swift in Sources */,
5FF465BD1CE2AC4500F7ED8C /* Management.swift in Sources */,
5F06DDCA1CC66B710011842B /* Auth0.swift in Sources */,
5FD255B51D14DD2600387ECB /* ManagementError.swift in Sources */,
5FE2F8B31CCEAED8003628F4 /* Requestable.swift in Sources */,
5FCCC31A1CF51BBD00901E2E /* NSError+Management.swift in Sources */,
5FE2F8B61CCEB1C0003628F4 /* Handlers.swift in Sources */,
Expand Down
27 changes: 14 additions & 13 deletions Auth0/Authentication/Authentication.swift
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public struct Authentication {
- returns: authentication request that will yield Auth0 User Credentials
- seeAlso: Credentials
*/
public func login(username: String, password: String, connection: String, scope: String = "openid", parameters: [String: AnyObject] = [:]) -> Request<Credentials, Error> {
public func login(username: String, password: String, connection: String, scope: String = "openid", parameters: [String: AnyObject] = [:]) -> Request<Credentials, AuthenticationError> {
let resourceOwner = NSURL(string: "/oauth/ro", relativeToURL: self.url)!
var payload: [String: AnyObject] = [
"username": username,
Expand Down Expand Up @@ -154,7 +154,7 @@ public struct Authentication {

- returns: request that will yield a created database user (just email, username and email verified flag)
*/
public func createUser(email: String, username: String? = nil, password: String, connection: String, userMetadata: [String: AnyObject]? = nil) -> Request<DatabaseUser, Error> {
public func createUser(email: String, username: String? = nil, password: String, connection: String, userMetadata: [String: AnyObject]? = nil) -> Request<DatabaseUser, AuthenticationError> {
var payload: [String: AnyObject] = [
"email": email,
"password": password,
Expand Down Expand Up @@ -188,7 +188,7 @@ public struct Authentication {

- returns: request to reset password
*/
public func resetPassword(email: String, connection: String) -> Request<Void, Error> {
public func resetPassword(email: String, connection: String) -> Request<Void, AuthenticationError> {
let payload = [
"email": email,
"connection": connection,
Expand Down Expand Up @@ -245,9 +245,10 @@ public struct Authentication {

- returns: an authentication request that will yield Auth0 user credentials after creating the user.
*/
public func signUp(email: String, username: String? = nil, password: String, connection: String, userMetadata: [String: AnyObject]? = nil, scope: String = "openid", parameters: [String: AnyObject] = [:]) -> ConcatRequest<DatabaseUser, Credentials, Error> {
return createUser(email, username: username, password: password, connection: connection, userMetadata: userMetadata)
.concat(login(email, password: password, connection: connection, scope: scope, parameters: parameters))
public func signUp(email: String, username: String? = nil, password: String, connection: String, userMetadata: [String: AnyObject]? = nil, scope: String = "openid", parameters: [String: AnyObject] = [:]) -> ConcatRequest<DatabaseUser, Credentials, AuthenticationError> {
let first = createUser(email, username: username, password: password, connection: connection, userMetadata: userMetadata)
let second = login(email, password: password, connection: connection, scope: scope, parameters: parameters)
return ConcatRequest(first: first, second: second)
}

/**
Expand Down Expand Up @@ -276,7 +277,7 @@ public struct Authentication {

- returns: a request
*/
public func startPasswordless(email email: String, type: PasswordlessType = .Code, connection: String = "email", parameters: [String: AnyObject] = [:]) -> Request<Void, Authentication.Error> {
public func startPasswordless(email email: String, type: PasswordlessType = .Code, connection: String = "email", parameters: [String: AnyObject] = [:]) -> Request<Void, AuthenticationError> {
var payload: [String: AnyObject] = [
"email": email,
"connection": connection,
Expand Down Expand Up @@ -316,7 +317,7 @@ public struct Authentication {

- returns: a request
*/
public func startPasswordless(phoneNumber phoneNumber: String, type: PasswordlessType = .Code, connection: String = "sms") -> Request<Void, Authentication.Error> {
public func startPasswordless(phoneNumber phoneNumber: String, type: PasswordlessType = .Code, connection: String = "sms") -> Request<Void, AuthenticationError> {
let payload: [String: AnyObject] = [
"phone_number": phoneNumber,
"connection": connection,
Expand All @@ -341,7 +342,7 @@ public struct Authentication {

- returns: a request that will yield token information
*/
public func tokenInfo(token: String) -> Request<UserProfile, Authentication.Error> {
public func tokenInfo(token: String) -> Request<UserProfile, AuthenticationError> {
let payload: [String: AnyObject] = ["id_token": token]
let tokenInfo = NSURL(string: "/tokeninfo", relativeToURL: self.url)!
return Request(session: session, url: tokenInfo, method: "POST", handle: authenticationObject, payload: payload)
Expand All @@ -361,7 +362,7 @@ public struct Authentication {

- returns: a request that will yield user information
*/
public func userInfo(token: String) -> Request<UserProfile, Authentication.Error> {
public func userInfo(token: String) -> Request<UserProfile, AuthenticationError> {
let userInfo = NSURL(string: "/userinfo", relativeToURL: self.url)!
return Request(session: session, url: userInfo, method: "GET", handle: authenticationObject, headers: ["Authorization": "Bearer \(token)"])
}
Expand Down Expand Up @@ -392,7 +393,7 @@ public struct Authentication {

- returns: a request that will yield Auth0 user's credentials
*/
public func loginSocial(token: String, connection: String, scope: String = "openid", parameters: [String: AnyObject] = [:]) -> Request<Credentials, Error> {
public func loginSocial(token: String, connection: String, scope: String = "openid", parameters: [String: AnyObject] = [:]) -> Request<Credentials, AuthenticationError> {
var payload: [String: AnyObject] = [
"access_token": token,
"connection": connection,
Expand Down Expand Up @@ -420,7 +421,7 @@ public struct Authentication {
- returns: a request that will yield Auth0 user's credentials
- seeAlso: Authentication#exchangeCode(codeVerifier:redirectURI:) for PKCE
*/
public func token(parameters: [String: AnyObject]) -> Request<Credentials, Error> {
public func token(parameters: [String: AnyObject]) -> Request<Credentials, AuthenticationError> {
var payload: [String: AnyObject] = [
"client_id": self.clientId
]
Expand Down Expand Up @@ -448,7 +449,7 @@ public struct Authentication {
- returns: a request that will yield Auth0 user's credentials
- seeAlso: https://tools.ietf.org/html/rfc7636
*/
public func exchangeCode(code: String, codeVerifier: String, redirectURI: String) -> Request<Credentials, Error> {
public func exchangeCode(code: String, codeVerifier: String, redirectURI: String) -> Request<Credentials, AuthenticationError> {
return self.token([
"code": code,
"code_verifier": codeVerifier,
Expand Down
32 changes: 21 additions & 11 deletions Auth0/Authentication/AuthenticationError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,30 +22,33 @@

import Foundation

let UnknownCode = "a0.internal_error.unknown"
let NonJSONError = "a0.internal_error.plain"
let EmptyBodyError = "a0.internal_error.empty"

/**
* Represents an error during a request to Auth0 Authentication API
*/
public struct AuthenticationError: ErrorType, CustomStringConvertible {
public class AuthenticationError: ResponseError, CustomStringConvertible {

static let UnknownCode = "a0.internal_error.unknown"
static let NonJSONError = "a0.internal_error.plain"
static let EmptyBodyError = "a0.internal_error.empty"
static let Domain = "com.auth0.authentication"
static let UserInfoKey = "com.auth0.authentication.error.info"

/**
Additional information about the error
- seeAlso: `code` & `description` properties
*/
public let info: [String: AnyObject]

init(string: String? = nil, statusCode: Int = 0) {
self.init(info: [
"code": string != nil ? AuthenticationError.NonJSONError : AuthenticationError.EmptyBodyError,
public required init(string: String? = nil, statusCode: Int = 0) {
self.info = [
"code": string != nil ? NonJSONError : EmptyBodyError,
"description": string ?? "Empty response body",
"statusCode": statusCode
])
]
}

init(info: [String: AnyObject]) {
public required init(info: [String: AnyObject]) {
self.info = info
}

Expand All @@ -54,7 +57,7 @@ public struct AuthenticationError: ErrorType, CustomStringConvertible {
*/
public var code: String {
let code = self.info["error"] ?? self.info["code"]
return code as? String ?? AuthenticationError.UnknownCode
return code as? String ?? UnknownCode
}

/**
Expand All @@ -67,8 +70,15 @@ public struct AuthenticationError: ErrorType, CustomStringConvertible {
return string
}

guard self.code == AuthenticationError.UnknownCode else { return "Received error with code \(self.code)" }
guard self.code == UnknownCode else { return "Received error with code \(self.code)" }

return "Failed with unknown error \(self.info)"
}

public var foundationError: NSError {
return NSError(domain: AuthenticationError.Domain, code: 1, userInfo: [
NSLocalizedDescriptionKey: self.description,
AuthenticationError.UserInfoKey: self,
])
}
}
72 changes: 20 additions & 52 deletions Auth0/Authentication/Handlers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,71 +22,39 @@

import Foundation

func authenticationObject<T: JSONObjectPayload>(response: Response, callback: Request<T, Authentication.Error>.Callback) {
switch response.result {
case .Success(let payload):
if let dictionary = payload as? [String: AnyObject], let object = T(json: dictionary) {
func authenticationObject<T: JSONObjectPayload>(response: Response<AuthenticationError>, callback: Request<T, AuthenticationError>.Callback) {
do {
if let dictionary = try response.result() as? [String: AnyObject], let object = T(json: dictionary) {
callback(.Success(result: object))
} else {
callback(.Failure(error: .InvalidResponse(response: response.data)))
callback(.Failure(error: AuthenticationError(string: string(response.data))))
}
case .Failure(let cause):
callback(.Failure(error: authenticationError(response.data, cause: cause)))

} catch let error {
callback(.Failure(error: error))
}
}

func databaseUser(response: Response, callback: Request<DatabaseUser, Authentication.Error>.Callback) {
switch response.result {
case .Success(let payload):
if let dictionary = payload as? [String: AnyObject], let email = dictionary["email"] as? String {
func databaseUser(response: Response<AuthenticationError>, callback: Request<DatabaseUser, AuthenticationError>.Callback) {
do {
if let dictionary = try response.result() as? [String: AnyObject], let email = dictionary["email"] as? String {
let username = dictionary["username"] as? String
let verified = dictionary["email_verified"] as? Bool ?? false
callback(.Success(result: (email: email, username: username, verified: verified)))
} else {
callback(.Failure(error: .InvalidResponse(response: response.data)))
callback(.Failure(error: AuthenticationError(string: string(response.data))))
}
case .Failure(let cause):
callback(.Failure(error: authenticationError(response.data, cause: cause)))
}
}

func noBody(response: Response, callback: Request<Void, Authentication.Error>.Callback) {
switch response.result {
case .Success:
callback(.Success(result: ()))
case .Failure(let cause):
callback(.Failure(error: authenticationError(response.data, cause: cause)))
}
}

private func authenticationError(data: NSData?, cause: Response.Error) -> Authentication.Error {
switch cause {
case .InvalidJSON(let data):
return .InvalidResponse(response: data)
case .ServerError(let status, let data) where (400...500).contains(status) && data != nil:
if
let json = try? NSJSONSerialization.JSONObjectWithData(data!, options: []),
let payload = json as? [String: AnyObject] {
return payloadError(payload, cause: cause)
} else {
return .RequestFailed(cause: cause)
}
default:
return .RequestFailed(cause: cause)
} catch let error {
callback(.Failure(error: error))
}
}

private func payloadError(payload: [String: AnyObject], cause: ErrorType) -> Authentication.Error {
if let code = payload["error"] as? String, let description = payload["error_description"] as? String {
return .Response(code: code, description: description, name: nil, extras: nil)
}

if let code = payload["code"] as? String, let description = payload["description"] as? String {
let name = payload["name"] as? String
var extras = payload
["code", "description", "name"].forEach { extras.removeValueForKey($0) }
return .Response(code: code, description: description, name: name, extras: extras)
func noBody(response: Response<AuthenticationError>, callback: Request<Void, AuthenticationError>.Callback) {
do {
let _ = try response.result()
callback(.Success(result: ()))
} catch let error {
callback(.Failure(error: error))
}

return .RequestFailed(cause: cause)
}
}
Loading