auth.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package auth
  5. import (
  6. "net/http"
  7. "reflect"
  8. "strings"
  9. "github.com/Unknwon/macaron"
  10. "github.com/macaron-contrib/binding"
  11. "github.com/macaron-contrib/session"
  12. "github.com/gogits/gogs/models"
  13. "github.com/gogits/gogs/modules/base"
  14. "github.com/gogits/gogs/modules/log"
  15. "github.com/gogits/gogs/modules/setting"
  16. )
  17. // SignedInId returns the id of signed in user.
  18. func SignedInId(req *http.Request, sess session.Store) int64 {
  19. if !models.HasEngine {
  20. return 0
  21. }
  22. // API calls need to check access token.
  23. if strings.HasPrefix(req.URL.Path, "/api/") {
  24. auHead := req.Header.Get("Authorization")
  25. if len(auHead) > 0 {
  26. auths := strings.Fields(auHead)
  27. if len(auths) == 2 && auths[0] == "token" {
  28. t, err := models.GetAccessTokenBySha(auths[1])
  29. if err != nil {
  30. if err != models.ErrAccessTokenNotExist {
  31. log.Error(4, "GetAccessTokenBySha: %v", err)
  32. }
  33. return 0
  34. }
  35. return t.Uid
  36. }
  37. }
  38. }
  39. uid := sess.Get("uid")
  40. if uid == nil {
  41. return 0
  42. }
  43. if id, ok := uid.(int64); ok {
  44. if _, err := models.GetUserById(id); err != nil {
  45. if err != models.ErrUserNotExist {
  46. log.Error(4, "GetUserById: %v", err)
  47. }
  48. return 0
  49. }
  50. return id
  51. }
  52. return 0
  53. }
  54. // SignedInUser returns the user object of signed user.
  55. // It returns a bool value to indicate whether user uses basic auth or not.
  56. func SignedInUser(req *http.Request, sess session.Store) (*models.User, bool) {
  57. if !models.HasEngine {
  58. return nil, false
  59. }
  60. uid := SignedInId(req, sess)
  61. if uid <= 0 {
  62. if setting.Service.EnableReverseProxyAuth {
  63. webAuthUser := req.Header.Get(setting.ReverseProxyAuthUser)
  64. if len(webAuthUser) > 0 {
  65. u, err := models.GetUserByName(webAuthUser)
  66. if err != nil {
  67. if err != models.ErrUserNotExist {
  68. log.Error(4, "GetUserByName: %v", err)
  69. return nil, false
  70. }
  71. // Check if enabled auto-registeration.
  72. if setting.Service.EnableReverseProxyAutoRegister {
  73. u := &models.User{
  74. Name: webAuthUser,
  75. Email: webAuthUser + "@gogs.io",
  76. Passwd: webAuthUser,
  77. IsActive: true,
  78. }
  79. if err = models.CreateUser(u); err != nil {
  80. // FIXME: should I create a system notice?
  81. log.Error(4, "CreateUser: %v", err)
  82. return nil, false
  83. } else {
  84. return u, false
  85. }
  86. }
  87. }
  88. return u, false
  89. }
  90. }
  91. // Check with basic auth.
  92. baHead := req.Header.Get("Authorization")
  93. if len(baHead) > 0 {
  94. auths := strings.Fields(baHead)
  95. if len(auths) == 2 && auths[0] == "Basic" {
  96. uname, passwd, _ := base.BasicAuthDecode(auths[1])
  97. u, err := models.GetUserByName(uname)
  98. if err != nil {
  99. if err != models.ErrUserNotExist {
  100. log.Error(4, "GetUserByName: %v", err)
  101. }
  102. return nil, false
  103. }
  104. if u.ValidtePassword(passwd) {
  105. return u, true
  106. }
  107. }
  108. }
  109. return nil, false
  110. }
  111. u, err := models.GetUserById(uid)
  112. if err != nil {
  113. log.Error(4, "GetUserById: %v", err)
  114. return nil, false
  115. }
  116. return u, false
  117. }
  118. type Form interface {
  119. binding.Validator
  120. }
  121. // AssignForm assign form values back to the template data.
  122. func AssignForm(form interface{}, data map[string]interface{}) {
  123. typ := reflect.TypeOf(form)
  124. val := reflect.ValueOf(form)
  125. if typ.Kind() == reflect.Ptr {
  126. typ = typ.Elem()
  127. val = val.Elem()
  128. }
  129. for i := 0; i < typ.NumField(); i++ {
  130. field := typ.Field(i)
  131. fieldName := field.Tag.Get("form")
  132. // Allow ignored fields in the struct
  133. if fieldName == "-" {
  134. continue
  135. }
  136. data[fieldName] = val.Field(i).Interface()
  137. }
  138. }
  139. func getSize(field reflect.StructField, prefix string) string {
  140. for _, rule := range strings.Split(field.Tag.Get("binding"), ";") {
  141. if strings.HasPrefix(rule, prefix) {
  142. return rule[8 : len(rule)-1]
  143. }
  144. }
  145. return ""
  146. }
  147. func GetMinSize(field reflect.StructField) string {
  148. return getSize(field, "MinSize(")
  149. }
  150. func GetMaxSize(field reflect.StructField) string {
  151. return getSize(field, "MaxSize(")
  152. }
  153. func validate(errs binding.Errors, data map[string]interface{}, f Form, l macaron.Locale) binding.Errors {
  154. if errs.Len() == 0 {
  155. return errs
  156. }
  157. data["HasError"] = true
  158. AssignForm(f, data)
  159. typ := reflect.TypeOf(f)
  160. val := reflect.ValueOf(f)
  161. if typ.Kind() == reflect.Ptr {
  162. typ = typ.Elem()
  163. val = val.Elem()
  164. }
  165. for i := 0; i < typ.NumField(); i++ {
  166. field := typ.Field(i)
  167. fieldName := field.Tag.Get("form")
  168. // Allow ignored fields in the struct
  169. if fieldName == "-" {
  170. continue
  171. }
  172. if errs[0].FieldNames[0] == field.Name {
  173. data["Err_"+field.Name] = true
  174. trName := l.Tr("form." + field.Name)
  175. switch errs[0].Classification {
  176. case binding.RequiredError:
  177. data["ErrorMsg"] = trName + l.Tr("form.require_error")
  178. case binding.AlphaDashError:
  179. data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_error")
  180. case binding.AlphaDashDotError:
  181. data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_dot_error")
  182. case binding.MinSizeError:
  183. data["ErrorMsg"] = trName + l.Tr("form.min_size_error", GetMinSize(field))
  184. case binding.MaxSizeError:
  185. data["ErrorMsg"] = trName + l.Tr("form.max_size_error", GetMaxSize(field))
  186. case binding.EmailError:
  187. data["ErrorMsg"] = trName + l.Tr("form.email_error")
  188. case binding.UrlError:
  189. data["ErrorMsg"] = trName + l.Tr("form.url_error")
  190. default:
  191. data["ErrorMsg"] = l.Tr("form.unknown_error") + " " + errs[0].Classification
  192. }
  193. return errs
  194. }
  195. }
  196. return errs
  197. }