2 Replies - 768 Views - Last Post: 17 August 2015 - 04:59 PM Rate Topic: -----

#1 graffix857   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 17-August 15

Changing PHP site to use REST for data access and need some help

Posted 17 August 2015 - 01:18 PM

Hi all, I currently have a web app (php my first once actually) that accesses a MySql database. How I was handling the login was like this: This user enters the username and pw which gets sent to a stored procedure. If they successfully are validated I output a record (contains userid, first name and if they are logged in or not) and I set two session variables, 1 that stores a boolean if they are logged in (1 if they are, 0 if they are not) and the other stores the user id of that user (so I can use later to make sure they only get their data). I then check these session variables to 1.Make sure they are logged in and 2. Make sure they are only requesting their data (userid)

I'm now going to be working on an Android app and make all the data access stuff a rest api that both the app and the website can consume. I modified the login stored procedure so it now will return a token as well. The token is generated on the DB(a hashed value of a couple of fields concatenated). When they log in successfully the token generated is stored in a user token table.(one user, one token) The table also stores a token_expire timestamp. Every time they log in a new token is created(and token_expire is updated). If they try to do something after the token expired (based on the token_expire field) then it should redirect them to login so a new token can be created.

When I do the Android app, dealing with this and storing this token on the client is easy and there are many ways to store it (I was thinking storing it in a local sqlite table, shared_prefs (prob not the best way) etc..) and I would just parse through the json result. So keeping track of the token is easy with the app but my problem comes in with the PHP web site.

So I'm faced with two issues:

Issue 1. Right now I have a php form (with login and password fields) and it posts to a login process page which calls the stored procedure and if all is good redirects them to a dashboard page. Now if I use rest the post action would be something like: api/users/login instead of loginprocess.php correct? But then the api just spits out json and I'm not sure how to hand the result from the api to the php code. As when I change the post action I just get a white page with the json result string. So I need help knowing what to do once the api returns the result. Does this have to be called differently than a normal form submit? Do I just have the form submit call a js funcation that makes the call to the page and parses the result? Similar to something like this but instead of passing the cookie passing the login information?

$opts = array('http' => array('header'=> 'Cookie: ' . $_SERVER['HTTP_COOKIE']."\r\n"));
$context = stream_context_create($opts);
session_write_close(); // unlock the file
$contents = file_get_contents(url, false, $context);


Issue 2. Once this token is generated in MySQL and sent back to the api, I need to pass it back to the PHP(related to #1) but How do I store it so that other pages of the site can send it when it requests the data? I know it has to be sent in the header in future requests and that's not my issue. My issue is where do I store the token on the web client so that other pages can use it? Should I store it in a client cookie? (but then doesn't this go against rest?) Store it in local storage? I'm pretty new to PHP and REST (was a classic ASP guy and just getting back into this stuff. This project is the first personal project for myself to learn this stuff and get the rust out) so I'm just trying to figure out the best way. I do not want to use sessions as that violates REST. I also do not want to use oauth or any 3rd party solution.

I have been reading a lot about this but I'm still unclear as to how to go about these changes to the web version of the app and have it function properly. This is what my rest login api looks like so far (I know this will have to change but I'm stuck here with it):

 function loginUser() {
	     global $app;
	     $req = $app->request(); 
	     $paramUsername = $req->params('username'); 
	     $paramPassword = $req->params('password');
	     $sql = "CALL checkPassword(:username,:password)";
	     try {
		     $dbCon = getConnection();
		     $stmt = $dbCon->prepare($sql);
		     $stmt->bindParam("username", $paramUsername);
		     $stmt->bindParam("password", $paramPassword);
		     $stmt->execute();		
		     $result = $stmt->fetchAll();
		     $loggedin=$result[0]["loggedin"];
		     $uid= $result[0]["uid"];
		     $fname=$result[0]["firstname"];
		     $token=$result[0]["token"];
		     $response["uid"]=$uid;
		     $response["loggedin"]=$loggedin;
		     $response["firstname"]=$fname;
		     $response["token"]=$token;
		     echo  json_encode($response);
		     $dbCon = null;
	     }
	     catch(PDOException $e) {
		     echo '{"error":{"text":'. $e->getMessage() .'}}'; 
	     }
    }


Which returns:

 {"uid":"100","loggedin":"1","firstname":"John","token":"f0165d67221563bef150018276f4f77b7bd1e1763223e"}


Here is what the form looks like calling the api currently:

<form id="login" method="post" action="webservices/api/users/login">
  <input class="my-class" style="width:20em" type="email" name="username" required>
  <input class="my-class" style="width:20em"  type="password" name="password" required>
  <button type="submit" id="SubmitButton" name="submit" "></button>
 </form>


Can anyone recommend the best way to deal with these two issues? Any help would be appreciated. Oh I should mention I'm using slim to help with the rest api's.

TIA

Is This A Good Question/Topic? 0
  • +

Replies To: Changing PHP site to use REST for data access and need some help

#2 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2764
  • View blog
  • Posts: 8,071
  • Joined: 15-January 14

Re: Changing PHP site to use REST for data access and need some help

Posted 17 August 2015 - 03:53 PM

Quote

If they successfully are validated I output a record (contains userid, first name and if they are logged in or not) and I set two session variables, 1 that stores a boolean if they are logged in (1 if they are, 0 if they are not)

What's the boolean for? They just logged in, why would that logged_in flag ever be false?

Quote

Now if I use rest the post action would be something like: api/users/login instead of loginprocess.php correct?

That's the basic idea of REST URLs, but authentication and authorization isn't as straight-forward with REST as you might think. It's actually a little bit counter to the design goals of REST. One aspect of REST is that it is stateless, and you can't really have stateless and also have login sessions (a login session is a state). There has been quite a bit of discussion around that topic though. You'll find a lot of articles that are language-specific, and others that talk about security and REST in a more general sense.

https://www.google.c...=UTF-8&oe=UTF-8

Quote

As when I change the post action I just get a white page with the json result string. So I need help knowing what to do once the api returns the result. Does this have to be called differently than a normal form submit?

Yeah, an API isn't a normal form. The output of the API (JSON, etc) is typically meant to be consumed by an application other than a web browser. If you were just using the browser then you wouldn't really need an API, just web pages. The API is for when you are consuming the service in something other than a web browser, like a custom Android application.

Quote

My issue is where do I store the token on the web client so that other pages can use it? Should I store it in a client cookie? (but then doesn't this go against rest?) Store it in local storage?

Most of the time you aren't using the web browser, just a generic HTTP library to allow your app to communicate with the server. You might not even need REST if you're just building a web application to be consumed in a browser. With an app you would store that kind of thing in a variable that you can access when building the other HTTP requests.

I think I'm a little confused about what you're doing though. Are you trying to use PHP to consume a REST API on another server? On the same server? In the same application?
Was This Post Helpful? 1
  • +
  • -

#3 graffix857   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 17-August 15

Re: Changing PHP site to use REST for data access and need some help

Posted 17 August 2015 - 04:58 PM

Thanks for your reply.

I actually posted on another forum and now it's more clear to me. I was trying to have both the web site version and the mobile app use the api but now I see that they should be different. The api shouldn't consume the service, just the app. I guess that's why I've been rattling my brain trying to make the api useful for both the php web version and the mobile app and been hitting brick walls when dealing with this stuff. So I basically got my answer.. the php website should not use the external api :)

The boolean I store just so when they try to access some other data. I check the boolean to make sure they are logged in, if they are I then check the user_id to make sure it matches the user_id for the data they are returning if so then I query the db and return the data, if they aren't logged in I redirect to a login page and if they are trying to access data not associated with them it gives them a not authorized error.

It's going to be one application with just a php web ui and then a mobile app. So I will leave the web site alone and then focus on the api for the mobile app to consume

Thanks again!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1