AuthService.swift 4.66 KB
//
//  NetworkManager.swift
//  InterQR-Internship
//
//  Created by Дмитрий Тимофеев on 25.06.2022.
//

import Foundation
import Alamofire

class AuthService {
    
    static let share = AuthService()
    
    var networkToken: String? {
        get {
            // обязательно ключи на подобии NETWORK_TOKEN выносить в Constants.networkTokenKey
            return UserDefaults.standard.string(forKey: "NETWORK_TOKEN")
        }
        
        set (newValue) {
            UserDefaults.standard.set(newValue, forKey: "NETWORK_TOKEN")
        }
    }
    
    typealias InitWebServiceResponse = (InitResponseModel) -> Void
    typealias StartWebServiceResponse = (StartResponseModel) -> Void
    typealias VerifyWebServiceResponse = (VerifyResponseModel) -> Void
    typealias LoginWebServiceResponse = (LoginResponseModel) -> Void
    typealias LogoutWebServiceResponse = (LogoutResponseModel) -> Void
    typealias FailedHandler = (Error) -> Void
    
    func initRequest(_ model: InitRequestModel, success: @escaping InitWebServiceResponse, fail: @escaping FailedHandler) {
        
        let params = ["device_uuid": model.deviceUUID,
                      "manufacturer": model.manufacturer,
                      "model": model.model,
                      "platform": model.platform,
                      "os_version": model.osVersion,
                      "app_version": model.appVersion] as [String: Any]
        
        AF.request(Constants.baseURL + APIRoutes.initURL.urlString, method: .post, parameters: params, encoding: JSONEncoding.default).responseDecodable(of: InitResponseModel.self ) { response in
            switch response.result {
            case .failure(let error) :
                fail(error)
            case .success(let res) :
                success(res)
            }
        }
    }
    
    func startRequest(_ url: URL, model: StartRequestModel, completion: @escaping StartWebServiceResponse, fail: @escaping FailedHandler) {
        
        let params = ["email_or_number": model.emailOrNumber] as [String: Any]
        
        AF.request(url, method: .post, parameters: params, encoding: JSONEncoding.default).responseDecodable(of: StartResponseModel.self ) { response in
            
            if let error = response.error {
                fail(error)
            } else {
                if let res = response.value {
                    completion(res)
                }
            }
        }
    }
    
    func verifyRequest(_ url: URL, model: VerifyRequestModel, completion: @escaping VerifyWebServiceResponse, fail: @escaping FailedHandler) {
        
        let params = ["email_or_number": model.emailOrNumber,
                      "code": model.code,
                      "second_auth_token": model.secondAuthToken] as [String: Any]
        
        AF.request(url, method: .post, parameters: params, encoding: JSONEncoding.default).responseDecodable(of: VerifyResponseModel.self ) { response in
            
            if let error = response.error {
                fail(error)
            } else {
                if let res = response.value {
                    self.networkToken = res.data.token
                    completion(res)
                }
            }
        }
    }
    
    func loginRequest(_ url: URL, model: LoginRequestModel, completion: @escaping LoginWebServiceResponse, fail: @escaping FailedHandler) {
        let headers = ["Authorization": "Bearer \(self.networkToken ?? "")"]
        let params = ["device_uuid": model.deviceUUID] as [String: Any]
        AF.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: HTTPHeaders(headers), interceptor: nil).responseDecodable(of: LoginResponseModel.self ) { response in
            if let error = response.error {
                fail(error)
            } else {
                if let res = response.value {
                    completion(res)
                }
            }
        }
    }
    
    func logoutRequest(_ url: URL, model: LogoutRequestModel, completion: @escaping LogoutWebServiceResponse, fail: @escaping FailedHandler) {
        let headers = ["Authorization": "Bearer \(self.networkToken ?? "")"]
        let params = ["device_uuid": model.deviceUUID] as [String: Any]
        
        AF.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: HTTPHeaders(headers), interceptor: nil).responseDecodable(of: LogoutResponseModel.self ) { response in
            
            if let error = response.error {
                fail(error)
            } else {
                if let res = response.value {
                    completion(res)
                }
            }
        }
    }
}