100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
iOS console : switched to AppAuth instead of AeroGear
William Balcaen40f683775a96
diff --git a/console/iOS/CustomURLProtocol.swift b/console/iOS/CustomURLProtocol.swiftdeleted file mode 100644index 7a01502f7..000000000--- a/console/iOS/CustomURLProtocol.swift+++ /dev/null@@ -1,88 +0,0 @@-//-// CustomURLProtocol.swift-// console-//-// Created by William Balcaen on 16/02/17.-// Copyright © 2017 TInSys. All rights reserved.-//--import Foundation-class CustomURLProtocol: URLProtocol, URLSessionDataDelegate, URLSessionTaskDelegate {- private var dataTask: URLSessionDataTask?- private var urlResponse: URLResponse?- private var receivedData: NSMutableData?- public static var accessToken : String?- class var CustomHeaderSet: String {- return "CustomHeaderSet"- }-- // MARK: NSURLProtocol-- override class func canInit(with request: URLRequest) -> Bool {- guard let host = request.url?.host, host == Server.hostURL else {- return false- }- if (URLProtocol.property(forKey: CustomURLProtocol.CustomHeaderSet, in: request as URLRequest) != nil) {- return false- }-- return true- }-- override class func canonicalRequest(for request: URLRequest) -> URLRequest {- return request- }-- override func startLoading() {-- let mutableRequest = NSMutableURLRequest.init(url: self.request.url!, cachePolicy: NSURLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 240.0)-- //Add Custom headers-- mutableRequest.setValue(String(format: "Bearer %@",CustomURLProtocol.accessToken!), forHTTPHeaderField: "Authorization")- mutableRequest.setValue("master", forHTTPHeaderField: "Auth-Realm")- URLProtocol.setProperty("true", forKey: CustomURLProtocol.CustomHeaderSet, in: mutableRequest)- let defaultConfigObj = URLSessionConfiguration.default- let defaultSession = URLSession(configuration: defaultConfigObj, delegate: self, delegateQueue: nil)- self.dataTask = defaultSession.dataTask(with: mutableRequest as URLRequest)- self.dataTask!.resume()-- }-- override func stopLoading() {- self.dataTask?.cancel()- self.dataTask = nil- self.receivedData = nil- self.urlResponse = nil- }-- // MARK: NSURLSessionDataDelegate-- func urlSession(_ session: URLSession, dataTask: URLSessionDataTask,- didReceive response: URLResponse,- completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {-- self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)-- self.urlResponse = response- self.receivedData = NSMutableData()-- completionHandler(.allow)- }-- func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {- self.client?.urlProtocol(self, didLoad: data as Data)-- self.receivedData?.append(data as Data)- }-- // MARK: NSURLSessionTaskDelegate-- func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {- if error != nil {- self.client?.urlProtocol(self, didFailWithError: error!)- } else {- self.client?.urlProtocolDidFinishLoading(self)- }- }-}diff --git a/console/iOS/console.xcodeproj/project.pbxproj b/console/iOS/console.xcodeproj/project.pbxprojindex 17290cc99..a67ccea66 100644--- a/console/iOS/console.xcodeproj/project.pbxproj+++ b/console/iOS/console.xcodeproj/project.pbxproj@@ -14,7 +14,6 @@FA1D73E91E53374E00F6240A /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = FA1D73E81E53374E00F6240A /* Assets.xcassets */; };FA1D73EC1E53374E00F6240A /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = FA1D73EA1E53374E00F6240A /* LaunchScreen.storyboard */; };FA1D73F61E53392F00F6240A /* ORViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA1D73F51E53392F00F6240A /* ORViewController.swift */; };- FA2D482F1E55F8F300C95665 /* CustomURLProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA2D482E1E55F8F300C95665 /* CustomURLProtocol.swift */; };FA2D48311E560B7500C95665 /* Constants.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA2D48301E560B7500C95665 /* Constants.swift */; };/* End PBXBuildFile section */@@ -30,7 +29,6 @@FA1D73EB1E53374E00F6240A /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };FA1D73ED1E53374E00F6240A /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };FA1D73F51E53392F00F6240A /* ORViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ORViewController.swift; sourceTree = "<group>"; };- FA2D482E1E55F8F300C95665 /* CustomURLProtocol.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = CustomURLProtocol.swift; path = ../CustomURLProtocol.swift; sourceTree = "<group>"; };FA2D48301E560B7500C95665 /* Constants.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Constants.swift; sourceTree = "<group>"; };/* End PBXFileReference section */@@ -100,7 +98,6 @@FA2D48291E55D9F600C95665 /* utils */ = {isa = PBXGroup;children = (- FA2D482E1E55F8F300C95665 /* CustomURLProtocol.swift */,);name = utils;sourceTree = "<group>";@@ -231,7 +228,6 @@files = (FA2D48311E560B7500C95665 /* Constants.swift in Sources */,FA1D73E41E53374E00F6240A /* ViewController.swift in Sources */,- FA2D482F1E55F8F300C95665 /* CustomURLProtocol.swift in Sources */,FA1D73F61E53392F00F6240A /* ORViewController.swift in Sources */,FA1D73E21E53374E00F6240A /* AppDelegate.swift in Sources */,);diff --git a/console/iOS/console/AppDelegate.swift b/console/iOS/console/AppDelegate.swiftindex 2dc7923cb..779e11d60 100644--- a/console/iOS/console/AppDelegate.swift+++ b/console/iOS/console/AppDelegate.swift@@ -7,13 +7,13 @@//import UIKit-import AeroGearOAuth2+import AppAuth@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate {var window: UIWindow?-+ var currentAuthorizationFlow : OIDAuthorizationFlowSession?func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {// allows to catch all request and add custom headers (works only with UIWebView not WKWebView).@@ -43,9 +43,11 @@ class AppDelegate: UIResponder, UIApplicationDelegate {}func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {- let notification = Notification(name: Notification.Name(rawValue: AGAppLaunchedWithURLNotification), object:nil, userInfo:[UIApplicationLaunchOptionsKey.url:url])- NotificationCenter.default.post(notification)- return true+ if (self.currentAuthorizationFlow?.resumeAuthorizationFlow(with: url))! {+ self.currentAuthorizationFlow = nil+ return true+ }+ return false}}diff --git a/console/iOS/console/Constants.swift b/console/iOS/console/Constants.swiftindex 82d4774fe..833fa1c48 100644--- a/console/iOS/console/Constants.swift+++ b/console/iOS/console/Constants.swift@@ -11,8 +11,9 @@ import Foundationstruct Server {static let hostURL = "192.168.99.100"static let port = "8080"- static let initialPath = "console/index.html"+ static let initialPath = "console/master/index.html"static let realm = "master"+ static let apiTestResource = "http://192.168.99.100:8080/master/asset"}struct Client {diff --git a/console/iOS/console/Info.plist b/console/iOS/console/Info.plistindex e75960e3f..298adf827 100644--- a/console/iOS/console/Info.plist+++ b/console/iOS/console/Info.plist@@ -31,6 +31,8 @@<string>1</string><key>LSRequiresIPhoneOS</key><true/>+ <key>NSPhotoLibraryUsageDescription</key>+ <string>$(PRODUCT_NAME) photo use</string><key>UILaunchStoryboardName</key><string>LaunchScreen</string><key>UIMainStoryboardFile</key>@@ -52,7 +54,5 @@<string>UIInterfaceOrientationLandscapeLeft</string><string>UIInterfaceOrientationLandscapeRight</string></array>- <key>NSPhotoLibraryUsageDescription</key>- <string>$(PRODUCT_NAME) photo use</string></dict></plist>diff --git a/console/iOS/console/ORViewController.swift b/console/iOS/console/ORViewController.swiftindex 52dfb7867..067ddceda 100644--- a/console/iOS/console/ORViewController.swift+++ b/console/iOS/console/ORViewController.swift@@ -12,20 +12,16 @@ import WebKitclass ORViewcontroller : UIViewController, URLSessionDelegate {- var accessToken : String = ""+ var data : Data?override func viewDidLoad() {super.viewDidLoad()-- CustomURLProtocol.accessToken = accessTokenlet myWebView = UIWebView(frame: view.frame)view.addSubview(myWebView)- let url = URL(string:String(format:"http://%@:%@/%@",Server.hostURL,Server.port,Server.initialPath))- let request = URLRequest(url: url!)myWebView.scalesPageToFit = true- myWebView.loadRequest(request)+ myWebView.load(self.data!, mimeType: "text/html", textEncodingName: "UTF-8", baseURL: URL(string: "http://192.168.99.100:8080/")!)}}diff --git a/console/iOS/console/ViewController.swift b/console/iOS/console/ViewController.swiftindex 68e534176..61303de20 100644--- a/console/iOS/console/ViewController.swift+++ b/console/iOS/console/ViewController.swift@@ -7,11 +7,10 @@//import UIKit-import AeroGearOAuth2-import AeroGearHttp+import AppAuthclass ViewController: UIViewController {-+ var authState : OIDAuthState?@IBOutlet weak var loginViewController: UIWebView!override func viewDidLoad() {super.viewDidLoad()@@ -24,43 +23,49 @@ class ViewController: UIViewController {}@IBAction func showLoginPage(_ sender: Any) {- let http = Http()- let keycloakConfig = KeycloakConfig(- clientId: Client.clientId,- host: String(format:"http://%@:%@",Server.hostURL,Server.port),- realm: Server.realm,- isOpenIDConnect: true)- keycloakConfig.isWebView = true- let oauth2Module = AccountManager.addAccountWith(config: keycloakConfig, moduleClass: OAuth2Module.self)- http.authzModule = oauth2Module- http.authzModule = oauth2Module- requestAccess(oauth2Module: oauth2Module)+ let authorizationEndoint = URL(string: String(format:"http://%@:%@/auth/realms/%@/protocol/openid-connect/auth",Server.hostURL,Server.port,Server.realm))+ let tokenEndpoint = URL(string: String(format:"http://%@:%@/auth/realms/%@/protocol/openid-connect/token",Server.hostURL,Server.port,Server.realm))+ let configuration = OIDServiceConfiguration(authorizationEndpoint: authorizationEndoint!, tokenEndpoint: tokenEndpoint!)+ let authRequest = OIDAuthorizationRequest(configuration: configuration, clientId: Client.clientId, scopes: ["offline_access"], redirectURL: URL(string:String(format:"%@://oauth2Callback",Bundle.main.bundleIdentifier!))!, responseType: OIDResponseTypeCode, additionalParameters: nil)+ let appDelegate :AppDelegate = UIApplication.shared.delegate as! AppDelegate- }-- func requestAccess(oauth2Module : OAuth2Module) {- oauth2Module.requestAccess { (response, error) in- var token : String- if response != nil {- token = response! as! String- URLProtocol.registerClass(CustomURLProtocol.self)- let orVC = ORViewcontroller()- orVC.accessToken = token-- self.navigationController?.pushViewController(orVC, animated: true)- } else if error != nil {- let alertVC = UIAlertController(title: "Error", message: error.debugDescription, preferredStyle: UIAlertControllerStyle.actionSheet)- let defaultAction = UIAlertAction(title: "Retry", style: .default, handler: { (alertAction) in- oauth2Module.requestAuthorizationCode(completionHandler: { (_, error) in- self.requestAccess(oauth2Module: oauth2Module)- })+ appDelegate.currentAuthorizationFlow = OIDAuthState.authState(byPresenting: authRequest, presenting: self, callback: { (state, error) in+ if (error != nil) {+ self.showError(error: error!)+ } else {+ self.authState = state+ self.authState?.performAction(freshTokens: { (accessToken, idToken, error) in+ if (error != nil) {+ self.showError(error: error!)+ } else {+ guard let urlRequest = URL(string: Server.apiTestResource) else { return }+ let request = NSMutableURLRequest(url: urlRequest)+ request.addValue(String(format:"Bearer %@", accessToken!), forHTTPHeaderField: "Authorization")+ let sessionConfiguration = URLSessionConfiguration.default+ let session = URLSession(configuration: sessionConfiguration)+ let reqDataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in+ DispatchQueue.main.async {+ if (error != nil) {+ self.showError(error: error!)+ } else {+ let orVC = ORViewcontroller()+ orVC.data = data+ self.navigationController?.pushViewController(orVC, animated: true)+ }+ }+ })+ reqDataTask.resume()+ }})- alertVC.addAction(defaultAction)-- self.present(alertVC, animated: true, completion: nil)}- }+ })}++ func showError(error : Error) {+ let alertVC = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: UIAlertControllerStyle.actionSheet)+ self.present(alertVC, animated: true, completion: nil)+ }+}diff --git a/console/iOS/podfile b/console/iOS/podfileindex 2e21725b0..e15c81427 100644--- a/console/iOS/podfile+++ b/console/iOS/podfile@@ -1,4 +1,4 @@target 'console' douse_frameworks!-pod 'AeroGearOAuth2'+pod 'AppAuth'end