本站源代码
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.

373 satır
9.8KB

  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package auth
  6. import (
  7. "reflect"
  8. "strings"
  9. "time"
  10. "code.gitea.io/gitea/models"
  11. "code.gitea.io/gitea/modules/base"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/setting"
  14. "code.gitea.io/gitea/modules/timeutil"
  15. "code.gitea.io/gitea/modules/validation"
  16. "gitea.com/macaron/binding"
  17. "gitea.com/macaron/macaron"
  18. "gitea.com/macaron/session"
  19. gouuid "github.com/satori/go.uuid"
  20. "github.com/unknwon/com"
  21. )
  22. // IsAPIPath if URL is an api path
  23. func IsAPIPath(url string) bool {
  24. return strings.HasPrefix(url, "/api/")
  25. }
  26. // IsAttachmentDownload check if request is a file download (GET) with URL to an attachment
  27. func IsAttachmentDownload(ctx *macaron.Context) bool {
  28. return strings.HasPrefix(ctx.Req.URL.Path, "/attachments/") && ctx.Req.Method == "GET"
  29. }
  30. // SignedInID returns the id of signed in user.
  31. func SignedInID(ctx *macaron.Context, sess session.Store) int64 {
  32. if !models.HasEngine {
  33. return 0
  34. }
  35. // Check access token.
  36. if IsAPIPath(ctx.Req.URL.Path) || IsAttachmentDownload(ctx) {
  37. tokenSHA := ctx.Query("token")
  38. if len(tokenSHA) == 0 {
  39. tokenSHA = ctx.Query("access_token")
  40. }
  41. if len(tokenSHA) == 0 {
  42. // Well, check with header again.
  43. auHead := ctx.Req.Header.Get("Authorization")
  44. if len(auHead) > 0 {
  45. auths := strings.Fields(auHead)
  46. if len(auths) == 2 && (auths[0] == "token" || strings.ToLower(auths[0]) == "bearer") {
  47. tokenSHA = auths[1]
  48. }
  49. }
  50. }
  51. // Let's see if token is valid.
  52. if len(tokenSHA) > 0 {
  53. if strings.Contains(tokenSHA, ".") {
  54. uid := CheckOAuthAccessToken(tokenSHA)
  55. if uid != 0 {
  56. ctx.Data["IsApiToken"] = true
  57. }
  58. return uid
  59. }
  60. t, err := models.GetAccessTokenBySHA(tokenSHA)
  61. if err != nil {
  62. if models.IsErrAccessTokenNotExist(err) || models.IsErrAccessTokenEmpty(err) {
  63. log.Error("GetAccessTokenBySHA: %v", err)
  64. }
  65. return 0
  66. }
  67. t.UpdatedUnix = timeutil.TimeStampNow()
  68. if err = models.UpdateAccessToken(t); err != nil {
  69. log.Error("UpdateAccessToken: %v", err)
  70. }
  71. ctx.Data["IsApiToken"] = true
  72. return t.UID
  73. }
  74. }
  75. uid := sess.Get("uid")
  76. if uid == nil {
  77. return 0
  78. } else if id, ok := uid.(int64); ok {
  79. return id
  80. }
  81. return 0
  82. }
  83. // CheckOAuthAccessToken returns uid of user from oauth token token
  84. func CheckOAuthAccessToken(accessToken string) int64 {
  85. // JWT tokens require a "."
  86. if !strings.Contains(accessToken, ".") {
  87. return 0
  88. }
  89. token, err := models.ParseOAuth2Token(accessToken)
  90. if err != nil {
  91. log.Trace("ParseOAuth2Token: %v", err)
  92. return 0
  93. }
  94. var grant *models.OAuth2Grant
  95. if grant, err = models.GetOAuth2GrantByID(token.GrantID); err != nil || grant == nil {
  96. return 0
  97. }
  98. if token.Type != models.TypeAccessToken {
  99. return 0
  100. }
  101. if token.ExpiresAt < time.Now().Unix() || token.IssuedAt > time.Now().Unix() {
  102. return 0
  103. }
  104. return grant.UserID
  105. }
  106. // SignedInUser returns the user object of signed user.
  107. // It returns a bool value to indicate whether user uses basic auth or not.
  108. func SignedInUser(ctx *macaron.Context, sess session.Store) (*models.User, bool) {
  109. if !models.HasEngine {
  110. return nil, false
  111. }
  112. if uid := SignedInID(ctx, sess); uid > 0 {
  113. user, err := models.GetUserByID(uid)
  114. if err == nil {
  115. return user, false
  116. } else if !models.IsErrUserNotExist(err) {
  117. log.Error("GetUserById: %v", err)
  118. }
  119. }
  120. if setting.Service.EnableReverseProxyAuth {
  121. webAuthUser := ctx.Req.Header.Get(setting.ReverseProxyAuthUser)
  122. if len(webAuthUser) > 0 {
  123. u, err := models.GetUserByName(webAuthUser)
  124. if err != nil {
  125. if !models.IsErrUserNotExist(err) {
  126. log.Error("GetUserByName: %v", err)
  127. return nil, false
  128. }
  129. // Check if enabled auto-registration.
  130. if setting.Service.EnableReverseProxyAutoRegister {
  131. email := gouuid.NewV4().String() + "@localhost"
  132. if setting.Service.EnableReverseProxyEmail {
  133. webAuthEmail := ctx.Req.Header.Get(setting.ReverseProxyAuthEmail)
  134. if len(webAuthEmail) > 0 {
  135. email = webAuthEmail
  136. }
  137. }
  138. u := &models.User{
  139. Name: webAuthUser,
  140. Email: email,
  141. Passwd: webAuthUser,
  142. IsActive: true,
  143. }
  144. if err = models.CreateUser(u); err != nil {
  145. // FIXME: should I create a system notice?
  146. log.Error("CreateUser: %v", err)
  147. return nil, false
  148. }
  149. return u, false
  150. }
  151. }
  152. return u, false
  153. }
  154. }
  155. // Check with basic auth.
  156. baHead := ctx.Req.Header.Get("Authorization")
  157. if len(baHead) > 0 {
  158. auths := strings.Fields(baHead)
  159. if len(auths) == 2 && auths[0] == "Basic" {
  160. var u *models.User
  161. uname, passwd, _ := base.BasicAuthDecode(auths[1])
  162. // Check if username or password is a token
  163. isUsernameToken := len(passwd) == 0 || passwd == "x-oauth-basic"
  164. // Assume username is token
  165. authToken := uname
  166. if !isUsernameToken {
  167. // Assume password is token
  168. authToken = passwd
  169. }
  170. uid := CheckOAuthAccessToken(authToken)
  171. if uid != 0 {
  172. var err error
  173. ctx.Data["IsApiToken"] = true
  174. u, err = models.GetUserByID(uid)
  175. if err != nil {
  176. log.Error("GetUserByID: %v", err)
  177. return nil, false
  178. }
  179. }
  180. token, err := models.GetAccessTokenBySHA(authToken)
  181. if err == nil {
  182. if isUsernameToken {
  183. u, err = models.GetUserByID(token.UID)
  184. if err != nil {
  185. log.Error("GetUserByID: %v", err)
  186. return nil, false
  187. }
  188. } else {
  189. u, err = models.GetUserByName(uname)
  190. if err != nil {
  191. log.Error("GetUserByID: %v", err)
  192. return nil, false
  193. }
  194. if u.ID != token.UID {
  195. return nil, false
  196. }
  197. }
  198. token.UpdatedUnix = timeutil.TimeStampNow()
  199. if err = models.UpdateAccessToken(token); err != nil {
  200. log.Error("UpdateAccessToken: %v", err)
  201. }
  202. } else if !models.IsErrAccessTokenNotExist(err) && !models.IsErrAccessTokenEmpty(err) {
  203. log.Error("GetAccessTokenBySha: %v", err)
  204. }
  205. if u == nil {
  206. if !setting.Service.EnableBasicAuth {
  207. return nil, false
  208. }
  209. u, err = models.UserSignIn(uname, passwd)
  210. if err != nil {
  211. if !models.IsErrUserNotExist(err) {
  212. log.Error("UserSignIn: %v", err)
  213. }
  214. return nil, false
  215. }
  216. } else {
  217. ctx.Data["IsApiToken"] = true
  218. }
  219. return u, true
  220. }
  221. }
  222. return nil, false
  223. }
  224. // Form form binding interface
  225. type Form interface {
  226. binding.Validator
  227. }
  228. func init() {
  229. binding.SetNameMapper(com.ToSnakeCase)
  230. }
  231. // AssignForm assign form values back to the template data.
  232. func AssignForm(form interface{}, data map[string]interface{}) {
  233. typ := reflect.TypeOf(form)
  234. val := reflect.ValueOf(form)
  235. if typ.Kind() == reflect.Ptr {
  236. typ = typ.Elem()
  237. val = val.Elem()
  238. }
  239. for i := 0; i < typ.NumField(); i++ {
  240. field := typ.Field(i)
  241. fieldName := field.Tag.Get("form")
  242. // Allow ignored fields in the struct
  243. if fieldName == "-" {
  244. continue
  245. } else if len(fieldName) == 0 {
  246. fieldName = com.ToSnakeCase(field.Name)
  247. }
  248. data[fieldName] = val.Field(i).Interface()
  249. }
  250. }
  251. func getRuleBody(field reflect.StructField, prefix string) string {
  252. for _, rule := range strings.Split(field.Tag.Get("binding"), ";") {
  253. if strings.HasPrefix(rule, prefix) {
  254. return rule[len(prefix) : len(rule)-1]
  255. }
  256. }
  257. return ""
  258. }
  259. // GetSize get size int form tag
  260. func GetSize(field reflect.StructField) string {
  261. return getRuleBody(field, "Size(")
  262. }
  263. // GetMinSize get minimal size in form tag
  264. func GetMinSize(field reflect.StructField) string {
  265. return getRuleBody(field, "MinSize(")
  266. }
  267. // GetMaxSize get max size in form tag
  268. func GetMaxSize(field reflect.StructField) string {
  269. return getRuleBody(field, "MaxSize(")
  270. }
  271. // GetInclude get include in form tag
  272. func GetInclude(field reflect.StructField) string {
  273. return getRuleBody(field, "Include(")
  274. }
  275. func validate(errs binding.Errors, data map[string]interface{}, f Form, l macaron.Locale) binding.Errors {
  276. if errs.Len() == 0 {
  277. return errs
  278. }
  279. data["HasError"] = true
  280. // If the field with name errs[0].FieldNames[0] is not found in form
  281. // somehow, some code later on will panic on Data["ErrorMsg"].(string).
  282. // So initialize it to some default.
  283. data["ErrorMsg"] = l.Tr("form.unknown_error")
  284. AssignForm(f, data)
  285. typ := reflect.TypeOf(f)
  286. val := reflect.ValueOf(f)
  287. if typ.Kind() == reflect.Ptr {
  288. typ = typ.Elem()
  289. val = val.Elem()
  290. }
  291. if field, ok := typ.FieldByName(errs[0].FieldNames[0]); ok {
  292. fieldName := field.Tag.Get("form")
  293. if fieldName != "-" {
  294. data["Err_"+field.Name] = true
  295. trName := field.Tag.Get("locale")
  296. if len(trName) == 0 {
  297. trName = l.Tr("form." + field.Name)
  298. } else {
  299. trName = l.Tr(trName)
  300. }
  301. switch errs[0].Classification {
  302. case binding.ERR_REQUIRED:
  303. data["ErrorMsg"] = trName + l.Tr("form.require_error")
  304. case binding.ERR_ALPHA_DASH:
  305. data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_error")
  306. case binding.ERR_ALPHA_DASH_DOT:
  307. data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_dot_error")
  308. case validation.ErrGitRefName:
  309. data["ErrorMsg"] = trName + l.Tr("form.git_ref_name_error")
  310. case binding.ERR_SIZE:
  311. data["ErrorMsg"] = trName + l.Tr("form.size_error", GetSize(field))
  312. case binding.ERR_MIN_SIZE:
  313. data["ErrorMsg"] = trName + l.Tr("form.min_size_error", GetMinSize(field))
  314. case binding.ERR_MAX_SIZE:
  315. data["ErrorMsg"] = trName + l.Tr("form.max_size_error", GetMaxSize(field))
  316. case binding.ERR_EMAIL:
  317. data["ErrorMsg"] = trName + l.Tr("form.email_error")
  318. case binding.ERR_URL:
  319. data["ErrorMsg"] = trName + l.Tr("form.url_error")
  320. case binding.ERR_INCLUDE:
  321. data["ErrorMsg"] = trName + l.Tr("form.include_error", GetInclude(field))
  322. case validation.ErrGlobPattern:
  323. data["ErrorMsg"] = trName + l.Tr("form.glob_pattern_error", errs[0].Message)
  324. default:
  325. data["ErrorMsg"] = l.Tr("form.unknown_error") + " " + errs[0].Classification
  326. }
  327. return errs
  328. }
  329. }
  330. return errs
  331. }
上海开阖软件有限公司 沪ICP备12045867号-1