Skip to content
DAO.php 2.49 KiB
Newer Older
<?php

/* ----------------------------------------------------------------------------
 *               INAF - National Institute for Astrophysics
 *               IRA  - Radioastronomical Institute - Bologna
 *               OATS - Astronomical Observatory - Trieste
 * ----------------------------------------------------------------------------
 *
 * Copyright (C) 2016 Istituto Nazionale di Astrofisica
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License Version 3 as published by the
 * Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

namespace RAP;

use PDO;

class DAO {

    private static function getDBHandler() {
        global $PDO;
        return new PDO($PDO['connection_string'], $PDO['user'], $PDO['password']);
    }

    public static function insertLogin($user) {

        global $log;

        $token = bin2hex(openssl_random_pseudo_bytes(16)); // http://stackoverflow.com/a/18890309/771431

        $dbh = DAO::getDBHandler();

        $stmt = $dbh->prepare("INSERT INTO token (token, data) VALUES(:token, :data)");

        $params = array(
            ':token' => $token,
            ':data' => json_encode($user)
        );

        if ($stmt->execute($params)) {
            return $token;
        } else {
            $log->error($stmt->errorInfo()[2]);
            throw new \Exception("SQL error while storing user token");
        }
    }

    public static function getTokenData($token) {

        $dbh = DAO::getDBHandler();

        $stmt = $dbh->prepare("SELECT data FROM token WHERE token = :token AND CURRENT_TIMESTAMP < TIMESTAMPADD(MINUTE,1,creation_time)");
        $stmt->bindParam(':token', $token);

        $stmt->execute();

        foreach ($stmt->fetchAll() as $row) {
            return $row['data'];
        }

        return null;
    }

    public static function deleteToken($token) {

        $dbh = DAO::getDBHandler();

        $stmt = $dbh->prepare("DELETE FROM token WHERE token = :token");
        $stmt->bindParam(':token', $token);
        $stmt->execute();
    }

}