api_login_gate.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package api
  2. import (
  3. ctx "context"
  4. "errors"
  5. "net/http"
  6. "connectrpc.com/connect"
  7. apiv1connect "github.com/OliveTin/OliveTin/gen/olivetin/api/v1/apiv1connect"
  8. auth "github.com/OliveTin/OliveTin/internal/auth"
  9. )
  10. // When authRequireGuestsToLogin is enabled, unauthenticated visitors may only
  11. // call these procedures, which are needed to log in or to check the server is
  12. // up. Every other procedure is refused before its handler runs, so a handler
  13. // cannot forget the check, and a lookup cannot reveal whether an ID exists.
  14. //
  15. // Adding a procedure here makes it public. TestEveryProcedureRequiresLoginUnlessPublic
  16. // lists the same procedures and fails if the two lists differ.
  17. var loginNotRequiredProcedures = map[string]bool{
  18. apiv1connect.OliveTinApiServiceInitProcedure: true,
  19. apiv1connect.OliveTinApiServiceGetReadyzProcedure: true,
  20. apiv1connect.OliveTinApiServiceLocalUserLoginProcedure: true,
  21. apiv1connect.OliveTinApiServiceLogoutProcedure: true,
  22. apiv1connect.OliveTinApiServicePasswordHashProcedure: true,
  23. }
  24. var errLoginRequired = errors.New("login is required")
  25. type loginRequiredInterceptor struct {
  26. api *oliveTinAPI
  27. }
  28. func (interceptor *loginRequiredInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc {
  29. return func(callCtx ctx.Context, req connect.AnyRequest) (connect.AnyResponse, error) {
  30. if err := interceptor.checkLoginRequired(req.Spec().Procedure, req.Header()); err != nil {
  31. return nil, err
  32. }
  33. return next(callCtx, req)
  34. }
  35. }
  36. func (interceptor *loginRequiredInterceptor) WrapStreamingClient(next connect.StreamingClientFunc) connect.StreamingClientFunc {
  37. return next
  38. }
  39. func (interceptor *loginRequiredInterceptor) WrapStreamingHandler(next connect.StreamingHandlerFunc) connect.StreamingHandlerFunc {
  40. return func(callCtx ctx.Context, conn connect.StreamingHandlerConn) error {
  41. if err := interceptor.checkLoginRequired(conn.Spec().Procedure, conn.RequestHeader()); err != nil {
  42. return err
  43. }
  44. return next(callCtx, conn)
  45. }
  46. }
  47. func (interceptor *loginRequiredInterceptor) checkLoginRequired(procedure string, header http.Header) error {
  48. if loginNotRequiredProcedures[procedure] {
  49. return nil
  50. }
  51. cfg := interceptor.api.cfg
  52. user := auth.UserFromHeaders(header, procedure, cfg)
  53. if user.MustLogIn(cfg) {
  54. return connect.NewError(connect.CodePermissionDenied, errLoginRequired)
  55. }
  56. return nil
  57. }