cutelyst  5.0.1
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  for (const auto &[key, value] : hash.asKeyValueRange()) {
37  if (value.userType() == qMetaTypeId<Cutelyst::Context *>()) {
38  c = value.value<Cutelyst::Context *>();
39  if (c) {
40  m_cutelystContext = key;
41  break;
42  }
43  }
44  }
45 
46  if (!c) {
47  return;
48  }
49  }
50 
51  *stream << Cutelyst::CSRFProtection::getTokenFormField(c);
52 #else
53  Q_UNUSED(stream)
54  Q_UNUSED(gc)
55  qWarning("%s", "The CSRF protection plugin has not been built.");
56 #endif
57 }
58 
59 Cutelee::Node *CSRFTokenTag::getNode(const QString &tagContent, Cutelee::Parser *p) const
60 {
61  Q_UNUSED(tagContent);
62  return new CSRFToken(p);
63 }
64 
65 CSRFToken::CSRFToken(Cutelee::Parser *parser)
66  : Cutelee::Node(parser)
67 {
68 }
69 
70 void CSRFToken::render(Cutelee::OutputStream *stream, Cutelee::Context *gc) const
71 {
72 #ifdef PLUGIN_CSRFPROTECTION_ENABLED
73  // In case cutelyst context is not set as "c"
74  auto c = gc->lookup(m_cutelystContext).value<Cutelyst::Context *>();
75  if (!c) {
76  const QVariantHash hash = gc->stackHash(0);
77  for (const auto &[key, value] : hash.asKeyValueRange()) {
78  if (value.userType() == qMetaTypeId<Cutelyst::Context *>()) {
79  c = value.value<Cutelyst::Context *>();
80  if (c) {
81  m_cutelystContext = key;
82  break;
83  }
84  }
85  }
86 
87  if (!c) {
88  return;
89  }
90  }
91 
92  *stream << QString::fromLatin1(Cutelyst::CSRFProtection::getToken(c));
93 #else
94  Q_UNUSED(stream)
95  Q_UNUSED(gc)
96  qWarning("%s", "The CSRF protection plugin has not been built.");
97 #endif
98 }
99 
100 #include "moc_csrf.cpp"
The Cutelyst Context.
Definition: context.h:42
QString fromLatin1(QByteArrayView str)