How to do a search in an app using Angularjs with correct parameter passage?

Asked

Viewed 194 times

0

How to do a search in an app using Angularjs with parameter passage correctly, when I speak correctly I refer to avoid SQL injection.

For example, the parameter var parameters = "joao"; in the query below.

self.searchAll = function(nameSearch){
  var parameters = "joao";

  return DBA.query('SELECT id, name FROM users WHERE name  ?', parameters)
    .then(function(result){
      return DBA.getAll(result);
    });
}
  • 3

    It would not be better (and safer) to leave the statement of query only in the file that is on your server, instead of having it explicit in Frontend? In this case, just make a function call and send only the parameters?

  • @Celsomtrindade, of course it would be, but I would like to know if there is any solution in Frontend for this.

  • 1

    Frontend solutions like the one mentioned in your example reveal your database structure for malicious users, thus increasing the 'exposed surface' of your application, something not exactly recommended from a security point of view.

  • what is DBA ? is a Rest that takes a query as parameter ?

1 answer

1


It is not safe and much less advisable to leave the query exposed in this way.

I advise you to work with Restful. If you work with PHP, you can use a microframework for this. I use and quite like the Slim Framework.

In my projects, I usually follow this structure:

In the example below, I make a Controller (usuario.controller.js), which sends the request to a Service (service.js) and this in turn returns the data that was requested from the application backend (/app/users/index.php).

# usuario.controller.js
...
angular.controller('UsuarioCtrl', Usuario);
...
function Usuario($scope,$stateParams,api) {

    api.getUsuario($stateParams.id).success(function(data){
        $scope.usuario = data.usuario;
    });

}
...


# service.js
...
angular.service('api', Api);
...
function Api($http,$rootScope) {

    this.getUsuario = function (id) {
        return $http.get("/app/api/usuarios/"+ id) || [];
    };
}
...


# /app/usuarios/index.php
...
function getUsuario($id){

    $sql = "
        SELECT id,nome,email
        FROM usuarios
        WHERE id = :id
    ";
    try {
        $con = getConnection();
        $stmt = $con->prepare($sql);
        $stmt->execute(array('id' => $id));
        $usuario = $stmt->fetchAll(PDO::FETCH_OBJ);

        echo json_encode(array("usuario"=>$usuario[0]));
    } catch (Exception $e) {
        echo '{"error":"' . $e->getMessage() . '"}';
    }
}
...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.