Skip to content

Commit

Permalink
fix: 애플로그인 오류 처리
Browse files Browse the repository at this point in the history
  • Loading branch information
ryr0121 committed Mar 28, 2023
1 parent a27a367 commit 30c8bee
Showing 1 changed file with 36 additions and 6 deletions.
42 changes: 36 additions & 6 deletions KeKi/Scenes/Login/LoginViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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]) ?? [:]
}
}


Expand Down

0 comments on commit 30c8bee

Please sign in to comment.