binding.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. emailPattern = regexp.MustCompile("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[a-zA-Z0-9](?:[\\w-]*[\\w])?")
  157. urlPattern = regexp.MustCompile(`(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?`)
  158. )
  159. func validateStruct(errors *base.BindingErrors, obj interface{}) {
  160. typ := reflect.TypeOf(obj)
  161. val := reflect.ValueOf(obj)
  162. if typ.Kind() == reflect.Ptr {
  163. typ = typ.Elem()
  164. val = val.Elem()
  165. }
  166. for i := 0; i < typ.NumField(); i++ {
  167. field := typ.Field(i)
  168. // Allow ignored fields in the struct
  169. if field.Tag.Get("form") == "-" {
  170. continue
  171. }
  172. fieldValue := val.Field(i).Interface()
  173. if field.Type.Kind() == reflect.Struct {
  174. validateStruct(errors, fieldValue)
  175. continue
  176. }
  177. zero := reflect.Zero(field.Type).Interface()
  178. // Match rules.
  179. for _, rule := range strings.Split(field.Tag.Get("binding"), ";") {
  180. if len(rule) == 0 {
  181. continue
  182. }
  183. switch {
  184. case rule == "Required":
  185. if reflect.DeepEqual(zero, fieldValue) {
  186. errors.Fields[field.Name] = base.BindingRequireError
  187. break
  188. }
  189. case rule == "AlphaDash":
  190. if alphaDashPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
  191. errors.Fields[field.Name] = base.BindingAlphaDashError
  192. break
  193. }
  194. case strings.HasPrefix(rule, "MinSize("):
  195. min, err := strconv.Atoi(rule[8 : len(rule)-1])
  196. if err != nil {
  197. errors.Overall["MinSize"] = err.Error()
  198. break
  199. }
  200. if str, ok := fieldValue.(string); ok && utf8.RuneCountInString(str) < min {
  201. errors.Fields[field.Name] = base.BindingMinSizeError
  202. break
  203. }
  204. v := reflect.ValueOf(fieldValue)
  205. if v.Kind() == reflect.Slice && v.Len() < min {
  206. errors.Fields[field.Name] = base.BindingMinSizeError
  207. break
  208. }
  209. case strings.HasPrefix(rule, "MaxSize("):
  210. max, err := strconv.Atoi(rule[8 : len(rule)-1])
  211. if err != nil {
  212. errors.Overall["MaxSize"] = err.Error()
  213. break
  214. }
  215. if str, ok := fieldValue.(string); ok && utf8.RuneCountInString(str) > max {
  216. errors.Fields[field.Name] = base.BindingMaxSizeError
  217. break
  218. }
  219. v := reflect.ValueOf(fieldValue)
  220. if v.Kind() == reflect.Slice && v.Len() > max {
  221. errors.Fields[field.Name] = base.BindingMinSizeError
  222. break
  223. }
  224. case rule == "Email":
  225. if !emailPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
  226. errors.Fields[field.Name] = base.BindingEmailError
  227. break
  228. }
  229. case rule == "Url":
  230. if !urlPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
  231. errors.Fields[field.Name] = base.BindingUrlError
  232. break
  233. }
  234. }
  235. }
  236. }
  237. }
  238. func mapForm(formStruct reflect.Value, form map[string][]string, errors *base.BindingErrors) {
  239. typ := formStruct.Elem().Type()
  240. for i := 0; i < typ.NumField(); i++ {
  241. typeField := typ.Field(i)
  242. if inputFieldName := typeField.Tag.Get("form"); inputFieldName != "" {
  243. structField := formStruct.Elem().Field(i)
  244. if !structField.CanSet() {
  245. continue
  246. }
  247. inputValue, exists := form[inputFieldName]
  248. if !exists {
  249. continue
  250. }
  251. numElems := len(inputValue)
  252. if structField.Kind() == reflect.Slice && numElems > 0 {
  253. sliceOf := structField.Type().Elem().Kind()
  254. slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
  255. for i := 0; i < numElems; i++ {
  256. setWithProperType(sliceOf, inputValue[i], slice.Index(i), inputFieldName, errors)
  257. }
  258. formStruct.Elem().Field(i).Set(slice)
  259. } else {
  260. setWithProperType(typeField.Type.Kind(), inputValue[0], structField, inputFieldName, errors)
  261. }
  262. }
  263. }
  264. }
  265. // ErrorHandler simply counts the number of errors in the
  266. // context and, if more than 0, writes a 400 Bad Request
  267. // response and a JSON payload describing the errors with
  268. // the "Content-Type" set to "application/json".
  269. // Middleware remaining on the stack will not even see the request
  270. // if, by this point, there are any errors.
  271. // This is a "default" handler, of sorts, and you are
  272. // welcome to use your own instead. The Bind middleware
  273. // invokes this automatically for convenience.
  274. func ErrorHandler(errs base.BindingErrors, resp http.ResponseWriter) {
  275. if errs.Count() > 0 {
  276. resp.Header().Set("Content-Type", "application/json; charset=utf-8")
  277. if _, ok := errs.Overall[base.BindingDeserializationError]; ok {
  278. resp.WriteHeader(http.StatusBadRequest)
  279. } else {
  280. resp.WriteHeader(422)
  281. }
  282. errOutput, _ := json.Marshal(errs)
  283. resp.Write(errOutput)
  284. return
  285. }
  286. }
  287. // This sets the value in a struct of an indeterminate type to the
  288. // matching value from the request (via Form middleware) in the
  289. // same type, so that not all deserialized values have to be strings.
  290. // Supported types are string, int, float, and bool.
  291. func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value, nameInTag string, errors *base.BindingErrors) {
  292. switch valueKind {
  293. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  294. if val == "" {
  295. val = "0"
  296. }
  297. intVal, err := strconv.ParseInt(val, 10, 64)
  298. if err != nil {
  299. errors.Fields[nameInTag] = base.BindingIntegerTypeError
  300. } else {
  301. structField.SetInt(intVal)
  302. }
  303. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  304. if val == "" {
  305. val = "0"
  306. }
  307. uintVal, err := strconv.ParseUint(val, 10, 64)
  308. if err != nil {
  309. errors.Fields[nameInTag] = base.BindingIntegerTypeError
  310. } else {
  311. structField.SetUint(uintVal)
  312. }
  313. case reflect.Bool:
  314. structField.SetBool(val == "on")
  315. case reflect.Float32:
  316. if val == "" {
  317. val = "0.0"
  318. }
  319. floatVal, err := strconv.ParseFloat(val, 32)
  320. if err != nil {
  321. errors.Fields[nameInTag] = base.BindingFloatTypeError
  322. } else {
  323. structField.SetFloat(floatVal)
  324. }
  325. case reflect.Float64:
  326. if val == "" {
  327. val = "0.0"
  328. }
  329. floatVal, err := strconv.ParseFloat(val, 64)
  330. if err != nil {
  331. errors.Fields[nameInTag] = base.BindingFloatTypeError
  332. } else {
  333. structField.SetFloat(floatVal)
  334. }
  335. case reflect.String:
  336. structField.SetString(val)
  337. }
  338. }
  339. // Don't pass in pointers to bind to. Can lead to bugs. See:
  340. // https://github.com/codegangsta/martini-contrib/issues/40
  341. // https://github.com/codegangsta/martini-contrib/pull/34#issuecomment-29683659
  342. func ensureNotPointer(obj interface{}) {
  343. if reflect.TypeOf(obj).Kind() == reflect.Ptr {
  344. panic("Pointers are not accepted as binding models")
  345. }
  346. }
  347. // Performs validation and combines errors from validation
  348. // with errors from deserialization, then maps both the
  349. // resulting struct and the errors to the context.
  350. func validateAndMap(obj reflect.Value, context martini.Context, errors *base.BindingErrors, ifacePtr ...interface{}) {
  351. context.Invoke(Validate(obj.Interface()))
  352. errors.Combine(getErrors(context))
  353. context.Map(*errors)
  354. context.Map(obj.Elem().Interface())
  355. if len(ifacePtr) > 0 {
  356. context.MapTo(obj.Elem().Interface(), ifacePtr[0])
  357. }
  358. }
  359. func newErrors() *base.BindingErrors {
  360. return &base.BindingErrors{make(map[string]string), make(map[string]string)}
  361. }
  362. func getErrors(context martini.Context) base.BindingErrors {
  363. return context.Get(reflect.TypeOf(base.BindingErrors{})).Interface().(base.BindingErrors)
  364. }
  365. type (
  366. // Implement the Validator interface to define your own input
  367. // validation before the request even gets to your application.
  368. // The Validate method will be executed during the validation phase.
  369. Validator interface {
  370. Validate(*base.BindingErrors, *http.Request, martini.Context)
  371. }
  372. )
  373. var (
  374. // Maximum amount of memory to use when parsing a multipart form.
  375. // Set this to whatever value you prefer; default is 10 MB.
  376. MaxMemory = int64(1024 * 1024 * 10)
  377. )