Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FormPart does not handle multiple selections correctly #210

Open
ryukoposting opened this issue Jan 14, 2023 · 1 comment
Open

FormPart does not handle multiple selections correctly #210

ryukoposting opened this issue Jan 14, 2023 · 1 comment

Comments

@ryukoposting
Copy link

FormPart can only hold one value for each form parameter. This is partly a bug in the parser (here and here) but it is also a bug in the FormPart's type definition:

FormPart* = object
    data*: OrderedTableRef[string, tuple[params: StringTableRef, body: string]]

Since the body field is string instead of seq[string], Prologue cannot properly handle data from a form input like this:

<select name="thing" multiple>
  <option value="Thing 1">Thing 1</option>
  <option value="Thing 2">Thing 2</option>
  <option value="Thing 3">Thing 3</option>
  <option value="Thing 4">Thing 4</option>
</select>

This is a pretty trivial thing to fix, but it does require API changes.

@Uzo2005
Copy link

Uzo2005 commented Jan 17, 2024

Hello I ran into this same exact problem in my last project, found out jester has the same problem and fixed it by modifying the way jester does it here Here is my patch(in case you are in a hurry) and I would try to write a good PR when I get back from school..

type
  MultiData* = OrderedTable[string, seq[tuple[fields: StringTableRef, body: string]]]

template parseContentDisposition*() {.dirty.} =
  var hCount = 0
  while hCount < hValue.len()-1:
    var key = ""
    hCount += hValue.parseUntil(key, {';', '='}, hCount)
    if hValue[hCount] == '=':
      var value = hvalue.captureBetween('"', start = hCount)
      hCount += value.len+2
      inc(hCount) # Skip ;
      hCount += hValue.skipWhitespace(hCount)
      if key == "name": name = value
      newPart[0][key] = value
    else:
      inc(hCount)
      hCount += hValue.skipWhitespace(hCount)

proc parseMultiPart*(body: string, boundary: string): MultiData =
  result = initOrderedTable[string, seq[tuple[fields: StringTableRef, body: string]]]()
  var mboundary = "--" & boundary

  var i = 0
  var partsLeft = true
  while partsLeft:
    var firstBoundary = body.skip(mboundary, i)
    if firstBoundary == 0:
      raise newException(ValueError, "Expected boundary. Got: " & body.substr(i, i+25))
    i += firstBoundary
    i += body.skipWhitespace(i)

    # Headers
    var newPart: tuple[fields: StringTableRef, body: string] = ({:}.newStringTable, "")
    var name = ""
    while true:
      if body[i] == '\c':
        inc(i, 2) # Skip \c\L
        break
      var hName = ""
      i += body.parseUntil(hName, ':', i)
      if body[i] != ':':
        raise newException(ValueError, "Expected : in headers.")
      inc(i) # Skip :
      i += body.skipWhitespace(i)
      var hValue = ""
      i += body.parseUntil(hValue, {'\c', '\L'}, i)
      if toLowerAscii(hName) == "content-disposition":
        parseContentDisposition()
      newPart[0][hName] = hValue
      i += body.skip("\c\L", i) # Skip *one* \c\L

    # Parse body.
    while true:
      if body[i] == '\c' and body[i+1] == '\L' and
         body.skip(mboundary, i+2) != 0:
        if body.skip("--", i+2+mboundary.len) != 0:
          partsLeft = false
          break
        break
      else:
        newPart[1].add(body[i])
      inc(i)
    i += body.skipWhitespace(i)

    discard result.hasKeyOrPut(name, @[])
    result[name].add(newPart)

    
proc parseMPFD*(contentType: string, body: string): MultiData =
  var boundaryEqIndex = contentType.find("boundary=")+9
  var boundary = contentType.substr(boundaryEqIndex, contentType.len()-1)
  return parseMultiPart(body, boundary)

proc formData*(req: Request): MultiData =
  let contentType = req.headers.getOrDefault("Content-Type")
  if contentType.startsWith("multipart/form-data"):
    result = parseMPFD(contentType, req.body)

You can then just include the code above in your prologue project and use it like this:

import prologue

proc handleRequest(ctx:Context) {.async, gcsafe.} =
     for (key, value) in formData(ctx.request): #pairs is already exported from prologue exporting the std/tables
        echo "Form Field Name : ",  key, "  ", "Value(s) Provided By The User: ", value

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants