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

Missing errorcodes #99

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
6 changes: 4 additions & 2 deletions Sources/ImperialCore/Errors/ImperialError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,19 @@ public enum ImperialError: Error, CustomStringConvertible {
/// no JSON in the response from the the request to `dataUri`.
case missingJSONFromResponse(String)



/// Thrown when `request.fetch` is called with a type that has not been run through `request.create`.
case typeNotInitialized(String)

/// Thrown when `code` is missing from within the authentication URL query
case missingCodeKey

/// A human readable version of the error thrown.
public var description: String {
switch self {
case let .missingEnvVar(variable): return "Missing enviroment variable '\(variable)'"
case let .missingJSONFromResponse(uri): return "Reponse returned from '\(uri)' does not contain JSON"
case let .typeNotInitialized(type): return "No instence of type '\(type)' has been created"
case .missingCodeKey: return "Missing 'code' key in URL query"
}
}
}
34 changes: 34 additions & 0 deletions Sources/ImperialCore/Errors/SessionError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import Vapor

/// Represents an error that occurs during a session action.
public enum SessionError: Error, CustomStringConvertible, AbortError {

/// Thrown when the user's access token is not found within the session's data
case usernotAuthenticated

/// Throws Errors when no object is stored in the session with the given key, or decoding fails.
case keynotFound(String)

public var description: String {
switch self {
case .usernotAuthenticated: return "User currently not authenticated"
case let .keynotFound(key): return "No element has been found with the key '\(key)'"
}
}

public var reason: String {
switch self {
case .usernotAuthenticated: return description
case .keynotFound: return description
}
}


public var status: HTTPStatus {
switch self {
case .usernotAuthenticated: return .unauthorized
case .keynotFound: return .internalServerError
}
}

}
13 changes: 7 additions & 6 deletions Sources/ImperialCore/Helpers/Sessions+Imperial.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ extension Session {
/// - Returns: The access token stored with the `access_token` key.
/// - Throws: `Abort.unauthorized` if no access token exists.
public func accessToken() throws -> String {
let notauthenticatedError = SessionError.usernotAuthenticated
guard let token = try? get(Keys.token, as: String.self) else {
throw Abort(.unauthorized, reason: "User currently not authenticated")
}
throw notauthenticatedError }
return token
}

Expand All @@ -54,10 +54,10 @@ extension Session {
/// - Returns: The refresh token stored with the `refresh_token` key.
/// - Throws: `Abort.unauthorized` if no refresh token exists.
public func refreshToken()throws -> String {
let notauthenticatedError = SessionError.usernotAuthenticated
guard let token = self.data[Keys.refresh] else {
if self.data[Keys.token] == nil {
throw Abort(.unauthorized, reason: "User currently not authenticated")
} else {
if self.data[Keys.token] == nil { throw notauthenticatedError }
else {
let oauthData = self.data["access_token_service"]?.data(using: .utf8) ?? Data()
let oauth = try? JSONSerialization.jsonObject(with: oauthData, options: [])
let oauthName = (oauth as? NSDictionary)?["name"] ?? "???"
Expand All @@ -82,9 +82,10 @@ extension Session {
/// - Returns: The JSON from the session, decoded to the type passed in.
/// - Throws: Errors when no object is stored in the session with the given key, or decoding fails.
public func get<T>(_ key: String, as type: T.Type) throws -> T where T: Codable {
let keynotfoundError = SessionError.keynotFound(key)
guard let stored = data[key] else {
if _isOptional(T.self) { return Optional<Void>.none as! T }
throw Abort(.internalServerError, reason: "No element found in session with ket '\(key)'")
throw keynotfoundError
}
return try JSONDecoder().decode(T.self, from: Data(stored.utf8))
}
Expand Down
6 changes: 3 additions & 3 deletions Sources/ImperialCore/Routing/FederatedServiceRouter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -92,13 +92,13 @@ extension FederatedServiceRouter {

public func fetchToken(from request: Request) throws -> EventLoopFuture<String> {
let code: String
let codeError = ImperialError.missingCodeKey

if let queryCode: String = try request.query.get(at: codeKey) {
code = queryCode
} else if let error: String = try request.query.get(at: errorKey) {
throw Abort(.badRequest, reason: error)
} else {
throw Abort(.badRequest, reason: "Missing 'code' key in URL query")
}
} else { throw codeError }

let body = callbackBody(with: code)
let url = URI(string: accessTokenURL)
Expand Down
Loading