auth.go 8.7 KB

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