Skip to content

The only tool you need to know what is happening and how to fix it.

feat: added organization & user management

ddux4e0c0b039be2
diff --git a/CLAUDE.md b/CLAUDE.md
index c06fd6f0..8c69ce05 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -11,6 +11,12 @@ Traceway is an error tracking and monitoring platform consisting of:
---
+## Code Style
+
+- **No pointless comments**: Do not add comments that simply describe what the code does. The code should be self-explanatory. Only add comments when explaining non-obvious "why" decisions.
+
+---
+
## Quick Start
### Development Commands
diff --git a/backend/app/controllers/auth.controller.go b/backend/app/controllers/auth.controller.go
index e6f3dc52..39b85d30 100644
--- a/backend/app/controllers/auth.controller.go
+++ b/backend/app/controllers/auth.controller.go
@@ -62,10 +62,17 @@ func (a authController) Login(c *gin.Context) {
return
}
+ organizations, err := repositories.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, err)
+ return
+ }
+
c.JSON(http.StatusOK, &models.LoginResponse{
- Token: token,
- User: user.ToResponse(),
- Projects: projects,
+ Token: token,
+ User: user.ToResponse(),
+ Projects: projects,
+ Organizations: organizations,
})
}
@@ -156,11 +163,18 @@ func (a authController) Register(c *gin.Context) {
OrganizationId: project.OrganizationId,
})
+ organizations, err := repositories.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, err)
+ return
+ }
+
c.JSON(http.StatusCreated, &models.RegisterResponse{
- Token: token,
- User: user.ToResponse(),
- Project: *project.ToProjectWithBackendUrl(),
- Projects: projects,
+ Token: token,
+ User: user.ToResponse(),
+ Project: *project.ToProjectWithBackendUrl(),
+ Projects: projects,
+ Organizations: organizations,
})
}
diff --git a/backend/app/controllers/invitation.controller.go b/backend/app/controllers/invitation.controller.go
new file mode 100644
index 00000000..c75749cf
--- /dev/null
+++ b/backend/app/controllers/invitation.controller.go
@@ -0,0 +1,371 @@
+package controllers
+
+import (
+ "backend/app/middleware"
+ "backend/app/models"
+ "backend/app/pgdb"
+ "backend/app/repositories"
+ "backend/app/services"
+ "database/sql"
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ traceway "go.tracewayapp.com"
+)
+
+type invitationController struct{}
+
+const maxMembersPerOrg = 10
+const invitationExpiryDays = 7
+
+func (c *invitationController) InviteUser(ctx *gin.Context) {
+ tx := middleware.GetTx(ctx)
+ organizationId := middleware.GetOrganizationId(ctx)
+ userId := middleware.GetUserId(ctx)
+
+ var request models.InviteUserRequest
+ if err := ctx.ShouldBindJSON(&request); err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ return
+ }
+
+ isMember, err := repositories.OrganizationRepository.IsUserMemberByEmail(tx, organizationId, request.Email)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to check membership: %w", err))
+ return
+ }
+ if isMember {
+ ctx.JSON(http.StatusConflict, gin.H{"error": "User is already a member of this organization"})
+ return
+ }
+
+ hasPending, err := repositories.InvitationRepository.HasPendingInvitation(tx, request.Email, organizationId)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to check pending invitations: %w", err))
+ return
+ }
+ if hasPending {
+ ctx.JSON(http.StatusConflict, gin.H{"error": "User already has a pending invitation"})
+ return
+ }
+
+ memberCount, err := repositories.OrganizationRepository.CountMembers(tx, organizationId)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to count members: %w", err))
+ return
+ }
+
+ invitations, err := repositories.InvitationRepository.FindByOrganization(tx, organizationId)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to count invitations: %w", err))
+ return
+ }
+
+ totalCount := memberCount + len(invitations)
+ if totalCount >= maxMembersPerOrg {
+ ctx.JSON(http.StatusConflict, gin.H{"error": "Organization has reached the maximum number of members"})
+ return
+ }
+
+ inviter, err := repositories.UserRepository.FindById(tx, userId)
+ if err != nil || inviter == nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to get inviter info: %w", err))
+ return
+ }
+
+ org, err := repositories.OrganizationRepository.FindById(tx, organizationId)
+ if err != nil || org == nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to get organization info: %w", err))
+ return
+ }
+
+ expiresAt := time.Now().AddDate(0, 0, invitationExpiryDays)
+ invitation, err := repositories.InvitationRepository.Create(tx, organizationId, request.Email, request.Role, userId, expiresAt)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to create invitation: %w", err))
+ return
+ }
+
+ go services.EmailService.SendInvitation(request.Email, inviter.Name, org.Name, invitation.Token)
+
+ ctx.JSON(http.StatusCreated, gin.H{"message": "Invitation sent"})
+}
+
+func (c *invitationController) ListInvitations(ctx *gin.Context) {
+ organizationId := middleware.GetOrganizationId(ctx)
+
+ invitations, err := pgdb.ExecuteTransaction(func(tx *sql.Tx) ([]*models.InvitationWithInviter, error) {
+ return repositories.InvitationRepository.FindByOrganization(tx, organizationId)
+ })
+
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to load invitations: %w", err))
+ return
+ }
+
+ ctx.JSON(http.StatusOK, invitations)
+}
+
+func (c *invitationController) RevokeInvitation(ctx *gin.Context) {
+ tx := middleware.GetTx(ctx)
+ organizationId := middleware.GetOrganizationId(ctx)
+
+ invitationId, err := strconv.Atoi(ctx.Param("id"))
+ if err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid invitation ID"})
+ return
+ }
+
+ invitation, err := repositories.InvitationRepository.FindById(tx, invitationId)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to find invitation: %w", err))
+ return
+ }
+ if invitation == nil {
+ ctx.JSON(http.StatusNotFound, gin.H{"error": "Invitation not found"})
+ return
+ }
+ if invitation.OrganizationId != organizationId {
+ ctx.JSON(http.StatusForbidden, gin.H{"error": "Access denied"})
+ return
+ }
+
+ err = repositories.InvitationRepository.Delete(tx, invitationId)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to revoke invitation: %w", err))
+ return
+ }
+
+ ctx.JSON(http.StatusOK, gin.H{"message": "Invitation revoked"})
+}
+
+func (c *invitationController) GetInvitationInfo(ctx *gin.Context) {
+ token := ctx.Param("token")
+
+ type invitationInfo struct {
+ Invitation *models.Invitation
+ Org *models.Organization
+ Inviter *models.User
+ UserExists bool
+ }
+
+ data, err := pgdb.ExecuteTransaction(func(tx *sql.Tx) (*invitationInfo, error) {
+ invitation, err := repositories.InvitationRepository.FindByToken(tx, token)
+ if err != nil {
+ return nil, err
+ }
+ if invitation == nil {
+ return nil, nil
+ }
+
+ org, err := repositories.OrganizationRepository.FindById(tx, invitation.OrganizationId)
+ if err != nil {
+ return nil, err
+ }
+
+ inviter, err := repositories.UserRepository.FindById(tx, invitation.InvitedBy)
+ if err != nil {
+ return nil, err
+ }
+
+ userExists, err := repositories.UserRepository.EmailExists(tx, invitation.Email)
+ if err != nil {
+ return nil, err
+ }
+
+ return &invitationInfo{
+ Invitation: invitation,
+ Org: org,
+ Inviter: inviter,
+ UserExists: userExists,
+ }, nil
+ })
+
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to load invitation: %w", err))
+ return
+ }
+
+ if data == nil || data.Invitation == nil {
+ ctx.JSON(http.StatusNotFound, gin.H{"error": "Invitation not found"})
+ return
+ }
+
+ if data.Invitation.Status != "pending" {
+ ctx.JSON(http.StatusGone, gin.H{"error": "Invitation has already been used or expired"})
+ return
+ }
+
+ if time.Now().After(data.Invitation.ExpiresAt) {
+ ctx.JSON(http.StatusGone, gin.H{"error": "Invitation has expired"})
+ return
+ }
+
+ ctx.JSON(http.StatusOK, &models.InvitationInfoResponse{
+ Email: data.Invitation.Email,
+ OrganizationName: data.Org.Name,
+ InviterName: data.Inviter.Name,
+ ExistsAsUser: data.UserExists,
+ Role: data.Invitation.Role,
+ })
+}
+
+func (c *invitationController) AcceptInvitation(ctx *gin.Context) {
+ tx := middleware.GetTx(ctx)
+ token := ctx.Param("token")
+
+ var request models.AcceptInvitationRequest
+ if err := ctx.ShouldBindJSON(&request); err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ return
+ }
+
+ invitation, err := repositories.InvitationRepository.FindByToken(tx, token)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to load invitation: %w", err))
+ return
+ }
+ if invitation == nil {
+ ctx.JSON(http.StatusNotFound, gin.H{"error": "Invitation not found"})
+ return
+ }
+
+ if invitation.Status != "pending" {
+ ctx.JSON(http.StatusGone, gin.H{"error": "Invitation has already been used or expired"})
+ return
+ }
+
+ if time.Now().After(invitation.ExpiresAt) {
+ ctx.JSON(http.StatusGone, gin.H{"error": "Invitation has expired"})
+ return
+ }
+
+ existingUser, err := repositories.UserRepository.FindByEmail(tx, invitation.Email)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to check user: %w", err))
+ return
+ }
+ if existingUser != nil {
+ ctx.JSON(http.StatusConflict, gin.H{"error": "User already exists. Please log in and accept the invitation."})
+ return
+ }
+
+ hashedPassword, err := services.HashPassword(request.Password)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to process password: %w", err))
+ return
+ }
+
+ user, err := repositories.UserRepository.Create(tx, invitation.Email, request.Name, hashedPassword)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to create user: %w", err))
+ return
+ }
+
+ _, err = repositories.OrganizationRepository.AddUser(tx, invitation.OrganizationId, user.Id, invitation.Role)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to add user to organization: %w", err))
+ return
+ }
+
+ now := time.Now()
+ invitation.AcceptedAt = &now
+ invitation.Status = "accepted"
+
+ err = repositories.InvitationRepository.Update(tx, invitation)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to update invitation: %w", err))
+ return
+ }
+
+ jwtToken, err := services.GenerateToken(user.Id, user.Email)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to generate token: %w", err))
+ return
+ }
+
+ projects, err := repositories.ProjectRepository.FindAllWithBackendUrlByUserId(tx, user.Id)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to load projects: %w", err))
+ return
+ }
+
+ ctx.JSON(http.StatusCreated, &models.LoginResponse{
+ Token: jwtToken,
+ User: user.ToResponse(),
+ Projects: projects,
+ })
+}
+
+func (c *invitationController) AcceptExistingUser(ctx *gin.Context) {
+ tx := middleware.GetTx(ctx)
+ token := ctx.Param("token")
+ userId := middleware.GetUserId(ctx)
+ userEmail := middleware.GetUserEmail(ctx)
+
+ invitation, err := repositories.InvitationRepository.FindByToken(tx, token)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to load invitation: %w", err))
+ return
+ }
+ if invitation == nil {
+ ctx.JSON(http.StatusNotFound, gin.H{"error": "Invitation not found"})
+ return
+ }
+
+ if invitation.Status != "pending" {
+ ctx.JSON(http.StatusGone, gin.H{"error": "Invitation has already been used or expired"})
+ return
+ }
+
+ if time.Now().After(invitation.ExpiresAt) {
+ ctx.JSON(http.StatusGone, gin.H{"error": "Invitation has expired"})
+ return
+ }
+
+ if userEmail != invitation.Email {
+ ctx.JSON(http.StatusForbidden, gin.H{"error": "This invitation was sent to a different email address. Please log in before trying to Accept the invitation."})
+ return
+ }
+
+ isMember, err := repositories.OrganizationRepository.IsUserMember(tx, invitation.OrganizationId, userId)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to check membership: %w", err))
+ return
+ }
+ if isMember {
+ ctx.JSON(http.StatusConflict, gin.H{"error": "You are already a member of this organization"})
+ return
+ }
+
+ _, err = repositories.OrganizationRepository.AddUser(tx, invitation.OrganizationId, userId, invitation.Role)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to add you to organization: %w", err))
+ return
+ }
+
+ now := time.Now()
+ invitation.AcceptedAt = &now
+ invitation.Status = "accepted"
+
+ err = repositories.InvitationRepository.Update(tx, invitation)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to update invitation: %w", err))
+ return
+ }
+
+ projects, err := repositories.ProjectRepository.FindAllWithBackendUrlByUserId(tx, userId)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to load projects: %w", err))
+ return
+ }
+
+ ctx.JSON(http.StatusOK, gin.H{
+ "message": "You have joined the organization",
+ "projects": projects,
+ })
+}
+
+var InvitationController = invitationController{}
diff --git a/backend/app/controllers/member.controller.go b/backend/app/controllers/member.controller.go
new file mode 100644
index 00000000..6279d4fb
--- /dev/null
+++ b/backend/app/controllers/member.controller.go
@@ -0,0 +1,108 @@
+package controllers
+
+import (
+ "backend/app/middleware"
+ "backend/app/models"
+ "backend/app/repositories"
+ "net/http"
+ "strconv"
+
+ "github.com/gin-gonic/gin"
+ traceway "go.tracewayapp.com"
+)
+
+type memberController struct{}
+
+func (c *memberController) UpdateRole(ctx *gin.Context) {
+ tx := middleware.GetTx(ctx)
+ organizationId := middleware.GetOrganizationId(ctx)
+ currentUserId := middleware.GetUserId(ctx)
+ currentUserRole := middleware.GetUserOrgRole(ctx)
+
+ targetUserId, err := strconv.Atoi(ctx.Param("userId"))
+ if err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user ID"})
+ return
+ }
+
+ var request models.UpdateMemberRoleRequest
+ if err := ctx.ShouldBindJSON(&request); err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ return
+ }
+
+ targetRole, err := repositories.OrganizationRepository.GetUserRole(tx, organizationId, targetUserId)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to get user role: %w", err))
+ return
+ }
+ if targetRole == "" {
+ ctx.JSON(http.StatusNotFound, gin.H{"error": "User is not a member of this organization"})
+ return
+ }
+
+ if targetRole == "owner" {
+ ctx.JSON(http.StatusForbidden, gin.H{"error": "Cannot change the owner's role"})
+ return
+ }
+
+ if request.Role == "admin" && currentUserRole != "owner" {
+ ctx.JSON(http.StatusForbidden, gin.H{"error": "Only owners can promote members to admin"})
+ return
+ }
+
+ if targetUserId == currentUserId {
+ ctx.JSON(http.StatusForbidden, gin.H{"error": "Cannot change your own role"})
+ return
+ }
+
+ err = repositories.OrganizationRepository.UpdateUserRole(tx, organizationId, targetUserId, request.Role)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to update role: %w", err))
+ return
+ }
+
+ ctx.JSON(http.StatusOK, gin.H{"message": "Role updated"})
+}
+
+func (c *memberController) RemoveMember(ctx *gin.Context) {
+ tx := middleware.GetTx(ctx)
+ organizationId := middleware.GetOrganizationId(ctx)
+ currentUserId := middleware.GetUserId(ctx)
+
+ targetUserId, err := strconv.Atoi(ctx.Param("userId"))
+ if err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user ID"})
+ return
+ }
+
+ if targetUserId == currentUserId {
+ ctx.JSON(http.StatusForbidden, gin.H{"error": "Cannot remove yourself from the organization"})
+ return
+ }
+
+ targetRole, err := repositories.OrganizationRepository.GetUserRole(tx, organizationId, targetUserId)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to get user role: %w", err))
+ return
+ }
+ if targetRole == "" {
+ ctx.JSON(http.StatusNotFound, gin.H{"error": "User is not a member of this organization"})
+ return
+ }
+
+ if targetRole == "owner" {
+ ctx.JSON(http.StatusForbidden, gin.H{"error": "Cannot remove the owner from the organization"})
+ return
+ }
+
+ err = repositories.OrganizationRepository.RemoveUser(tx, organizationId, targetUserId)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to remove member: %w", err))
+ return
+ }
+
+ ctx.JSON(http.StatusOK, gin.H{"message": "Member removed"})
+}
+
+var MemberController = memberController{}
diff --git a/backend/app/controllers/organization.controller.go b/backend/app/controllers/organization.controller.go
new file mode 100644
index 00000000..7a046291
--- /dev/null
+++ b/backend/app/controllers/organization.controller.go
@@ -0,0 +1,113 @@
+package controllers
+
+import (
+ "backend/app/middleware"
+ "backend/app/models"
+ "backend/app/pgdb"
+ "backend/app/repositories"
+ "database/sql"
+ "net/http"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ traceway "go.tracewayapp.com"
+)
+
+type organizationController struct{}
+
+func (c *organizationController) GetSettings(ctx *gin.Context) {
+ organizationId := middleware.GetOrganizationId(ctx)
+ userRole := middleware.GetUserOrgRole(ctx)
+
+ type settingsData struct {
+ Organization *models.Organization
+ Members []*models.OrganizationMember
+ Invitations []*models.InvitationWithInviter
+ }
+
+ data, err := pgdb.ExecuteTransaction(func(tx *sql.Tx) (*settingsData, error) {
+ org, err := repositories.OrganizationRepository.FindById(tx, organizationId)
+ if err != nil {
+ return nil, err
+ }
+
+ members, err := repositories.OrganizationRepository.GetMembersWithDetails(tx, organizationId)
+ if err != nil {
+ return nil, err
+ }
+
+ invitations, err := repositories.InvitationRepository.FindByOrganization(tx, organizationId)
+ if err != nil {
+ return nil, err
+ }
+
+ return &settingsData{
+ Organization: org,
+ Members: members,
+ Invitations: invitations,
+ }, nil
+ })
+
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to load settings: %w", err))
+ return
+ }
+
+ if data.Organization == nil {
+ ctx.JSON(http.StatusNotFound, gin.H{"error": "Organization not found"})
+ return
+ }
+
+ ctx.JSON(http.StatusOK, &models.OrganizationSettingsResponse{
+ Organization: data.Organization,
+ Members: data.Members,
+ Invitations: data.Invitations,
+ UserRole: userRole,
+ })
+}
+
+func (c *organizationController) GetMembers(ctx *gin.Context) {
+ organizationId := middleware.GetOrganizationId(ctx)
+
+ members, err := pgdb.ExecuteTransaction(func(tx *sql.Tx) ([]*models.OrganizationMember, error) {
+ return repositories.OrganizationRepository.GetMembersWithDetails(tx, organizationId)
+ })
+
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to load members: %w", err))
+ return
+ }
+
+ ctx.JSON(http.StatusOK, members)
+}
+
+type UpdateSettingsRequest struct {
+ Timezone string `json:"timezone" binding:"required"`
+}
+
+func (c *organizationController) UpdateSettings(ctx *gin.Context) {
+ organizationId := middleware.GetOrganizationId(ctx)
+ tx := middleware.GetTx(ctx)
+
+ var req UpdateSettingsRequest
+ if err := ctx.ShouldBindJSON(&req); err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
+ return
+ }
+
+ _, err := time.LoadLocation(req.Timezone)
+ if err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid timezone"})
+ return
+ }
+
+ err = repositories.OrganizationRepository.UpdateTimezone(tx, organizationId, req.Timezone)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to update settings: %w", err))
+ return
+ }
+
+ ctx.JSON(http.StatusOK, gin.H{"timezone": req.Timezone})
+}
+
+var OrganizationController = organizationController{}
diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.go
index edb6c8e5..0d13f286 100644
--- a/backend/app/controllers/routes.go
+++ b/backend/app/controllers/routes.go
@@ -69,4 +69,23 @@ func RegisterControllers(router *gin.RouterGroup) {
if os.Getenv("CLOUD_MODE") != "true" {
router.GET("/has-organizations", middleware.Transactional, AuthController.HasOrganizations)
}
+
+ // Organization settings (admin/owner access)
+ router.GET("/organizations/:organizationId/settings", middleware.UseAppAuth, middleware.RequireAdminAccess, OrganizationController.GetSettings)
+ router.PUT("/organizations/:organizationId/settings", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, OrganizationController.UpdateSettings)
+ router.GET("/organizations/:organizationId/members", middleware.UseAppAuth, middleware.RequireAdminAccess, OrganizationController.GetMembers)
+
+ // Member management (admin/owner) - TRANSACTIONAL
+ router.PUT("/organizations/:organizationId/members/:userId", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, MemberController.UpdateRole)
+ router.DELETE("/organizations/:organizationId/members/:userId", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, MemberController.RemoveMember)
+
+ // Invitations management (admin/owner) - TRANSACTIONAL
+ router.POST("/organizations/:organizationId/invitations", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, InvitationController.InviteUser)
+ router.GET("/organizations/:organizationId/invitations", middleware.UseAppAuth, middleware.RequireAdminAccess, InvitationController.ListInvitations)
+ router.DELETE("/organizations/:organizationId/invitations/:id", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, InvitationController.RevokeInvitation)
+
+ // Public invitation endpoints - TRANSACTIONAL
+ router.GET("/invitations/:token", InvitationController.GetInvitationInfo)
+ router.POST("/invitations/:token/accept", middleware.Transactional, InvitationController.AcceptInvitation)
+ router.POST("/invitations/:token/accept-existing", middleware.UseAppAuth, middleware.Transactional, InvitationController.AcceptExistingUser)
}
diff --git a/backend/app/middleware/require_admin_access.middleware.go b/backend/app/middleware/require_admin_access.middleware.go
new file mode 100644
index 00000000..5fdb7fa8
--- /dev/null
+++ b/backend/app/middleware/require_admin_access.middleware.go
@@ -0,0 +1,66 @@
+package middleware
+
+import (
+ "backend/app/pgdb"
+ "backend/app/repositories"
+ "database/sql"
+ "net/http"
+ "strconv"
+
+ "github.com/gin-gonic/gin"
+ traceway "go.tracewayapp.com"
+)
+
+const OrganizationIdContextKey = "organizationId"
+const UserOrgRoleContextKey = "userOrgRole"
+
+var RequireAdminAccess gin.HandlerFunc
+
+func InitRequireAdminAccess() {
+ RequireAdminAccess = func(c *gin.Context) {
+ userId := GetUserId(c)
+ if userId == 0 {
+ c.AbortWithStatus(http.StatusUnauthorized)
+ return
+ }
+
+ organizationIdStr := c.Param("organizationId")
+ organizationId, err := strconv.Atoi(organizationIdStr)
+ if err != nil {
+ c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid organization ID"})
+ return
+ }
+
+ role, err := pgdb.ExecuteTransaction(func(tx *sql.Tx) (string, error) {
+ return repositories.OrganizationRepository.GetUserRole(tx, organizationId, userId)
+ })
+
+ if err != nil {
+ c.AbortWithStatusJSON(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to check permissions: %w", err))
+ return
+ }
+
+ if role != "owner" && role != "admin" {
+ c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "Admin or owner access required"})
+ return
+ }
+
+ c.Set(OrganizationIdContextKey, organizationId)
+ c.Set(UserOrgRoleContextKey, role)
+ c.Next()
+ }
+}
+
+func GetOrganizationId(c *gin.Context) int {
+ if id, exists := c.Get(OrganizationIdContextKey); exists {
+ return id.(int)
+ }
+ return 0
+}
+
+func GetUserOrgRole(c *gin.Context) string {
+ if role, exists := c.Get(UserOrgRoleContextKey); exists {
+ return role.(string)
+ }
+ return ""
+}
diff --git a/backend/app/middleware/require_write_access.middleware.go b/backend/app/middleware/require_write_access.middleware.go
index e6ce2fb8..084f3296 100644
--- a/backend/app/middleware/require_write_access.middleware.go
+++ b/backend/app/middleware/require_write_access.middleware.go
@@ -9,6 +9,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
+ traceway "go.tracewayapp.com"
)
// RequireWriteAccess middleware checks if the user has write access to the project's organization.
@@ -37,7 +38,7 @@ func InitRequireWriteAccess() {
}
if project.OrganizationId == nil {
- c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Project has no organization"})
+ c.AbortWithStatusJSON(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Project has no organization: %d %s", project.Id, project.Name))
return
}
diff --git a/backend/app/migrations/pg/0009_create_invitations_table.up.sql b/backend/app/migrations/pg/0009_create_invitations_table.up.sql
new file mode 100644
index 00000000..92386763
--- /dev/null
+++ b/backend/app/migrations/pg/0009_create_invitations_table.up.sql
@@ -0,0 +1,12 @@
+CREATE TABLE invitations (
+ id SERIAL PRIMARY KEY,
+ organization_id INT NOT NULL REFERENCES organizations(id),
+ email TEXT NOT NULL,
+ role TEXT NOT NULL CHECK (role IN ('admin','user','readonly')),
+ token TEXT NOT NULL UNIQUE,
+ invited_by INT NOT NULL REFERENCES users(id),
+ status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','accepted','expired')),
+ expires_at TIMESTAMPTZ NOT NULL,
+ accepted_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ DEFAULT NOW()
+)
diff --git a/backend/app/migrations/pg/0010_create_invitations_indexes.up.sql b/backend/app/migrations/pg/0010_create_invitations_indexes.up.sql
new file mode 100644
index 00000000..8e9183f3
--- /dev/null
+++ b/backend/app/migrations/pg/0010_create_invitations_indexes.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX idx_invitations_email_org_pending ON invitations(email, organization_id) WHERE status = 'pending'
diff --git a/backend/app/migrations/pg/0011_add_timezone_to_organizations.up.sql b/backend/app/migrations/pg/0011_add_timezone_to_organizations.up.sql
new file mode 100644
index 00000000..afcbb6b4
--- /dev/null
+++ b/backend/app/migrations/pg/0011_add_timezone_to_organizations.up.sql
@@ -0,0 +1 @@
+ALTER TABLE organizations ADD COLUMN timezone VARCHAR(64) NOT NULL DEFAULT 'UTC'
diff --git a/backend/app/models/auth.model.go b/backend/app/models/auth.model.go
index 0d8178df..c88a17df 100644
--- a/backend/app/models/auth.model.go
+++ b/backend/app/models/auth.model.go
@@ -5,10 +5,18 @@ type LoginRequest struct {
Password string `json:"password" binding:"required"`
}
+type UserOrganizationResponse struct {
+ Id int `json:"id"`
+ Name string `json:"name"`
+ Role string `json:"role"`
+ Timezone string `json:"timezone"`
+}
+
type LoginResponse struct {
- Token string `json:"token"`
- User UserResponse `json:"user"`
- Projects []*ProjectWithBackendUrl `json:"projects"`
+ Token string `json:"token"`
+ User UserResponse `json:"user"`
+ Projects []*ProjectWithBackendUrl `json:"projects"`
+ Organizations []*UserOrganizationResponse `json:"organizations"`
}
type RegisterRequest struct {
@@ -21,8 +29,9 @@ type RegisterRequest struct {
}
type RegisterResponse struct {
- Token string `json:"token"`
- User UserResponse `json:"user"`
- Project ProjectWithBackendUrl `json:"project"`
- Projects []*ProjectWithBackendUrl `json:"projects"`
+ Token string `json:"token"`
+ User UserResponse `json:"user"`
+ Project ProjectWithBackendUrl `json:"project"`
+ Projects []*ProjectWithBackendUrl `json:"projects"`
+ Organizations []*UserOrganizationResponse `json:"organizations"`
}
diff --git a/backend/app/models/count_result.model.go b/backend/app/models/count_result.model.go
new file mode 100644
index 00000000..60250697
--- /dev/null
+++ b/backend/app/models/count_result.model.go
@@ -0,0 +1,5 @@
+package models
+
+type CountResult struct {
+ Count int `lit:"count"`
+}
diff --git a/backend/app/models/invitation.model.go b/backend/app/models/invitation.model.go
new file mode 100644
index 00000000..e3e1186b
--- /dev/null
+++ b/backend/app/models/invitation.model.go
@@ -0,0 +1,49 @@
+package models
+
+import (
+ "time"
+)
+
+type Invitation struct {
+ Id int `json:"id"`
+ OrganizationId int `json:"organizationId"`
+ Email string `json:"email"`
+ Role string `json:"role"`
+ Token string `json:"-"`
+ InvitedBy int `json:"invitedBy"`
+ Status string `json:"status"`
+ ExpiresAt time.Time `json:"expiresAt"`
+ AcceptedAt *time.Time `json:"acceptedAt,omitempty"`
+ CreatedAt time.Time `json:"createdAt"`
+}
+
+type InvitationWithInviter struct {
+ Id int `json:"id"`
+ OrganizationId int `json:"organizationId"`
+ Email string `json:"email"`
+ Role string `json:"role"`
+ InvitedBy int `json:"invitedBy"`
+ InviterName string `json:"inviterName" lit:"inviter_name"`
+ Status string `json:"status"`
+ ExpiresAt time.Time `json:"expiresAt"`
+ AcceptedAt *time.Time `json:"acceptedAt,omitempty"`
+ CreatedAt time.Time `json:"createdAt"`
+}
+
+type InviteUserRequest struct {
+ Email string `json:"email" binding:"required,email"`
+ Role string `json:"role" binding:"required,oneof=admin user readonly"`
+}
+
+type AcceptInvitationRequest struct {
+ Name string `json:"name" binding:"required,min=1"`
+ Password string `json:"password" binding:"required,min=8"`
+}
+
+type InvitationInfoResponse struct {
+ Email string `json:"email"`
+ OrganizationName string `json:"organizationName"`
+ InviterName string `json:"inviterName"`
+ ExistsAsUser bool `json:"existsAsUser"`
+ Role string `json:"role"`
+}
diff --git a/backend/app/models/models.go b/backend/app/models/models.go
index 8cdaf957..611ba79b 100644
--- a/backend/app/models/models.go
+++ b/backend/app/models/models.go
@@ -9,4 +9,9 @@ func Init() {
lit.RegisterModel[User](lit.PostgreSQL)
lit.RegisterModel[Organization](lit.PostgreSQL)
lit.RegisterModel[OrganizationUser](lit.PostgreSQL)
+ lit.RegisterModel[OrganizationMember](lit.PostgreSQL)
+ lit.RegisterModel[Invitation](lit.PostgreSQL)
+ lit.RegisterModel[InvitationWithInviter](lit.PostgreSQL)
+ lit.RegisterModel[UserOrganizationResponse](lit.PostgreSQL)
+ lit.RegisterModel[CountResult](lit.PostgreSQL)
}
diff --git a/backend/app/models/organization.model.go b/backend/app/models/organization.model.go
index 86c9a102..93874ac9 100644
--- a/backend/app/models/organization.model.go
+++ b/backend/app/models/organization.model.go
@@ -7,6 +7,7 @@ import (
type Organization struct {
Id int `json:"id"`
Name string `json:"name"`
+ Timezone string `json:"timezone"`
CreatedAt time.Time `json:"createdAt"`
}
@@ -14,6 +15,28 @@ type OrganizationUser struct {
Id int `json:"id"`
UserId int `json:"userId"`
OrganizationId int `json:"organizationId"`
- Role string `json:"role"` // owner, admin, user
+ Role string `json:"role"` // owner, admin, user, readonly
CreatedAt time.Time `json:"createdAt"`
}
+
+// OrganizationMember represents a user with their role in an organization
+type OrganizationMember struct {
+ Id int `json:"id"`
+ Email string `json:"email"`
+ Name string `json:"name"`
+ Role string `json:"role"`
+ CreatedAt time.Time `json:"createdAt"`
+}
+
+// OrganizationSettingsResponse is returned for the settings page
+type OrganizationSettingsResponse struct {
+ Organization *Organization `json:"organization"`
+ Members []*OrganizationMember `json:"members"`
+ Invitations []*InvitationWithInviter `json:"invitations"`
+ UserRole string `json:"userRole"`
+}
+
+// UpdateMemberRoleRequest is the request body for updating a member's role
+type UpdateMemberRoleRequest struct {
+ Role string `json:"role" binding:"required,oneof=admin user readonly"`
+}
diff --git a/backend/app/repositories/invitation.repository.go b/backend/app/repositories/invitation.repository.go
new file mode 100644
index 00000000..0f597e96
--- /dev/null
+++ b/backend/app/repositories/invitation.repository.go
@@ -0,0 +1,96 @@
+package repositories
+
+import (
+ "backend/app/models"
+ "database/sql"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/tracewayapp/go-lightning/lit"
+)
+
+type invitationRepository struct{}
+
+func (r *invitationRepository) Create(tx *sql.Tx, organizationId int, email string, role string, invitedBy int, expiresAt time.Time) (*models.Invitation, error) {
+ token := uuid.New().String()
+
+ invitation := &models.Invitation{
+ OrganizationId: organizationId,
+ Email: email,
+ Role: role,
+ Token: token,
+ InvitedBy: invitedBy,
+ Status: "pending",
+ ExpiresAt: expiresAt,
+ }
+
+ id, err := lit.Insert(tx, invitation)
+ if err != nil {
+ return nil, err
+ }
+ invitation.Id = id
+
+ return invitation, nil
+}
+
+func (r *invitationRepository) FindByToken(tx *sql.Tx, token string) (*models.Invitation, error) {
+ return lit.SelectSingle[models.Invitation](
+ tx,
+ `SELECT id, organization_id, email, role, token, invited_by, status, expires_at, accepted_at, created_at
+ FROM invitations
+ WHERE token = $1`,
+ token,
+ )
+}
+
+func (r *invitationRepository) FindByOrganization(tx *sql.Tx, organizationId int) ([]*models.InvitationWithInviter, error) {
+ return lit.Select[models.InvitationWithInviter](
+ tx,
+ `SELECT i.id, i.organization_id, i.email, i.role, i.invited_by, u.name as inviter_name, i.status, i.expires_at, i.accepted_at, i.created_at
+ FROM invitations i
+ JOIN users u ON i.invited_by = u.id
+ WHERE i.organization_id = $1 AND i.status = 'pending'
+ ORDER BY i.created_at DESC`,
+ organizationId,
+ )
+}
+
+func (r *invitationRepository) Update(tx *sql.Tx, invitation *models.Invitation) error {
+ return lit.Update[models.Invitation](
+ tx,
+ invitation,
+ "id = $1",
+ invitation.Id,
+ )
+}
+
+func (r *invitationRepository) Delete(tx *sql.Tx, id int) error {
+ return lit.Delete(tx, "DELETE FROM invitations WHERE id = $1", id)
+}
+
+func (r *invitationRepository) HasPendingInvitation(tx *sql.Tx, email string, organizationId int) (bool, error) {
+ invitation, err := lit.SelectSingle[models.Invitation](
+ tx,
+ `SELECT id, organization_id, email, role, token, invited_by, status, expires_at, accepted_at, created_at
+ FROM invitations
+ WHERE email = $1 AND organization_id = $2 AND status = 'pending'`,
+ email,
+ organizationId,
+ )
+ if err != nil {
+ return false, err
+ }
+ return invitation != nil, nil
+}
+
+func (r *invitationRepository) FindById(tx *sql.Tx, id int) (*models.Invitation, error) {
+ return lit.SelectSingle[models.Invitation](
+ tx,
+ `SELECT id, organization_id, email, role, token, invited_by, status, expires_at, accepted_at, created_at
+ FROM invitations
+ WHERE id = $1`,
+ id,
+ )
+}
+
+var InvitationRepository = invitationRepository{}
diff --git a/backend/app/repositories/organization.repository.go b/backend/app/repositories/organization.repository.go
index 9e5bd417..0071cbfd 100644
--- a/backend/app/repositories/organization.repository.go
+++ b/backend/app/repositories/organization.repository.go
@@ -24,7 +24,7 @@ func (r *organizationRepository) Create(tx *sql.Tx, name string) (*models.Organi
}
func (r *organizationRepository) HasOrganizations(tx *sql.Tx) (bool, error) {
- result, err := lit.SelectSingle[CountResult](
+ result, err := lit.SelectSingle[models.CountResult](
tx,
`SELECT COUNT(*) as count
FROM organizations`,
@@ -42,7 +42,7 @@ func (r *organizationRepository) HasOrganizations(tx *sql.Tx) (bool, error) {
func (r *organizationRepository) FindById(tx *sql.Tx, id int) (*models.Organization, error) {
return lit.SelectSingle[models.Organization](
tx,
- "SELECT id, name, created_at FROM organizations WHERE id = $1",
+ "SELECT id, name, timezone, created_at FROM organizations WHERE id = $1",
id,
)
}
@@ -91,4 +91,101 @@ func (r *organizationRepository) GetUserRole(tx *sql.Tx, organizationId int, use
return orgUser.Role, nil
}
+func (r *organizationRepository) CountMembers(tx *sql.Tx, organizationId int) (int, error) {
+ result, err := lit.SelectSingle[models.CountResult](
+ tx,
+ `SELECT COUNT(*) as count FROM organization_users WHERE organization_id = $1`,
+ organizationId,
+ )
+ if err != nil {
+ return 0, err
+ }
+ if result == nil {
+ return 0, nil
+ }
+ return result.Count, nil
+}
+
+func (r *organizationRepository) GetMembersWithDetails(tx *sql.Tx, organizationId int) ([]*models.OrganizationMember, error) {
+ return lit.Select[models.OrganizationMember](
+ tx,
+ `SELECT u.id, u.email, u.name, ou.role, ou.created_at
+ FROM users u
+ JOIN organization_users ou ON u.id = ou.user_id
+ WHERE ou.organization_id = $1
+ ORDER BY ou.created_at ASC`,
+ organizationId,
+ )
+}
+
+func (r *organizationRepository) IsOwner(tx *sql.Tx, organizationId int, userId int) (bool, error) {
+ role, err := r.GetUserRole(tx, organizationId, userId)
+ if err != nil {
+ return false, err
+ }
+ return role == "owner", nil
+}
+
+func (r *organizationRepository) UpdateUserRole(tx *sql.Tx, organizationId int, userId int, role string) error {
+ return lit.UpdateNative(
+ tx,
+ "UPDATE organization_users SET role = $1 WHERE organization_id = $2 AND user_id = $3",
+ role,
+ organizationId,
+ userId,
+ )
+}
+
+func (r *organizationRepository) RemoveUser(tx *sql.Tx, organizationId int, userId int) error {
+ return lit.Delete(tx, "DELETE FROM organization_users WHERE organization_id = $1 AND user_id = $2", organizationId, userId)
+}
+
+func (r *organizationRepository) IsUserMember(tx *sql.Tx, organizationId int, userId int) (bool, error) {
+ role, err := r.GetUserRole(tx, organizationId, userId)
+ if err != nil {
+ return false, err
+ }
+ return role != "", nil
+}
+
+func (r *organizationRepository) IsUserMemberByEmail(tx *sql.Tx, organizationId int, email string) (bool, error) {
+ result, err := lit.SelectSingle[models.CountResult](
+ tx,
+ `SELECT COUNT(*) as count
+ FROM organization_users ou
+ JOIN users u ON u.id = ou.user_id
+ WHERE ou.organization_id = $1 AND u.email = $2`,
+ organizationId,
+ email,
+ )
+ if err != nil {
+ return false, err
+ }
+ if result == nil {
+ return false, nil
+ }
+ return result.Count > 0, nil
+}
+
+func (r *organizationRepository) FindByUserIdWithRoles(tx *sql.Tx, userId int) ([]*models.UserOrganizationResponse, error) {
+ return lit.Select[models.UserOrganizationResponse](
+ tx,
+ `SELECT o.id, o.name, ou.role, o.timezone
+ FROM organizations o
+ INNER JOIN organization_users ou ON o.id = ou.organization_id
+ WHERE ou.user_id = $1
+ ORDER BY o.created_at ASC`,
+ userId,
+ )
+}
+
+func (r *organizationRepository) UpdateTimezone(tx *sql.Tx, organizationId int, timezone string) error {
+ return lit.UpdateNative(
+ tx,
+ "UPDATE organizations SET timezone = $1 WHERE id = $2",
+ timezone,
+ organizationId,
+ )
+}
+
var OrganizationRepository = organizationRepository{}
diff --git a/backend/app/repositories/project.repository.go b/backend/app/repositories/project.repository.go
index a83cd42f..b0531167 100644
--- a/backend/app/repositories/project.repository.go
+++ b/backend/app/repositories/project.repository.go
@@ -103,17 +103,8 @@ func (p *projectRepository) FindByUserId(tx *sql.Tx, userId int) ([]*models.Proj
userId,
)
}
-
-type CountResult struct {
- Count int `lit:"count"`
-}
-
-func init() {
- lit.RegisterModel[CountResult](lit.PostgreSQL)
-}
-
func (p *projectRepository) UserHasAccess(tx *sql.Tx, projectId uuid.UUID, userId int) (bool, error) {
- result, err := lit.SelectSingle[CountResult](
+ result, err := lit.SelectSingle[models.CountResult](
tx,
`SELECT COUNT(*) as count
FROM projects p
diff --git a/backend/app/services/email.service.go b/backend/app/services/email.service.go
new file mode 100644
index 00000000..db7f05f3
--- /dev/null
+++ b/backend/app/services/email.service.go
@@ -0,0 +1,94 @@
+package services
+
+import (
+ "fmt"
+ "log"
+ "net/smtp"
+ "os"
+ "strconv"
+)
+
+type emailService struct {
+ enabled bool
+ host string
+ port int
+ username string
+ password string
+ from string
+ baseUrl string
+}
+
+var EmailService *emailService
+
+func InitEmail() {
+ enabled := os.Getenv("SMTP_ENABLED") == "true"
+ port, _ := strconv.Atoi(os.Getenv("SMTP_PORT"))
+ if port == 0 {
+ port = 587
+ }
+
+ baseUrl := os.Getenv("APP_BASE_URL")
+ if baseUrl == "" {
+ baseUrl = "http://localhost:5173"
+ }
+
+ EmailService = &emailService{
+ enabled: enabled,
+ host: os.Getenv("SMTP_HOST"),
+ port: port,
+ username: os.Getenv("SMTP_USERNAME"),
+ password: os.Getenv("SMTP_PASSWORD"),
+ from: os.Getenv("SMTP_FROM"),
+ baseUrl: baseUrl,
+ }
+
+ if enabled {
+ log.Println("Email service initialized with SMTP")
+ } else {
+ log.Println("Email service initialized in log-only mode (SMTP disabled)")
+ }
+}
+
+func (e *emailService) SendInvitation(toEmail string, inviterName string, orgName string, token string) error {
+ inviteUrl := fmt.Sprintf("%s/accept-invitation?token=%s", e.baseUrl, token)
+
+ subject := fmt.Sprintf("You've been invited to join %s on Traceway", orgName)
+ body := fmt.Sprintf(`Hello,
+
+%s has invited you to join %s on Traceway.
+
+Click the link below to accept the invitation:
+%s
+
+This invitation will expire in 7 days.
+
+If you did not expect this invitation, you can safely ignore this email.
+
+Best regards,
+The Traceway Team
+`, inviterName, orgName, inviteUrl)
+
+ if !e.enabled {
+ log.Printf("[EMAIL LOG] To: %s\nSubject: %s\nBody:\n%s", toEmail, subject, body)
+ return nil
+ }
+
+ msg := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s",
+ e.from, toEmail, subject, body)
+
+ auth := smtp.PlainAuth("", e.username, e.password, e.host)
+ addr := fmt.Sprintf("%s:%d", e.host, e.port)
+
+ err := smtp.SendMail(addr, auth, e.from, []string{toEmail}, []byte(msg))
+ if err != nil {
+ log.Printf("Failed to send invitation email to %s: %v", toEmail, err)
+ return err
+ }
+
+ log.Printf("Invitation email sent to %s for organization %s", toEmail, orgName)
+ return nil
+}
+
+func (e *emailService) IsEnabled() bool {
+ return e.enabled
+}
diff --git a/backend/main.go b/backend/main.go
index 1ed9da4f..19d94824 100644
--- a/backend/main.go
+++ b/backend/main.go
@@ -69,6 +69,10 @@ func main() {
middleware.InitUseAppAuth()
middleware.InitRequireWriteAccess()
middleware.InitRequireProjectAccess()
+ middleware.InitRequireAdminAccess()
+
+ // Initialize email service
+ services.InitEmail()
router := gin.Default()
diff --git a/frontend/src/lib/components/app-sidebar.svelte b/frontend/src/lib/components/app-sidebar.svelte
index 80399e25..ac00e872 100644
--- a/frontend/src/lib/components/app-sidebar.svelte
+++ b/frontend/src/lib/components/app-sidebar.svelte
@@ -1,34 +1,53 @@
<script lang="ts">
import * as Sidebar from "$lib/components/ui/sidebar";
import { useSidebar } from '$lib/components/ui/sidebar';
- import { Bug, Link2, ChartNoAxesCombined, ChartNoAxesGantt, Gauge, ListEnd } from "@lucide/svelte";
+ import { Bug, Link2, ChartNoAxesCombined, ChartNoAxesGantt, Gauge, ListEnd, Settings, BookOpen } from "@lucide/svelte";
import { themeState } from '$lib/state/theme.svelte';
+ import { projectsState } from '$lib/state/projects.svelte';
import { LayoutDashboard } from "@lucide/svelte";
import { page } from '$app/state';
import { createRowClickHandler } from "$lib/utils/navigation";
- const sidebarItems = [
- {Icon: LayoutDashboard, href: "/", title: "Dashboard", stickyParams: [] as string[]},
- {Icon: Bug, href: "/issues", title: "Issues", stickyParams: [] as string[]},
+ interface SidebarItem {
+ Icon: typeof LayoutDashboard;
+ href: string;
+ title: string;
+ stickyParams: string[];
+ adminOnly?: boolean;
+ external?: boolean;
+ }
+
+ const sidebarItems: SidebarItem[] = [
+ {Icon: LayoutDashboard, href: "/", title: "Dashboard", stickyParams: []},
+ {Icon: Bug, href: "/issues", title: "Issues", stickyParams: []},
{Icon: Gauge, href: "/endpoints", title: "Endpoints", stickyParams: ['presets', 'from', 'to']},
- {Icon: ListEnd, href: "/tasks", title: "Tasks", stickyParams: ['presets', 'from', 'to']}, // ChartNoAxesGantt
+ {Icon: ListEnd, href: "/tasks", title: "Tasks", stickyParams: ['presets', 'from', 'to']},
{Icon: ChartNoAxesCombined, href: "/metrics", title: "Metrics", stickyParams: ['presets', 'from', 'to']},
- {Icon: Link2, href: "/connection", title: "Connection", stickyParams: [] as string[]},
+ {Icon: Link2, href: "/connection", title: "Connection", stickyParams: []},
+ ]
+
+ const allSidebarItemsBottom: SidebarItem[] = [
+ {Icon: BookOpen, href: "https://docs.tracewayapp.com", title: "Docs", stickyParams: [], external: true},
+ {Icon: Settings, href: "/settings", title: "Settings", stickyParams: [], adminOnly: true},
]
+ const sidebarItemsBottom = $derived(
+ allSidebarItemsBottom.filter(item => !item.adminOnly || projectsState.canManageCurrentProject)
+ );
+
const sidebar = useSidebar();
</script>
<Sidebar.Sidebar>
<Sidebar.SidebarHeader class="p-4 flex items-start">
{#if themeState.isDark}
- <img src="/traceway-logo-white.svg" alt="Traceway Logo" class="h-10 w-auto" />
+ <img src="/traceway-logo-white.svg" alt="Traceway Logo" class="h-9 w-auto" />
{:else}
- <img src="/traceway-logo.png" alt="Traceway Logo" class="h-10 w-auto" />
+ <img src="/traceway-logo.png" alt="Traceway Logo" class="h-9 w-auto" />
{/if}
</Sidebar.SidebarHeader>
<Sidebar.SidebarContent>
- <Sidebar.SidebarGroup>
+ <Sidebar.SidebarGroup class="p-4 pt-0 pb-0">
<Sidebar.SidebarGroupContent>
<Sidebar.SidebarMenu>
{#each sidebarItems as sidebarItem}
@@ -45,6 +64,38 @@
</Sidebar.SidebarMenu>
</Sidebar.SidebarGroupContent>
</Sidebar.SidebarGroup>
+
+ {#if sidebarItemsBottom.length}
+ <div class="flex-1"></div>
+
+ <Sidebar.SidebarGroup class="p-4 pt-0">
+ <Sidebar.SidebarGroupContent>
+ <Sidebar.SidebarMenu>
+ {#each sidebarItemsBottom as sidebarItem}
+ <Sidebar.SidebarMenuItem>
+ {#if sidebarItem.external}
+ <Sidebar.SidebarMenuButton onclick={() => {
+ sidebar.setOpenMobile(false)
+ window.open(sidebarItem.href, '_blank', 'noopener,noreferrer')
+ }}>
+ <sidebarItem.Icon />
+ <span>{sidebarItem.title}</span>
+ </Sidebar.SidebarMenuButton>
+ {:else}
+ <Sidebar.SidebarMenuButton isActive={page.url.pathname === sidebarItem.href || page.url.pathname.startsWith(sidebarItem.href + '/')} onclick={(e) => {
+ sidebar.setOpenMobile(false)
+ createRowClickHandler(sidebarItem.href, ...sidebarItem.stickyParams)(e)
+ }}>
+ <sidebarItem.Icon />
+ <span>{sidebarItem.title}</span>
+ </Sidebar.SidebarMenuButton>
+ {/if}
+ </Sidebar.SidebarMenuItem>
+ {/each}
+ </Sidebar.SidebarMenu>
+ </Sidebar.SidebarGroupContent>
+ </Sidebar.SidebarGroup>
+ {/if}
</Sidebar.SidebarContent>
<Sidebar.SidebarFooter class="py-1 border-t border-border flex flex-row justify-center italic">
<span class="text-xs text-muted-foreground">Traceway - v{__APP_VERSION__}</span>
diff --git a/frontend/src/lib/components/ui/table/table-row.svelte b/frontend/src/lib/components/ui/table/table-row.svelte
index 0df769e0..f877d6a2 100644
--- a/frontend/src/lib/components/ui/table/table-row.svelte
+++ b/frontend/src/lib/components/ui/table/table-row.svelte
@@ -14,7 +14,7 @@
bind:this={ref}
data-slot="table-row"
class={cn(
- "hover:[&,&>svelte-css-wrapper]:[&>th,td]:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
+ "hover:[&,&>svelte-css-wrapper]:[&>td]:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
className
)}
{...restProps}
diff --git a/frontend/src/lib/state/auth.svelte.ts b/frontend/src/lib/state/auth.svelte.ts
index d7cbd0cd..fc5855f9 100644
--- a/frontend/src/lib/state/auth.svelte.ts
+++ b/frontend/src/lib/state/auth.svelte.ts
@@ -1,7 +1,17 @@
import { clearNavDepth } from '$lib/utils/back-navigation';
+export interface UserOrganizationResponse {
+ id: number;
+ name: string;
+ role: string;
+ timezone: string;
+}
+
class AuthState {
token = $state<string | null>(localStorage.getItem('AUTH_TOKEN'));
+ organizations = $state<UserOrganizationResponse[]>(
+ JSON.parse(localStorage.getItem('USER_ORGANIZATIONS') || '[]')
+ );
isAuthenticated = $derived(!!this.token);
@@ -14,6 +24,13 @@ class AuthState {
localStorage.removeItem('AUTH_TOKEN');
}
});
+ $effect(() => {
+ if (this.organizations.length > 0) {
+ localStorage.setItem('USER_ORGANIZATIONS', JSON.stringify(this.organizations));
+ } else {
+ localStorage.removeItem('USER_ORGANIZATIONS');
+ }
+ });
});
}
@@ -21,8 +38,36 @@ class AuthState {
this.token = token;
}
+ setOrganizations(organizations: UserOrganizationResponse[]) {
+ this.organizations = organizations;
+ }
+
+ getRoleForOrganization(organizationId: number): string | null {
+ const organization = this.organizations.find(o => o.id === organizationId);
+ return organization?.role || null;
+ }
+
+ canManageOrganization(organizationId: number): boolean {
+ const role = this.getRoleForOrganization(organizationId);
+ return role === 'owner' || role === 'admin';
+ }
+
+ getTimezoneForOrganization(organizationId: number): string | null {
+ const organization = this.organizations.find(o => o.id === organizationId);
+ return organization?.timezone || null;
+ }
+
+ updateOrganizationTimezone(organizationId: number, timezone: string) {
+ const organization = this.organizations.find(o => o.id === organizationId);
+ if (organization) {
+ organization.timezone = timezone;
+ this.organizations = [...this.organizations];
+ }
+ }
+
logout() {
this.token = null;
+ this.organizations = [];
clearNavDepth();
}
}
diff --git a/frontend/src/lib/state/organization.svelte.ts b/frontend/src/lib/state/organization.svelte.ts
new file mode 100644
index 00000000..1f239f0f
--- /dev/null
+++ b/frontend/src/lib/state/organization.svelte.ts
@@ -0,0 +1,107 @@
+import { api } from '$lib/api';
+
+export interface Organization {
+ id: number;
+ name: string;
+ timezone: string;
+ createdAt: string;
+}
+
+export interface OrganizationMember {
+ id: number;
+ email: string;
+ name: string;
+ role: string;
+ createdAt: string;
+}
+
+export interface Invitation {
+ id: number;
+ organizationId: number;
+ email: string;
+ role: string;
+ invitedBy: number;
+ inviterName: string;
+ status: string;
+ expiresAt: string;
+ acceptedAt?: string;
+ createdAt: string;
+}
+
+export interface OrganizationSettings {
+ organization: Organization;
+ members: OrganizationMember[];
+ invitations: Invitation[];
+ userRole: string;
+}
+
+class OrganizationState {
+ currentOrganization = $state<Organization | null>(null);
+ members = $state<OrganizationMember[]>([]);
+ invitations = $state<Invitation[]>([]);
+ loading = $state(false);
+ error = $state<string | null>(null);
+ userRole = $state<string | null>(null);
+
+ isOwner = $derived(this.userRole === 'owner');
+ isAdmin = $derived(this.userRole === 'admin');
+ canManage = $derived(this.userRole === 'owner' || this.userRole === 'admin');
+ memberCount = $derived(this.members.length + this.invitations.filter(i => i.status === 'pending').length);
+ canInvite = $derived(this.memberCount < 10);
+
+ async loadSettings(organizationId: number) {
+ this.loading = true;
+ this.error = null;
+
+ try {
+ const response: OrganizationSettings = await api.get(`/organizations/${organizationId}/settings`);
+ this.currentOrganization = response.organization;
+ this.members = response.members;
+ this.invitations = response.invitations;
+ this.userRole = response.userRole;
+ } catch (e: unknown) {
+ const errorMessage = e instanceof Error ? e.message : 'Failed to load settings';
+ this.error = errorMessage;
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ async inviteUser(organizationId: number, email: string, role: string) {
+ const response = await api.post(`/organizations/${organizationId}/invitations`, { email, role });
+ await this.loadSettings(organizationId);
+ return response;
+ }
+
+ async revokeInvitation(organizationId: number, invitationId: number) {
+ await api.delete(`/organizations/${organizationId}/invitations/${invitationId}`);
+ await this.loadSettings(organizationId);
+ }
+
+ async updateMemberRole(organizationId: number, userId: number, role: string) {
+ await api.put(`/organizations/${organizationId}/members/${userId}`, { role });
+ await this.loadSettings(organizationId);
+ }
+
+ async removeMember(organizationId: number, userId: number) {
+ await api.delete(`/organizations/${organizationId}/members/${userId}`);
+ await this.loadSettings(organizationId);
+ }
+
+ async updateTimezone(organizationId: number, timezone: string) {
+ await api.put(`/organizations/${organizationId}/settings`, { timezone });
+ if (this.currentOrganization) {
+ this.currentOrganization = { ...this.currentOrganization, timezone };
+ }
+ }
+
+ clear() {
+ this.currentOrganization = null;
+ this.members = [];
+ this.invitations = [];
+ this.userRole = null;
+ this.error = null;
+ }
+}
+
+export const organizationState = new OrganizationState();
diff --git a/frontend/src/lib/state/projects.svelte.ts b/frontend/src/lib/state/projects.svelte.ts
index 61c9cea2..bc70d648 100644
--- a/frontend/src/lib/state/projects.svelte.ts
+++ b/frontend/src/lib/state/projects.svelte.ts
@@ -1,4 +1,5 @@
import { api } from '$lib/api';
+import { authState } from './auth.svelte';
export type Framework = 'gin' | 'fiber' | 'chi' | 'fasthttp' | 'stdlib' | 'custom';
@@ -7,6 +8,7 @@ export interface Project {
name: string;
token: string;
framework: Framework;
+ organizationId: number | null;
createdAt: string;
backendUrl: string;
}
@@ -16,7 +18,9 @@ export interface ProjectWithToken extends Project {
}
class ProjectsState {
- projects = $state<Project[]>([]);
+ projects = $state<Project[]>(
+ JSON.parse(localStorage.getItem('PROJECTS_CACHE') || '[]')
+ );
currentProjectId = $state<string | null>(localStorage.getItem('CURRENT_PROJECT_ID'));
loading = $state(false);
error = $state<string | null>(null);
@@ -25,6 +29,12 @@ class ProjectsState {
this.projects.find(p => p.id === this.currentProjectId) || this.projects[0] || null
);
+ canManageCurrentProject = $derived.by(() => {
+ const organizationId = this.currentProject?.organizationId;
+ if (!organizationId) return false;
+ return authState.canManageOrganization(organizationId);
+ });
+
constructor() {
$effect.root(() => {
$effect(() => {
diff --git a/frontend/src/lib/state/timezone.svelte.ts b/frontend/src/lib/state/timezone.svelte.ts
index e5001b83..266a4f73 100644
--- a/frontend/src/lib/state/timezone.svelte.ts
+++ b/frontend/src/lib/state/timezone.svelte.ts
@@ -1,21 +1,12 @@
import { DateTime } from 'luxon';
-
-export const timezoneState = $state({
- timezone: ''
-});
-
-export function initTimezone() {
- if (typeof window !== 'undefined') {
- const stored = localStorage.getItem('timezone');
- timezoneState.timezone = stored || DateTime.local().zoneName || 'UTC';
- }
-}
+import { projectsState } from './projects.svelte';
+import { authState } from './auth.svelte';
export function getTimezone(): string {
- return timezoneState.timezone || DateTime.local().zoneName || 'UTC';
-}
-
-export function setTimezone(tz: string) {
- timezoneState.timezone = tz;
- localStorage.setItem('timezone', tz);
+ const organizationId = projectsState.currentProject?.organizationId;
+ if (organizationId) {
+ const timezone = authState.getTimezoneForOrganization(organizationId);
+ if (timezone) return timezone;
+ }
+ return DateTime.local().zoneName || 'UTC';
}
diff --git a/frontend/src/routes/+layout.svelte b/frontend/src/routes/+layout.svelte
index ee367c21..45f1ab31 100644
--- a/frontend/src/routes/+layout.svelte
+++ b/frontend/src/routes/+layout.svelte
@@ -4,7 +4,6 @@
import { authState } from '$lib/state/auth.svelte';
import { projectsState } from '$lib/state/projects.svelte';
import { themeState, initTheme, toggleTheme } from '$lib/state/theme.svelte';
- import { initTimezone } from '$lib/state/timezone.svelte';
import { incrementNavDepth, decrementNavDepth } from '$lib/utils/back-navigation';
import AppSidebar from '$lib/components/app-sidebar.svelte';
import AddProjectModal from '$lib/components/add-project-modal.svelte';
@@ -41,10 +40,8 @@
onMount(() => {
initTheme();
- initTimezone();
if (authState.isAuthenticated) {
- projectsState.initFromCache();
projectsState.loadProjects();
}
});
@@ -74,7 +71,7 @@
<!-- This is not ideal, but because our layout is a top level route it can end up showing sidebar on the login page (after the login before the transition). -->
<!-- We could consider moving this to a lower level layout for the actual app, for now it's just a path check -->
-{#if authState.isAuthenticated && page.url.pathname !== "/login" && page.url.pathname !== "/register"}
+{#if authState.isAuthenticated && page.url.pathname !== "/login" && page.url.pathname !== "/register" && !page.url.pathname.startsWith("/accept-invitation")}
<Sidebar.SidebarProvider>
<AppSidebar />
<Sidebar.SidebarInset>
diff --git a/frontend/src/routes/+page.svelte b/frontend/src/routes/+page.svelte
index e8e3f821..e04a0448 100644
--- a/frontend/src/routes/+page.svelte
+++ b/frontend/src/routes/+page.svelte
@@ -126,7 +126,7 @@
// Show success toast if data was received
if (!hadDataBefore && data?.hasData) {
- toast.success('Integration successful! Data received from your application.');
+ toast.success('Integration successful! Data received from your application.', { position: 'top-center' });
} else if (!data?.hasData) {
toast.warning('No data received yet', {
position: 'top-center'
diff --git a/frontend/src/routes/accept-invitation/+page.svelte b/frontend/src/routes/accept-invitation/+page.svelte
new file mode 100644
index 00000000..c5279905
--- /dev/null
+++ b/frontend/src/routes/accept-invitation/+page.svelte
@@ -0,0 +1,256 @@
+<script lang="ts">
+ import { goto } from '$app/navigation';
+ import { page } from '$app/state';
+ import { onMount } from 'svelte';
+ import { Button } from "$lib/components/ui/button";
+ import { Input } from "$lib/components/ui/input";
+ import { Label } from "$lib/components/ui/label";
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "$lib/components/ui/card";
+ import { Alert, AlertDescription, AlertTitle } from "$lib/components/ui/alert";
+ import { CircleAlert, Check } from "@lucide/svelte";
+ import { authState } from '$lib/state/auth.svelte';
+ import { projectsState } from '$lib/state/projects.svelte';
+ import { themeState } from '$lib/state/theme.svelte';
+
+ interface InvitationInfo {
+ email: string;
+ organizationName: string;
+ inviterName: string;
+ existsAsUser: boolean;
+ role: string;
+ }
+
+ let loading = $state(true);
+ let submitting = $state(false);
+ let error = $state('');
+ let invitationInfo = $state<InvitationInfo | null>(null);
+ let name = $state('');
+ let password = $state('');
+ let confirmPassword = $state('');
+ let success = $state(false);
+
+ const token = $derived(page.url.searchParams.get('token'));
+
+ onMount(async () => {
+ if (!token) {
+ error = 'Invalid invitation link';
+ loading = false;
+ return;
+ }
+
+ try {
+ const response = await fetch(`/api/invitations/${token}`);
+
+ if (!response.ok) {
+ const data = await response.json();
+ throw new Error(data.error || 'Invalid or expired invitation');
+ }
+
+ invitationInfo = await response.json();
+ } catch (e) {
+ error = e instanceof Error ? e.message : 'Failed to load invitation';
+ } finally {
+ loading = false;
+ }
+ });
+
+ async function handleNewUserSubmit() {
+ if (password !== confirmPassword) {
+ error = 'Passwords do not match';
+ return;
+ }
+
+ if (password.length < 8) {
+ error = 'Password must be at least 8 characters';
+ return;
+ }
+
+ submitting = true;
+ error = '';
+
+ try {
+ const response = await fetch(`/api/invitations/${token}/accept`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name, password })
+ });
+
+ if (!response.ok) {
+ const data = await response.json();
+ throw new Error(data.error || 'Failed to accept invitation');
+ }
+
+ const data = await response.json();
+
+ authState.setToken(data.token);
+ authState.setOrganizations(data.organizations || []);
+ projectsState.setProjects(data.projects);
+
+ success = true;
+ setTimeout(() => goto('/'), 1500);
+ } catch (e) {
+ error = e instanceof Error ? e.message : 'Failed to accept invitation';
+ } finally {
+ submitting = false;
+ }
+ }
+
+ async function handleExistingUserAccept() {
+ submitting = true;
+ error = '';
+
+ try {
+ const response = await fetch(`/api/invitations/${token}/accept-existing`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${authState.token}`
+ }
+ });
+
+ if (!response.ok) {
+ const data = await response.json();
+ throw new Error(data.error || 'Failed to accept invitation');
+ }
+
+ const data = await response.json();
+ projectsState.setProjects(data.projects);
+ success = true;
+ setTimeout(() => goto('/'), 1500);
+ } catch (e) {
+ error = e instanceof Error ? e.message : 'Failed to accept invitation';
+ } finally {
+ submitting = false;
+ }
+ }
+
+ function handleLoginRedirect() {
+ const returnTo = encodeURIComponent(`/accept-invitation?token=${token}`);
+ goto(`/login?returnTo=${returnTo}`);
+ }
+
+ function getRoleLabel(role: string): string {
+ switch (role) {
+ case 'admin': return 'Admin';
+ case 'readonly': return 'Read Only';
+ default: return 'Member';
+ }
+ }
+</script>
+
+<div class="flex min-h-screen w-full items-center justify-center px-4 py-8">
+ <Card class="w-[400px]">
+ <CardHeader>
+ <CardTitle class="text-2xl">
+ <div class="flex flex-row items-center justify-center gap-2">
+ {#if themeState.isDark}
+ <img src="/traceway-logo-white.svg" alt="Traceway Logo" class="h-8 w-auto" />
+ {:else}
+ <img src="/traceway-logo.png" alt="Traceway Logo" class="h-8 w-auto" />
+ {/if}
+ </div>
+ </CardTitle>
+ {#if invitationInfo && !success}
+ <CardDescription class="text-center">
+ You've been invited to join <strong>{invitationInfo.organizationName}</strong>
+ </CardDescription>
+ {/if}
+ </CardHeader>
+ <CardContent>
+ {#if loading}
+ <div class="flex items-center justify-center py-8">
+ <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
+ </div>
+ {:else if success}
+ <div class="flex flex-col items-center justify-center py-8 gap-4">
+ <div class="rounded-full bg-green-100 p-3">
+ <Check class="h-8 w-8 text-green-600" />
+ </div>
+ <p class="text-center text-lg font-medium">Welcome to {invitationInfo?.organizationName}!</p>
+ <p class="text-center text-muted-foreground">Redirecting to dashboard...</p>
+ </div>
+ {:else if error && !invitationInfo}
+ <Alert variant="destructive" class="bg-red-50 border-red-200">
+ <CircleAlert class="h-4 w-4 text-red-700" />
+ <AlertTitle class="text-red-800">Error</AlertTitle>
+ <AlertDescription class="text-red-700">
+ {error}
+ </AlertDescription>
+ </Alert>
+ <div class="mt-4 text-center">
+ <Button variant="outline" onclick={() => goto('/login')}>
+ Go to Login
+ </Button>
+ </div>
+ {:else if invitationInfo}
+ <div class="space-y-4">
+ <div class="bg-muted/50 rounded-lg p-4 text-sm">
+ <p><strong>{invitationInfo.inviterName}</strong> invited you to join as a <strong>{getRoleLabel(invitationInfo.role)}</strong></p>
+ </div>
+
+ {#if error}
+ <Alert variant="destructive" class="bg-red-50 border-red-200">
+ <CircleAlert class="h-4 w-4 text-red-700" />
+ <AlertDescription class="text-red-700">
+ {error}
+ </AlertDescription>
+ </Alert>
+ {/if}
+
+ {#if invitationInfo.existsAsUser}
+ {#if authState.isAuthenticated}
+ <p class="text-center text-muted-foreground">
+ Click below to join the organization
+ </p>
+ <Button class="w-full" onclick={handleExistingUserAccept} disabled={submitting}>
+ {#if submitting}
+ Joining...
+ {:else}
+ Accept Invitation
+ {/if}
+ </Button>
+ <div>
+ <p class="text-sm text-muted-foreground">
+ To go to the Login page <a href="/login" class="text-primary hover:underline">Click Here</a>
+ </p>
+ </div>
+ {:else}
+ <p class="text-center text-muted-foreground">
+ You already have an account. Please log in to accept this invitation.
+ </p>
+ <Button class="w-full" onclick={handleLoginRedirect}>
+ Login to Accept
+ </Button>
+ {/if}
+ {:else}
+ <form onsubmit={(e) => { e.preventDefault(); handleNewUserSubmit(); }} class="space-y-4">
+ <div class="space-y-2">
+ <Label for="email">Email</Label>
+ <Input id="email" type="email" value={invitationInfo.email} disabled />
+ </div>
+ <div class="space-y-2">
+ <Label for="name">Your Name</Label>
+ <Input id="name" type="text" bind:value={name} placeholder="Your name" required />
+ </div>
+ <div class="space-y-2">
+ <Label for="password">Password</Label>
+ <Input id="password" type="password" bind:value={password} placeholder="Min 8 characters" required />
+ </div>
+ <div class="space-y-2">
+ <Label for="confirmPassword">Confirm Password</Label>
+ <Input id="confirmPassword" type="password" bind:value={confirmPassword} placeholder="Confirm password" required />
+ </div>
+ <Button type="submit" class="w-full" disabled={submitting}>
+ {#if submitting}
+ Creating account...
+ {:else}
+ Create Account & Join
+ {/if}
+ </Button>
+ </form>
+ {/if}
+ </div>
+ {/if}
+ </CardContent>
+ </Card>
+</div>
diff --git a/frontend/src/routes/accept-invitation/+page.ts b/frontend/src/routes/accept-invitation/+page.ts
new file mode 100644
index 00000000..d43d0cd2
--- /dev/null
+++ b/frontend/src/routes/accept-invitation/+page.ts
@@ -0,0 +1 @@
+export const prerender = false;
diff --git a/frontend/src/routes/login/+page.svelte b/frontend/src/routes/login/+page.svelte
index 3c94fe75..7f4c310e 100644
--- a/frontend/src/routes/login/+page.svelte
+++ b/frontend/src/routes/login/+page.svelte
@@ -1,5 +1,6 @@
<script lang="ts">
import { goto } from '$app/navigation';
+ import { page } from '$app/state';
import { Button } from "$lib/components/ui/button";
import { Input } from "$lib/components/ui/input";
import { Label } from "$lib/components/ui/label";
@@ -16,6 +17,9 @@
let error = $state('');
let loading = $state(false);
+ // Get returnTo parameter for redirecting after login
+ const returnTo = $derived(page.url.searchParams.get('returnTo'));
+
if (!__CLOUD_MODE__) {
$effect(() => {
// if we're not in the cloud mode we have to check if an organization exists and if it does not we need to take the user to the register page
@@ -60,9 +64,12 @@
const data = await response.json();
authState.setToken(data.token);
+ authState.setOrganizations(data.organizations || []);
projectsState.setProjects(data.projects);
- goto('/');
+ // Redirect to returnTo if provided, otherwise go to dashboard
+ const redirectTo = returnTo ? decodeURIComponent(returnTo) : '/';
+ goto(redirectTo);
} catch (e) {
error = e instanceof Error ? e.message : 'Invalid email or password';
} finally {
diff --git a/frontend/src/routes/register/+page.svelte b/frontend/src/routes/register/+page.svelte
index e28a4f76..9551e7ba 100644
--- a/frontend/src/routes/register/+page.svelte
+++ b/frontend/src/routes/register/+page.svelte
@@ -6,11 +6,12 @@
import { Card, CardContent, CardFooter, CardHeader, CardTitle, CardDescription } from "$lib/components/ui/card";
import { Alert, AlertDescription, AlertTitle } from "$lib/components/ui/alert";
import * as Select from "$lib/components/ui/select";
- import { CircleAlert } from "@lucide/svelte";
+ import { CircleAlert, Check } from "@lucide/svelte";
import { authState } from '$lib/state/auth.svelte';
- import { projectsState } from '$lib/state/projects.svelte';
+ import { projectsState, type Framework } from '$lib/state/projects.svelte';
import { themeState } from '$lib/state/theme.svelte';
- import { toast } from 'svelte-sonner';
+ import { toast } from 'svelte-sonner';
+ import FrameworkIcon from '$lib/components/framework-icon.svelte';
let email = $state('');
let name = $state('');
@@ -18,7 +19,7 @@
let confirmPassword = $state('');
let organizationName = $state('');
let projectName = $state('');
- let framework = $state('gin');
+ let framework = $state<Framework>('gin');
let error = $state('');
let loading = $state(false);
@@ -47,11 +48,17 @@
}
const frameworks = [
- { value: 'gin', label: 'Gin (Go)' },
- { value: 'echo', label: 'Echo (Go)' },
- { value: 'fiber', label: 'Fiber (Go)' },
- { value: 'other', label: 'Other' }
- ];
+ { value: 'gin', label: 'Gin', description: 'Fast HTTP web framework' },
+ { value: 'fiber', label: 'Fiber', description: 'Express-inspired framework' },
+ { value: 'chi', label: 'Chi', description: 'Lightweight router' },
+ { value: 'fasthttp', label: 'FastHTTP', description: 'High-performance HTTP' },
+ { value: 'stdlib', label: 'Standard Library', description: 'net/http package' },
+ { value: 'custom', label: 'Custom', description: 'Other / manual setup' },
+ ] as const;
+
+ const selectedFrameworkLabel = $derived(
+ frameworks.find(f => f.value === framework)?.label ?? 'Select framework'
+ );
async function handleRegister() {
if (password !== confirmPassword) {
@@ -91,6 +98,7 @@
const data = await response.json();
authState.setToken(data.token);
+ authState.setOrganizations(data.organizations || []);
projectsState.setProjects(data.projects);
goto('/connection');
@@ -164,12 +172,26 @@
<Label for="framework">Framework</Label>
<Select.Root type="single" bind:value={framework}>
<Select.Trigger class="w-full">
- {frameworks.find(f => f.value === framework)?.label || 'Select framework'}
+ <div class="flex items-center gap-2">
+ <FrameworkIcon framework={framework} />
+ <span>{selectedFrameworkLabel}</span>
+ </div>
</Select.Trigger>
<Select.Content>
{#each frameworks as fw}
<Select.Item value={fw.value}>
- {fw.label}
+ {#snippet children({ selected })}
+ <div class="flex items-center gap-2">
+ <FrameworkIcon framework={fw.value} />
+ <div class="flex flex-col">
+ <span class="font-medium">{fw.label}</span>
+ <span class="text-xs text-muted-foreground">{fw.description}</span>
+ </div>
+ </div>
+ {#if selected}
+ <Check class="absolute end-2 size-4" />
+ {/if}
+ {/snippet}
</Select.Item>
{/each}
</Select.Content>
diff --git a/frontend/src/routes/settings/+page.svelte b/frontend/src/routes/settings/+page.svelte
new file mode 100644
index 00000000..5dbc95e5
--- /dev/null
+++ b/frontend/src/routes/settings/+page.svelte
@@ -0,0 +1,59 @@
+<script lang="ts">
+ import { goto } from '$app/navigation';
+ import { authState } from '$lib/state/auth.svelte';
+ import { projectsState } from '$lib/state/projects.svelte';
+ import { organizationState } from '$lib/state/organization.svelte';
+ import OrganizationTab from './organization-tab.svelte';
+ import UsersTab from './users-tab.svelte';
+
+ let loading = $state(true);
+ let error = $state<string | null>(null);
+
+ const currentOrganizationId = $derived(projectsState.currentProject?.organizationId);
+
+ const hasAccess = $derived(
+ currentOrganizationId !== null &&
+ currentOrganizationId !== undefined &&
+ authState.canManageOrganization(currentOrganizationId)
+ );
+
+ $effect(() => {
+ if (!hasAccess && !loading) {
+ goto('/');
+ }
+ });
+
+ $effect(() => {
+ if (currentOrganizationId && hasAccess) {
+ loading = true;
+ organizationState.loadSettings(currentOrganizationId)
+ .catch(e => {
+ error = e instanceof Error ? e.message : 'Failed to load settings';
+ })
+ .finally(() => {
+ loading = false;
+ });
+ }
+ });
+</script>
+
+<div class="space-y-6">
+ <div>
+ <h1 class="text-2xl font-semibold tracking-tight">Settings</h1>
+ </div>
+
+ {#if loading}
+ <div class="flex items-center justify-center py-12">
+ <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
+ </div>
+ {:else if error}
+ <div class="text-center py-12 text-destructive">
+ {error}
+ </div>
+ {:else}
+ <div class="space-y-6">
+ <OrganizationTab />
+ <UsersTab organizationId={currentOrganizationId!} />
+ </div>
+ {/if}
+</div>
diff --git a/frontend/src/routes/settings/+page.ts b/frontend/src/routes/settings/+page.ts
new file mode 100644
index 00000000..d43d0cd2
--- /dev/null
+++ b/frontend/src/routes/settings/+page.ts
@@ -0,0 +1 @@
+export const prerender = false;
diff --git a/frontend/src/routes/settings/invite-user-dialog.svelte b/frontend/src/routes/settings/invite-user-dialog.svelte
new file mode 100644
index 00000000..e8c60882
--- /dev/null
+++ b/frontend/src/routes/settings/invite-user-dialog.svelte
@@ -0,0 +1,119 @@
+<script lang="ts">
+ import * as AlertDialog from "$lib/components/ui/alert-dialog";
+ import { Button } from "$lib/components/ui/button";
+ import { Input } from "$lib/components/ui/input";
+ import { Label } from "$lib/components/ui/label";
+ import * as Select from "$lib/components/ui/select";
+ import { UserPlus } from "@lucide/svelte";
+ import { toast } from 'svelte-sonner';
+ import { organizationState } from '$lib/state/organization.svelte';
+
+ interface Props {
+ open: boolean;
+ organizationId: number;
+ }
+
+ let { open = $bindable(), organizationId }: Props = $props();
+
+ let email = $state('');
+ let role = $state('user');
+ let loading = $state(false);
+ let error = $state('');
+
+ const roleOptions = [
+ { value: 'admin', label: 'Admin', description: 'Full access to projects and settings' },
+ { value: 'user', label: 'User', description: 'Can view and modify projects' },
+ { value: 'readonly', label: 'Read Only', description: 'Can only view projects' }
+ ];
+
+ async function handleSubmit() {
+ if (!email) {
+ error = 'Email is required';
+ return;
+ }
+
+ loading = true;
+ error = '';
+
+ try {
+ await organizationState.inviteUser(organizationId, email, role);
+ toast.success('Invitation sent', { position: 'top-center' });
+ email = '';
+ role = 'user';
+ open = false;
+ } catch (e: unknown) {
+ error = e instanceof Error ? e.message : 'Failed to send invitation';
+ toast.error(error);
+ } finally {
+ loading = false;
+ }
+ }
+
+ function handleOpenChange(isOpen: boolean) {
+ if (!isOpen) {
+ email = '';
+ role = 'user';
+ error = '';
+ }
+ open = isOpen;
+ }
+</script>
+
+<AlertDialog.Root {open} onOpenChange={handleOpenChange}>
+ <AlertDialog.Content class="max-w-md">
+ <AlertDialog.Header>
+ <AlertDialog.Title>Invite Team Member</AlertDialog.Title>
+ <AlertDialog.Description>
+ Send an invitation to join your organization
+ </AlertDialog.Description>
+ </AlertDialog.Header>
+
+ <form onsubmit={(e) => { e.preventDefault(); handleSubmit(); }} class="space-y-4 py-4">
+ <div class="space-y-2">
+ <Label for="email">Email Address</Label>
+ <Input
+ id="email"
+ type="email"
+ bind:value={email}
+ placeholder="[email protected]"
+ required
+ />
+ </div>
+
+ <div class="space-y-2">
+ <Label for="role">Role</Label>
+ <Select.Root type="single" bind:value={role}>
+ <Select.Trigger class="w-full">
+ {roleOptions.find(r => r.value === role)?.label || 'Select role'}
+ </Select.Trigger>
+ <Select.Content>
+ {#each roleOptions as roleOption}
+ <Select.Item value={roleOption.value}>
+ <div class="flex flex-col">
+ <span>{roleOption.label}</span>
+ <span class="text-xs text-muted-foreground">{roleOption.description}</span>
+ </div>
+ </Select.Item>
+ {/each}
+ </Select.Content>
+ </Select.Root>
+ </div>
+
+ {#if error}
+ <p class="text-sm text-destructive">{error}</p>
+ {/if}
+ </form>
+
+ <AlertDialog.Footer>
+ <AlertDialog.Cancel disabled={loading}>Cancel</AlertDialog.Cancel>
+ <Button onclick={handleSubmit} disabled={loading}>
+ <UserPlus class="mr-2 h-4 w-4" />
+ {#if loading}
+ Inviting...
+ {:else}
+ Invite User
+ {/if}
+ </Button>
+ </AlertDialog.Footer>
+ </AlertDialog.Content>
+</AlertDialog.Root>
diff --git a/frontend/src/routes/settings/organization-tab.svelte b/frontend/src/routes/settings/organization-tab.svelte
new file mode 100644
index 00000000..3d81ab5c
--- /dev/null
+++ b/frontend/src/routes/settings/organization-tab.svelte
@@ -0,0 +1,154 @@
+<script lang="ts">
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "$lib/components/ui/card";
+ import { Label } from "$lib/components/ui/label";
+ import { Button } from "$lib/components/ui/button";
+ import * as Select from "$lib/components/ui/select";
+ import { organizationState } from '$lib/state/organization.svelte';
+ import { authState } from '$lib/state/auth.svelte';
+ import { toast } from 'svelte-sonner';
+
+ const organization = $derived(organizationState.currentOrganization);
+ const canManage = $derived(organizationState.canManage);
+
+ let selectedTimezone = $state(organization?.timezone || 'UTC');
+ let saving = $state(false);
+
+ $effect(() => {
+ if (organization?.timezone) {
+ selectedTimezone = organization.timezone;
+ }
+ });
+
+ const hasChanges = $derived(selectedTimezone !== organization?.timezone);
+
+ const timezoneGroups = [
+ {
+ label: 'Common',
+ timezones: [
+ { value: 'UTC', label: 'UTC (Coordinated Universal Time)' },
+ { value: 'America/New_York', label: 'US Eastern (New York)' },
+ { value: 'America/Chicago', label: 'US Central (Chicago)' },
+ { value: 'America/Denver', label: 'US Mountain (Denver)' },
+ { value: 'America/Los_Angeles', label: 'US Pacific (Los Angeles)' },
+ ]
+ },
+ {
+ label: 'Europe',
+ timezones: [
+ { value: 'Europe/London', label: 'London (GMT/BST)' },
+ { value: 'Europe/Paris', label: 'Paris (CET/CEST)' },
+ { value: 'Europe/Berlin', label: 'Berlin (CET/CEST)' },
+ { value: 'Europe/Belgrade', label: 'Belgrade (CET/CEST)' },
+ { value: 'Europe/Amsterdam', label: 'Amsterdam (CET/CEST)' },
+ { value: 'Europe/Stockholm', label: 'Stockholm (CET/CEST)' },
+ { value: 'Europe/Zurich', label: 'Zurich (CET/CEST)' },
+ { value: 'Europe/Madrid', label: 'Madrid (CET/CEST)' },
+ { value: 'Europe/Rome', label: 'Rome (CET/CEST)' },
+ { value: 'Europe/Athens', label: 'Athens (EET/EEST)' },
+ { value: 'Europe/Moscow', label: 'Moscow (MSK)' },
+ ]
+ },
+ {
+ label: 'Asia & Pacific',
+ timezones: [
+ { value: 'Asia/Dubai', label: 'Dubai (GST)' },
+ { value: 'Asia/Kolkata', label: 'India (IST)' },
+ { value: 'Asia/Singapore', label: 'Singapore (SGT)' },
+ { value: 'Asia/Hong_Kong', label: 'Hong Kong (HKT)' },
+ { value: 'Asia/Shanghai', label: 'Shanghai (CST)' },
+ { value: 'Asia/Tokyo', label: 'Tokyo (JST)' },
+ { value: 'Asia/Seoul', label: 'Seoul (KST)' },
+ { value: 'Australia/Sydney', label: 'Sydney (AEST/AEDT)' },
+ { value: 'Australia/Melbourne', label: 'Melbourne (AEST/AEDT)' },
+ { value: 'Pacific/Auckland', label: 'Auckland (NZST/NZDT)' },
+ ]
+ },
+ {
+ label: 'Americas',
+ timezones: [
+ { value: 'America/Toronto', label: 'Toronto (EST/EDT)' },
+ { value: 'America/Vancouver', label: 'Vancouver (PST/PDT)' },
+ { value: 'America/Mexico_City', label: 'Mexico City (CST/CDT)' },
+ { value: 'America/Sao_Paulo', label: 'São Paulo (BRT)' },
+ { value: 'America/Buenos_Aires', label: 'Buenos Aires (ART)' },
+ ]
+ }
+ ];
+
+ function getTimezoneLabel(value: string): string {
+ for (const group of timezoneGroups) {
+ const tz = group.timezones.find(t => t.value === value);
+ if (tz) return tz.label;
+ }
+ return value;
+ }
+
+ async function handleSave() {
+ if (!organization) return;
+
+ saving = true;
+ try {
+ await organizationState.updateTimezone(organization.id, selectedTimezone);
+ authState.updateOrganizationTimezone(organization.id, selectedTimezone);
+ toast.success('Successfully updated the Timezone', { position: 'top-center' });
+ } catch (e: unknown) {
+ const errorMessage = e instanceof Error ? e.message : 'Failed to update timezone';
+ toast.error(errorMessage);
+ } finally {
+ saving = false;
+ }
+ }
+</script>
+
+<Card>
+ <CardHeader>
+ <CardTitle>Organization Details</CardTitle>
+ <CardDescription>Information about your organization</CardDescription>
+ </CardHeader>
+ <CardContent class="space-y-4">
+ {#if organization}
+ <div class="grid gap-4">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label class="text-right text-muted-foreground">Name</Label>
+ <div class="col-span-3">{organization.name}</div>
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label class="text-right text-muted-foreground">Timezone</Label>
+ <div class="col-span-3">
+ {#if canManage}
+ <div class="flex items-center gap-2">
+ <Select.Root type="single" bind:value={selectedTimezone}>
+ <Select.Trigger class="w-[280px]">
+ {getTimezoneLabel(selectedTimezone)}
+ </Select.Trigger>
+ <Select.Content class="max-h-[300px]">
+ {#each timezoneGroups as group}
+ <Select.Group>
+ <Select.GroupHeading>{group.label}</Select.GroupHeading>
+ {#each group.timezones as tz}
+ <Select.Item value={tz.value}>{tz.label}</Select.Item>
+ {/each}
+ </Select.Group>
+ {/each}
+ </Select.Content>
+ </Select.Root>
+ {#if hasChanges}
+ <Button onclick={handleSave} disabled={saving} size="sm">
+ {saving ? 'Saving...' : 'Save'}
+ </Button>
+ {/if}
+ </div>
+ <p class="text-xs text-muted-foreground mt-1">
+ All team members will see timestamps in this timezone
+ </p>
+ {:else}
+ <span>{getTimezoneLabel(organization.timezone)}</span>
+ {/if}
+ </div>
+ </div>
+ </div>
+ {:else}
+ <p class="text-muted-foreground">Organization information not available</p>
+ {/if}
+ </CardContent>
+</Card>
diff --git a/frontend/src/routes/settings/users-tab.svelte b/frontend/src/routes/settings/users-tab.svelte
new file mode 100644
index 00000000..d87691d5
--- /dev/null
+++ b/frontend/src/routes/settings/users-tab.svelte
@@ -0,0 +1,262 @@
+<script lang="ts">
+ import { Button } from "$lib/components/ui/button";
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "$lib/components/ui/card";
+ import * as Table from "$lib/components/ui/table";
+ import * as Select from "$lib/components/ui/select";
+ import * as AlertDialog from "$lib/components/ui/alert-dialog";
+ import { Badge } from "$lib/components/ui/badge";
+ import { UserPlus, Trash2 } from "@lucide/svelte";
+ import { toast } from 'svelte-sonner';
+ import { organizationState, type OrganizationMember, type Invitation } from '$lib/state/organization.svelte';
+ import { authState } from '$lib/state/auth.svelte';
+ import InviteUserDialog from './invite-user-dialog.svelte';
+
+ interface Props {
+ organizationId: number;
+ }
+
+ let { organizationId }: Props = $props();
+
+ let showInviteDialog = $state(false);
+ let memberToRemove = $state<OrganizationMember | null>(null);
+ let invitationToRevoke = $state<Invitation | null>(null);
+ let processingRoleChange = $state<number | null>(null);
+
+ const members = $derived(organizationState.members);
+ const invitations = $derived(organizationState.invitations.filter(i => i.status === 'pending'));
+ const canInvite = $derived(organizationState.canInvite);
+ const isOwner = $derived(organizationState.isOwner);
+
+ const roleOptions = [
+ { value: 'admin', label: 'Admin' },
+ { value: 'user', label: 'User' },
+ { value: 'readonly', label: 'Read Only' }
+ ];
+
+ async function handleRoleChange(userId: number, newRole: string) {
+ processingRoleChange = userId;
+ try {
+ await organizationState.updateMemberRole(organizationId, userId, newRole);
+ toast.success('Role updated', { position: 'top-center' });
+ } catch (e) {
+ toast.error(e instanceof Error ? e.message : 'Failed to update role', { position: 'top-center' });
+ } finally {
+ processingRoleChange = null;
+ }
+ }
+
+ async function handleRemoveMember() {
+ if (!memberToRemove) return;
+
+ try {
+ await organizationState.removeMember(organizationId, memberToRemove.id);
+ toast.success('Successfully removed the Member', { position: 'top-center' });
+ } catch (e) {
+ toast.error(e instanceof Error ? e.message : 'Failed to remove member');
+ } finally {
+ memberToRemove = null;
+ }
+ }
+
+ async function handleRevokeInvitation() {
+ if (!invitationToRevoke) return;
+
+ try {
+ await organizationState.revokeInvitation(organizationId, invitationToRevoke.id);
+ toast.success('Successfully revoked the Invitation', { position: 'top-center' });
+ } catch (e) {
+ toast.error(e instanceof Error ? e.message : 'Failed to revoke invitation');
+ } finally {
+ invitationToRevoke = null;
+ }
+ }
+
+ function canChangeRole(member: OrganizationMember): boolean {
+ if (member.role === 'owner') return false;
+ return true;
+ }
+
+ function canRemoveMember(member: OrganizationMember): boolean {
+ return member.role !== 'owner';
+ }
+
+ function getRoleBadgeVariant(role: string): 'default' | 'secondary' | 'destructive' | 'outline' {
+ switch (role) {
+ case 'owner': return 'default';
+ case 'admin': return 'secondary';
+ case 'readonly': return 'outline';
+ default: return 'outline';
+ }
+ }
+</script>
+
+<div class="space-y-6">
+ <Card class="pb-0">
+ <CardHeader class="flex flex-row items-center justify-between space-y-0 pb-4">
+ <div>
+ <CardTitle>Team Members</CardTitle>
+ <CardDescription>Manage your organization's team members</CardDescription>
+ </div>
+ <Button variant="outline" onclick={() => showInviteDialog = true} disabled={!canInvite}>
+ <UserPlus class="mr-2 h-4 w-4" />
+ Invite User
+ </Button>
+ </CardHeader>
+ <CardContent class="p-0">
+ <Table.Root>
+ <Table.Header>
+ <Table.Row class="hover:bg-transparent">
+ <Table.Head>Name</Table.Head>
+ <Table.Head>Email</Table.Head>
+ <Table.Head>Role</Table.Head>
+ <Table.Head>Status</Table.Head>
+ <Table.Head class="w-[100px]"></Table.Head>
+ </Table.Row>
+ </Table.Header>
+ <Table.Body>
+ {#each members as member}
+ <Table.Row>
+ <Table.Cell class="font-medium">{member.name}</Table.Cell>
+ <Table.Cell>{member.email}</Table.Cell>
+ <Table.Cell>
+ {#if canChangeRole(member) && member.role !== 'owner'}
+ <Select.Root
+ type="single"
+ value={member.role}
+ onValueChange={(val) => val && handleRoleChange(member.id, val)}
+ disabled={processingRoleChange === member.id || (!isOwner && member.role === 'admin')}
+ >
+ <Select.Trigger class="w-[130px]">
+ {roleOptions.find(r => r.value === member.role)?.label || member.role}
+ </Select.Trigger>
+ <Select.Content>
+ {#each roleOptions as role}
+ {#if isOwner || role.value !== 'admin'}
+ <Select.Item value={role.value}>
+ {role.label}
+ </Select.Item>
+ {/if}
+ {/each}
+ </Select.Content>
+ </Select.Root>
+ {:else}
+ <Badge variant={getRoleBadgeVariant(member.role)}>
+ {member.role === 'owner' ? 'Owner' :
+ member.role === 'admin' ? 'Admin' :
+ member.role === 'readonly' ? 'Read Only' : 'User'}
+ </Badge>
+ {/if}
+ </Table.Cell>
+ <Table.Cell>
+ <Badge variant="outline" class="bg-green-50 text-green-700 border-green-200">
+ Active
+ </Badge>
+ </Table.Cell>
+ <Table.Cell>
+ {#if canRemoveMember(member)}
+ <Button
+ variant="ghost"
+ size="icon"
+ onclick={() => memberToRemove = member}
+ >
+ <Trash2 class="h-4 w-4 text-destructive" />
+ </Button>
+ {/if}
+ </Table.Cell>
+ </Table.Row>
+ {/each}
+ </Table.Body>
+ </Table.Root>
+ </CardContent>
+ </Card>
+
+ {#if invitations.length > 0}
+ <Card class="pb-0">
+ <CardHeader>
+ <CardTitle>Pending Invitations</CardTitle>
+ <CardDescription>Invitations that have not yet been accepted</CardDescription>
+ </CardHeader>
+ <CardContent class="p-0">
+ <Table.Root>
+ <Table.Header>
+ <Table.Row class="hover:bg-transparent">
+ <Table.Head>Email</Table.Head>
+ <Table.Head>Role</Table.Head>
+ <Table.Head>Invited By</Table.Head>
+ <Table.Head>Status</Table.Head>
+ <Table.Head class="w-[100px]"></Table.Head>
+ </Table.Row>
+ </Table.Header>
+ <Table.Body>
+ {#each invitations as invitation}
+ <Table.Row>
+ <Table.Cell class="font-medium">{invitation.email}</Table.Cell>
+ <Table.Cell>
+ <Badge variant="outline">
+ {invitation.role === 'admin' ? 'Admin' :
+ invitation.role === 'readonly' ? 'Read Only' : 'User'}
+ </Badge>
+ </Table.Cell>
+ <Table.Cell>{invitation.inviterName}</Table.Cell>
+ <Table.Cell>
+ <Badge variant="outline" class="bg-yellow-50 text-yellow-700 border-yellow-200">
+ Invited
+ </Badge>
+ </Table.Cell>
+ <Table.Cell>
+ <Button
+ variant="ghost"
+ size="icon"
+ onclick={() => invitationToRevoke = invitation}
+ >
+ <Trash2 class="h-4 w-4 text-destructive" />
+ </Button>
+ </Table.Cell>
+ </Table.Row>
+ {/each}
+ </Table.Body>
+ </Table.Root>
+ </CardContent>
+ </Card>
+ {/if}
+</div>
+
+<InviteUserDialog
+ bind:open={showInviteDialog}
+ {organizationId}
+/>
+
+<AlertDialog.Root open={memberToRemove !== null} onOpenChange={(open) => { if (!open) memberToRemove = null; }}>
+ <AlertDialog.Content>
+ <AlertDialog.Header>
+ <AlertDialog.Title>Remove Team Member</AlertDialog.Title>
+ <AlertDialog.Description>
+ Are you sure you want to remove {memberToRemove?.name} from this organization?
+ They will lose access to all projects.
+ </AlertDialog.Description>
+ </AlertDialog.Header>
+ <AlertDialog.Footer>
+ <AlertDialog.Cancel>Cancel</AlertDialog.Cancel>
+ <AlertDialog.Action onclick={handleRemoveMember}>
+ Remove
+ </AlertDialog.Action>
+ </AlertDialog.Footer>
+ </AlertDialog.Content>
+</AlertDialog.Root>
+
+<AlertDialog.Root open={invitationToRevoke !== null} onOpenChange={(open) => { if (!open) invitationToRevoke = null; }}>
+ <AlertDialog.Content>
+ <AlertDialog.Header>
+ <AlertDialog.Title>Revoke Invitation</AlertDialog.Title>
+ <AlertDialog.Description>
+ Are you sure you want to revoke the invitation for {invitationToRevoke?.email}?
+ </AlertDialog.Description>
+ </AlertDialog.Header>
+ <AlertDialog.Footer>
+ <AlertDialog.Cancel>Cancel</AlertDialog.Cancel>
+ <AlertDialog.Action onclick={handleRevokeInvitation}>
+ Revoke
+ </AlertDialog.Action>
+ </AlertDialog.Footer>
+ </AlertDialog.Content>
+</AlertDialog.Root>