/**
  * @param Request $request
  * @return \Psr\Http\Message\ResponseInterface|RedirectResponse
  */
 public function handle(Request $request)
 {
     $redirectUri = (string) $request->getAttribute('originalUri', $request->getUri())->withQuery('');
     $server = new Twitter(['identifier' => $this->settings->get('flarum-auth-twitter.api_key'), 'secret' => $this->settings->get('flarum-auth-twitter.api_secret'), 'callback_uri' => $redirectUri]);
     $session = $request->getAttribute('session');
     $queryParams = $request->getQueryParams();
     $oAuthToken = array_get($queryParams, 'oauth_token');
     $oAuthVerifier = array_get($queryParams, 'oauth_verifier');
     if (!$oAuthToken || !$oAuthVerifier) {
         $temporaryCredentials = $server->getTemporaryCredentials();
         $session->set('temporary_credentials', serialize($temporaryCredentials));
         $session->save();
         // Second part of OAuth 1.0 authentication is to redirect the
         // resource owner to the login screen on the server.
         $server->authorize($temporaryCredentials);
         exit;
     }
     // Retrieve the temporary credentials we saved before
     $temporaryCredentials = unserialize($session->get('temporary_credentials'));
     // We will now retrieve token credentials from the server
     $tokenCredentials = $server->getTokenCredentials($temporaryCredentials, $oAuthToken, $oAuthVerifier);
     $user = $server->getUserDetails($tokenCredentials);
     $identification = ['twitter_id' => $user->uid];
     $suggestions = ['username' => $user->nickname, 'avatarUrl' => str_replace('_normal', '', $user->imageUrl)];
     return $this->authResponse->make($request, $identification, $suggestions);
 }
 public function prepareApiAttributes(PrepareApiAttributes $event)
 {
     if ($event->isSerializer(ForumSerializer::class)) {
         $event->attributes['logo_url'] = $this->settings->get('santiagobiali-logo.logo_url');
         $event->attributes['logo_css'] = $this->settings->get('santiagobiali-logo.logo_css');
     }
 }
Esempio n. 3
0
 /**
  * {@inheritdoc}
  */
 public function data(ServerRequestInterface $request, Document $document)
 {
     $this->assertAdmin($request->getAttribute('actor'));
     $file = array_get($request->getUploadedFiles(), 'favicon');
     $tmpFile = tempnam($this->app->storagePath() . '/tmp', 'favicon');
     $file->moveTo($tmpFile);
     $extension = pathinfo($file->getClientFilename(), PATHINFO_EXTENSION);
     if ($extension !== 'ico') {
         $manager = new ImageManager();
         $encodedImage = $manager->make($tmpFile)->resize(64, 64, function ($constraint) {
             $constraint->aspectRatio();
             $constraint->upsize();
         })->encode('png');
         file_put_contents($tmpFile, $encodedImage);
         $extension = 'png';
     }
     $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => new Filesystem(new Local($this->app->publicPath() . '/assets'))]);
     if (($path = $this->settings->get('favicon_path')) && $mount->has($file = "target://{$path}")) {
         $mount->delete($file);
     }
     $uploadName = 'favicon-' . Str::lower(Str::quickRandom(8)) . '.' . $extension;
     $mount->move('source://' . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}");
     $this->settings->set('favicon_path', $uploadName);
     return parent::data($request, $document);
 }
Esempio n. 4
0
 /**
  * @param PrepareApiAttributes $event
  */
 public function prepareApiAttributes(PrepareApiAttributes $event)
 {
     if ($event->isSerializer(ForumSerializer::class)) {
         $event->attributes['minPrimaryTags'] = $this->settings->get('flarum-tags.min_primary_tags');
         $event->attributes['maxPrimaryTags'] = $this->settings->get('flarum-tags.max_primary_tags');
         $event->attributes['minSecondaryTags'] = $this->settings->get('flarum-tags.min_secondary_tags');
         $event->attributes['maxSecondaryTags'] = $this->settings->get('flarum-tags.max_secondary_tags');
     }
 }
Esempio n. 5
0
 /**
  * @param User $actor
  * @param Discussion $discussion
  * @return bool|null
  */
 public function rename(User $actor, Discussion $discussion)
 {
     if ($discussion->start_user_id == $actor->id) {
         $allowRenaming = $this->settings->get('allow_renaming');
         if ($allowRenaming === '-1' || $allowRenaming === 'reply' && $discussion->participants_count <= 1 || $discussion->start_time->diffInMinutes(new Carbon()) < $allowRenaming) {
             return true;
         }
     }
 }
Esempio n. 6
0
 /**
  * {@inheritdoc}
  */
 protected function getView(ServerRequestInterface $request)
 {
     $view = parent::getView($request);
     $settings = $this->settings->all();
     $this->events->fire(new PrepareUnserializedSettings($settings));
     $view->setVariable('settings', $settings);
     $view->setVariable('permissions', Permission::map());
     $view->setVariable('extensions', $this->extensions->getExtensions()->toArray());
     return $view;
 }
 /**
  * @param PrepareApiAttributes $event
  */
 public function prepareApiAttributes(PrepareApiAttributes $event)
 {
     if ($event->isSerializer(ForumSerializer::class)) {
         $attributes = array('vovayatsyuk-auth-magento' => array('store_name' => 'Magento', 'background_color' => '#ef672f'));
         foreach ($attributes as $namespace => $keys) {
             foreach ($keys as $key => $default) {
                 $event->attributes[$namespace . '.' . $key] = $this->settings->get($namespace . '.' . $key) ?: $default;
             }
         }
     }
 }
Esempio n. 8
0
 /**
  * {@inheritdoc}
  */
 protected function delete(ServerRequestInterface $request)
 {
     $this->assertAdmin($request->getAttribute('actor'));
     $path = $this->settings->get('favicon_path');
     $this->settings->set('favicon_path', null);
     $uploadDir = new Filesystem(new Local($this->app->publicPath() . '/assets'));
     if ($uploadDir->has($path)) {
         $uploadDir->delete($path);
     }
     return new EmptyResponse(204);
 }
 /**
  * @param ServerRequestInterface $request
  * @return EmptyResponse|JsonResponse
  */
 public function handle(ServerRequestInterface $request)
 {
     $userChannel = 'private-user' . $request->getAttribute('actor')->id;
     $body = $request->getParsedBody();
     if (array_get($body, 'channel_name') === $userChannel) {
         $pusher = new Pusher($this->settings->get('flarum-pusher.app_key'), $this->settings->get('flarum-pusher.app_secret'), $this->settings->get('flarum-pusher.app_id'), ['cluster' => $this->settings->get('flarum-pusher.app_cluster')]);
         $payload = json_decode($pusher->socket_auth($userChannel, array_get($body, 'socket_id')), true);
         return new JsonResponse($payload);
     }
     return new EmptyResponse(403);
 }
Esempio n. 10
0
 /**
  * {@inheritdoc}
  */
 public function handle(ServerRequestInterface $request)
 {
     $this->assertAdmin($request->getAttribute('actor'));
     $settings = $request->getParsedBody();
     foreach ($settings as $k => $v) {
         $this->dispatcher->fire(new PrepareSerializedSetting($k, $v));
         $this->settings->set($k, $v);
         $this->dispatcher->fire(new SettingWasSet($k, $v));
     }
     return new EmptyResponse(204);
 }
 public function addAssets(ConfigureClientView $event)
 {
     if ($event->isAdmin()) {
         $event->addAssets([__DIR__ . '/../../js/admin/dist/extension.js']);
         $event->addBootstrapper('sijad/google/analytics/main');
     }
     if ($event->isForum() && ($code = $this->settings->get('sijad-google-analytics.tracking_code'))) {
         $event->view->addFootString($code);
         $event->addAssets([__DIR__ . '/../../js/forum/dist/extension.js']);
         $event->addBootstrapper('sijad/google/analytics/main');
     }
 }
Esempio n. 12
0
 /**
  * @param User $actor
  * @param Post $post
  * @return bool|null
  */
 public function edit(User $actor, Post $post)
 {
     // A post is allowed to be edited if the user has permission to moderate
     // the discussion which it's in, or if they are the author and the post
     // hasn't been deleted by someone else.
     if ($post->user_id == $actor->id && (!$post->hide_time || $post->hide_user_id == $actor->id)) {
         $allowEditing = $this->settings->get('allow_post_editing');
         if ($allowEditing === '-1' || $allowEditing === 'reply' && $post->number >= $post->discussion->last_post_number || $post->time->diffInMinutes(new Carbon()) < $allowEditing) {
             return true;
         }
     }
 }
Esempio n. 13
0
 /**
  * @param RegisterUser $command
  * @throws PermissionDeniedException if signup is closed and the actor is
  *     not an administrator.
  * @throws \Flarum\Core\Exception\InvalidConfirmationTokenException if an
  *     email confirmation token is provided but is invalid.
  * @return User
  */
 public function handle(RegisterUser $command)
 {
     $actor = $command->actor;
     $data = $command->data;
     if (!$this->settings->get('allow_sign_up')) {
         $this->assertAdmin($actor);
     }
     $username = array_get($data, 'attributes.username');
     $email = array_get($data, 'attributes.email');
     $password = array_get($data, 'attributes.password');
     // If a valid authentication token was provided as an attribute,
     // then we won't require the user to choose a password.
     if (isset($data['attributes']['token'])) {
         $token = AuthToken::validOrFail($data['attributes']['token']);
         $password = $password ?: str_random(20);
     }
     $user = User::register($username, $email, $password);
     // If a valid authentication token was provided, then we will assign
     // the attributes associated with it to the user's account. If this
     // includes an email address, then we will activate the user's account
     // from the get-go.
     if (isset($token)) {
         foreach ($token->payload as $k => $v) {
             $user->{$k} = $v;
         }
         if (isset($token->payload['email'])) {
             $user->activate();
         }
     }
     if ($actor->isAdmin() && array_get($data, 'attributes.isActivated')) {
         $user->activate();
     }
     $this->events->fire(new UserWillBeSaved($user, $actor, $data));
     $this->validator->assertValid(array_merge($user->getAttributes(), compact('password')));
     if ($avatarUrl = array_get($data, 'attributes.avatarUrl')) {
         $validation = $this->validatorFactory->make(compact('avatarUrl'), ['avatarUrl' => 'url']);
         if ($validation->fails()) {
             throw new ValidationException($validation);
         }
         try {
             $this->saveAvatarFromUrl($user, $avatarUrl);
         } catch (Exception $e) {
             //
         }
     }
     $user->save();
     if (isset($token)) {
         $token->delete();
     }
     $this->dispatchEventsFor($user, $actor);
     return $user;
 }
 /**
  * Uploads raw contents to the service.
  *
  * @param string $contents
  * @return array    The meta of the file.
  */
 public function uploadContents($name, $contents)
 {
     $this->filesystem->write($name, $contents);
     $meta = $this->filesystem->getMetadata($name);
     $urlGenerator = app('Flarum\\Forum\\UrlGenerator');
     if (empty($this->settings->get('flagrow.image-upload.cdnUrl'))) {
         // if there is no cdnUrl
         $meta['url'] = $urlGenerator->toPath('assets/images/' . $name);
     } else {
         // if there is
         $meta['url'] = $this->settings->get('flagrow.image-upload.cdnUrl') . 'assets/images/' . $name;
     }
     return $meta;
 }
 /**
  * Handles the command execution.
  *
  * @param UploadImage $command
  * @return null|string
  *
  * @todo check permission
  */
 public function handle(UploadImage $command)
 {
     // check if the user can upload images, otherwise return
     $this->assertCan($command->actor, 'flagrow.image.upload');
     $tmpFile = tempnam($this->app->storagePath() . '/tmp', 'image');
     $command->file->moveTo($tmpFile);
     $file = new UploadedFile($tmpFile, $command->file->getClientFilename(), $command->file->getClientMediaType(), $command->file->getSize(), $command->file->getError(), true);
     // validate the file
     $this->validator->maxFileSize = $this->settings->get('flagrow.image-upload.maxFileSize', 2048);
     $this->validator->assertValid(['image' => $file]);
     // resize if enabled
     if ($this->settings->get('flagrow.image-upload.mustResize')) {
         $manager = new ImageManager();
         $manager->make($tmpFile)->fit($this->settings->get('flagrow.image-upload.resizeMaxWidth', 100), $this->settings->get('flagrow.image-upload.resizeMaxHeight', 100))->save();
     }
     $image = (new Image())->forceFill(['user_id' => $command->actor->id, 'upload_method' => $this->settings->get('flagrow.image-upload.uploadMethod', 'local'), 'created_at' => Carbon::now(), 'file_name' => sprintf('%d-%s.%s', $command->actor->id, Str::quickRandom(), $file->guessExtension() ?: 'jpg'), 'file_size' => $file->getSize()]);
     // fire the Event ImageWillBeSaved, which can be extended and/or modified elsewhere
     $this->events->fire(new ImageWillBeSaved($command->actor, $image, $file));
     $tmpFilesystem = new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME)));
     $meta = $this->upload->uploadContents($image->file_name, $tmpFilesystem->readAndDelete(pathinfo($tmpFile, PATHINFO_BASENAME)));
     if ($meta) {
         $image->file_url = array_get($meta, 'url');
         if ($image->isDirty()) {
             $image->save();
         }
         return $image;
     }
     return false;
 }
Esempio n. 16
0
 /**
  * @param RequestPasswordReset $command
  * @return \Flarum\Core\User
  * @throws ModelNotFoundException
  */
 public function handle(RequestPasswordReset $command)
 {
     $user = $this->users->findByEmail($command->email);
     if (!$user) {
         throw new ModelNotFoundException();
     }
     $token = PasswordToken::generate($user->id);
     $token->save();
     $data = ['{username}' => $user->username, '{url}' => $this->url->toRoute('resetPassword', ['token' => $token->id]), '{forum}' => $this->settings->get('forum_title')];
     $body = $this->translator->trans('core.email.reset_password.body', $data);
     $this->mailer->raw($body, function (Message $message) use($user, $data) {
         $message->to($user->email);
         $message->subject('[' . $data['{forum}'] . '] ' . $this->translator->trans('core.email.reset_password.subject'));
     });
     return $user;
 }
Esempio n. 17
0
 /**
  * @param PrepareApiAttributes $event
  */
 public function prepareApiAttributes(PrepareApiAttributes $event)
 {
     if ($event->isSerializer(ForumSerializer::class)) {
         $event->attributes['canViewFlags'] = $event->actor->hasPermissionLike('discussion.viewFlags');
         if ($event->attributes['canViewFlags']) {
             $event->attributes['flagsCount'] = (int) $this->getFlagsCount($event->actor);
         }
         $event->attributes['guidelinesUrl'] = $this->settings->get('flarum-flags.guidelines_url');
     }
     if ($event->isSerializer(CurrentUserSerializer::class)) {
         $event->attributes['newFlagsCount'] = (int) $this->getNewFlagsCount($event->model);
     }
     if ($event->isSerializer(PostSerializer::class)) {
         $event->attributes['canFlag'] = $event->actor->can('flag', $event->model);
     }
 }
Esempio n. 18
0
 /**
  * @param $count
  * @throws ValidationException
  */
 protected function validateSecondaryTagCount($count)
 {
     $min = $this->settings->get('flarum-tags.min_secondary_tags');
     $max = $this->settings->get('flarum-tags.max_secondary_tags');
     if ($count < $min || $count > $max) {
         throw new ValidationException(['tags' => sprintf('Discussion must have between %d and %d secondary tags.', $min, $max)]);
     }
 }
Esempio n. 19
0
 /**
  * {@inheritdoc}
  */
 protected function getDefaultAttributes($model)
 {
     $gate = $this->gate->forUser($this->actor);
     $attributes = ['title' => $this->settings->get('forum_title'), 'description' => $this->settings->get('forum_description'), 'baseUrl' => $url = $this->app->url(), 'basePath' => parse_url($url, PHP_URL_PATH) ?: '', 'debug' => $this->app->inDebugMode(), 'apiUrl' => $this->app->url('api'), 'welcomeTitle' => $this->settings->get('welcome_title'), 'welcomeMessage' => $this->settings->get('welcome_message'), 'themePrimaryColor' => $this->settings->get('theme_primary_color'), 'allowSignUp' => (bool) $this->settings->get('allow_sign_up'), 'defaultRoute' => $this->settings->get('default_route'), 'canViewDiscussions' => $gate->allows('viewDiscussions'), 'canStartDiscussion' => $gate->allows('startDiscussion')];
     if ($gate->allows('administrate')) {
         $attributes['adminUrl'] = $this->app->url('admin');
         $attributes['version'] = $this->app->version();
     }
     return $attributes;
 }
Esempio n. 20
0
 public function subscribe(Dispatcher $event)
 {
     if (static::$called) {
         return;
     }
     // only actively do something in case the default cache driver has been changed
     if ($this->settings->get('hyn.cache.driver', 'file') != 'file') {
         /** @var \Illuminate\Contracts\Config\Repository $config */
         $config = $this->application->make('config');
         $cacheConfig = ['driver' => $this->settings->get('hyn.cache.driver')];
         switch ($this->settings->get('hyn.cache.driver')) {
             case 'database':
                 $merge = ['table' => $this->settings->get('hyn.cache.table', 'cache'), 'connection' => $this->settings->get('hyn.cache.connection')];
                 break;
             case 'redis':
                 $merge = ['connection' => $this->settings->get('hyn.cache.connection')];
                 break;
             case 'memcached':
                 // @todo..
                 break;
             default:
                 $merge = [];
         }
         // merges driver specific settings into the config
         $cacheConfig = array_merge($cacheConfig, $merge);
         // sets the cache store
         $config->set('cache.stores.hyn-cache', $cacheConfig);
         $config->set('cache.driver', 'hyn-cache');
     }
 }
 /**
  * This method checks, if the user is still allowed to edit the tags
  * based on the configuration item.
  *
  * @param User $actor
  * @param Discussion $discussion
  * @return bool
  */
 public function tag(User $actor, Discussion $discussion)
 {
     if ($discussion->start_user_id == $actor->id) {
         $allowEditTags = $this->settings->get('allow_tag_change');
         if ($allowEditTags === '-1' || $allowEditTags === 'reply' && $discussion->participants_count <= 1 || $discussion->start_time->diffInMinutes(new Carbon()) < $allowEditTags) {
             return true;
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function handle(ServerRequestInterface $request)
 {
     $id = array_get($request->getQueryParams(), 'id');
     $actor = $request->getAttribute('actor');
     $this->assertRegistered($actor);
     if ($actor->id != $id || $actor->is_activated) {
         throw new PermissionDeniedException();
     }
     $token = EmailToken::generate($actor->email, $actor->id);
     $token->save();
     $data = ['{username}' => $actor->username, '{url}' => $this->url->toRoute('confirmEmail', ['token' => $token->id]), '{forum}' => $this->settings->get('forum_title')];
     $body = $this->translator->trans('core.email.activate_account.body', $data);
     $this->mailer->raw($body, function (Message $message) use($actor, $data) {
         $message->to($actor->email);
         $message->subject('[' . $data['{forum}'] . '] ' . $this->translator->trans('core.email.activate_account.subject'));
     });
     return new EmptyResponse();
 }
Esempio n. 23
0
 /**
  * @param SettingsRepositoryInterface $settings
  * @param boolean $throw
  * @throws SingleSOException
  * @return array
  */
 public static function settingsAuth(SettingsRepositoryInterface $settings, $throw)
 {
     // Add all auth settings to array.
     $data = [];
     foreach (static::$settingsAuthKeys as $key => $required) {
         $val = $settings->get('singleso-singleso-flarum.' . $key);
         // Throw exception if any required settings are missing.
         if ($required && !$val) {
             // Throw on missing values or just return null.
             if ($throw) {
                 throw new SingleSOException(['Not fully configured.']);
             }
             return null;
         }
         $data[$key] = $val;
     }
     return $data;
 }
 /**
  * @param Request $request
  * @param array $routeParams
  * @return \Psr\Http\Message\ResponseInterface|RedirectResponse
  */
 public function handle(Request $request, array $routeParams = [])
 {
     session_start();
     $provider = new Facebook(['clientId' => $this->settings->get('flarum-auth-facebook.app_id'), 'clientSecret' => $this->settings->get('flarum-auth-facebook.app_secret'), 'redirectUri' => $this->url->toRoute('auth.facebook'), 'graphApiVersion' => 'v2.4']);
     if (!isset($_GET['code'])) {
         $authUrl = $provider->getAuthorizationUrl(['scope' => ['email']]);
         $_SESSION['oauth2state'] = $provider->getState();
         return new RedirectResponse($authUrl);
     } elseif (empty($_GET['state']) || $_GET['state'] !== $_SESSION['oauth2state']) {
         unset($_SESSION['oauth2state']);
         echo 'Invalid state.';
         exit;
     }
     $token = $provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
     $owner = $provider->getResourceOwner($token);
     $email = $owner->getEmail();
     $username = preg_replace('/[^a-z0-9-_]/i', '', $owner->getName());
     return $this->authenticate(compact('email'), compact('username'));
 }
 /**
  * @param string $type
  * @param int $count
  * @throws ValidationException
  */
 protected function validateTagCount($type, $count)
 {
     $min = $this->settings->get('flarum-tags.min_' . $type . '_tags');
     $max = $this->settings->get('flarum-tags.max_' . $type . '_tags');
     $key = 'tag_count_' . $type;
     $validator = $this->validator->make([$key => $count], [$key => ['numeric', $min === $max ? "size:{$min}" : "between:{$min},{$max}"]]);
     if ($validator->fails()) {
         throw new ValidationException([], ['tags' => $validator->getMessageBag()->first($key)]);
     }
 }
 /**
  * @param Request $request
  * @param array $routeParams
  * @return \Psr\Http\Message\ResponseInterface|RedirectResponse
  */
 public function handle(Request $request, array $routeParams = [])
 {
     session_start();
     $server = new Twitter(array('identifier' => $this->settings->get('flarum-auth-twitter.api_key'), 'secret' => $this->settings->get('flarum-auth-twitter.api_secret'), 'callback_uri' => $this->url->toRoute('auth.twitter')));
     if (!isset($_GET['oauth_token']) || !isset($_GET['oauth_verifier'])) {
         $temporaryCredentials = $server->getTemporaryCredentials();
         $_SESSION['temporary_credentials'] = serialize($temporaryCredentials);
         session_write_close();
         // Second part of OAuth 1.0 authentication is to redirect the
         // resource owner to the login screen on the server.
         $server->authorize($temporaryCredentials);
         exit;
     }
     // Retrieve the temporary credentials we saved before
     $temporaryCredentials = unserialize($_SESSION['temporary_credentials']);
     // We will now retrieve token credentials from the server
     $tokenCredentials = $server->getTokenCredentials($temporaryCredentials, $_GET['oauth_token'], $_GET['oauth_verifier']);
     $user = $server->getUserDetails($tokenCredentials);
     return $this->authenticate(['twitter_id' => $user->uid], ['username' => $user->nickname]);
 }
 /**
  * @param Request $request
  * @param array $routeParams
  * @return \Psr\Http\Message\ResponseInterface|RedirectResponse
  */
 public function handle(Request $request, array $routeParams = [])
 {
     session_start();
     $provider = new Qq(['clientId' => $this->settings->get('lazyboywu-auth-qq.client_id'), 'clientSecret' => $this->settings->get('lazyboywu-auth-qq.client_secret'), 'redirectUri' => $this->url->toRoute('auth.qq')]);
     if (!isset($_GET['code'])) {
         $authUrl = $provider->getAuthorizationUrl();
         $_SESSION['oauth2state'] = $provider->getState();
         return new RedirectResponse($authUrl);
     } elseif (empty($_GET['state']) || $_GET['state'] !== $_SESSION['oauth2state']) {
         unset($_SESSION['oauth2state']);
         echo 'Invalid state.';
         exit;
     }
     $token = $provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
     $owner = $provider->getResourceOwner($token);
     $qqopenid = $owner->getOpenId();
     $username = preg_replace('/[^a-z0-9-_]/i', '', $owner->getNickname());
     $avatar_path = $owner->getFigureUrl();
     return $this->authenticate(compact('qqopenid'), compact('username'));
 }
Esempio n. 28
0
 /**
  * @param Request $request
  * @param array $routeParams
  * @return \Psr\Http\Message\ResponseInterface|RedirectResponse
  */
 public function handle(Request $request, array $routeParams = [])
 {
     session_start();
     $provider = new QQ(['clientId' => $this->settings->get('azonwan-auth-qq.client_id'), 'clientSecret' => $this->settings->get('azonwan-auth-qq.client_secret'), 'redirectUri' => $this->url->toRoute('auth.qq')]);
     if (!isset($_GET['code'])) {
         $authUrl = $provider->getAuthorizationUrl(['grant_type' => ['authorization_code']]);
         $_SESSION['oauth2state'] = $provider->getState();
         return new RedirectResponse($authUrl);
     } elseif (empty($_GET['state']) || $_GET['state'] !== $_SESSION['oauth2state']) {
         unset($_SESSION['oauth2state']);
         echo 'Invalid state.';
         exit;
     }
     $token = $provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
     $openid = $provider->getAccessOpenId('authorization_code', ['access_token' => $token->getToken(), 'code' => $_GET['code']]);
     $options = ['openid' => $openid, 'access_token' => $token->getToken(), 'oauth_consumer_key' => $this->settings->get('azonwan-auth-qq.client_id')];
     $owner = $provider->getResourceOwner($token, $options);
     $username = preg_replace('/[^a-z0-9-_]/i', '', $owner->getName()) . "_qq";
     return $this->authenticate(compact('username'));
 }
 /**
  * @param Request $request
  * @param array $routeParams
  * @return \Psr\Http\Message\ResponseInterface|RedirectResponse
  */
 public function handle(Request $request, array $routeParams = [])
 {
     session_start();
     $server = new Magento(array('host' => $this->settings->get('vovayatsyuk-auth-magento.store_url'), 'identifier' => $this->settings->get('vovayatsyuk-auth-magento.api_key'), 'secret' => $this->settings->get('vovayatsyuk-auth-magento.api_secret'), 'callback_uri' => $this->url->toRoute('auth.magento')));
     if (!isset($_GET['oauth_token']) || !isset($_GET['oauth_verifier'])) {
         $temporaryCredentials = $server->getTemporaryCredentials();
         $_SESSION['temporary_credentials'] = serialize($temporaryCredentials);
         session_write_close();
         // Second part of OAuth 1.0 authentication is to redirect the
         // resource owner to the login screen on the server.
         $server->authorize($temporaryCredentials);
         exit;
     }
     // Retrieve the temporary credentials we saved before
     $temporaryCredentials = unserialize($_SESSION['temporary_credentials']);
     // We will now retrieve token credentials from the server
     $tokenCredentials = $server->getTokenCredentials($temporaryCredentials, $_GET['oauth_token'], $_GET['oauth_verifier']);
     $user = $server->getUserDetails($tokenCredentials);
     $email = $user->email;
     $username = preg_replace('/[^a-z0-9-_]/i', '', $user->firstName . $user->lastName);
     return $this->authenticate(compact('email'), compact('username'));
 }
 /**
  * @param Request $request
  * @return \Psr\Http\Message\ResponseInterface|RedirectResponse
  */
 public function handle(Request $request)
 {
     $redirectUri = $request->getOriginalRequest()->getUri()->withQuery('');
     $session = $request->getAttribute('session');
     $queryParams = $request->getQueryParams();
     $oidSig = array_get($queryParams, 'openid_sig');
     if (!$oidSig) {
         return new RedirectResponse((string) (new Uri(SteamAuthController::LOGIN_URL))->withQuery(http_build_query(['openid.ns' => 'http://specs.openid.net/auth/2.0', 'openid.mode' => 'checkid_setup', 'openid.identity' => 'http://specs.openid.net/auth/2.0/identifier_select', 'openid.claimed_id' => 'http://specs.openid.net/auth/2.0/identifier_select', 'openid.return_to' => (string) $redirectUri, 'openid.realm' => (string) $redirectUri->withPath('')])));
     }
     $query = ['openid.ns' => 'http://specs.openid.net/auth/2.0', 'openid.sig' => array_get($queryParams, 'openid_sig')];
     foreach (explode(',', array_get($queryParams, 'openid_signed')) as $param) {
         $query['openid.' . $param] = array_get($queryParams, 'openid_' . $param);
     }
     // do not let overwrite this one via openid_signed
     $query['openid.mode'] = 'check_authentication';
     $client = new Client();
     try {
         $res = $client->request('POST', SteamAuthController::LOGIN_URL, ['form_params' => $query]);
     } catch (Exception $e) {
         return new Response("Can't Verify OpenID", 500);
     }
     if ($res->getStatusCode() === 200 and preg_match("/^is_valid:true+\$/im", (string) $res->getBody()) === 1) {
         if ($steam_id = array_get($queryParams, 'openid_claimed_id') and $steam_id = basename($steam_id) and is_numeric($steam_id)) {
             try {
                 $res = $client->request('GET', SteamAuthController::API_URL, ['query' => ['key' => $this->settings->get('sijad-auth-steam.api_key'), 'steamids' => $steam_id]]);
             } catch (Exception $e) {
                 return new Response("Can't Get User Info", 500);
             }
             if ($info = json_decode((string) $res->getBody(), true)) {
                 $identification = ['steam_id' => $steam_id];
                 $suggestions = ['username' => $info['response']['players'][0]['personaname'], 'avatarUrl' => $info['response']['players'][0]['avatarfull']];
                 return $this->authResponse->make($request, $identification, $suggestions);
             }
         }
     }
     return new Response("Can't Get User Info", 500);
 }