Skip to content

Commit

Permalink
feat: allow sessions without cf lat/lng
Browse files Browse the repository at this point in the history
  • Loading branch information
its-felix committed Oct 9, 2024
1 parent 66af20a commit 2a1a35e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
11 changes: 10 additions & 1 deletion service/auth/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ type SessionMetadata struct {
Lng float64 `json:"lng"`
}

func (sm SessionMetadata) IsZero() bool {
var zero SessionMetadata
return sm == zero
}

type PgxConn interface {
Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error)
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
Expand Down Expand Up @@ -117,7 +122,11 @@ func DeleteSession(ctx context.Context, conn PgxConn, id string) error {
return err
}

func isMetadataPlausible(orig SessionMetadata, current SessionMetadata, passed time.Duration) bool {
func isMetadataPlausible(orig, current SessionMetadata, passed time.Duration) bool {
if orig.IsZero() {
return true
}

travelledKm := distance(orig.Lat, orig.Lng, current.Lat, current.Lng)
if travelledKm > 1000 {
// never allow to travel more than 1000km
Expand Down
19 changes: 12 additions & 7 deletions web/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,14 +161,19 @@ func AuthenticatedMiddleware(conv *service.SessionJwtConverter) echo.MiddlewareF
}

var sessionMetadata auth.SessionMetadata
sessionMetadata.Lat, err = strconv.ParseFloat(c.Request().Header.Get(cfLatHeaderName), 64)
if err != nil {
return ctx, nil, onErr(c, rctx, cookie, claims.SessionId, err)
}
if cfLat, cfLng := c.Request().Header.Get(cfLatHeaderName), c.Request().Header.Get(cfLngHeaderName); cfLat != "" && cfLng != "" {
sessionMetadata.Lat, err = strconv.ParseFloat(cfLat, 64)
if err != nil {
return ctx, nil, onErr(c, rctx, cookie, claims.SessionId, err)
}

sessionMetadata.Lng, err = strconv.ParseFloat(c.Request().Header.Get(cfLngHeaderName), 64)
if err != nil {
return ctx, nil, onErr(c, rctx, cookie, claims.SessionId, err)
sessionMetadata.Lng, err = strconv.ParseFloat(cfLng, 64)
if err != nil {
return ctx, nil, onErr(c, rctx, cookie, claims.SessionId, err)
}
} else {
slog.WarnContext(ctx, fmt.Sprintf("CF headers not present: %v", c.Request().Header))
// continue with zero value of SessionMetadata
}

var session auth.Session
Expand Down

0 comments on commit 2a1a35e

Please sign in to comment.