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] 비밀번호 변경 인증 뷰 서버 연결 #63 #64

Open
wants to merge 14 commits into
base: develop
Choose a base branch
from
Open
8 changes: 6 additions & 2 deletions Hyangyu/Hyangyu/Resources/Constants/URL.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,22 @@ extension Const {
static let signUpURL = "/user/signup"

// 로그인 (POST)

static let signInURL = "/auth"

// 비밀번호 찾기(POST)
static let findPasswordURL = "/send-email"

// 비밀번호 변경 (POST)
static let passwordURL = "/user/password"

// 인증번호 동일 확인 (DELETE)
static let checkCodeURL = "/authnum"

// MARK: - Saved - My Page Saved Service

// 전시회 저장 (POST), 전시회 취소(DELETE), 전시회 조회 (GET), 카테고리 - 전시회(GET)
static let displayURL = "/display"


// MARK: - My Page - User Service

// 닉네임 변경 (POST)
Expand Down
2 changes: 0 additions & 2 deletions Hyangyu/Hyangyu/Sources/APIModels/Auth.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,3 @@ struct CodeData: Codable {
struct EmailCheckData: Codable {
let message: String
}


38 changes: 27 additions & 11 deletions Hyangyu/Hyangyu/Sources/APIServices/AuthAPI/PasswordAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,16 @@ public class PasswordAPI {

public init() { }

func putNewPassword(completion: @escaping (NetworkResult<Any>) -> Void, email: String, password: String) {
courseProvider.request(.putChangedPassword(email: email, password: password)) { (result) in
func postNewPassword(completion: @escaping (NetworkResult<Any>) -> Void, email: String, password: String) {
courseProvider.request(.postChangedPassword(email: email, password: password)) { (result) in
print(result)
switch result {
case .success(let response):
print("response 제대로 오는지 확인: ", response)
let statusCode = response.statusCode
let data = response.data

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

case .failure(let err):
Expand All @@ -31,13 +33,28 @@ public class PasswordAPI {
}
}

func getEmailCode(completion: @escaping (NetworkResult<Any>) -> Void, email: String) {
courseProvider.request(.getEmailCode(email: email)) { (result) in
func postEmailCode(completion: @escaping (NetworkResult<Any>) -> Void, email: String) {
courseProvider.request(.postEmailCode(email: email)) { (result) in
switch result {
case .success(let response):
let statusCode = response.statusCode
let data = response.data
let networkResult = self.judgeGetEmailCodeStatus(by: statusCode, data)
let networkResult = self.judgeStatus(by: statusCode, data)
completion(networkResult)

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

func checkCode(completion: @escaping (NetworkResult<Any>) -> Void, email: String, authNum: String) {
courseProvider.request(.checkCode(email: email, authNum: authNum)) { (result) in
switch result {
case .success(let response):
let statusCode = response.statusCode
let data = response.data
let networkResult = self.judgeStatus(by: statusCode, data)
completion(networkResult)

case .failure(let err):
Expand Down Expand Up @@ -67,16 +84,16 @@ public class PasswordAPI {
}
}

private func judgeGetEmailCodeStatus(by statusCode: Int, _ data: Data) -> NetworkResult<Any> {

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

switch statusCode {
case 200:
return .success(decodedData.data)
return .success(decodedData.message)
case 400..<500:
return .requestErr(decodedData.message)
case 500:
Expand All @@ -86,4 +103,3 @@ public class PasswordAPI {
}
}
}

35 changes: 23 additions & 12 deletions Hyangyu/Hyangyu/Sources/APIServices/AuthAPI/PasswordService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ import Foundation
import Moya

enum PasswordService {
case putChangedPassword(email: String, password: String)
case getEmailCode(email: String)
case postChangedPassword(email: String, password: String)
case postEmailCode(email: String)
case checkCode(email: String, authNum: String)

}

extension PasswordService: TargetType {
Expand All @@ -20,19 +22,23 @@ extension PasswordService: TargetType {

var path: String {
switch self {
case .putChangedPassword(_, _):
case .postChangedPassword(_, _):
return Const.URL.passwordURL
case .getEmailCode(let email):
return Const.URL.passwordURL + "/\(email)"
case .postEmailCode(let email):
return Const.URL.findPasswordURL + "/\(email)"
case .checkCode(let email, let authNum):
return Const.URL.checkCodeURL
}
}

var method: Moya.Method {
switch self {
case .putChangedPassword(_, _):
return .put
case .getEmailCode(_):
return .get
case .postChangedPassword(_, _):
return .post
case .postEmailCode(_):
return .post
case .checkCode(_, _):
return .delete
}
}

Expand All @@ -42,14 +48,20 @@ extension PasswordService: TargetType {

var task: Task {
switch self {
case .putChangedPassword(let email, let password):
case .postChangedPassword(let email, let password):
// body가 있는 request - JSONEncoding.default
return .requestParameters(parameters: [
"email": email,
"username": "",
"password": password
], encoding: JSONEncoding.default)
case .getEmailCode(_):
case .postEmailCode(_):
return .requestPlain
case .checkCode(let email, let authNum):
return .requestParameters(parameters: [
"email": email,
"authNum": authNum
], encoding: JSONEncoding.default)
}
}

Expand All @@ -59,4 +71,3 @@ extension PasswordService: TargetType {
]
}
}

13 changes: 0 additions & 13 deletions Hyangyu/Hyangyu/Sources/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,6 @@ import CoreData

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

// MARK: - Core Data
lazy var persistentContainer: NSPersistentContainer = {
// name: Core Data 만든 파일명 지정
let container = NSPersistentContainer(name: "RecentSearchTerm")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error {
fatalError("Unresolved error, \((error as NSError).userInfo)")
}
})
return container
}()


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
Expand Down
2 changes: 2 additions & 0 deletions Hyangyu/Hyangyu/Sources/AppModels/User.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import UIKit
class User {
static let shared = User()

var email: String?
var username: String?
var profileImage: UIImage?
var password: String?
}
1 change: 0 additions & 1 deletion Hyangyu/Hyangyu/Sources/CustomTabBar/UIColor+RGB.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,3 @@ extension UIColor {
}
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,18 @@ class FindPasswordViewController: UIViewController {

// MARK: - Properties

let user = SignUpUser.shared
let user = User.shared
var isResetCodeEnabled: Bool = false
private var userResetCode: Int = 0
private var isEmailRight: Bool = false

// MARK: - @IBOutlet Properties
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var emailTextFieldView: UIView!
@IBOutlet weak var emailWarningLabel: UILabel!


@IBOutlet weak var nextButton: UIButton!

// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
initNavigationBar()
Expand All @@ -30,6 +32,23 @@ class FindPasswordViewController: UIViewController {
}

// MARK: - Functions
private func addTarget() {
emailTextField.addTarget(self, action: #selector(self.activateEmailTextField), for: .editingDidBegin)
emailTextField.addTarget(self, action: #selector(self.inactivateEmailTextField), for: .editingDidEnd)
}

// 텍스트 필드 확성화
@objc private func activateEmailTextField() {
emailTextFieldView.makeRoundedWithBorder(radius: 12, color: UIColor.systemGray2.cgColor)
}

// 텍스트 필드 비활성화
@objc private func inactivateEmailTextField() {

isEmailRight = checkEmail(email: emailTextField.text ?? "")
emailWarningLabel.isHidden = isEmailRight || !emailTextField.hasText ? true : false
emailTextFieldView.layer.borderColor = isEmailRight || !emailTextField.hasText ? UIColor.systemGray2.cgColor : UIColor.systemRed.cgColor
}

private func initNavigationBar() {
self.navigationController?.initWithBackButton()
Expand All @@ -39,19 +58,17 @@ class FindPasswordViewController: UIViewController {
emailTextField.delegate = self
}


private func configureUI() {
emailTextFieldView.makeRoundedWithBorder(radius: 12, color: UIColor.systemGray2.cgColor)
nextButton.makeRounded(radius: 20)
emailTextFieldView.makeRoundedWithBorder(radius: 12, color: UIColor.systemGray6.cgColor)
nextButton.makeRounded(radius: 12)

emailWarningLabel.isHidden = true


nextButton.isEnabled = false
}

private func checkEmailFormat(email: String) {
if validateEmail(email: email) {
if checkEmail(email: email) {
nextButton.isEnabled = true
nextButton.alpha = 1.0

Expand All @@ -65,7 +82,7 @@ class FindPasswordViewController: UIViewController {
}
}

func validateEmail(email: String) -> Bool {
private func checkEmail(email: String) -> Bool {
// Email 정규식
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegEx)
Expand All @@ -82,51 +99,45 @@ class FindPasswordViewController: UIViewController {
nextButton.alpha = 0.3
}

func validateCode(code: String) -> Bool {
// Email 정규식
let codeRegEx = "^[0-9]{4}$"
let codeTest = NSPredicate(format: "SELF MATCHES %@", codeRegEx)
return codeTest.evaluate(with: code)
// 화면 터치시 키보드 내림
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}

private func checkCodeFormat(userInput: String) {
if validateCode(code: userInput) {
makeCompleteButtonEnable()
} else {
makeCompleteButtonDisable()
}
}
private func pushToNewPasswordViewController(email: String) {
let resetCodeViewController = ResetCodeViewController.loadFromNib()
resetCodeViewController.email = email
self.navigationController?.pushViewController(resetCodeViewController, animated: true)



private func pushToNewPasswordViewController() {
self.navigationController?.pushViewController(NewPasswordViewController.loadFromNib(), animated: true)
}

@IBAction func touchNextButton(_ sender: Any) {
getCode()
}


}

extension FindPasswordViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
emailWarningLabel.isHidden = true
emailTextFieldView.makeRoundedWithBorder(radius: 12, color: UIColor.systemGray2.cgColor)
}

// 실시간
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else {
return false
}
checkEmailFormat(email: text)
return true
}
// func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// guard let text = textField.text else {
// return false
// }
// return true
// }

// 키보드 내렸을 때 (.co 등 때문에 추가)
func textFieldDidEndEditing(_ textField: UITextField) {
guard let text = textField.text else {
return
}
checkEmailFormat(email: text)
if text != "" {
checkEmailFormat(email: text)
}

emailTextFieldView.makeRoundedWithBorder(radius: 12, color: UIColor.systemGray6.cgColor)
}

Expand All @@ -137,19 +148,23 @@ extension FindPasswordViewController {

if let email = self.emailTextField.text {

PasswordAPI.shared.getEmailCode(completion: { (result) in
PasswordAPI.shared.postEmailCode(completion: { (result) in
switch result {
case .success(let code):

if let data = code as? CodeData {
if let data = code as? String {
self.emailWarningLabel.isHidden = true
self.user.email = email
print("data.message: \(data)")
self.emailWarningLabel.text = "\(data)"
self.pushToNewPasswordViewController(email: email)
}
case .requestErr(let message):
self.emailWarningLabel.isHidden = false
if let message = message as? String {
self.emailWarningLabel.text = "\(message)"
}
self.pushToNewPasswordViewController(email: email)
case .pathErr:
print(".pathErr")
case .serverErr:
Expand Down
Loading