Skip to content
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

회원 탈퇴 애플토큰 revoke 구현 #106

Merged
merged 11 commits into from
Dec 12, 2022
Merged

Conversation

pyj9748
Copy link
Collaborator

@pyj9748 pyj9748 commented Dec 12, 2022

제출 전 필수 확인 사항:

  • Merge 하는 브랜치가 올바른가?
  • 코드 컨벤션을 준수하는가?
  • 빌드가 되는 코드인가요?
  • 버그가 발생하지 않는지 충분히 테스트 해봤나요?

작업 내용:

  • Authorizatioin Code 값 저장
  • JWT(Client Secret) 만들기
  • 회원 탈퇴 시, 로그인 유도하여 유효한 Authorizatioin Code 저장
  • Authorizatioin Code 값을 사용해, refresh Token 얻어오기
  • 회원 탈퇴 시, refresh token을 사용해 token revoke

이번에 공들였던 부분:

JWT Valid 한지 확인하기 위해 학습하는 부분이 어려웠습니다.

Copy link
Member

@trumanfromkorea trumanfromkorea left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

주말동안 정말정말 고생하셨습니다!

영준님께서 고생해주신 덕분에 탈퇴기능을 사용할 수 있게 되었어요 ㅋㅅㅋ

Comment on lines +13 to +43
struct Header: Encodable {
let alg = "ES256"
let kid = "4979Z7MUXJ"
}

struct Payload: Claims {
var iss = "4G6ZD4247R"
var iat = Date().epochIATTimeStamp
var exp = Date().epochEXPTimeStamp
var aud = "https://appleid.apple.com"
var sub = "com.boostcamp.BoogieSpaceCapsule"
}

struct RefreshTokenResponse: Decodable {
let accessToken: String?
let refreshToken: String?
let idToken: String?

init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
accessToken = try? values.decode(String.self, forKey: .accessToken)
refreshToken = try? values.decode(String.self, forKey: .refreshToken)
idToken = try? values.decode(String.self, forKey: .idToken)
}

enum CodingKeys: String, CodingKey {
case accessToken = "access_token"
case refreshToken = "refresh_token"
case idToken = "id_token"
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

파일 분리 부탁드립니다 ( _ _)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

넵 알겠습니다.

Comment on lines +73 to +76
if let error = error {
print(error.localizedDescription)
completion(error)
} else {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

guard let 쓰면 아래 코드 indent 가 줄어들어서 가독성이 더 좋을 것 같아용 ㅎㅎ

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

참고하겠습니다.

Comment on lines +46 to +56
func downloadAuthP8(urlString: String, completion: @escaping (Data?) -> Void) {
let storageReference = storage.reference(forURL: urlString)
let megaByte = Int64(1 * 1024 * 1024)
storageReference.getData(maxSize: megaByte) { data, _ in
guard let data = data else {
completion(nil)
return
}
completion(data)
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

좋네요 👍

Comment on lines +208 to +251
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
}

// Adapted from https://auth0.com/docs/api-auth/tutorials/nonce#generate-a-cryptographically-random-nonce
private func randomNonceString(length: Int = 32) -> String {
precondition(length > 0)
let charset: [Character] =
Array("0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._")
var result = ""
var remainingLength = length

while remainingLength > 0 {
let randoms: [UInt8] = (0 ..< 16).map { _ in
var random: UInt8 = 0
let errorCode = SecRandomCopyBytes(kSecRandomDefault, 1, &random)
if errorCode != errSecSuccess {
fatalError(
"Unable to generate nonce. SecRandomCopyBytes failed with OSStatus \(errorCode)"
)
}
return random
}

randoms.forEach { random in
if remainingLength == 0 {
return
}

if random < charset.count {
result.append(charset[Int(random)])
remainingLength -= 1
}
}
}

return result
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

중복되는 부분은 분리해주세요!

VC 에서도 분리하면 좋을것 같아요

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오늘 리팩토링 할 예정입니다.

Comment on lines +105 to +139
var requestBodyComponents = URLComponents()
requestBodyComponents.queryItems = [
URLQueryItem(name: "token", value: refreshToken),
URLQueryItem(name: "client_id", value: "com.boostcamp.BoogieSpaceCapsule"),
URLQueryItem(name: "client_secret", value: clientSecret),
URLQueryItem(name: "token_type_hint", value: "refresh_token"),
]
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = header
request.httpBody = requestBodyComponents.query?.data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { _, response, error in
if let error = error {
print(error.localizedDescription)
return
}
}
auth.currentUser?.delete { error in
if let response = response as? HTTPURLResponse {
print(response.description)
if response.statusCode == 200 {
completion(nil)
return
} else {
completion(ECError.failedEvpInit) // TODO:
return
}
}
if let error = error {
print(error.localizedDescription)
completion(error)
} else {
completion(nil)
}
}
task.resume()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

요청하는 부분도 중복되서 간편화 하면 좋을것 같긴 한데

나중에 저랑 같이해요

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

좋습니당

@trumanfromkorea trumanfromkorea merged commit 41f3f5b into develop Dec 12, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants