diff --git a/KeKi/Scenes/Login/LoginViewController.swift b/KeKi/Scenes/Login/LoginViewController.swift index 1aec9f8..3381816 100644 --- a/KeKi/Scenes/Login/LoginViewController.swift +++ b/KeKi/Scenes/Login/LoginViewController.swift @@ -158,14 +158,14 @@ extension LoginViewController: ASAuthorizationControllerDelegate, ASAuthorizatio func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) { guard let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential else { return } - if let email = UserDefaults.standard.value(forKey: "appleEmail") { - requestSocialLogin(email: email as! String, provider: "애플") - - } else if let email = appleIDCredential.email { - UserDefaults.standard.set(email, forKey: "appleEmail") + if let email = appleIDCredential.email { // 2번째 애플 로그인부터는 email이 identityToken에 들어있음. requestSocialLogin(email: email, provider: "애플") + } else { + if let tokenString = String(data: appleIDCredential.identityToken ?? Data(), encoding: .utf8) { + let email = decode(jwtToken: tokenString)["email"] as? String ?? "" + requestSocialLogin(email: email, provider: "애플") + } } - } func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) { @@ -175,6 +175,36 @@ extension LoginViewController: ASAuthorizationControllerDelegate, ASAuthorizatio func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor { return self.view.window! } + + // (두번째 이후부터의 애플로그인을 위한 메소드) JWTToken -> dictionary + private func decode(jwtToken jwt: String) -> [String: Any] { + + func base64UrlDecode(_ value: String) -> Data? { + var base64 = value + .replacingOccurrences(of: "-", with: "+") + .replacingOccurrences(of: "_", with: "/") + + let length = Double(base64.lengthOfBytes(using: String.Encoding.utf8)) + let requiredLength = 4 * ceil(length / 4.0) + let paddingLength = requiredLength - length + if paddingLength > 0 { + let padding = "".padding(toLength: Int(paddingLength), withPad: "=", startingAt: 0) + base64 = base64 + padding + } + return Data(base64Encoded: base64, options: .ignoreUnknownCharacters) + } + + func decodeJWTPart(_ value: String) -> [String: Any]? { + guard let bodyData = base64UrlDecode(value), + let json = try? JSONSerialization.jsonObject(with: bodyData, options: []), let payload = json as? [String: Any] else { + return nil + } + return payload + } + + let segments = jwt.components(separatedBy: ".") + return decodeJWTPart(segments[1]) ?? [:] + } }