auth.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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/database"
  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. type AuthStore interface {
  94. // GetAccessTokenBySHA1 returns the access token with given SHA1. It returns
  95. // database.ErrAccessTokenNotExist when not found.
  96. GetAccessTokenBySHA1(ctx context.Context, sha1 string) (*database.AccessToken, error)
  97. // TouchAccessTokenByID updates the updated time of the given access token to
  98. // the current time.
  99. TouchAccessTokenByID(ctx context.Context, id int64) error
  100. // GetUserByID returns the user with given ID. It returns
  101. // database.ErrUserNotExist when not found.
  102. GetUserByID(ctx context.Context, id int64) (*database.User, error)
  103. // GetUserByUsername returns the user with given username. It returns
  104. // database.ErrUserNotExist when not found.
  105. GetUserByUsername(ctx context.Context, username string) (*database.User, error)
  106. // CreateUser creates a new user and persists to database. It returns
  107. // database.ErrNameNotAllowed if the given name or pattern of the name is not
  108. // allowed as a username, or database.ErrUserAlreadyExist when a user with same
  109. // name already exists, or database.ErrEmailAlreadyUsed if the email has been
  110. // verified by another user.
  111. CreateUser(ctx context.Context, username, email string, opts database.CreateUserOptions) (*database.User, error)
  112. // AuthenticateUser validates username and password via given login source ID.
  113. // It returns database.ErrUserNotExist when the user was not found.
  114. //
  115. // When the "loginSourceID" is negative, it aborts the process and returns
  116. // database.ErrUserNotExist if the user was not found in the database.
  117. //
  118. // When the "loginSourceID" is non-negative, it returns
  119. // database.ErrLoginSourceMismatch if the user has different login source ID
  120. // than the "loginSourceID".
  121. //
  122. // When the "loginSourceID" is positive, it tries to authenticate via given
  123. // login source and creates a new user when not yet exists in the database.
  124. AuthenticateUser(ctx context.Context, login, password string, loginSourceID int64) (*database.User, error)
  125. }
  126. // authenticatedUserID returns the ID of the authenticated user, along with a bool value
  127. // which indicates whether the user uses token authentication.
  128. func authenticatedUserID(store AuthStore, c *macaron.Context, sess session.Store) (_ int64, isTokenAuth bool) {
  129. if !database.HasEngine {
  130. return 0, false
  131. }
  132. // Check access token.
  133. if isAPIPath(c.Req.URL.Path) {
  134. tokenSHA := c.Query("token")
  135. if len(tokenSHA) <= 0 {
  136. tokenSHA = c.Query("access_token")
  137. }
  138. if tokenSHA == "" {
  139. // Well, check with header again.
  140. auHead := c.Req.Header.Get("Authorization")
  141. if len(auHead) > 0 {
  142. auths := strings.Fields(auHead)
  143. if len(auths) == 2 && auths[0] == "token" {
  144. tokenSHA = auths[1]
  145. }
  146. }
  147. }
  148. // Let's see if token is valid.
  149. if len(tokenSHA) > 0 {
  150. t, err := store.GetAccessTokenBySHA1(c.Req.Context(), tokenSHA)
  151. if err != nil {
  152. if !database.IsErrAccessTokenNotExist(err) {
  153. log.Error("GetAccessTokenBySHA: %v", err)
  154. }
  155. return 0, false
  156. }
  157. if err = store.TouchAccessTokenByID(c.Req.Context(), t.ID); err != nil {
  158. log.Error("Failed to touch access token: %v", err)
  159. }
  160. return t.UserID, true
  161. }
  162. }
  163. uid := sess.Get("uid")
  164. if uid == nil {
  165. return 0, false
  166. }
  167. if id, ok := uid.(int64); ok {
  168. _, err := store.GetUserByID(c.Req.Context(), id)
  169. if err != nil {
  170. if !database.IsErrUserNotExist(err) {
  171. log.Error("Failed to get user by ID: %v", err)
  172. }
  173. return 0, false
  174. }
  175. return id, false
  176. }
  177. return 0, false
  178. }
  179. // authenticatedUser returns the user object of the authenticated user, along with two bool values
  180. // which indicate whether the user uses HTTP Basic Authentication or token authentication respectively.
  181. func authenticatedUser(store AuthStore, ctx *macaron.Context, sess session.Store) (_ *database.User, isBasicAuth, isTokenAuth bool) {
  182. if !database.HasEngine {
  183. return nil, false, false
  184. }
  185. uid, isTokenAuth := authenticatedUserID(store, ctx, sess)
  186. if uid <= 0 {
  187. if conf.Auth.EnableReverseProxyAuthentication {
  188. webAuthUser := ctx.Req.Header.Get(conf.Auth.ReverseProxyAuthenticationHeader)
  189. if len(webAuthUser) > 0 {
  190. user, err := store.GetUserByUsername(ctx.Req.Context(), webAuthUser)
  191. if err != nil {
  192. if !database.IsErrUserNotExist(err) {
  193. log.Error("Failed to get user by name: %v", err)
  194. return nil, false, false
  195. }
  196. // Check if enabled auto-registration.
  197. if conf.Auth.EnableReverseProxyAutoRegistration {
  198. user, err = store.CreateUser(
  199. ctx.Req.Context(),
  200. webAuthUser,
  201. gouuid.NewV4().String()+"@localhost",
  202. database.CreateUserOptions{
  203. Activated: true,
  204. },
  205. )
  206. if err != nil {
  207. log.Error("Failed to create user %q: %v", webAuthUser, err)
  208. return nil, false, false
  209. }
  210. }
  211. }
  212. return user, false, false
  213. }
  214. }
  215. // Check with basic auth.
  216. baHead := ctx.Req.Header.Get("Authorization")
  217. if len(baHead) > 0 {
  218. auths := strings.Fields(baHead)
  219. if len(auths) == 2 && auths[0] == "Basic" {
  220. uname, passwd, _ := tool.BasicAuthDecode(auths[1])
  221. u, err := store.AuthenticateUser(ctx.Req.Context(), uname, passwd, -1)
  222. if err != nil {
  223. if !auth.IsErrBadCredentials(err) {
  224. log.Error("Failed to authenticate user: %v", err)
  225. }
  226. return nil, false, false
  227. }
  228. return u, true, false
  229. }
  230. }
  231. return nil, false, false
  232. }
  233. u, err := store.GetUserByID(ctx.Req.Context(), uid)
  234. if err != nil {
  235. log.Error("GetUserByID: %v", err)
  236. return nil, false, false
  237. }
  238. return u, false, isTokenAuth
  239. }
  240. // AuthenticateByToken attempts to authenticate a user by the given access
  241. // token. It returns database.ErrAccessTokenNotExist when the access token does not
  242. // exist.
  243. func AuthenticateByToken(store AuthStore, ctx context.Context, token string) (*database.User, error) {
  244. t, err := store.GetAccessTokenBySHA1(ctx, token)
  245. if err != nil {
  246. return nil, errors.Wrap(err, "get access token by SHA1")
  247. }
  248. if err = store.TouchAccessTokenByID(ctx, t.ID); err != nil {
  249. // NOTE: There is no need to fail the auth flow if we can't touch the token.
  250. log.Error("Failed to touch access token [id: %d]: %v", t.ID, err)
  251. }
  252. user, err := store.GetUserByID(ctx, t.UserID)
  253. if err != nil {
  254. return nil, errors.Wrapf(err, "get user by ID [user_id: %d]", t.UserID)
  255. }
  256. return user, nil
  257. }