Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- import WebKit
- import Dispatch
- import UserNotifications
- // === INFOS ===
- // LOGIN URL : https://esam.imageinfrance.com/login
- // email : postmaster@imageinfrance.com
- // mdp : iifIIF130899
- class ViewController: UIViewController {
- @IBOutlet weak var emailTXT: UITextField!
- @IBOutlet weak var passwordTXT: UITextField!
- @IBOutlet weak var connexionBTN: UIButton!
- let device = UIDevice.current
- var csrf_token : String?
- var cookie: [HTTPCookie]?
- override func viewDidLoad() {
- super.viewDidLoad()
- let url = "https://esam.imageinfrance.com/login";
- var req = URLRequest(url: URL(string:url)!)
- req.httpMethod = "POST"
- req.addValue("iOS esam/", forHTTPHeaderField: "User-Agent")
- req.addValue("XMLHttpRequest", forHTTPHeaderField: "XMLHttpRequest")
- req.addValue("application/json", forHTTPHeaderField: "Content-Type")
- req.addValue("application/json", forHTTPHeaderField: "Accept")
- req.httpShouldHandleCookies = true
- let session = URLSession.shared
- session.configuration.httpCookieStorage = HTTPCookieStorage.shared
- session.configuration.httpCookieAcceptPolicy = .always
- session.configuration.httpShouldSetCookies = true
- session.dataTask(with: req, completionHandler: { (data, res, err) in
- if err != nil {
- displayMsg(self, userMsg: "La requete a échoué ! Veuillez recommencer (session.dataTask Error)")
- print("Related Error = \(String(describing: err))")
- return
- }
- if let res = res {
- print("Res:: ", (res as! HTTPURLResponse).allHeaderFields)
- self.cookie = HTTPCookie.cookies(withResponseHeaderFields: (res as! HTTPURLResponse).allHeaderFields as! [String:String], for: URL(string: url)!)
- if let cookie = self.cookie {
- print("Cookies : \(cookie)")
- }
- }
- if let data = data {
- print("Data:: ", data)
- do {
- let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any]
- if let jsonData = json {
- self.csrf_token = jsonData["_csrf_token"] as? String
- }
- print(json);
- } catch { print(error) }
- }
- }).resume()
- let model = device.model // ex: "iPhone"
- print(model)
- let modelName = device.modelName // ex: "iPhone 6"
- print(modelName)
- let deviceName = device.name // ex: "My iPhone"
- print(deviceName)
- let systemName = device.systemName // ex: "iOS"
- print(systemName)
- let systemVersion = device.systemVersion // ex: "iOS"
- print(systemVersion)
- }
- override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() }
- override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) }
- @IBAction func connectBTN(_ sender: Any) {
- print("Btn Connect Pressed !");
- DispatchQueue.main.async {
- self.emailTXT.isEnabled = false
- self.passwordTXT.isEnabled = false
- (sender as! UIButton).isEnabled = false
- let email = self.emailTXT.text
- let password = self.passwordTXT.text
- if (email?.isEmpty)! || (password?.isEmpty)! {
- print("User \(String(describing: email)) or password \(String(describing: password)) is empty")
- displayMsg(self, userMsg: "Tous les champs sont requis")
- return
- }
- // Activity Indicator
- let activityIndic = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.whiteLarge)
- activityIndic.center = self.view.center
- activityIndic.hidesWhenStopped = false
- activityIndic.startAnimating()
- self.view.addSubview(activityIndic)
- // Send HTTP Req to sign in
- let finalURL = URL(string: "https://esam.imageinfrance.com/login")
- var req = URLRequest(url: finalURL!)
- req.httpMethod = "POST"
- if let cookie = self.cookie {
- // req.addValue(self.cookie, forHTTPHeaderField: "Cookie")
- print("Cookies : \(cookie)")
- let headers = HTTPCookie.requestHeaderFields(with: cookie)
- if let cookieString = headers["Cookie"] {
- req.addValue(cookieString, forHTTPHeaderField: "Cookie")
- }
- }
- req.addValue("XMLHttpRequest", forHTTPHeaderField: "X-Requested-With")
- req.addValue("iOS", forHTTPHeaderField: "User-Agent")
- req.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
- print("REQ = \(req.allHTTPHeaderFields ?? [:])")
- if let csrf = self.csrf_token {
- let postString = [
- "email" : email!,
- "password": password!,
- "type": UIDevice.current.modelName,
- "_csrf_token": csrf,
- "os": "iOS",
- "version": UIDevice.current.systemVersion,
- "name": UIDevice.current.name,
- ] as [String: String]
- //String.init(format: "email=%@&password=%@", email!, password!)
- var components = URLComponents()
- components.queryItems = postString.map {
- URLQueryItem(name: $0, value: $1)
- }
- if let url = components.url {
- print(url.absoluteString)
- req.httpBody = url.absoluteString.data(using: .utf8)
- }
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.4, execute: {
- let task = URLSession.shared.dataTask(with: req) { (data: Data?, response: URLResponse?, error: Error?) in
- removeActivityIndicator(self, activityIndicator: activityIndic)
- if error != nil {
- displayMsg(self, userMsg: "Erreur pendant la requete ! Veuillez réesayer !")
- print("error=\(String(describing: error))")
- return
- }
- do {
- let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String:Any]
- if let parseJson = json {
- let access_token = parseJson["token"] as? String
- let user_id = parseJson["id"] as? String
- DispatchQueue.main.async {
- let csrf_token: String? = parseJson["_csrf_token"] as? String
- let goToHomePage = self.storyboard?.instantiateViewController(withIdentifier: "HomePageViewController") as! HomePageViewController
- let appDelegate = UIApplication.shared.delegate
- appDelegate?.window??.rootViewController = goToHomePage
- }
- } else {
- displayMsg(self, userMsg: "La requete a échoué 2 - ! Veuillez réésayer")
- }
- } catch {
- displayMsg(self, userMsg: "La requete a échoué 1 - ! Veuillez réesayer")
- print(String.init(data: data!, encoding: .utf8))
- print(error)
- }
- }
- task.resume()
- })
- }
- }
- return
- }
- }
- /*
- private func setCookies(response: URLResponse) {
- if let httpResponse = response as? HTTPCookie {
- let cookies = HTTPCookie.cookies(withResponseHeaderFields: (httpResponse as? HTTPURLResponse)?.allHeaderFields as! [String : String], for: response.url!) as! [HTTPCookie]
- HTTPCookieStorage.shared.setCookies(cookies, for: response.url!, mainDocumentURL: nil)
- for cookie in cookies {
- var cookieProperties = [HTTPCookiePropertyKey: AnyObject]()
- cookieProperties[HTTPCookiePropertyKey.name] = cookie.name as AnyObject
- cookieProperties[HTTPCookiePropertyKey.value] = cookie.value as AnyObject
- cookieProperties[HTTPCookiePropertyKey.domain] = cookie.domain as AnyObject
- cookieProperties[HTTPCookiePropertyKey.path] = cookie.path as AnyObject
- cookieProperties[HTTPCookiePropertyKey.version] = cookie.version as AnyObject
- cookieProperties[HTTPCookiePropertyKey.expires] = NSDate().addingTimeInterval(31536000) as AnyObject
- let newCookie = HTTPCookie(properties: cookieProperties)
- HTTPCookieStorage.shared.setCookie(newCookie!)
- print("name: \(cookie.name) value: \(cookie.value)")
- }
- }
- }
- */
- func displayMsg(_ controller: UIViewController, userMsg:String) -> Void {
- DispatchQueue.main.async {
- let alertCtrl = UIAlertController(title: "Attention", message: userMsg, preferredStyle: .alert)
- let OnOK = UIAlertAction(title: "OK", style: .default) {
- (action: UIAlertAction!) in
- print("Ok Btn !")
- DispatchQueue.main.async {
- controller.dismiss(animated: true, completion: nil)
- }
- }
- alertCtrl.addAction(OnOK)
- controller.present(alertCtrl, animated: true, completion: nil)
- }
- }
- func removeActivityIndicator(_ controller: UIViewController, activityIndicator: UIActivityIndicatorView) {
- DispatchQueue.main.async {
- activityIndicator.stopAnimating()
- activityIndicator.removeFromSuperview()
- }
- }
- extension UIDevice {
- var modelName: String {
- var systemInfo = utsname()
- uname(&systemInfo)
- let machineMirror = Mirror(reflecting: systemInfo.machine)
- let identifier = machineMirror.children.reduce("") { identifier, element in
- guard let value = element.value as? Int8, value != 0 else { return identifier }
- return identifier + String(UnicodeScalar(UInt8(value)))
- }
- switch identifier {
- case "iPod5,1": return "iPod Touch 5"
- case "iPod7,1": return "iPod Touch 6"
- case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
- case "iPhone4,1": return "iPhone 4s"
- case "iPhone5,1", "iPhone5,2": return "iPhone 5"
- case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
- case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
- case "iPhone7,2": return "iPhone 6"
- case "iPhone7,1": return "iPhone 6 Plus"
- case "iPhone8,1": return "iPhone 6s"
- case "iPhone8,2": return "iPhone 6s Plus"
- case "iPhone9,1", "iPhone9,3": return "iPhone 7"
- case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus"
- case "iPhone8,4": return "iPhone SE"
- case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
- case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3"
- case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4"
- case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
- case "iPad5,3", "iPad5,4": return "iPad Air 2"
- case "iPad6,11", "iPad6,12": return "iPad 5"
- case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini"
- case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2"
- case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3"
- case "iPad5,1", "iPad5,2": return "iPad Mini 4"
- case "iPad6,3", "iPad6,4": return "iPad Pro 9.7 Inch"
- case "iPad6,7", "iPad6,8": return "iPad Pro 12.9 Inch"
- case "iPad7,1", "iPad7,2": return "iPad Pro 12.9 Inch 2. Generation"
- case "iPad7,3", "iPad7,4": return "iPad Pro 10.5 Inch"
- case "AppleTV5,3": return "Apple TV"
- case "i386", "x86_64": return "Simulator"
- default: return identifier
- }
- }
- }
- extension ViewController: UITextFieldDelegate {
- func textFieldShouldReturn(_ textField: UITextField) -> Bool {
- if textField == self.emailTXT {
- textField.resignFirstResponder()
- self.passwordTXT.becomeFirstResponder()
- } else if textField == self.passwordTXT {
- textField.resignFirstResponder()
- self.connectBTN(self.connexionBTN!)
- }
- return true
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement