问题描述:

I'm writing a password reset page.

Logic:

  1. User requests pw
  2. It's sent to their email with a unique string (that expires) appended to the /reset/$string
  3. Once at the page in my controller I check if the string matches one in the db, if so then I match that to the userId
  4. If it does, I allow them to enter their new pass
  5. If they POST to the same controller and mess up and enter 2 incorrect passwords, I lose the original URL with the reset string

    so now I don't know which user to update in the db

My options (that I can think of):

  1. Set the string and user ID in a session and look that up in the controller (and make sure to clear this out once the pass is successfully reset)
  2. On step 4 above, I'll add in the user's ID in a hidden input field in the form and POST with that to check which user it is

网友答案:

Your solution in option 2 (add token to a hidden input) makes sense or you could just post the form to the same URL (the one with the token in it so you don't lose it) and structure your logic to work based on whether or not the form was posted.

The logic could look like this:

  • User hits site.com/password/reset/token_here as GET or POST
  • Check token from URL in database to see if its valid and current
  • If request method is POST, check for matching, secure passwords
    • If passwords do not match, assign error message to HTML view
    • If passwords match, change password, delete token, redirect to success page
  • Display form to user - form posts back to same URL w/ the token
网友答案:

I would do this:

  1. The user provides his email in a form and requests password reset.
  2. You check the db for the uid (user id) that matches the email.
  3. If the user exists you make a url like this: http://domain.com/password_reset.php?uid=xxxx&key=fdhgf5115d4f15dfdb5fdf5
  4. The key is generated by the this: $key = md5(uniqid())
  5. You store the key into a session with the uid: $_SESSION['pass_res']['key'] = $key; $_SESSION['pass_res']['uid'] = $uid;
  6. When user click on the url you check if: $_SESSION['pass_res']['uid'] == $_GET['uid'] and if $_SESSION['pass_res']['key'] == $_GET['key']
  7. If they match you allow the user to change his password
  8. And after this unset($_SESSION['pass_res'])
  9. Also if a user close his browser the session expires

By this way only the user with the session id that requested password reset can change his password

相关阅读:
Top