auth.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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.GetUserByName(uname)
  100. if err != nil {
  101. if err != models.ErrUserNotExist {
  102. log.Error(4, "GetUserByName: %v", err)
  103. }
  104. return nil, false
  105. }
  106. if u.ValidtePassword(passwd) {
  107. return u, true
  108. }
  109. }
  110. }
  111. return nil, false
  112. }
  113. u, err := models.GetUserById(uid)
  114. if err != nil {
  115. log.Error(4, "GetUserById: %v", err)
  116. return nil, false
  117. }
  118. return u, false
  119. }
  120. type Form interface {
  121. binding.Validator
  122. }
  123. func init() {
  124. binding.SetNameMapper(com.ToSnakeCase)
  125. }
  126. // AssignForm assign form values back to the template data.
  127. func AssignForm(form interface{}, data map[string]interface{}) {
  128. typ := reflect.TypeOf(form)
  129. val := reflect.ValueOf(form)
  130. if typ.Kind() == reflect.Ptr {
  131. typ = typ.Elem()
  132. val = val.Elem()
  133. }
  134. for i := 0; i < typ.NumField(); i++ {
  135. field := typ.Field(i)
  136. fieldName := field.Tag.Get("form")
  137. // Allow ignored fields in the struct
  138. if fieldName == "-" {
  139. continue
  140. } else if len(fieldName) == 0 {
  141. fieldName = com.ToSnakeCase(field.Name)
  142. }
  143. data[fieldName] = val.Field(i).Interface()
  144. }
  145. }
  146. func getSize(field reflect.StructField, prefix string) string {
  147. for _, rule := range strings.Split(field.Tag.Get("binding"), ";") {
  148. if strings.HasPrefix(rule, prefix) {
  149. return rule[8 : len(rule)-1]
  150. }
  151. }
  152. return ""
  153. }
  154. func GetMinSize(field reflect.StructField) string {
  155. return getSize(field, "MinSize(")
  156. }
  157. func GetMaxSize(field reflect.StructField) string {
  158. return getSize(field, "MaxSize(")
  159. }
  160. func validate(errs binding.Errors, data map[string]interface{}, f Form, l macaron.Locale) binding.Errors {
  161. if errs.Len() == 0 {
  162. return errs
  163. }
  164. data["HasError"] = true
  165. AssignForm(f, data)
  166. typ := reflect.TypeOf(f)
  167. val := reflect.ValueOf(f)
  168. if typ.Kind() == reflect.Ptr {
  169. typ = typ.Elem()
  170. val = val.Elem()
  171. }
  172. for i := 0; i < typ.NumField(); i++ {
  173. field := typ.Field(i)
  174. fieldName := field.Tag.Get("form")
  175. // Allow ignored fields in the struct
  176. if fieldName == "-" {
  177. continue
  178. }
  179. if errs[0].FieldNames[0] == field.Name {
  180. data["Err_"+field.Name] = true
  181. trName := l.Tr("form." + field.Name)
  182. switch errs[0].Classification {
  183. case binding.ERR_REQUIRED:
  184. data["ErrorMsg"] = trName + l.Tr("form.require_error")
  185. case binding.ERR_ALPHA_DASH:
  186. data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_error")
  187. case binding.ERR_ALPHA_DASH_DOT:
  188. data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_dot_error")
  189. case binding.ERR_MIN_SIZE:
  190. data["ErrorMsg"] = trName + l.Tr("form.min_size_error", GetMinSize(field))
  191. case binding.ERR_MAX_SIZE:
  192. data["ErrorMsg"] = trName + l.Tr("form.max_size_error", GetMaxSize(field))
  193. case binding.ERR_EMAIL:
  194. data["ErrorMsg"] = trName + l.Tr("form.email_error")
  195. case binding.ERR_URL:
  196. data["ErrorMsg"] = trName + l.Tr("form.url_error")
  197. default:
  198. data["ErrorMsg"] = l.Tr("form.unknown_error") + " " + errs[0].Classification
  199. }
  200. return errs
  201. }
  202. }
  203. return errs
  204. }