restapi.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package httpservers
  2. import (
  3. "context"
  4. "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
  5. log "github.com/sirupsen/logrus"
  6. "google.golang.org/grpc"
  7. "google.golang.org/grpc/metadata"
  8. "google.golang.org/protobuf/encoding/protojson"
  9. "net/http"
  10. gw "github.com/OliveTin/OliveTin/gen/grpc"
  11. config "github.com/OliveTin/OliveTin/internal/config"
  12. cors "github.com/OliveTin/OliveTin/internal/cors"
  13. )
  14. var (
  15. cfg *config.Config
  16. )
  17. func parseHttpHeaderForAuth(req *http.Request) (string, string) {
  18. username, ok := req.Header[cfg.AuthHttpHeaderUsername]
  19. if !ok {
  20. return "", ""
  21. }
  22. if cfg.AuthHttpHeaderUserGroup != "" {
  23. usergroup, ok := req.Header[cfg.AuthHttpHeaderUserGroup]
  24. if ok {
  25. return username[0], usergroup[0]
  26. }
  27. }
  28. return username[0], ""
  29. }
  30. func parseRequestMetadata(ctx context.Context, req *http.Request) metadata.MD {
  31. username := ""
  32. usergroup := ""
  33. if cfg.AuthJwtCookieName != "" {
  34. username, usergroup = parseJwtCookie(req)
  35. }
  36. if cfg.AuthHttpHeaderUsername != "" {
  37. username, usergroup = parseHttpHeaderForAuth(req)
  38. }
  39. md := metadata.Pairs(
  40. "username", username,
  41. "usergroup", usergroup,
  42. )
  43. log.Debugf("jwt usable claims: %+v", md)
  44. return md
  45. }
  46. func startRestAPIServer(globalConfig *config.Config) error {
  47. cfg = globalConfig
  48. log.WithFields(log.Fields{
  49. "address": cfg.ListenAddressGrpcActions,
  50. }).Info("Starting REST API")
  51. ctx := context.Background()
  52. ctx, cancel := context.WithCancel(ctx)
  53. defer cancel()
  54. // The JSONPb.EmitDefaults is necssary, so "empty" fields are returned in JSON.
  55. mux := runtime.NewServeMux(
  56. runtime.WithMetadata(func(ctx context.Context, request *http.Request) metadata.MD {
  57. return parseRequestMetadata(ctx, request)
  58. }),
  59. runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.HTTPBodyMarshaler{
  60. Marshaler: &runtime.JSONPb{
  61. MarshalOptions: protojson.MarshalOptions{
  62. UseProtoNames: true,
  63. EmitUnpopulated: true,
  64. },
  65. },
  66. }),
  67. )
  68. opts := []grpc.DialOption{grpc.WithInsecure()}
  69. err := gw.RegisterOliveTinApiHandlerFromEndpoint(ctx, mux, cfg.ListenAddressGrpcActions, opts)
  70. if err != nil {
  71. log.Errorf("Could not register REST API Handler %v", err)
  72. return err
  73. }
  74. return http.ListenAndServe(cfg.ListenAddressRestActions, cors.AllowCors(mux))
  75. }