CBController.php 10.2 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
70
71
72
73
74
75
76
77
78
79
80
81
        $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();
            $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));
82
83
84
85
86
87
88
89
90
91
92
        $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;
93
            $this->redirect_url = $ostauthConfig->redirect_url->value;
94
95
96
97
98
99
100
101
102
103
        } else {
            $response = new Response();
            $response->setContent('forbidden');
            $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);
104
105
        $epalToken = $this->authenticatePhase2($request, $authToken, $authVerifier);
        if ($epalToken) {
106
            if ('oauthost_taxisnet_config' === $configRowName) {
107
/*                $this->logger->notice('$configRowName='.$configRowName.'***url='.$this->redirect_url);
108
                $cookie = new Cookie('auth_token', $epalToken, 0, '/', null, false, false);
109
110
                $cookie2 = new Cookie('auth_role', 'student', 0, '/', null, false, false); */
                return new RedirectResponse($this->redirect_url . $epalToken.'&auth_role=student', 302, []);
111
            } else {
112
                \Drupal::service('page_cache_kill_switch')->trigger();
113
                return new RedirectResponseWithCookieExt($this->redirect_url . $epalToken.'&auth_role=student', 302, []);
114

115
            }
116
117
118


//            return new RedirectResponse($this->redirect_url . $epalToken.'&auth_role=student', 302, []);
119
        } else {
120
            $this->logger->notice('epalToken false');
121
122
123
124
125
126
            $response = new Response();
            $response->setContent('forbidden');
            $response->setStatusCode(Response::HTTP_FORBIDDEN);
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
127
    }
128

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

141
        $this->logger->warning($oauth->getLastResponse());
142
143
        $taxis_userid = $this->xmlParse($oauth->getLastResponse(), 'messageText');

144
        $currentTime = time();
145
146
        $epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('taxis_userid' => $taxis_userid));
        $epalUser = reset($epalUsers);
147
148

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

165
166
167
                $epalUser->save();
            }
        }
168
169

        if ($epalUser === null || !$epalUser) {
170
171
172
173

            //Create a User
            $user = User::create();
            //Mandatory settings
174
            $unique_id = uniqid('####');
175
            $user->setPassword($epalToken);
176
177
            $user->enforceIsNew();
            $user->setEmail($unique_id);
178
            $user->setUsername($epalToken); //This username must be unique and accept only a-Z,0-9, - _ @ .
179
180
181
182
183
184
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
            $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'],
211
                'authtoken' => $epalToken,
212
213
214
215
                'requesttoken' => $this->requestToken,
                'requesttoken_secret' => $this->requestTokenSecret,
                'timelogin' => $currentTime,
                'timeregistration' => $currentTime,
216
217
218
                'timetokeninvalid' => 0,
                'userip' => $request->getClientIp(),
                'status' => 1
219
220
221
222
223
224
            ));
            $epalUser->save();
            } else {
                return false;
            }

225
        }
226
227
228
        $this->oauthostSession->set('authtoken', $epalToken);
        $this->oauthostSession->save();
//        $this->oauthostSession->delete();
229

230

231
        return $epalToken;
232
233
    } catch (OAuthException $e) {
        $this->logger->warning($e->getMessage());
234
235
        $trx->rollback();
        return false;
236
    } catch (\Exception $ee) {
237
238
        $this->logger->warning($ee->getMessage());
        $trx->rollback();
239
240
241
        return false;
    }

242
243
        return false;
    }
244

245
246
247
    public function xmlParse($xmlText, $token){
        return '12345';
    }
248
}