1

from mobile application when i will pass username and password if value will match with the db it should show all the details of user or else username & password invalid.For this i am generating the api. How to encrypt or decrypt the password in drupal8?

class Userverifier extends ResourceBase
{
    public function get($username = 'NULL',$password = 'NULL') {

        $result = \Drupal::database()->select('users_field_data`', 'n')
            ->fields('n', array('uid', 'name', 'pass', 'mail'))
            ->condition('n.name', $username, '=')
            //->condition('n.pass', $decrypted_pass, '=')
            ->execute()->fetchAllAssoc('uid');

        $rows = array();
        foreach ($result as $row => $content) {
            $rows[] = array('data' => array($content->uid, $content->name, $content->pass, $content->mail));
        }
        return new ResourceResponse($rows);
    }
}
Robbie
  • 17,605
  • 4
  • 35
  • 72
Barsa Pati
  • 19
  • 1
  • 2
  • how are your passwords stored in your database ? Plain text or hashed ? If they are hashed than just compare the hash of what the user entered into the password field and don't try to decrypt it. – Igor Ilic Jul 28 '18 at 11:54
  • 1
    Possible duplicate of [Secure hash and salt for PHP passwords](https://stackoverflow.com/questions/401656/secure-hash-and-salt-for-php-passwords) – Progman Jul 28 '18 at 11:59

3 Answers3

0

There is a password interface for this in Drupal:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Password%21PasswordInterface.php/interface/PasswordInterface/8.2.x

There is a similar question on the Drupal StackExchange that gives examples of how to use that interface - not perfect for what you're asking but will help.

https://drupal.stackexchange.com/questions/195669/how-do-i-check-if-the-current-password-that-the-user-gives-in-the-password-reset

This actually uses the user class as opposed to trying to drive the database yourself - something I'd recommend as it's more "future proof".

Robbie
  • 17,605
  • 4
  • 35
  • 72
0

It is not possible to decrypt the password in a Drupal 8 database!

Use code like this to verify the credentials:

$account = User::load($theUsersId);
$saltedPwd = $account->getPassword();
$match = $this->passwordService->check($givenPwd, $saltedPwd);

You should inject passwordService, or else use Drupal::service('password').

Rainer Feike
  • 191
  • 1
  • 9
0

This code helped me a lot.

$password_hasher = \Drupal::service('password');
$match = $password_hasher->check($currpwd, $user->getPassword());

$match will be bool (true or false). Hope this will be helpful to you as well.

Denis O.
  • 1,841
  • 19
  • 37
Archana Kamath
  • 426
  • 4
  • 4