CBController.php 9.08 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php

namespace Drupal\oauthost\Controller;

use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Controller\ControllerBase;
11 12
use OAuth;
use OAuthException;
13 14 15 16 17
use Drupal\user\Entity\User;
use Drupal\Core\Database\Connection;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
18

19 20 21 22 23 24 25
class CBController extends ControllerBase
{
    protected $entity_query;
    protected $entityTypeManager;
    protected $logger;
    protected $connection;

26 27
    protected $consumer_key = '';
    protected $consumer_secret = '';
28 29 30 31 32 33 34
    protected $request_token_url;
    protected $user_authorization_url;
    protected $access_token_url;
    protected $signature_method;
    protected $api_url;
    protected $callback_url;
    protected $logout_url;
35
    protected $redirect_url;
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

    protected $requestToken;
    protected $requestTokenSecret;
    protected $oauthostSession;

    public function __construct(
    EntityTypeManagerInterface $entityTypeManager,
    QueryFactory $entity_query,
    Connection $connection,
    LoggerChannelFactoryInterface $loggerChannel)
    {
        $this->entityTypeManager = $entityTypeManager;
        $this->entity_query = $entity_query;
        $this->connection = $connection;
        $this->logger = $loggerChannel->get('oauthost');
    }

    public static function create(ContainerInterface $container)
    {
        return new static(
56
          $container->get('entity_type.manager'),
57 58 59
          $container->get('entity.query'),
          $container->get('database'),
          $container->get('logger.factory')
60
      );
61
    }
62

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    public function loginCB(Request $request)
    {

        $ostauthConfigs = $this->entityTypeManager->getStorage('oauthost_config')->loadByProperties(array('name' => 'oauthost_taxisnet_config'));
        $ostauthConfig = reset($ostauthConfigs);
        if ($ostauthConfig) {
            $this->consumer_key = $ostauthConfig->consumer_key->value;
            $this->consumer_secret = $ostauthConfig->consumer_secret->value;
            $this->request_token_url = $ostauthConfig->request_token_url->value;
            $this->user_authorization_url = $ostauthConfig->user_authorization_url->value;
            $this->access_token_url = $ostauthConfig->access_token_url->value;
            $this->signature_method = $ostauthConfig->signature_method->value;
            $this->api_url = $ostauthConfig->api_url->value;
            $this->callback_url = $ostauthConfig->callback_url->value;
            $this->logout_url = $ostauthConfig->logout_url->value;
78
            $this->redirect_url = $ostauthConfig->redirect_url->value;
79 80 81 82 83 84 85
        } else {
            $response = new Response();
            $response->setContent('forbidden');
            $response->setStatusCode(Response::HTTP_FORBIDDEN);
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
86

87 88 89 90 91 92 93 94 95 96 97 98
        $oauthostSessions = $this->entityTypeManager->getStorage('oauthost_session')->loadByProperties(array('name' => $request->query->get('sid_ost')));
        $this->oauthostSession = reset($oauthostSessions);
        if ($this->oauthostSession) {
            $this->requestToken = $this->oauthostSession->request_token->value;
            $this->requestTokenSecret = $this->oauthostSession->request_token_secret->value;
        } else {
            $response = new Response();
            $response->setContent('forbidden');
            $response->setStatusCode(Response::HTTP_FORBIDDEN);
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
99

100 101 102
        $authToken = $request->query->get('oauth_token');
        $authVerifier = $request->query->get('oauth_verifier');
//        $this->logger->notice('authToken='.$authToken.'***authVerifier='.$authVerifier);
103

104
        $epalToken = $this->authenticatePhase2($request, $authToken, $authVerifier);
105

106 107
        if ($epalToken) {
            return new RedirectResponse($this->redirect_url . $epalToken.'&auth_role=student', 302, []);
108 109 110 111 112 113 114
        } else {
            $response = new Response();
            $response->setContent('forbidden');
            $response->setStatusCode(Response::HTTP_FORBIDDEN);
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
115
    }
116

117
    public function authenticatePhase2($request, $authToken, $authVerifier)
118 119 120
    {
    $taxis_userid = null;
    $trx = $this->connection->startTransaction();
121 122 123
    try {
        $oauth = new OAuth($this->consumer_key, $this->consumer_secret, OAUTH_SIG_METHOD_PLAINTEXT, OAUTH_AUTH_TYPE_URI);
        $oauth->enableDebug();
124
        $oauth->setToken($authToken, $this->requestTokenSecret);
125
        $accessToken = $oauth->getAccessToken($this->access_token_url, '', $authVerifier);
126
        $oauth->setToken($accessToken['oauth_token'], $accessToken['oauth_token_secret']);
127
        $oauth->fetch($this->api_url);
128

129
        $this->logger->warning($oauth->getLastResponse());
130 131
        $taxis_userid = $this->xmlParse($oauth->getLastResponse(), 'messageText');

132
        $currentTime = time();
133 134
        $epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('taxis_userid' => $taxis_userid));
        $epalUser = reset($epalUsers);
135 136

        $epalToken = md5(uniqid(mt_rand(), true));
137 138 139
        if ($epalUser) {
            $user = $this->entityTypeManager->getStorage('user')->load($epalUser->user_id->target_id);
            if ($user) {
140 141
                $user->setPassword($epalToken);
                $user->setUsername($epalToken);
142
                $user->save();
143
                $epalUser->set('authtoken', $epalToken);
144 145 146 147
                $epalUser->set('accesstoken', $accessToken['oauth_token']);
                $epalUser->set('accesstoken_secret', $accessToken['oauth_token_secret']);
                $epalUser->set('requesttoken',$this->requestToken);
                $epalUser->set('requesttoken_secret', $this->requestTokenSecret);
148 149 150
                $epalUser->set('timelogin', $currentTime);
                $epalUser->set('userip', $request->getClientIp());

151 152 153
                $epalUser->save();
            }
        }
154 155

        if ($epalUser === null || !$epalUser) {
156 157 158 159

            //Create a User
            $user = User::create();
            //Mandatory settings
160
            $unique_id = uniqid('####');
161
            $user->setPassword($epalToken);
162 163
            $user->enforceIsNew();
            $user->setEmail($unique_id);
164
            $user->setUsername($epalToken); //This username must be unique and accept only a-Z,0-9, - _ @ .
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
            $user->activate();
            $user->set('init', $unique_id);

            //Set Language
            $language_interface = \Drupal::languageManager()->getCurrentLanguage();
            $user->set('langcode', $language_interface->getId());
            $user->set('preferred_langcode', $language_interface->getId());
            $user->set('preferred_admin_langcode', $language_interface->getId());

            //Adding default user role
            $user->addRole('applicant');
            $user->save();


            $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('mail' => $unique_id));
            $user = reset($users);
            if ($user) {
                $this->logger->warning('userid 190='.$user->id().'*** name='.$user->name->value);

                $epalUser = $this->entityTypeManager()->getStorage('epal_users')->create(array(
            //    'langcode' => $language_interface->getId(),
                'langcode' => 'el',
                'user_id' => $user->id(),
                'drupaluser_id' => $user->id(),
                'taxis_userid' => $taxis_userid,
                'taxis_taxid' => $unique_id,
                'name' => $unique_id,
                'surname' => $unique_id,
                'fathername' => $unique_id,
                'mothername' => $unique_id,
                'accesstoken' => $accessToken['oauth_token'],
                'accesstoken_secret' => $accessToken['oauth_token_secret'],
197
                'authtoken' => $epalToken,
198 199 200 201
                'requesttoken' => $this->requestToken,
                'requesttoken_secret' => $this->requestTokenSecret,
                'timelogin' => $currentTime,
                'timeregistration' => $currentTime,
202 203 204
                'timetokeninvalid' => 0,
                'userip' => $request->getClientIp(),
                'status' => 1
205 206 207 208 209 210
            ));
            $epalUser->save();
            } else {
                return false;
            }

211
        }
212
        $this->oauthostSession->delete();
213

214
        return $epalToken;
215 216
    } catch (OAuthException $e) {
        $this->logger->warning($e->getMessage());
217 218 219 220 221
        $trx->rollback();
        return false;
    } catch (Exception $ee) {
        $this->logger->warning($ee->getMessage());
        $trx->rollback();
222 223 224
        return false;
    }

225 226
        return false;
    }
227

228 229 230
    public function xmlParse($xmlText, $token){
        return '12345';
    }
231
}