auth.go 5.6 KB

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