CBController.php 14.5 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
use OAuth;
12
use DOMDocument;
13
use OAuthException;
14
15
16
17
18
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;
19
use Symfony\Component\HttpFoundation\Cookie;
20
use Drupal\epal\Crypt;
21
require ('RedirectResponseWithCookieExt.php');
22

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

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

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

67
68
69
    public function loginCB(Request $request)
    {

70
71
72
73
74
75
76
77
        $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;
            $configRowName = $this->oauthostSession->configrowname->value;
        } else {
            $response = new Response();
78
            $response->setContent('forbidden1');
79
80
81
82
83
            $response->setStatusCode(Response::HTTP_FORBIDDEN);
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
        $ostauthConfigs = $this->entityTypeManager->getStorage('oauthost_config')->loadByProperties(array('name' => $configRowName));
84
85
        $ostauthConfig = reset($ostauthConfigs);
        if ($ostauthConfig) {
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108

            $crypt = new Crypt();

            try  {
              $consumer_key_decoded = $crypt->decrypt($ostauthConfig->consumer_key->value);
              $consumer_secret_decoded = $crypt->decrypt($ostauthConfig->consumer_secret->value);
            }
            catch (\Exception $e) {
              unset($crypt);
              $this->logger->notice('epalToken decoding false');
              $response = new Response();
              $response->setContent('internal_server_error');
              $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
              $response->headers->set('Content-Type', 'application/json');
              return $response;
            }
            unset($crypt);

            $this->consumer_key = $consumer_key_decoded;
            $this->consumer_secret = $consumer_secret_decoded;
            //$this->consumer_key = $ostauthConfig->consumer_key->value;
            //$this->consumer_secret = $ostauthConfig->consumer_secret->value;

109
110
111
112
113
114
115
            $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;
116
            $this->redirect_url = $ostauthConfig->redirect_url->value;
117
118
        } else {
            $response = new Response();
119
            $response->setContent('forbidden2');
120
121
122
123
124
125
126
            $response->setStatusCode(Response::HTTP_FORBIDDEN);
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
        $authToken = $request->query->get('oauth_token');
        $authVerifier = $request->query->get('oauth_verifier');
//        $this->logger->notice('authToken='.$authToken.'***authVerifier='.$authVerifier);
127
128
        $epalToken = $this->authenticatePhase2($request, $authToken, $authVerifier);
        if ($epalToken) {
129
            if ('oauthost_taxisnet_config' === $configRowName) {
130
/*                $this->logger->notice('$configRowName='.$configRowName.'***url='.$this->redirect_url);
131
                $cookie = new Cookie('auth_token', $epalToken, 0, '/', null, false, false);
132
133
                $cookie2 = new Cookie('auth_role', 'student', 0, '/', null, false, false); */
                return new RedirectResponse($this->redirect_url . $epalToken.'&auth_role=student', 302, []);
134
            } else {
135
                \Drupal::service('page_cache_kill_switch')->trigger();
136
                return new RedirectResponseWithCookieExt($this->redirect_url . $epalToken.'&auth_role=student', 302, []);
137

138
            }
139
140
141


//            return new RedirectResponse($this->redirect_url . $epalToken.'&auth_role=student', 302, []);
142
        } else {
143
            $this->logger->notice('epalToken false');
144
            $response = new Response();
145
            $response->setContent('forbidden3');
146
147
148
149
            $response->setStatusCode(Response::HTTP_FORBIDDEN);
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
150
    }
151

152
    public function authenticatePhase2($request, $authToken, $authVerifier)
153
    {
Σταύρος Παπαδάκης's avatar
Σταύρος Παπαδάκης committed
154
        try {
155
156
            $taxis_userid = null;
            $trx = $this->connection->startTransaction();
Σταύρος Παπαδάκης's avatar
Σταύρος Παπαδάκης committed
157
            $oauth = new OAuth($this->consumer_key, $this->consumer_secret, OAUTH_SIG_METHOD_PLAINTEXT, OAUTH_AUTH_TYPE_URI);
158
//            $oauth->enableDebug();
Σταύρος Παπαδάκης's avatar
Σταύρος Παπαδάκης committed
159
160
161
162
163
            $oauth->setToken($authToken, $this->requestTokenSecret);
            $accessToken = $oauth->getAccessToken($this->access_token_url, '', $authVerifier);
            $oauth->setToken($accessToken['oauth_token'], $accessToken['oauth_token_secret']);
            $oauth->fetch($this->api_url);

164
165
166
167
168
169
            $dom = $this->loadXML($oauth->getLastResponse());
            $taxis_userData = $this->getXMLElements($dom);

            if (!$taxis_userData || sizeof($taxis_userData) === 0) {
                return false;
            }
Σταύρος Παπαδάκης's avatar
Σταύρος Παπαδάκης committed
170
171

            $currentTime = time();
172
            $epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('taxis_userid' => $taxis_userData['tin']));
Σταύρος Παπαδάκης's avatar
Σταύρος Παπαδάκης committed
173
174
175
            $epalUser = reset($epalUsers);

            $epalToken = md5(uniqid(mt_rand(), true));
176

Σταύρος Παπαδάκης's avatar
Σταύρος Παπαδάκης committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
            if ($epalUser) {
                $user = $this->entityTypeManager->getStorage('user')->load($epalUser->user_id->target_id);
                if ($user) {
                    $user->setPassword($epalToken);
                    $user->setUsername($epalToken);
                    $user->save();
                    $epalUser->set('authtoken', $epalToken);
                    $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);
                    $epalUser->set('timelogin', $currentTime);
                    $epalUser->set('userip', $request->getClientIp());

                    $epalUser->save();
                }
193
            }
Σταύρος Παπαδάκης's avatar
Σταύρος Παπαδάκης committed
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
            if ($epalUser === null || !$epalUser) {
                //Create a User
                $user = User::create();
                //Mandatory settings
                $unique_id = uniqid('####');
                $user->setPassword($epalToken);
                $user->enforceIsNew();
                $user->setEmail($unique_id);
                $user->setUsername($epalToken); //This username must be unique and accept only a-Z,0-9, - _ @ .
                $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();
215

Σταύρος Παπαδάκης's avatar
Σταύρος Παπαδάκης committed
216
217
218
                $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('mail' => $unique_id));
                $user = reset($users);
                if ($user) {
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
                    $crypt = new Crypt();
                    try  {
                      $name_encoded = $crypt->encrypt($unique_id);
                    }
                    catch (\Exception $e) {
                      unset($crypt);
                      $this->logger->notice('epalToken encoding false');
                      $response = new Response();
                      $response->setContent('internal_server_error');
                      $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
                      $response->headers->set('Content-Type', 'application/json');
                      return $response;
                    }
                    unset($crypt);


Σταύρος Παπαδάκης's avatar
Σταύρος Παπαδάκης committed
235
236
237
238
                    $epalUser = $this->entityTypeManager()->getStorage('epal_users')->create(array(
                        'langcode' => 'el',
                        'user_id' => $user->id(),
                        'drupaluser_id' => $user->id(),
239
240
                        'taxis_userid' => $taxis_userData['tin'],
                        'taxis_taxid' => $taxis_userData['tin'],
241
/*                        'name' => $taxis_userData['firstName'],
242
                        'surname' => $taxis_userData['surname'],
243
                        'fathername' => $taxis_userData['fathersName'], */
244
245
246
247
248
249
250
251
252
                        //'name' => $unique_id,
                        //'surname' => $unique_id,
                        //'fathername' => $unique_id,
                        //'mothername' => $unique_id,
                        'name' => $name_encoded,
                        'surname' => $name_encoded,
                        'fathername' => $name_encoded,
                        'mothername' => $name_encoded,

Σταύρος Παπαδάκης's avatar
Σταύρος Παπαδάκης committed
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
                        'accesstoken' => $accessToken['oauth_token'],
                        'accesstoken_secret' => $accessToken['oauth_token_secret'],
                        'authtoken' => $epalToken,
                        'requesttoken' => $this->requestToken,
                        'requesttoken_secret' => $this->requestTokenSecret,
                        'timelogin' => $currentTime,
                        'timeregistration' => $currentTime,
                        'timetokeninvalid' => 0,
                        'userip' => $request->getClientIp(),
                        'status' => 1
                    ));
                    $epalUser->save();
                } else {
                    return false;
                }
268

Σταύρος Παπαδάκης's avatar
Σταύρος Παπαδάκης committed
269
270
271
272
273
274
275
276
277
278
279
280
281
282
            }
            $this->oauthostSession->set('authtoken', $epalToken);
            $this->oauthostSession->save();

            return $epalToken;
        } catch (OAuthException $e) {
            $this->logger->warning($e->getMessage());
            $trx->rollback();
            return false;
        } catch (\Exception $ee) {
            $this->logger->warning($ee->getMessage());
            $trx->rollback();
            return false;
        }
283

284
285
        return false;
    }
286

287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
    public function loadXML($text_response){
        $dom = new DOMDocument();
        // Fix possible whitespace problems
        $dom->preserveWhiteSpace = false;

        if (!($dom->loadXML($text_response))) {
            $this->logger->warning('dom->loadXML() failed');
            return false;
        }

        if (!($tree_response = $dom->documentElement)) {
            $this->logger->warning('documentElement() failed');
            return false;
        }
        return $dom;
    }

    public function getXMLElements($doc){
        $webUserDetails = $doc->getElementsByTagName( "WebUserDetails" );
        if (!$webUserDetails || $webUserDetails->length === 0)
307
308
            return false;
/*            return array(   // to be changed to empty array
309
310
311
312
313
                'firstName' => '',
                'surname' => '',
                'fathersName' => '',
                'comments' => '',
                'tin' => '12345'
314
315
            ); */

316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
        foreach( $webUserDetails as $element )
        {
            $comments = $element->getElementsByTagName( "comments" );
            $comment = $comments->item(0)->nodeValue;

            $fathersNames = $element->getElementsByTagName( "fathersName" );
            $fathersName = $fathersNames->item(0)->nodeValue;

            $firstNames = $element->getElementsByTagName( "name" );
            $firstName = $firstNames->item(0)->nodeValue;

            $surnames = $element->getElementsByTagName( "surname" );
            $surname = $surnames->item(0)->nodeValue;

            $tins = $element->getElementsByTagName( "tin" );
            $tin = $tins->item(0)->nodeValue;

            if (!$tin || $tin === '')
334
335
                return false;
/*                return array(   // to be changed to empty array
336
337
338
339
340
                    'firstName' => '',
                    'surname' => '',
                    'fathersName' => '',
                    'comments' => '',
                    'tin' => '12345'
341
                ); */
342
343
344
345
346
347
348
349
            return array(
                'firstName' => $firstName,
                'surname' => $surname,
                'fathersName' => $fathersName,
                'comments' => $comment,
                'tin' => $tin
            );
        }
350
    }
351
}