CBController.php 10.3 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
use Symfony\Component\HttpFoundation\Cookie;
19
require ('RedirectResponseWithCookieExt.php');
20

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

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

    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(
58
          $container->get('entity_type.manager'),
59 60 61
          $container->get('entity.query'),
          $container->get('database'),
          $container->get('logger.factory')
62
      );
63
    }
64

65 66 67
    public function loginCB(Request $request)
    {

68 69
        $oauthostSessions = $this->entityTypeManager->getStorage('oauthost_session')->loadByProperties(array('name' => $request->query->get('sid_ost')));
        $this->oauthostSession = reset($oauthostSessions);
70
$this->logger->warning('$configRowName=gjvjvjgvjhvjhv'.'***sid='.$this->oauthostSession->id());
71 72 73 74 75 76 77 78 79 80 81 82
        if ($this->oauthostSession) {
            $this->requestToken = $this->oauthostSession->request_token->value;
            $this->requestTokenSecret = $this->oauthostSession->request_token_secret->value;
            $configRowName = $this->oauthostSession->configrowname->value;
        } else {
            $response = new Response();
            $response->setContent('forbidden');
            $response->setStatusCode(Response::HTTP_FORBIDDEN);
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
        $ostauthConfigs = $this->entityTypeManager->getStorage('oauthost_config')->loadByProperties(array('name' => $configRowName));
83 84 85 86 87 88 89 90 91 92 93
        $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;
94
            $this->redirect_url = $ostauthConfig->redirect_url->value;
95 96 97 98 99 100 101
        } else {
            $response = new Response();
            $response->setContent('forbidden');
            $response->setStatusCode(Response::HTTP_FORBIDDEN);
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
102

103

104

105 106 107
        $authToken = $request->query->get('oauth_token');
        $authVerifier = $request->query->get('oauth_verifier');
//        $this->logger->notice('authToken='.$authToken.'***authVerifier='.$authVerifier);
108

109
        $epalToken = $this->authenticatePhase2($request, $authToken, $authVerifier);
110

111
        if ($epalToken) {
112
            if ('oauthost_taxisnet_config' === $configRowName) {
113
/*                $this->logger->notice('$configRowName='.$configRowName.'***url='.$this->redirect_url);
114
                $cookie = new Cookie('auth_token', $epalToken, 0, '/', null, false, false);
115
                $cookie2 = new Cookie('auth_role', 'student', 0, '/', null, false, false); */
116

117
                return new RedirectResponse($this->redirect_url . $epalToken.'&auth_role=student', 302, []);
118
            } else {
119
//                $this->logger->notice('***url2='.$this->redirect_url);
120 121
                return new RedirectResponseWithCookieExt($this->redirect_url . $epalToken.'&auth_role=student', 302, []);
            }
122 123 124


//            return new RedirectResponse($this->redirect_url . $epalToken.'&auth_role=student', 302, []);
125
        } else {
126
            $this->logger->notice('epalToken false');
127 128 129 130 131 132
            $response = new Response();
            $response->setContent('forbidden');
            $response->setStatusCode(Response::HTTP_FORBIDDEN);
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
133
    }
134

135
    public function authenticatePhase2($request, $authToken, $authVerifier)
136 137 138
    {
    $taxis_userid = null;
    $trx = $this->connection->startTransaction();
139 140 141
    try {
        $oauth = new OAuth($this->consumer_key, $this->consumer_secret, OAUTH_SIG_METHOD_PLAINTEXT, OAUTH_AUTH_TYPE_URI);
        $oauth->enableDebug();
142
        $oauth->setToken($authToken, $this->requestTokenSecret);
143
        $accessToken = $oauth->getAccessToken($this->access_token_url, '', $authVerifier);
144
        $oauth->setToken($accessToken['oauth_token'], $accessToken['oauth_token_secret']);
145
        $oauth->fetch($this->api_url);
146

147
        $this->logger->warning($oauth->getLastResponse());
148 149
        $taxis_userid = $this->xmlParse($oauth->getLastResponse(), 'messageText');

150
        $currentTime = time();
151 152
        $epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('taxis_userid' => $taxis_userid));
        $epalUser = reset($epalUsers);
153 154

        $epalToken = md5(uniqid(mt_rand(), true));
155 156 157
        if ($epalUser) {
            $user = $this->entityTypeManager->getStorage('user')->load($epalUser->user_id->target_id);
            if ($user) {
158 159
//                $user->setPassword('harispass');
//                $user->setUsername('harisp');
160 161
                $user->setPassword($epalToken);
                $user->setUsername($epalToken);
162
                $user->save();
163
                $epalUser->set('authtoken', $epalToken);
164 165 166 167
                $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);
168 169 170
                $epalUser->set('timelogin', $currentTime);
                $epalUser->set('userip', $request->getClientIp());

171 172 173
                $epalUser->save();
            }
        }
174 175

        if ($epalUser === null || !$epalUser) {
176 177 178 179

            //Create a User
            $user = User::create();
            //Mandatory settings
180
            $unique_id = uniqid('####');
181
            $user->setPassword($epalToken);
182 183
            $user->enforceIsNew();
            $user->setEmail($unique_id);
184
            $user->setUsername($epalToken); //This username must be unique and accept only a-Z,0-9, - _ @ .
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
            $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'],
217
                'authtoken' => $epalToken,
218 219 220 221
                'requesttoken' => $this->requestToken,
                'requesttoken_secret' => $this->requestTokenSecret,
                'timelogin' => $currentTime,
                'timeregistration' => $currentTime,
222 223 224
                'timetokeninvalid' => 0,
                'userip' => $request->getClientIp(),
                'status' => 1
225 226 227 228 229 230
            ));
            $epalUser->save();
            } else {
                return false;
            }

231
        }
232 233 234
        $this->oauthostSession->set('authtoken', $epalToken);
        $this->oauthostSession->save();
//        $this->oauthostSession->delete();
235

236

237
        return $epalToken;
238 239
    } catch (OAuthException $e) {
        $this->logger->warning($e->getMessage());
240 241
        $trx->rollback();
        return false;
242
    } catch (\Exception $ee) {
243 244
        $this->logger->warning($ee->getMessage());
        $trx->rollback();
245 246 247
        return false;
    }

248 249
        return false;
    }
250

251 252 253
    public function xmlParse($xmlText, $token){
        return '12345';
    }
254
}