您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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