Created response structs and a json response util.

This commit is contained in:
2026-05-01 07:50:31 +02:00
parent 85b83a0741
commit 6f9e37b69a
4 changed files with 71 additions and 49 deletions
+24 -35
View File
@@ -17,26 +17,20 @@ import (
"golang.org/x/crypto/bcrypt"
)
const ISSUER = "nfeeder-app"
type AuthResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
}
type RefreshTokenReq struct {
RefreshToken string `json:"refresh_token"`
}
func (s *Server) handleRegister() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
email := r.FormValue("email")
password := r.FormValue("password")
if email == "" || password == "" {
WriteJSON(w, http.StatusBadRequest, ErrorResponse{Error: "Email and password required"})
return
}
// hash password
hashpw, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
http.Error(w, "Internal Error", http.StatusInternalServerError)
WriteJSON(w, http.StatusInternalServerError, ErrorResponse{Error: "Internal Error"})
return
}
@@ -47,8 +41,8 @@ func (s *Server) handleRegister() http.HandlerFunc {
})
if err != nil {
// Log the actual error for yourself, send a generic one to the user
log.Printf("failed to create user: %v", err)
http.Error(w, "Could not create user", http.StatusBadRequest)
log.Printf("Failed to create user: %v", err)
WriteJSON(w, http.StatusBadRequest, ErrorResponse{Error: "Failed to create user"})
return
}
@@ -64,7 +58,7 @@ func (s *Server) handleLogin() http.HandlerFunc {
user, err := s.store.GetUserByEmail(r.Context(), email)
if err != nil {
log.Printf("failed to get user: %v", err)
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
WriteJSON(w, http.StatusUnauthorized, ErrorResponse{Error: "Invalid credentials"})
return
}
@@ -72,7 +66,7 @@ func (s *Server) handleLogin() http.HandlerFunc {
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
if err != nil {
log.Printf("incorrect password entered: %v", err)
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
WriteJSON(w, http.StatusUnauthorized, ErrorResponse{Error: "Invalid credentials"})
return
}
@@ -87,7 +81,7 @@ func (s *Server) handleLogout() http.HandlerFunc {
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
log.Printf("handleRefresh failed to parse request body: %v", err)
http.Error(w, "Invalid JSON", http.StatusBadRequest)
WriteJSON(w, http.StatusBadRequest, ErrorResponse{Error: "Invalid JSON"})
return
}
@@ -97,8 +91,7 @@ func (s *Server) handleLogout() http.HandlerFunc {
tokenRecord, err := s.store.GetValidRefreshToken(r.Context(), hex_token)
if err != nil {
log.Printf("Logout succes, warning: token not found or expired: %v", err)
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"message": "logout success"})
WriteJSON(w, http.StatusOK, SuccessResponse{Message: "logout success"})
return
}
@@ -110,8 +103,9 @@ func (s *Server) handleLogout() http.HandlerFunc {
log.Printf("Failed to delete old refresh token: %v", err)
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"message": "logout success"})
WriteJSON(w, http.StatusOK, SuccessResponse{
Message: "logout success",
})
}
}
@@ -122,7 +116,7 @@ func (s *Server) handleRefresh() http.HandlerFunc {
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
log.Printf("handleRefresh failed to parse request body: %v", err)
http.Error(w, "Invalid JSON", http.StatusBadRequest)
WriteJSON(w, http.StatusBadRequest, ErrorResponse{Error: "Invalid JSON"})
return
}
@@ -132,7 +126,7 @@ func (s *Server) handleRefresh() http.HandlerFunc {
tokenRecord, err := s.store.GetValidRefreshToken(r.Context(), hex_token)
if err != nil {
log.Printf("Refresh failed - token not found or expired: %v", err)
http.Error(w, "Invalid or expired session", http.StatusUnauthorized)
WriteJSON(w, http.StatusUnauthorized, ErrorResponse{Error: "Invalid or expired session"})
return
}
@@ -144,7 +138,7 @@ func (s *Server) handleRefresh() http.HandlerFunc {
log.Printf("Failed to delete old refresh token: %v", err)
}
s.issueToken(w, r, tokenRecord.UserID, true)
s.issueToken(w, r, tokenRecord.UserID, false)
}
}
@@ -162,27 +156,22 @@ func (s *Server) issueToken(w http.ResponseWriter, r *http.Request, userID int64
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(s.jwtSecret)
if err != nil {
http.Error(w, "Internal Error", http.StatusInternalServerError)
WriteJSON(w, http.StatusInternalServerError, ErrorResponse{
Error: "Internal Server Error",
})
return
}
refreshToken := s.issueRefreshToken(r.Context(), userID, nowTime, checkLimit)
if refreshToken == "" {
http.Error(w, "Internal Error", http.StatusInternalServerError)
WriteJSON(w, http.StatusInternalServerError, ErrorResponse{Error: "Internal Server Error"})
return
}
resp := AuthResponse{
WriteJSON(w, http.StatusOK, AuthResponse{
AccessToken: tokenString,
RefreshToken: refreshToken,
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(resp); err != nil {
log.Printf("json encoding failed: %v", err)
return
}
})
}
func (s *Server) issueRefreshToken(ctx context.Context, userID int64, issuedTime time.Time, checkLimit bool) string {