user.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Package user provides user management functionality for the SFTP server
  2. package user
  3. import (
  4. "math/rand/v2"
  5. "path/filepath"
  6. )
  7. // User represents an SFTP user with authentication and permission details
  8. type User struct {
  9. Username string // Username for authentication
  10. Password string // Plaintext password
  11. PublicKeys []string // Authorized public keys
  12. HomeDir string // User's home directory
  13. Permissions map[string][]string // path -> permissions (read, write, list, etc.)
  14. Uid uint32 // User ID for file ownership
  15. Gid uint32 // Group ID for file ownership
  16. }
  17. // NewUser creates a new user with default settings
  18. func NewUser(username string) *User {
  19. // Generate a random UID/GID between 1000 and 60000
  20. // This range is typically safe for regular users in most systems
  21. // 0-999 are often reserved for system users
  22. randomId := 1000 + rand.IntN(59000)
  23. return &User{
  24. Username: username,
  25. Permissions: make(map[string][]string),
  26. HomeDir: filepath.Join("/home", username),
  27. Uid: uint32(randomId),
  28. Gid: uint32(randomId),
  29. }
  30. }
  31. // SetPassword sets a plaintext password for the user
  32. func (u *User) SetPassword(password string) {
  33. u.Password = password
  34. }
  35. // AddPublicKey adds a public key to the user
  36. func (u *User) AddPublicKey(key string) {
  37. // Check if key already exists
  38. for _, existingKey := range u.PublicKeys {
  39. if existingKey == key {
  40. return
  41. }
  42. }
  43. u.PublicKeys = append(u.PublicKeys, key)
  44. }
  45. // RemovePublicKey removes a public key from the user
  46. func (u *User) RemovePublicKey(key string) bool {
  47. for i, existingKey := range u.PublicKeys {
  48. if existingKey == key {
  49. // Remove the key by replacing it with the last element and truncating
  50. u.PublicKeys[i] = u.PublicKeys[len(u.PublicKeys)-1]
  51. u.PublicKeys = u.PublicKeys[:len(u.PublicKeys)-1]
  52. return true
  53. }
  54. }
  55. return false
  56. }
  57. // SetPermission sets permissions for a specific path
  58. func (u *User) SetPermission(path string, permissions []string) {
  59. u.Permissions[path] = permissions
  60. }
  61. // RemovePermission removes permissions for a specific path
  62. func (u *User) RemovePermission(path string) bool {
  63. if _, exists := u.Permissions[path]; exists {
  64. delete(u.Permissions, path)
  65. return true
  66. }
  67. return false
  68. }