Skip to content

Commit ff42349

Browse files
committed
fix(auth): handle 2FA prompts on .unauthorized instead of .badRequest
Updated authentication flow to detect two-factor authentication requirements from .unauthorized responses. Previously, only .badRequest was checked for `AuthFactorTokenRequired`, which caused 2FA to fail when servers returned 401 instead of 400. Now both cases are supported.
1 parent 11bbc81 commit ff42349

File tree

1 file changed

+33
-16
lines changed

1 file changed

+33
-16
lines changed

Sources/ATProtoKit/APIReference/SessionManager/SessionConfiguration.swift

Lines changed: 33 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -269,24 +269,41 @@ extension SessionConfiguration {
269269
)
270270
} catch let error as ATAPIError {
271271
switch error {
272-
case .badRequest(error: let responseError):
273-
if responseError.error == "AuthFactorTokenRequired" {
274-
twoFactorAuthenticationAttempts += 1
275-
if twoFactorAuthenticationAttempts > maxTwoFactorAuthenticationAttempts {
276-
throw ATAPIError.badRequest(error: APIClientService.ATHTTPResponseError(
277-
error: "TooManyTwoFactorAuthenticationAttempts",
278-
message: "Too many invalid two-factor authentication codes. Please try again later."
279-
))
280-
}
281-
282-
// Ask the user for a new code, then continue the loop.
283-
userCode = await waitForUserCode()
284-
continue
285-
} else {
286-
throw error
272+
case .badRequest(error: let responseError):
273+
if responseError.error == "AuthFactorTokenRequired" {
274+
twoFactorAuthenticationAttempts += 1
275+
if twoFactorAuthenticationAttempts > maxTwoFactorAuthenticationAttempts {
276+
throw ATAPIError.badRequest(error: APIClientService.ATHTTPResponseError(
277+
error: "TooManyTwoFactorAuthenticationAttempts",
278+
message: "Too many invalid two-factor authentication codes. Please try again later."
279+
))
287280
}
288-
default:
281+
282+
// Ask the user for a new code, then continue the loop.
283+
userCode = await waitForUserCode()
284+
continue
285+
} else {
289286
throw error
287+
}
288+
case .unauthorized(error: let responseError, wwwAuthenticate: _):
289+
// Handle 2FA requirement that comes as unauthorized instead of badRequest
290+
if responseError.error == "AuthFactorTokenRequired" {
291+
twoFactorAuthenticationAttempts += 1
292+
if twoFactorAuthenticationAttempts > maxTwoFactorAuthenticationAttempts {
293+
throw ATAPIError.badRequest(error: APIClientService.ATHTTPResponseError(
294+
error: "TooManyTwoFactorAuthenticationAttempts",
295+
message: "Too many invalid two-factor authentication codes. Please try again later."
296+
))
297+
}
298+
299+
// Ask the user for a new code, then continue the loop.
300+
userCode = await waitForUserCode()
301+
continue
302+
} else {
303+
throw error
304+
}
305+
default:
306+
throw error
290307
}
291308
} catch {
292309
throw error

0 commit comments

Comments
 (0)