You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

275 lines
6.7 KiB

8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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. "reflect"
  7. "strings"
  8. "time"
  9. "github.com/Unknwon/com"
  10. "github.com/go-macaron/binding"
  11. "github.com/go-macaron/session"
  12. gouuid "github.com/satori/go.uuid"
  13. "gopkg.in/macaron.v1"
  14. "code.gitea.io/gitea/models"
  15. "code.gitea.io/gitea/modules/base"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/setting"
  18. )
  19. // IsAPIPath if URL is an api path
  20. func IsAPIPath(url string) bool {
  21. return strings.HasPrefix(url, "/api/")
  22. }
  23. // SignedInID returns the id of signed in user.
  24. func SignedInID(ctx *macaron.Context, sess session.Store) int64 {
  25. if !models.HasEngine {
  26. return 0
  27. }
  28. // Check access token.
  29. if IsAPIPath(ctx.Req.URL.Path) {
  30. tokenSHA := ctx.Query("token")
  31. if len(tokenSHA) <= 0 {
  32. tokenSHA = ctx.Query("access_token")
  33. }
  34. if len(tokenSHA) == 0 {
  35. // Well, check with header again.
  36. auHead := ctx.Req.Header.Get("Authorization")
  37. if len(auHead) > 0 {
  38. auths := strings.Fields(auHead)
  39. if len(auths) == 2 && auths[0] == "token" {
  40. tokenSHA = auths[1]
  41. }
  42. }
  43. }
  44. // Let's see if token is valid.
  45. if len(tokenSHA) > 0 {
  46. t, err := models.GetAccessTokenBySHA(tokenSHA)
  47. if err != nil {
  48. if models.IsErrAccessTokenNotExist(err) || models.IsErrAccessTokenEmpty(err) {
  49. log.Error(4, "GetAccessTokenBySHA: %v", err)
  50. }
  51. return 0
  52. }
  53. t.Updated = time.Now()
  54. if err = models.UpdateAccessToken(t); err != nil {
  55. log.Error(4, "UpdateAccessToken: %v", err)
  56. }
  57. return t.UID
  58. }
  59. }
  60. uid := sess.Get("uid")
  61. if uid == nil {
  62. return 0
  63. } else if id, ok := uid.(int64); ok {
  64. return id
  65. }
  66. return 0
  67. }
  68. // SignedInUser returns the user object of signed user.
  69. // It returns a bool value to indicate whether user uses basic auth or not.
  70. func SignedInUser(ctx *macaron.Context, sess session.Store) (*models.User, bool) {
  71. if !models.HasEngine {
  72. return nil, false
  73. }
  74. if uid := SignedInID(ctx, sess); uid > 0 {
  75. user, err := models.GetUserByID(uid)
  76. if err == nil {
  77. return user, false
  78. } else if !models.IsErrUserNotExist(err) {
  79. log.Error(4, "GetUserById: %v", err)
  80. }
  81. }
  82. if setting.Service.EnableReverseProxyAuth {
  83. webAuthUser := ctx.Req.Header.Get(setting.ReverseProxyAuthUser)
  84. if len(webAuthUser) > 0 {
  85. u, err := models.GetUserByName(webAuthUser)
  86. if err != nil {
  87. if !models.IsErrUserNotExist(err) {
  88. log.Error(4, "GetUserByName: %v", err)
  89. return nil, false
  90. }
  91. // Check if enabled auto-registration.
  92. if setting.Service.EnableReverseProxyAutoRegister {
  93. u := &models.User{
  94. Name: webAuthUser,
  95. Email: gouuid.NewV4().String() + "@localhost",
  96. Passwd: webAuthUser,
  97. IsActive: true,
  98. }
  99. if err = models.CreateUser(u); err != nil {
  100. // FIXME: should I create a system notice?
  101. log.Error(4, "CreateUser: %v", err)
  102. return nil, false
  103. }
  104. return u, false
  105. }
  106. }
  107. return u, false
  108. }
  109. }
  110. // Check with basic auth.
  111. baHead := ctx.Req.Header.Get("Authorization")
  112. if len(baHead) > 0 {
  113. auths := strings.Fields(baHead)
  114. if len(auths) == 2 && auths[0] == "Basic" {
  115. uname, passwd, _ := base.BasicAuthDecode(auths[1])
  116. u, err := models.UserSignIn(uname, passwd)
  117. if err != nil {
  118. if !models.IsErrUserNotExist(err) {
  119. log.Error(4, "UserSignIn: %v", err)
  120. }
  121. return nil, false
  122. }
  123. return u, true
  124. }
  125. }
  126. return nil, false
  127. }
  128. // Form form binding interface
  129. type Form interface {
  130. binding.Validator
  131. }
  132. func init() {
  133. binding.SetNameMapper(com.ToSnakeCase)
  134. }
  135. // AssignForm assign form values back to the template data.
  136. func AssignForm(form interface{}, data map[string]interface{}) {
  137. typ := reflect.TypeOf(form)
  138. val := reflect.ValueOf(form)
  139. if typ.Kind() == reflect.Ptr {
  140. typ = typ.Elem()
  141. val = val.Elem()
  142. }
  143. for i := 0; i < typ.NumField(); i++ {
  144. field := typ.Field(i)
  145. fieldName := field.Tag.Get("form")
  146. // Allow ignored fields in the struct
  147. if fieldName == "-" {
  148. continue
  149. } else if len(fieldName) == 0 {
  150. fieldName = com.ToSnakeCase(field.Name)
  151. }
  152. data[fieldName] = val.Field(i).Interface()
  153. }
  154. }
  155. func getRuleBody(field reflect.StructField, prefix string) string {
  156. for _, rule := range strings.Split(field.Tag.Get("binding"), ";") {
  157. if strings.HasPrefix(rule, prefix) {
  158. return rule[len(prefix) : len(rule)-1]
  159. }
  160. }
  161. return ""
  162. }
  163. // GetSize get size int form tag
  164. func GetSize(field reflect.StructField) string {
  165. return getRuleBody(field, "Size(")
  166. }
  167. // GetMinSize get minimal size in form tag
  168. func GetMinSize(field reflect.StructField) string {
  169. return getRuleBody(field, "MinSize(")
  170. }
  171. // GetMaxSize get max size in form tag
  172. func GetMaxSize(field reflect.StructField) string {
  173. return getRuleBody(field, "MaxSize(")
  174. }
  175. // GetInclude get include in form tag
  176. func GetInclude(field reflect.StructField) string {
  177. return getRuleBody(field, "Include(")
  178. }
  179. // FIXME: struct contains a struct
  180. func validateStruct(obj interface{}) binding.Errors {
  181. return nil
  182. }
  183. func validate(errs binding.Errors, data map[string]interface{}, f Form, l macaron.Locale) binding.Errors {
  184. if errs.Len() == 0 {
  185. return errs
  186. }
  187. data["HasError"] = true
  188. AssignForm(f, data)
  189. typ := reflect.TypeOf(f)
  190. val := reflect.ValueOf(f)
  191. if typ.Kind() == reflect.Ptr {
  192. typ = typ.Elem()
  193. val = val.Elem()
  194. }
  195. for i := 0; i < typ.NumField(); i++ {
  196. field := typ.Field(i)
  197. fieldName := field.Tag.Get("form")
  198. // Allow ignored fields in the struct
  199. if fieldName == "-" {
  200. continue
  201. }
  202. if errs[0].FieldNames[0] == field.Name {
  203. data["Err_"+field.Name] = true
  204. trName := field.Tag.Get("locale")
  205. if len(trName) == 0 {
  206. trName = l.Tr("form." + field.Name)
  207. } else {
  208. trName = l.Tr(trName)
  209. }
  210. switch errs[0].Classification {
  211. case binding.ERR_REQUIRED:
  212. data["ErrorMsg"] = trName + l.Tr("form.require_error")
  213. case binding.ERR_ALPHA_DASH:
  214. data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_error")
  215. case binding.ERR_ALPHA_DASH_DOT:
  216. data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_dot_error")
  217. case binding.ERR_SIZE:
  218. data["ErrorMsg"] = trName + l.Tr("form.size_error", GetSize(field))
  219. case binding.ERR_MIN_SIZE:
  220. data["ErrorMsg"] = trName + l.Tr("form.min_size_error", GetMinSize(field))
  221. case binding.ERR_MAX_SIZE:
  222. data["ErrorMsg"] = trName + l.Tr("form.max_size_error", GetMaxSize(field))
  223. case binding.ERR_EMAIL:
  224. data["ErrorMsg"] = trName + l.Tr("form.email_error")
  225. case binding.ERR_URL:
  226. data["ErrorMsg"] = trName + l.Tr("form.url_error")
  227. case binding.ERR_INCLUDE:
  228. data["ErrorMsg"] = trName + l.Tr("form.include_error", GetInclude(field))
  229. default:
  230. data["ErrorMsg"] = l.Tr("form.unknown_error") + " " + errs[0].Classification
  231. }
  232. return errs
  233. }
  234. }
  235. return errs
  236. }