<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 */

namespace SimpleSAML\Module\lifestyle\Auth\Source;

use SimpleSAML\Error\Error;
use SimpleSAML\Logger;
use SimpleSAML\Module\core\Auth\UserPassBase;
use SimpleSAML\Module\lifestyle\Webservice\Handler;

/**
 * Class Webservice
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 * @package SimpleSAML\Module\lifestyle\Auth\Source
 */
class Webservice extends UserPassBase
{
    /**
     * Attempt to log in using the given username and password.
     *
     * On a successful login, this function should return the users attributes. On failure,
     * it should throw an exception/error. If the error was caused by the user entering the wrong
     * username or password, a SimpleSAML\Error\Error('WRONGUSERPASS') should be thrown.
     *
     * Note that both the username and the password are UTF-8 encoded.
     *
     * @param string $username The username the user wrote.
     * @param string $password The password the user wrote.
     * @return array Associative array with the user's attributes.
     * @throws SimpleSAML\Error\Error
     */
    protected function login($username, $password)
    {
        assert('is_string($username)');
        assert('is_string($password)');

        if (null === ($user = Handler::getUser($username, $password))) {
            Logger::error('webservice:' . $this->authId . ': Failed to get user. Probably wrong username.');
            throw new Error('WRONGUSERPASS');
        }

        if (!$user->isPasswordValid()) {
            Handler::setLoginStatus($username, false);
            Logger::error('webservice:' . $this->authId . ': Failed to verify password. Probably wrong username/password.');
            throw new Error('WRONGUSERPASS');
        }

        $attributes = $user->getUserAttributes();

        Logger::info('webservice:' . $this->authId . ': Attributes: ' . implode(', ', array_keys($attributes)));

        return $attributes;
    }
}
