auth.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package ui // import "miniflux.app/v2/internal/ui"
  4. import (
  5. "context"
  6. "net/http"
  7. "time"
  8. "miniflux.app/v2/internal/config"
  9. "miniflux.app/v2/internal/http/request"
  10. "miniflux.app/v2/internal/model"
  11. "miniflux.app/v2/internal/oauth2"
  12. "miniflux.app/v2/internal/storage"
  13. )
  14. const sessionCookieName = "MinifluxSessionID"
  15. // authenticateWebSession binds the current browser session to the given user,
  16. // rotates its identifier and secret, and refreshes the client cookie.
  17. func authenticateWebSession(w http.ResponseWriter, r *http.Request, store *storage.Storage, user *model.User) error {
  18. session := request.WebSession(r)
  19. session.SetUser(user)
  20. oldID, secret := session.Rotate()
  21. if err := store.RotateWebSession(oldID, session); err != nil {
  22. return err
  23. }
  24. setSessionCookie(w, session, secret)
  25. return nil
  26. }
  27. // setSessionCookie writes the session cookie to the response with the
  28. // security attributes used by miniflux (HttpOnly, SameSite=Lax, Secure
  29. // when HTTPS).
  30. func setSessionCookie(w http.ResponseWriter, session *model.WebSession, secret string) {
  31. path := config.Opts.BasePath()
  32. if path == "" {
  33. path = "/"
  34. }
  35. http.SetCookie(w, &http.Cookie{
  36. Name: sessionCookieName,
  37. Value: session.ID + "." + secret,
  38. Path: path,
  39. Secure: config.Opts.HTTPS(),
  40. HttpOnly: true,
  41. Expires: time.Now().Add(config.Opts.CleanupRemoveSessionsInterval()),
  42. SameSite: http.SameSiteLaxMode,
  43. })
  44. }
  45. func getOAuth2Manager(ctx context.Context) *oauth2.Manager {
  46. return oauth2.NewManager(
  47. ctx,
  48. config.Opts.OAuth2Provider(),
  49. config.Opts.OAuth2ClientID(),
  50. config.Opts.OAuth2ClientSecret(),
  51. config.Opts.OAuth2RedirectURL(),
  52. config.Opts.OAuth2OIDCDiscoveryEndpoint(),
  53. )
  54. }