capacitor-auth-manager 2.4.1 → 2.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,288 +0,0 @@
1
- import Foundation
2
- import Capacitor
3
- import AuthenticationServices
4
-
5
- class AppleAuthProvider: NSObject, BaseAuthProvider {
6
- let provider: AuthProvider = .apple
7
- let storage: AuthStorage
8
- let logger: AuthLogger
9
-
10
- private var currentUser: AuthUser?
11
- private var signInCompletion: ((AuthResult?, Error?) -> Void)?
12
- private var currentNonce: String?
13
-
14
- init(config: AuthProviderConfig, storage: AuthStorage, logger: AuthLogger) {
15
- self.storage = storage
16
- self.logger = logger
17
- super.init()
18
- }
19
-
20
- func initialize(completion: @escaping (Error?) -> Void) {
21
- logger.info("Initializing Apple auth provider")
22
-
23
- // Check for existing credential
24
- if let savedCredential = storage.getCredential(for: provider) {
25
- // Verify the credential is still valid
26
- let appleIDProvider = ASAuthorizationAppleIDProvider()
27
- appleIDProvider.getCredentialState(forUserID: savedCredential.accessToken ?? "") { [weak self] state, error in
28
- switch state {
29
- case .authorized:
30
- self?.logger.info("Apple credential is still valid")
31
- case .revoked, .notFound:
32
- self?.storage.deleteCredential(for: .apple)
33
- self?.currentUser = nil
34
- default:
35
- break
36
- }
37
- completion(nil)
38
- }
39
- } else {
40
- completion(nil)
41
- }
42
- }
43
-
44
- func signIn(credentials: JSObject?, options: JSObject?, completion: @escaping (AuthResult?, Error?) -> Void) {
45
- logger.info("Starting Apple sign-in")
46
-
47
- signInCompletion = completion
48
- currentNonce = generateNonce()
49
-
50
- let appleIDProvider = ASAuthorizationAppleIDProvider()
51
- let request = appleIDProvider.createRequest()
52
- request.requestedScopes = [.fullName, .email]
53
-
54
- if let nonce = currentNonce {
55
- request.nonce = sha256(nonce)
56
- }
57
-
58
- let authorizationController = ASAuthorizationController(authorizationRequests: [request])
59
- authorizationController.delegate = self
60
- authorizationController.presentationContextProvider = self
61
- authorizationController.performRequests()
62
- }
63
-
64
- func signOut(options: JSObject?, completion: @escaping (Error?) -> Void) {
65
- logger.info("Signing out from Apple")
66
-
67
- currentUser = nil
68
- storage.deleteCredential(for: provider)
69
- completion(nil)
70
- }
71
-
72
- func getCurrentUser(completion: @escaping (AuthUser?, Error?) -> Void) {
73
- completion(currentUser, nil)
74
- }
75
-
76
- func refreshToken(options: JSObject?, completion: @escaping (AuthResult?, Error?) -> Void) {
77
- // Apple doesn't support token refresh - need to re-authenticate
78
- completion(nil, createAuthError(code: .operationNotAllowed, message: "Apple Sign In doesn't support token refresh. Please sign in again."))
79
- }
80
-
81
- func isSupported(completion: @escaping (Bool, Error?) -> Void) {
82
- // Apple Sign In is available on iOS 13+
83
- if #available(iOS 13.0, *) {
84
- completion(true, nil)
85
- } else {
86
- completion(false, nil)
87
- }
88
- }
89
-
90
- func linkAccount(credentials: JSObject?, options: JSObject?, completion: @escaping (AuthResult?, Error?) -> Void) {
91
- signIn(credentials: credentials, options: options, completion: completion)
92
- }
93
-
94
- func unlinkAccount(completion: @escaping (Error?) -> Void) {
95
- signOut(options: nil, completion: completion)
96
- }
97
-
98
- func getIdToken(forceRefresh: Bool, completion: @escaping (String?, Error?) -> Void) {
99
- if let credential = storage.getCredential(for: provider) {
100
- completion(credential.idToken, nil)
101
- } else {
102
- completion(nil, createAuthError(code: .invalidUserToken, message: "No Apple credential found"))
103
- }
104
- }
105
-
106
- func revokeAccess(token: String?, completion: @escaping (Error?) -> Void) {
107
- // Apple doesn't have a direct revoke API
108
- signOut(options: nil, completion: completion)
109
- }
110
-
111
- // MARK: - Nonce Generation
112
-
113
- private func generateNonce(length: Int = 32) -> String {
114
- precondition(length > 0)
115
- let charset: [Character] = Array("0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._")
116
- var result = ""
117
- var remainingLength = length
118
-
119
- while remainingLength > 0 {
120
- let randoms: [UInt8] = (0 ..< 16).map { _ in
121
- var random: UInt8 = 0
122
- let errorCode = SecRandomCopyBytes(kSecRandomDefault, 1, &random)
123
- if errorCode != errSecSuccess {
124
- fatalError("Unable to generate nonce. SecRandomCopyBytes failed with OSStatus \(errorCode)")
125
- }
126
- return random
127
- }
128
-
129
- randoms.forEach { random in
130
- if remainingLength == 0 { return }
131
- if random < charset.count {
132
- result.append(charset[Int(random)])
133
- remainingLength -= 1
134
- }
135
- }
136
- }
137
-
138
- return result
139
- }
140
-
141
- private func sha256(_ input: String) -> String {
142
- let inputData = Data(input.utf8)
143
- var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
144
- inputData.withUnsafeBytes {
145
- _ = CC_SHA256($0.baseAddress, CC_LONG(inputData.count), &hash)
146
- }
147
- return hash.map { String(format: "%02x", $0) }.joined()
148
- }
149
- }
150
-
151
- // MARK: - ASAuthorizationControllerDelegate
152
-
153
- extension AppleAuthProvider: ASAuthorizationControllerDelegate {
154
- func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
155
- guard let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential else {
156
- signInCompletion?(nil, createAuthError(code: .internalError, message: "Invalid credential type"))
157
- return
158
- }
159
-
160
- logger.info("Apple sign-in successful")
161
-
162
- let userIdentifier = appleIDCredential.user
163
- let fullName = appleIDCredential.fullName
164
- let email = appleIDCredential.email
165
-
166
- var idTokenString: String?
167
- if let identityToken = appleIDCredential.identityToken,
168
- let tokenString = String(data: identityToken, encoding: .utf8) {
169
- idTokenString = tokenString
170
- }
171
-
172
- var authorizationCodeString: String?
173
- if let authorizationCode = appleIDCredential.authorizationCode,
174
- let codeString = String(data: authorizationCode, encoding: .utf8) {
175
- authorizationCodeString = codeString
176
- }
177
-
178
- let displayName: String? = {
179
- if let givenName = fullName?.givenName, let familyName = fullName?.familyName {
180
- return "\(givenName) \(familyName)"
181
- } else if let givenName = fullName?.givenName {
182
- return givenName
183
- }
184
- return nil
185
- }()
186
-
187
- let authUser = AuthUser(
188
- uid: userIdentifier,
189
- email: email,
190
- emailVerified: email != nil,
191
- displayName: displayName,
192
- photoURL: nil,
193
- phoneNumber: nil,
194
- isAnonymous: false,
195
- tenantId: nil,
196
- providerData: [
197
- UserInfo(
198
- providerId: provider.rawValue,
199
- uid: userIdentifier,
200
- displayName: displayName,
201
- email: email,
202
- phoneNumber: nil,
203
- photoURL: nil
204
- )
205
- ],
206
- metadata: UserMetadata(
207
- creationTime: ISO8601DateFormatter().string(from: Date()),
208
- lastSignInTime: ISO8601DateFormatter().string(from: Date()),
209
- lastRefreshTime: nil
210
- ),
211
- refreshToken: nil,
212
- customClaims: nil
213
- )
214
-
215
- currentUser = authUser
216
-
217
- let credential = AuthCredential(
218
- providerId: provider.rawValue,
219
- signInMethod: "apple",
220
- accessToken: userIdentifier,
221
- idToken: idTokenString,
222
- refreshToken: authorizationCodeString,
223
- expiresAt: nil,
224
- tokenType: "Bearer",
225
- scope: "email name",
226
- rawNonce: currentNonce
227
- )
228
-
229
- storage.saveCredential(credential, for: provider)
230
-
231
- let authResult = AuthResult(
232
- user: authUser,
233
- credential: credential,
234
- additionalUserInfo: AdditionalUserInfo(
235
- isNewUser: email != nil, // Apple only provides email on first sign-in
236
- providerId: provider.rawValue,
237
- profile: nil,
238
- username: nil
239
- ),
240
- operationType: "signIn"
241
- )
242
-
243
- signInCompletion?(authResult, nil)
244
- signInCompletion = nil
245
- currentNonce = nil
246
- }
247
-
248
- func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
249
- logger.error("Apple sign-in failed: \(error.localizedDescription)")
250
-
251
- let authError: Error
252
- if let asError = error as? ASAuthorizationError {
253
- switch asError.code {
254
- case .canceled:
255
- authError = createAuthError(code: .userCancelled, message: "User cancelled sign-in")
256
- case .invalidResponse:
257
- authError = createAuthError(code: .internalError, message: "Invalid response from Apple")
258
- case .notHandled:
259
- authError = createAuthError(code: .internalError, message: "Authorization not handled")
260
- case .failed:
261
- authError = createAuthError(code: .internalError, message: "Authorization failed")
262
- case .notInteractive:
263
- authError = createAuthError(code: .internalError, message: "Non-interactive authorization failed")
264
- case .unknown:
265
- authError = createAuthError(code: .internalError, message: "Unknown error")
266
- @unknown default:
267
- authError = createAuthError(code: .internalError, message: error.localizedDescription)
268
- }
269
- } else {
270
- authError = createAuthError(code: .internalError, message: error.localizedDescription)
271
- }
272
-
273
- signInCompletion?(nil, authError)
274
- signInCompletion = nil
275
- currentNonce = nil
276
- }
277
- }
278
-
279
- // MARK: - ASAuthorizationControllerPresentationContextProviding
280
-
281
- extension AppleAuthProvider: ASAuthorizationControllerPresentationContextProviding {
282
- func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
283
- return UIApplication.shared.windows.first { $0.isKeyWindow } ?? UIApplication.shared.windows.first!
284
- }
285
- }
286
-
287
- // MARK: - CommonCrypto Import
288
- import CommonCrypto
@@ -1,297 +0,0 @@
1
- import Foundation
2
- import Capacitor
3
- import FBSDKLoginKit
4
- import FBSDKCoreKit
5
-
6
- class FacebookAuthProvider: BaseAuthProvider {
7
- let provider: AuthProvider = .facebook
8
- let storage: AuthStorage
9
- let logger: AuthLogger
10
-
11
- private var appId: String?
12
- private var permissions: [String] = ["public_profile", "email"]
13
- private var loginManager: LoginManager
14
- private var currentUser: AuthUser?
15
-
16
- init(config: AuthProviderConfig, storage: AuthStorage, logger: AuthLogger) {
17
- self.storage = storage
18
- self.logger = logger
19
- self.loginManager = LoginManager()
20
-
21
- // Extract configuration
22
- if let appId = config.options["appId"] as? String {
23
- self.appId = appId
24
- }
25
- if let scopes = config.options["scopes"] as? [String] {
26
- self.permissions = scopes
27
- }
28
- }
29
-
30
- func initialize(completion: @escaping (Error?) -> Void) {
31
- logger.info("Initializing Facebook auth provider")
32
-
33
- // Check for existing token
34
- if let token = AccessToken.current, !token.isExpired {
35
- loadCurrentUser { [weak self] in
36
- self?.logger.info("Restored previous Facebook session")
37
- completion(nil)
38
- }
39
- } else {
40
- completion(nil)
41
- }
42
- }
43
-
44
- func signIn(credentials: JSObject?, options: JSObject?, completion: @escaping (AuthResult?, Error?) -> Void) {
45
- logger.info("Starting Facebook sign-in")
46
-
47
- guard let presentingVC = UIApplication.shared.windows.first?.rootViewController else {
48
- completion(nil, createAuthError(code: .internalError, message: "No presenting view controller available"))
49
- return
50
- }
51
-
52
- loginManager.logIn(permissions: permissions, from: presentingVC) { [weak self] result, error in
53
- guard let self = self else { return }
54
-
55
- if let error = error {
56
- self.logger.error("Facebook sign-in failed: \(error.localizedDescription)")
57
- completion(nil, self.createAuthError(code: .internalError, message: error.localizedDescription))
58
- return
59
- }
60
-
61
- guard let result = result else {
62
- completion(nil, self.createAuthError(code: .internalError, message: "No result returned"))
63
- return
64
- }
65
-
66
- if result.isCancelled {
67
- completion(nil, self.createAuthError(code: .userCancelled, message: "User cancelled sign-in"))
68
- return
69
- }
70
-
71
- self.loadCurrentUser { [weak self] in
72
- guard let self = self, let user = self.currentUser else {
73
- completion(nil, self?.createAuthError(code: .internalError, message: "Failed to load user data"))
74
- return
75
- }
76
-
77
- guard let token = AccessToken.current else {
78
- completion(nil, self.createAuthError(code: .internalError, message: "No access token"))
79
- return
80
- }
81
-
82
- let credential = AuthCredential(
83
- providerId: self.provider.rawValue,
84
- signInMethod: "oauth",
85
- accessToken: token.tokenString,
86
- idToken: nil,
87
- refreshToken: nil,
88
- expiresAt: Int(token.expirationDate.timeIntervalSince1970) * 1000,
89
- tokenType: "Bearer",
90
- scope: self.permissions.joined(separator: " "),
91
- rawNonce: nil
92
- )
93
-
94
- self.storage.saveCredential(credential, for: self.provider)
95
-
96
- let authResult = AuthResult(
97
- user: user,
98
- credential: credential,
99
- additionalUserInfo: AdditionalUserInfo(
100
- isNewUser: false,
101
- providerId: self.provider.rawValue,
102
- profile: nil,
103
- username: nil
104
- ),
105
- operationType: "signIn"
106
- )
107
-
108
- self.logger.info("Facebook sign-in successful")
109
- completion(authResult, nil)
110
- }
111
- }
112
- }
113
-
114
- func signOut(options: JSObject?, completion: @escaping (Error?) -> Void) {
115
- logger.info("Signing out from Facebook")
116
-
117
- loginManager.logOut()
118
- currentUser = nil
119
- storage.deleteCredential(for: provider)
120
-
121
- completion(nil)
122
- }
123
-
124
- func getCurrentUser(completion: @escaping (AuthUser?, Error?) -> Void) {
125
- if let user = currentUser {
126
- completion(user, nil)
127
- } else if AccessToken.current != nil {
128
- loadCurrentUser { [weak self] in
129
- completion(self?.currentUser, nil)
130
- }
131
- } else {
132
- completion(nil, nil)
133
- }
134
- }
135
-
136
- func refreshToken(options: JSObject?, completion: @escaping (AuthResult?, Error?) -> Void) {
137
- logger.info("Refreshing Facebook token")
138
-
139
- AccessToken.refreshCurrentAccessToken { [weak self] connection, result, error in
140
- guard let self = self else { return }
141
-
142
- if let error = error {
143
- completion(nil, self.createAuthError(code: .tokenExpired, message: error.localizedDescription))
144
- return
145
- }
146
-
147
- guard let token = AccessToken.current else {
148
- completion(nil, self.createAuthError(code: .internalError, message: "No access token after refresh"))
149
- return
150
- }
151
-
152
- guard let user = self.currentUser else {
153
- completion(nil, self.createAuthError(code: .internalError, message: "No current user"))
154
- return
155
- }
156
-
157
- let credential = AuthCredential(
158
- providerId: self.provider.rawValue,
159
- signInMethod: "oauth",
160
- accessToken: token.tokenString,
161
- idToken: nil,
162
- refreshToken: nil,
163
- expiresAt: Int(token.expirationDate.timeIntervalSince1970) * 1000,
164
- tokenType: "Bearer",
165
- scope: self.permissions.joined(separator: " "),
166
- rawNonce: nil
167
- )
168
-
169
- self.storage.saveCredential(credential, for: self.provider)
170
-
171
- let authResult = AuthResult(
172
- user: user,
173
- credential: credential,
174
- additionalUserInfo: nil,
175
- operationType: "refresh"
176
- )
177
-
178
- completion(authResult, nil)
179
- }
180
- }
181
-
182
- func isSupported(completion: @escaping (Bool, Error?) -> Void) {
183
- completion(true, nil)
184
- }
185
-
186
- func linkAccount(credentials: JSObject?, options: JSObject?, completion: @escaping (AuthResult?, Error?) -> Void) {
187
- signIn(credentials: credentials, options: options, completion: completion)
188
- }
189
-
190
- func unlinkAccount(completion: @escaping (Error?) -> Void) {
191
- signOut(options: nil, completion: completion)
192
- }
193
-
194
- func getIdToken(forceRefresh: Bool, completion: @escaping (String?, Error?) -> Void) {
195
- // Facebook doesn't provide ID tokens, return access token instead
196
- if let token = AccessToken.current {
197
- if forceRefresh {
198
- AccessToken.refreshCurrentAccessToken { _, _, _ in
199
- completion(AccessToken.current?.tokenString, nil)
200
- }
201
- } else {
202
- completion(token.tokenString, nil)
203
- }
204
- } else {
205
- completion(nil, createAuthError(code: .invalidUserToken, message: "No Facebook token found"))
206
- }
207
- }
208
-
209
- func revokeAccess(token: String?, completion: @escaping (Error?) -> Void) {
210
- logger.info("Revoking Facebook access")
211
-
212
- guard AccessToken.current != nil else {
213
- completion(nil)
214
- return
215
- }
216
-
217
- GraphRequest(graphPath: "/me/permissions", httpMethod: .delete).start { [weak self] _, _, error in
218
- guard let self = self else { return }
219
-
220
- if let error = error {
221
- self.logger.error("Failed to revoke Facebook permissions: \(error.localizedDescription)")
222
- }
223
-
224
- self.loginManager.logOut()
225
- self.currentUser = nil
226
- self.storage.deleteCredential(for: self.provider)
227
-
228
- completion(error)
229
- }
230
- }
231
-
232
- private func loadCurrentUser(completion: @escaping () -> Void) {
233
- let request = GraphRequest(
234
- graphPath: "me",
235
- parameters: ["fields": "id,name,email,picture.type(large)"]
236
- )
237
-
238
- request.start { [weak self] _, result, error in
239
- guard let self = self else {
240
- completion()
241
- return
242
- }
243
-
244
- if let error = error {
245
- self.logger.error("Failed to load Facebook user: \(error.localizedDescription)")
246
- completion()
247
- return
248
- }
249
-
250
- guard let data = result as? [String: Any] else {
251
- completion()
252
- return
253
- }
254
-
255
- let uid = data["id"] as? String ?? ""
256
- let name = data["name"] as? String
257
- let email = data["email"] as? String
258
- var photoURL: String?
259
-
260
- if let picture = data["picture"] as? [String: Any],
261
- let pictureData = picture["data"] as? [String: Any],
262
- let url = pictureData["url"] as? String {
263
- photoURL = url
264
- }
265
-
266
- self.currentUser = AuthUser(
267
- uid: uid,
268
- email: email,
269
- emailVerified: email != nil,
270
- displayName: name,
271
- photoURL: photoURL,
272
- phoneNumber: nil,
273
- isAnonymous: false,
274
- tenantId: nil,
275
- providerData: [
276
- UserInfo(
277
- providerId: self.provider.rawValue,
278
- uid: uid,
279
- displayName: name,
280
- email: email,
281
- phoneNumber: nil,
282
- photoURL: photoURL
283
- )
284
- ],
285
- metadata: UserMetadata(
286
- creationTime: nil,
287
- lastSignInTime: ISO8601DateFormatter().string(from: Date()),
288
- lastRefreshTime: nil
289
- ),
290
- refreshToken: nil,
291
- customClaims: nil
292
- )
293
-
294
- completion()
295
- }
296
- }
297
- }
@@ -1,54 +0,0 @@
1
- import Foundation
2
- import Capacitor
3
-
4
- class GitHubAuthProvider: OAuthWebProvider {
5
-
6
- init(config: AuthProviderConfig, storage: AuthStorage, logger: AuthLogger) {
7
- super.init(
8
- provider: .github,
9
- config: config,
10
- storage: storage,
11
- logger: logger,
12
- authUrl: "https://github.com/login/oauth/authorize",
13
- tokenUrl: "https://github.com/login/oauth/access_token",
14
- userInfoUrl: "https://api.github.com/user",
15
- defaultScopes: ["user:email", "read:user"]
16
- )
17
- }
18
-
19
- override func parseUserInfo(json: [String: Any]) -> AuthUser {
20
- let uid = (json["id"] as? Int).map { String($0) } ?? ""
21
- let email = json["email"] as? String
22
- let name = json["name"] as? String ?? json["login"] as? String
23
- let avatarUrl = json["avatar_url"] as? String
24
- let login = json["login"] as? String
25
-
26
- return AuthUser(
27
- uid: uid,
28
- email: email,
29
- emailVerified: email != nil,
30
- displayName: name,
31
- photoURL: avatarUrl,
32
- phoneNumber: nil,
33
- isAnonymous: false,
34
- tenantId: nil,
35
- providerData: [
36
- UserInfo(
37
- providerId: provider.rawValue,
38
- uid: uid,
39
- displayName: name,
40
- email: email,
41
- phoneNumber: nil,
42
- photoURL: avatarUrl
43
- )
44
- ],
45
- metadata: UserMetadata(
46
- creationTime: json["created_at"] as? String,
47
- lastSignInTime: ISO8601DateFormatter().string(from: Date()),
48
- lastRefreshTime: nil
49
- ),
50
- refreshToken: nil,
51
- customClaims: ["login": login as Any]
52
- )
53
- }
54
- }
@@ -1,63 +0,0 @@
1
- import Foundation
2
- import Capacitor
3
-
4
- class LinkedInAuthProvider: OAuthWebProvider {
5
-
6
- init(config: AuthProviderConfig, storage: AuthStorage, logger: AuthLogger) {
7
- super.init(
8
- provider: .linkedin,
9
- config: config,
10
- storage: storage,
11
- logger: logger,
12
- authUrl: "https://www.linkedin.com/oauth/v2/authorization",
13
- tokenUrl: "https://www.linkedin.com/oauth/v2/accessToken",
14
- userInfoUrl: "https://api.linkedin.com/v2/userinfo",
15
- defaultScopes: ["openid", "profile", "email"]
16
- )
17
- }
18
-
19
- override func parseUserInfo(json: [String: Any]) -> AuthUser {
20
- // LinkedIn OpenID Connect userinfo endpoint response
21
- let uid = json["sub"] as? String ?? ""
22
- let email = json["email"] as? String
23
- let emailVerified = json["email_verified"] as? Bool ?? false
24
- let name = json["name"] as? String
25
- let givenName = json["given_name"] as? String
26
- let familyName = json["family_name"] as? String
27
- let picture = json["picture"] as? String
28
- let locale = json["locale"] as? String
29
-
30
- var displayName = name
31
- if displayName == nil && (givenName != nil || familyName != nil) {
32
- displayName = [givenName, familyName].compactMap { $0 }.joined(separator: " ")
33
- }
34
-
35
- return AuthUser(
36
- uid: uid,
37
- email: email,
38
- emailVerified: emailVerified,
39
- displayName: displayName,
40
- photoURL: picture,
41
- phoneNumber: nil,
42
- isAnonymous: false,
43
- tenantId: nil,
44
- providerData: [
45
- UserInfo(
46
- providerId: provider.rawValue,
47
- uid: uid,
48
- displayName: displayName,
49
- email: email,
50
- phoneNumber: nil,
51
- photoURL: picture
52
- )
53
- ],
54
- metadata: UserMetadata(
55
- creationTime: nil,
56
- lastSignInTime: ISO8601DateFormatter().string(from: Date()),
57
- lastRefreshTime: nil
58
- ),
59
- refreshToken: nil,
60
- customClaims: locale != nil ? ["locale": locale as Any] : nil
61
- )
62
- }
63
- }