Duffer Derek

Current Path : /var/www/podiomigration.bitkit.dk/httpdocs/src/classes/Repository/General/
Upload File :
Current File : /var/www/podiomigration.bitkit.dk/httpdocs/src/classes/Repository/General/AuthRepo.php

<?php namespace App\Repository\General;

use PDO;
use Podio;
use PodioError;
use PodioOAuth;
use PodioUserStatus;

/**
 * Created by PhpStorm.
 * User: jis
 * Date: 19/11/16
 * Time: 11:52 AM
 */
class AuthRepo
{
    private $const;
    private $tblUserAuth;

    /**
     * AuthRepo constructor.
     */
    public function __construct()
    {
        $this->const = 250;
        $this->tblUserAuth = "user_auth";
    }


    public function userPodioAuthenticate($identifier)
    {
        $sql = "select `user` from `transfer_process` where `id` =:identifier ";
        $STH = DB::prepare($sql);
        $STH->execute(array(
            'identifier' => $identifier,
        ));
        $result = $STH->fetchAll(PDO::FETCH_ASSOC);
        if ($result || count($result) > 0) {
            $user = $result[0]['user'];
            if ($this->podioAuthenticate($user)) {
                Constants::setIDENTIFIER($identifier);
                Constants::setUSER($user);
                return true;
            }
        }
        Log::log("userPodioAuthenticate user is null, identifier: " . $identifier, null, "warning");

        return false;
    }

    // todo check rate limit

    public function podioAuthenticate($user)
    {
        if (!Podio::is_authenticated()) {
            $result = $this->getUserAuthentication($user);
            if (!$result || count($result) < 1) { // no values in DB
                return $this->authenticateAndSaveTokens($user);
            } else {
                $auth = $result[0];
                if ($this->isExpired($auth)) {
                    return $this->authenticateAndSaveTokens($user);
                } else {
                    return $this->authenticateUsingAccessToken($auth);
                }
            }
        }
        return true;
    }


    function getUserAuthentication($identifier)
    {
        // `id` , `user_type` , `access_token` , `api_key_used` , `expire_time` , `updated_at`
        $sql = "SELECT t1.`id`, t1.`expire_time` , t1.`user_type` , t1.`api_key_used` , t1.`rate_limit_gen` ,
          t1.`rate_limit` , t1.`start_time` ,t1.`end_time`, t1.`identifier`,
          AES_DECRYPT(t1.`access_token`,:secret) as access_token,
          AES_DECRYPT(t1.`refresh_token`,:secret) as refresh_token 
          from `$this->tblUserAuth` t1  where  t1.`identifier`=:identifier";
        $STH = DB::prepare($sql);
        $STH->execute(array(
            'secret' => PodioConfig::$SECRET_KEY,
            'identifier' => $identifier,
        ));
        return $STH->fetchAll(PDO::FETCH_ASSOC);
    }

    private function authenticateAndSaveTokens($identifier)
    {
        Log::log("authenticateAndSaveTokens" . $identifier);
        $user = null;
        $data = array();
        switch ($identifier) {
            case "logmein":
                $user = PodioConfig::getLogMeUser();
                break;
        }
        if ($user) {
            try {
                Podio::setup(PodioConfig::$PODIO_CLIENT_ID, PodioConfig::$PODIO_CLIENT_SECRET);
                Podio::authenticate('password', array('username' => $user['username'],
                    'password' => $user['password']));

                //`access_token` , `refresh_token` , `expire_time` , `user_type` , `api_key_used` , `rate_limit_gen` , `rate_limit` , `start_time` , `end_time`
                $data = array(
                    'access_token' => Podio::$oauth->access_token,
                    'refresh_token' => Podio::$oauth->refresh_token,
                    'identifier' => Podio::$auth_type['identifier'],
                    'expire_time' => time() + Podio::$oauth->expires_in,
                    'start_time' => time(),
                    'end_time' => time() + (60 * 60),
                );
                Log::log("authenticateAndSaveTokens" . $identifier, $data);
                $id = $this->saveUserAuth($data);
                return true;

            } catch (PodioError $e) {
                $details = json_encode($data);
                Log::logError($e . "", $details, "authenticateUsingAccessToken");
            }
        } else {
            Log::log("authenticateAndSaveTokens user is null, identifier: " . $identifier, null, "warning");
        }
        return false;
    }

    function saveUserAuth($data)
    {
        $sql = "DELETE FROM `$this->tblUserAuth`  WHERE identifier=:identifier";
        $STH = DB::prepare($sql);
        $STH->execute(array(
            'identifier' => $data['identifier'],
        ));

        //  `access_token` , `refresh_token` , `expire_time` , `user_type` , `api_key_used` , `rate_limit_gen` , `rate_limit` , `start_time` , `end_time` , `updated_time`
        $sql = "insert into `$this->tblUserAuth` (`access_token` , `refresh_token` ,`identifier`, `expire_time`,  `start_time` , `end_time` ) 
                 values ( AES_ENCRYPT(:access_token,:secret),AES_ENCRYPT(:refresh_token,:secret),:identifier,:expire_time,:start_time,:end_time)";
        $data['secret'] = PodioConfig::$SECRET_KEY;
        $STH = DB::prepare($sql);
        $STH->execute($data);
        return DB::lastInsertId();
    }

    private function isExpired($auth)
    {
        $time = time() + (10 * 60);
        if ($auth['expire_time'] < $time) {
            Log::log("AuthRepo expired", array('expire_time' => $auth['expire_time'], 'time' => $time));

            return true;
        }
        return false;
    }

    private function authenticateUsingAccessToken($auth)
    {
        $time = $auth['expire_time'] - time() - (2 * 60);
        Podio::setup($auth['client_id'], $auth['client_secret']);
        Podio::$auth_type = array(
            "type" => "password",
            "identifier" => $auth['identifier']
        );
        Podio::$oauth = new PodioOAuth(
            $auth['access_token'],
            $auth['refresh_token'],
            $time,
            array("type" => "password", "id" => $auth['identifier'])
        );
        // todo
        try {
            if (Podio::is_authenticated()) {
                $user = PodioUserStatus::get();

                return true;
            }
        } catch (PodioError $e) {
            $details = json_encode($auth);
            Log::logError($e . "", "authenticateUsingAccessToken", $details);
        }
        return false;
    }

    private function updateRateLimitObject($auth)
    {
        Constants::setRATELIMIT(array(
            'id' => $auth['id'],
            'rate_limit' => $auth['rate_limit'],
            'rate_limit_gen' => $auth['rate_limit_gen'],
        ));
    }

    public function podioAuthPers()
    {
        try {
            Podio::setup(PodioConfig::$PODIO_CLIENT_ID, PodioConfig::$PODIO_CLIENT_SECRET);
            Podio::authenticate('password', array('username' => "jis.jose@phases.dk",
                'password' => "JisPhases@123"));
            return true;
        } catch (PodioError $e) {
            Log::logError($e . "", null, "podioAuthPers");
        }
        return false;
    }
}

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists