Skip to main content

saphir_cookie/
builder.rs

1use std::borrow::Cow;
2
3use time::Tm;
4
5use chrono::{DateTime, TimeZone};
6use {Cookie, SameSite};
7
8/// Structure that follows the builder pattern for building `Cookie` structs.
9///
10/// To construct a cookie:
11///
12///   1. Call [`Cookie::build`](struct.Cookie.html#method.build) to start building.
13///   2. Use any of the builder methods to set fields in the cookie.
14///   3. Call [finish](#method.finish) to retrieve the built cookie.
15///
16/// # Example
17///
18/// ```rust
19/// # extern crate cookie;
20/// extern crate time;
21///
22/// use cookie::Cookie;
23/// use time::Duration;
24///
25/// # fn main() {
26/// let cookie: Cookie = Cookie::build("name", "value")
27///     .domain("www.rust-lang.org")
28///     .path("/")
29///     .secure(true)
30///     .http_only(true)
31///     .max_age(60 * 60 * 24)
32///     .finish();
33/// # }
34/// ```
35#[derive(Debug, Clone)]
36pub struct CookieBuilder<'c> {
37    /// The cookie being built.
38    cookie: Cookie<'c>,
39}
40
41impl<'c> CookieBuilder<'c> {
42    /// Creates a new `CookieBuilder` instance from the given name and value.
43    ///
44    /// This method is typically called indirectly via
45    /// [Cookie::build](struct.Cookie.html#method.build).
46    ///
47    /// # Example
48    ///
49    /// ```rust
50    /// use cookie::Cookie;
51    ///
52    /// let c = Cookie::build("foo", "bar").finish();
53    /// assert_eq!(c.name_value(), ("foo", "bar"));
54    /// ```
55    pub fn new<N, V>(name: N, value: V) -> Self
56    where
57        N: Into<Cow<'c, str>>,
58        V: Into<Cow<'c, str>>,
59    {
60        CookieBuilder {
61            cookie: Cookie::new(name, value),
62        }
63    }
64
65    /// This function is deprecated, please use the expire_ts() or expire_datetime() functions instead.
66    #[deprecated(
67        since = "0.13.1",
68        note = "Use the expire_ts() or expire_datetime() functions instead. It makes the interface independent from time crate. "
69    )]
70    pub fn expires(mut self, when: Tm) -> Self {
71        self.cookie.set_expires(when);
72        self
73    }
74
75    /// Sets the `expires` field in the cookie being built with a timestamp.
76    ///
77    /// # Example
78    ///
79    /// ```rust
80    /// # extern crate cookie;
81    /// extern crate chrono;
82    ///
83    /// use cookie::Cookie;
84    ///
85    /// # fn main() {
86    /// let c = Cookie::build("foo", "bar")
87    ///     .expires_ts(chrono::Local::now().timestamp())
88    ///     .finish();
89    ///
90    /// assert!(c.expires().is_some());
91    /// # }
92    /// ```
93    #[inline]
94    pub fn expires_ts(mut self, when_in_sec: i64) -> Self {
95        let tm: time::Tm = time::at_utc(time::Timespec::new(when_in_sec, 0));
96        self.cookie.set_expires(tm);
97        self
98    }
99
100    /// Sets the `expires` field in the cookie being built with a Utc DateTime.
101    ///
102    /// # Example
103    ///
104    /// ```rust
105    /// # extern crate cookie;
106    ///
107    /// extern crate chrono;
108    /// use cookie::Cookie;
109    ///
110    /// # fn main() {
111    /// let c = Cookie::build("foo", "bar")
112    ///     .expires_datetime(chrono::Utc::now())
113    ///     .finish();
114    ///
115    /// assert!(c.expires().is_some());
116    /// # }
117    /// ```
118    #[inline]
119    pub fn expires_datetime<T>(self, when: DateTime<T>) -> Self
120    where
121        T: TimeZone,
122    {
123        self.expires_ts(when.timestamp())
124    }
125
126    /// Sets the `max_age` field in the cookie being built.
127    ///
128    /// # Example
129    ///
130    /// ```rust
131    /// # extern crate cookie;
132    /// extern crate time;
133    /// use time::Duration;
134    ///
135    /// use cookie::Cookie;
136    ///
137    /// # fn main() {
138    /// let c = Cookie::build("foo", "bar")
139    ///     .max_age(60 * 30) // 30 minutes
140    ///     .finish();
141    ///
142    /// assert_eq!(c.max_age(), Some(60 * 30));
143    /// # }
144    /// ```
145    #[inline]
146    pub fn max_age(mut self, value: u64) -> Self {
147        self.cookie.set_max_age(value);
148        self
149    }
150
151    /// Sets the `domain` field in the cookie being built.
152    ///
153    /// # Example
154    ///
155    /// ```rust
156    /// use cookie::Cookie;
157    ///
158    /// let c = Cookie::build("foo", "bar")
159    ///     .domain("www.rust-lang.org")
160    ///     .finish();
161    ///
162    /// assert_eq!(c.domain(), Some("www.rust-lang.org"));
163    /// ```
164    pub fn domain<D: Into<Cow<'c, str>>>(mut self, value: D) -> Self {
165        self.cookie.set_domain(value);
166        self
167    }
168
169    /// Sets the `path` field in the cookie being built.
170    ///
171    /// # Example
172    ///
173    /// ```rust
174    /// use cookie::Cookie;
175    ///
176    /// let c = Cookie::build("foo", "bar")
177    ///     .path("/")
178    ///     .finish();
179    ///
180    /// assert_eq!(c.path(), Some("/"));
181    /// ```
182    pub fn path<P: Into<Cow<'c, str>>>(mut self, path: P) -> Self {
183        self.cookie.set_path(path);
184        self
185    }
186
187    /// Sets the `secure` field in the cookie being built.
188    ///
189    /// # Example
190    ///
191    /// ```rust
192    /// use cookie::Cookie;
193    ///
194    /// let c = Cookie::build("foo", "bar")
195    ///     .secure(true)
196    ///     .finish();
197    ///
198    /// assert_eq!(c.secure(), Some(true));
199    /// ```
200    #[inline]
201    pub fn secure(mut self, value: bool) -> Self {
202        self.cookie.set_secure(value);
203        self
204    }
205
206    /// Sets the `http_only` field in the cookie being built.
207    ///
208    /// # Example
209    ///
210    /// ```rust
211    /// use cookie::Cookie;
212    ///
213    /// let c = Cookie::build("foo", "bar")
214    ///     .http_only(true)
215    ///     .finish();
216    ///
217    /// assert_eq!(c.http_only(), Some(true));
218    /// ```
219    #[inline]
220    pub fn http_only(mut self, value: bool) -> Self {
221        self.cookie.set_http_only(value);
222        self
223    }
224
225    /// Sets the `same_site` field in the cookie being built.
226    ///
227    /// # Example
228    ///
229    /// ```rust
230    /// use cookie::{Cookie, SameSite};
231    ///
232    /// let c = Cookie::build("foo", "bar")
233    ///     .same_site(SameSite::Strict)
234    ///     .finish();
235    ///
236    /// assert_eq!(c.same_site(), Some(SameSite::Strict));
237    /// ```
238    #[inline]
239    pub fn same_site(mut self, value: SameSite) -> Self {
240        self.cookie.set_same_site(value);
241        self
242    }
243
244    /// Makes the cookie being built 'permanent' by extending its expiration and
245    /// max age 20 years into the future.
246    ///
247    /// # Example
248    ///
249    /// ```rust
250    /// # extern crate cookie;
251    /// extern crate time;
252    ///
253    /// use cookie::Cookie;
254    /// use time::Duration;
255    ///
256    /// # fn main() {
257    /// let c = Cookie::build("foo", "bar")
258    ///     .permanent()
259    ///     .finish();
260    ///
261    /// let twenty_years = 60 * 60 * 24 * 365 * 20;
262    /// assert_eq!(c.max_age(), Some(twenty_years));
263    /// # assert!(c.expires().is_some());
264    /// # }
265    /// ```
266    #[inline]
267    pub fn permanent(mut self) -> Self {
268        self.cookie.make_permanent();
269        self
270    }
271
272    /// Finishes building and returns the built `Cookie`.
273    ///
274    /// # Example
275    ///
276    /// ```rust
277    /// use cookie::Cookie;
278    ///
279    /// let c = Cookie::build("foo", "bar")
280    ///     .domain("crates.io")
281    ///     .path("/")
282    ///     .finish();
283    ///
284    /// assert_eq!(c.name_value(), ("foo", "bar"));
285    /// assert_eq!(c.domain(), Some("crates.io"));
286    /// assert_eq!(c.path(), Some("/"));
287    /// ```
288    #[inline]
289    pub fn finish(self) -> Cookie<'c> {
290        self.cookie
291    }
292}