package handlers import ( "encoding/json" "errors" "strings" "Rezina-Backend/internal/domain" "Rezina-Backend/internal/services/authentication" jwtutil "Rezina-Backend/internal/web_server/jwt" "github.com/gofiber/fiber/v2" "github.com/google/uuid" ) type deviceLimitData struct { ChallengeToken string `json:"challenge_token"` ExpiresAt string `json:"expires_at"` Devices []deviceSummary `json:"devices"` } type deviceSummary struct { ID uuid.UUID `json:"id"` Label string `json:"label"` Platform string `json:"platform"` LastSeenAt string `json:"last_seen_at"` } type replaceSessionRequest struct { ChallengeToken string `json:"challenge_token" validate:"required"` SessionID string `json:"session_id" validate:"required"` } func deviceInfoFromRequest(c *fiber.Ctx) (domain.DeviceInfo, error) { key := strings.TrimSpace(c.Get("X-Device-Id")) if len(key) > 128 { return domain.DeviceInfo{}, errors.New("X-Device-Id must be at most 128 characters") } platform := strings.ToLower(strings.TrimSpace(c.Get("X-Device-Platform"))) ua := strings.ToLower(c.Get("User-Agent")) if platform == "" { switch { case strings.Contains(ua, "android"): platform = "android" case strings.Contains(ua, "iphone") || strings.Contains(ua, "ipad"): platform = "ios" default: platform = "web" } } if platform != "web" && platform != "android" && platform != "ios" { return domain.DeviceInfo{}, errors.New("X-Device-Platform must be web, android, or ios") } browser := "Browser" switch { case strings.Contains(ua, "edg/"), strings.Contains(ua, "edgios/"), strings.Contains(ua, "edga/"): browser = "Edge" case strings.Contains(ua, "chrome/"), strings.Contains(ua, "crios/"): browser = "Chrome" case strings.Contains(ua, "firefox/"), strings.Contains(ua, "fxios/"): browser = "Firefox" case strings.Contains(ua, "safari/"): browser = "Safari" } osName := "" switch { case strings.Contains(ua, "android"): osName = "Android" case strings.Contains(ua, "iphone"): osName = "iPhone" case strings.Contains(ua, "ipad"): osName = "iPad" case strings.Contains(ua, "windows"): osName = "Windows" case strings.Contains(ua, "macintosh"), strings.Contains(ua, "mac os x"): osName = "macOS" case strings.Contains(ua, "linux"): osName = "Linux" } label := browser if osName != "" { label += " on " + osName } return domain.DeviceInfo{Key: key, Label: label, Platform: platform}, nil } func (h *Handler) respondLearnerLogin(c *fiber.Ctx, login domain.LoginSuccess, message, activityDescription string) error { device, err := deviceInfoFromRequest(c) if err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid device information", Error: err.Error()}) } issued, err := h.authSvc.IssueLearnerSession(c.Context(), login.UserId, login.Role, device) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{Message: "Failed to login", Error: err.Error()}) } if issued.LimitReached { devices := make([]deviceSummary, 0, len(issued.Devices)) for _, item := range issued.Devices { devices = append(devices, deviceSummary{ID: item.ID, Label: item.Label, Platform: item.Platform, LastSeenAt: item.LastSeenAt.Format("2006-01-02T15:04:05.999999999Z07:00")}) } return c.Status(fiber.StatusConflict).JSON(fiber.Map{"message": "Device limit reached", "code": "DEVICE_LIMIT_REACHED", "data": deviceLimitData{ChallengeToken: issued.ChallengeToken, ExpiresAt: issued.ChallengeExpires.Format("2006-01-02T15:04:05.999999999Z07:00"), Devices: devices}}) } accessToken, err := jwtutil.CreateLearnerJwt(login.UserId, login.Role, issued.Session.ID.String(), h.jwtConfig.JwtAccessKey, h.jwtConfig.JwtAccessExpiry) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{Message: "Failed to login", Error: "Failed to generate access token"}) } if activityDescription != "" { userID := login.UserId h.recordActivityAs(c, userID, login.Role, domain.ActionAuthLogin, domain.ResourceAuth, &userID, activityDescription, nil) } return c.Status(fiber.StatusOK).JSON(domain.Response{Message: message, Data: loginUserRes{AccessToken: accessToken, RefreshToken: issued.RefreshToken, Role: string(login.Role), UserID: login.UserId}}) } // ReplaceSession godoc // @Summary Replace an active learner device session // @Tags auth // @Accept json // @Produce json // @Param body body replaceSessionRequest true "Session replacement challenge and active session ID" // @Success 200 {object} domain.Response{data=loginUserRes} // @Failure 401 {object} domain.ErrorResponse // @Router /api/v1/auth/sessions/replace [post] func (h *Handler) ReplaceSession(c *fiber.Ctx) error { var req replaceSessionRequest if err := c.BodyParser(&req); err != nil { return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{Message: "Invalid session replacement"}) } id, err := uuid.Parse(req.SessionID) if err != nil || req.ChallengeToken == "" { return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{Message: "Invalid session replacement"}) } login, err := h.authSvc.ReplaceLearnerSession(c.Context(), req.ChallengeToken, id) if err != nil { if errors.Is(err, authentication.ErrInvalidDeviceChallenge) || errors.Is(err, authentication.ErrSessionNotFound) { return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{Message: "Invalid session replacement"}) } return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{Message: "Failed to replace session"}) } accessToken, err := jwtutil.CreateLearnerJwt(login.UserId, login.Role, login.SessionID.String(), h.jwtConfig.JwtAccessKey, h.jwtConfig.JwtAccessExpiry) if err != nil { return fiber.NewError(fiber.StatusInternalServerError, "Failed to generate access token") } return c.Status(fiber.StatusOK).JSON(domain.Response{Message: "Login successful", Data: loginUserRes{AccessToken: accessToken, RefreshToken: login.RfToken, Role: string(login.Role), UserID: login.UserId}}) } // GetMySessions godoc // @Summary List the current learner's active device sessions // @Tags user // @Produce json // @Success 200 {object} domain.Response{data=[]domain.UserSession} // @Security Bearer // @Router /api/v1/user/me/sessions [get] func (h *Handler) GetMySessions(c *fiber.Ctx) error { userID := c.Locals("user_id").(int64) sessions, err := h.authSvc.SessionStore().ListUserSessions(c.Context(), userID) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "Failed to list sessions", "code": "SESSION_LIST_FAILED"}) } current, _ := c.Locals("session_id").(uuid.UUID) for i := range sessions { sessions[i].IsCurrent = sessions[i].ID == current } return c.JSON(domain.Response{Message: "Active sessions", Data: sessions}) } // DeleteMySession godoc // @Summary Remove one of the current learner's device sessions // @Tags user // @Param id path string true "Session UUID" // @Success 200 {object} domain.Response // @Failure 404 {object} domain.ErrorResponse // @Security Bearer // @Router /api/v1/user/me/sessions/{id} [delete] func (h *Handler) DeleteMySession(c *fiber.Ctx) error { userID := c.Locals("user_id").(int64) id, err := uuid.Parse(c.Params("id")) if err != nil { return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"message": "Session not found", "code": "SESSION_NOT_FOUND"}) } if err := h.authSvc.SessionStore().RevokeOwnUserSession(c.Context(), userID, id, "user_removed"); err != nil { if errors.Is(err, authentication.ErrSessionNotFound) { return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"message": "Session not found", "code": "SESSION_NOT_FOUND"}) } return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "Failed to remove session", "code": "SESSION_REMOVE_FAILED"}) } return c.JSON(domain.Response{Message: "Session removed"}) } // AdminGetUserSessions godoc // @Summary List a user's active device sessions // @Tags admin // @Param user_id path int true "User ID" // @Success 200 {object} domain.Response{data=[]domain.UserSession} // @Security Bearer // @Router /api/v1/admin/users/{user_id}/sessions [get] func (h *Handler) AdminGetUserSessions(c *fiber.Ctx) error { userID, err := c.ParamsInt("user_id") if err != nil || userID <= 0 { return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "Invalid user ID", "code": "INVALID_USER_ID"}) } sessions, err := h.authSvc.SessionStore().ListUserSessions(c.Context(), int64(userID)) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "Failed to list sessions", "code": "SESSION_LIST_FAILED"}) } uid := int64(userID) meta, _ := json.Marshal(map[string]any{"target_user_id": userID}) h.recordActivity(c, domain.ActionUserUpdated, domain.ResourceUser, &uid, "Viewed user sessions", meta) return c.JSON(domain.Response{Message: "Active sessions", Data: sessions}) } // AdminDeleteUserSession godoc // @Summary Remove a user's active device session // @Tags admin // @Param user_id path int true "User ID" // @Param id path string true "Session UUID" // @Success 200 {object} domain.Response // @Failure 404 {object} domain.ErrorResponse // @Security Bearer // @Router /api/v1/admin/users/{user_id}/sessions/{id} [delete] func (h *Handler) AdminDeleteUserSession(c *fiber.Ctx) error { targetID, err := c.ParamsInt("user_id") if err != nil || targetID <= 0 { return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "Invalid user ID", "code": "INVALID_USER_ID"}) } id, err := uuid.Parse(c.Params("id")) if err != nil { return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"message": "Session not found", "code": "SESSION_NOT_FOUND"}) } err = h.authSvc.SessionStore().RevokeUserSession(c.Context(), int64(targetID), id, "admin_removed") if err != nil { if errors.Is(err, authentication.ErrSessionNotFound) { return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"message": "Session not found", "code": "SESSION_NOT_FOUND"}) } return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "Failed to remove session", "code": "SESSION_REMOVE_FAILED"}) } meta, _ := json.Marshal(map[string]any{"session_id": id.String(), "target_user_id": targetID}) uid := int64(targetID) h.recordActivity(c, domain.ActionUserUpdated, domain.ResourceUser, &uid, "Removed user session", meta) return c.JSON(domain.Response{Message: "Session removed"}) }