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

[Feat] #126 - 로그인 서버 연결 #128

Merged
merged 5 commits into from
Jan 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Spark-iOS/Spark-iOS.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@
F8E3496827969B61001B67E7 /* AuthAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8E3496727969B61001B67E7 /* AuthAPI.swift */; };
F8E3496A27969B67001B67E7 /* AuthService.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8E3496927969B67001B67E7 /* AuthService.swift */; };
F8E3496D2796B7F6001B67E7 /* Signup.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8E3496C2796B7F6001B67E7 /* Signup.swift */; };
F8F6D70027982D6400725537 /* Login.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8F6D6FF27982D6400725537 /* Login.swift */; };
F8F6D6F52797359600725537 /* HabitRoom.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = F8F6D6F42797359600725537 /* HabitRoom.storyboard */; };
F8F6D6F7279735BF00725537 /* HabitRoomVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8F6D6F6279735BF00725537 /* HabitRoomVC.swift */; };
F8F6D6FB2797527A00725537 /* HabitRoomMemberCVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8F6D6F92797527A00725537 /* HabitRoomMemberCVC.swift */; };
Expand Down Expand Up @@ -274,6 +275,7 @@
F8E3496727969B61001B67E7 /* AuthAPI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AuthAPI.swift; sourceTree = "<group>"; };
F8E3496927969B67001B67E7 /* AuthService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AuthService.swift; sourceTree = "<group>"; };
F8E3496C2796B7F6001B67E7 /* Signup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Signup.swift; sourceTree = "<group>"; };
F8F6D6FF27982D6400725537 /* Login.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Login.swift; sourceTree = "<group>"; };
F8F6D6F42797359600725537 /* HabitRoom.storyboard */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; path = HabitRoom.storyboard; sourceTree = "<group>"; };
F8F6D6F6279735BF00725537 /* HabitRoomVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HabitRoomVC.swift; sourceTree = "<group>"; };
F8F6D6F92797527A00725537 /* HabitRoomMemberCVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HabitRoomMemberCVC.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -944,6 +946,7 @@
isa = PBXGroup;
children = (
F8E3496C2796B7F6001B67E7 /* Signup.swift */,
F8F6D6FF27982D6400725537 /* Login.swift */,
);
path = Auth;
sourceTree = "<group>";
Expand Down Expand Up @@ -1147,6 +1150,7 @@
buildActionMask = 2147483647;
files = (
2BC1726D278E8F1000BA3029 /* UIView+.swift in Sources */,
F8F6D70027982D6400725537 /* Login.swift in Sources */,
F8FAA9722790344D00C4190F /* HomeHabitCVC.swift in Sources */,
2B9852072790984C00CE40A7 /* UIViewController+.swift in Sources */,
F82B2E0B278EBC4400219628 /* UserDefaultsKey.swift in Sources */,
Expand Down
13 changes: 8 additions & 5 deletions Spark-iOS/Spark-iOS/Resource/Constants/Header.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,14 @@ import Foundation
extension Const {
struct Header {
/// Content-Type: application/json
static var basicHeader = ["Content-Type": "application/json"]
static let basicHeader = ["Content-Type": "application/json"]
/// access token 을 헤더에 담아서 보내야하는 경우에 사용.
// static var authrizationHeader = ["Content-Type": "application/json",
// "Authorization": accessToken]
static var authrizationHeader = ["Content-Type": "application/json",
"Authorization": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjcxLCJpYXQiOjE2NDI1NzU5MjksImV4cCI6MTY0NTE2NzkyOSwiaXNzIjoic3BhcmsifQ.na6paylY4-2dGBLcTtalxaJc-Xt380MnqSJV2JyC64I"]
static let authorizationHeader = ["Content-Type": "application/json",
"Authorization": accessToken]
// static var authorizationHeader = ["Content-Type": "application/json",
// "Authorization": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjcxLCJpYXQiOjE2NDI1NzU5MjksImV4cCI6MTY0NTE2NzkyOSwiaXNzIjoic3BhcmsifQ.na6paylY4-2dGBLcTtalxaJc-Xt380MnqSJV2JyC64I"]
static let multipartHeader = ["Content-Type": "multipart/form-data"]
static let multipartAuthorizationHeader = ["Content-Type": "multipart/form-data",
"Authorization": accessToken]
Comment on lines +15 to +21
Copy link
Member

Choose a reason for hiding this comment

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

헤더를 이렇게 나눠줄 수 있군뇨!! 잘 배워갑니다!

}
}
20 changes: 20 additions & 0 deletions Spark-iOS/Spark-iOS/Source/NetworkModels/Auth/Login.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//
// Login.swift
// Spark-iOS
//
// Created by kimhyungyu on 2022/01/19.
//

import Foundation

// MARK: - Login

struct Login: Codable {
let accesstoken: String?
let isNew: Bool

enum CodingKeys: String, CodingKey {
case accesstoken
case isNew
}
}
41 changes: 38 additions & 3 deletions Spark-iOS/Spark-iOS/Source/NetworkServices/Auth/AuthAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ public class AuthAPI {
static let shared = AuthAPI()
var userProvider = MoyaProvider<AuthService>(plugins: [MoyaLoggerPlugin()])

public init() { }
// 객체화할 수 없게 만들어서 싱글톤 패턴으로만 사용하도록 접근 제어자 설정.
private init() { }

func signup(socailID: String, profileImg: UIImage, nickname: String, fcmToken: String, completion: @escaping (NetworkResult<Any>) -> Void) {
userProvider.request(.signup(socialId: socailID, profileImg: profileImg, nickname: nickname, fcmToken: fcmToken)) { result in
userProvider.request(.signup(socialID: socailID, profileImg: profileImg, nickname: nickname, fcmToken: fcmToken)) { result in
switch result {
case .success(let response):
let statusCode = response.statusCode
Expand All @@ -31,8 +32,42 @@ public class AuthAPI {
}
}

private func judgeSignupStatus(by statusCode: Int, _ data: Data) -> NetworkResult<Any> {
func login(socialID: String, fcmToken: String, completion: @escaping (NetworkResult<Any>) -> Void) {
userProvider.request(.login(socialID: socialID, fcmToken: fcmToken)) { result in
switch result {
case .success(let response):
let statusCode = response.statusCode
let data = response.data

let networkResult = self.judgeLoginStatus(by: statusCode, data)
completion(networkResult)

case .failure(let err):
print(err)
}
}
}

private func judgeLoginStatus(by statusCode: Int, _ data: Data) -> NetworkResult<Any> {
let decoder = JSONDecoder()
guard let decodedData = try? decoder.decode(GenericResponse<Login>.self, from: data)
else {
return .pathErr
}

switch statusCode {
case 200:
return .success(decodedData.data ?? "None-Data")
case 400..<500:
return .requestErr(decodedData.message)
case 500:
return .serverErr
default:
return .networkFail
}
}

private func judgeSignupStatus(by statusCode: Int, _ data: Data) -> NetworkResult<Any> {
let decoder = JSONDecoder()
guard let decodedData = try? decoder.decode(GenericResponse<Signup>.self, from: data)
else {
Expand Down
15 changes: 13 additions & 2 deletions Spark-iOS/Spark-iOS/Source/NetworkServices/Auth/AuthService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import Foundation
import Moya

enum AuthService {
case signup(socialId: String, profileImg: UIImage, nickname: String, fcmToken: String)
case signup(socialID: String, profileImg: UIImage, nickname: String, fcmToken: String)
case login(socialID: String, fcmToken: String)
}

extension AuthService: TargetType {
Expand All @@ -21,13 +22,17 @@ extension AuthService: TargetType {
switch self {
case .signup:
return "/auth/signup"
case .login:
return "/auth/doorbell"
}
}

var method: Moya.Method {
switch self {
case .signup:
return .post
case .login:
return .get
}
}

Expand All @@ -47,13 +52,19 @@ extension AuthService: TargetType {
multiPartData.append(profileImgData)

return .uploadMultipart(multiPartData)
case .login(let socialID, let fcmToken):
return .requestParameters(parameters: ["socialId": socialID,
"fcmToken": fcmToken],
encoding: URLEncoding.queryString)
}
}

var headers: [String: String]? {
switch self {
case .signup:
return Const.Header.authrizationHeader
return Const.Header.basicHeader
case .login:
return Const.Header.basicHeader
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ extension FeedService: TargetType {
var headers: [String : String]? {
switch self {
case .feedFetch:
return Const.Header.authrizationHeader
return Const.Header.authorizationHeader
case .feedLike:
return Const.Header.authrizationHeader
return Const.Header.authorizationHeader
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ extension HomeService: TargetType {
var headers: [String: String]? {
switch self {
case .habitRoomFetch:
return Const.Header.authrizationHeader
return Const.Header.authorizationHeader
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ extension MyRoomService: TargetType {
var headers: [String: String]? {
switch self {
case .myRoomFetch, .myRoomCertiFetch:
return Const.Header.authrizationHeader
return Const.Header.authorizationHeader
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -122,21 +122,21 @@ extension RoomService: TargetType {
var headers: [String: String]? {
switch self {
case .waitingFetch:
return Const.Header.authrizationHeader
return Const.Header.authorizationHeader
case .codeJoinCheckFetch:
return Const.Header.authrizationHeader
return Const.Header.authorizationHeader
case .enterRoom:
return Const.Header.authrizationHeader
return Const.Header.authorizationHeader
case .waitingMemberFetch:
return Const.Header.authrizationHeader
return Const.Header.authorizationHeader
case .authUpload:
return Const.Header.authrizationHeader
return Const.Header.authorizationHeader
case .createRoom:
return Const.Header.authrizationHeader
return Const.Header.authorizationHeader
case .sendSpark:
return Const.Header.authrizationHeader
return Const.Header.authorizationHeader
case .startRoom:
return Const.Header.authrizationHeader
return Const.Header.authorizationHeader
case .setConsiderRest:
return Const.Header.authrizationHeader
case .habitRoomDetailFetch:
Expand Down
2 changes: 1 addition & 1 deletion Spark-iOS/Spark-iOS/Source/SceneDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {

window = UIWindow(frame: windowScene.coordinateSpace.bounds)
window?.windowScene = windowScene
let rootViewController = UIStoryboard(name: Const.Storyboard.Name.habitRoom, bundle: nil).instantiateViewController(withIdentifier: Const.ViewController.Identifier.habitRoom)
let rootViewController = UIStoryboard(name: Const.Storyboard.Name.splash, bundle: nil).instantiateViewController(withIdentifier: Const.ViewController.Identifier.splash)
window?.rootViewController = rootViewController
window?.makeKeyAndVisible()
}
Expand Down
66 changes: 46 additions & 20 deletions Spark-iOS/Spark-iOS/Source/ViewControllers/Login/LoginVC.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ class LoginVC: UIViewController {
@IBOutlet weak var appleLoginButton: UIButton!
@IBOutlet weak var logoImageView: UIImageView!


// MARK: - View Life Cycle

override func viewDidLoad() {
Expand Down Expand Up @@ -103,10 +102,10 @@ extension LoginVC {
print(error)
} else {
if let userID = user?.id {
self.signupWithAPI(userID: String(userID))

UserDefaults.standard.set(String(userID), forKey: Const.UserDefaultsKey.userID)
UserDefaults.standard.set(String("Kakao@\(userID)"), forKey: Const.UserDefaultsKey.userID)
UserDefaults.standard.set(false, forKey: Const.UserDefaultsKey.isAppleLogin)

self.loginWithAPI(userID: String("Kakao@\(userID)"))
}
}
}
Expand All @@ -121,20 +120,6 @@ extension LoginVC {
}
}

// MARK: - Network

extension LoginVC {

// TODO: - Network. 회원가입 서버통신

private func signupWithAPI(userID: String) {

// TODO: - 엑세스 토큰 userdefaults 등록하고 화면전환

presentToMainTabBar()
}
}

// MARK: - AppleSignIn

extension LoginVC: ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
Expand All @@ -146,11 +131,12 @@ extension LoginVC: ASAuthorizationControllerDelegate, ASAuthorizationControllerP
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
switch authorization.credential {
case let appleIDCredential as ASAuthorizationAppleIDCredential:

let userIdentifier = appleIDCredential.user
signupWithAPI(userID: userIdentifier)

UserDefaults.standard.set("Apple@\(userIdentifier)", forKey: Const.UserDefaultsKey.userID)
UserDefaults.standard.set(true, forKey: Const.UserDefaultsKey.isAppleLogin)

loginWithAPI(userID: "Apple@\(userIdentifier)")
default:
break
}
Expand All @@ -161,3 +147,43 @@ extension LoginVC: ASAuthorizationControllerDelegate, ASAuthorizationControllerP
// Handle error.
}
}

// MARK: - Network

extension LoginVC {
private func loginWithAPI(userID: String) {
AuthAPI.shared.login(socialID: userID, fcmToken: UserDefaults.standard.string(forKey: Const.UserDefaultsKey.fcmToken) ?? "") { response in
switch response {
case .success(let data):
if let data = data as? Login {
if data.isNew {
// 회원가입을 하지 않은 사용자입니다.
guard let nextVC = UIStoryboard(name: Const.Storyboard.Name.profileSetting, bundle: nil).instantiateViewController(withIdentifier: Const.ViewController.Identifier.profileSetting) as? ProfileSettingVC else { return }

nextVC.modalPresentationStyle = .fullScreen

self.present(nextVC, animated: true, completion: nil)
} else {
// 회원 정보를 불러왔습니다.
UserDefaults.standard.set(data.accesstoken, forKey: Const.UserDefaultsKey.accessToken)

guard let nextVC = UIStoryboard(name: Const.Storyboard.Name.mainTabBar, bundle: nil).instantiateViewController(withIdentifier: Const.ViewController.Identifier.mainTabBar) as? MainTBC else { return }

nextVC.modalPresentationStyle = .fullScreen
nextVC.modalTransitionStyle = .crossDissolve

self.present(nextVC, animated: true, completion: nil)
}
}
case .requestErr(let message):
print("loginWithAPI - requestErr: \(message)")
case .pathErr:
print("loginWithAPI - pathErr")
case .serverErr:
print("loginWithAPI - serverErr")
case .networkFail:
print("loginWithAPI - networkFail")
}
}
}
}
Loading