diff --git a/internal/api/me.go b/internal/api/me.go new file mode 100644 index 000000000..e58574df6 --- /dev/null +++ b/internal/api/me.go @@ -0,0 +1,49 @@ +package api + +import ( + "fmt" + "net/http" + + "github.com/hashicorp/go-hclog" +) + +func MeHandler( + l hclog.Logger, +) http.Handler { + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + errResp := func(httpCode int, userErrMsg, logErrMsg string, err error) { + l.Error(logErrMsg, + "method", r.Method, + "path", r.URL.Path, + "error", err, + ) + errJSON := fmt.Sprintf(`{"error": "%s"}`, userErrMsg) + http.Error(w, errJSON, httpCode) + } + + // Authorize request. + userEmail := r.Context().Value("userEmail").(string) + if userEmail == "" { + errResp( + http.StatusUnauthorized, + "No authorization information for request", + "no user email found in request context", + nil, + ) + return + } + + switch r.Method { + // The HEAD method is used to determine if the user is currently + // authenticated. + case "HEAD": + w.WriteHeader(http.StatusOK) + return + + default: + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + }) +} diff --git a/internal/api/me_subscriptions.go b/internal/api/me_subscriptions.go index 4e403b334..1efb9d99d 100644 --- a/internal/api/me_subscriptions.go +++ b/internal/api/me_subscriptions.go @@ -81,22 +81,6 @@ func MeSubscriptionsHandler( ) return } - case "HEAD": - // Find or create user. - u := models.User{ - EmailAddress: userEmail, - } - // Write response. - w.WriteHeader(http.StatusOK) - if err := u.FirstOrCreate(db); err != nil { - errResp( - http.StatusInternalServerError, - "Error authorizing the request", - "error finding or creating user", - err, - ) - return - } case "POST": // Decode request. diff --git a/internal/cmd/commands/server/server.go b/internal/cmd/commands/server/server.go index e85613f63..a779b35c8 100644 --- a/internal/cmd/commands/server/server.go +++ b/internal/cmd/commands/server/server.go @@ -266,6 +266,7 @@ func (c *Command) Run(args []string) int { api.DraftsHandler(cfg, c.Log, algoSearch, algoWrite, goog, db)}, {"/api/v1/drafts/", api.DraftsDocumentHandler(cfg, c.Log, algoSearch, algoWrite, goog)}, + {"/api/v1/me", api.MeHandler(c.Log)}, {"/api/v1/me/subscriptions", api.MeSubscriptionsHandler(cfg, c.Log, goog, db)}, {"/api/v1/people", api.PeopleDataHandler(cfg, c.Log, goog)},