/*
 * BSD 2-Clause License
 *
 * Copyright (c) 2020, Agnieszka Cicha-Cisek
 * Copyright (c) 2020, Patryk Cisek
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#ifndef AUTHENTICATION_H
#define AUTHENTICATION_H

#include <memory>
#include <mutex>
#include <QObject>

#include "authenticatedialog.h"
#include "nitrokeyprovider.h"
#include "randompasswordgenerator.h"

/**
 * @brief Abstraction over managing authentication session with the USB key.
 *
 * This class encapsulates the mechanism of authentication used in Nitrokey
 * (and NitroKey for that matter). When you authenticate to the key, you generate
 * a session password and call libnitrokey's authentication API with both,
 * the PIN (user, or admin) and that session password. After successfull
 * authentication call, you can use that password for operations that
 * require authentication.
 *
 * Ideally the passowrd should not be kept in memory for long periods of time.
 * If you don't use the key, it's better to delete the password from memory,
 * so possibility of leaking the password (even though it's temporary) is lower
 * (the password doesn't linger in RAM indefinitelly).
 */
class Authentication : public QObject
{
    Q_OBJECT

    using Lock = std::lock_guard<std::mutex>;

    std::shared_ptr<AuthenticateDialog> authenticateDialog;
    RandomPasswordGenerator tempPasswordGenerator;

    mutable std::mutex tempPasswordMutex;
    RandomPasswordGenerator::KeyPassword tempPassword;

    std::shared_ptr<NitrokeyProvider> keyProvider;

    unsigned int sessionTimeoutMSec;

    bool checkIfAuthenticated() const;

private slots:
    void onAuthenticated();
    void onAuthenticationFailure();

signals:
    /**
     * @brief Emitted upon successfull authentication.
     */
    void authenticated();

    /**
     * @brief Emitted upon failed authentication attempt.
     */
    void authenticationFailure();

    /**
     * @brief Emitted when authentication is canceled (Cancel button on AuthenticateDialog clicked).
     */
    void authenticationCanceled();

public slots:
    /**
     * @brief Scrubs the temporary session password from memory.
     */
    void scrubPassword();

public:
    /**
     * @brief Creates an instance of Authentication.
     * @param authenticateDialog Instance of a modal dialog used to ask user for PIN.
     * @param keyProvider Instance of Nitrokey provider class, used by Authentication class
     * to interact with the USB key (to perform authentication).
     * @param sessionTimeoutMSec Duration of the session. After this timeout, password gets
     * scrubbed from memory. Time unit is milliseconds.
     */
    Authentication(std::shared_ptr<AuthenticateDialog> authenticateDialog,
                   std::shared_ptr<NitrokeyProvider> keyProvider,
                   unsigned int sessionTimeoutMSec);

    /**
     * @brief Authenticates user. This function must be called before password().
     */
    void authenticate();

    /**
     * @brief Returns session password, or throws UnauthenticatedException, if
     * user has not authenticated yet, or session expired.
     * @return Session password.
     *
     * User first needs to call authenticate(). Then wait for authenticated() signal
     * to be emitted and then call password(). password() has to always be called in
     * try/catch block -- there's always a risk, the password will expire due to timeout.
     * Also there is no race condition in situation where you manage to properly get the key,
     * then session expires and password gets invalidated here, and after that user actually
     * uses previously obtained passowrd. The password may still be safely used, even though
     * it migh have been scrubbed here. Password scrubbing here is only to automatically remove
     * lingering session passwords from memory. If user maintains their own copy outside of this
     * class, that copy is still valid and can be used.
     */
    RandomPasswordGenerator::KeyPassword password();
};

#endif // AUTHENTICATION_H
