Passed
Pull Request — master (#125)
by MusikAnimal
03:53
created

DefaultController   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 152
Duplicated Lines 0 %

Test Coverage

Coverage 43.33%

Importance

Changes 0
Metric Value
dl 0
loc 152
ccs 13
cts 30
cp 0.4333
rs 10
c 0
b 0
f 0
wmc 13

5 Methods

Rating   Name   Duplication   Size   Complexity  
A indexAction() 0 6 1
A loginAction() 0 16 2
A getOauthClient() 0 17 2
A configAction() 0 21 4
B oauthCallbackAction() 0 26 2
1
<?php
2
/**
3
 * This file contains only the DefaultController class.
4
 */
5
6
namespace AppBundle\Controller;
7
8
use MediaWiki\OAuthClient\Client;
9
use MediaWiki\OAuthClient\ClientConfig;
10
use MediaWiki\OAuthClient\Consumer;
11
use MediaWiki\OAuthClient\Exception;
12
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
13
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
14
use Symfony\Component\HttpFoundation\RedirectResponse;
15
use Symfony\Component\HttpFoundation\Request;
16
use Symfony\Component\HttpFoundation\Session\Session;
17
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
18
use Xtools\ProjectRepository;
19
20
/**
21
 * The DefaultController handles the homepage, about pages, and user authentication.
22
 */
23
class DefaultController extends XtoolsController
24
{
25
    /** @var Client The Oauth HTTP client. */
26
    protected $oauthClient;
27
28
    /**
29
     * Display the homepage.
30
     * @Route("/", name="homepage")
31
     * @Route("/index.php", name="homepageIndexPhp")
32
     */
33 1
    public function indexAction()
34
    {
35
        // replace this example code with whatever you need
36 1
        return $this->render('default/index.html.twig', [
37 1
            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..'),
38 1
            'xtPage' => 'home',
39
        ]);
40
    }
41
42
    /**
43
     * Diplay XTools' about page.
44
     * @Route("/about", name="aboutPage")
45
     * @Route("/info.php", name="info")
46
     */
47 1
    public function aboutAction()
48
    {
49 1
        return $this->render('default/about.html.twig', [
50 1
            'xtPage' => 'about',
51
        ]);
52
    }
53
54
    /**
55
     * Display some configuration details, when in development mode.
56
     * @Route("/config", name="configPage")
57
     * @codeCoverageIgnore
58
     */
59
    public function configAction()
60
    {
61
62
        if ($this->container->getParameter('kernel.environment') !== 'dev') {
63
            throw new NotFoundHttpException();
64
        }
65
66
        $params = $this->container->getParameterBag()->all();
0 ignored issues
show
Bug introduced by
The method getParameterBag() does not exist on Symfony\Component\Depend...tion\ContainerInterface. Did you maybe mean getParameter()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

66
        $params = $this->container->/** @scrutinizer ignore-call */ getParameterBag()->all();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
67
68
        foreach ($params as $key => $value) {
69
            if (strpos($key, 'password') !== false) {
70
                $params[$key] = '<REDACTED>';
71
            }
72
        }
73
74
        // replace this example code with whatever you need
75
        return $this->render('default/config.html.twig', [
76
            'xtTitle' => 'Config',
77
            'xtPageTitle' => 'Config',
78
            'xtPage' => 'index',
79
            'dump' => print_r($params, true),
80
        ]);
81
    }
82
83
    /**
84
     * Redirect to the default project (or Meta) for Oauth authentication.
85
     * @Route("/login", name="login")
86
     * @return RedirectResponse
87
     * @throws Exception If initialization fails.
88
     */
89
    public function loginAction()
90
    {
91
        try {
92
            list( $next, $token ) = $this->getOauthClient()->initiate();
93
        } catch (Exception $oauthException) {
94
            throw $oauthException;
95
            // @TODO Make this work.
96
            //$this->addFlash('error', $oauthException->getMessage());
97
            //return $this->redirectToRoute('homepage');
98
        }
99
100
        // Save the request token to the session.
101
        /** @var Session $session */
102
        $session = $this->get('session');
103
        $session->set('oauth_request_token', $token);
104
        return new RedirectResponse($next);
105
    }
106
107
    /**
108
     * Receive authentication credentials back from the Oauth wiki.
109
     * @Route("/oauth_callback", name="oauth_callback")
110
     * @Route("/oauthredirector.php", name="old_oauth_callback")
111
     * @param Request $request The HTTP request.
112
     * @return RedirectResponse
113
     */
114 1
    public function oauthCallbackAction(Request $request)
115
    {
116
        // Give up if the required GET params don't exist.
117 1
        if (!$request->get('oauth_verifier')) {
118 1
            throw $this->createNotFoundException('No OAuth verifier given.');
119
        }
120
121
        /** @var Session $session */
122
        $session = $this->get('session');
123
124
        // Complete authentication.
125
        $client = $this->getOauthClient();
126
        $token = $session->get('oauth_request_token');
127
        $verifier = $request->get('oauth_verifier');
128
        $accessToken = $client->complete($token, $verifier);
129
130
        // Store access token, and remove request token.
131
        $session->set('oauth_access_token', $accessToken);
132
        $session->remove('oauth_request_token');
133
134
        // Store user identity.
135
        $ident = $client->identify($accessToken);
136
        $session->set('logged_in_user', $ident);
137
138
        // Send back to homepage.
139
        return $this->redirectToRoute('homepage');
140
    }
141
142
    /**
143
     * Get an OAuth client, configured to the default project.
144
     * (This shouldn't really be in this class, but oh well.)
145
     * @return Client
146
     * @codeCoverageIgnore
147
     */
148
    protected function getOauthClient()
149
    {
150
        if ($this->oauthClient instanceof Client) {
151
            return $this->oauthClient;
152
        }
153
        $defaultProject = ProjectRepository::getDefaultProject($this->container);
154
        $endpoint = $defaultProject->getUrl(false)
155
                    . $defaultProject->getScript()
156
                    . '?title=Special:OAuth';
157
        $conf = new ClientConfig($endpoint);
158
        $consumerKey = $this->getParameter('oauth_key');
159
        $consumerSecret =  $this->getParameter('oauth_secret');
160
        $conf->setConsumer(new Consumer($consumerKey, $consumerSecret));
161
        $this->oauthClient = new Client($conf);
162
        // Callback URL is hardcoded in the consumer registration.
163
        $this->oauthClient->setCallback('oob');
164
        return $this->oauthClient;
165
    }
166
167
    /**
168
     * Log out the user and return to the homepage.
169
     * @Route("/logout", name="logout")
170
     */
171 1
    public function logoutAction()
172
    {
173 1
        $this->get('session')->invalidate();
174 1
        return $this->redirectToRoute('homepage');
175
    }
176
}
177