如何使用Slim PHP验证登录

时间:2015-05-24 17:31:10

标签: angularjs authentication pdo login slim

我正在使用AngularJS(前端),Slim Framework(后端),PHP和MySQL。我试图用数据库存储的值验证用户电子邮件和密码,但我能够使用不正确的电子邮件和密码登录。我看不出我的问题在哪里。请帮我!这是我的代码

的login.html

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;


public class DataListActivity extends ActionBarActivity {
    ListView listView;
    SQLiteDatabase sqLiteDatabase;
    FoodDbHelper foodDbHelper;
    Cursor cursor;
    ListDataAdapter listDataAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.data_list_layout);
        listView();

        listView = (ListView)findViewById(R.id.list_View);
        listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.row_layout);
        listView.setAdapter(listDataAdapter);
        foodDbHelper = new FoodDbHelper(getApplicationContext());
        sqLiteDatabase = foodDbHelper.getReadableDatabase();
        cursor = foodDbHelper.getInformations(sqLiteDatabase);
        if (cursor.moveToFirst())
        {
            do {
                String name,calorie,fat;
                name = cursor.getString(0);
                calorie = cursor.getString(1);
                fat = cursor.getString(2);
                DataProvider dataProvider = new DataProvider(name,calorie,fat);
                listDataAdapter.add(dataProvider);

            }while (cursor.moveToNext());
        }
    }

    public void listView(){

        List list = new ArrayList();
        ArrayListt ArrayListt = null;


        listView = (ListView)findViewById(R.id.list_View);
        final String ArrayListtt = new String((char[]) null);
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.row_layout, Integer.parseInt(ArrayListtt));
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(
                new AdapterView.OnItemClickListener(){
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                        String ArrayListtt = "You selected " +
                                String.valueOf(adapterView.getItemAtPosition(i));

                        Toast.makeText(DataListActivity.this, "position : " + i + ArrayListtt, Toast.LENGTH_LONG).show();

                    }



                });
    }



}

app.js

<form novalidate name="SigninForm" id="add-new-form" method="post" action=""> <div class="form-group">
  <label for="first_name">Email:</label>
  <input class="form-control" type="text" ng-model="user.email" required />
</div>

<div class="form-group">
  <label for="address">Password:</label>
  <input class="form-control" type="text" ng-model="user.password" />
</div>
   <button class="btn btn-primary" ng-disabled="SigninForm .$invalid || isUnchanged(user)" id="login" ng-click="signin(user)">Login!</button></form>

的index.php

angular.module('CrudApp', []).
  config(['$routeProvider', function($routeProvider) 
{
  $routeProvider.
when('/', {templateUrl: 'assets/tpl/home.html', controller: HomeCtrl}).
 when('/login-user', {templateUrl: 'assets/tpl/login.html', controller: LoginCtrl}).
otherwise({redirectTo: '/'});
}]);
function HomeCtrl($scope, $http) 
{
  $http.get('api/users').success(function(data) 
  {
    $scope.users = data;
  });
}
function LoginCtrl($scope, $http, $location) {
  $scope.master = {};
  $scope.activePath = null;
  $scope.signin = function(user, AddNewForm) {
    $http.post('api/login_user', user).success(function(){
      $scope.reset();
      $scope.activePath = $location.path('/list-user');
      //alert('No access available.');
    });
    $scope.reset = function() {
      $scope.user = angular.copy($scope.master);
    };
    $scope.reset();
  };
}

1 个答案:

答案 0 :(得分:0)

问题在于,无论用户输入如何,您都会返回成功的结果。 Apache,nginx和PHP的内置Web服务器返回一个默认的HTTP代码200,用于他们可以毫无问题地处理的请求。由于您的路线没有明确失败,因此您的服务器似乎可以通过请求/响应一切正常。

例如,如果用户使用电子邮件或密码为空提交表单,您应该返回包含代码400的响应(错误请求)。此外,如果在数据库中找不到与给定电子邮件和密码匹配的用户,您可能会返回代码401(未授权)。

有关HTTP状态代码的详细信息,请参阅http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

使用正确的状态代码时,login功能可能如下所示:

function login()
{
    $app = Slim::getInstance();
    $request = $app->request();
    $user = json_decode($request->getBody());
    $email = $user->email;
    $password = $user->password;
    if (empty($email) || empty($password)) {
        $error = 'Email and password are required';

        // Bad request
        return jsonResponse($error, 400);
    }
    $sql = "SELECT name, email FROM user "
        . "WHERE email = '$email' AND password = '$password'";
    $db = getConnection();
    $row = array();
    try {
        $result = $db->query($sql); 
        if (!$result) {
            $error = 'Invalid query: ' . mysql_error();

            // Internal server error
            return jsonResponse($error, 500);
        }
        $user = $result->fetchAll(PDO::FETCH_OBJ);
        if (empty($user)) {

            // Unauthorized
            return jsonResponse($error, 401);
        }
        $row["user"] = $user;
        $db = null;
    } catch(PDOException $e) {
        error_log($e->getMessage(), 3, '/var/tmp/php.log');
        $error = array( 'error' => array ( 'text' => $e->getMessage() ) );

        // Internal server error
        return jsonResponse($error, 500);
    }

    // OK, default is 200
    return jsonResponse($row);
}

在上面的代码中,我使用以下函数来避免代码重复。它不属于Slim或PHP,因此如果您想使用它,请将其添加到您的项目中。

function jsonResponse($data, $code = 200)
{
    $app = Slim::getInstance();
    $app->response->setStatus($code);
    $app->response->headers->set(
        'Content-type',
        'application/json; charset=utf-8'
    );
    return $app->response->setBody(json_encode($data));
}