How to create a login route with slim


#1

Hey, so I am new to Slim Framework and PHP aswell, What I am trying to do is to create a route that validates if the user trying to login actually exists, this is what i have so far

    $app->post('/login', function ($request, $response, $args) {
    $usuario = ($POST['usuario']);
    $input = $request->getParsedBody();
    $sth = $this->db->prepare("SELECT * FROM aldroges8.oficina_virtual_usuarios WHERE 
    usuario='".$usuario."'");
    $result = $sth->execute();

    $row_cnt = $result->num_rows;
    if ($row_cnt>0){
      return $this->response->withJson(array("ok"=>"acceso autorizado"));

    }else{
      return $this->response->withJson(array("error"=>"acceso negado"));

    }
    });

And i tried doing (user in the database) but returns error
curl http://localhost:8080/login -d"usuario=sara"

so anybody can give me a hand on why this is not working?

EDIT:
I did it, i have it now working.

Now i have another question, If I want to add JWT auth, how to I return a token if the user login was successful?


#2

Beware of SQL injections!

If I want to add JWT auth, how to I return a token if the user login was successful?

It depends. Return it from your server however you want to return it. For example in a HTTP response header or/and in a JSON value.

$response = $response->withHeader('Authorization', 'Bearer ' . $token);

https://jwt.io/introduction/


#3

Beware of SQL injections!

Do i avoid SQL injections with this way?

      $sth = $this->db->prepare("SELECT * FROM aldroges8.oficina_virtual_usuarios WHERE 
      usuario=:usuario");

And thanks, I’ll take a look to the documentation


#4

Do i avoid SQL injections with this way?

Prepared statements are good for solving the SQL Injection problem. This works quite good for simple statements. But if you have a lot of “dynamic” SQL queries then better use a SQL Query Builder (e.g. illuminate/database)