Skip to content

Commit

Permalink
Merge pull request #54 from microtherion/Refresh_Token_L1
Browse files Browse the repository at this point in the history
Minimal refresh token support
  • Loading branch information
calebkleveter authored Apr 6, 2020
2 parents da16ef0 + 6c496cc commit 5b318a4
Showing 1 changed file with 38 additions and 2 deletions.
40 changes: 38 additions & 2 deletions Sources/Imperial/Helpers/Sessions+Imperial.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,30 @@ extension Request {
public func accessToken()throws -> String {
return try self.session().accessToken()
}

/// Gets the refresh token from the current session.
///
/// - Returns: The refresh token in the current session.
/// - Throws:
/// - `Abort.unauthorized` if no refresh token exists.
/// - `SessionsError.notConfigured` if session middlware is not configured yet.
public func refreshToken()throws -> String {
return try self.session().refreshToken()
}
}

extension Session {

/// Keys used to store and retrieve items from the session
enum Keys {
static let token = "access_token"
static let refresh = "refresh_token"
}

/// Gets the access token from the session.
///
/// - Returns: The access token stored with the `access_token` key.
/// - Throws: `Abort.unauthorized` if no access token exists.m
/// - Throws: `Abort.unauthorized` if no access token exists.
public func accessToken()throws -> String {
guard let token = self[Keys.token] else {
throw Abort(.unauthorized, reason: "User currently not authenticated")
Expand All @@ -38,7 +49,32 @@ extension Session {
public func setAccessToken(_ token: String) {
self[Keys.token] = token
}


/// Gets the refresh token from the session.
///
/// - Returns: The refresh token stored with the `refresh_token` key.
/// - Throws: `Abort.unauthorized` if no refresh token exists.
public func refreshToken()throws -> String {
guard let token = self[Keys.refresh] else {
if self[Keys.token] == nil {
throw Abort(.unauthorized, reason: "User currently not authenticated")
} else {
let oauthData = self["access_token_service"]?.data(using: .utf8) ?? Data()
let oauth = try? JSONSerialization.jsonObject(with: oauthData, options: [])
let oauthName = (oauth as? NSDictionary)?["name"] ?? "???"
throw Abort(.methodNotAllowed, reason: "OAuth provider '\(oauthName)' uses no refresh tokens")
}
}
return token
}

/// Sets the refresh token on the session.
///
/// - Parameter token: the refresh token to store on the session
public func setRefreshToken(_ token: String) {
self[Keys.refresh] = token
}

/// Gets an object stored in a session with JSON as a given type.
///
/// - Parameters:
Expand Down

0 comments on commit 5b318a4

Please sign in to comment.