Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FR-12442 - New iOS SDK implementation #12

Merged
merged 14 commits into from
Jul 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions .github/workflows/onPush.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,10 @@ jobs:
run: xcodebuild -project demo/demo.xcodeproj -showdestinations -scheme "demo"
- name: Build for Testing
run: xcodebuild CC=clang CPLUSPLUS=clang++ LD=clang LDPLUSPLUS=clang++ build-for-testing -scheme "demo" -project "demo/demo.xcodeproj" -destination "platform=iOS Simulator,name=iPhone 14 Pro" -configuration "Debug" -enableCodeCoverage "YES"
- name: Test without Building
run: xcodebuild CC=clang CPLUSPLUS=clang++ LD=clang LDPLUSPLUS=clang++ test-without-building -scheme "demo" -project "demo/demo.xcodeproj" -destination "platform=iOS Simulator,name=iPhone 14 Pro" -configuration "Debug" -resultBundlePath "TestResults" -enableCodeCoverage "YES"
- name: "Parse Test XCResults"
uses: kishikawakatsumi/xcresulttool@v1
if: success() || failure()
with:
path: TestResults.xcresult
# - name: Test without Building
# run: xcodebuild CC=clang CPLUSPLUS=clang++ LD=clang LDPLUSPLUS=clang++ test-without-building -scheme "demo" -project "demo/demo.xcodeproj" -destination "platform=iOS Simulator,name=iPhone 14 Pro" -configuration "Debug" -resultBundlePath "TestResults" -enableCodeCoverage "YES"
# - name: "Parse Test XCResults"
# uses: kishikawakatsumi/xcresulttool@v1
# if: success() || failure()
# with:
# path: TestResults.xcresult
10 changes: 5 additions & 5 deletions FronteggSwift.podspec
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
Pod::Spec.new do |s|
s.name = 'FronteggSwift'
s.version = '1.0.0'
s.version = '1.0.4'
s.summary = 'A swift library for easy integrating iOS application with Frontegg Services'
s.description = 'Frontegg is an end-to-end user management platform for B2B SaaS, powering strategies from PLG to enterprise readiness. Easy migration, no credit card required'
s.homepage = 'https://github.com/frontegg/frontegg-ios-swift'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Frontegg LTD' => 'info@frontegg.com' }
s.source = { :git => 'https://github.com/frontegg/frontegg-ios-swift.git', :tag => 'v'+s.version.to_s }
s.swift_versions = ['5.7', '5.8']
s.platform = :ios, '14.0'
s.source_files = 'Sources/**/*'
s.source = { :git => 'https://github.com/frontegg/frontegg-ios-swift.git', :tag => s.version.to_s }
s.swift_version = '5.5'
s.platforms = { :ios => '14.0' }
s.source_files = 'Sources/**/*.swift'
s.ios.deployment_target = '14.0'
end
66 changes: 43 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ Copy FronteggDomain to future steps from [Frontegg Portal Domain](https://portal

- Navigate to [Login Method Settings](https://portal.frontegg.com/development/authentication/hosted)
- Toggle Hosted login method
- Add `{{LOGIN_URL}}/mobile/callback`
- Add `{{IOS_BUNDLE_IDENTIFIER}}://{{FRONTEGG_BASE_URL}}/ios/oauth/callback`
- Replace `IOS_BUNDLE_IDENTIFIER` with your application identifier
- Replace `FRONTEGG_BASE_URL` with your frontegg base url


### Add frontegg package to the project
Expand Down Expand Up @@ -116,7 +118,12 @@ your root project directory, this file will store values to be used variables by
if fronteggAuth.isAuthenticated {
[YOU APPLICATION TABS / ROUTER / VIEWS]
} else {
FronteggLoginPage()

Button {
fronteggAuth.login()
} label: {
Text("Login Button")
}
}
}
}
Expand Down Expand Up @@ -187,19 +194,26 @@ your root project directory, this file will store values to be used variables by
url.stopAccessingSecurityScopedResource()
}
if url.absoluteString.hasPrefix( FronteggApp.shared.baseUrl ) {
FronteggApp.shared.auth.pendingAppLink = url
window?.rootViewController = FronteggController()
window?.makeKeyAndVisible()
if(FronteggApp.shared.auth.handleOpenUrl(url)){
// Display your own Authentication View Controller
// to handle after oauth callback
window?.rootViewController = AuthenticationController()
window?.makeKeyAndVisible()
return
}
}

}
}
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
if let url = userActivity.webpageURL,
url.absoluteString.hasPrefix( FronteggApp.shared.baseUrl ){
FronteggApp.shared.auth.pendingAppLink = url
window?.rootViewController = FronteggController()
window?.makeKeyAndVisible()
if let url = userActivity.webpageURL {
if(FronteggApp.shared.auth.handleOpenUrl(url)){
// Display your own Authentication View Controller
// to handle after oauth callback
window?.rootViewController = AuthenticationController()
window?.makeKeyAndVisible()
return
}
}
}
```
Expand All @@ -220,28 +234,35 @@ your root project directory, this file will store values to be used variables by

// Label to display logged in user's email
@IBOutlet weak var label: UILabel!
var showLoader: Boolean = true

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.

// subscribe to isAuthenticated and navigate to login page
// if the user is not authenticated


let fronteggAuth = FronteggApp.shared.auth
let sub = AnySubscriber<Bool, Never>(
receiveSubscription: {query in
query.request(.unlimited)
}, receiveValue: { isAuthenticated in
if(!isAuthenticated){
self.view.window?.rootViewController = FronteggController()
self.view.window?.makeKeyAndVisible()
return .none
}
return .unlimited
})
FronteggApp.shared.auth.$isAuthenticated.subscribe(sub)

label.text = FronteggApp.shared.auth.user?.email ?? "Unknown"
}, receiveValue: { showLoader in
self.showLoader = showLoader
self.label.text = fronteggAuth.user?.email ?? "Unknown"

if(!showLoader && !fronteggAuth.isAuthenticated){
// Display your own Authentication View Controller
// to handle after oauth callback
window?.rootViewController = AuthenticationController()
window?.makeKeyAndVisible()
return .none
}
return .unlimited
})

FronteggApp.shared.auth.$showLoader.subscribe(sub)

}

@IBAction func logoutButton (){
Expand All @@ -251,7 +272,6 @@ your root project directory, this file will store values to be used variables by
}

```




Expand Down
48 changes: 24 additions & 24 deletions Sources/FronteggSwift/FronteggAuth.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@ public class FronteggAuth: ObservableObject {
@Published public var isLoading = true
@Published public var initializing = true
@Published public var showLoader = true
@Published public var pendingAppLink: URL?
@Published public var appLink: URL?
@Published public var externalLink = false
@Published public var appLink: Bool = false
public var baseUrl = ""
public var clientId = ""

Expand Down Expand Up @@ -48,15 +46,6 @@ public class FronteggAuth: ObservableObject {
}.store(in: &subscribers)


self.$pendingAppLink.sink() { pendingAppLinkValue in
if(pendingAppLinkValue != nil){
DispatchQueue.main.async {
self.appLink = pendingAppLinkValue
self.pendingAppLink = nil
}
}
}.store(in: &subscribers)

if let refreshToken = try? credentialManager.get(key: KeychainKeys.refreshToken.rawValue),
let accessToken = try? credentialManager.get(key: KeychainKeys.accessToken.rawValue) {

Expand Down Expand Up @@ -91,8 +80,7 @@ public class FronteggAuth: ObservableObject {
self.accessToken = accessToken
self.user = user
self.isAuthenticated = true
self.pendingAppLink = nil
self.appLink = nil
self.appLink = false

let offset = Double((decode["exp"] as! Int) - Int(Date().timeIntervalSince1970)) * 0.9
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + offset) {
Expand All @@ -114,6 +102,7 @@ public class FronteggAuth: ObservableObject {
DispatchQueue.main.sync {
self.isLoading = false
self.initializing = false
self.appLink = false
}
}

Expand All @@ -139,6 +128,7 @@ public class FronteggAuth: ObservableObject {
self.accessToken = nil
self.refreshToken = nil
self.initializing = false
self.appLink = false
}
}
}
Expand All @@ -161,16 +151,19 @@ public class FronteggAuth: ObservableObject {
self.initializing = false
self.isLoading = false
self.isAuthenticated = false
self.accessToken = nil
self.refreshToken = nil
self.credentialManager.clear()
}
}
}

func handleHostedLoginCallback(_ code: String, _ codeVerifier: String, _ completion: @escaping FronteggAuth.CompletionHandler) {

let redirectUri = generateRedirectUri()
setIsLoading(true)

Task {

let (responseData, error) = await api.exchangeToken(
code: code,
redirectUrl: redirectUri,
Expand All @@ -179,11 +172,13 @@ public class FronteggAuth: ObservableObject {

guard error == nil else {
completion(.failure(error!))
setIsLoading(false)
return
}

guard let data = responseData else {
completion(.failure(FronteggError.authError("Failed to authenticate with frontegg")))
setIsLoading(false)
return
}

Expand All @@ -192,23 +187,21 @@ public class FronteggAuth: ObservableObject {
await setCredentials(accessToken: data.access_token, refreshToken: data.refresh_token)

completion(.success(user!))

setIsLoading(false)
} catch {
completion(.failure(FronteggError.authError("Failed to load user data: \(error.localizedDescription)")))
setIsLoading(false)
return
}

}

}


func createCompletionHandler(message: String) -> ((Bool) -> Void) {
return { (isSuccess: Bool) in
if isSuccess {
print("\(message) - Task completed successfully.")
} else {
print("\(message) - Task failed.")
}
internal func setIsLoading(_ isLoading: Bool){
DispatchQueue.main.async {
self.isLoading = isLoading
}
}

Expand All @@ -227,6 +220,7 @@ public class FronteggAuth: ObservableObject {
return
}


self.logger.trace("handleHostedLoginCallback, url: \(url)")
guard let queryItems = getQueryItems(url.absoluteString), let code = queryItems["code"] else {
let error = FronteggError.authError("Failed to get extract code from hostedLoginCallback url")
Expand All @@ -246,8 +240,11 @@ public class FronteggAuth: ObservableObject {
}
public typealias CompletionHandler = (Result<User, FronteggError>) -> Void

public func login( completion: @escaping FronteggAuth.CompletionHandler) {
public func login(_ _completion: FronteggAuth.CompletionHandler? = nil) {

let completion = _completion ?? { res in

}
self.webAuthentication?.webAuthSession?.cancel()
self.webAuthentication = WebAuthentication()

Expand All @@ -262,9 +259,12 @@ public class FronteggAuth: ObservableObject {
public func handleOpenUrl(_ url: URL) -> Bool {

if(!url.absoluteString.hasPrefix(self.baseUrl)){
self.appLink = false
return false
}

self.appLink = true

self.webAuthentication?.webAuthSession?.cancel()
self.webAuthentication = WebAuthentication()
let oauthCallback = createOauthCallbackHandler() { res in
Expand Down
1 change: 0 additions & 1 deletion Sources/FronteggSwift/utils/AuthorizeUrlGenerator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ public class AuthorizeUrlGenerator {

let baseUrl = FronteggApp.shared.baseUrl
let redirectUri = generateRedirectUri();
logger.trace("CodeVerifier saved in memory to be able to validate the response")


var authorizeUrl = URLComponents(string: baseUrl)!
Expand Down
36 changes: 0 additions & 36 deletions Sources/FronteggSwift/views/AbstractFronteggController.swift

This file was deleted.

Loading