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,315 +0,0 @@
1
- import Foundation
2
- import Capacitor
3
- import MSAL
4
-
5
- class MicrosoftAuthProvider: BaseAuthProvider {
6
- let provider: AuthProvider = .microsoft
7
- let storage: AuthStorage
8
- let logger: AuthLogger
9
-
10
- private var clientId: String?
11
- private var authority: String?
12
- private var redirectUri: String?
13
- private var scopes: [String] = ["openid", "profile", "email"]
14
- private var msalApplication: MSALPublicClientApplication?
15
- private var currentUser: AuthUser?
16
-
17
- init(config: AuthProviderConfig, storage: AuthStorage, logger: AuthLogger) {
18
- self.storage = storage
19
- self.logger = logger
20
-
21
- // Extract configuration
22
- if let clientId = config.options["clientId"] as? String {
23
- self.clientId = clientId
24
- }
25
- if let authority = config.options["authority"] as? String {
26
- self.authority = authority
27
- }
28
- if let redirectUri = config.options["redirectUri"] as? String {
29
- self.redirectUri = redirectUri
30
- }
31
- if let scopes = config.options["scopes"] as? [String] {
32
- self.scopes = scopes
33
- }
34
- }
35
-
36
- func initialize(completion: @escaping (Error?) -> Void) {
37
- logger.info("Initializing Microsoft auth provider")
38
-
39
- guard let clientId = clientId else {
40
- completion(createAuthError(code: .missingConfiguration, message: "Microsoft client ID is required"))
41
- return
42
- }
43
-
44
- do {
45
- let authorityURL: URL
46
- if let authority = authority, let url = URL(string: authority) {
47
- authorityURL = url
48
- } else {
49
- authorityURL = URL(string: "https://login.microsoftonline.com/common")!
50
- }
51
-
52
- let msalAuthority = try MSALAADAuthority(url: authorityURL)
53
-
54
- let config = MSALPublicClientApplicationConfig(
55
- clientId: clientId,
56
- redirectUri: redirectUri,
57
- authority: msalAuthority
58
- )
59
-
60
- msalApplication = try MSALPublicClientApplication(configuration: config)
61
-
62
- // Check for existing account
63
- if let accounts = try? msalApplication?.allAccounts(), let account = accounts.first {
64
- loadUser(from: account)
65
- }
66
-
67
- completion(nil)
68
- } catch {
69
- logger.error("Failed to initialize MSAL: \(error.localizedDescription)")
70
- completion(createAuthError(code: .internalError, message: error.localizedDescription))
71
- }
72
- }
73
-
74
- func signIn(credentials: JSObject?, options: JSObject?, completion: @escaping (AuthResult?, Error?) -> Void) {
75
- logger.info("Starting Microsoft sign-in")
76
-
77
- guard let application = msalApplication else {
78
- completion(nil, createAuthError(code: .missingConfiguration, message: "MSAL not initialized"))
79
- return
80
- }
81
-
82
- guard let presentingVC = UIApplication.shared.windows.first?.rootViewController else {
83
- completion(nil, createAuthError(code: .internalError, message: "No presenting view controller available"))
84
- return
85
- }
86
-
87
- let webViewParameters = MSALWebviewParameters(authPresentationViewController: presentingVC)
88
- let interactiveParameters = MSALInteractiveTokenParameters(scopes: scopes, webviewParameters: webViewParameters)
89
-
90
- application.acquireToken(with: interactiveParameters) { [weak self] result, error in
91
- guard let self = self else { return }
92
-
93
- if let error = error {
94
- self.logger.error("Microsoft sign-in failed: \(error.localizedDescription)")
95
- if let nsError = error as NSError?, nsError.domain == MSALErrorDomain {
96
- if nsError.code == MSALError.userCanceled.rawValue {
97
- completion(nil, self.createAuthError(code: .userCancelled, message: "User cancelled sign-in"))
98
- return
99
- }
100
- }
101
- completion(nil, self.createAuthError(code: .internalError, message: error.localizedDescription))
102
- return
103
- }
104
-
105
- guard let result = result else {
106
- completion(nil, self.createAuthError(code: .internalError, message: "No result returned"))
107
- return
108
- }
109
-
110
- let authResult = self.createAuthResult(from: result)
111
- self.logger.info("Microsoft sign-in successful")
112
- completion(authResult, nil)
113
- }
114
- }
115
-
116
- func signOut(options: JSObject?, completion: @escaping (Error?) -> Void) {
117
- logger.info("Signing out from Microsoft")
118
-
119
- guard let application = msalApplication else {
120
- completion(nil)
121
- return
122
- }
123
-
124
- do {
125
- let accounts = try application.allAccounts()
126
- for account in accounts {
127
- try application.remove(account)
128
- }
129
- currentUser = nil
130
- storage.deleteCredential(for: provider)
131
- completion(nil)
132
- } catch {
133
- completion(error)
134
- }
135
- }
136
-
137
- func getCurrentUser(completion: @escaping (AuthUser?, Error?) -> Void) {
138
- completion(currentUser, nil)
139
- }
140
-
141
- func refreshToken(options: JSObject?, completion: @escaping (AuthResult?, Error?) -> Void) {
142
- logger.info("Refreshing Microsoft token")
143
-
144
- guard let application = msalApplication else {
145
- completion(nil, createAuthError(code: .missingConfiguration, message: "MSAL not initialized"))
146
- return
147
- }
148
-
149
- do {
150
- let accounts = try application.allAccounts()
151
- guard let account = accounts.first else {
152
- completion(nil, createAuthError(code: .invalidUserToken, message: "No account found"))
153
- return
154
- }
155
-
156
- let silentParameters = MSALSilentTokenParameters(scopes: scopes, account: account)
157
- silentParameters.forceRefresh = true
158
-
159
- application.acquireTokenSilent(with: silentParameters) { [weak self] result, error in
160
- guard let self = self else { return }
161
-
162
- if let error = error {
163
- // If silent refresh fails, try interactive
164
- self.signIn(credentials: nil, options: nil, completion: completion)
165
- return
166
- }
167
-
168
- guard let result = result else {
169
- completion(nil, self.createAuthError(code: .internalError, message: "No result returned"))
170
- return
171
- }
172
-
173
- let authResult = self.createAuthResult(from: result)
174
- completion(authResult, nil)
175
- }
176
- } catch {
177
- completion(nil, createAuthError(code: .internalError, message: error.localizedDescription))
178
- }
179
- }
180
-
181
- func isSupported(completion: @escaping (Bool, Error?) -> Void) {
182
- completion(true, nil)
183
- }
184
-
185
- func linkAccount(credentials: JSObject?, options: JSObject?, completion: @escaping (AuthResult?, Error?) -> Void) {
186
- signIn(credentials: credentials, options: options, completion: completion)
187
- }
188
-
189
- func unlinkAccount(completion: @escaping (Error?) -> Void) {
190
- signOut(options: nil, completion: completion)
191
- }
192
-
193
- func getIdToken(forceRefresh: Bool, completion: @escaping (String?, Error?) -> Void) {
194
- guard let application = msalApplication else {
195
- completion(nil, createAuthError(code: .missingConfiguration, message: "MSAL not initialized"))
196
- return
197
- }
198
-
199
- do {
200
- let accounts = try application.allAccounts()
201
- guard let account = accounts.first else {
202
- completion(nil, createAuthError(code: .invalidUserToken, message: "No account found"))
203
- return
204
- }
205
-
206
- let silentParameters = MSALSilentTokenParameters(scopes: scopes, account: account)
207
- silentParameters.forceRefresh = forceRefresh
208
-
209
- application.acquireTokenSilent(with: silentParameters) { result, error in
210
- if let error = error {
211
- completion(nil, error)
212
- } else {
213
- completion(result?.idToken, nil)
214
- }
215
- }
216
- } catch {
217
- completion(nil, error)
218
- }
219
- }
220
-
221
- func revokeAccess(token: String?, completion: @escaping (Error?) -> Void) {
222
- // Microsoft requires web-based sign out to fully revoke
223
- signOut(options: nil, completion: completion)
224
- }
225
-
226
- private func loadUser(from account: MSALAccount) {
227
- currentUser = AuthUser(
228
- uid: account.homeAccountId?.identifier ?? account.username ?? "",
229
- email: account.username,
230
- emailVerified: account.username?.contains("@") ?? false,
231
- displayName: account.username,
232
- photoURL: nil,
233
- phoneNumber: nil,
234
- isAnonymous: false,
235
- tenantId: account.homeAccountId?.tenantId,
236
- providerData: [
237
- UserInfo(
238
- providerId: provider.rawValue,
239
- uid: account.homeAccountId?.identifier ?? "",
240
- displayName: account.username,
241
- email: account.username,
242
- phoneNumber: nil,
243
- photoURL: nil
244
- )
245
- ],
246
- metadata: UserMetadata(
247
- creationTime: nil,
248
- lastSignInTime: ISO8601DateFormatter().string(from: Date()),
249
- lastRefreshTime: nil
250
- ),
251
- refreshToken: nil,
252
- customClaims: nil
253
- )
254
- }
255
-
256
- private func createAuthResult(from msalResult: MSALResult) -> AuthResult {
257
- let account = msalResult.account
258
-
259
- let authUser = AuthUser(
260
- uid: account.homeAccountId?.identifier ?? account.username ?? "",
261
- email: account.username,
262
- emailVerified: account.username?.contains("@") ?? false,
263
- displayName: account.username,
264
- photoURL: nil,
265
- phoneNumber: nil,
266
- isAnonymous: false,
267
- tenantId: account.homeAccountId?.tenantId,
268
- providerData: [
269
- UserInfo(
270
- providerId: provider.rawValue,
271
- uid: account.homeAccountId?.identifier ?? "",
272
- displayName: account.username,
273
- email: account.username,
274
- phoneNumber: nil,
275
- photoURL: nil
276
- )
277
- ],
278
- metadata: UserMetadata(
279
- creationTime: nil,
280
- lastSignInTime: ISO8601DateFormatter().string(from: Date()),
281
- lastRefreshTime: nil
282
- ),
283
- refreshToken: nil,
284
- customClaims: nil
285
- )
286
-
287
- currentUser = authUser
288
-
289
- let credential = AuthCredential(
290
- providerId: provider.rawValue,
291
- signInMethod: "oauth",
292
- accessToken: msalResult.accessToken,
293
- idToken: msalResult.idToken,
294
- refreshToken: nil,
295
- expiresAt: Int(msalResult.expiresOn?.timeIntervalSince1970 ?? 0) * 1000,
296
- tokenType: "Bearer",
297
- scope: msalResult.scopes.joined(separator: " "),
298
- rawNonce: nil
299
- )
300
-
301
- storage.saveCredential(credential, for: provider)
302
-
303
- return AuthResult(
304
- user: authUser,
305
- credential: credential,
306
- additionalUserInfo: AdditionalUserInfo(
307
- isNewUser: false,
308
- providerId: provider.rawValue,
309
- profile: nil,
310
- username: account.username
311
- ),
312
- operationType: "signIn"
313
- )
314
- }
315
- }