You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

admin.go 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. // Copyright 2016 The Gogs Authors. All rights reserved.
  2. // Copyright 2016 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package cmd
  5. import (
  6. "errors"
  7. "fmt"
  8. "net/url"
  9. "os"
  10. "strings"
  11. "text/tabwriter"
  12. asymkey_model "code.gitea.io/gitea/models/asymkey"
  13. auth_model "code.gitea.io/gitea/models/auth"
  14. "code.gitea.io/gitea/models/db"
  15. repo_model "code.gitea.io/gitea/models/repo"
  16. "code.gitea.io/gitea/modules/git"
  17. "code.gitea.io/gitea/modules/graceful"
  18. "code.gitea.io/gitea/modules/log"
  19. repo_module "code.gitea.io/gitea/modules/repository"
  20. "code.gitea.io/gitea/modules/util"
  21. auth_service "code.gitea.io/gitea/services/auth"
  22. "code.gitea.io/gitea/services/auth/source/oauth2"
  23. "code.gitea.io/gitea/services/auth/source/smtp"
  24. repo_service "code.gitea.io/gitea/services/repository"
  25. "github.com/urfave/cli"
  26. )
  27. var (
  28. // CmdAdmin represents the available admin sub-command.
  29. CmdAdmin = cli.Command{
  30. Name: "admin",
  31. Usage: "Command line interface to perform common administrative operations",
  32. Subcommands: []cli.Command{
  33. subcmdUser,
  34. subcmdRepoSyncReleases,
  35. subcmdRegenerate,
  36. subcmdAuth,
  37. subcmdSendMail,
  38. },
  39. }
  40. subcmdRepoSyncReleases = cli.Command{
  41. Name: "repo-sync-releases",
  42. Usage: "Synchronize repository releases with tags",
  43. Action: runRepoSyncReleases,
  44. }
  45. subcmdRegenerate = cli.Command{
  46. Name: "regenerate",
  47. Usage: "Regenerate specific files",
  48. Subcommands: []cli.Command{
  49. microcmdRegenHooks,
  50. microcmdRegenKeys,
  51. },
  52. }
  53. microcmdRegenHooks = cli.Command{
  54. Name: "hooks",
  55. Usage: "Regenerate git-hooks",
  56. Action: runRegenerateHooks,
  57. }
  58. microcmdRegenKeys = cli.Command{
  59. Name: "keys",
  60. Usage: "Regenerate authorized_keys file",
  61. Action: runRegenerateKeys,
  62. }
  63. subcmdAuth = cli.Command{
  64. Name: "auth",
  65. Usage: "Modify external auth providers",
  66. Subcommands: []cli.Command{
  67. microcmdAuthAddOauth,
  68. microcmdAuthUpdateOauth,
  69. cmdAuthAddLdapBindDn,
  70. cmdAuthUpdateLdapBindDn,
  71. cmdAuthAddLdapSimpleAuth,
  72. cmdAuthUpdateLdapSimpleAuth,
  73. microcmdAuthAddSMTP,
  74. microcmdAuthUpdateSMTP,
  75. microcmdAuthList,
  76. microcmdAuthDelete,
  77. },
  78. }
  79. microcmdAuthList = cli.Command{
  80. Name: "list",
  81. Usage: "List auth sources",
  82. Action: runListAuth,
  83. Flags: []cli.Flag{
  84. cli.IntFlag{
  85. Name: "min-width",
  86. Usage: "Minimal cell width including any padding for the formatted table",
  87. Value: 0,
  88. },
  89. cli.IntFlag{
  90. Name: "tab-width",
  91. Usage: "width of tab characters in formatted table (equivalent number of spaces)",
  92. Value: 8,
  93. },
  94. cli.IntFlag{
  95. Name: "padding",
  96. Usage: "padding added to a cell before computing its width",
  97. Value: 1,
  98. },
  99. cli.StringFlag{
  100. Name: "pad-char",
  101. Usage: `ASCII char used for padding if padchar == '\\t', the Writer will assume that the width of a '\\t' in the formatted output is tabwidth, and cells are left-aligned independent of align_left (for correct-looking results, tabwidth must correspond to the tab width in the viewer displaying the result)`,
  102. Value: "\t",
  103. },
  104. cli.BoolFlag{
  105. Name: "vertical-bars",
  106. Usage: "Set to true to print vertical bars between columns",
  107. },
  108. },
  109. }
  110. idFlag = cli.Int64Flag{
  111. Name: "id",
  112. Usage: "ID of authentication source",
  113. }
  114. microcmdAuthDelete = cli.Command{
  115. Name: "delete",
  116. Usage: "Delete specific auth source",
  117. Flags: []cli.Flag{idFlag},
  118. Action: runDeleteAuth,
  119. }
  120. oauthCLIFlags = []cli.Flag{
  121. cli.StringFlag{
  122. Name: "name",
  123. Value: "",
  124. Usage: "Application Name",
  125. },
  126. cli.StringFlag{
  127. Name: "provider",
  128. Value: "",
  129. Usage: "OAuth2 Provider",
  130. },
  131. cli.StringFlag{
  132. Name: "key",
  133. Value: "",
  134. Usage: "Client ID (Key)",
  135. },
  136. cli.StringFlag{
  137. Name: "secret",
  138. Value: "",
  139. Usage: "Client Secret",
  140. },
  141. cli.StringFlag{
  142. Name: "auto-discover-url",
  143. Value: "",
  144. Usage: "OpenID Connect Auto Discovery URL (only required when using OpenID Connect as provider)",
  145. },
  146. cli.StringFlag{
  147. Name: "use-custom-urls",
  148. Value: "false",
  149. Usage: "Use custom URLs for GitLab/GitHub OAuth endpoints",
  150. },
  151. cli.StringFlag{
  152. Name: "custom-tenant-id",
  153. Value: "",
  154. Usage: "Use custom Tenant ID for OAuth endpoints",
  155. },
  156. cli.StringFlag{
  157. Name: "custom-auth-url",
  158. Value: "",
  159. Usage: "Use a custom Authorization URL (option for GitLab/GitHub)",
  160. },
  161. cli.StringFlag{
  162. Name: "custom-token-url",
  163. Value: "",
  164. Usage: "Use a custom Token URL (option for GitLab/GitHub)",
  165. },
  166. cli.StringFlag{
  167. Name: "custom-profile-url",
  168. Value: "",
  169. Usage: "Use a custom Profile URL (option for GitLab/GitHub)",
  170. },
  171. cli.StringFlag{
  172. Name: "custom-email-url",
  173. Value: "",
  174. Usage: "Use a custom Email URL (option for GitHub)",
  175. },
  176. cli.StringFlag{
  177. Name: "icon-url",
  178. Value: "",
  179. Usage: "Custom icon URL for OAuth2 login source",
  180. },
  181. cli.BoolFlag{
  182. Name: "skip-local-2fa",
  183. Usage: "Set to true to skip local 2fa for users authenticated by this source",
  184. },
  185. cli.StringSliceFlag{
  186. Name: "scopes",
  187. Value: nil,
  188. Usage: "Scopes to request when to authenticate against this OAuth2 source",
  189. },
  190. cli.StringFlag{
  191. Name: "required-claim-name",
  192. Value: "",
  193. Usage: "Claim name that has to be set to allow users to login with this source",
  194. },
  195. cli.StringFlag{
  196. Name: "required-claim-value",
  197. Value: "",
  198. Usage: "Claim value that has to be set to allow users to login with this source",
  199. },
  200. cli.StringFlag{
  201. Name: "group-claim-name",
  202. Value: "",
  203. Usage: "Claim name providing group names for this source",
  204. },
  205. cli.StringFlag{
  206. Name: "admin-group",
  207. Value: "",
  208. Usage: "Group Claim value for administrator users",
  209. },
  210. cli.StringFlag{
  211. Name: "restricted-group",
  212. Value: "",
  213. Usage: "Group Claim value for restricted users",
  214. },
  215. cli.StringFlag{
  216. Name: "group-team-map",
  217. Value: "",
  218. Usage: "JSON mapping between groups and org teams",
  219. },
  220. cli.BoolFlag{
  221. Name: "group-team-map-removal",
  222. Usage: "Activate automatic team membership removal depending on groups",
  223. },
  224. }
  225. microcmdAuthUpdateOauth = cli.Command{
  226. Name: "update-oauth",
  227. Usage: "Update existing Oauth authentication source",
  228. Action: runUpdateOauth,
  229. Flags: append(oauthCLIFlags[:1], append([]cli.Flag{idFlag}, oauthCLIFlags[1:]...)...),
  230. }
  231. microcmdAuthAddOauth = cli.Command{
  232. Name: "add-oauth",
  233. Usage: "Add new Oauth authentication source",
  234. Action: runAddOauth,
  235. Flags: oauthCLIFlags,
  236. }
  237. subcmdSendMail = cli.Command{
  238. Name: "sendmail",
  239. Usage: "Send a message to all users",
  240. Action: runSendMail,
  241. Flags: []cli.Flag{
  242. cli.StringFlag{
  243. Name: "title",
  244. Usage: `a title of a message`,
  245. Value: "",
  246. },
  247. cli.StringFlag{
  248. Name: "content",
  249. Usage: "a content of a message",
  250. Value: "",
  251. },
  252. cli.BoolFlag{
  253. Name: "force,f",
  254. Usage: "A flag to bypass a confirmation step",
  255. },
  256. },
  257. }
  258. smtpCLIFlags = []cli.Flag{
  259. cli.StringFlag{
  260. Name: "name",
  261. Value: "",
  262. Usage: "Application Name",
  263. },
  264. cli.StringFlag{
  265. Name: "auth-type",
  266. Value: "PLAIN",
  267. Usage: "SMTP Authentication Type (PLAIN/LOGIN/CRAM-MD5) default PLAIN",
  268. },
  269. cli.StringFlag{
  270. Name: "host",
  271. Value: "",
  272. Usage: "SMTP Host",
  273. },
  274. cli.IntFlag{
  275. Name: "port",
  276. Usage: "SMTP Port",
  277. },
  278. cli.BoolTFlag{
  279. Name: "force-smtps",
  280. Usage: "SMTPS is always used on port 465. Set this to force SMTPS on other ports.",
  281. },
  282. cli.BoolTFlag{
  283. Name: "skip-verify",
  284. Usage: "Skip TLS verify.",
  285. },
  286. cli.StringFlag{
  287. Name: "helo-hostname",
  288. Value: "",
  289. Usage: "Hostname sent with HELO. Leave blank to send current hostname",
  290. },
  291. cli.BoolTFlag{
  292. Name: "disable-helo",
  293. Usage: "Disable SMTP helo.",
  294. },
  295. cli.StringFlag{
  296. Name: "allowed-domains",
  297. Value: "",
  298. Usage: "Leave empty to allow all domains. Separate multiple domains with a comma (',')",
  299. },
  300. cli.BoolTFlag{
  301. Name: "skip-local-2fa",
  302. Usage: "Skip 2FA to log on.",
  303. },
  304. cli.BoolTFlag{
  305. Name: "active",
  306. Usage: "This Authentication Source is Activated.",
  307. },
  308. }
  309. microcmdAuthAddSMTP = cli.Command{
  310. Name: "add-smtp",
  311. Usage: "Add new SMTP authentication source",
  312. Action: runAddSMTP,
  313. Flags: smtpCLIFlags,
  314. }
  315. microcmdAuthUpdateSMTP = cli.Command{
  316. Name: "update-smtp",
  317. Usage: "Update existing SMTP authentication source",
  318. Action: runUpdateSMTP,
  319. Flags: append(smtpCLIFlags[:1], append([]cli.Flag{idFlag}, smtpCLIFlags[1:]...)...),
  320. }
  321. )
  322. func runRepoSyncReleases(_ *cli.Context) error {
  323. ctx, cancel := installSignals()
  324. defer cancel()
  325. if err := initDB(ctx); err != nil {
  326. return err
  327. }
  328. log.Trace("Synchronizing repository releases (this may take a while)")
  329. for page := 1; ; page++ {
  330. repos, count, err := repo_model.SearchRepositoryByName(ctx, &repo_model.SearchRepoOptions{
  331. ListOptions: db.ListOptions{
  332. PageSize: repo_model.RepositoryListDefaultPageSize,
  333. Page: page,
  334. },
  335. Private: true,
  336. })
  337. if err != nil {
  338. return fmt.Errorf("SearchRepositoryByName: %w", err)
  339. }
  340. if len(repos) == 0 {
  341. break
  342. }
  343. log.Trace("Processing next %d repos of %d", len(repos), count)
  344. for _, repo := range repos {
  345. log.Trace("Synchronizing repo %s with path %s", repo.FullName(), repo.RepoPath())
  346. gitRepo, err := git.OpenRepository(ctx, repo.RepoPath())
  347. if err != nil {
  348. log.Warn("OpenRepository: %v", err)
  349. continue
  350. }
  351. oldnum, err := getReleaseCount(repo.ID)
  352. if err != nil {
  353. log.Warn(" GetReleaseCountByRepoID: %v", err)
  354. }
  355. log.Trace(" currentNumReleases is %d, running SyncReleasesWithTags", oldnum)
  356. if err = repo_module.SyncReleasesWithTags(repo, gitRepo); err != nil {
  357. log.Warn(" SyncReleasesWithTags: %v", err)
  358. gitRepo.Close()
  359. continue
  360. }
  361. count, err = getReleaseCount(repo.ID)
  362. if err != nil {
  363. log.Warn(" GetReleaseCountByRepoID: %v", err)
  364. gitRepo.Close()
  365. continue
  366. }
  367. log.Trace(" repo %s releases synchronized to tags: from %d to %d",
  368. repo.FullName(), oldnum, count)
  369. gitRepo.Close()
  370. }
  371. }
  372. return nil
  373. }
  374. func getReleaseCount(id int64) (int64, error) {
  375. return repo_model.GetReleaseCountByRepoID(
  376. db.DefaultContext,
  377. id,
  378. repo_model.FindReleasesOptions{
  379. IncludeTags: true,
  380. },
  381. )
  382. }
  383. func runRegenerateHooks(_ *cli.Context) error {
  384. ctx, cancel := installSignals()
  385. defer cancel()
  386. if err := initDB(ctx); err != nil {
  387. return err
  388. }
  389. return repo_service.SyncRepositoryHooks(graceful.GetManager().ShutdownContext())
  390. }
  391. func runRegenerateKeys(_ *cli.Context) error {
  392. ctx, cancel := installSignals()
  393. defer cancel()
  394. if err := initDB(ctx); err != nil {
  395. return err
  396. }
  397. return asymkey_model.RewriteAllPublicKeys()
  398. }
  399. func parseOAuth2Config(c *cli.Context) *oauth2.Source {
  400. var customURLMapping *oauth2.CustomURLMapping
  401. if c.IsSet("use-custom-urls") {
  402. customURLMapping = &oauth2.CustomURLMapping{
  403. TokenURL: c.String("custom-token-url"),
  404. AuthURL: c.String("custom-auth-url"),
  405. ProfileURL: c.String("custom-profile-url"),
  406. EmailURL: c.String("custom-email-url"),
  407. Tenant: c.String("custom-tenant-id"),
  408. }
  409. } else {
  410. customURLMapping = nil
  411. }
  412. return &oauth2.Source{
  413. Provider: c.String("provider"),
  414. ClientID: c.String("key"),
  415. ClientSecret: c.String("secret"),
  416. OpenIDConnectAutoDiscoveryURL: c.String("auto-discover-url"),
  417. CustomURLMapping: customURLMapping,
  418. IconURL: c.String("icon-url"),
  419. SkipLocalTwoFA: c.Bool("skip-local-2fa"),
  420. Scopes: c.StringSlice("scopes"),
  421. RequiredClaimName: c.String("required-claim-name"),
  422. RequiredClaimValue: c.String("required-claim-value"),
  423. GroupClaimName: c.String("group-claim-name"),
  424. AdminGroup: c.String("admin-group"),
  425. RestrictedGroup: c.String("restricted-group"),
  426. GroupTeamMap: c.String("group-team-map"),
  427. GroupTeamMapRemoval: c.Bool("group-team-map-removal"),
  428. }
  429. }
  430. func runAddOauth(c *cli.Context) error {
  431. ctx, cancel := installSignals()
  432. defer cancel()
  433. if err := initDB(ctx); err != nil {
  434. return err
  435. }
  436. config := parseOAuth2Config(c)
  437. if config.Provider == "openidConnect" {
  438. discoveryURL, err := url.Parse(config.OpenIDConnectAutoDiscoveryURL)
  439. if err != nil || (discoveryURL.Scheme != "http" && discoveryURL.Scheme != "https") {
  440. return fmt.Errorf("invalid Auto Discovery URL: %s (this must be a valid URL starting with http:// or https://)", config.OpenIDConnectAutoDiscoveryURL)
  441. }
  442. }
  443. return auth_model.CreateSource(&auth_model.Source{
  444. Type: auth_model.OAuth2,
  445. Name: c.String("name"),
  446. IsActive: true,
  447. Cfg: config,
  448. })
  449. }
  450. func runUpdateOauth(c *cli.Context) error {
  451. if !c.IsSet("id") {
  452. return fmt.Errorf("--id flag is missing")
  453. }
  454. ctx, cancel := installSignals()
  455. defer cancel()
  456. if err := initDB(ctx); err != nil {
  457. return err
  458. }
  459. source, err := auth_model.GetSourceByID(c.Int64("id"))
  460. if err != nil {
  461. return err
  462. }
  463. oAuth2Config := source.Cfg.(*oauth2.Source)
  464. if c.IsSet("name") {
  465. source.Name = c.String("name")
  466. }
  467. if c.IsSet("provider") {
  468. oAuth2Config.Provider = c.String("provider")
  469. }
  470. if c.IsSet("key") {
  471. oAuth2Config.ClientID = c.String("key")
  472. }
  473. if c.IsSet("secret") {
  474. oAuth2Config.ClientSecret = c.String("secret")
  475. }
  476. if c.IsSet("auto-discover-url") {
  477. oAuth2Config.OpenIDConnectAutoDiscoveryURL = c.String("auto-discover-url")
  478. }
  479. if c.IsSet("icon-url") {
  480. oAuth2Config.IconURL = c.String("icon-url")
  481. }
  482. if c.IsSet("scopes") {
  483. oAuth2Config.Scopes = c.StringSlice("scopes")
  484. }
  485. if c.IsSet("required-claim-name") {
  486. oAuth2Config.RequiredClaimName = c.String("required-claim-name")
  487. }
  488. if c.IsSet("required-claim-value") {
  489. oAuth2Config.RequiredClaimValue = c.String("required-claim-value")
  490. }
  491. if c.IsSet("group-claim-name") {
  492. oAuth2Config.GroupClaimName = c.String("group-claim-name")
  493. }
  494. if c.IsSet("admin-group") {
  495. oAuth2Config.AdminGroup = c.String("admin-group")
  496. }
  497. if c.IsSet("restricted-group") {
  498. oAuth2Config.RestrictedGroup = c.String("restricted-group")
  499. }
  500. if c.IsSet("group-team-map") {
  501. oAuth2Config.GroupTeamMap = c.String("group-team-map")
  502. }
  503. if c.IsSet("group-team-map-removal") {
  504. oAuth2Config.GroupTeamMapRemoval = c.Bool("group-team-map-removal")
  505. }
  506. // update custom URL mapping
  507. customURLMapping := &oauth2.CustomURLMapping{}
  508. if oAuth2Config.CustomURLMapping != nil {
  509. customURLMapping.TokenURL = oAuth2Config.CustomURLMapping.TokenURL
  510. customURLMapping.AuthURL = oAuth2Config.CustomURLMapping.AuthURL
  511. customURLMapping.ProfileURL = oAuth2Config.CustomURLMapping.ProfileURL
  512. customURLMapping.EmailURL = oAuth2Config.CustomURLMapping.EmailURL
  513. customURLMapping.Tenant = oAuth2Config.CustomURLMapping.Tenant
  514. }
  515. if c.IsSet("use-custom-urls") && c.IsSet("custom-token-url") {
  516. customURLMapping.TokenURL = c.String("custom-token-url")
  517. }
  518. if c.IsSet("use-custom-urls") && c.IsSet("custom-auth-url") {
  519. customURLMapping.AuthURL = c.String("custom-auth-url")
  520. }
  521. if c.IsSet("use-custom-urls") && c.IsSet("custom-profile-url") {
  522. customURLMapping.ProfileURL = c.String("custom-profile-url")
  523. }
  524. if c.IsSet("use-custom-urls") && c.IsSet("custom-email-url") {
  525. customURLMapping.EmailURL = c.String("custom-email-url")
  526. }
  527. if c.IsSet("use-custom-urls") && c.IsSet("custom-tenant-id") {
  528. customURLMapping.Tenant = c.String("custom-tenant-id")
  529. }
  530. oAuth2Config.CustomURLMapping = customURLMapping
  531. source.Cfg = oAuth2Config
  532. return auth_model.UpdateSource(source)
  533. }
  534. func parseSMTPConfig(c *cli.Context, conf *smtp.Source) error {
  535. if c.IsSet("auth-type") {
  536. conf.Auth = c.String("auth-type")
  537. validAuthTypes := []string{"PLAIN", "LOGIN", "CRAM-MD5"}
  538. if !util.SliceContainsString(validAuthTypes, strings.ToUpper(c.String("auth-type"))) {
  539. return errors.New("Auth must be one of PLAIN/LOGIN/CRAM-MD5")
  540. }
  541. conf.Auth = c.String("auth-type")
  542. }
  543. if c.IsSet("host") {
  544. conf.Host = c.String("host")
  545. }
  546. if c.IsSet("port") {
  547. conf.Port = c.Int("port")
  548. }
  549. if c.IsSet("allowed-domains") {
  550. conf.AllowedDomains = c.String("allowed-domains")
  551. }
  552. if c.IsSet("force-smtps") {
  553. conf.ForceSMTPS = c.BoolT("force-smtps")
  554. }
  555. if c.IsSet("skip-verify") {
  556. conf.SkipVerify = c.BoolT("skip-verify")
  557. }
  558. if c.IsSet("helo-hostname") {
  559. conf.HeloHostname = c.String("helo-hostname")
  560. }
  561. if c.IsSet("disable-helo") {
  562. conf.DisableHelo = c.BoolT("disable-helo")
  563. }
  564. if c.IsSet("skip-local-2fa") {
  565. conf.SkipLocalTwoFA = c.BoolT("skip-local-2fa")
  566. }
  567. return nil
  568. }
  569. func runAddSMTP(c *cli.Context) error {
  570. ctx, cancel := installSignals()
  571. defer cancel()
  572. if err := initDB(ctx); err != nil {
  573. return err
  574. }
  575. if !c.IsSet("name") || len(c.String("name")) == 0 {
  576. return errors.New("name must be set")
  577. }
  578. if !c.IsSet("host") || len(c.String("host")) == 0 {
  579. return errors.New("host must be set")
  580. }
  581. if !c.IsSet("port") {
  582. return errors.New("port must be set")
  583. }
  584. active := true
  585. if c.IsSet("active") {
  586. active = c.BoolT("active")
  587. }
  588. var smtpConfig smtp.Source
  589. if err := parseSMTPConfig(c, &smtpConfig); err != nil {
  590. return err
  591. }
  592. // If not set default to PLAIN
  593. if len(smtpConfig.Auth) == 0 {
  594. smtpConfig.Auth = "PLAIN"
  595. }
  596. return auth_model.CreateSource(&auth_model.Source{
  597. Type: auth_model.SMTP,
  598. Name: c.String("name"),
  599. IsActive: active,
  600. Cfg: &smtpConfig,
  601. })
  602. }
  603. func runUpdateSMTP(c *cli.Context) error {
  604. if !c.IsSet("id") {
  605. return fmt.Errorf("--id flag is missing")
  606. }
  607. ctx, cancel := installSignals()
  608. defer cancel()
  609. if err := initDB(ctx); err != nil {
  610. return err
  611. }
  612. source, err := auth_model.GetSourceByID(c.Int64("id"))
  613. if err != nil {
  614. return err
  615. }
  616. smtpConfig := source.Cfg.(*smtp.Source)
  617. if err := parseSMTPConfig(c, smtpConfig); err != nil {
  618. return err
  619. }
  620. if c.IsSet("name") {
  621. source.Name = c.String("name")
  622. }
  623. if c.IsSet("active") {
  624. source.IsActive = c.BoolT("active")
  625. }
  626. source.Cfg = smtpConfig
  627. return auth_model.UpdateSource(source)
  628. }
  629. func runListAuth(c *cli.Context) error {
  630. ctx, cancel := installSignals()
  631. defer cancel()
  632. if err := initDB(ctx); err != nil {
  633. return err
  634. }
  635. authSources, err := auth_model.Sources()
  636. if err != nil {
  637. return err
  638. }
  639. flags := tabwriter.AlignRight
  640. if c.Bool("vertical-bars") {
  641. flags |= tabwriter.Debug
  642. }
  643. padChar := byte('\t')
  644. if len(c.String("pad-char")) > 0 {
  645. padChar = c.String("pad-char")[0]
  646. }
  647. // loop through each source and print
  648. w := tabwriter.NewWriter(os.Stdout, c.Int("min-width"), c.Int("tab-width"), c.Int("padding"), padChar, flags)
  649. fmt.Fprintf(w, "ID\tName\tType\tEnabled\n")
  650. for _, source := range authSources {
  651. fmt.Fprintf(w, "%d\t%s\t%s\t%t\n", source.ID, source.Name, source.Type.String(), source.IsActive)
  652. }
  653. w.Flush()
  654. return nil
  655. }
  656. func runDeleteAuth(c *cli.Context) error {
  657. if !c.IsSet("id") {
  658. return fmt.Errorf("--id flag is missing")
  659. }
  660. ctx, cancel := installSignals()
  661. defer cancel()
  662. if err := initDB(ctx); err != nil {
  663. return err
  664. }
  665. source, err := auth_model.GetSourceByID(c.Int64("id"))
  666. if err != nil {
  667. return err
  668. }
  669. return auth_service.DeleteSource(source)
  670. }