binding.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. // Copyright 2013 The Martini Contrib Authors. All rights reserved.
  2. // Copyright 2014 The Gogs Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package middleware
  6. import (
  7. "encoding/json"
  8. "fmt"
  9. "io"
  10. "net/http"
  11. "reflect"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "unicode/utf8"
  16. "github.com/go-martini/martini"
  17. "github.com/gogits/gogs/modules/base"
  18. )
  19. /*
  20. To the land of Middle-ware Earth:
  21. One func to rule them all,
  22. One func to find them,
  23. One func to bring them all,
  24. And in this package BIND them.
  25. */
  26. // Bind accepts a copy of an empty struct and populates it with
  27. // values from the request (if deserialization is successful). It
  28. // wraps up the functionality of the Form and Json middleware
  29. // according to the Content-Type of the request, and it guesses
  30. // if no Content-Type is specified. Bind invokes the ErrorHandler
  31. // middleware to bail out if errors occurred. If you want to perform
  32. // your own error handling, use Form or Json middleware directly.
  33. // An interface pointer can be added as a second argument in order
  34. // to map the struct to a specific interface.
  35. func Bind(obj interface{}, ifacePtr ...interface{}) martini.Handler {
  36. return func(context martini.Context, req *http.Request) {
  37. contentType := req.Header.Get("Content-Type")
  38. if strings.Contains(contentType, "form-urlencoded") {
  39. context.Invoke(Form(obj, ifacePtr...))
  40. } else if strings.Contains(contentType, "multipart/form-data") {
  41. context.Invoke(MultipartForm(obj, ifacePtr...))
  42. } else if strings.Contains(contentType, "json") {
  43. context.Invoke(Json(obj, ifacePtr...))
  44. } else {
  45. context.Invoke(Json(obj, ifacePtr...))
  46. if getErrors(context).Count() > 0 {
  47. context.Invoke(Form(obj, ifacePtr...))
  48. }
  49. }
  50. context.Invoke(ErrorHandler)
  51. }
  52. }
  53. // BindIgnErr will do the exactly same thing as Bind but without any
  54. // error handling, which user has freedom to deal with them.
  55. // This allows user take advantages of validation.
  56. func BindIgnErr(obj interface{}, ifacePtr ...interface{}) martini.Handler {
  57. return func(context martini.Context, req *http.Request) {
  58. contentType := req.Header.Get("Content-Type")
  59. if strings.Contains(contentType, "form-urlencoded") {
  60. context.Invoke(Form(obj, ifacePtr...))
  61. } else if strings.Contains(contentType, "multipart/form-data") {
  62. context.Invoke(MultipartForm(obj, ifacePtr...))
  63. } else if strings.Contains(contentType, "json") {
  64. context.Invoke(Json(obj, ifacePtr...))
  65. } else {
  66. context.Invoke(Json(obj, ifacePtr...))
  67. if getErrors(context).Count() > 0 {
  68. context.Invoke(Form(obj, ifacePtr...))
  69. }
  70. }
  71. }
  72. }
  73. // Form is middleware to deserialize form-urlencoded data from the request.
  74. // It gets data from the form-urlencoded body, if present, or from the
  75. // query string. It uses the http.Request.ParseForm() method
  76. // to perform deserialization, then reflection is used to map each field
  77. // into the struct with the proper type. Structs with primitive slice types
  78. // (bool, float, int, string) can support deserialization of repeated form
  79. // keys, for example: key=val1&key=val2&key=val3
  80. // An interface pointer can be added as a second argument in order
  81. // to map the struct to a specific interface.
  82. func Form(formStruct interface{}, ifacePtr ...interface{}) martini.Handler {
  83. return func(context martini.Context, req *http.Request) {
  84. ensureNotPointer(formStruct)
  85. formStruct := reflect.New(reflect.TypeOf(formStruct))
  86. errors := newErrors()
  87. parseErr := req.ParseForm()
  88. // Format validation of the request body or the URL would add considerable overhead,
  89. // and ParseForm does not complain when URL encoding is off.
  90. // Because an empty request body or url can also mean absence of all needed values,
  91. // it is not in all cases a bad request, so let's return 422.
  92. if parseErr != nil {
  93. errors.Overall[base.BindingDeserializationError] = parseErr.Error()
  94. }
  95. mapForm(formStruct, req.Form, errors)
  96. validateAndMap(formStruct, context, errors, ifacePtr...)
  97. }
  98. }
  99. func MultipartForm(formStruct interface{}, ifacePtr ...interface{}) martini.Handler {
  100. return func(context martini.Context, req *http.Request) {
  101. ensureNotPointer(formStruct)
  102. formStruct := reflect.New(reflect.TypeOf(formStruct))
  103. errors := newErrors()
  104. // Workaround for multipart forms returning nil instead of an error
  105. // when content is not multipart
  106. // https://code.google.com/p/go/issues/detail?id=6334
  107. multipartReader, err := req.MultipartReader()
  108. if err != nil {
  109. errors.Overall[base.BindingDeserializationError] = err.Error()
  110. } else {
  111. form, parseErr := multipartReader.ReadForm(MaxMemory)
  112. if parseErr != nil {
  113. errors.Overall[base.BindingDeserializationError] = parseErr.Error()
  114. }
  115. req.MultipartForm = form
  116. }
  117. mapForm(formStruct, req.MultipartForm.Value, errors)
  118. validateAndMap(formStruct, context, errors, ifacePtr...)
  119. }
  120. }
  121. // Json is middleware to deserialize a JSON payload from the request
  122. // into the struct that is passed in. The resulting struct is then
  123. // validated, but no error handling is actually performed here.
  124. // An interface pointer can be added as a second argument in order
  125. // to map the struct to a specific interface.
  126. func Json(jsonStruct interface{}, ifacePtr ...interface{}) martini.Handler {
  127. return func(context martini.Context, req *http.Request) {
  128. ensureNotPointer(jsonStruct)
  129. jsonStruct := reflect.New(reflect.TypeOf(jsonStruct))
  130. errors := newErrors()
  131. if req.Body != nil {
  132. defer req.Body.Close()
  133. }
  134. if err := json.NewDecoder(req.Body).Decode(jsonStruct.Interface()); err != nil && err != io.EOF {
  135. errors.Overall[base.BindingDeserializationError] = err.Error()
  136. }
  137. validateAndMap(jsonStruct, context, errors, ifacePtr...)
  138. }
  139. }
  140. // Validate is middleware to enforce required fields. If the struct
  141. // passed in is a Validator, then the user-defined Validate method
  142. // is executed, and its errors are mapped to the context. This middleware
  143. // performs no error handling: it merely detects them and maps them.
  144. func Validate(obj interface{}) martini.Handler {
  145. return func(context martini.Context, req *http.Request) {
  146. errors := newErrors()
  147. validateStruct(errors, obj)
  148. if validator, ok := obj.(Validator); ok {
  149. validator.Validate(errors, req, context)
  150. }
  151. context.Map(*errors)
  152. }
  153. }
  154. var (
  155. alphaDashPattern = regexp.MustCompile("[^\\d\\w-_]")
  156. alphaDashDotPattern = regexp.MustCompile("[^\\d\\w-_\\.]")
  157. emailPattern = regexp.MustCompile("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[a-zA-Z0-9](?:[\\w-]*[\\w])?")
  158. urlPattern = regexp.MustCompile(`(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?`)
  159. )
  160. func validateStruct(errors *base.BindingErrors, obj interface{}) {
  161. typ := reflect.TypeOf(obj)
  162. val := reflect.ValueOf(obj)
  163. if typ.Kind() == reflect.Ptr {
  164. typ = typ.Elem()
  165. val = val.Elem()
  166. }
  167. for i := 0; i < typ.NumField(); i++ {
  168. field := typ.Field(i)
  169. // Allow ignored fields in the struct
  170. if field.Tag.Get("form") == "-" {
  171. continue
  172. }
  173. fieldValue := val.Field(i).Interface()
  174. if field.Type.Kind() == reflect.Struct {
  175. validateStruct(errors, fieldValue)
  176. continue
  177. }
  178. zero := reflect.Zero(field.Type).Interface()
  179. // Match rules.
  180. for _, rule := range strings.Split(field.Tag.Get("binding"), ";") {
  181. if len(rule) == 0 {
  182. continue
  183. }
  184. switch {
  185. case rule == "Required":
  186. if reflect.DeepEqual(zero, fieldValue) {
  187. errors.Fields[field.Name] = base.BindingRequireError
  188. break
  189. }
  190. case rule == "AlphaDash":
  191. if alphaDashPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
  192. errors.Fields[field.Name] = base.BindingAlphaDashError
  193. break
  194. }
  195. case rule == "AlphaDashDot":
  196. if alphaDashDotPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
  197. errors.Fields[field.Name] = base.BindingAlphaDashDotError
  198. break
  199. }
  200. case strings.HasPrefix(rule, "MinSize("):
  201. min, err := strconv.Atoi(rule[8 : len(rule)-1])
  202. if err != nil {
  203. errors.Overall["MinSize"] = err.Error()
  204. break
  205. }
  206. if str, ok := fieldValue.(string); ok && utf8.RuneCountInString(str) < min {
  207. errors.Fields[field.Name] = base.BindingMinSizeError
  208. break
  209. }
  210. v := reflect.ValueOf(fieldValue)
  211. if v.Kind() == reflect.Slice && v.Len() < min {
  212. errors.Fields[field.Name] = base.BindingMinSizeError
  213. break
  214. }
  215. case strings.HasPrefix(rule, "MaxSize("):
  216. max, err := strconv.Atoi(rule[8 : len(rule)-1])
  217. if err != nil {
  218. errors.Overall["MaxSize"] = err.Error()
  219. break
  220. }
  221. if str, ok := fieldValue.(string); ok && utf8.RuneCountInString(str) > max {
  222. errors.Fields[field.Name] = base.BindingMaxSizeError
  223. break
  224. }
  225. v := reflect.ValueOf(fieldValue)
  226. if v.Kind() == reflect.Slice && v.Len() > max {
  227. errors.Fields[field.Name] = base.BindingMinSizeError
  228. break
  229. }
  230. case rule == "Email":
  231. if !emailPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
  232. errors.Fields[field.Name] = base.BindingEmailError
  233. break
  234. }
  235. case rule == "Url":
  236. if !urlPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
  237. errors.Fields[field.Name] = base.BindingUrlError
  238. break
  239. }
  240. }
  241. }
  242. }
  243. }
  244. func mapForm(formStruct reflect.Value, form map[string][]string, errors *base.BindingErrors) {
  245. typ := formStruct.Elem().Type()
  246. for i := 0; i < typ.NumField(); i++ {
  247. typeField := typ.Field(i)
  248. if inputFieldName := typeField.Tag.Get("form"); inputFieldName != "" {
  249. structField := formStruct.Elem().Field(i)
  250. if !structField.CanSet() {
  251. continue
  252. }
  253. inputValue, exists := form[inputFieldName]
  254. if !exists {
  255. continue
  256. }
  257. numElems := len(inputValue)
  258. if structField.Kind() == reflect.Slice && numElems > 0 {
  259. sliceOf := structField.Type().Elem().Kind()
  260. slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
  261. for i := 0; i < numElems; i++ {
  262. setWithProperType(sliceOf, inputValue[i], slice.Index(i), inputFieldName, errors)
  263. }
  264. formStruct.Elem().Field(i).Set(slice)
  265. } else {
  266. setWithProperType(typeField.Type.Kind(), inputValue[0], structField, inputFieldName, errors)
  267. }
  268. }
  269. }
  270. }
  271. // ErrorHandler simply counts the number of errors in the
  272. // context and, if more than 0, writes a 400 Bad Request
  273. // response and a JSON payload describing the errors with
  274. // the "Content-Type" set to "application/json".
  275. // Middleware remaining on the stack will not even see the request
  276. // if, by this point, there are any errors.
  277. // This is a "default" handler, of sorts, and you are
  278. // welcome to use your own instead. The Bind middleware
  279. // invokes this automatically for convenience.
  280. func ErrorHandler(errs base.BindingErrors, resp http.ResponseWriter) {
  281. if errs.Count() > 0 {
  282. resp.Header().Set("Content-Type", "application/json; charset=utf-8")
  283. if _, ok := errs.Overall[base.BindingDeserializationError]; ok {
  284. resp.WriteHeader(http.StatusBadRequest)
  285. } else {
  286. resp.WriteHeader(422)
  287. }
  288. errOutput, _ := json.Marshal(errs)
  289. resp.Write(errOutput)
  290. return
  291. }
  292. }
  293. // This sets the value in a struct of an indeterminate type to the
  294. // matching value from the request (via Form middleware) in the
  295. // same type, so that not all deserialized values have to be strings.
  296. // Supported types are string, int, float, and bool.
  297. func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value, nameInTag string, errors *base.BindingErrors) {
  298. switch valueKind {
  299. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  300. if val == "" {
  301. val = "0"
  302. }
  303. intVal, err := strconv.ParseInt(val, 10, 64)
  304. if err != nil {
  305. errors.Fields[nameInTag] = base.BindingIntegerTypeError
  306. } else {
  307. structField.SetInt(intVal)
  308. }
  309. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  310. if val == "" {
  311. val = "0"
  312. }
  313. uintVal, err := strconv.ParseUint(val, 10, 64)
  314. if err != nil {
  315. errors.Fields[nameInTag] = base.BindingIntegerTypeError
  316. } else {
  317. structField.SetUint(uintVal)
  318. }
  319. case reflect.Bool:
  320. structField.SetBool(val == "on")
  321. case reflect.Float32:
  322. if val == "" {
  323. val = "0.0"
  324. }
  325. floatVal, err := strconv.ParseFloat(val, 32)
  326. if err != nil {
  327. errors.Fields[nameInTag] = base.BindingFloatTypeError
  328. } else {
  329. structField.SetFloat(floatVal)
  330. }
  331. case reflect.Float64:
  332. if val == "" {
  333. val = "0.0"
  334. }
  335. floatVal, err := strconv.ParseFloat(val, 64)
  336. if err != nil {
  337. errors.Fields[nameInTag] = base.BindingFloatTypeError
  338. } else {
  339. structField.SetFloat(floatVal)
  340. }
  341. case reflect.String:
  342. structField.SetString(val)
  343. }
  344. }
  345. // Don't pass in pointers to bind to. Can lead to bugs. See:
  346. // https://github.com/codegangsta/martini-contrib/issues/40
  347. // https://github.com/codegangsta/martini-contrib/pull/34#issuecomment-29683659
  348. func ensureNotPointer(obj interface{}) {
  349. if reflect.TypeOf(obj).Kind() == reflect.Ptr {
  350. panic("Pointers are not accepted as binding models")
  351. }
  352. }
  353. // Performs validation and combines errors from validation
  354. // with errors from deserialization, then maps both the
  355. // resulting struct and the errors to the context.
  356. func validateAndMap(obj reflect.Value, context martini.Context, errors *base.BindingErrors, ifacePtr ...interface{}) {
  357. context.Invoke(Validate(obj.Interface()))
  358. errors.Combine(getErrors(context))
  359. context.Map(*errors)
  360. context.Map(obj.Elem().Interface())
  361. if len(ifacePtr) > 0 {
  362. context.MapTo(obj.Elem().Interface(), ifacePtr[0])
  363. }
  364. }
  365. func newErrors() *base.BindingErrors {
  366. return &base.BindingErrors{make(map[string]string), make(map[string]string)}
  367. }
  368. func getErrors(context martini.Context) base.BindingErrors {
  369. return context.Get(reflect.TypeOf(base.BindingErrors{})).Interface().(base.BindingErrors)
  370. }
  371. type (
  372. // Implement the Validator interface to define your own input
  373. // validation before the request even gets to your application.
  374. // The Validate method will be executed during the validation phase.
  375. Validator interface {
  376. Validate(*base.BindingErrors, *http.Request, martini.Context)
  377. }
  378. )
  379. var (
  380. // Maximum amount of memory to use when parsing a multipart form.
  381. // Set this to whatever value you prefer; default is 10 MB.
  382. MaxMemory = int64(1024 * 1024 * 10)
  383. )