Line data Source code
1 : #ifndef THINGER_HTTP_COOKIE_HPP
2 : #define THINGER_HTTP_COOKIE_HPP
3 :
4 : #include <string>
5 : #include <cstdint>
6 : #include <optional>
7 : #include <vector>
8 :
9 : namespace thinger::http{
10 :
11 : enum class same_site_policy {
12 : none,
13 : lax,
14 : strict
15 : };
16 :
17 : class cookie {
18 : public:
19 : // constructors
20 96 : cookie() = default;
21 : cookie(std::string name, std::string value);
22 160 : virtual ~cookie() = default;
23 :
24 : // parsing
25 : static cookie parse(const std::string& cookie_string);
26 :
27 : // setters
28 : cookie& set_name(std::string name);
29 : cookie& set_value(std::string value);
30 : cookie& set_path(std::string path);
31 : cookie& set_domain(std::string domain);
32 : cookie& set_expires(int64_t expires);
33 : cookie& set_max_age(std::optional<int64_t> max_age);
34 : cookie& set_secure(bool secure);
35 : cookie& set_http_only(bool http_only);
36 : cookie& set_same_site(same_site_policy policy);
37 :
38 : // getters
39 : [[nodiscard]] const std::string& get_name() const;
40 : [[nodiscard]] const std::string& get_value() const;
41 : [[nodiscard]] const std::string& get_path() const;
42 : [[nodiscard]] const std::string& get_domain() const;
43 : [[nodiscard]] int64_t get_expires() const;
44 : [[nodiscard]] std::optional<int64_t> get_max_age() const;
45 : [[nodiscard]] bool is_secure() const;
46 : [[nodiscard]] bool is_http_only() const;
47 : [[nodiscard]] same_site_policy get_same_site() const;
48 :
49 : // validity
50 : [[nodiscard]] bool is_valid() const;
51 : [[nodiscard]] bool is_expired() const;
52 :
53 : // serialization
54 : [[nodiscard]] std::string to_string() const;
55 :
56 : private:
57 : std::string name_;
58 : std::string value_;
59 : std::string path_;
60 : std::string domain_;
61 : int64_t expires_ = 0;
62 : std::optional<int64_t> max_age_;
63 : bool secure_ = false;
64 : bool http_only_ = false;
65 : same_site_policy same_site_ = same_site_policy::lax;
66 :
67 : // helpers for parsing
68 : static std::string trim(const std::string& str);
69 : static bool iequals(const std::string& a, const std::string& b);
70 : // The parts of a Set-Cookie header between semicolons, trimmed, without empty ones
71 : static std::vector<std::string> split_parts(const std::string& cookie_string);
72 : // An attribute after name=value: name=value, or a flag without value
73 : void set_attribute(const std::string& part);
74 : void set_max_age_attribute(const std::string& value);
75 : };
76 :
77 : }
78 :
79 : #endif
|