Completed
Pull Request — master (#37)
by Benjamin
02:45
created

NodeController::isAuthenticated()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 17
rs 9.2
cc 4
eloc 10
nc 6
nop 1
1
<?php
2
3
namespace Alpixel\Bundle\CMSBundle\Controller;
4
5
use Alpixel\Bundle\CMSBundle\Entity\Node;
6
use Alpixel\Bundle\SEOBundle\Annotation\MetaTag;
7
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
8
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
9
use Symfony\Component\Debug\Exception\ContextErrorException;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\Response;
12
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
13
use Symfony\Component\Serializer\Serializer;
14
15
class NodeController extends Controller
16
{
17
    /**
18
     * @Method({"GET", "POST"})
19
     * @param Request $request
20
     * @param         $slug
21
     *
22
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
23
     */
24
    public function dispatchAction(Request $request, $slug)
25
    {
26
        $entityManager = $this->get('doctrine.orm.entity_manager');
27
        $node = $entityManager->getRepository('AlpixelCMSBundle:Node')
28
                              ->findOneBySlugAndLocale($slug, $request->getLocale());
29
30
        if ($node !== null) {
31
            if ($node->getPublished() === false && !$this->isAuthenticated($request)) {
32
                throw $this->createNotFoundException();
33
            }
34
35
            $contentType = $this->get('alpixel_cms.helper.cms')->getContentTypeFromNodeElementClass($node);
36
            $controller = explode('::', $contentType['controller']);
37
38
            try {
39
                if (count($controller) !== 2) {
40
                    throw new \LogicException('The parameter controller must be a valid callable controller, like "My\Namespace\Controller\Class::method"');
41
                } elseif (!class_exists($controller[0]) || !method_exists($controller[0], $controller[1])) {
42
                    throw new \LogicException(sprintf(
43
                        'Unable to find the "%s" controller or the method "%s" doesn\'t exist.',
44
                        $controller[0],
45
                        $controller[1]
46
                    ));
47
                }
48
49
                return $this->forward($contentType['controller'], [
50
                    '_route'        => $request->attributes->get('_route'),
51
                    '_route_params' => $request->attributes->get('_route_params'),
52
                    'object'        => $node,
53
                ]);
54
            } catch (\LogicException $e) {
55
                $environment = $this->container->get('kernel')->getEnvironment();
56
                if ($environment === 'prod') {
57
                    $logger = $this->get('logger');
58
                    $logger->error($e->getMessage());
59
                } else {
60
                    throw $e;
61
                }
62
            }
63
        } else {
64
            //Trying to find another node with this slug, in another language
65
            $node = $entityManager->getRepository('AlpixelCMSBundle:Node')
66
                                  ->findOnePublishedBySlug($slug);
67
68
            if ($node !== null) {
69
                $translation = $entityManager->getRepository('AlpixelCMSBundle:Node')
70
                                             ->findTranslation($node, $request->getLocale());
71
                if ($translation !== null) {
72
                    return $this->redirect($this->generateUrl('alpixel_cms', [
73
                        'slug'    => $translation->getSlug(),
74
                        '_locale' => $translation->getLocale(),
75
                    ]));
76
                }
77
            }
78
        }
79
80
        throw $this->createNotFoundException();
81
    }
82
83
    /**
84
     * @param $node
85
     *
86
     * @return Response
87
     */
88
    public function displayNodeAdminBarAction(Request $request, $node)
89
    {
90
        $entityManager = $this->get('doctrine.orm.entity_manager');
91
        $node = $entityManager->getRepository('AlpixelCMSBundle:Node')->find($node);
92
93
        $response = new Response();
94
        $response->setPrivate();
95
        $response->setMaxAge(900);
96
97
        if ($this->isAuthenticated($request)) {
98
            $content = $this->renderView('AlpixelCMSBundle:admin:blocks/admin_bar_page.html.twig', [
99
                'node' => $node,
100
                'link' => $this->generateUrl('alpixel_admin_cms_node_forwardEdit', [
101
                    'type' => $node->getType(),
102
                    'id'   => $node->getId()
103
                ]),
104
            ]);
105
            $response->setContent($content);
106
        }
107
108
        return $response;
109
    }
110
111
    /**
112
     * @param $link
113
     *
114
     * @return Response
115
     */
116
    public function displayCustomAdminBarAction(Request $request, $link)
117
    {
118
        $response = new Response();
119
        $response->setPrivate();
120
        $response->setMaxAge(900);
121
122
        if ($this->isAuthenticated($request)) {
123
            $content = $this->renderView('AlpixelCMSBundle:admin:blocks/admin_bar_page.html.twig', [
124
                'link' => $link,
125
            ]);
126
            $response->setContent($content);
127
        }
128
129
        return $response;
130
    }
131
132
    /**
133
     * @param Request $request
134
     */
135
    private function isAuthenticated(Request $request)
136
    {
137
        $canEdit = $request->cookies->get('can_edit');
138
139
        if (isset($canEdit)) {
140
            if ($request->getSession()->has('_security_admin')) {
141
                try {
142
                    $token = unserialize($request->getSession()->get('_security_admin'));
143
                    $user = $token->getUser();
144
                    return ($canEdit === hash('sha256', 'can_edit' . $this->container->getParameter('secret') . $user->getSalt()));
145
                } catch (ContextErrorException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
146
147
                }
148
            }
149
        }
150
        return false;
151
    }
152
}
153