简体   繁体   English

角度验证:http发布未发送请求

[英]Angular authentication : http post not sending request

EDIT : I guess I misplaced my submit button because I ve got it working since then (in fact the request was not sent because my function was not called, classic issue..). 编辑 :我猜我放错了提交按钮,因为自那时以来我一直在使用它(实际上,因为未调用我的函数,所以没有发送请求,这是经典问题..)。

Also , the fact that the authentication was always successful is because the verification via my DB was totally skipped due to the lack of params I guess, so this step was skipped, my http_response_code wasn't called back, and I was directly redirected to my home page... 另外 ,身份验证始终成功的事实是,由于我猜缺少参数,因此完全跳过了通过我的数据库进行的验证,因此跳过了这一步,没有回叫我的http_response_code,我直接重定向到了我的主页...
Not sure if I should answer myself but the question is solved ! 不知道我是否应该回答自己,但问题已解决

I have an Angular app, I'm making authentication through a PHP file (simple yet) with POST params, but when I click on submit, no request is sent and whether my username/password are filled or not (or right, or wrong), the authentication is a success and I go straight to my Home page. 我有一个Angular应用程序,我正在通过带有POST参数的PHP文件(尚简单)进行身份验证,但是当我单击Submit时,没有发送请求,并且是否填写了我的用户名/密码(正确或错误)。 ),验证成功,因此我直接进入主页。
It basically never check if the conditions are ok or not.. 它基本上从不检查条件是否还可以。
My user.service : 我的user.service:

angular
  .module("service")
  .factory("user", userService);

function userService($q, $http) {

  User.userConnected = null;
  User.getUserConnected = getUserConnected;
  User.setUserConnected = setUserConnected;


  // attribution des logs après validation
  function User() {
    this.nom = null;
    this.password = null;
    this.login = login;
  }

  // get last logged user
  function getUserConnected() {
    return User.userConnected;
  }

  // set last connected user as 'main' user
  function setUserConnected(user) {
    User.userConnected = user;
  }

  function login() {
    var there = this;
    var deferred = $q.defer();
    var params = 'nom='+this.nom+'&password='+this.password;
    $http({
        method: 'POST',
        url: '/api',
        data: params,
        headers: {'Content-Type': 'application/json'}
    })
    .success(function (success) {
      there.password = null;
      User.setUserConnected(there);
      deferred.resolve(success);
    })
    .error(function(error){
      deferred.reject(error);
    });
    return deferred.promise;
  }

  return User;
}

My controller : 我的控制器:

//Controller login
.controller('LoginCtrl', function ($http, user, $state, $scope) {

  var vm = this;
  vm.errorMessage = null;
  vm.userLog = new user();
  vm.doLogin = doLogin;

//login -> on récupère les identifiants
  function doLogin() {
    vm.userLog
    .login()
    .then(_userLogged, _userRefused);
  }

// on success, go to Home page
  function _userLogged(success) {
    $state.go('home');
    console.log('OK!!!');
  }

// on error, show error
  function _userRefused(error) {
    vm.errorMessage = 'Combinaison login/mdp incorrect';
  }
})

My login.php : 我的login.php:

<?php

if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');
}

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    exit(0);
}

// host/bdd settings
$hostname = '******.****.com';
$username = '*****';
$password = '*****';
$database = '*****';

try {
$pdo = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
  echo 'Connection bdd ok <br>';
}
catch (Exception $e)
{
        die('Erreur : ' . $e->getMessage());
}

//On récupère les identifiants
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);

$nom = $request->nom;
$password = $request->password;

if ($nom != "") {

  // Vérification des identifiants
  $req = $pdo->prepare('SELECT nom FROM users WHERE (nom = :nom AND password = :password)');
  $req->execute(array(
      'nom' => $nom,
      "password" => $password
    ));

  $rows = ($req->fetch(PDO::FETCH_OBJ));

  if (!$rows) //if pas de résultat correspondant
  {
      echo 'Mauvais identifiant ou mot de passe !';
  }
  else //sinon, tout est bon
  {
      foreach($rows as $row){
      echo json_encode($row);
      echo "<br> Vous êtes connecté !";
      }
  }
}
else {
  echo 'Indiquez votre pseudo';
}

?>

My submit button looks like this: 我的提交按钮如下所示:

 <button class="button button-block button-positive" type="submit" ng-click="vm.doLogin()">Connexion</button>

Its driving me crazy, I really don't get where is my mistake. 它让我发疯,我真的不明白我的错误在哪里。 I am supposed to get my parameters from my http post request, it looks ok to me..Any help will be greatly appreciated !!! 我应该从我的http发布请求中获取参数,对我来说看起来不错。任何帮助将不胜感激!

That's because you are returning HTTP status 200 with different content, even if you found a user or not. 这是因为您将返回具有不同内容的HTTP状态200,即使您是否找到了用户也是如此。 That's why the code Java Script below runs: 这就是下面的代码Java Script运行的原因:

.success(function (success) {
  there.password = null;
  User.setUserConnected(there);
  deferred.resolve(success);
})

If the logic responsible for checking user name and password is implemented properly, then changing: 如果负责检查用户名和密码的逻辑正确实现,则更改:

echo 'Mauvais identifiant ou mot de passe !';

to

die('Mauvais identifiant ou mot de passe !');

should make it working, but it is insecure. 应该使其工作,但这是不安全的。

Please never store user password as a text in your database. 请勿将用户密码以文本形式存储在数据库中。

You should use http://php.net/manual/en/function.password-hash.php or other hashing strategy. 您应该使用http://php.net/manual/en/function.password-hash.php或其他哈希策略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM