first commit

This commit is contained in:
2025-09-12 12:38:11 +02:00
commit 0db2fd0314
46 changed files with 23221 additions and 0 deletions

208
backend/api/auth.go Normal file
View File

@@ -0,0 +1,208 @@
package api
import (
"net/http"
"project-dashboard/api/utils"
"project-dashboard/middleware"
"project-dashboard/models"
"github.com/gin-gonic/gin"
)
type LoginRequest struct {
Email string `json:"email" binding:"required,email"`
Password string `json:"password" binding:"required"`
}
type RegisterRequest struct {
Email string `json:"email" binding:"required,email"`
Password string `json:"password" binding:"required,min=6"`
FirstName string `json:"first_name" binding:"required"`
LastName string `json:"last_name" binding:"required"`
}
type AuthResponse struct {
Token string `json:"token"`
User models.User `json:"user"`
}
// Register creates a new user account
func Register(c *gin.Context) {
var req RegisterRequest
if err := c.ShouldBindJSON(&req); err != nil {
utils.ValidationErrorResponse(c, gin.H{
"error": err.Error(),
})
return
}
// Check if user already exists
var existingUser models.User
if err := models.GetDB().Where("email = ?", req.Email).First(&existingUser).Error; err == nil {
utils.ErrorResponse(c, http.StatusConflict, "User with this email already exists")
return
}
// Create new user
user := models.User{
Email: req.Email,
FirstName: req.FirstName,
LastName: req.LastName,
Role: "member", // Default role
}
// Hash password
if err := user.HashPassword(req.Password); err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to hash password")
return
}
// Save user to database
if err := models.GetDB().Create(&user).Error; err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to create user")
return
}
// Generate token
token, err := middleware.GenerateToken(&user)
if err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to generate token")
return
}
utils.SuccessResponse(c, http.StatusCreated, "User created successfully", AuthResponse{
Token: token,
User: user,
})
}
// Login authenticates a user
func Login(c *gin.Context) {
var req LoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
utils.ValidationErrorResponse(c, gin.H{
"error": err.Error(),
})
return
}
// Find user by email
var user models.User
if err := models.GetDB().Where("email = ?", req.Email).First(&user).Error; err != nil {
utils.ErrorResponse(c, http.StatusUnauthorized, "Invalid email or password")
return
}
// Check password
if !user.CheckPassword(req.Password) {
utils.ErrorResponse(c, http.StatusUnauthorized, "Invalid email or password")
return
}
// Generate token
token, err := middleware.GenerateToken(&user)
if err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to generate token")
return
}
utils.SuccessResponse(c, http.StatusOK, "Login successful", AuthResponse{
Token: token,
User: user,
})
}
// GetProfile returns the current user's profile
func GetProfile(c *gin.Context) {
user, exists := c.Get("user")
if !exists {
utils.ErrorResponse(c, http.StatusUnauthorized, "User not authenticated")
return
}
utils.SuccessResponse(c, http.StatusOK, "Profile retrieved successfully", user)
}
// UpdateProfile updates the current user's profile
func UpdateProfile(c *gin.Context) {
user, exists := c.Get("user")
if !exists {
utils.ErrorResponse(c, http.StatusUnauthorized, "User not authenticated")
return
}
userObj := user.(*models.User)
var updateData struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Avatar string `json:"avatar"`
}
if err := c.ShouldBindJSON(&updateData); err != nil {
utils.ValidationErrorResponse(c, gin.H{
"error": err.Error(),
})
return
}
// Update fields
if updateData.FirstName != "" {
userObj.FirstName = updateData.FirstName
}
if updateData.LastName != "" {
userObj.LastName = updateData.LastName
}
if updateData.Avatar != "" {
userObj.Avatar = updateData.Avatar
}
if err := models.GetDB().Save(userObj).Error; err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to update profile")
return
}
utils.SuccessResponse(c, http.StatusOK, "Profile updated successfully", userObj)
}
// ChangePassword changes the user's password
func ChangePassword(c *gin.Context) {
user, exists := c.Get("user")
if !exists {
utils.ErrorResponse(c, http.StatusUnauthorized, "User not authenticated")
return
}
userObj := user.(*models.User)
var req struct {
CurrentPassword string `json:"current_password" binding:"required"`
NewPassword string `json:"new_password" binding:"required,min=6"`
}
if err := c.ShouldBindJSON(&req); err != nil {
utils.ValidationErrorResponse(c, gin.H{
"error": err.Error(),
})
return
}
// Verify current password
if !userObj.CheckPassword(req.CurrentPassword) {
utils.ErrorResponse(c, http.StatusBadRequest, "Current password is incorrect")
return
}
// Hash new password
if err := userObj.HashPassword(req.NewPassword); err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to hash new password")
return
}
if err := models.GetDB().Save(userObj).Error; err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to update password")
return
}
utils.SuccessResponse(c, http.StatusOK, "Password changed successfully", nil)
}

243
backend/api/files.go Normal file
View File

@@ -0,0 +1,243 @@
package api
import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"project-dashboard/api/utils"
"project-dashboard/models"
"strconv"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
// UploadFile handles file uploads
func UploadFile(c *gin.Context) {
user, exists := c.Get("user")
if !exists {
utils.ErrorResponse(c, http.StatusUnauthorized, "User not authenticated")
return
}
userObj := user.(*models.User)
project, _ := c.Get("project")
projectObj := project.(*models.Project)
// Get task ID if provided
taskIDStr := c.PostForm("task_id")
var taskID *uint
if taskIDStr != "" {
if id, err := strconv.ParseUint(taskIDStr, 10, 32); err == nil {
taskIDUint := uint(id)
taskID = &taskIDUint
}
}
// Get file from form
file, header, err := c.Request.FormFile("file")
if err != nil {
utils.ErrorResponse(c, http.StatusBadRequest, "No file provided")
return
}
defer file.Close()
// Validate file size (10MB limit)
const maxFileSize = 10 << 20 // 10MB
if header.Size > maxFileSize {
utils.ErrorResponse(c, http.StatusBadRequest, "File size too large (max 10MB)")
return
}
// Generate unique filename
ext := filepath.Ext(header.Filename)
fileName := uuid.New().String() + ext
// Create uploads directory if it doesn't exist
uploadDir := "./uploads"
if err := os.MkdirAll(uploadDir, 0755); err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to create upload directory")
return
}
// Save file
filePath := filepath.Join(uploadDir, fileName)
dst, err := os.Create(filePath)
if err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to create file")
return
}
defer dst.Close()
if _, err := io.Copy(dst, file); err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to save file")
return
}
// Get MIME type
mimeType := header.Header.Get("Content-Type")
if mimeType == "" {
mimeType = "application/octet-stream"
}
// Create file record
fileUpload := models.FileUpload{
FileName: fileName,
OriginalName: header.Filename,
FilePath: filePath,
FileSize: header.Size,
MimeType: mimeType,
UploadedByID: userObj.ID,
ProjectID: &projectObj.ID,
TaskID: taskID,
}
if err := models.GetDB().Create(&fileUpload).Error; err != nil {
// Clean up file if database save fails
os.Remove(filePath)
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to save file record")
return
}
// Load file with relationships
models.GetDB().
Preload("UploadedBy").
Preload("Project").
Preload("Task").
First(&fileUpload, fileUpload.ID)
utils.SuccessResponse(c, http.StatusCreated, "File uploaded successfully", fileUpload)
}
// GetFiles returns all files for a project
func GetFiles(c *gin.Context) {
project, exists := c.Get("project")
if !exists {
utils.ErrorResponse(c, http.StatusNotFound, "Project not found")
return
}
projectObj := project.(*models.Project)
var files []models.FileUpload
if err := models.GetDB().
Preload("UploadedBy").
Preload("Project").
Preload("Task").
Where("project_id = ?", projectObj.ID).
Order("created_at DESC").
Find(&files).Error; err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to fetch files")
return
}
utils.SuccessResponse(c, http.StatusOK, "Files retrieved successfully", files)
}
// GetTaskFiles returns all files for a specific task
func GetTaskFiles(c *gin.Context) {
project, _ := c.Get("project")
projectObj := project.(*models.Project)
taskID := c.Param("task_id")
if taskID == "" {
utils.ErrorResponse(c, http.StatusBadRequest, "Task ID required")
return
}
// Verify task exists and belongs to project
var task models.Task
if err := models.GetDB().
Where("id = ? AND project_id = ?", taskID, projectObj.ID).
First(&task).Error; err != nil {
utils.ErrorResponse(c, http.StatusNotFound, "Task not found")
return
}
var files []models.FileUpload
if err := models.GetDB().
Preload("UploadedBy").
Preload("Project").
Preload("Task").
Where("task_id = ?", taskID).
Order("created_at DESC").
Find(&files).Error; err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to fetch task files")
return
}
utils.SuccessResponse(c, http.StatusOK, "Task files retrieved successfully", files)
}
// DownloadFile serves a file for download
func DownloadFile(c *gin.Context) {
project, _ := c.Get("project")
projectObj := project.(*models.Project)
fileID := c.Param("file_id")
if fileID == "" {
utils.ErrorResponse(c, http.StatusBadRequest, "File ID required")
return
}
var fileUpload models.FileUpload
if err := models.GetDB().
Where("id = ? AND project_id = ?", fileID, projectObj.ID).
First(&fileUpload).Error; err != nil {
utils.ErrorResponse(c, http.StatusNotFound, "File not found")
return
}
// Check if file exists on disk
if _, err := os.Stat(fileUpload.FilePath); os.IsNotExist(err) {
utils.ErrorResponse(c, http.StatusNotFound, "File not found on disk")
return
}
// Set headers for file download
c.Header("Content-Description", "File Transfer")
c.Header("Content-Transfer-Encoding", "binary")
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileUpload.OriginalName))
c.Header("Content-Type", "application/octet-stream")
// Serve file
c.File(fileUpload.FilePath)
}
// DeleteFile deletes a file
func DeleteFile(c *gin.Context) {
project, _ := c.Get("project")
projectObj := project.(*models.Project)
fileID := c.Param("file_id")
if fileID == "" {
utils.ErrorResponse(c, http.StatusBadRequest, "File ID required")
return
}
var fileUpload models.FileUpload
if err := models.GetDB().
Where("id = ? AND project_id = ?", fileID, projectObj.ID).
First(&fileUpload).Error; err != nil {
utils.ErrorResponse(c, http.StatusNotFound, "File not found")
return
}
// Delete file from disk
if err := os.Remove(fileUpload.FilePath); err != nil {
// Log error but continue with database deletion
fmt.Printf("Failed to delete file from disk: %v\n", err)
}
// Delete file record from database
if err := models.GetDB().Delete(&fileUpload).Error; err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to delete file record")
return
}
utils.SuccessResponse(c, http.StatusOK, "File deleted successfully", nil)
}

312
backend/api/projects.go Normal file
View File

@@ -0,0 +1,312 @@
package api
import (
"net/http"
"project-dashboard/api/utils"
"project-dashboard/models"
"strconv"
"github.com/gin-gonic/gin"
)
type CreateProjectRequest struct {
Name string `json:"name" binding:"required"`
Description string `json:"description"`
Color string `json:"color"`
}
type UpdateProjectRequest struct {
Name string `json:"name"`
Description string `json:"description"`
Status string `json:"status"`
Color string `json:"color"`
}
type AddMemberRequest struct {
UserID uint `json:"user_id" binding:"required"`
Role string `json:"role"`
}
// CreateProject creates a new project
func CreateProject(c *gin.Context) {
user, exists := c.Get("user")
if !exists {
utils.ErrorResponse(c, http.StatusUnauthorized, "User not authenticated")
return
}
userObj := user.(*models.User)
var req CreateProjectRequest
if err := c.ShouldBindJSON(&req); err != nil {
utils.ValidationErrorResponse(c, gin.H{
"error": err.Error(),
})
return
}
project := models.Project{
Name: req.Name,
Description: req.Description,
Color: req.Color,
OwnerID: userObj.ID,
Status: "active",
}
if project.Color == "" {
project.Color = "#3b82f6"
}
if err := models.GetDB().Create(&project).Error; err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to create project")
return
}
// Add owner as project member
member := models.ProjectMember{
ProjectID: project.ID,
UserID: userObj.ID,
Role: "owner",
}
models.GetDB().Create(&member)
// Load project with relationships
models.GetDB().Preload("Owner").Preload("Members").First(&project, project.ID)
utils.SuccessResponse(c, http.StatusCreated, "Project created successfully", project)
}
// GetProjects returns all projects for the current user
func GetProjects(c *gin.Context) {
user, exists := c.Get("user")
if !exists {
utils.ErrorResponse(c, http.StatusUnauthorized, "User not authenticated")
return
}
userObj := user.(*models.User)
var projects []models.Project
// Get projects where user is owner or member
if err := models.GetDB().
Preload("Owner").
Preload("Members").
Where("owner_id = ? OR id IN (SELECT project_id FROM project_members WHERE user_id = ?)",
userObj.ID, userObj.ID).
Find(&projects).Error; err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to fetch projects")
return
}
utils.SuccessResponse(c, http.StatusOK, "Projects retrieved successfully", projects)
}
// GetProject returns a specific project
func GetProject(c *gin.Context) {
project, exists := c.Get("project")
if !exists {
utils.ErrorResponse(c, http.StatusNotFound, "Project not found")
return
}
projectObj := project.(*models.Project)
// Load additional relationships
models.GetDB().
Preload("Owner").
Preload("Members").
Preload("Tasks").
Preload("Files").
First(projectObj, projectObj.ID)
utils.SuccessResponse(c, http.StatusOK, "Project retrieved successfully", projectObj)
}
// UpdateProject updates a project
func UpdateProject(c *gin.Context) {
project, exists := c.Get("project")
if !exists {
utils.ErrorResponse(c, http.StatusNotFound, "Project not found")
return
}
projectObj := project.(*models.Project)
user, _ := c.Get("user")
userObj := user.(*models.User)
// Check if user is owner or manager
role := projectObj.GetMemberRole(userObj.ID)
if role != "owner" && role != "manager" {
utils.ErrorResponse(c, http.StatusForbidden, "Insufficient permissions")
return
}
var req UpdateProjectRequest
if err := c.ShouldBindJSON(&req); err != nil {
utils.ValidationErrorResponse(c, gin.H{
"error": err.Error(),
})
return
}
// Update fields
if req.Name != "" {
projectObj.Name = req.Name
}
if req.Description != "" {
projectObj.Description = req.Description
}
if req.Status != "" {
projectObj.Status = req.Status
}
if req.Color != "" {
projectObj.Color = req.Color
}
if err := models.GetDB().Save(projectObj).Error; err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to update project")
return
}
utils.SuccessResponse(c, http.StatusOK, "Project updated successfully", projectObj)
}
// DeleteProject deletes a project
func DeleteProject(c *gin.Context) {
project, exists := c.Get("project")
if !exists {
utils.ErrorResponse(c, http.StatusNotFound, "Project not found")
return
}
projectObj := project.(*models.Project)
user, _ := c.Get("user")
userObj := user.(*models.User)
// Only owner can delete project
if !projectObj.IsOwner(userObj.ID) {
utils.ErrorResponse(c, http.StatusForbidden, "Only project owner can delete project")
return
}
if err := models.GetDB().Delete(projectObj).Error; err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to delete project")
return
}
utils.SuccessResponse(c, http.StatusOK, "Project deleted successfully", nil)
}
// AddMember adds a member to the project
func AddMember(c *gin.Context) {
project, exists := c.Get("project")
if !exists {
utils.ErrorResponse(c, http.StatusNotFound, "Project not found")
return
}
projectObj := project.(*models.Project)
user, _ := c.Get("user")
userObj := user.(*models.User)
// Check if user has permission to add members
role := projectObj.GetMemberRole(userObj.ID)
if role != "owner" && role != "manager" {
utils.ErrorResponse(c, http.StatusForbidden, "Insufficient permissions")
return
}
var req AddMemberRequest
if err := c.ShouldBindJSON(&req); err != nil {
utils.ValidationErrorResponse(c, gin.H{
"error": err.Error(),
})
return
}
// Check if user exists
var targetUser models.User
if err := models.GetDB().First(&targetUser, req.UserID).Error; err != nil {
utils.ErrorResponse(c, http.StatusNotFound, "User not found")
return
}
// Check if user is already a member
if projectObj.HasMember(req.UserID) {
utils.ErrorResponse(c, http.StatusConflict, "User is already a member of this project")
return
}
// Set default role
if req.Role == "" {
req.Role = "member"
}
member := models.ProjectMember{
ProjectID: projectObj.ID,
UserID: req.UserID,
Role: req.Role,
}
if err := models.GetDB().Create(&member).Error; err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to add member")
return
}
// Load updated project
models.GetDB().Preload("Members").First(projectObj, projectObj.ID)
utils.SuccessResponse(c, http.StatusOK, "Member added successfully", projectObj)
}
// RemoveMember removes a member from the project
func RemoveMember(c *gin.Context) {
project, exists := c.Get("project")
if !exists {
utils.ErrorResponse(c, http.StatusNotFound, "Project not found")
return
}
projectObj := project.(*models.Project)
user, _ := c.Get("user")
userObj := user.(*models.User)
// Check if user has permission to remove members
role := projectObj.GetMemberRole(userObj.ID)
if role != "owner" && role != "manager" {
utils.ErrorResponse(c, http.StatusForbidden, "Insufficient permissions")
return
}
userIDStr := c.Param("user_id")
if userIDStr == "" {
utils.ErrorResponse(c, http.StatusBadRequest, "User ID required")
return
}
userID, err := strconv.ParseUint(userIDStr, 10, 32)
if err != nil {
utils.ErrorResponse(c, http.StatusBadRequest, "Invalid user ID")
return
}
// Check if user is a member
if !projectObj.HasMember(uint(userID)) {
utils.ErrorResponse(c, http.StatusNotFound, "User is not a member of this project")
return
}
// Remove member
if err := models.GetDB().
Where("project_id = ? AND user_id = ?", projectObj.ID, uint(userID)).
Delete(&models.ProjectMember{}).Error; err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to remove member")
return
}
// Load updated project
models.GetDB().Preload("Members").First(projectObj, projectObj.ID)
utils.SuccessResponse(c, http.StatusOK, "Member removed successfully", projectObj)
}

359
backend/api/tasks.go Normal file
View File

@@ -0,0 +1,359 @@
package api
import (
"net/http"
"project-dashboard/api/utils"
"project-dashboard/models"
"time"
"github.com/gin-gonic/gin"
)
type CreateTaskRequest struct {
Title string `json:"title" binding:"required"`
Description string `json:"description"`
Priority string `json:"priority"`
DueDate string `json:"due_date"`
AssignedToID *uint `json:"assigned_to_id"`
}
type UpdateTaskRequest struct {
Title string `json:"title"`
Description string `json:"description"`
Status string `json:"status"`
Priority string `json:"priority"`
DueDate string `json:"due_date"`
AssignedToID *uint `json:"assigned_to_id"`
Position *int `json:"position"`
}
type CreateSubtaskRequest struct {
Title string `json:"title" binding:"required"`
Description string `json:"description"`
AssignedToID *uint `json:"assigned_to_id"`
}
type CreateCommentRequest struct {
Content string `json:"content" binding:"required"`
}
// CreateTask creates a new task
func CreateTask(c *gin.Context) {
user, exists := c.Get("user")
if !exists {
utils.ErrorResponse(c, http.StatusUnauthorized, "User not authenticated")
return
}
userObj := user.(*models.User)
project, _ := c.Get("project")
projectObj := project.(*models.Project)
var req CreateTaskRequest
if err := c.ShouldBindJSON(&req); err != nil {
utils.ValidationErrorResponse(c, gin.H{
"error": err.Error(),
})
return
}
task := models.Task{
Title: req.Title,
Description: req.Description,
Priority: req.Priority,
ProjectID: projectObj.ID,
CreatedByID: userObj.ID,
AssignedToID: req.AssignedToID,
Status: "todo",
}
if task.Priority == "" {
task.Priority = "medium"
}
// Parse due date if provided
if req.DueDate != "" {
if dueDate, err := time.Parse("2006-01-02T15:04:05Z07:00", req.DueDate); err == nil {
task.DueDate = &dueDate
}
}
if err := models.GetDB().Create(&task).Error; err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to create task")
return
}
// Load task with relationships
models.GetDB().
Preload("Project").
Preload("AssignedTo").
Preload("CreatedBy").
First(&task, task.ID)
utils.SuccessResponse(c, http.StatusCreated, "Task created successfully", task)
}
// GetTasks returns all tasks for a project
func GetTasks(c *gin.Context) {
project, exists := c.Get("project")
if !exists {
utils.ErrorResponse(c, http.StatusNotFound, "Project not found")
return
}
projectObj := project.(*models.Project)
var tasks []models.Task
if err := models.GetDB().
Preload("AssignedTo").
Preload("CreatedBy").
Preload("Comments").
Preload("Files").
Preload("Subtasks").
Preload("Labels").
Where("project_id = ?", projectObj.ID).
Order("position ASC, created_at DESC").
Find(&tasks).Error; err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to fetch tasks")
return
}
utils.SuccessResponse(c, http.StatusOK, "Tasks retrieved successfully", tasks)
}
// GetTask returns a specific task
func GetTask(c *gin.Context) {
project, _ := c.Get("project")
projectObj := project.(*models.Project)
taskID := c.Param("task_id")
if taskID == "" {
utils.ErrorResponse(c, http.StatusBadRequest, "Task ID required")
return
}
var task models.Task
if err := models.GetDB().
Preload("Project").
Preload("AssignedTo").
Preload("CreatedBy").
Preload("Comments").
Preload("Comments.User").
Preload("Files").
Preload("Subtasks").
Preload("Subtasks.AssignedTo").
Preload("Labels").
Where("id = ? AND project_id = ?", taskID, projectObj.ID).
First(&task).Error; err != nil {
utils.ErrorResponse(c, http.StatusNotFound, "Task not found")
return
}
utils.SuccessResponse(c, http.StatusOK, "Task retrieved successfully", task)
}
// UpdateTask updates a task
func UpdateTask(c *gin.Context) {
project, _ := c.Get("project")
projectObj := project.(*models.Project)
taskID := c.Param("task_id")
if taskID == "" {
utils.ErrorResponse(c, http.StatusBadRequest, "Task ID required")
return
}
var task models.Task
if err := models.GetDB().
Where("id = ? AND project_id = ?", taskID, projectObj.ID).
First(&task).Error; err != nil {
utils.ErrorResponse(c, http.StatusNotFound, "Task not found")
return
}
var req UpdateTaskRequest
if err := c.ShouldBindJSON(&req); err != nil {
utils.ValidationErrorResponse(c, gin.H{
"error": err.Error(),
})
return
}
// Update fields
if req.Title != "" {
task.Title = req.Title
}
if req.Description != "" {
task.Description = req.Description
}
if req.Status != "" {
task.Status = req.Status
if req.Status == "done" {
task.MarkAsCompleted()
}
}
if req.Priority != "" {
task.Priority = req.Priority
}
if req.AssignedToID != nil {
task.AssignedToID = req.AssignedToID
}
if req.Position != nil {
task.Position = *req.Position
}
// Parse due date if provided
if req.DueDate != "" {
if dueDate, err := time.Parse("2006-01-02T15:04:05Z07:00", req.DueDate); err == nil {
task.DueDate = &dueDate
}
}
if err := models.GetDB().Save(&task).Error; err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to update task")
return
}
// Load updated task with relationships
models.GetDB().
Preload("AssignedTo").
Preload("CreatedBy").
Preload("Comments").
Preload("Files").
Preload("Subtasks").
Preload("Labels").
First(&task, task.ID)
utils.SuccessResponse(c, http.StatusOK, "Task updated successfully", task)
}
// DeleteTask deletes a task
func DeleteTask(c *gin.Context) {
project, _ := c.Get("project")
projectObj := project.(*models.Project)
taskID := c.Param("task_id")
if taskID == "" {
utils.ErrorResponse(c, http.StatusBadRequest, "Task ID required")
return
}
var task models.Task
if err := models.GetDB().
Where("id = ? AND project_id = ?", taskID, projectObj.ID).
First(&task).Error; err != nil {
utils.ErrorResponse(c, http.StatusNotFound, "Task not found")
return
}
if err := models.GetDB().Delete(&task).Error; err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to delete task")
return
}
utils.SuccessResponse(c, http.StatusOK, "Task deleted successfully", nil)
}
// CreateSubtask creates a new subtask
func CreateSubtask(c *gin.Context) {
project, _ := c.Get("project")
projectObj := project.(*models.Project)
taskID := c.Param("task_id")
if taskID == "" {
utils.ErrorResponse(c, http.StatusBadRequest, "Task ID required")
return
}
// Verify task exists and belongs to project
var task models.Task
if err := models.GetDB().
Where("id = ? AND project_id = ?", taskID, projectObj.ID).
First(&task).Error; err != nil {
utils.ErrorResponse(c, http.StatusNotFound, "Task not found")
return
}
var req CreateSubtaskRequest
if err := c.ShouldBindJSON(&req); err != nil {
utils.ValidationErrorResponse(c, gin.H{
"error": err.Error(),
})
return
}
subtask := models.Subtask{
Title: req.Title,
Description: req.Description,
ParentTaskID: task.ID,
AssignedToID: req.AssignedToID,
Status: "todo",
}
if err := models.GetDB().Create(&subtask).Error; err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to create subtask")
return
}
// Load subtask with relationships
models.GetDB().
Preload("AssignedTo").
First(&subtask, subtask.ID)
utils.SuccessResponse(c, http.StatusCreated, "Subtask created successfully", subtask)
}
// AddComment adds a comment to a task
func AddComment(c *gin.Context) {
user, exists := c.Get("user")
if !exists {
utils.ErrorResponse(c, http.StatusUnauthorized, "User not authenticated")
return
}
userObj := user.(*models.User)
project, _ := c.Get("project")
projectObj := project.(*models.Project)
taskID := c.Param("task_id")
if taskID == "" {
utils.ErrorResponse(c, http.StatusBadRequest, "Task ID required")
return
}
// Verify task exists and belongs to project
var task models.Task
if err := models.GetDB().
Where("id = ? AND project_id = ?", taskID, projectObj.ID).
First(&task).Error; err != nil {
utils.ErrorResponse(c, http.StatusNotFound, "Task not found")
return
}
var req CreateCommentRequest
if err := c.ShouldBindJSON(&req); err != nil {
utils.ValidationErrorResponse(c, gin.H{
"error": err.Error(),
})
return
}
comment := models.Comment{
Content: req.Content,
TaskID: task.ID,
UserID: userObj.ID,
}
if err := models.GetDB().Create(&comment).Error; err != nil {
utils.ErrorResponse(c, http.StatusInternalServerError, "Failed to create comment")
return
}
// Load comment with user
models.GetDB().
Preload("User").
First(&comment, comment.ID)
utils.SuccessResponse(c, http.StatusCreated, "Comment added successfully", comment)
}

View File

@@ -0,0 +1,64 @@
package utils
import (
"net/http"
"github.com/gin-gonic/gin"
)
type APIResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
Error string `json:"error,omitempty"`
}
// SuccessResponse sends a successful response
func SuccessResponse(c *gin.Context, statusCode int, message string, data interface{}) {
c.JSON(statusCode, APIResponse{
Success: true,
Message: message,
Data: data,
})
}
// ErrorResponse sends an error response
func ErrorResponse(c *gin.Context, statusCode int, message string) {
c.JSON(statusCode, APIResponse{
Success: false,
Error: message,
})
}
// ValidationErrorResponse sends a validation error response
func ValidationErrorResponse(c *gin.Context, errors interface{}) {
c.JSON(http.StatusBadRequest, APIResponse{
Success: false,
Error: "Validation failed",
Data: errors,
})
}
// PaginatedResponse sends a paginated response
type PaginatedResponse struct {
Data interface{} `json:"data"`
Pagination Pagination `json:"pagination"`
}
type Pagination struct {
Page int `json:"page"`
PerPage int `json:"per_page"`
Total int64 `json:"total"`
TotalPages int `json:"total_pages"`
}
func PaginatedSuccessResponse(c *gin.Context, message string, data interface{}, pagination Pagination) {
c.JSON(http.StatusOK, APIResponse{
Success: true,
Message: message,
Data: PaginatedResponse{
Data: data,
Pagination: pagination,
},
})
}

138
backend/cmd/server/main.go Normal file
View File

@@ -0,0 +1,138 @@
package main
import (
"log"
"project-dashboard/api"
"project-dashboard/middleware"
"project-dashboard/models"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func main() {
// Initialize database
models.InitDB()
defer models.CloseDB()
// Create default admin user if not exists
createDefaultAdmin()
// Set Gin mode
gin.SetMode(gin.ReleaseMode)
// Create Gin router
r := gin.Default()
// Configure CORS
config := cors.DefaultConfig()
config.AllowOrigins = []string{"http://localhost:3000", "http://localhost:3001"}
config.AllowMethods = []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}
config.AllowHeaders = []string{"Origin", "Content-Type", "Accept", "Authorization", "X-Requested-With"}
config.AllowCredentials = true
r.Use(cors.New(config))
// Serve static files
r.Static("/uploads", "./uploads")
// Health check endpoint
r.GET("/health", func(c *gin.Context) {
c.JSON(200, gin.H{
"status": "ok",
"message": "Project Dashboard API is running",
})
})
// API routes
v1 := r.Group("/api/v1")
{
// Authentication routes
auth := v1.Group("/auth")
{
auth.POST("/register", api.Register)
auth.POST("/login", api.Login)
auth.GET("/profile", middleware.AuthMiddleware(), api.GetProfile)
auth.PUT("/profile", middleware.AuthMiddleware(), api.UpdateProfile)
auth.PUT("/change-password", middleware.AuthMiddleware(), api.ChangePassword)
}
// Project routes
projects := v1.Group("/projects")
projects.Use(middleware.AuthMiddleware())
{
projects.POST("", api.CreateProject)
projects.GET("", api.GetProjects)
// Project-specific routes
project := projects.Group("/:project_id")
project.Use(middleware.ProjectAccessMiddleware())
{
project.GET("", api.GetProject)
project.PUT("", api.UpdateProject)
project.DELETE("", api.DeleteProject)
// Project members
project.POST("/members", api.AddMember)
project.DELETE("/members/:user_id", api.RemoveMember)
// Tasks
project.POST("/tasks", api.CreateTask)
project.GET("/tasks", api.GetTasks)
task := project.Group("/tasks/:task_id")
{
task.GET("", api.GetTask)
task.PUT("", api.UpdateTask)
task.DELETE("", api.DeleteTask)
// Task comments
task.POST("/comments", api.AddComment)
// Task subtasks
task.POST("/subtasks", api.CreateSubtask)
}
// Files
project.POST("/files", api.UploadFile)
project.GET("/files", api.GetFiles)
file := project.Group("/files/:file_id")
{
file.GET("", api.DownloadFile)
file.DELETE("", api.DeleteFile)
}
}
}
}
// Start server
log.Println("Starting server on :8080")
if err := r.Run(":8080"); err != nil {
log.Fatal("Failed to start server:", err)
}
}
func createDefaultAdmin() {
var admin models.User
if err := models.GetDB().Where("email = ?", "admin@example.com").First(&admin).Error; err != nil {
// Create default admin user
admin = models.User{
Email: "admin@example.com",
FirstName: "Admin",
LastName: "User",
Role: "admin",
}
if err := admin.HashPassword("admin123"); err != nil {
log.Printf("Failed to hash admin password: %v", err)
return
}
if err := models.GetDB().Create(&admin).Error; err != nil {
log.Printf("Failed to create admin user: %v", err)
return
}
log.Println("Default admin user created: admin@example.com / admin123")
}
}

43
backend/go.mod Normal file
View File

@@ -0,0 +1,43 @@
module project-dashboard
go 1.23.0
toolchain go1.24.7
require (
github.com/bytedance/sonic v1.13.3 // indirect
github.com/bytedance/sonic/loader v0.2.4 // indirect
github.com/cloudwego/base64x v0.1.5 // indirect
github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect
github.com/gabriel-vasile/mimetype v1.4.9 // indirect
github.com/gin-contrib/cors v1.7.6 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/gin-gonic/gin v1.10.1 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.26.0 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/jinzhu/gorm v1.9.16 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.10 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-sqlite3 v1.14.22 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.0 // indirect
golang.org/x/arch v0.18.0 // indirect
golang.org/x/crypto v0.39.0 // indirect
golang.org/x/net v0.41.0 // indirect
golang.org/x/sys v0.33.0 // indirect
golang.org/x/text v0.26.0 // indirect
google.golang.org/protobuf v1.36.6 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
gorm.io/driver/sqlite v1.6.0 // indirect
gorm.io/gorm v1.31.0 // indirect
)

111
backend/go.sum Normal file
View File

@@ -0,0 +1,111 @@
github.com/PuerkitoBio/goquery v1.5.1/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc=
github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y=
github.com/bytedance/sonic v1.13.3 h1:MS8gmaH16Gtirygw7jV91pDCN33NyMrPbN7qiYhEsF0=
github.com/bytedance/sonic v1.13.3/go.mod h1:o68xyaF9u2gvVBuGHPlUVCy+ZfmNNO5ETf1+KgkJhz4=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/bytedance/sonic/loader v0.2.4 h1:ZWCw4stuXUsn1/+zQDqeE7JKP+QO47tz7QCNan80NzY=
github.com/bytedance/sonic/loader v0.2.4/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
github.com/cloudwego/base64x v0.1.5 h1:XPciSp1xaq2VCSt6lF0phncD4koWyULpl5bUxbfCyP4=
github.com/cloudwego/base64x v0.1.5/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0=
github.com/gabriel-vasile/mimetype v1.4.9 h1:5k+WDwEsD9eTLL8Tz3L0VnmVh9QxGjRmjBvAG7U/oYY=
github.com/gabriel-vasile/mimetype v1.4.9/go.mod h1:WnSQhFKJuBlRyLiKohA/2DtIlPFAbguNaG7QCHcyGok=
github.com/gin-contrib/cors v1.7.6 h1:3gQ8GMzs1Ylpf70y8bMw4fVpycXIeX1ZemuSQIsnQQY=
github.com/gin-contrib/cors v1.7.6/go.mod h1:Ulcl+xN4jel9t1Ry8vqph23a60FwH9xVLd+3ykmTjOk=
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
github.com/gin-gonic/gin v1.10.1 h1:T0ujvqyCSqRopADpgPgiTT63DUQVSfojyME59Ei63pQ=
github.com/gin-gonic/gin v1.10.1/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.26.0 h1:SP05Nqhjcvz81uJaRfEV0YBSSSGMc/iMaVtFbr3Sw2k=
github.com/go-playground/validator/v10 v10.26.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jinzhu/gorm v1.9.16 h1:+IyIjPEABKRpsu/F8OvDPy9fyQlgsg2luMV2ZIH5i5o=
github.com/jinzhu/gorm v1.9.16/go.mod h1:G3LB3wezTOWM2ITLzPxEXgSkOXAntiLHS7UdBefADcs=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
golang.org/x/arch v0.18.0 h1:WN9poc33zL4AzGxqf8VtpKUnGvMi8O9lhNyBMF/85qc=
golang.org/x/arch v0.18.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM=
golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U=
golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw=
golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
gorm.io/gorm v1.31.0 h1:0VlycGreVhK7RF/Bwt51Fk8v0xLiiiFdbGDPIZQ7mJY=
gorm.io/gorm v1.31.0/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=

BIN
backend/main Executable file

Binary file not shown.

158
backend/middleware/auth.go Normal file
View File

@@ -0,0 +1,158 @@
package middleware
import (
"net/http"
"project-dashboard/api/utils"
"project-dashboard/models"
"strings"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
)
type Claims struct {
UserID uint `json:"user_id"`
Email string `json:"email"`
Role string `json:"role"`
jwt.StandardClaims
}
var jwtSecret = []byte("your-secret-key") // In production, use environment variable
// GenerateToken generates a JWT token for the user
func GenerateToken(user *models.User) (string, error) {
claims := Claims{
UserID: user.ID,
Email: user.Email,
Role: user.Role,
StandardClaims: jwt.StandardClaims{
ExpiresAt: 15000, // 24 hours
Issuer: "project-dashboard",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(jwtSecret)
}
// AuthMiddleware validates JWT token
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
utils.ErrorResponse(c, http.StatusUnauthorized, "Authorization header required")
c.Abort()
return
}
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
if tokenString == authHeader {
utils.ErrorResponse(c, http.StatusUnauthorized, "Invalid authorization header format")
c.Abort()
return
}
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return jwtSecret, nil
})
if err != nil || !token.Valid {
utils.ErrorResponse(c, http.StatusUnauthorized, "Invalid token")
c.Abort()
return
}
// Get user from database
var user models.User
if err := models.GetDB().First(&user, claims.UserID).Error; err != nil {
utils.ErrorResponse(c, http.StatusUnauthorized, "User not found")
c.Abort()
return
}
c.Set("user", &user)
c.Set("user_id", user.ID)
c.Next()
}
}
// AdminMiddleware ensures user has admin role
func AdminMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
user, exists := c.Get("user")
if !exists {
utils.ErrorResponse(c, http.StatusUnauthorized, "User not authenticated")
c.Abort()
return
}
userObj := user.(*models.User)
if !userObj.IsAdmin() {
utils.ErrorResponse(c, http.StatusForbidden, "Admin access required")
c.Abort()
return
}
c.Next()
}
}
// ManagerMiddleware ensures user has manager role or higher
func ManagerMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
user, exists := c.Get("user")
if !exists {
utils.ErrorResponse(c, http.StatusUnauthorized, "User not authenticated")
c.Abort()
return
}
userObj := user.(*models.User)
if !userObj.IsManager() {
utils.ErrorResponse(c, http.StatusForbidden, "Manager access required")
c.Abort()
return
}
c.Next()
}
}
// ProjectAccessMiddleware ensures user has access to the project
func ProjectAccessMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
user, exists := c.Get("user")
if !exists {
utils.ErrorResponse(c, http.StatusUnauthorized, "User not authenticated")
c.Abort()
return
}
userObj := user.(*models.User)
projectID := c.Param("project_id")
if projectID == "" {
utils.ErrorResponse(c, http.StatusBadRequest, "Project ID required")
c.Abort()
return
}
var project models.Project
if err := models.GetDB().Preload("Members").First(&project, projectID).Error; err != nil {
utils.ErrorResponse(c, http.StatusNotFound, "Project not found")
c.Abort()
return
}
// Check if user is owner or member
if !project.IsOwner(userObj.ID) && !project.HasMember(userObj.ID) {
utils.ErrorResponse(c, http.StatusForbidden, "Access denied to project")
c.Abort()
return
}
c.Set("project", &project)
c.Next()
}
}

View File

@@ -0,0 +1,51 @@
package models
import (
"log"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
var db *gorm.DB
// InitDB initializes the database connection
func InitDB() {
var err error
db, err = gorm.Open(sqlite.Open("project_dashboard.db"), &gorm.Config{})
if err != nil {
log.Fatal("Failed to connect to database:", err)
}
// Auto-migrate the schema
err = db.AutoMigrate(
&User{},
&Project{},
&ProjectMember{},
&Task{},
&Subtask{},
&Label{},
&Comment{},
&FileUpload{},
)
if err != nil {
log.Fatal("Failed to migrate database:", err)
}
log.Println("Database connected and migrated successfully")
}
// GetDB returns the database instance
func GetDB() *gorm.DB {
return db
}
// CloseDB closes the database connection
func CloseDB() {
sqlDB, err := db.DB()
if err != nil {
log.Printf("Error getting database instance: %v", err)
return
}
sqlDB.Close()
}

102
backend/models/file.go Normal file
View File

@@ -0,0 +1,102 @@
package models
import (
"fmt"
"time"
"gorm.io/gorm"
)
type FileUpload struct {
ID uint `json:"id" gorm:"primaryKey"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
FileName string `json:"file_name" gorm:"not null"`
OriginalName string `json:"original_name" gorm:"not null"`
FilePath string `json:"file_path" gorm:"not null"`
FileSize int64 `json:"file_size" gorm:"not null"`
MimeType string `json:"mime_type" gorm:"not null"`
Description string `json:"description"`
// Foreign Keys
UploadedByID uint `json:"uploaded_by_id" gorm:"not null"`
ProjectID *uint `json:"project_id"`
TaskID *uint `json:"task_id"`
// Relationships
UploadedBy User `json:"uploaded_by" gorm:"foreignKey:UploadedByID"`
Project *Project `json:"project" gorm:"foreignKey:ProjectID"`
Task *Task `json:"task" gorm:"foreignKey:TaskID"`
}
// GetFileExtension returns the file extension
func (f *FileUpload) GetFileExtension() string {
if len(f.OriginalName) == 0 {
return ""
}
lastDot := -1
for i := len(f.OriginalName) - 1; i >= 0; i-- {
if f.OriginalName[i] == '.' {
lastDot = i
break
}
}
if lastDot == -1 {
return ""
}
return f.OriginalName[lastDot:]
}
// IsImage checks if the file is an image
func (f *FileUpload) IsImage() bool {
imageTypes := []string{
"image/jpeg", "image/jpg", "image/png", "image/gif",
"image/webp", "image/svg+xml", "image/bmp", "image/tiff",
}
for _, imgType := range imageTypes {
if f.MimeType == imgType {
return true
}
}
return false
}
// IsDocument checks if the file is a document
func (f *FileUpload) IsDocument() bool {
docTypes := []string{
"application/pdf", "application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.ms-powerpoint",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
"text/plain", "text/csv",
}
for _, docType := range docTypes {
if f.MimeType == docType {
return true
}
}
return false
}
// FormatFileSize returns a human-readable file size
func (f *FileUpload) FormatFileSize() string {
const unit = 1024
if f.FileSize < unit {
return fmt.Sprintf("%d B", f.FileSize)
}
div, exp := int64(unit), 0
for n := f.FileSize / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB", float64(f.FileSize)/float64(div), "KMGTPE"[exp])
}

79
backend/models/project.go Normal file
View File

@@ -0,0 +1,79 @@
package models
import (
"time"
"gorm.io/gorm"
)
type Project struct {
ID uint `json:"id" gorm:"primaryKey"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
Name string `json:"name" gorm:"not null"`
Description string `json:"description"`
Status string `json:"status" gorm:"default:'active'"` // active, completed, archived, on_hold
StartDate *time.Time `json:"start_date"`
EndDate *time.Time `json:"end_date"`
Color string `json:"color" gorm:"default:'#3b82f6'"` // Hex color for UI
// Foreign Keys
OwnerID uint `json:"owner_id" gorm:"not null"`
// Relationships
Owner User `json:"owner" gorm:"foreignKey:OwnerID"`
Members []User `json:"members" gorm:"many2many:project_members"`
Tasks []Task `json:"tasks" gorm:"foreignKey:ProjectID"`
Files []FileUpload `json:"files" gorm:"foreignKey:ProjectID"`
}
type ProjectMember struct {
ID uint `json:"id" gorm:"primaryKey"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
ProjectID uint `json:"project_id" gorm:"not null"`
UserID uint `json:"user_id" gorm:"not null"`
Role string `json:"role" gorm:"default:'member'"` // owner, manager, member
// Relationships
Project Project `json:"project" gorm:"foreignKey:ProjectID"`
User User `json:"user" gorm:"foreignKey:UserID"`
}
// IsOwner checks if the given user is the owner of this project
func (p *Project) IsOwner(userID uint) bool {
return p.OwnerID == userID
}
// HasMember checks if the given user is a member of this project
func (p *Project) HasMember(userID uint) bool {
for _, member := range p.Members {
if member.ID == userID {
return true
}
}
return false
}
// GetMemberRole returns the role of a member in this project
func (p *Project) GetMemberRole(userID uint) string {
if p.OwnerID == userID {
return "owner"
}
for _, member := range p.Members {
if member.ID == userID {
// Get role from ProjectMember table
var pm ProjectMember
if err := db.Where("project_id = ? AND user_id = ?", p.ID, userID).First(&pm).Error; err == nil {
return pm.Role
}
return "member"
}
}
return ""
}

125
backend/models/task.go Normal file
View File

@@ -0,0 +1,125 @@
package models
import (
"time"
"gorm.io/gorm"
)
type Task struct {
ID uint `json:"id" gorm:"primaryKey"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
Title string `json:"title" gorm:"not null"`
Description string `json:"description"`
Status string `json:"status" gorm:"default:'todo'"` // todo, in_progress, review, done
Priority string `json:"priority" gorm:"default:'medium'"` // low, medium, high, urgent
DueDate *time.Time `json:"due_date"`
CompletedAt *time.Time `json:"completed_at"`
Position int `json:"position" gorm:"default:0"` // For ordering in kanban board
// Foreign Keys
ProjectID uint `json:"project_id" gorm:"not null"`
AssignedToID *uint `json:"assigned_to_id"`
CreatedByID uint `json:"created_by_id" gorm:"not null"`
// Relationships
Project Project `json:"project" gorm:"foreignKey:ProjectID"`
AssignedTo *User `json:"assigned_to" gorm:"foreignKey:AssignedToID"`
CreatedBy User `json:"created_by" gorm:"foreignKey:CreatedByID"`
Comments []Comment `json:"comments" gorm:"foreignKey:TaskID"`
Files []FileUpload `json:"files" gorm:"foreignKey:TaskID"`
Subtasks []Subtask `json:"subtasks" gorm:"foreignKey:ParentTaskID"`
Labels []Label `json:"labels" gorm:"many2many:task_labels"`
}
type Subtask struct {
ID uint `json:"id" gorm:"primaryKey"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
Title string `json:"title" gorm:"not null"`
Description string `json:"description"`
Status string `json:"status" gorm:"default:'todo'"` // todo, in_progress, done
Position int `json:"position" gorm:"default:0"`
CompletedAt *time.Time `json:"completed_at"`
// Foreign Keys
ParentTaskID uint `json:"parent_task_id" gorm:"not null"`
AssignedToID *uint `json:"assigned_to_id"`
// Relationships
ParentTask Task `json:"parent_task" gorm:"foreignKey:ParentTaskID"`
AssignedTo *User `json:"assigned_to" gorm:"foreignKey:AssignedToID"`
}
type Label struct {
ID uint `json:"id" gorm:"primaryKey"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
Name string `json:"name" gorm:"not null"`
Color string `json:"color" gorm:"default:'#6b7280'"` // Hex color
// Foreign Keys
ProjectID uint `json:"project_id" gorm:"not null"`
// Relationships
Project Project `json:"project" gorm:"foreignKey:ProjectID"`
Tasks []Task `json:"tasks" gorm:"many2many:task_labels"`
}
type Comment struct {
ID uint `json:"id" gorm:"primaryKey"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
Content string `json:"content" gorm:"not null"`
// Foreign Keys
TaskID uint `json:"task_id" gorm:"not null"`
UserID uint `json:"user_id" gorm:"not null"`
// Relationships
Task Task `json:"task" gorm:"foreignKey:TaskID"`
User User `json:"user" gorm:"foreignKey:UserID"`
}
// IsOverdue checks if the task is overdue
func (t *Task) IsOverdue() bool {
if t.DueDate == nil {
return false
}
return t.Status != "done" && t.DueDate.Before(time.Now())
}
// GetCompletionPercentage returns the completion percentage based on subtasks
func (t *Task) GetCompletionPercentage() int {
if len(t.Subtasks) == 0 {
if t.Status == "done" {
return 100
}
return 0
}
completed := 0
for _, subtask := range t.Subtasks {
if subtask.Status == "done" {
completed++
}
}
return (completed * 100) / len(t.Subtasks)
}
// MarkAsCompleted marks the task as completed
func (t *Task) MarkAsCompleted() {
t.Status = "done"
now := time.Now()
t.CompletedAt = &now
}

60
backend/models/user.go Normal file
View File

@@ -0,0 +1,60 @@
package models
import (
"time"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
type User struct {
ID uint `json:"id" gorm:"primaryKey"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
Email string `json:"email" gorm:"uniqueIndex;not null"`
Password string `json:"-" gorm:"not null"` // Hidden from JSON
FirstName string `json:"first_name" gorm:"not null"`
LastName string `json:"last_name" gorm:"not null"`
Avatar string `json:"avatar"`
Role string `json:"role" gorm:"default:'member'"` // admin, manager, member
// Relationships
Projects []Project `json:"projects" gorm:"many2many:project_members"`
OwnedProjects []Project `json:"owned_projects" gorm:"foreignKey:OwnerID"`
Tasks []Task `json:"tasks" gorm:"foreignKey:AssignedToID"`
Comments []Comment `json:"comments" gorm:"foreignKey:UserID"`
FileUploads []FileUpload `json:"file_uploads" gorm:"foreignKey:UploadedByID"`
}
// HashPassword hashes the user's password
func (u *User) HashPassword(password string) error {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return err
}
u.Password = string(hashedPassword)
return nil
}
// CheckPassword checks if the provided password matches the user's password
func (u *User) CheckPassword(password string) bool {
err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
return err == nil
}
// GetFullName returns the user's full name
func (u *User) GetFullName() string {
return u.FirstName + " " + u.LastName
}
// IsAdmin checks if the user has admin role
func (u *User) IsAdmin() bool {
return u.Role == "admin"
}
// IsManager checks if the user has manager role or higher
func (u *User) IsManager() bool {
return u.Role == "manager" || u.Role == "admin"
}

Binary file not shown.