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.

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