player profile added
This commit is contained in:
84
internal/handlers/player_view.go
Normal file
84
internal/handlers/player_view.go
Normal file
@@ -0,0 +1,84 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"git.haelnorr.com/h/golib/hws"
|
||||
"git.haelnorr.com/h/oslstats/internal/db"
|
||||
"git.haelnorr.com/h/oslstats/internal/throw"
|
||||
playersview "git.haelnorr.com/h/oslstats/internal/view/playersview"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
// ProfileRedirect redirects the authenticated user to their own player page.
|
||||
func ProfileRedirect(
|
||||
s *hws.Server,
|
||||
) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
user := db.CurrentUser(r.Context())
|
||||
if user == nil {
|
||||
throw.Unauthorized(s, w, r, "You must be logged in to view your profile", errors.New("user not authenticated"))
|
||||
return
|
||||
}
|
||||
if user.Player == nil {
|
||||
throw.InternalServiceError(s, w, r, "Player profile not found", errors.New("user has no linked player"))
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, fmt.Sprintf("/players/%d", user.Player.ID), http.StatusSeeOther)
|
||||
})
|
||||
}
|
||||
|
||||
// PlayerView renders the player profile page.
|
||||
// If the player has no SlapID and the viewer is the player's owner, show the link prompt.
|
||||
// If the player has no SlapID and the viewer is not the owner, show 404.
|
||||
func PlayerView(
|
||||
s *hws.Server,
|
||||
conn *db.DB,
|
||||
) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
playerIDStr := r.PathValue("player_id")
|
||||
|
||||
playerID, err := strconv.Atoi(playerIDStr)
|
||||
if err != nil {
|
||||
throw.NotFound(s, w, r, r.URL.Path)
|
||||
return
|
||||
}
|
||||
|
||||
var player *db.Player
|
||||
var isOwner bool
|
||||
|
||||
if ok := conn.WithReadTx(s, w, r, func(ctx context.Context, tx bun.Tx) (bool, error) {
|
||||
var err error
|
||||
player, err = db.GetPlayer(ctx, tx, playerID)
|
||||
if err != nil {
|
||||
if db.IsBadRequest(err) {
|
||||
throw.NotFound(s, w, r, r.URL.Path)
|
||||
return false, nil
|
||||
}
|
||||
return false, errors.Wrap(err, "db.GetPlayer")
|
||||
}
|
||||
|
||||
// Check if the current user owns this player
|
||||
user := db.CurrentUser(ctx)
|
||||
if user != nil && player.UserID != nil && *player.UserID == user.ID {
|
||||
isOwner = true
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}); !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// If player has no SlapID and viewer is not the owner, show 404
|
||||
if player.SlapID == nil && !isOwner {
|
||||
throw.NotFound(s, w, r, r.URL.Path)
|
||||
return
|
||||
}
|
||||
|
||||
renderSafely(playersview.PlayerPage(player, isOwner), s, r, w)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user