Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add /me endpoint to determine if the user is currently authenticated #108

Merged
merged 1 commit into from
Mar 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions internal/api/me.go
Original file line number Diff line number Diff line change
@@ -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
}
})
}
16 changes: 0 additions & 16 deletions internal/api/me_subscriptions.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions internal/cmd/commands/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)},
Expand Down