Update documentation

This commit is contained in:
2024-11-28 21:53:03 +01:00
parent 51ed9e53a4
commit f5d616fe00
13 changed files with 53 additions and 205 deletions

View File

@@ -62,31 +62,17 @@ func NewJWTService(config JWTConfig) (JWTManager, error) {
return &jwtService{config: config}, nil
}
// GenerateAccessToken creates a new access token for a user
// Parameters:
// - userID: the ID of the user
// - role: the role of the user
// Returns the signed token string or an error
// GenerateAccessToken creates a new access token for a user with the given userID and role
func (s *jwtService) GenerateAccessToken(userID int, role string) (string, error) {
return s.generateToken(userID, role, AccessToken, s.config.AccessTokenExpiry)
}
// GenerateRefreshToken creates a new refresh token for a user
// Parameters:
// - userID: the ID of the user
// - role: the role of the user
// Returns the signed token string or an error
// GenerateRefreshToken creates a new refresh token for a user with the given userID and role
func (s *jwtService) GenerateRefreshToken(userID int, role string) (string, error) {
return s.generateToken(userID, role, RefreshToken, s.config.RefreshTokenExpiry)
}
// generateToken is an internal helper function that creates a new JWT token
// Parameters:
// - userID: the ID of the user
// - role: the role of the user
// - tokenType: the type of token (access or refresh)
// - expiry: how long the token should be valid
// Returns the signed token string or an error
func (s *jwtService) generateToken(userID int, role string, tokenType TokenType, expiry time.Duration) (string, error) {
now := time.Now()
@@ -113,9 +99,6 @@ func (s *jwtService) generateToken(userID int, role string, tokenType TokenType,
}
// ValidateToken validates and parses a JWT token
// Parameters:
// - tokenString: the token to validate
// Returns the token claims if valid, or an error if invalid
func (s *jwtService) ValidateToken(tokenString string) (*Claims, error) {
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
// Validate the signing method
@@ -136,10 +119,7 @@ func (s *jwtService) ValidateToken(tokenString string) (*Claims, error) {
return nil, fmt.Errorf("invalid token claims")
}
// RefreshAccessToken creates a new access token using a refresh token
// Parameters:
// - refreshToken: the refresh token to use
// Returns a new access token if the refresh token is valid, or an error
// RefreshAccessToken creates a new access token using a refreshToken
func (s *jwtService) RefreshAccessToken(refreshToken string) (string, error) {
claims, err := s.ValidateToken(refreshToken)
if err != nil {

View File

@@ -13,10 +13,6 @@ type Middleware struct {
}
// NewMiddleware creates a new authentication middleware
// Parameters:
// - jwtManager: the JWT manager to use for token operations
// Returns:
// - *Middleware: the new middleware instance
func NewMiddleware(jwtManager JWTManager) *Middleware {
return &Middleware{
jwtManager: jwtManager,
@@ -24,10 +20,6 @@ func NewMiddleware(jwtManager JWTManager) *Middleware {
}
// Authenticate middleware validates JWT tokens and sets user information in context
// Parameters:
// - next: the next handler to call
// Returns:
// - http.Handler: the handler function
func (m *Middleware) Authenticate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Extract token from Authorization header
@@ -69,10 +61,6 @@ func (m *Middleware) Authenticate(next http.Handler) http.Handler {
}
// RequireRole returns a middleware that ensures the user has the required role
// Parameters:
// - role: the required role
// Returns:
// - func(http.Handler) http.Handler: the middleware function
func (m *Middleware) RequireRole(role string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -92,10 +80,6 @@ func (m *Middleware) RequireRole(role string) func(http.Handler) http.Handler {
}
// RequireWorkspaceAccess returns a middleware that ensures the user has access to the workspace
// Parameters:
// - next: the next handler to call
// Returns:
// - http.Handler: the handler function
func (m *Middleware) RequireWorkspaceAccess(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, ok := context.GetRequestContext(w, r)

View File

@@ -15,10 +15,7 @@ type SessionService struct {
jwtManager JWTManager // JWT Manager for token operations
}
// NewSessionService creates a new session service
// Parameters:
// - db: database connection
// - jwtManager: JWT service for token operations
// NewSessionService creates a new session service with the given database and JWT manager
func NewSessionService(db db.SessionStore, jwtManager JWTManager) *SessionService {
return &SessionService{
db: db,
@@ -26,14 +23,7 @@ func NewSessionService(db db.SessionStore, jwtManager JWTManager) *SessionServic
}
}
// CreateSession creates a new user session
// Parameters:
// - userID: the ID of the user
// - role: the role of the user
// Returns:
// - session: the created session
// - accessToken: a new access token
// - error: any error that occurred
// CreateSession creates a new user session for a user with the given userID and role
func (s *SessionService) CreateSession(userID int, role string) (*models.Session, string, error) {
// Generate both access and refresh tokens
accessToken, err := s.jwtManager.GenerateAccessToken(userID, role)
@@ -69,12 +59,7 @@ func (s *SessionService) CreateSession(userID int, role string) (*models.Session
return session, accessToken, nil
}
// RefreshSession creates a new access token using a refresh token
// Parameters:
// - refreshToken: the refresh token to use
// Returns:
// - string: a new access token
// - error: any error that occurred
// RefreshSession creates a new access token using a refreshToken
func (s *SessionService) RefreshSession(refreshToken string) (string, error) {
// Get session from database first
session, err := s.db.GetSessionByRefreshToken(refreshToken)
@@ -97,18 +82,12 @@ func (s *SessionService) RefreshSession(refreshToken string) (string, error) {
return s.jwtManager.GenerateAccessToken(claims.UserID, claims.Role)
}
// InvalidateSession removes a session from the database
// Parameters:
// - sessionID: the ID of the session to invalidate
// Returns:
// - error: any error that occurred
// InvalidateSession removes a session with the given sessionID from the database
func (s *SessionService) InvalidateSession(sessionID string) error {
return s.db.DeleteSession(sessionID)
}
// CleanExpiredSessions removes all expired sessions from the database
// Returns:
// - error: any error that occurred
func (s *SessionService) CleanExpiredSessions() error {
return s.db.CleanExpiredSessions()
}

View File

@@ -38,7 +38,7 @@ func (db *database) CreateUser(user *models.User) (*models.User, error) {
UserID: user.ID,
Name: "Main",
}
defaultWorkspace.GetDefaultSettings() // Initialize default settings
defaultWorkspace.SetDefaultSettings() // Initialize default settings
// Create workspace with settings
err = db.createWorkspaceTx(tx, defaultWorkspace)

View File

@@ -10,7 +10,7 @@ import (
func (db *database) CreateWorkspace(workspace *models.Workspace) error {
// Set default settings if not provided
if workspace.Theme == "" {
workspace.GetDefaultSettings()
workspace.SetDefaultSettings()
}
// Encrypt token if present

View File

@@ -77,7 +77,7 @@ func TestWorkspaceOperations(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
if tc.workspace.Theme == "" {
tc.workspace.GetDefaultSettings()
tc.workspace.SetDefaultSettings()
}
err := database.CreateWorkspace(tc.workspace)
@@ -117,7 +117,7 @@ func TestWorkspaceOperations(t *testing.T) {
UserID: user.ID,
Name: "Get By ID Workspace",
}
workspace.GetDefaultSettings()
workspace.SetDefaultSettings()
if err := database.CreateWorkspace(workspace); err != nil {
t.Fatalf("failed to create test workspace: %v", err)
}
@@ -167,7 +167,7 @@ func TestWorkspaceOperations(t *testing.T) {
UserID: user.ID,
Name: "Get By Name Workspace",
}
workspace.GetDefaultSettings()
workspace.SetDefaultSettings()
if err := database.CreateWorkspace(workspace); err != nil {
t.Fatalf("failed to create test workspace: %v", err)
}
@@ -229,7 +229,7 @@ func TestWorkspaceOperations(t *testing.T) {
UserID: user.ID,
Name: "Update Workspace",
}
workspace.GetDefaultSettings()
workspace.SetDefaultSettings()
if err := database.CreateWorkspace(workspace); err != nil {
t.Fatalf("failed to create test workspace: %v", err)
}
@@ -272,7 +272,7 @@ func TestWorkspaceOperations(t *testing.T) {
}
for _, w := range testWorkspaces {
w.GetDefaultSettings()
w.SetDefaultSettings()
if err := database.CreateWorkspace(w); err != nil {
t.Fatalf("failed to create test workspace: %v", err)
}
@@ -314,7 +314,7 @@ func TestWorkspaceOperations(t *testing.T) {
UserID: user.ID,
Name: "Last File Workspace",
}
workspace.GetDefaultSettings()
workspace.SetDefaultSettings()
if err := database.CreateWorkspace(workspace); err != nil {
t.Fatalf("failed to create test workspace: %v", err)
}
@@ -369,7 +369,7 @@ func TestWorkspaceOperations(t *testing.T) {
UserID: user.ID,
Name: "Delete Workspace",
}
workspace.GetDefaultSettings()
workspace.SetDefaultSettings()
if err := database.CreateWorkspace(workspace); err != nil {
t.Fatalf("failed to create test workspace: %v", err)
}

View File

@@ -33,14 +33,7 @@ type client struct {
repo *git.Repository
}
// New creates a new Client instance
// Parameters:
// - url: the URL of the Git repository
// - username: the username for the Git repository
// - token: the access token for the Git repository
// - workDir: the local directory to clone the repository to
// Returns:
// - Client: the Git client
// New creates a new git Client instance
func New(url, username, token, workDir string) Client {
return &client{
Config: Config{
@@ -53,8 +46,6 @@ func New(url, username, token, workDir string) Client {
}
// Clone clones the Git repository to the local directory
// Returns:
// - error: any error that occurred during cloning
func (c *client) Clone() error {
auth := &http.BasicAuth{
Username: c.Username,
@@ -76,8 +67,6 @@ func (c *client) Clone() error {
}
// Pull pulls the latest changes from the remote repository
// Returns:
// - error: any error that occurred during pulling
func (c *client) Pull() error {
if c.repo == nil {
return fmt.Errorf("repository not initialized")
@@ -105,11 +94,7 @@ func (c *client) Pull() error {
return nil
}
// Commit commits the changes in the repository
// Parameters:
// - message: the commit message
// Returns:
// - error: any error that occurred during committing
// Commit commits the changes in the repository with the given message
func (c *client) Commit(message string) error {
if c.repo == nil {
return fmt.Errorf("repository not initialized")
@@ -134,8 +119,6 @@ func (c *client) Commit(message string) error {
}
// Push pushes the changes to the remote repository
// Returns:
// - error: any error that occurred during pushing
func (c *client) Push() error {
if c.repo == nil {
return fmt.Errorf("repository not initialized")
@@ -158,9 +141,7 @@ func (c *client) Push() error {
return nil
}
// EnsureRepo ensures the local repository is up-to-date
// Returns:
// - error: any error that occurred during the operation
// EnsureRepo ensures the local repository is cloned and up-to-date
func (c *client) EnsureRepo() error {
if _, err := os.Stat(filepath.Join(c.WorkDir, ".git")); os.IsNotExist(err) {
return c.Clone()

View File

@@ -8,14 +8,17 @@ import (
var validate = validator.New()
// UserRole represents the role of a user in the system
type UserRole string
// User roles
const (
RoleAdmin UserRole = "admin"
RoleEditor UserRole = "editor"
RoleViewer UserRole = "viewer"
)
// User represents a user in the system
type User struct {
ID int `json:"id" validate:"required,min=1"`
Email string `json:"email" validate:"required,email"`
@@ -26,6 +29,7 @@ type User struct {
LastWorkspaceID int `json:"lastWorkspaceId"`
}
// Validate validates the user struct
func (u *User) Validate() error {
return validate.Struct(u)
}

View File

@@ -4,6 +4,7 @@ import (
"time"
)
// Workspace represents a user's workspace in the system
type Workspace struct {
ID int `json:"id" validate:"required,min=1"`
UserID int `json:"userId" validate:"required,min=1"`
@@ -23,11 +24,13 @@ type Workspace struct {
GitCommitMsgTemplate string `json:"gitCommitMsgTemplate"`
}
// Validate validates the workspace struct
func (w *Workspace) Validate() error {
return validate.Struct(w)
}
func (w *Workspace) GetDefaultSettings() {
// SetDefaultSettings sets the default settings for the workspace
func (w *Workspace) SetDefaultSettings() {
w.Theme = "light"
w.AutoSave = false
w.ShowHiddenFiles = false

View File

@@ -30,12 +30,7 @@ type FileNode struct {
}
// ListFilesRecursively returns a list of all files in the workspace directory and its subdirectories.
// Parameters:
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to list files in
// Returns:
// - nodes: a list of files and directories in the workspace
// - error: any error that occurred during listing
// Workspace is identified by the given userID and workspaceID.
func (s *Service) ListFilesRecursively(userID, workspaceID int) ([]FileNode, error) {
workspacePath := s.GetWorkspacePath(userID, workspaceID)
return s.walkDirectory(workspacePath, "")
@@ -106,13 +101,8 @@ func (s *Service) walkDirectory(dir, prefix string) ([]FileNode, error) {
}
// FindFileByName returns a list of file paths that match the given filename.
// Parameters:
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to search for the file
// - filename: the name of the file to search for
// Returns:
// - foundPaths: a list of file paths that match the filename
// - error: any error that occurred during the search
// Files are searched recursively in the workspace directory and its subdirectories.
// Workspace is identified by the given userID and workspaceID.
func (s *Service) FindFileByName(userID, workspaceID int, filename string) ([]string, error) {
var foundPaths []string
workspacePath := s.GetWorkspacePath(userID, workspaceID)
@@ -144,14 +134,8 @@ func (s *Service) FindFileByName(userID, workspaceID int, filename string) ([]st
return foundPaths, nil
}
// GetFileContent returns the content of the file at the given path.
// Parameters:
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to get the file from
// - filePath: the path of the file to get
// Returns:
// - content: the content of the file
// - error: any error that occurred during reading
// GetFileContent returns the content of the file at the given filePath.
// Path must be a relative path within the workspace directory given by userID and workspaceID.
func (s *Service) GetFileContent(userID, workspaceID int, filePath string) ([]byte, error) {
fullPath, err := s.ValidatePath(userID, workspaceID, filePath)
if err != nil {
@@ -160,14 +144,8 @@ func (s *Service) GetFileContent(userID, workspaceID int, filePath string) ([]by
return s.fs.ReadFile(fullPath)
}
// SaveFile writes the content to the file at the given path.
// Parameters:
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to save the file to
// - filePath: the path of the file to save
// - content: the content to write to the file
// Returns:
// - error: any error that occurred during saving
// SaveFile writes the content to the file at the given filePath.
// Path must be a relative path within the workspace directory given by userID and workspaceID.
func (s *Service) SaveFile(userID, workspaceID int, filePath string, content []byte) error {
fullPath, err := s.ValidatePath(userID, workspaceID, filePath)
if err != nil {
@@ -182,13 +160,8 @@ func (s *Service) SaveFile(userID, workspaceID int, filePath string, content []b
return s.fs.WriteFile(fullPath, content, 0644)
}
// DeleteFile deletes the file at the given path.
// Parameters:
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to delete the file from
// - filePath: the path of the file to delete
// Returns:
// - error: any error that occurred during deletion
// DeleteFile deletes the file at the given filePath.
// Path must be a relative path within the workspace directory given by userID and workspaceID.
func (s *Service) DeleteFile(userID, workspaceID int, filePath string) error {
fullPath, err := s.ValidatePath(userID, workspaceID, filePath)
if err != nil {
@@ -204,12 +177,7 @@ type FileCountStats struct {
}
// GetFileStats returns the total number of files and related statistics in a workspace
// Parameters:
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to count files in
// Returns:
// - result: statistics about the files in the workspace
// - error: any error that occurred during counting
// Workspace is identified by the given userID and workspaceID
func (s *Service) GetFileStats(userID, workspaceID int) (*FileCountStats, error) {
workspacePath := s.GetWorkspacePath(userID, workspaceID)
@@ -223,8 +191,6 @@ func (s *Service) GetFileStats(userID, workspaceID int) (*FileCountStats, error)
}
// GetTotalFileStats returns the total file statistics for the storage.
// Returns:
// - result: statistics about the files in the storage
func (s *Service) GetTotalFileStats() (*FileCountStats, error) {
return s.countFilesInPath(s.RootDir)
}

View File

@@ -13,15 +13,8 @@ type RepositoryManager interface {
Pull(userID, workspaceID int) error
}
// SetupGitRepo sets up a Git repository for the given user and workspace IDs.
// Parameters:
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to set up the Git repository for
// - gitURL: the URL of the Git repository
// - gitUser: the username for the Git repository
// - gitToken: the access token for the Git repository
// Returns:
// - error: any error that occurred during setup
// SetupGitRepo sets up a Git repository for the given userID and workspaceID.
// The repository is cloned from the given gitURL using the given gitUser and gitToken.
func (s *Service) SetupGitRepo(userID, workspaceID int, gitURL, gitUser, gitToken string) error {
workspacePath := s.GetWorkspacePath(userID, workspaceID)
if _, ok := s.GitRepos[userID]; !ok {
@@ -31,10 +24,7 @@ func (s *Service) SetupGitRepo(userID, workspaceID int, gitURL, gitUser, gitToke
return s.GitRepos[userID][workspaceID].EnsureRepo()
}
// DisableGitRepo disables the Git repository for the given user and workspace IDs.
// Parameters:
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to disable the Git repository for
// DisableGitRepo disables the Git repository for the given userID and workspaceID.
func (s *Service) DisableGitRepo(userID, workspaceID int) {
if userRepos, ok := s.GitRepos[userID]; ok {
delete(userRepos, workspaceID)
@@ -44,13 +34,8 @@ func (s *Service) DisableGitRepo(userID, workspaceID int) {
}
}
// StageCommitAndPush stages, commits, and pushes the changes to the Git repository.
// Parameters:
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to commit and push
// - message: the commit message
// Returns:
// - error: any error that occurred during the operation
// StageCommitAndPush stages, commit with the message, and pushes the changes to the Git repository.
// The git repository belongs to the given userID and is associated with the given workspaceID.
func (s *Service) StageCommitAndPush(userID, workspaceID int, message string) error {
repo, ok := s.getGitRepo(userID, workspaceID)
if !ok {
@@ -65,11 +50,7 @@ func (s *Service) StageCommitAndPush(userID, workspaceID int, message string) er
}
// Pull pulls the changes from the remote Git repository.
// Parameters:
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to pull changes for
// Returns:
// - error: any error that occurred during the operation
// The git repository belongs to the given userID and is associated with the given workspaceID.
func (s *Service) Pull(userID, workspaceID int) error {
repo, ok := s.getGitRepo(userID, workspaceID)
if !ok {

View File

@@ -25,11 +25,7 @@ type Options struct {
NewGitClient func(url, user, token, path string) git.Client
}
// NewService creates a new Storage instance.
// Parameters:
// - rootDir: the root directory for the storage
// Returns:
// - result: the new Storage instance
// NewService creates a new Storage instance with the default options and the given rootDir root directory.
func NewService(rootDir string) *Service {
return NewServiceWithOptions(rootDir, Options{
Fs: &osFS{},
@@ -37,16 +33,11 @@ func NewService(rootDir string) *Service {
})
}
// NewServiceWithOptions creates a new Storage instance with the given options.
// Parameters:
// - rootDir: the root directory for the storage
// - opts: the options for the storage service
// Returns:
// - result: the new Storage instance
func NewServiceWithOptions(rootDir string, opts Options) *Service {
// NewServiceWithOptions creates a new Storage instance with the given options and the given rootDir root directory.
func NewServiceWithOptions(rootDir string, options Options) *Service {
return &Service{
fs: opts.Fs,
newGitClient: opts.NewGitClient,
fs: options.Fs,
newGitClient: options.NewGitClient,
RootDir: rootDir,
GitRepos: make(map[int]map[int]git.Client),
}

View File

@@ -14,14 +14,8 @@ type WorkspaceManager interface {
DeleteUserWorkspace(userID, workspaceID int) error
}
// ValidatePath validates the given path and returns the cleaned path if it is valid.
// Parameters:
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to validate the path for
// - path: the path to validate
// Returns:
// - result: the cleaned path if it is valid
// - error: any error that occurred during validation
// ValidatePath validates the if the given path is valid within the workspace directory.
// Workspace directory is defined as the directory for the given userID and workspaceID.
func (s *Service) ValidatePath(userID, workspaceID int, path string) (string, error) {
workspacePath := s.GetWorkspacePath(userID, workspaceID)
@@ -42,22 +36,12 @@ func (s *Service) ValidatePath(userID, workspaceID int, path string) (string, er
return cleanPath, nil
}
// GetWorkspacePath returns the path to the workspace directory for the given user and workspace IDs.
// Parameters:
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace
// Returns:
// - result: the path to the workspace directory
// GetWorkspacePath returns the path to the workspace directory for the given userID and workspaceID.
func (s *Service) GetWorkspacePath(userID, workspaceID int) string {
return filepath.Join(s.RootDir, fmt.Sprintf("%d", userID), fmt.Sprintf("%d", workspaceID))
}
// InitializeUserWorkspace creates the workspace directory for the given user and workspace IDs.
// Parameters:
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to initialize
// Returns:
// - error: any error that occurred during the operation
// InitializeUserWorkspace creates the workspace directory for the given userID and workspaceID.
func (s *Service) InitializeUserWorkspace(userID, workspaceID int) error {
workspacePath := s.GetWorkspacePath(userID, workspaceID)
err := s.fs.MkdirAll(workspacePath, 0755)
@@ -68,12 +52,7 @@ func (s *Service) InitializeUserWorkspace(userID, workspaceID int) error {
return nil
}
// DeleteUserWorkspace deletes the workspace directory for the given user and workspace IDs.
// Parameters:
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to delete
// Returns:
// - error: any error that occurred during the operation
// DeleteUserWorkspace deletes the workspace directory for the given userID and workspaceID.
func (s *Service) DeleteUserWorkspace(userID, workspaceID int) error {
workspacePath := s.GetWorkspacePath(userID, workspaceID)
err := s.fs.RemoveAll(workspacePath)