admin.go 20 KB

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