Categories: php, ios, swift, alamofire, swift5

How would I authentication users logging in to my iOS app with alamofire in swift 5?

2 answers

I thought I finished my login system but it turned out I could write random letters and to be able to proceed to my tab bar controller. The information didn't authenticate. This is my first app and I'm not sure where to start. Any help on this problem?

Here is my login.php code:

<?php  //Step 1 Check variables passing to this file via POST $username = htmlentities($_REQUEST["username"]); $password = htmlentities($_REQUEST["password"]);  if (empty($username) || empty($password)) {   $returnArray["status"] = "400";   $returnArray["message"] = "Missing required information";   echo json_encode($returnArray);   return; }  //Step 2. Build connection //Secure way to build conn $file = parse_ini_file("../../../iHertzmusic.ini");  // store in php var inf from ini var $host = trim($file["dbhost"]); $user = trim($file["dbuser"]); $pass = trim($file["dbpass"]); $name = trim($file["dbname"]);  // include access.php to call func from access.php file require ("secure/access.php"); $access = new access($host, $user, $pass, $name); $access->connect();  //Step 3. Get user information //Assign result of execution of getUser to $user var $user = $access->getUser($username);  //if we did not get any user information if (empty($user)) {     $returnArray["statusCode"] = "403";     $returnArray["message"] = "User is not found";     echo json_encode($returnArray);     return; }  //Step 4. Check validity of entered password //get password and salt from db $secured_password = $user["password"]; $salt = $user["salt"];  // check do passwords match: from db & entered one if ($secured_password == sha1($password . $salt)) {     $returnArray["statusCode"] = "200";     $returnArray["message"] = "Logged in successfully";     $returnArray["id"] = $user["id"];     $returnArray["username"] = $user["username"];     $returnArray["email"] = $user["email"];     $returnArray["fullname"] = $user["fullname"]; } else {     $returnArray["statusCode"] = "403"; //changed     $returnArray["message"] = "passwords do not match";   }  //STEP 5. Close connection $access->disconnect();  //STEP 6. Throw back all infomation to users echo json_encode($returnArray);     ?> 

Here is my .swift code

@IBAction func loginTapped(_ sender: Any) {          // If no text entered         if usernameTextfield.text!.isEmpty || passwordTextField.text!.isEmpty {              //send message if fields are not filled             print("User name \(String(describing: usernameTextfield)) or password \(String(describing: passwordTextField)) is empty")             self.errorLabel.alpha = 1             return         } else {              //Shortcuts             let username = usernameTextfield.text             let password = passwordTextField.text              //send request to sql db             let url = ""              let parameters: Parameters=[              "username":usernameTextfield.text!,              "password":passwordTextField.text!             ]              AF.request(url, method: .post, parameters: parameters as Parameters, encoding:             URLEncoding.default).validate().response { (response) in                      switch response.result {                          case .success:                          //sign in                          let tabVC =                          self.storyboard?.instantiateViewController(identifier: Constants.Storyboard.TabBarController) as? UITabBarController                          self.view.window?.rootViewController = tabVC                          self.view.window?.makeKeyAndVisible()                           case .failure(let error):                          // Couldn't sign in                             self.errorLabel.text = error.localizedDescription                          self.errorLabel.alpha = 1                     }                   } 
Received answers to this question:
The best answer according to the author of the question:

Based on the answer to What is the use of the validate() method in Alamofire.request?:

It would appear that the issue is due to the fact that you are returning the statusCode in the field status and are using a String and not an Int.

Try changing

$returnArray["status"] = "403"; 


$returnArray["statusCode"] = 403; 


$returnArray["status"] = "200"; 


$returnArray["statusCode"] = 200; 

If your php code returns success, you should save some data into app like

UserDefaults.standard.set(true, forKey: "isLoggedIn") 

and then in your appdelegate you should check this value

let isLoggedIn = UserDefaults.standard.bool(forKey: "isLoggedIn")  if isLoggedIn {     // push main view cont } else {     //not logged in show login view  }  

you may need additional data like user info and want to save object see

Save custom objects into NSUserDefaults

this is just for swift code didn't check your php api is correcty written