cutelyst  4.8.0
A C++ Web Framework built on top of Qt, using the simple approach of Catalyst (Perl) framework.
csrf.cpp
1 /*
2  * SPDX-FileCopyrightText: (C) 2017-2022 Matthias Fehring <mf@huessenbergnetz.de>
3  * SPDX-License-Identifier: BSD-3-Clause
4  */
5 #include "csrf.h"
6 
7 #include <Cutelyst/Context>
8 #include <Cutelyst/ParamsMultiMap>
9 #include <Cutelyst/Request>
10 #include <Cutelyst/Response>
11 #include <cutelee/exception.h>
12 #include <cutelee/parser.h>
13 
14 #ifdef PLUGIN_CSRFPROTECTION_ENABLED
15 # include <Cutelyst/Plugins/CSRFProtection/CSRFProtection>
16 #endif
17 
18 Cutelee::Node *CSRFTag::getNode(const QString &tagContent, Cutelee::Parser *p) const
19 {
20  Q_UNUSED(tagContent);
21  return new CSRF(p);
22 }
23 
24 CSRF::CSRF(Cutelee::Parser *parser)
25  : Cutelee::Node(parser)
26 {
27 }
28 
29 void CSRF::render(Cutelee::OutputStream *stream, Cutelee::Context *gc) const
30 {
31 #ifdef PLUGIN_CSRFPROTECTION_ENABLED
32  // In case cutelyst context is not set as "c"
33  auto c = gc->lookup(m_cutelystContext).value<Cutelyst::Context *>();
34  if (!c) {
35  const QVariantHash hash = gc->stackHash(0);
36  auto it = hash.constBegin();
37  while (it != hash.constEnd()) {
38  if (it.value().userType() == qMetaTypeId<Cutelyst::Context *>()) {
39  c = it.value().value<Cutelyst::Context *>();
40  if (c) {
41  m_cutelystContext = it.key();
42  break;
43  }
44  }
45  ++it;
46  }
47 
48  if (!c) {
49  return;
50  }
51  }
52 
53  *stream << Cutelyst::CSRFProtection::getTokenFormField(c);
54 #else
55  Q_UNUSED(stream)
56  Q_UNUSED(gc)
57  qWarning("%s", "The CSRF protection plugin has not been built.");
58 #endif
59 }
60 
61 Cutelee::Node *CSRFTokenTag::getNode(const QString &tagContent, Cutelee::Parser *p) const
62 {
63  Q_UNUSED(tagContent);
64  return new CSRFToken(p);
65 }
66 
67 CSRFToken::CSRFToken(Cutelee::Parser *parser)
68  : Cutelee::Node(parser)
69 {
70 }
71 
72 void CSRFToken::render(Cutelee::OutputStream *stream, Cutelee::Context *gc) const
73 {
74 #ifdef PLUGIN_CSRFPROTECTION_ENABLED
75  // In case cutelyst context is not set as "c"
76  auto c = gc->lookup(m_cutelystContext).value<Cutelyst::Context *>();
77  if (!c) {
78  const QVariantHash hash = gc->stackHash(0);
79  auto it = hash.constBegin();
80  while (it != hash.constEnd()) {
81  if (it.value().userType() == qMetaTypeId<Cutelyst::Context *>()) {
82  c = it.value().value<Cutelyst::Context *>();
83  if (c) {
84  m_cutelystContext = it.key();
85  break;
86  }
87  }
88  ++it;
89  }
90 
91  if (!c) {
92  return;
93  }
94  }
95 
96  *stream << QString::fromLatin1(Cutelyst::CSRFProtection::getToken(c));
97 #else
98  Q_UNUSED(stream)
99  Q_UNUSED(gc)
100  qWarning("%s", "The CSRF protection plugin has not been built.");
101 #endif
102 }
103 
104 #include "moc_csrf.cpp"
The Cutelyst Context.
Definition: context.h:42
QString fromLatin1(QByteArrayView str)