add: better logging in user controller and tests

This commit is contained in:
$(pass /github/name)
2024-09-05 16:38:23 +02:00
parent ae2ab42969
commit 4e5e0963c7
2 changed files with 47 additions and 15 deletions

View File

@@ -27,6 +27,23 @@ type RegistrationData struct {
User models.User `json:"user"` User models.User `json:"user"`
} }
func (uc *UserController) CurrentUserHandler(c *gin.Context) {
userID, err := middlewares.GetUserIDFromContext(c)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Failed to authenticate user"})
c.Abort()
return
}
user, err := uc.Service.GetUserByID(userID)
if err != nil {
logger.Error.Printf("Error retrieving valid user: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error retrieving user."})
return
}
c.JSON(http.StatusOK, user)
}
func (uc *UserController) LoginUser(c *gin.Context) { func (uc *UserController) LoginUser(c *gin.Context) {
var input struct { var input struct {
Email string `json:"email"` Email string `json:"email"`
@@ -66,9 +83,19 @@ func (uc *UserController) LoginUser(c *gin.Context) {
return return
} }
c.SetCookie(
"jwt",
token,
10*60, // 10 minutes
"/",
"",
true,
true,
)
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"message": "Login successful", "message": "Login successful",
"token": token, "set-token": token,
}) })
} }
@@ -82,14 +109,14 @@ func (uc *UserController) RegisterUser(c *gin.Context) {
return return
} }
if regData.User.Membership.SubscriptionModel.Name == "" { if regData.User.Membership.SubscriptionModel.Name == "" {
logger.Error.Printf("No subscription model provided") logger.Error.Printf("No subscription model provided: %v", regData.User.Email)
c.JSON(http.StatusNotAcceptable, gin.H{"error": "No subscription model provided"}) c.JSON(http.StatusNotAcceptable, gin.H{"error": "No subscription model provided"})
return return
} }
selectedModel, err := uc.MembershipService.GetModelByName(&regData.User.Membership.SubscriptionModel.Name) selectedModel, err := uc.MembershipService.GetModelByName(&regData.User.Membership.SubscriptionModel.Name)
if err != nil { if err != nil {
logger.Error.Printf("No subscription model found: %#v", err) logger.Error.Printf("%v:No subscription model found: %#v", regData.User.Email, err)
c.JSON(http.StatusNotFound, gin.H{"error": "Not a valid subscription model"}) c.JSON(http.StatusNotFound, gin.H{"error": "Not a valid subscription model"})
return return
} }
@@ -101,7 +128,7 @@ func (uc *UserController) RegisterUser(c *gin.Context) {
// Register User // Register User
id, token, err := uc.Service.RegisterUser(&regData.User) id, token, err := uc.Service.RegisterUser(&regData.User)
if err != nil { if err != nil {
logger.Error.Printf("Couldn't register User: %v", err) logger.Error.Printf("Couldn't register User(%v): %v", regData.User.Email, err)
c.JSON(int(id), gin.H{"error": fmt.Sprintf("Couldn't register User: %v", err)}) c.JSON(int(id), gin.H{"error": fmt.Sprintf("Couldn't register User: %v", err)})
return return
} }
@@ -125,7 +152,7 @@ func (uc *UserController) RegisterUser(c *gin.Context) {
for _, consent := range consents { for _, consent := range consents {
_, err = uc.ConsentService.RegisterConsent(&consent) _, err = uc.ConsentService.RegisterConsent(&consent)
if err != nil { if err != nil {
logger.Error.Printf("Couldn't register consent: %v", err) logger.Error.Printf("%v, Couldn't register consent: %v", regData.User.Email, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Couldn't register User-consent"}) c.JSON(http.StatusInternalServerError, gin.H{"error": "Couldn't register User-consent"})
return return
} }
@@ -133,13 +160,13 @@ func (uc *UserController) RegisterUser(c *gin.Context) {
// Send notifications // Send notifications
if err := uc.EmailService.SendVerificationEmail(&regData.User, &token); err != nil { if err := uc.EmailService.SendVerificationEmail(&regData.User, &token); err != nil {
logger.Error.Printf("Failed to send email verification email to user: %v", err) logger.Error.Printf("Failed to send email verification email to user(%v): %v", regData.User.Email, err)
// Proceed without returning error since user registration is successful // Proceed without returning error since user registration is successful
} }
// Notify admin of new user registration // Notify admin of new user registration
if err := uc.EmailService.SendRegistrationNotification(&regData.User); err != nil { if err := uc.EmailService.SendRegistrationNotification(&regData.User); err != nil {
logger.Error.Printf("Failed to notify admin of new user registration: %v", err) logger.Error.Printf("Failed to notify admin of new user(%v) registration: %v", regData.User.Email, err)
// Proceed without returning error since user registration is successful // Proceed without returning error since user registration is successful
} }
c.JSON(http.StatusCreated, gin.H{ c.JSON(http.StatusCreated, gin.H{

View File

@@ -3,6 +3,7 @@ package controllers
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
@@ -40,7 +41,8 @@ func (rt *RegisterUserTest) RunHandler(c *gin.Context, router *gin.Engine) {
func (rt *RegisterUserTest) ValidateResponse(w *httptest.ResponseRecorder) error { func (rt *RegisterUserTest) ValidateResponse(w *httptest.ResponseRecorder) error {
if w.Code != rt.WantResponse { if w.Code != rt.WantResponse {
return fmt.Errorf("Didn't get the expected response code: got: %v; expected: %v", w.Code, rt.WantResponse) responseBody, _ := io.ReadAll(w.Body)
return fmt.Errorf("Register User: Didn't get the expected response code: got: %v; expected: %v. Context: %#v", w.Code, rt.WantResponse, string(responseBody))
} }
return nil return nil
} }
@@ -55,7 +57,7 @@ func TestUserController(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.Name, func(t *testing.T) { t.Run(tt.Name, func(t *testing.T) {
if err := runSingleTest(&tt); err != nil { if err := runSingleTest(&tt); err != nil {
t.Errorf("Test failed: %v", err.Error()) t.Fatalf("Test failed: %v", err.Error())
} }
}) })
} }
@@ -118,10 +120,10 @@ func testLoginUser(t *testing.T) {
if tt.wantToken { if tt.wantToken {
logger.Info.Printf("Response: %#v", response) logger.Info.Printf("Response: %#v", response)
assert.Contains(t, response, "token") assert.Contains(t, response, "set-token")
assert.NotEmpty(t, response["token"]) assert.NotEmpty(t, response["set-token"])
} else { } else {
assert.NotContains(t, response, "token") assert.NotContains(t, response, "set-token")
} }
}) })
} }
@@ -291,7 +293,7 @@ func verifyMail(verificationURL string) error {
router := gin.New() router := gin.New()
router.LoadHTMLGlob(filepath.Join(config.Templates.HTMLPath, "*")) router.LoadHTMLGlob(filepath.Join(config.Templates.HTMLPath, "*"))
router.GET("/verify", Uc.VerifyMailHandler) router.GET("/users/verify", Uc.VerifyMailHandler)
wv := httptest.NewRecorder() wv := httptest.NewRecorder()
cv, _ := gin.CreateTestContext(wv) cv, _ := gin.CreateTestContext(wv)
var err error var err error
@@ -301,7 +303,10 @@ func verifyMail(verificationURL string) error {
} }
router.ServeHTTP(wv, cv.Request) router.ServeHTTP(wv, cv.Request)
if wv.Code != 200 { if wv.Code != 200 {
return fmt.Errorf("Didn't get the expected response code: got: %v; expected: %v", wv.Code, 200)
responseBody, _ := io.ReadAll(wv.Body)
return fmt.Errorf("VerifyMail: Didn't get the expected response code: got: %v; expected: %v Context: %#v", wv.Code, 200, string(responseBody))
} }
return nil return nil
} }