Skip to content

Commit

Permalink
Merge pull request #45 from Cidaas/development
Browse files Browse the repository at this point in the history
Development
  • Loading branch information
cidaas-samples authored Dec 12, 2018
2 parents 3007176 + dbe6207 commit 5695c76
Show file tree
Hide file tree
Showing 11 changed files with 375 additions and 49 deletions.
2 changes: 1 addition & 1 deletion Cidaas.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

Pod::Spec.new do |s|
s.name = 'Cidaas'
s.version = '1.1.0'
s.version = '1.1.0.1'
s.summary = 'Native SDK for iOS providing login, registration and verification functionalities'
s.homepage = 'https://github.com/Cidaas/cidaas-sdk-ios-v2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class LoginController {

// shared instance
public static var shared : LoginController = LoginController()
public var delegate: UIViewController = UIViewController()
public var delegate: UIViewController!
public var storage: TransactionStore = TransactionStore.shared

// constructor
Expand All @@ -36,8 +36,6 @@ public class LoginController {
return
}

self.delegate = delegate

// construct url
let loginURL = constructURL(properties: properties)
let redirectURL = URL(string: properties["RedirectURL"] ?? "")!
Expand All @@ -51,25 +49,57 @@ public class LoginController {
self.storage.store(session)
}
else {

self.delegate = delegate
// call open safari method
openSafari(loginURL : loginURL)
}
}

// login With social
public func loginWithSocial(provider: String, requestId: String, delegate: UIViewController, properties: Dictionary<String, String>, callback: @escaping(Result<LoginResponseEntity>) -> Void) {
// null check
if properties["DomainURL"] == "" || properties["DomainURL"] == nil || properties["ClientId"] == "" || properties["ClientId"] == nil || properties["RedirectURL"] == "" || properties["RedirectURL"] == nil {
let error = WebAuthError.shared.propertyMissingException()
// log error
let loggerMessage = "Read properties failure : " + "Error Code - " + String(describing: error.errorCode) + ", Error Message - " + error.errorMessage + ", Status Code - " + String(describing: error.statusCode)
logw(loggerMessage, cname: "cidaas-sdk-error-log")

DispatchQueue.main.async {
callback(Result.failure(error: error))
}
return
}

// construct url
let loginURL = constructSocialURL(provider: provider, requestId: requestId, properties: properties)
let redirectURL = URL(string: properties["RedirectURL"] ?? "")!

if #available(iOS 11.0, *) {

// initiate safari session with the constructed url performing single sign on
let session = SafariAuthenticationSession(loginURL: loginURL, redirectURL: redirectURL, callback: callback)

// save the session
self.storage.store(session)
}
else {
self.delegate = delegate
// call open safari method
openSafari(loginURL : loginURL)
}
}

// open safari browser. This method opens the Safari browser to display the login page. This method should be called internally and only for lower versions of ios (below 11.0)
private func openSafari(loginURL : URL) {

// assign url to safari controller
let vc = SFSafariViewController(url: loginURL)

// present the safari controller
self.delegate.present(vc, animated: true, completion: nil)
}

private func constructURL(properties: Dictionary<String, String>) -> URL {
public func constructURL(properties: Dictionary<String, String>) -> URL {

var urlParams = Dictionary<String, String>()
urlParams["redirect_uri"] = properties["RedirectURL"] ?? ""
Expand All @@ -78,13 +108,31 @@ public class LoginController {
urlParams["view_type"] = properties["ViewType"] ?? "login"
urlParams["code_challenge"] = properties["Challenge"]
urlParams["code_challenge_method"] = properties["Method"]
urlParams["nonce"] = UUID.init().uuidString

var urlComponents = URLComponents(string : properties["AuthorizationURL"] ?? "")
urlComponents?.queryItems = []

for (key, value) in urlParams {
urlComponents?.queryItems?.append(URLQueryItem(name: key, value: value))
}

for(key, value) in Cidaas.shared.extraParams {
urlComponents?.queryItems?.append(URLQueryItem(name: key, value: value))
}

return (urlComponents?.url)!
}

public func constructSocialURL(provider: String, requestId: String, properties: Dictionary<String, String>) -> URL {

let baseURL = (properties["DomainURL"]) ?? ""

// construct url
let urlString = baseURL + URLHelper.shared.getSocialLoginURL(provider: provider, requestId: requestId)

let urlComponents = URLComponents(string : urlString)

return (urlComponents?.url)!
}

Expand Down
5 changes: 5 additions & 0 deletions Cidaas/Classes/Core/Helpers/General/URLHelper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ public class URLHelper {
public var denyRequestURL = "/verification-srv/notification/reject"
public var updateFCMTokenURL = "/devices-srv/device/updatefcm"
public var pendingNotificationListURL = "/verification-srv/notification/initiated"
public var socialLoginURL = "/login-srv/social/login/"

public func getRequestIdURL() -> String {
return requestIdURL
Expand Down Expand Up @@ -171,6 +172,10 @@ public class URLHelper {
return consentURL + "?consent_name=" + consent_name + "&version=" + String(version)
}

public func getSocialLoginURL(provider: String, requestId: String) -> String {
return socialLoginURL + provider + "/" + requestId
}

public func getConsentDetailsURL(consent_name: String) -> String {
return consentDetailsURL + "?name=" + consent_name
}
Expand Down
2 changes: 2 additions & 0 deletions Cidaas/Classes/Core/Helpers/Session/AuthSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@ public class AuthSession: NSObject, OAuthTransactionDelegate {
}

public func resume(_ url: URL, options: [UIApplicationOpenURLOptionsKey: Any] = [:]) -> Bool {
Cidaas.shared.handleToken(url: url)
return true
}

public func cancel() {
// return error
self.callback(Result.failure(error: WebAuthError.shared.userCancelledException()))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ public class SafariAuthenticationSession : AuthSession {
self.authSession = SFAuthenticationSession(url: self.loginURL, callbackURLScheme: self.redirectURL.absoluteString, completionHandler: { (resultURL, resultError) in
guard resultError == nil, let callbackURL = resultURL else {
if case SFAuthenticationError.canceledLogin = resultError! {
// return error
callback(Result.failure(error: WebAuthError.shared.userCancelledException()))
} else {
// return error
callback(Result.failure(error: WebAuthError.shared.userCancelledException()))
}
return TransactionStore.shared.clear()
}
Expand Down
91 changes: 87 additions & 4 deletions Cidaas/Classes/Core/Views/Cidaas.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ public class Cidaas {
var storage: TransactionStore
var timer = Timer()
var trackingManager: TrackingManager!
public var browserCallback: ((Result<LoginResponseEntity>) -> ())!
var browserCallback: ((Result<LoginResponseEntity>) -> ())!
var propertyFileRead: Bool = false
public var extraParams: Dictionary<String, String> = Dictionary<String, String>()

// static variables
public static var intermediate_verifiation_id: String = ""
Expand Down Expand Up @@ -115,6 +117,7 @@ public class Cidaas {
// log success
let loggerMessage = "Saved Property status : \(response)"
logw(loggerMessage, cname: "cidaas-sdk-success-log")
self.propertyFileRead = true
break
}
}
Expand Down Expand Up @@ -187,12 +190,92 @@ public class Cidaas {
}
}

// -------------------------------------------------------------------------------------------------- //

// login with social
public func loginWithSocial(provider: String, requestId: String, delegate: UIViewController, callback: @escaping (Result<LoginResponseEntity>) -> Void) {
let savedProp = DBHelper.shared.getPropertyFile()
if (savedProp != nil) {
self.browserCallback = callback
LoginController.shared.loginWithSocial(provider: provider, requestId: requestId, delegate: delegate, properties: savedProp!, callback: callback)
}
else {
// log error
let loggerMessage = "Read properties file failure : " + "Error Code - 10001, Error Message - File not found, Status Code - 404"
logw(loggerMessage, cname: "cidaas-sdk-error-log")

let error = WebAuthError.shared.fileNotFoundException()

// return failure callback
DispatchQueue.main.async {
callback(Result.failure(error: error))
}
return
}
}

// -------------------------------------------------------------------------------------------------- //

// get login url
public func getLoginURL(callback: @escaping (Result<URL>) -> Void) {
var savedProp = DBHelper.shared.getPropertyFile()
if (savedProp != nil) {
savedProp?["ViewType"] = "login"
callback(Result.success(result: LoginController.shared.constructURL(properties: savedProp!)))
}
else {
// log error
let loggerMessage = "Read properties file failure : " + "Error Code - 10001, Error Message - File not found, Status Code - 404"
logw(loggerMessage, cname: "cidaas-sdk-error-log")

let error = WebAuthError.shared.fileNotFoundException()

// return failure callback
DispatchQueue.main.async {
callback(Result.failure(error: error))
}
return
}
}

// -------------------------------------------------------------------------------------------------- //

// get register url
public func getRegistrationURL(callback: @escaping (Result<URL>) -> Void) {
var savedProp = DBHelper.shared.getPropertyFile()
if (savedProp != nil) {
savedProp?["ViewType"] = "register"
callback(Result.success(result: LoginController.shared.constructURL(properties: savedProp!)))
}
else {
// log error
let loggerMessage = "Read properties file failure : " + "Error Code - 10001, Error Message - File not found, Status Code - 404"
logw(loggerMessage, cname: "cidaas-sdk-error-log")

let error = WebAuthError.shared.fileNotFoundException()

// return failure callback
DispatchQueue.main.async {
callback(Result.failure(error: error))
}
return
}
}

// -------------------------------------------------------------------------------------------------- //

// handle token
public func handleToken(url: URL) {
let code = url.valueOf("code") ?? ""
AccessTokenController.shared.getAccessToken(code: code, callback: browserCallback!)
if LoginController.shared.delegate != nil {
LoginController.shared.delegate.dismiss(animated: true, completion: nil)
}

if browserCallback != nil {
let code = url.valueOf("code") ?? ""
if code != "" {
AccessTokenController.shared.getAccessToken(code: code, callback: browserCallback!)
}
}
}

// -------------------------------------------------------------------------------------------------- //
Expand Down Expand Up @@ -2535,7 +2618,7 @@ public class Cidaas {
// 2. Call getPendingNotifications method
// 3. Maintain logs based on flags

public func getPendingNotifications(sub: String, fcmId: String, callback: @escaping(Result<PendingNotificationListResponseEntity>) -> Void) {
public func getPendingNotifications(sub: String, callback: @escaping(Result<PendingNotificationListResponseEntity>) -> Void) {

let savedProp = DBHelper.shared.getPropertyFile()
if (savedProp != nil) {
Expand Down
3 changes: 2 additions & 1 deletion Example/Cidaas/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// Cidaas.shared.ENABLE_LOG = true
Cidaas.shared.ENABLE_LOG = true
return true
}

Expand All @@ -31,6 +31,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
return true
}



func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
Expand Down
8 changes: 6 additions & 2 deletions Example/Cidaas/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,13 @@
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>com.cidaas.sdk.demo</string>
<key>CFBundleURLSchemes</key>
<array>
<string>fb1889502804712451</string>
<string>com.cidaas.sdk.demo</string>
</array>
</dict>
</array>
Expand All @@ -52,7 +56,7 @@
<string>Location in foreground</string>
<key>UIBackgroundModes</key>
<array>
<string>remote-notification</string>
<string>fetch</string>
</array>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
Expand Down
50 changes: 41 additions & 9 deletions Example/Cidaas/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,14 @@ import Cidaas

class ViewController: UIViewController {

var requestId: String = ""

// did load
override func viewDidLoad() {
super.viewDidLoad()

var dict = Dictionary<String, String>()
dict["scope"] = "openid email profile offline_access"
Cidaas.shared.extraParams = dict
}

// did receive memory warning
Expand All @@ -24,17 +27,46 @@ class ViewController: UIViewController {
}

@IBAction func loginAction(_ sender: Any) {
Cidaas.shared.loginWithBrowser(delegate: self) {

Cidaas.shared.getRequestId() {
switch $0 {
case .failure(let errorResponse):
print(errorResponse.errorMessage)
break
case .success(let successResponse):
print(successResponse.data.access_token)
break
case .success(let resultURL):
print(resultURL.data.requestId)
self.requestId = resultURL.data.requestId

Cidaas.shared.loginWithSocial(provider: "facebook", requestId: self.requestId, delegate: self) {
switch $0 {
case .success(let loginSuccessResponse):
print(loginSuccessResponse.data.access_token)
break
case .failure(let loginErrorResponse):
print(loginErrorResponse.errorMessage)
break
}
}

break
case .failure(let errorResponse):
print(errorResponse.errorMessage)
break
}
}

// Cidaas.shared.loginWithBrowser(delegate: self) {
// switch $0 {
// case .failure(let errorResponse):
// print(errorResponse.errorMessage)
// break
// case .success(let successResponse):
// let alert = UIAlertController(title: "Access Token", message: "\(successResponse.data.access_token)", preferredStyle: .alert)
// alert.addAction(UIAlertAction(title: "Done", style: .default, handler: nil))
// self.present(alert, animated: true, completion: nil)
// break
// }
// }

// guard let url = URL(string: "https://stackoverflow.com") else { return }
// UIApplication.shared.open(url)

}
}

Loading

0 comments on commit 5695c76

Please sign in to comment.