forked from achesak/nim-biscuits
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbiscuits.nim
433 lines (307 loc) · 12.8 KB
/
biscuits.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
## Biscuits is a Nim module for better cookie handling.
##
## Differences from cookie module in standard library:
## * Better handling of multiple key-value pairs, particularly with regard to creating cookies.
## * Supports "max-age" cookie field.
## * Better separation of data from cookie special fields.
## * Better methods for editing cookies.
## * Object-oriented interface, if you like that kind of thing.
##
## Examples:
##
## .. code-block:: nimrod
##
## # Start with a cookie, represented as a string.
## var cookieExample: string = "username=John Doe; password=notverysecure; expires=Thu, 30 Dec 2015 12:00:00 UTC; path=/; secure"
##
## # Parse the cookie.
## var myBiscuit: Biscuit = parseBiscuit(cookieExample)
##
## # If the password key is set and equal to "notverysecure", set it to something else.
## if myBiscuit.hasKey("password") and myBiscuit.getKey("password") == "notverysecure":
## discard myBiscuit.setKey("password", "reallyshouldbechanged")
##
## # Add a new key to the cookie.
## discard myBiscuit.setKey("userLevel", "admin")
##
## # Try to set the userLevel key to a different value, but don't overwrite if a value is already set.
## discard myBiscuit.setKey("userLevel", "user", overwrite = false)
## echo(myBiscuit.getKey("userLevel")) # still outputs "admin"
##
## # Change the path of the cookie.
## discard myBiscuit.setPath("/nimExample/")
## echo(myBiscuit.getPath()) # ouputs "/nimExample/"
##
## # Format the cookie as a string.
## var cookieStr: string = $myBiscuit;
## echo(cookieStr)
## # outputs "userLevel=admin; username=John Doe; password=reallyshouldbechanged; path=/nimExample/; expires=Thu, 30 Dec 2015 12:00:00 UTC; secure"
##
## # Create a new cookie. Can also be created with a string table, in order to use multiple key-value pairs.
## var newBiscuit: Biscuit = createBiscuit("thisisakey", "thisisavalue", path = "/", maxAge = "300", httpOnly = true)
## echo(newBiscuit.toString(includeName = true))
## # outputs "Set-Cookie: thisisakey=thisisavalue; path=/; max-age=300; HttpOnly"
# Written by Adam Chesak.
# Released under the MIT open source license.
import cookies
import strtabs
import strutils
import times
import unicode
type
Biscuit* = ref object
data*: StringTableRef
domain: string
path: string
expires: string
maxAge: string
secure: bool
httpOnly: bool
BiscuitError* = object of Exception
proc parseBiscuit*(s: string): Biscuit =
## Parses a cookie and returns it as a ``Biscuit`` object.
var cs: StringTableRef = cookies.parseCookies(s)
var c: Biscuit = Biscuit()
c.data = newStringTable(modeCaseSensitive)
for key, value in cs:
var keyCheck = unicode.toLower(key)
if keyCheck == "domain":
c.domain = value
elif keyCheck == "path":
c.path = value
elif keyCheck == "expires":
c.expires = value
elif keyCheck == "max-age":
c.maxAge = value
elif keyCheck == "secure":
if unicode.toLower(value) != "false":
c.secure = true
else:
c.secure = false
elif keyCheck == "httponly":
if unicode.toLower(value) != "false":
c.httpOnly = true
else:
c.httpOnly = false
else:
c.data[key] = value
# Sometimes secure and HttpOnly fields don't get set properly in the previous loop.
# Double check here. Kind of messy but works for now.
var fields: seq[string] = s.split(";")
for i in 0..high(fields):
fields[i] = unicode.toLower(strutils.strip(fields[i],leading = true, trailing = true))
if fields[i] == "secure":
c.secure = true
if fields[i] == "httponly":
c.httpOnly = true
return c
proc createBiscuit*(data: StringTableRef, domain: string = "", path: string = "", expires: string = "",
maxAge: string = "", secure: bool = false, httpOnly: bool = false): Biscuit =
## Creates a ``Biscuit`` object from the given parameters
var c: Biscuit = Biscuit(data: data, domain: domain, path: path, expires: expires, maxAge: maxAge,
secure: secure, httpOnly: httpOnly)
return c
proc createBiscuit*(key: string, value: string, domain: string = "", path: string = "", expires: string = "",
maxAge: string = "", secure: bool = false, httpOnly: bool = false): Biscuit =
## Creates a ``Biscuit`` object from the given parameters
var c: Biscuit = Biscuit(data: newStringTable(key, value, modeCaseSensitive), domain: domain, path: path, expires: expires, maxAge: maxAge,
secure: secure, httpOnly: httpOnly)
return c
proc toString*(c: Biscuit, includeName: bool = false): string =
## Converts the given ``Biscuit`` to a string. If ``includeName`` is set to ``true``, prepends ``Set-Cookie:``.
var s: string = ""
if includeName:
s &= "Set-Cookie: "
for key, value in c.data:
s &= key & "=" & value & "; "
if c.domain != "":
s &= "domain=" & c.domain & "; "
if c.path != "":
s &= "path=" & c.path & "; "
if c.expires != "":
s &= "expires=" & c.expires & "; "
if c.maxAge != "":
s &= "max-age=" & c.maxAge & "; "
if c.secure:
s &= "secure; "
if c.httpOnly:
s &= "HttpOnly; "
s = strutils.strip(s, trailing = true)
if s.endsWith(";"):
s = s[0..high(s) - 1]
return s
proc `$`*(c: Biscuit): string =
## Converts the given ``Biscuit`` to a string.
return c.toString()
proc hasKey*(c: Biscuit, key: string): bool =
## Returns ``true`` if the given ``Biscuit`` has given data ``key``, and ``false`` otherwise.
return c.data.hasKey(key)
proc getKey*(c: Biscuit, key: string, defaultValue: string = ""): string =
## Gets the value of the ``key`` in the given ``Biscuit``. If the ``key`` has no value associated with it and
## a ``defaultValue`` is given, the default value is returned instead.
if not c.data.hasKey(key):
return defaultValue
else:
return c.data[key]
proc setKey*(c: Biscuit, key: string, value: string, overwrite: bool = true): bool =
## Sets the ``key`` to the given ``value. If ``overwrite`` is ``false` and the ``key`` already has a value
## associated with it, nothing will be changed.
# Don't allow reserved fields.
if unicode.toLower(key) in @["domain", "path", "expires", "max-age", "secure", "httponly"]:
raise newException(BiscuitError, "Key cannot be set to a reserved field.")
if c.data.hasKey(key) and not overwrite:
return false
else:
c.data[key] = value
return true
proc clearKeys*(c: Biscuit): seq[string] =
## Clears all keys from the given ``Biscuit``.
var k: seq[string] = @[]
for key, value in c.data:
k.add(key)
c.data.clear(modeCaseSensitive)
return k
proc hasDomain*(c: Biscuit): bool =
## Returns ``true`` if the given ``Biscuit`` has a domain field set, and ``false`` otherwise.
return c.domain != ""
proc getDomain*(c: Biscuit, defaultValue: string = ""): string =
## Gets the value of the domain field for the given ``Biscuit``. If no domain field is set and a ``defaultValue`` is given,
## the default value is returned instead.
if c.domain == "":
return defaultValue
else:
return c.domain
proc setDomain*(c: Biscuit, domain: string): string =
## Sets the domain field to the specified value.
var d: string = c.domain
c.domain = domain
return d
proc hasPath*(c: Biscuit): bool =
## Returns ``true`` if the given ``Biscuit`` has a path field set, and ``false`` otherwise.
return c.path != ""
proc getPath*(c: Biscuit, defaultValue: string = ""): string =
## Gets the value of the path field for the given ``Biscuit``. If no path field is set and a ``defaultValue`` is given,
## the default value is returned instead.
if c.path == "":
return defaultValue
else:
return c.path
proc setPath*(c: Biscuit, path: string): string =
## Sets the path field to the specified value.
var p: string = c.path
c.path = path
return p
proc hasExpires*(c: Biscuit): bool =
## Returns ``true`` if the given ``Biscuit`` has an expires field set, and ``false`` otherwise.
return c.expires != ""
proc getExpires*(c: Biscuit, defaultValue: string = ""): string =
## Gets the value of the expires field for the given ``Biscuit``. If no expires field is set and a ``defaultValue`` is given,
## the default value is returned instead.
if c.expires == "":
return defaultValue
else:
return c.expires
proc getExpiresDateTime*(c: Biscuit): DateTime =
## Gets the value of the expires field for the given ``Biscuit``. Returns the field as a ``DateTime`` object.
var t: string = c.getExpires()
return times.parse(t, "ddd, dd MMM yyyy hh:mm:ss", utc())
proc setExpires*(c: Biscuit, expires: string): string =
## Sets the expires field to the specified value.
var e: string = c.expires
c.expires = expires
return e
proc setExpiresDateTime*(c: Biscuit, expires: DateTime): DateTime =
## Sets the expires field to the specifiied value.
var e: DateTime = times.parse(c.expires, "ddd, dd MMM yyyy hh:mm:ss", utc())
c.expires = expires.format("ddd, dd MMM yyyy HH:mm:ss z")
return e
proc hasMaxAge*(c: Biscuit): bool =
## Returns ``true`` if the given ``Biscuit`` has a max-age field set, and ``false`` otherwise.
return c.maxAge != ""
proc getMaxAge*(c: Biscuit, defaultValue: string = ""): string =
## Gets the value of the max-age field for the given ``Biscuit``. If no max-age field is set and a ``defaultValue`` is given,
## the default value is returned instead.
if c.maxAge == "":
return defaultValue
else:
return c.maxAge
proc getMaxAgeDateTime*(c: Biscuit): DateTime =
## Gets the value of the max-age field for the given ``Biscuit``. Returns the field as a ``DateTime`` object.
var t: string = c.getMaxAge()
return parseInt(t).fromUnix().local()
proc setMaxAge*(c: Biscuit, maxAge: string): string =
## Sets the max-age field to the specified value.
var m: string = c.maxAge
c.maxAge = maxAge
return m
proc setMaxAgeDateTime*(c: Biscuit, maxAge: DateTime): DateTime =
## Sets the max-age field to the specifiied value.
var m: DateTime = c.getMaxAgeDateTime()
c.maxAge = int(maxAge.toTime().toUnix()).intToStr()
return m
proc isSecure*(c: Biscuit): bool =
## Returns ``true`` if the secure field of the given ``Biscuit`` is set and true, and ``false`` otherwise.
return c.secure
proc setSecure*(c: Biscuit, secure: bool): bool =
## Sets the secure field to the specified value.
var s: bool = c.secure
c.secure = secure
return s
proc isHttpOnly*(c: Biscuit): bool =
## Returns ``true`` if the HttpOnly field of the given ``Biscuit`` is set and true, and ``false`` otherwise.
return c.httpOnly
proc setHttpOnly*(c: Biscuit, httpOnly: bool): bool =
## Sets the HttpOnly field to the specified value.
var h: bool = c.httpOnly
c.httpOnly = httpOnly
return h
proc `[]`*(c: Biscuit, key: string): string =
## Shortcut for ``getKey()``.
return c.getKey(key)
proc `[]=`*(c: Biscuit, key: string, value: string): void =
## Shortcut for ``setKey()``.
discard c.setKey(key, value)
proc `==`*(c1: Biscuit, c2: Biscuit): bool =
## Equality operator for ``Biscuit``.
# Check that the cookie fields are the same.
if c1.domain != c2.domain:
return false
if c1.path != c2.path:
return false
if c1.expires != c2.expires:
return false
if c1.maxAge != c2.maxAge:
return false
if c1.secure != c2.secure:
return false
if c1.httpOnly != c2.httpOnly:
return false
# Check that the data fields are the same.
if len(c1.data) != len(c2.data):
return false
for key, value in c1.data:
if not c2.hasKey(key):
return false
if value != c2.getKey(key):
return false
for key, value in c2.data:
if not c1.hasKey(key):
return false
if value != c1.getKey(key):
return false
return true
proc `!=`*(c1: Biscuit, c2: Biscuit): bool =
## Inequality operator for ``Biscuit``.
return not (c1 == c2)
iterator pairs*(c: Biscuit): tuple[key: string, value: string] =
## Iterates over key-value pairs.
for key, value in c.data:
yield (key, value)
iterator keys*(c: Biscuit): string =
## Iterates over keys.
for key in keys(c.data):
yield key
iterator values*(c: Biscuit): string =
## Iterates over values.
for value in values(c.data):
yield value