1
0

auth.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. package context
  2. import (
  3. "context"
  4. "net/http"
  5. "net/url"
  6. "strings"
  7. "github.com/cockroachdb/errors"
  8. "github.com/flamego/csrf"
  9. "github.com/flamego/flamego"
  10. "github.com/flamego/session"
  11. gouuid "github.com/satori/go.uuid"
  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) flamego.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.Request.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.Request.RequestURI != "/" {
  44. c.RedirectSubpath("/")
  45. return
  46. }
  47. if !options.SignOutRequired && !options.DisableCSRF && c.Request.Method == "POST" && !isAPIPath(c.Request.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.Request.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.Request.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.Request.URL.Path) &&
  73. len(c.GetCookie(conf.Security.CookieUsername)) > 0 {
  74. c.SetCookie("redirect_to", url.QueryEscape(conf.Server.Subpath+c.Request.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 flamego.Context, sess session.Session) (_ int64, isTokenAuth bool) {
  126. if !database.HasEngine {
  127. return 0, false
  128. }
  129. req := c.Request()
  130. // Check access token.
  131. if isAPIPath(req.URL.Path) {
  132. tokenSHA := c.Query("token")
  133. if len(tokenSHA) <= 0 {
  134. tokenSHA = c.Query("access_token")
  135. }
  136. if tokenSHA == "" {
  137. // Well, check with header again.
  138. auHead := req.Header.Get("Authorization")
  139. if len(auHead) > 0 {
  140. auths := strings.Fields(auHead)
  141. if len(auths) == 2 && auths[0] == "token" {
  142. tokenSHA = auths[1]
  143. }
  144. }
  145. }
  146. // Let's see if token is valid.
  147. if len(tokenSHA) > 0 {
  148. t, err := store.GetAccessTokenBySHA1(req.Context(), tokenSHA)
  149. if err != nil {
  150. if !database.IsErrAccessTokenNotExist(err) {
  151. log.Error("GetAccessTokenBySHA: %v", err)
  152. }
  153. return 0, false
  154. }
  155. if err = store.TouchAccessTokenByID(req.Context(), t.ID); err != nil {
  156. log.Error("Failed to touch access token: %v", err)
  157. }
  158. return t.UserID, true
  159. }
  160. }
  161. uid := sess.Get("uid")
  162. if uid == nil {
  163. return 0, false
  164. }
  165. if id, ok := uid.(int64); ok {
  166. _, err := store.GetUserByID(req.Context(), id)
  167. if err != nil {
  168. if !database.IsErrUserNotExist(err) {
  169. log.Error("Failed to get user by ID: %v", err)
  170. }
  171. return 0, false
  172. }
  173. return id, false
  174. }
  175. return 0, false
  176. }
  177. // authenticatedUser returns the user object of the authenticated user, along with two bool values
  178. // which indicate whether the user uses HTTP Basic Authentication or token authentication respectively.
  179. func authenticatedUser(store AuthStore, ctx flamego.Context, sess session.Session) (_ *database.User, isBasicAuth, isTokenAuth bool) {
  180. if !database.HasEngine {
  181. return nil, false, false
  182. }
  183. uid, isTokenAuth := authenticatedUserID(store, ctx, sess)
  184. req := ctx.Request()
  185. if uid <= 0 {
  186. if conf.Auth.EnableReverseProxyAuthentication {
  187. webAuthUser := req.Header.Get(conf.Auth.ReverseProxyAuthenticationHeader)
  188. if len(webAuthUser) > 0 {
  189. user, err := store.GetUserByUsername(req.Context(), webAuthUser)
  190. if err != nil {
  191. if !database.IsErrUserNotExist(err) {
  192. log.Error("Failed to get user by name: %v", err)
  193. return nil, false, false
  194. }
  195. // Check if enabled auto-registration.
  196. if conf.Auth.EnableReverseProxyAutoRegistration {
  197. user, err = store.CreateUser(
  198. req.Context(),
  199. webAuthUser,
  200. gouuid.NewV4().String()+"@localhost",
  201. database.CreateUserOptions{
  202. Activated: true,
  203. },
  204. )
  205. if err != nil {
  206. log.Error("Failed to create user %q: %v", webAuthUser, err)
  207. return nil, false, false
  208. }
  209. }
  210. }
  211. return user, false, false
  212. }
  213. }
  214. // Check with basic auth.
  215. baHead := req.Header.Get("Authorization")
  216. if len(baHead) > 0 {
  217. auths := strings.Fields(baHead)
  218. if len(auths) == 2 && auths[0] == "Basic" {
  219. uname, passwd, _ := tool.BasicAuthDecode(auths[1])
  220. u, err := store.AuthenticateUser(req.Context(), uname, passwd, -1)
  221. if err != nil {
  222. if !auth.IsErrBadCredentials(err) {
  223. log.Error("Failed to authenticate user: %v", err)
  224. }
  225. return nil, false, false
  226. }
  227. return u, true, false
  228. }
  229. }
  230. return nil, false, false
  231. }
  232. u, err := store.GetUserByID(req.Context(), uid)
  233. if err != nil {
  234. log.Error("GetUserByID: %v", err)
  235. return nil, false, false
  236. }
  237. return u, false, isTokenAuth
  238. }
  239. // AuthenticateByToken attempts to authenticate a user by the given access
  240. // token. It returns database.ErrAccessTokenNotExist when the access token does not
  241. // exist.
  242. func AuthenticateByToken(store AuthStore, ctx context.Context, token string) (*database.User, error) {
  243. t, err := store.GetAccessTokenBySHA1(ctx, token)
  244. if err != nil {
  245. return nil, errors.Wrap(err, "get access token by SHA1")
  246. }
  247. if err = store.TouchAccessTokenByID(ctx, t.ID); err != nil {
  248. // NOTE: There is no need to fail the auth flow if we can't touch the token.
  249. log.Error("Failed to touch access token [id: %d]: %v", t.ID, err)
  250. }
  251. user, err := store.GetUserByID(ctx, t.UserID)
  252. if err != nil {
  253. return nil, errors.Wrapf(err, "get user by ID [user_id: %d]", t.UserID)
  254. }
  255. return user, nil
  256. }