ZfcUser authentication for an API

515 views Asked by At

In the project I am currently working on, I have the following situation: there is a web application that is accessible for human users through a browser, where the user can manipulate data in a database (representing the state of household devices in a house) after he has logged in. The logging functionality is implemented with the ZfcUser module. Furthermore, the application is accessible for a computer (a raspberry pi that is installed in the house with the devices and is responsible for turning them on and off), which sees the state of the database and reacts accordingly.

The communication between the computer and the application is implemented using JSON and works fine. But right now, the computer does not send any user specific information (email, password...) so that the application functionality used by the raspberry can be accessed by any post request to the right URL. I would like to include the email and the password of the user into the JSON object sent by the computer, so that before executing a function, the web application checks whether the request is valid.

What I would like to know is whether there is a simple possibility to check whether the credentials (email and password, both represented as strings) are valid using ZfcUser (if I understand it correctly, the zfcUserAuthentification() methods can not be used for this task because they work with the cookies stored by the browser).

1

There are 1 answers

0
Simone Bracaloni On

You can use the httprequest and populate it with credentials from JSON POST, then try to authenticate on it after calling prepareForAuthentication

$adapter = $this->zfcUserAuthentication()->getAuthAdapter();
    /** @var \Zend\Http\Request */
    $fakeRequest = $this->getRequest();
    $fakeRequest->getPost()->set('identity', $username);
    $fakeRequest->getPost()->set('credential', $password);
    $result = $adapter->prepareForAuthentication($this->getRequest());

    // Return early if an adapter returned a response
    if ($result instanceof Response) {
        throw new LoginException("");
    }

    $auth = $this->zfcUserAuthentication()->getAuthService()->authenticate($adapter);

    if (!$auth->isValid()) {
        $this->flashMessenger()->setNamespace('zfcuser-login-form')->addMessage($this->failedLoginMessage);
        $adapter->resetAdapters();
        // Password does not match
        throw new LoginException("Invalid Username or password");
    }