package route import ( "net/http" "omctf.ru/block-game-backend/auth" "omctf.ru/block-game-backend/codegen/ent" "omctf.ru/block-game-backend/codegen/ent/predicate" "omctf.ru/block-game-backend/codegen/ent/user" "omctf.ru/block-game-backend/db" "omctf.ru/block-game-backend/utils" ) func Whoami(w http.ResponseWriter, r *http.Request) { user, err := auth.GetUser(r.Context()) if err != nil || user == nil { utils.BailInternalServerError(w, err) return } utils.RespondWithJSON(w, map[string]any{ "id": user.ID, "username": user.Username, }) } func GetUser(w http.ResponseWriter, r *http.Request) { _, err := auth.GetUser(r.Context()) if err != nil { utils.BailInternalServerError(w, err) return } req, err := utils.GetJSONBody[struct { Id int `json:"id"` Username string `json:"username"` }](r) if err != nil || req == nil { http.Error(w, err.Error(), http.StatusBadRequest) return } if req.Id == 0 && req.Username == "" { http.Error(w, "Either id or username must be provided", http.StatusBadRequest) return } predicates := []predicate.User{} if req.Id != 0 { predicates = append(predicates, user.ID(req.Id)) } if req.Username != "" { predicates = append(predicates, user.Username(req.Username)) } user, err := db.Client.User.Query().Where(predicates...).Only(r.Context()) if ent.IsNotFound(err) { http.Error(w, "User not found", http.StatusNotFound) return } if err != nil { utils.BailInternalServerError(w, err) return } utils.RespondWithJSON(w, map[string]any{ "id": user.ID, "username": user.Username, }) }