mirror of
https://github.com/home-assistant/iOS.git
synced 2026-02-21 13:24:03 -06:00
<!-- Thank you for submitting a Pull Request and helping to improve Home Assistant. Please complete the following sections to help the processing and review of your changes. Please do not delete anything from this template. --> ## Summary <!-- Provide a brief summary of the changes you have made and most importantly what they aim to achieve --> To avoid using internal URL out of local network, this PR makes "activeURL" optional, and it will not use internalURL when out of local network. Tested the internal/external logic on: - iPhone - iPad - Mac - Watch - Shortcuts - Notifications - Widgets For VPN users, they have to set external URL the same as internal URL to have their setup working. Pending: - [x] Verify all edge cases where "guard let" were added - [ ] Enforce SSID to use internal URL in the App Next possible iteration: - Add noise protocol between app and server to make http connections secure ## Screenshots <!-- If this is a user-facing change not in the frontend, please include screenshots in light and dark mode. --> <img width="1154" alt="Screenshot 2024-05-13 at 11 46 47" src="https://github.com/home-assistant/iOS/assets/5808343/7ea634cc-382b-49c2-ab64-a218f996452e"> ## Link to pull request in Documentation repository <!-- Pull requests that add, change or remove functionality must have a corresponding pull request in the Companion App Documentation repository (https://github.com/home-assistant/companion.home-assistant). Please add the number of this pull request after the "#" --> Documentation: home-assistant/companion.home-assistant# ## Any other notes <!-- If there is any other information of note, like if this Pull Request is part of a bigger change, please include it here. -->
141 lines
4.8 KiB
Swift
141 lines
4.8 KiB
Swift
import Alamofire
|
|
import Foundation
|
|
import ObjectMapper
|
|
import PromiseKit
|
|
|
|
typealias URLRequestConvertible = Alamofire.URLRequestConvertible
|
|
|
|
public enum ServerConnectionError: Error {
|
|
case noActiveURL
|
|
}
|
|
|
|
public class AuthenticationAPI {
|
|
public enum AuthenticationError: LocalizedError {
|
|
case serverError(statusCode: Int, errorCode: String?, error: String?)
|
|
|
|
public var errorDescription: String? {
|
|
switch self {
|
|
case let .serverError(statusCode: statusCode, errorCode: errorCode, error: error):
|
|
return [String(describing: statusCode), errorCode, error].compactMap { $0 }.joined(separator: ", ")
|
|
}
|
|
}
|
|
}
|
|
|
|
let server: Server
|
|
let session: Session
|
|
|
|
init(server: Server) {
|
|
self.server = server
|
|
self.session = Session(serverTrustManager: CustomServerTrustManager(server: server))
|
|
}
|
|
|
|
public func refreshTokenWith(tokenInfo: TokenInfo) -> Promise<TokenInfo> {
|
|
Promise { seal in
|
|
guard let activeUrl = server.info.connection.activeURL() else {
|
|
seal.reject(ServerConnectionError.noActiveURL)
|
|
return
|
|
}
|
|
let token = tokenInfo.refreshToken
|
|
let routeInfo = RouteInfo(
|
|
route: AuthenticationRoute.refreshToken(token: token),
|
|
baseURL: activeUrl
|
|
)
|
|
let request = session.request(routeInfo)
|
|
|
|
let context = TokenInfo.TokenInfoContext(oldTokenInfo: tokenInfo)
|
|
request.validateAuth().responseObject(context: context) { (response: DataResponse<TokenInfo, AFError>) in
|
|
switch response.result {
|
|
case let .failure(error):
|
|
seal.reject(error)
|
|
case let .success(value):
|
|
seal.fulfill(value)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
public func revokeToken(tokenInfo: TokenInfo) -> Promise<Bool> {
|
|
Promise { seal in
|
|
guard let activeUrl = server.info.connection.activeURL() else {
|
|
seal.reject(ServerConnectionError.noActiveURL)
|
|
return
|
|
}
|
|
let token = tokenInfo.accessToken
|
|
let routeInfo = RouteInfo(
|
|
route: AuthenticationRoute.revokeToken(token: token),
|
|
baseURL: activeUrl
|
|
)
|
|
let request = session.request(routeInfo)
|
|
|
|
request.validateAuth().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)
|
|
}
|
|
}
|
|
}
|
|
|
|
public static func fetchToken(
|
|
authorizationCode: String,
|
|
baseURL: URL,
|
|
exceptions: SecurityExceptions
|
|
) -> Promise<TokenInfo> {
|
|
let session = Session(serverTrustManager: CustomServerTrustManager(exceptions: exceptions))
|
|
|
|
return Promise { seal in
|
|
let routeInfo = RouteInfo(
|
|
route: AuthenticationRoute.token(authorizationCode: authorizationCode),
|
|
baseURL: baseURL
|
|
)
|
|
let request = session.request(routeInfo)
|
|
|
|
request.validateAuth().responseObject { (dataresponse: DataResponse<TokenInfo, AFError>) in
|
|
switch dataresponse.result {
|
|
case let .failure(error):
|
|
seal.reject(error)
|
|
case let .success(value):
|
|
seal.fulfill(value)
|
|
}
|
|
}
|
|
}.ensure {
|
|
withExtendedLifetime(session) {
|
|
// keeping session around until we're done
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
extension DataRequest {
|
|
@discardableResult
|
|
func validateAuth() -> Self {
|
|
validate { _, response, data in
|
|
if case 200 ..< 300 = response.statusCode {
|
|
return .success(())
|
|
} else if let data {
|
|
let errorCode: String?
|
|
let error: String?
|
|
|
|
if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
|
|
errorCode = json["error"] as? String
|
|
error = json["error_description"] as? String
|
|
} else {
|
|
errorCode = nil
|
|
error = String(data: data, encoding: .utf8)
|
|
}
|
|
|
|
return .failure(AuthenticationAPI.AuthenticationError.serverError(
|
|
statusCode: response.statusCode,
|
|
errorCode: errorCode,
|
|
error: error
|
|
))
|
|
} else {
|
|
return .failure(AFError.responseValidationFailed(
|
|
reason: .unacceptableStatusCode(code: response.statusCode)
|
|
))
|
|
}
|
|
}
|
|
}
|
|
}
|