Autoría | Ultima modificación | Ver Log |
//// LoginView.swift// twogetskills//// Created by Efrain Yanez Recanatini on 1/27/22.//import SwiftUIimport Networkimport Alamofireimport SwiftyJSONimport SafariServicesimport RNCryptorstruct LoginView: View {@Environment(\.openURL) var openURLprivate let colorTitle = UIColor(hex: Config.COLOR_TEXT_VIEW_TITLE);private let colorEditText = UIColor(hex: Config.COLOR_EDIT_TEXT);private let colorButtonIntroBackground = UIColor(hex: Config.COLOR_BUTTON_INTRO_BACKGROUND);private let colorButtonIntroForeground = UIColor(hex: Config.COLOR_BUTTON_INTRO_FOREGROUND);@State private var email: String = "efrain.yanez@leaderslinked.com"@State private var password: String = "Cesa2020$"@State private var goToMain : Bool = false@State private var showProgressView : Bool = false@State private var showInputError : Bool = false;@State private var errorMessageEmail : String = ""@State private var errorMessagePassword : String = ""@State private var presentAlert : Bool = false@State private var titleAlert : String = ""@State private var messageAlert : String = ""var body: some View {GeometryReader { geometry inZStack {NavigationLink(destination: MainView(),isActive: self.$goToMain,label: {Text("")})VStack {Image(uiImage: UIImage(named: "logo") ?? UIImage()).resizable().aspectRatio(contentMode: .fit).frame(width: geometry.size.width * 0.5).padding(EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16))/*.background(Color.white).cornerRadius(8.0).shadow(radius: 4.0)*/Text("¿Ya tienes una cuenta? Registrarse").font(.headline).foregroundColor(Color(colorTitle ?? .red)).padding(.top, 10)TextField("Email", text: self.$email).frame(height: 35).textFieldStyle(PlainTextFieldStyle()).padding([.horizontal], 4).background(Color(colorEditText ?? .red)).cornerRadius(16).overlay(RoundedRectangle(cornerRadius: 16).stroke(Color.gray)).padding([.horizontal], 24).font(.system(size: 14.0))//if !self.errorMessageEmail.isEmpty {Text(self.errorMessageEmail).foregroundColor(.red).font(.system(size: 12.0)).padding(.top, 5)//}Group {SecureField("Contraseña", text: self.$password).frame(height: 35).textFieldStyle(PlainTextFieldStyle()).padding([.horizontal], 4).background(Color(colorEditText ?? .red)).cornerRadius(16).overlay(RoundedRectangle(cornerRadius: 16).stroke(Color.gray)).padding([.horizontal], 24).font(.system(size: 14.0))}.padding(.top, 5)//if !self.errorMessageEmail.isEmpty {Text(self.errorMessagePassword)// }.foregroundColor(.red).font(.system(size: 12.0)).padding(.top, 5).padding([.horizontal], 4)Button(action: {if(validate()) {signin()}}, label: {Text("ENTRAR").frame(width: 200).padding(.vertical, 12.0).foregroundColor(Color(colorButtonIntroForeground ?? .white)).background(Color(colorButtonIntroBackground ?? .systemBlue)).cornerRadius(10)}).padding(.top, 20)Button(action: {openURL(URL(string: "https://leaderslinked.com/signup")!)}, label: {Text("CREAR CUENTA").frame(width: 200).padding(.vertical, 12.0).foregroundColor(Color(colorButtonIntroForeground ?? .white)).background(Color(colorButtonIntroBackground ?? .systemBlue)).cornerRadius(10)}).padding(.top, 10)Spacer()}.frame(width: geometry.size.width, height: geometry.size.height, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)if(self.showProgressView) {ProgressView().scaleEffect(3, anchor: .center).zIndex(1000)}Spacer()}.alert(isPresented: $presentAlert) {Alert(title: Text(self.titleAlert),message: Text(self.messageAlert),dismissButton: .default(Text("Ok")))}.navigationBarHidden(true)//.navigationBarBackButtonHidden(true).frame(width: geometry.size.width, height: geometry.size.height, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)}}private func signin() -> Void{let preference = Preference.sharedInstancelet device_uuid = preference.deviceUuidprint("signin")print(" aes = \(preference.aes) " )print(" email = \(self.email) " )print(" password = \(self.password) " )let syncDao = SyncDao()if preference.aes.isEmpty {let syncRecord = syncDao.selectOneByType(type: Constants.SYNC_ADAPTER_TYPE_DEVICE)if syncRecord.id > 0 {let syncAdapter = SyncAdapter()syncAdapter.sync {success in}}self.titleAlert = "Dispositivo no registrado"self.messageAlert = "Espere un momento y vuelva a intentarlo"self.presentAlert = truereturn}self.showProgressView = true;let emailData = email.data(using: .utf8)!let emailCipherData = RNCryptor.encrypt(data: emailData, withPassword: preference.aes)let emailEncrypted = emailCipherData.base64EncodedString()let passwordData = password.data(using: .utf8)!let passwordCipherData = RNCryptor.encrypt(data: passwordData, withPassword: preference.aes)let passwordEncrypted = passwordCipherData.base64EncodedString()print(" email encrypted = \(emailEncrypted) " )print(" password encrypted = \(passwordEncrypted) " )let parameters = [Constants.POST_SIGNIN_FIELD_APPLICATION_ID: "\(Constants.GLOBAL_APPLICATION_ID)",Constants.POST_SYNC_FIELD_DEVICE_UUID: device_uuid,Constants.POST_SIGNIN_FIELD_EMAIL: emailEncrypted,Constants.POST_SIGNIN_FIELD_PASSWORD: passwordEncrypted,Constants.POST_SIGNIN_FIELD_ENCRYPTER: Constants.GLOBAL_ENCRYPTER]let headers: HTTPHeaders = [.accept(Constants.HTTP_HEADER_ACCEPT)]print("URL signin : \(Config.URL_SIGNIN)")self.showProgressView = trueAF.request(Config.URL_SIGNIN, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headers).responseJSON{(response) inself.showProgressView = falseswitch response.result {case .success:let json = try? JSON(data: response.data!)print("json : \(json)")if json?["success"] ?? "" != false {let dataService = DataService()if dataService.syncFromServer(json : json) {let now = Date()let dateFormatter = DateFormatter()dateFormatter.dateFormat = Constants.FORMAT_DATETIME_SERVICElet dateOn = dateFormatter.string(from: now)var userLog = UserLogModel()userLog.userUuid = preference.userUuiduserLog.activity = Constants.USER_LOG_ACTIVITY_SIGNINuserLog.addedOn = dateOnlet userLogDao = UserLogDao()userLogDao.insert(record: userLog)var sync = SyncModel()var json = userLog.toJson()json[Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME] = Constants.SYNC_ADAPTER_DATA_TYPE_USER_LOGsync = SyncModel();sync.type = Constants.SYNC_ADAPTER_TYPE_SYNCif let theJSONData = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted),let data = String(data: theJSONData, encoding: String.Encoding.ascii) {sync.data = data}syncDao.insert(record : sync);self.goToMain = true}} else {let message = json?["data"].string ?? ""if !message.isEmpty {self.titleAlert = "Error"self.messageAlert = messageself.presentAlert = true}}returncase .failure :self.titleAlert = "Servidor no encontrado"self.messageAlert = "Ocurrio un error de comunicación"self.presentAlert = truereturn}/*switch response.result {case .success:print("Response Data : \(response.data!) ")let json = try? JSON(data: response.data!)if json?["success"] ?? "" != false {let dataService = DataService()if dataService.syncFromServer(json : json) {self.goToMain = true}} else {let message = json?["data"].string ?? ""if !message.isEmpty {self.titleAlert = "Error"self.messageAlert = messageself.presentAlert = true}}returncase .failure:self.titleAlert = "Servidor no encontrado"self.messageAlert = "Ocurrio un error de comunicación"self.presentAlert = truereturn}*/}}private func validate() -> Bool{self.errorMessageEmail = ""self.errorMessagePassword = ""print("validate - email : \(email)")print("validate - password : \(password)")var isOk = trueif email.isEmpty {self.errorMessageEmail = "No puede estar en blanco"isOk = false}if !checkEmail(email: email) {self.errorMessageEmail = "Formato invalido"isOk = false}if password.isEmpty {self.errorMessagePassword = "No puede estar en blanco"isOk = false}if(!checkPassword(password: password)) {self.errorMessagePassword = "Formato invalido"isOk = false}return isOk}private func checkEmail(email : String) -> Bool {let regex = #"^[a-zA-Z0-9_\-\.~]{2,}@[a-zA-Z0-9_\-\.~]{2,}\.[a-zA-Z]{2,}$"#let predicate = NSPredicate(format: "SELF MATCHES %@", regex)return predicate.evaluate(with: email) ? true : false;}private func checkPassword(password : String) -> Bool {let regexOld = #"^(?=.*\d+)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{6,16}$"#let regexNew = #"^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[\#\?\!\@\$\^\%\*\-]).{6,16}$"#let predicateNew = NSPredicate(format: "SELF MATCHES %@", regexNew)let predicateOld = NSPredicate(format: "SELF MATCHES %@", regexOld)if(predicateOld.evaluate(with: password)) {return true} else if(predicateNew.evaluate(with: password)) {return true} else {return false}}}struct LoginView_Previews: PreviewProvider {static var previews: some View {LoginView()}}