admin.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. // Copyright (C) 2019-2022 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package dataprovider
  15. import (
  16. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "net"
  20. "os"
  21. "sort"
  22. "strconv"
  23. "strings"
  24. "github.com/alexedwards/argon2id"
  25. "github.com/sftpgo/sdk"
  26. passwordvalidator "github.com/wagslane/go-password-validator"
  27. "golang.org/x/crypto/bcrypt"
  28. "github.com/drakkan/sftpgo/v2/internal/kms"
  29. "github.com/drakkan/sftpgo/v2/internal/logger"
  30. "github.com/drakkan/sftpgo/v2/internal/mfa"
  31. "github.com/drakkan/sftpgo/v2/internal/util"
  32. )
  33. // Available permissions for SFTPGo admins
  34. const (
  35. PermAdminAny = "*"
  36. PermAdminAddUsers = "add_users"
  37. PermAdminChangeUsers = "edit_users"
  38. PermAdminDeleteUsers = "del_users"
  39. PermAdminViewUsers = "view_users"
  40. PermAdminViewConnections = "view_conns"
  41. PermAdminCloseConnections = "close_conns"
  42. PermAdminViewServerStatus = "view_status"
  43. PermAdminManageAdmins = "manage_admins"
  44. PermAdminManageGroups = "manage_groups"
  45. PermAdminManageAPIKeys = "manage_apikeys"
  46. PermAdminQuotaScans = "quota_scans"
  47. PermAdminManageSystem = "manage_system"
  48. PermAdminManageDefender = "manage_defender"
  49. PermAdminViewDefender = "view_defender"
  50. PermAdminRetentionChecks = "retention_checks"
  51. PermAdminMetadataChecks = "metadata_checks"
  52. PermAdminViewEvents = "view_events"
  53. PermAdminManageEventRules = "manage_event_rules"
  54. )
  55. const (
  56. // GroupAddToUsersAsMembership defines that the admin's group will be added as membership group for new users
  57. GroupAddToUsersAsMembership = iota
  58. // GroupAddToUsersAsPrimary defines that the admin's group will be added as primary group for new users
  59. GroupAddToUsersAsPrimary
  60. // GroupAddToUsersAsSecondary defines that the admin's group will be added as secondary group for new users
  61. GroupAddToUsersAsSecondary
  62. )
  63. var (
  64. validAdminPerms = []string{PermAdminAny, PermAdminAddUsers, PermAdminChangeUsers, PermAdminDeleteUsers,
  65. PermAdminViewUsers, PermAdminManageGroups, PermAdminViewConnections, PermAdminCloseConnections,
  66. PermAdminViewServerStatus, PermAdminManageAdmins, PermAdminManageEventRules, PermAdminManageAPIKeys,
  67. PermAdminQuotaScans, PermAdminManageSystem, PermAdminManageDefender, PermAdminViewDefender,
  68. PermAdminRetentionChecks, PermAdminMetadataChecks, PermAdminViewEvents}
  69. )
  70. // AdminTOTPConfig defines the time-based one time password configuration
  71. type AdminTOTPConfig struct {
  72. Enabled bool `json:"enabled,omitempty"`
  73. ConfigName string `json:"config_name,omitempty"`
  74. Secret *kms.Secret `json:"secret,omitempty"`
  75. }
  76. func (c *AdminTOTPConfig) validate(username string) error {
  77. if !c.Enabled {
  78. c.ConfigName = ""
  79. c.Secret = kms.NewEmptySecret()
  80. return nil
  81. }
  82. if c.ConfigName == "" {
  83. return util.NewValidationError("totp: config name is mandatory")
  84. }
  85. if !util.Contains(mfa.GetAvailableTOTPConfigNames(), c.ConfigName) {
  86. return util.NewValidationError(fmt.Sprintf("totp: config name %#v not found", c.ConfigName))
  87. }
  88. if c.Secret.IsEmpty() {
  89. return util.NewValidationError("totp: secret is mandatory")
  90. }
  91. if c.Secret.IsPlain() {
  92. c.Secret.SetAdditionalData(username)
  93. if err := c.Secret.Encrypt(); err != nil {
  94. return util.NewValidationError(fmt.Sprintf("totp: unable to encrypt secret: %v", err))
  95. }
  96. }
  97. return nil
  98. }
  99. // AdminPreferences defines the admin preferences
  100. type AdminPreferences struct {
  101. // Allow to hide some sections from the user page.
  102. // These are not security settings and are not enforced server side
  103. // in any way. They are only intended to simplify the user page in
  104. // the WebAdmin UI.
  105. //
  106. // 1 means hide groups section
  107. // 2 means hide filesystem section, "users_base_dir" must be set in the config file otherwise this setting is ignored
  108. // 4 means hide virtual folders section
  109. // 8 means hide profile section
  110. // 16 means hide ACLs section
  111. // 32 means hide disk and bandwidth quota limits section
  112. // 64 means hide advanced settings section
  113. //
  114. // The settings can be combined
  115. HideUserPageSections int `json:"hide_user_page_sections,omitempty"`
  116. }
  117. // HideGroups returns true if the groups section should be hidden
  118. func (p *AdminPreferences) HideGroups() bool {
  119. return p.HideUserPageSections&1 != 0
  120. }
  121. // HideFilesystem returns true if the filesystem section should be hidden
  122. func (p *AdminPreferences) HideFilesystem() bool {
  123. return config.UsersBaseDir != "" && p.HideUserPageSections&2 != 0
  124. }
  125. // HideVirtualFolders returns true if the virtual folder section should be hidden
  126. func (p *AdminPreferences) HideVirtualFolders() bool {
  127. return p.HideUserPageSections&4 != 0
  128. }
  129. // HideProfile returns true if the profile section should be hidden
  130. func (p *AdminPreferences) HideProfile() bool {
  131. return p.HideUserPageSections&8 != 0
  132. }
  133. // HideACLs returns true if the ACLs section should be hidden
  134. func (p *AdminPreferences) HideACLs() bool {
  135. return p.HideUserPageSections&16 != 0
  136. }
  137. // HideDiskQuotaAndBandwidthLimits returns true if the disk quota and bandwidth limits
  138. // section should be hidden
  139. func (p *AdminPreferences) HideDiskQuotaAndBandwidthLimits() bool {
  140. return p.HideUserPageSections&32 != 0
  141. }
  142. // HideAdvancedSettings returns true if the advanced settings section should be hidden
  143. func (p *AdminPreferences) HideAdvancedSettings() bool {
  144. return p.HideUserPageSections&64 != 0
  145. }
  146. // VisibleUserPageSections returns the number of visible sections
  147. // in the user page
  148. func (p *AdminPreferences) VisibleUserPageSections() int {
  149. var result int
  150. if !p.HideProfile() {
  151. result++
  152. }
  153. if !p.HideACLs() {
  154. result++
  155. }
  156. if !p.HideDiskQuotaAndBandwidthLimits() {
  157. result++
  158. }
  159. if !p.HideAdvancedSettings() {
  160. result++
  161. }
  162. return result
  163. }
  164. // AdminFilters defines additional restrictions for SFTPGo admins
  165. // TODO: rename to AdminOptions in v3
  166. type AdminFilters struct {
  167. // only clients connecting from these IP/Mask are allowed.
  168. // IP/Mask must be in CIDR notation as defined in RFC 4632 and RFC 4291
  169. // for example "192.0.2.0/24" or "2001:db8::/32"
  170. AllowList []string `json:"allow_list,omitempty"`
  171. // API key auth allows to impersonate this administrator with an API key
  172. AllowAPIKeyAuth bool `json:"allow_api_key_auth,omitempty"`
  173. // Time-based one time passwords configuration
  174. TOTPConfig AdminTOTPConfig `json:"totp_config,omitempty"`
  175. // Recovery codes to use if the user loses access to their second factor auth device.
  176. // Each code can only be used once, you should use these codes to login and disable or
  177. // reset 2FA for your account
  178. RecoveryCodes []RecoveryCode `json:"recovery_codes,omitempty"`
  179. Preferences AdminPreferences `json:"preferences"`
  180. }
  181. // AdminGroupMappingOptions defines the options for admin/group mapping
  182. type AdminGroupMappingOptions struct {
  183. AddToUsersAs int `json:"add_to_users_as,omitempty"`
  184. }
  185. func (o *AdminGroupMappingOptions) validate() error {
  186. if o.AddToUsersAs < GroupAddToUsersAsMembership || o.AddToUsersAs > GroupAddToUsersAsSecondary {
  187. return util.NewValidationError(fmt.Sprintf("Invalid mode to add groups to new users: %d", o.AddToUsersAs))
  188. }
  189. return nil
  190. }
  191. // GetUserGroupType returns the type for the matching user group
  192. func (o *AdminGroupMappingOptions) GetUserGroupType() int {
  193. switch o.AddToUsersAs {
  194. case GroupAddToUsersAsPrimary:
  195. return sdk.GroupTypePrimary
  196. case GroupAddToUsersAsSecondary:
  197. return sdk.GroupTypeSecondary
  198. default:
  199. return sdk.GroupTypeMembership
  200. }
  201. }
  202. // AdminGroupMapping defines the mapping between an SFTPGo admin and a group
  203. type AdminGroupMapping struct {
  204. Name string `json:"name"`
  205. Options AdminGroupMappingOptions `json:"options"`
  206. }
  207. // Admin defines a SFTPGo admin
  208. type Admin struct {
  209. // Database unique identifier
  210. ID int64 `json:"id"`
  211. // 1 enabled, 0 disabled (login is not allowed)
  212. Status int `json:"status"`
  213. // Username
  214. Username string `json:"username"`
  215. Password string `json:"password,omitempty"`
  216. Email string `json:"email,omitempty"`
  217. Permissions []string `json:"permissions"`
  218. Filters AdminFilters `json:"filters,omitempty"`
  219. Description string `json:"description,omitempty"`
  220. AdditionalInfo string `json:"additional_info,omitempty"`
  221. // Groups membership
  222. Groups []AdminGroupMapping `json:"groups,omitempty"`
  223. // Creation time as unix timestamp in milliseconds. It will be 0 for admins created before v2.2.0
  224. CreatedAt int64 `json:"created_at"`
  225. // last update time as unix timestamp in milliseconds
  226. UpdatedAt int64 `json:"updated_at"`
  227. // Last login as unix timestamp in milliseconds
  228. LastLogin int64 `json:"last_login"`
  229. }
  230. // CountUnusedRecoveryCodes returns the number of unused recovery codes
  231. func (a *Admin) CountUnusedRecoveryCodes() int {
  232. unused := 0
  233. for _, code := range a.Filters.RecoveryCodes {
  234. if !code.Used {
  235. unused++
  236. }
  237. }
  238. return unused
  239. }
  240. func (a *Admin) hashPassword() error {
  241. if a.Password != "" && !util.IsStringPrefixInSlice(a.Password, internalHashPwdPrefixes) {
  242. if config.PasswordValidation.Admins.MinEntropy > 0 {
  243. if err := passwordvalidator.Validate(a.Password, config.PasswordValidation.Admins.MinEntropy); err != nil {
  244. return util.NewValidationError(err.Error())
  245. }
  246. }
  247. if config.PasswordHashing.Algo == HashingAlgoBcrypt {
  248. pwd, err := bcrypt.GenerateFromPassword([]byte(a.Password), config.PasswordHashing.BcryptOptions.Cost)
  249. if err != nil {
  250. return err
  251. }
  252. a.Password = string(pwd)
  253. } else {
  254. pwd, err := argon2id.CreateHash(a.Password, argon2Params)
  255. if err != nil {
  256. return err
  257. }
  258. a.Password = pwd
  259. }
  260. }
  261. return nil
  262. }
  263. func (a *Admin) hasRedactedSecret() bool {
  264. return a.Filters.TOTPConfig.Secret.IsRedacted()
  265. }
  266. func (a *Admin) validateRecoveryCodes() error {
  267. for i := 0; i < len(a.Filters.RecoveryCodes); i++ {
  268. code := &a.Filters.RecoveryCodes[i]
  269. if code.Secret.IsEmpty() {
  270. return util.NewValidationError("mfa: recovery code cannot be empty")
  271. }
  272. if code.Secret.IsPlain() {
  273. code.Secret.SetAdditionalData(a.Username)
  274. if err := code.Secret.Encrypt(); err != nil {
  275. return util.NewValidationError(fmt.Sprintf("mfa: unable to encrypt recovery code: %v", err))
  276. }
  277. }
  278. }
  279. return nil
  280. }
  281. func (a *Admin) validatePermissions() error {
  282. a.Permissions = util.RemoveDuplicates(a.Permissions, false)
  283. if len(a.Permissions) == 0 {
  284. return util.NewValidationError("please grant some permissions to this admin")
  285. }
  286. if util.Contains(a.Permissions, PermAdminAny) {
  287. a.Permissions = []string{PermAdminAny}
  288. }
  289. for _, perm := range a.Permissions {
  290. if !util.Contains(validAdminPerms, perm) {
  291. return util.NewValidationError(fmt.Sprintf("invalid permission: %#v", perm))
  292. }
  293. }
  294. return nil
  295. }
  296. func (a *Admin) validateGroups() error {
  297. hasPrimary := false
  298. for _, g := range a.Groups {
  299. if g.Name == "" {
  300. return util.NewValidationError("group name is mandatory")
  301. }
  302. if err := g.Options.validate(); err != nil {
  303. return err
  304. }
  305. if g.Options.AddToUsersAs == GroupAddToUsersAsPrimary {
  306. if hasPrimary {
  307. return util.NewValidationError("only one primary group is allowed")
  308. }
  309. hasPrimary = true
  310. }
  311. }
  312. return nil
  313. }
  314. func (a *Admin) validate() error {
  315. a.SetEmptySecretsIfNil()
  316. if a.Username == "" {
  317. return util.NewValidationError("username is mandatory")
  318. }
  319. if err := checkReservedUsernames(a.Username); err != nil {
  320. return err
  321. }
  322. if a.Password == "" {
  323. return util.NewValidationError("please set a password")
  324. }
  325. if a.hasRedactedSecret() {
  326. return util.NewValidationError("cannot save an admin with a redacted secret")
  327. }
  328. if err := a.Filters.TOTPConfig.validate(a.Username); err != nil {
  329. return err
  330. }
  331. if err := a.validateRecoveryCodes(); err != nil {
  332. return err
  333. }
  334. if config.NamingRules&1 == 0 && !usernameRegex.MatchString(a.Username) {
  335. return util.NewValidationError(fmt.Sprintf("username %#v is not valid, the following characters are allowed: a-zA-Z0-9-_.~", a.Username))
  336. }
  337. if err := a.hashPassword(); err != nil {
  338. return err
  339. }
  340. if err := a.validatePermissions(); err != nil {
  341. return err
  342. }
  343. if a.Email != "" && !util.IsEmailValid(a.Email) {
  344. return util.NewValidationError(fmt.Sprintf("email %#v is not valid", a.Email))
  345. }
  346. a.Filters.AllowList = util.RemoveDuplicates(a.Filters.AllowList, false)
  347. for _, IPMask := range a.Filters.AllowList {
  348. _, _, err := net.ParseCIDR(IPMask)
  349. if err != nil {
  350. return util.NewValidationError(fmt.Sprintf("could not parse allow list entry %#v : %v", IPMask, err))
  351. }
  352. }
  353. return a.validateGroups()
  354. }
  355. // GetGroupsAsString returns the user's groups as a string
  356. func (a *Admin) GetGroupsAsString() string {
  357. if len(a.Groups) == 0 {
  358. return ""
  359. }
  360. var groups []string
  361. for _, g := range a.Groups {
  362. groups = append(groups, g.Name)
  363. }
  364. sort.Strings(groups)
  365. return strings.Join(groups, ",")
  366. }
  367. // CheckPassword verifies the admin password
  368. func (a *Admin) CheckPassword(password string) (bool, error) {
  369. if strings.HasPrefix(a.Password, bcryptPwdPrefix) {
  370. if err := bcrypt.CompareHashAndPassword([]byte(a.Password), []byte(password)); err != nil {
  371. return false, ErrInvalidCredentials
  372. }
  373. return true, nil
  374. }
  375. match, err := argon2id.ComparePasswordAndHash(password, a.Password)
  376. if !match || err != nil {
  377. return false, ErrInvalidCredentials
  378. }
  379. return match, err
  380. }
  381. // CanLoginFromIP returns true if login from the given IP is allowed
  382. func (a *Admin) CanLoginFromIP(ip string) bool {
  383. if len(a.Filters.AllowList) == 0 {
  384. return true
  385. }
  386. parsedIP := net.ParseIP(ip)
  387. if parsedIP == nil {
  388. return len(a.Filters.AllowList) == 0
  389. }
  390. for _, ipMask := range a.Filters.AllowList {
  391. _, network, err := net.ParseCIDR(ipMask)
  392. if err != nil {
  393. continue
  394. }
  395. if network.Contains(parsedIP) {
  396. return true
  397. }
  398. }
  399. return false
  400. }
  401. // CanLogin returns an error if the login is not allowed
  402. func (a *Admin) CanLogin(ip string) error {
  403. if a.Status != 1 {
  404. return fmt.Errorf("admin %#v is disabled", a.Username)
  405. }
  406. if !a.CanLoginFromIP(ip) {
  407. return fmt.Errorf("login from IP %v not allowed", ip)
  408. }
  409. return nil
  410. }
  411. func (a *Admin) checkUserAndPass(password, ip string) error {
  412. if err := a.CanLogin(ip); err != nil {
  413. return err
  414. }
  415. if a.Password == "" || password == "" {
  416. return errors.New("credentials cannot be null or empty")
  417. }
  418. match, err := a.CheckPassword(password)
  419. if err != nil {
  420. return err
  421. }
  422. if !match {
  423. return ErrInvalidCredentials
  424. }
  425. return nil
  426. }
  427. // RenderAsJSON implements the renderer interface used within plugins
  428. func (a *Admin) RenderAsJSON(reload bool) ([]byte, error) {
  429. if reload {
  430. admin, err := provider.adminExists(a.Username)
  431. if err != nil {
  432. providerLog(logger.LevelError, "unable to reload admin before rendering as json: %v", err)
  433. return nil, err
  434. }
  435. admin.HideConfidentialData()
  436. return json.Marshal(admin)
  437. }
  438. a.HideConfidentialData()
  439. return json.Marshal(a)
  440. }
  441. // HideConfidentialData hides admin confidential data
  442. func (a *Admin) HideConfidentialData() {
  443. a.Password = ""
  444. if a.Filters.TOTPConfig.Secret != nil {
  445. a.Filters.TOTPConfig.Secret.Hide()
  446. }
  447. for _, code := range a.Filters.RecoveryCodes {
  448. if code.Secret != nil {
  449. code.Secret.Hide()
  450. }
  451. }
  452. a.SetNilSecretsIfEmpty()
  453. }
  454. // SetEmptySecretsIfNil sets the secrets to empty if nil
  455. func (a *Admin) SetEmptySecretsIfNil() {
  456. if a.Filters.TOTPConfig.Secret == nil {
  457. a.Filters.TOTPConfig.Secret = kms.NewEmptySecret()
  458. }
  459. }
  460. // SetNilSecretsIfEmpty set the secrets to nil if empty.
  461. // This is useful before rendering as JSON so the empty fields
  462. // will not be serialized.
  463. func (a *Admin) SetNilSecretsIfEmpty() {
  464. if a.Filters.TOTPConfig.Secret != nil && a.Filters.TOTPConfig.Secret.IsEmpty() {
  465. a.Filters.TOTPConfig.Secret = nil
  466. }
  467. }
  468. // HasPermission returns true if the admin has the specified permission
  469. func (a *Admin) HasPermission(perm string) bool {
  470. if util.Contains(a.Permissions, PermAdminAny) {
  471. return true
  472. }
  473. return util.Contains(a.Permissions, perm)
  474. }
  475. // GetPermissionsAsString returns permission as string
  476. func (a *Admin) GetPermissionsAsString() string {
  477. return strings.Join(a.Permissions, ", ")
  478. }
  479. // GetLastLoginAsString returns the last login as string
  480. func (a *Admin) GetLastLoginAsString() string {
  481. if a.LastLogin > 0 {
  482. return util.GetTimeFromMsecSinceEpoch(a.LastLogin).UTC().Format(iso8601UTCFormat)
  483. }
  484. return ""
  485. }
  486. // GetAllowedIPAsString returns the allowed IP as comma separated string
  487. func (a *Admin) GetAllowedIPAsString() string {
  488. return strings.Join(a.Filters.AllowList, ",")
  489. }
  490. // GetValidPerms returns the allowed admin permissions
  491. func (a *Admin) GetValidPerms() []string {
  492. return validAdminPerms
  493. }
  494. // CanManageMFA returns true if the admin can add a multi-factor authentication configuration
  495. func (a *Admin) CanManageMFA() bool {
  496. return len(mfa.GetAvailableTOTPConfigs()) > 0
  497. }
  498. // GetSignature returns a signature for this admin.
  499. // It will change after an update
  500. func (a *Admin) GetSignature() string {
  501. return strconv.FormatInt(a.UpdatedAt, 10)
  502. }
  503. func (a *Admin) getACopy() Admin {
  504. a.SetEmptySecretsIfNil()
  505. permissions := make([]string, len(a.Permissions))
  506. copy(permissions, a.Permissions)
  507. filters := AdminFilters{}
  508. filters.AllowList = make([]string, len(a.Filters.AllowList))
  509. filters.AllowAPIKeyAuth = a.Filters.AllowAPIKeyAuth
  510. filters.TOTPConfig.Enabled = a.Filters.TOTPConfig.Enabled
  511. filters.TOTPConfig.ConfigName = a.Filters.TOTPConfig.ConfigName
  512. filters.TOTPConfig.Secret = a.Filters.TOTPConfig.Secret.Clone()
  513. copy(filters.AllowList, a.Filters.AllowList)
  514. filters.RecoveryCodes = make([]RecoveryCode, 0)
  515. for _, code := range a.Filters.RecoveryCodes {
  516. if code.Secret == nil {
  517. code.Secret = kms.NewEmptySecret()
  518. }
  519. filters.RecoveryCodes = append(filters.RecoveryCodes, RecoveryCode{
  520. Secret: code.Secret.Clone(),
  521. Used: code.Used,
  522. })
  523. }
  524. filters.Preferences = AdminPreferences{
  525. HideUserPageSections: a.Filters.Preferences.HideUserPageSections,
  526. }
  527. groups := make([]AdminGroupMapping, 0, len(a.Groups))
  528. for _, g := range a.Groups {
  529. groups = append(groups, AdminGroupMapping{
  530. Name: g.Name,
  531. Options: AdminGroupMappingOptions{
  532. AddToUsersAs: g.Options.AddToUsersAs,
  533. },
  534. })
  535. }
  536. return Admin{
  537. ID: a.ID,
  538. Status: a.Status,
  539. Username: a.Username,
  540. Password: a.Password,
  541. Email: a.Email,
  542. Permissions: permissions,
  543. Groups: groups,
  544. Filters: filters,
  545. AdditionalInfo: a.AdditionalInfo,
  546. Description: a.Description,
  547. LastLogin: a.LastLogin,
  548. CreatedAt: a.CreatedAt,
  549. UpdatedAt: a.UpdatedAt,
  550. }
  551. }
  552. func (a *Admin) setFromEnv() error {
  553. envUsername := strings.TrimSpace(os.Getenv("SFTPGO_DEFAULT_ADMIN_USERNAME"))
  554. envPassword := strings.TrimSpace(os.Getenv("SFTPGO_DEFAULT_ADMIN_PASSWORD"))
  555. if envUsername == "" || envPassword == "" {
  556. return errors.New(`to create the default admin you need to set the env vars "SFTPGO_DEFAULT_ADMIN_USERNAME" and "SFTPGO_DEFAULT_ADMIN_PASSWORD"`)
  557. }
  558. a.Username = envUsername
  559. a.Password = envPassword
  560. a.Status = 1
  561. a.Permissions = []string{PermAdminAny}
  562. return nil
  563. }