auth.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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 context
  5. import (
  6. "context"
  7. "net/http"
  8. "net/url"
  9. "strings"
  10. "github.com/go-macaron/csrf"
  11. "github.com/go-macaron/session"
  12. "github.com/pkg/errors"
  13. gouuid "github.com/satori/go.uuid"
  14. "gopkg.in/macaron.v1"
  15. log "unknwon.dev/clog/v2"
  16. "gogs.io/gogs/internal/auth"
  17. "gogs.io/gogs/internal/conf"
  18. "gogs.io/gogs/internal/db"
  19. "gogs.io/gogs/internal/tool"
  20. )
  21. type ToggleOptions struct {
  22. SignInRequired bool
  23. SignOutRequired bool
  24. AdminRequired bool
  25. DisableCSRF bool
  26. }
  27. func Toggle(options *ToggleOptions) macaron.Handler {
  28. return func(c *Context) {
  29. // Cannot view any page before installation.
  30. if !conf.Security.InstallLock {
  31. c.RedirectSubpath("/install")
  32. return
  33. }
  34. // Check prohibit login users.
  35. if c.IsLogged && c.User.ProhibitLogin {
  36. c.Data["Title"] = c.Tr("auth.prohibit_login")
  37. c.Success("user/auth/prohibit_login")
  38. return
  39. }
  40. // Check non-logged users landing page.
  41. if !c.IsLogged && c.Req.RequestURI == "/" && conf.Server.LandingURL != "/" {
  42. c.RedirectSubpath(conf.Server.LandingURL)
  43. return
  44. }
  45. // Redirect to dashboard if user tries to visit any non-login page.
  46. if options.SignOutRequired && c.IsLogged && c.Req.RequestURI != "/" {
  47. c.RedirectSubpath("/")
  48. return
  49. }
  50. if !options.SignOutRequired && !options.DisableCSRF && c.Req.Method == "POST" && !isAPIPath(c.Req.URL.Path) {
  51. csrf.Validate(c.Context, c.csrf)
  52. if c.Written() {
  53. return
  54. }
  55. }
  56. if options.SignInRequired {
  57. if !c.IsLogged {
  58. // Restrict API calls with error message.
  59. if isAPIPath(c.Req.URL.Path) {
  60. c.JSON(http.StatusForbidden, map[string]string{
  61. "message": "Only authenticated user is allowed to call APIs.",
  62. })
  63. return
  64. }
  65. c.SetCookie("redirect_to", url.QueryEscape(conf.Server.Subpath+c.Req.RequestURI), 0, conf.Server.Subpath)
  66. c.RedirectSubpath("/user/login")
  67. return
  68. } else if !c.User.IsActive && conf.Auth.RequireEmailConfirmation {
  69. c.Title("auth.active_your_account")
  70. c.Success("user/auth/activate")
  71. return
  72. }
  73. }
  74. // Redirect to log in page if auto-signin info is provided and has not signed in.
  75. if !options.SignOutRequired && !c.IsLogged && !isAPIPath(c.Req.URL.Path) &&
  76. len(c.GetCookie(conf.Security.CookieUsername)) > 0 {
  77. c.SetCookie("redirect_to", url.QueryEscape(conf.Server.Subpath+c.Req.RequestURI), 0, conf.Server.Subpath)
  78. c.RedirectSubpath("/user/login")
  79. return
  80. }
  81. if options.AdminRequired {
  82. if !c.User.IsAdmin {
  83. c.Status(http.StatusForbidden)
  84. return
  85. }
  86. c.PageIs("Admin")
  87. }
  88. }
  89. }
  90. func isAPIPath(url string) bool {
  91. return strings.HasPrefix(url, "/api/")
  92. }
  93. // authenticatedUserID returns the ID of the authenticated user, along with a bool value
  94. // which indicates whether the user uses token authentication.
  95. func authenticatedUserID(c *macaron.Context, sess session.Store) (_ int64, isTokenAuth bool) {
  96. if !db.HasEngine {
  97. return 0, false
  98. }
  99. // Check access token.
  100. if isAPIPath(c.Req.URL.Path) {
  101. tokenSHA := c.Query("token")
  102. if len(tokenSHA) <= 0 {
  103. tokenSHA = c.Query("access_token")
  104. }
  105. if tokenSHA == "" {
  106. // Well, check with header again.
  107. auHead := c.Req.Header.Get("Authorization")
  108. if len(auHead) > 0 {
  109. auths := strings.Fields(auHead)
  110. if len(auths) == 2 && auths[0] == "token" {
  111. tokenSHA = auths[1]
  112. }
  113. }
  114. }
  115. // Let's see if token is valid.
  116. if len(tokenSHA) > 0 {
  117. t, err := db.AccessTokens.GetBySHA1(c.Req.Context(), tokenSHA)
  118. if err != nil {
  119. if !db.IsErrAccessTokenNotExist(err) {
  120. log.Error("GetAccessTokenBySHA: %v", err)
  121. }
  122. return 0, false
  123. }
  124. if err = db.AccessTokens.Touch(c.Req.Context(), t.ID); err != nil {
  125. log.Error("Failed to touch access token: %v", err)
  126. }
  127. return t.UserID, true
  128. }
  129. }
  130. uid := sess.Get("uid")
  131. if uid == nil {
  132. return 0, false
  133. }
  134. if id, ok := uid.(int64); ok {
  135. _, err := db.Users.GetByID(c.Req.Context(), id)
  136. if err != nil {
  137. if !db.IsErrUserNotExist(err) {
  138. log.Error("Failed to get user by ID: %v", err)
  139. }
  140. return 0, false
  141. }
  142. return id, false
  143. }
  144. return 0, false
  145. }
  146. // authenticatedUser returns the user object of the authenticated user, along with two bool values
  147. // which indicate whether the user uses HTTP Basic Authentication or token authentication respectively.
  148. func authenticatedUser(ctx *macaron.Context, sess session.Store) (_ *db.User, isBasicAuth, isTokenAuth bool) {
  149. if !db.HasEngine {
  150. return nil, false, false
  151. }
  152. uid, isTokenAuth := authenticatedUserID(ctx, sess)
  153. if uid <= 0 {
  154. if conf.Auth.EnableReverseProxyAuthentication {
  155. webAuthUser := ctx.Req.Header.Get(conf.Auth.ReverseProxyAuthenticationHeader)
  156. if len(webAuthUser) > 0 {
  157. user, err := db.Users.GetByUsername(ctx.Req.Context(), webAuthUser)
  158. if err != nil {
  159. if !db.IsErrUserNotExist(err) {
  160. log.Error("Failed to get user by name: %v", err)
  161. return nil, false, false
  162. }
  163. // Check if enabled auto-registration.
  164. if conf.Auth.EnableReverseProxyAutoRegistration {
  165. user, err = db.Users.Create(
  166. ctx.Req.Context(),
  167. webAuthUser,
  168. gouuid.NewV4().String()+"@localhost",
  169. db.CreateUserOptions{
  170. Activated: true,
  171. },
  172. )
  173. if err != nil {
  174. log.Error("Failed to create user %q: %v", webAuthUser, err)
  175. return nil, false, false
  176. }
  177. }
  178. }
  179. return user, false, false
  180. }
  181. }
  182. // Check with basic auth.
  183. baHead := ctx.Req.Header.Get("Authorization")
  184. if len(baHead) > 0 {
  185. auths := strings.Fields(baHead)
  186. if len(auths) == 2 && auths[0] == "Basic" {
  187. uname, passwd, _ := tool.BasicAuthDecode(auths[1])
  188. u, err := db.Users.Authenticate(ctx.Req.Context(), uname, passwd, -1)
  189. if err != nil {
  190. if !auth.IsErrBadCredentials(err) {
  191. log.Error("Failed to authenticate user: %v", err)
  192. }
  193. return nil, false, false
  194. }
  195. return u, true, false
  196. }
  197. }
  198. return nil, false, false
  199. }
  200. u, err := db.Users.GetByID(ctx.Req.Context(), uid)
  201. if err != nil {
  202. log.Error("GetUserByID: %v", err)
  203. return nil, false, false
  204. }
  205. return u, false, isTokenAuth
  206. }
  207. // AuthenticateByToken attempts to authenticate a user by the given access
  208. // token. It returns db.ErrAccessTokenNotExist when the access token does not
  209. // exist.
  210. func AuthenticateByToken(ctx context.Context, token string) (*db.User, error) {
  211. t, err := db.AccessTokens.GetBySHA1(ctx, token)
  212. if err != nil {
  213. return nil, errors.Wrap(err, "get access token by SHA1")
  214. }
  215. if err = db.AccessTokens.Touch(ctx, t.ID); err != nil {
  216. // NOTE: There is no need to fail the auth flow if we can't touch the token.
  217. log.Error("Failed to touch access token [id: %d]: %v", t.ID, err)
  218. }
  219. user, err := db.Users.GetByID(ctx, t.UserID)
  220. if err != nil {
  221. return nil, errors.Wrapf(err, "get user by ID [user_id: %d]", t.UserID)
  222. }
  223. return user, nil
  224. }