Files
iOS/Sources/Shared/API/Authentication/AuthenticationAPI.swift
Zac West c1fac47cdd Update to Alamofire 5.x (#1364)
Fixes #1300.

## Summary
Updates Alamofire to 5.x and updates how we do authentication adapting and failure retrying.

## Screenshots
n/a

## Link to pull request in Documentation repository
n/a

## Any other notes
- Switches to using `AuthenticationInterceptor` to handle authenticated requests. This has a lot of good things: it's heavily tested, it only executes the refresh one at a time, and it has explicit handling of "this request failed with an _old_ access token" which is the root cause of some logouts in #1300.
- Switches from manually doing retries and backoffs to using `RetryPolicy` which also adds in retries for 5xx errors in addition to all of the URLError-specific logic that it has.
- Updates the apparently-copied-from-`AlamofireObjectMapper` repository for 5.x and removes some old Sodium-based handling that is now part of the Webhook flow, which is separate from Alamofire.
2021-01-10 15:42:16 -08:00

114 lines
4.4 KiB
Swift

//
// AuthenticationAPI.swift
// Shared
//
// Created by Stephan Vanterpool on 7/21/18.
// Copyright © 2018 Robbie Trencheny. All rights reserved.
//
import PromiseKit
import Alamofire
import Foundation
import ObjectMapper
typealias URLRequestConvertible = Alamofire.URLRequestConvertible
public class AuthenticationAPI {
public enum AuthenticationError: Error {
case unexepectedType
case unexpectedResponse
case invalidCode
case noConnectionInfo
}
private let forcedConnectionInfo: ConnectionInfo?
init(forcedConnectionInfo: ConnectionInfo? = nil) {
self.forcedConnectionInfo = forcedConnectionInfo
}
private func activeURL() throws -> URL {
if let forcedConnectionInfo = forcedConnectionInfo {
return forcedConnectionInfo.activeURL
} else if let url = Current.settingsStore.connectionInfo?.activeURL {
return url
} else {
throw AuthenticationError.noConnectionInfo
}
}
public func refreshTokenWith(tokenInfo: TokenInfo) -> Promise<TokenInfo> {
return Promise { seal in
let token = tokenInfo.refreshToken
let routeInfo = RouteInfo(route: AuthenticationRoute.refreshToken(token: token),
baseURL: try activeURL())
let request = Session.default.request(routeInfo)
let context = TokenInfo.TokenInfoContext(oldTokenInfo: tokenInfo)
request.validate().responseObject(context: context) { (dataresponse: DataResponse<TokenInfo, AFError>) in
switch dataresponse.result {
case .failure(let error):
seal.reject(error)
case .success(let value):
seal.fulfill(value)
}
return
}
}
}
public func revokeToken(tokenInfo: TokenInfo) -> Promise<Bool> {
return Promise { seal in
let token = tokenInfo.accessToken
let routeInfo = RouteInfo(route: AuthenticationRoute.revokeToken(token: token),
baseURL: try activeURL())
let request = Session.default.request(routeInfo)
request.validate().response { _ in
// https://developers.home-assistant.io/docs/en/auth_api.html#revoking-a-refresh-token says:
//
// The request will always respond with an empty body and HTTP status 200,
// regardless if the request was successful.
seal.fulfill(true)
return
}
}
}
public func fetchTokenWithCode(_ authorizationCode: String) -> Promise<TokenInfo> {
return Promise { seal in
let routeInfo = RouteInfo(route: AuthenticationRoute.token(authorizationCode: authorizationCode),
baseURL: try activeURL())
let request = Session.default.request(routeInfo)
request.validate().responseObject { (dataresponse: DataResponse<TokenInfo, AFError>) in
switch dataresponse.result {
case .failure(let networkError):
guard case let AFError.responseValidationFailed(reason: reason) = networkError,
case let AFError.ResponseValidationFailureReason.unacceptableStatusCode(code: code)
= reason, code == 400, let errorData = dataresponse.data else {
seal.reject(networkError)
return
}
do {
let jsonObject = try JSONSerialization.jsonObject(with: errorData,
options: .allowFragments)
if let errorDictionary = jsonObject as? [String: AnyObject],
let errorString = errorDictionary["error_description"] as? String,
errorString == "Invalid code" {
seal.reject(AuthenticationError.invalidCode)
return
}
} catch {
Current.Log.error("Error deserializing failure json response: \(error)")
}
case .success(let value):
seal.fulfill(value)
}
return
}
}
}
}