-
Notifications
You must be signed in to change notification settings - Fork 0
[Feature] 애플 로그인 구현 #25
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| <?xml version="1.0" encoding="UTF-8"?> | ||
| <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> | ||
| <plist version="1.0"> | ||
| <dict/> | ||
| </plist> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| // | ||
| // LoginViewModel.swift | ||
| // Mark-In | ||
| // | ||
| // Created by 이정동 on 5/1/25. | ||
| // | ||
|
|
||
| import Foundation | ||
| import AuthenticationServices | ||
| import SwiftUI | ||
|
|
||
| import FirebaseAuth | ||
|
|
||
| import Util | ||
|
|
||
| @Observable | ||
| final class LoginViewModel: Reducer { | ||
| struct State { | ||
| var isSignInSuccess: Bool = false | ||
| } | ||
|
|
||
| enum Action { | ||
| case appleLoginButtonTapped(AuthorizationController) | ||
|
|
||
| case signInError(SignInError) | ||
|
|
||
| case firebaseAuthRequest(AuthCredential) | ||
| case firebaseAuthResponse(Result<Void, Error>) | ||
|
|
||
| case empty | ||
| } | ||
|
|
||
| private(set) var state: State = .init() | ||
|
|
||
| func send(_ action: Action) { | ||
| let effect = reduce(state: &state, action: action) | ||
| handleEffect(effect) | ||
| } | ||
|
|
||
| func reduce(state: inout State, action: Action) -> Effect<Action> { | ||
| switch action { | ||
| case .appleLoginButtonTapped(let authController): | ||
| /// 1. 애플 로그인 요청을 위한 객체 생성 | ||
| let requestProvider = SignInWithAppleRequestProvider() | ||
| let request = requestProvider.makeRequest() | ||
|
|
||
| /// 2. 애플 로그인 인증 요청 | ||
| return .run { [nonce = requestProvider.currentNonce] in | ||
|
|
||
| /// 중간에 로그인을 취소하거나, 애플 로그인 인증 방식이 아닌 경우는 빈 액션 반환 | ||
| /// (에러 상황은 아니고, 어떠한 액션을 던질 필요가 없음) | ||
| guard let result = try? await authController.performRequest(request), | ||
| case let .appleID(idCredential) = result else { return .empty } | ||
|
|
||
| /// 애플 로그인 정보에 필요한 정보들이 누락되는 경우 | ||
| guard let nonce, | ||
| let appleIDToken = idCredential.identityToken, | ||
| let idTokenString = String(data: appleIDToken, encoding: .utf8) else { | ||
| return .signInError(.invalid) | ||
| } | ||
|
|
||
| /// Firebase 인증 요청을 위한 AuthCredential 생성 | ||
| let credential = OAuthProvider.appleCredential( | ||
| withIDToken: idTokenString, | ||
| rawNonce: nonce, | ||
| fullName: idCredential.fullName | ||
| ) | ||
|
|
||
| return .firebaseAuthRequest(credential) | ||
| } | ||
|
|
||
| // TODO: 에러 처리 필요 | ||
| case .signInError(_): | ||
| return .none | ||
|
|
||
| // TODO: 현재는 러프하고 구현된 상태. 구글 로그인까지 구현 후 디테일 수정 | ||
| case .firebaseAuthRequest(let credential): | ||
| return .run { | ||
| do { | ||
| /// Firebase 인증 요청 | ||
| let _ = try await Auth.auth().signIn(with: credential) | ||
|
|
||
| return .firebaseAuthResponse(.success(())) | ||
| } catch { | ||
| return .firebaseAuthResponse(.failure(error)) | ||
| } | ||
| } | ||
|
|
||
| case .firebaseAuthResponse(let result): | ||
| switch result { | ||
| case .success(_): | ||
| state.isSignInSuccess = true | ||
| case .failure(let error): | ||
| // TODO: 에러 처리 필요 | ||
| let _ = error as? AuthErrorCode | ||
| break | ||
| } | ||
| return .none | ||
|
|
||
| case .empty: | ||
| return .none | ||
| } | ||
| } | ||
|
|
||
| private func handleEffect(_ effect: Effect<Action>) { | ||
| switch effect { | ||
| case .none: | ||
| break | ||
| case .run(let action): | ||
| Task { | ||
| let newAction = await action() | ||
| send(newAction) | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| extension LoginViewModel { | ||
| enum SignInError: Error { | ||
| case invalid | ||
| } | ||
| } |
54 changes: 54 additions & 0 deletions
54
Mark-In/Sources/Feature/Login/SignInWithAppleRequestProvider.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| // | ||
| // SignInWithAppleRequestProvider.swift | ||
| // Mark-In | ||
| // | ||
| // Created by 이정동 on 5/2/25. | ||
| // | ||
|
|
||
| import Foundation | ||
| import CryptoKit | ||
| import AuthenticationServices | ||
|
|
||
| final class SignInWithAppleRequestProvider { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 인터페이스 분리하면 좋을 것 같아요~ |
||
|
|
||
| private(set) var currentNonce: String? | ||
|
|
||
| func makeRequest() -> ASAuthorizationAppleIDRequest { | ||
| let nonce = self.randomNonceString() | ||
| let appleIDProvider = ASAuthorizationAppleIDProvider() | ||
| let request = appleIDProvider.createRequest() | ||
| request.requestedScopes = [.fullName, .email] | ||
| request.nonce = self.sha256(nonce) | ||
| self.currentNonce = nonce | ||
| return request | ||
| } | ||
|
|
||
| private func randomNonceString(length: Int = 32) -> String { | ||
| precondition(length > 0) | ||
| var randomBytes = [UInt8](repeating: 0, count: length) | ||
| let errorCode = SecRandomCopyBytes(kSecRandomDefault, randomBytes.count, &randomBytes) | ||
| if errorCode != errSecSuccess { | ||
| fatalError( | ||
| "Unable to generate nonce. SecRandomCopyBytes failed with OSStatus \(errorCode)" | ||
| ) | ||
| } | ||
|
|
||
| let charset: [Character] = | ||
| Array("0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._") | ||
|
|
||
| let nonce = randomBytes.map { byte in | ||
| // Pick a random character from the set, wrapping around if needed. | ||
| charset[Int(byte) % charset.count] | ||
| } | ||
|
|
||
| return String(nonce) | ||
| } | ||
|
|
||
| private func sha256(_ input: String) -> String { | ||
| let inputData = Data(input.utf8) | ||
| let hashedData = SHA256.hash(data: inputData) | ||
| let hashString = hashedData.compactMap { String(format: "%02x", $0) }.joined() | ||
|
|
||
| return hashString | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
a-z 정렬하면 더 좋아요