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 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. // Copyright 2016 The Gogs Authors. All rights reserved.
  2. // Copyright 2016 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package cmd
  6. import (
  7. "context"
  8. "errors"
  9. "fmt"
  10. "os"
  11. "strings"
  12. "text/tabwriter"
  13. "code.gitea.io/gitea/models"
  14. asymkey_model "code.gitea.io/gitea/models/asymkey"
  15. "code.gitea.io/gitea/models/auth"
  16. "code.gitea.io/gitea/models/db"
  17. user_model "code.gitea.io/gitea/models/user"
  18. "code.gitea.io/gitea/modules/git"
  19. "code.gitea.io/gitea/modules/graceful"
  20. "code.gitea.io/gitea/modules/log"
  21. pwd "code.gitea.io/gitea/modules/password"
  22. repo_module "code.gitea.io/gitea/modules/repository"
  23. "code.gitea.io/gitea/modules/setting"
  24. "code.gitea.io/gitea/modules/storage"
  25. auth_service "code.gitea.io/gitea/services/auth"
  26. "code.gitea.io/gitea/services/auth/source/oauth2"
  27. repo_service "code.gitea.io/gitea/services/repository"
  28. user_service "code.gitea.io/gitea/services/user"
  29. "github.com/urfave/cli"
  30. )
  31. var (
  32. // CmdAdmin represents the available admin sub-command.
  33. CmdAdmin = cli.Command{
  34. Name: "admin",
  35. Usage: "Command line interface to perform common administrative operations",
  36. Subcommands: []cli.Command{
  37. subcmdUser,
  38. subcmdRepoSyncReleases,
  39. subcmdRegenerate,
  40. subcmdAuth,
  41. subcmdSendMail,
  42. },
  43. }
  44. subcmdUser = cli.Command{
  45. Name: "user",
  46. Usage: "Modify users",
  47. Subcommands: []cli.Command{
  48. microcmdUserCreate,
  49. microcmdUserList,
  50. microcmdUserChangePassword,
  51. microcmdUserDelete,
  52. },
  53. }
  54. microcmdUserList = cli.Command{
  55. Name: "list",
  56. Usage: "List users",
  57. Action: runListUsers,
  58. Flags: []cli.Flag{
  59. cli.BoolFlag{
  60. Name: "admin",
  61. Usage: "List only admin users",
  62. },
  63. },
  64. }
  65. microcmdUserCreate = cli.Command{
  66. Name: "create",
  67. Usage: "Create a new user in database",
  68. Action: runCreateUser,
  69. Flags: []cli.Flag{
  70. cli.StringFlag{
  71. Name: "name",
  72. Usage: "Username. DEPRECATED: use username instead",
  73. },
  74. cli.StringFlag{
  75. Name: "username",
  76. Usage: "Username",
  77. },
  78. cli.StringFlag{
  79. Name: "password",
  80. Usage: "User password",
  81. },
  82. cli.StringFlag{
  83. Name: "email",
  84. Usage: "User email address",
  85. },
  86. cli.BoolFlag{
  87. Name: "admin",
  88. Usage: "User is an admin",
  89. },
  90. cli.BoolFlag{
  91. Name: "random-password",
  92. Usage: "Generate a random password for the user",
  93. },
  94. cli.BoolFlag{
  95. Name: "must-change-password",
  96. Usage: "Set this option to false to prevent forcing the user to change their password after initial login, (Default: true)",
  97. },
  98. cli.IntFlag{
  99. Name: "random-password-length",
  100. Usage: "Length of the random password to be generated",
  101. Value: 12,
  102. },
  103. cli.BoolFlag{
  104. Name: "access-token",
  105. Usage: "Generate access token for the user",
  106. },
  107. },
  108. }
  109. microcmdUserChangePassword = cli.Command{
  110. Name: "change-password",
  111. Usage: "Change a user's password",
  112. Action: runChangePassword,
  113. Flags: []cli.Flag{
  114. cli.StringFlag{
  115. Name: "username,u",
  116. Value: "",
  117. Usage: "The user to change password for",
  118. },
  119. cli.StringFlag{
  120. Name: "password,p",
  121. Value: "",
  122. Usage: "New password to set for user",
  123. },
  124. },
  125. }
  126. microcmdUserDelete = cli.Command{
  127. Name: "delete",
  128. Usage: "Delete specific user by id, name or email",
  129. Flags: []cli.Flag{
  130. cli.Int64Flag{
  131. Name: "id",
  132. Usage: "ID of user of the user to delete",
  133. },
  134. cli.StringFlag{
  135. Name: "username,u",
  136. Usage: "Username of the user to delete",
  137. },
  138. cli.StringFlag{
  139. Name: "email,e",
  140. Usage: "Email of the user to delete",
  141. },
  142. },
  143. Action: runDeleteUser,
  144. }
  145. subcmdRepoSyncReleases = cli.Command{
  146. Name: "repo-sync-releases",
  147. Usage: "Synchronize repository releases with tags",
  148. Action: runRepoSyncReleases,
  149. }
  150. subcmdRegenerate = cli.Command{
  151. Name: "regenerate",
  152. Usage: "Regenerate specific files",
  153. Subcommands: []cli.Command{
  154. microcmdRegenHooks,
  155. microcmdRegenKeys,
  156. },
  157. }
  158. microcmdRegenHooks = cli.Command{
  159. Name: "hooks",
  160. Usage: "Regenerate git-hooks",
  161. Action: runRegenerateHooks,
  162. }
  163. microcmdRegenKeys = cli.Command{
  164. Name: "keys",
  165. Usage: "Regenerate authorized_keys file",
  166. Action: runRegenerateKeys,
  167. }
  168. subcmdAuth = cli.Command{
  169. Name: "auth",
  170. Usage: "Modify external auth providers",
  171. Subcommands: []cli.Command{
  172. microcmdAuthAddOauth,
  173. microcmdAuthUpdateOauth,
  174. cmdAuthAddLdapBindDn,
  175. cmdAuthUpdateLdapBindDn,
  176. cmdAuthAddLdapSimpleAuth,
  177. cmdAuthUpdateLdapSimpleAuth,
  178. microcmdAuthList,
  179. microcmdAuthDelete,
  180. },
  181. }
  182. microcmdAuthList = cli.Command{
  183. Name: "list",
  184. Usage: "List auth sources",
  185. Action: runListAuth,
  186. Flags: []cli.Flag{
  187. cli.IntFlag{
  188. Name: "min-width",
  189. Usage: "Minimal cell width including any padding for the formatted table",
  190. Value: 0,
  191. },
  192. cli.IntFlag{
  193. Name: "tab-width",
  194. Usage: "width of tab characters in formatted table (equivalent number of spaces)",
  195. Value: 8,
  196. },
  197. cli.IntFlag{
  198. Name: "padding",
  199. Usage: "padding added to a cell before computing its width",
  200. Value: 1,
  201. },
  202. cli.StringFlag{
  203. Name: "pad-char",
  204. 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)`,
  205. Value: "\t",
  206. },
  207. cli.BoolFlag{
  208. Name: "vertical-bars",
  209. Usage: "Set to true to print vertical bars between columns",
  210. },
  211. },
  212. }
  213. idFlag = cli.Int64Flag{
  214. Name: "id",
  215. Usage: "ID of authentication source",
  216. }
  217. microcmdAuthDelete = cli.Command{
  218. Name: "delete",
  219. Usage: "Delete specific auth source",
  220. Flags: []cli.Flag{idFlag},
  221. Action: runDeleteAuth,
  222. }
  223. oauthCLIFlags = []cli.Flag{
  224. cli.StringFlag{
  225. Name: "name",
  226. Value: "",
  227. Usage: "Application Name",
  228. },
  229. cli.StringFlag{
  230. Name: "provider",
  231. Value: "",
  232. Usage: "OAuth2 Provider",
  233. },
  234. cli.StringFlag{
  235. Name: "key",
  236. Value: "",
  237. Usage: "Client ID (Key)",
  238. },
  239. cli.StringFlag{
  240. Name: "secret",
  241. Value: "",
  242. Usage: "Client Secret",
  243. },
  244. cli.StringFlag{
  245. Name: "auto-discover-url",
  246. Value: "",
  247. Usage: "OpenID Connect Auto Discovery URL (only required when using OpenID Connect as provider)",
  248. },
  249. cli.StringFlag{
  250. Name: "use-custom-urls",
  251. Value: "false",
  252. Usage: "Use custom URLs for GitLab/GitHub OAuth endpoints",
  253. },
  254. cli.StringFlag{
  255. Name: "custom-auth-url",
  256. Value: "",
  257. Usage: "Use a custom Authorization URL (option for GitLab/GitHub)",
  258. },
  259. cli.StringFlag{
  260. Name: "custom-token-url",
  261. Value: "",
  262. Usage: "Use a custom Token URL (option for GitLab/GitHub)",
  263. },
  264. cli.StringFlag{
  265. Name: "custom-profile-url",
  266. Value: "",
  267. Usage: "Use a custom Profile URL (option for GitLab/GitHub)",
  268. },
  269. cli.StringFlag{
  270. Name: "custom-email-url",
  271. Value: "",
  272. Usage: "Use a custom Email URL (option for GitHub)",
  273. },
  274. cli.StringFlag{
  275. Name: "icon-url",
  276. Value: "",
  277. Usage: "Custom icon URL for OAuth2 login source",
  278. },
  279. cli.BoolFlag{
  280. Name: "skip-local-2fa",
  281. Usage: "Set to true to skip local 2fa for users authenticated by this source",
  282. },
  283. cli.StringSliceFlag{
  284. Name: "scopes",
  285. Value: nil,
  286. Usage: "Scopes to request when to authenticate against this OAuth2 source",
  287. },
  288. cli.StringFlag{
  289. Name: "required-claim-name",
  290. Value: "",
  291. Usage: "Claim name that has to be set to allow users to login with this source",
  292. },
  293. cli.StringFlag{
  294. Name: "required-claim-value",
  295. Value: "",
  296. Usage: "Claim value that has to be set to allow users to login with this source",
  297. },
  298. cli.StringFlag{
  299. Name: "group-claim-name",
  300. Value: "",
  301. Usage: "Claim name providing group names for this source",
  302. },
  303. cli.StringFlag{
  304. Name: "admin-group",
  305. Value: "",
  306. Usage: "Group Claim value for administrator users",
  307. },
  308. cli.StringFlag{
  309. Name: "restricted-group",
  310. Value: "",
  311. Usage: "Group Claim value for restricted users",
  312. },
  313. }
  314. microcmdAuthUpdateOauth = cli.Command{
  315. Name: "update-oauth",
  316. Usage: "Update existing Oauth authentication source",
  317. Action: runUpdateOauth,
  318. Flags: append(oauthCLIFlags[:1], append([]cli.Flag{idFlag}, oauthCLIFlags[1:]...)...),
  319. }
  320. microcmdAuthAddOauth = cli.Command{
  321. Name: "add-oauth",
  322. Usage: "Add new Oauth authentication source",
  323. Action: runAddOauth,
  324. Flags: oauthCLIFlags,
  325. }
  326. subcmdSendMail = cli.Command{
  327. Name: "sendmail",
  328. Usage: "Send a message to all users",
  329. Action: runSendMail,
  330. Flags: []cli.Flag{
  331. cli.StringFlag{
  332. Name: "title",
  333. Usage: `a title of a message`,
  334. Value: "",
  335. },
  336. cli.StringFlag{
  337. Name: "content",
  338. Usage: "a content of a message",
  339. Value: "",
  340. },
  341. cli.BoolFlag{
  342. Name: "force,f",
  343. Usage: "A flag to bypass a confirmation step",
  344. },
  345. },
  346. }
  347. )
  348. func runChangePassword(c *cli.Context) error {
  349. if err := argsSet(c, "username", "password"); err != nil {
  350. return err
  351. }
  352. ctx, cancel := installSignals()
  353. defer cancel()
  354. if err := initDB(ctx); err != nil {
  355. return err
  356. }
  357. if len(c.String("password")) < setting.MinPasswordLength {
  358. return fmt.Errorf("Password is not long enough. Needs to be at least %d", setting.MinPasswordLength)
  359. }
  360. if !pwd.IsComplexEnough(c.String("password")) {
  361. return errors.New("Password does not meet complexity requirements")
  362. }
  363. pwned, err := pwd.IsPwned(context.Background(), c.String("password"))
  364. if err != nil {
  365. return err
  366. }
  367. if pwned {
  368. return errors.New("The password you chose is on a list of stolen passwords previously exposed in public data breaches. Please try again with a different password.\nFor more details, see https://haveibeenpwned.com/Passwords")
  369. }
  370. uname := c.String("username")
  371. user, err := user_model.GetUserByName(uname)
  372. if err != nil {
  373. return err
  374. }
  375. if err = user.SetPassword(c.String("password")); err != nil {
  376. return err
  377. }
  378. if err = user_model.UpdateUserCols(db.DefaultContext, user, "passwd", "passwd_hash_algo", "salt"); err != nil {
  379. return err
  380. }
  381. fmt.Printf("%s's password has been successfully updated!\n", user.Name)
  382. return nil
  383. }
  384. func runCreateUser(c *cli.Context) error {
  385. if err := argsSet(c, "email"); err != nil {
  386. return err
  387. }
  388. if c.IsSet("name") && c.IsSet("username") {
  389. return errors.New("Cannot set both --name and --username flags")
  390. }
  391. if !c.IsSet("name") && !c.IsSet("username") {
  392. return errors.New("One of --name or --username flags must be set")
  393. }
  394. if c.IsSet("password") && c.IsSet("random-password") {
  395. return errors.New("cannot set both -random-password and -password flags")
  396. }
  397. var username string
  398. if c.IsSet("username") {
  399. username = c.String("username")
  400. } else {
  401. username = c.String("name")
  402. fmt.Fprintf(os.Stderr, "--name flag is deprecated. Use --username instead.\n")
  403. }
  404. ctx, cancel := installSignals()
  405. defer cancel()
  406. if err := initDB(ctx); err != nil {
  407. return err
  408. }
  409. var password string
  410. if c.IsSet("password") {
  411. password = c.String("password")
  412. } else if c.IsSet("random-password") {
  413. var err error
  414. password, err = pwd.Generate(c.Int("random-password-length"))
  415. if err != nil {
  416. return err
  417. }
  418. fmt.Printf("generated random password is '%s'\n", password)
  419. } else {
  420. return errors.New("must set either password or random-password flag")
  421. }
  422. // always default to true
  423. var changePassword = true
  424. // If this is the first user being created.
  425. // Take it as the admin and don't force a password update.
  426. if n := user_model.CountUsers(); n == 0 {
  427. changePassword = false
  428. }
  429. if c.IsSet("must-change-password") {
  430. changePassword = c.Bool("must-change-password")
  431. }
  432. u := &user_model.User{
  433. Name: username,
  434. Email: c.String("email"),
  435. Passwd: password,
  436. IsActive: true,
  437. IsAdmin: c.Bool("admin"),
  438. MustChangePassword: changePassword,
  439. Theme: setting.UI.DefaultTheme,
  440. }
  441. if err := user_model.CreateUser(u); err != nil {
  442. return fmt.Errorf("CreateUser: %v", err)
  443. }
  444. if c.Bool("access-token") {
  445. t := &models.AccessToken{
  446. Name: "gitea-admin",
  447. UID: u.ID,
  448. }
  449. if err := models.NewAccessToken(t); err != nil {
  450. return err
  451. }
  452. fmt.Printf("Access token was successfully created... %s\n", t.Token)
  453. }
  454. fmt.Printf("New user '%s' has been successfully created!\n", username)
  455. return nil
  456. }
  457. func runListUsers(c *cli.Context) error {
  458. ctx, cancel := installSignals()
  459. defer cancel()
  460. if err := initDB(ctx); err != nil {
  461. return err
  462. }
  463. users, err := user_model.GetAllUsers()
  464. if err != nil {
  465. return err
  466. }
  467. w := tabwriter.NewWriter(os.Stdout, 5, 0, 1, ' ', 0)
  468. if c.IsSet("admin") {
  469. fmt.Fprintf(w, "ID\tUsername\tEmail\tIsActive\n")
  470. for _, u := range users {
  471. if u.IsAdmin {
  472. fmt.Fprintf(w, "%d\t%s\t%s\t%t\n", u.ID, u.Name, u.Email, u.IsActive)
  473. }
  474. }
  475. } else {
  476. fmt.Fprintf(w, "ID\tUsername\tEmail\tIsActive\tIsAdmin\n")
  477. for _, u := range users {
  478. fmt.Fprintf(w, "%d\t%s\t%s\t%t\t%t\n", u.ID, u.Name, u.Email, u.IsActive, u.IsAdmin)
  479. }
  480. }
  481. w.Flush()
  482. return nil
  483. }
  484. func runDeleteUser(c *cli.Context) error {
  485. if !c.IsSet("id") && !c.IsSet("username") && !c.IsSet("email") {
  486. return fmt.Errorf("You must provide the id, username or email of a user to delete")
  487. }
  488. ctx, cancel := installSignals()
  489. defer cancel()
  490. if err := initDB(ctx); err != nil {
  491. return err
  492. }
  493. if err := storage.Init(); err != nil {
  494. return err
  495. }
  496. var err error
  497. var user *user_model.User
  498. if c.IsSet("email") {
  499. user, err = user_model.GetUserByEmail(c.String("email"))
  500. } else if c.IsSet("username") {
  501. user, err = user_model.GetUserByName(c.String("username"))
  502. } else {
  503. user, err = user_model.GetUserByID(c.Int64("id"))
  504. }
  505. if err != nil {
  506. return err
  507. }
  508. if c.IsSet("username") && user.LowerName != strings.ToLower(strings.TrimSpace(c.String("username"))) {
  509. return fmt.Errorf("The user %s who has email %s does not match the provided username %s", user.Name, c.String("email"), c.String("username"))
  510. }
  511. if c.IsSet("id") && user.ID != c.Int64("id") {
  512. return fmt.Errorf("The user %s does not match the provided id %d", user.Name, c.Int64("id"))
  513. }
  514. return user_service.DeleteUser(user)
  515. }
  516. func runRepoSyncReleases(_ *cli.Context) error {
  517. ctx, cancel := installSignals()
  518. defer cancel()
  519. if err := initDB(ctx); err != nil {
  520. return err
  521. }
  522. log.Trace("Synchronizing repository releases (this may take a while)")
  523. for page := 1; ; page++ {
  524. repos, count, err := models.SearchRepositoryByName(&models.SearchRepoOptions{
  525. ListOptions: db.ListOptions{
  526. PageSize: models.RepositoryListDefaultPageSize,
  527. Page: page,
  528. },
  529. Private: true,
  530. })
  531. if err != nil {
  532. return fmt.Errorf("SearchRepositoryByName: %v", err)
  533. }
  534. if len(repos) == 0 {
  535. break
  536. }
  537. log.Trace("Processing next %d repos of %d", len(repos), count)
  538. for _, repo := range repos {
  539. log.Trace("Synchronizing repo %s with path %s", repo.FullName(), repo.RepoPath())
  540. gitRepo, err := git.OpenRepository(repo.RepoPath())
  541. if err != nil {
  542. log.Warn("OpenRepository: %v", err)
  543. continue
  544. }
  545. oldnum, err := getReleaseCount(repo.ID)
  546. if err != nil {
  547. log.Warn(" GetReleaseCountByRepoID: %v", err)
  548. }
  549. log.Trace(" currentNumReleases is %d, running SyncReleasesWithTags", oldnum)
  550. if err = repo_module.SyncReleasesWithTags(repo, gitRepo); err != nil {
  551. log.Warn(" SyncReleasesWithTags: %v", err)
  552. gitRepo.Close()
  553. continue
  554. }
  555. count, err = getReleaseCount(repo.ID)
  556. if err != nil {
  557. log.Warn(" GetReleaseCountByRepoID: %v", err)
  558. gitRepo.Close()
  559. continue
  560. }
  561. log.Trace(" repo %s releases synchronized to tags: from %d to %d",
  562. repo.FullName(), oldnum, count)
  563. gitRepo.Close()
  564. }
  565. }
  566. return nil
  567. }
  568. func getReleaseCount(id int64) (int64, error) {
  569. return models.GetReleaseCountByRepoID(
  570. id,
  571. models.FindReleasesOptions{
  572. IncludeTags: true,
  573. },
  574. )
  575. }
  576. func runRegenerateHooks(_ *cli.Context) error {
  577. ctx, cancel := installSignals()
  578. defer cancel()
  579. if err := initDB(ctx); err != nil {
  580. return err
  581. }
  582. return repo_service.SyncRepositoryHooks(graceful.GetManager().ShutdownContext())
  583. }
  584. func runRegenerateKeys(_ *cli.Context) error {
  585. ctx, cancel := installSignals()
  586. defer cancel()
  587. if err := initDB(ctx); err != nil {
  588. return err
  589. }
  590. return asymkey_model.RewriteAllPublicKeys()
  591. }
  592. func parseOAuth2Config(c *cli.Context) *oauth2.Source {
  593. var customURLMapping *oauth2.CustomURLMapping
  594. if c.IsSet("use-custom-urls") {
  595. customURLMapping = &oauth2.CustomURLMapping{
  596. TokenURL: c.String("custom-token-url"),
  597. AuthURL: c.String("custom-auth-url"),
  598. ProfileURL: c.String("custom-profile-url"),
  599. EmailURL: c.String("custom-email-url"),
  600. }
  601. } else {
  602. customURLMapping = nil
  603. }
  604. return &oauth2.Source{
  605. Provider: c.String("provider"),
  606. ClientID: c.String("key"),
  607. ClientSecret: c.String("secret"),
  608. OpenIDConnectAutoDiscoveryURL: c.String("auto-discover-url"),
  609. CustomURLMapping: customURLMapping,
  610. IconURL: c.String("icon-url"),
  611. SkipLocalTwoFA: c.Bool("skip-local-2fa"),
  612. Scopes: c.StringSlice("scopes"),
  613. RequiredClaimName: c.String("required-claim-name"),
  614. RequiredClaimValue: c.String("required-claim-value"),
  615. GroupClaimName: c.String("group-claim-name"),
  616. AdminGroup: c.String("admin-group"),
  617. RestrictedGroup: c.String("restricted-group"),
  618. }
  619. }
  620. func runAddOauth(c *cli.Context) error {
  621. ctx, cancel := installSignals()
  622. defer cancel()
  623. if err := initDB(ctx); err != nil {
  624. return err
  625. }
  626. return auth.CreateSource(&auth.Source{
  627. Type: auth.OAuth2,
  628. Name: c.String("name"),
  629. IsActive: true,
  630. Cfg: parseOAuth2Config(c),
  631. })
  632. }
  633. func runUpdateOauth(c *cli.Context) error {
  634. if !c.IsSet("id") {
  635. return fmt.Errorf("--id flag is missing")
  636. }
  637. ctx, cancel := installSignals()
  638. defer cancel()
  639. if err := initDB(ctx); err != nil {
  640. return err
  641. }
  642. source, err := auth.GetSourceByID(c.Int64("id"))
  643. if err != nil {
  644. return err
  645. }
  646. oAuth2Config := source.Cfg.(*oauth2.Source)
  647. if c.IsSet("name") {
  648. source.Name = c.String("name")
  649. }
  650. if c.IsSet("provider") {
  651. oAuth2Config.Provider = c.String("provider")
  652. }
  653. if c.IsSet("key") {
  654. oAuth2Config.ClientID = c.String("key")
  655. }
  656. if c.IsSet("secret") {
  657. oAuth2Config.ClientSecret = c.String("secret")
  658. }
  659. if c.IsSet("auto-discover-url") {
  660. oAuth2Config.OpenIDConnectAutoDiscoveryURL = c.String("auto-discover-url")
  661. }
  662. if c.IsSet("icon-url") {
  663. oAuth2Config.IconURL = c.String("icon-url")
  664. }
  665. if c.IsSet("scopes") {
  666. oAuth2Config.Scopes = c.StringSlice("scopes")
  667. }
  668. if c.IsSet("required-claim-name") {
  669. oAuth2Config.RequiredClaimName = c.String("required-claim-name")
  670. }
  671. if c.IsSet("required-claim-value") {
  672. oAuth2Config.RequiredClaimValue = c.String("required-claim-value")
  673. }
  674. if c.IsSet("group-claim-name") {
  675. oAuth2Config.GroupClaimName = c.String("group-claim-name")
  676. }
  677. if c.IsSet("admin-group") {
  678. oAuth2Config.AdminGroup = c.String("admin-group")
  679. }
  680. if c.IsSet("restricted-group") {
  681. oAuth2Config.RestrictedGroup = c.String("restricted-group")
  682. }
  683. // update custom URL mapping
  684. var customURLMapping = &oauth2.CustomURLMapping{}
  685. if oAuth2Config.CustomURLMapping != nil {
  686. customURLMapping.TokenURL = oAuth2Config.CustomURLMapping.TokenURL
  687. customURLMapping.AuthURL = oAuth2Config.CustomURLMapping.AuthURL
  688. customURLMapping.ProfileURL = oAuth2Config.CustomURLMapping.ProfileURL
  689. customURLMapping.EmailURL = oAuth2Config.CustomURLMapping.EmailURL
  690. }
  691. if c.IsSet("use-custom-urls") && c.IsSet("custom-token-url") {
  692. customURLMapping.TokenURL = c.String("custom-token-url")
  693. }
  694. if c.IsSet("use-custom-urls") && c.IsSet("custom-auth-url") {
  695. customURLMapping.AuthURL = c.String("custom-auth-url")
  696. }
  697. if c.IsSet("use-custom-urls") && c.IsSet("custom-profile-url") {
  698. customURLMapping.ProfileURL = c.String("custom-profile-url")
  699. }
  700. if c.IsSet("use-custom-urls") && c.IsSet("custom-email-url") {
  701. customURLMapping.EmailURL = c.String("custom-email-url")
  702. }
  703. oAuth2Config.CustomURLMapping = customURLMapping
  704. source.Cfg = oAuth2Config
  705. return auth.UpdateSource(source)
  706. }
  707. func runListAuth(c *cli.Context) error {
  708. ctx, cancel := installSignals()
  709. defer cancel()
  710. if err := initDB(ctx); err != nil {
  711. return err
  712. }
  713. authSources, err := auth.Sources()
  714. if err != nil {
  715. return err
  716. }
  717. flags := tabwriter.AlignRight
  718. if c.Bool("vertical-bars") {
  719. flags |= tabwriter.Debug
  720. }
  721. padChar := byte('\t')
  722. if len(c.String("pad-char")) > 0 {
  723. padChar = c.String("pad-char")[0]
  724. }
  725. // loop through each source and print
  726. w := tabwriter.NewWriter(os.Stdout, c.Int("min-width"), c.Int("tab-width"), c.Int("padding"), padChar, flags)
  727. fmt.Fprintf(w, "ID\tName\tType\tEnabled\n")
  728. for _, source := range authSources {
  729. fmt.Fprintf(w, "%d\t%s\t%s\t%t\n", source.ID, source.Name, source.Type.String(), source.IsActive)
  730. }
  731. w.Flush()
  732. return nil
  733. }
  734. func runDeleteAuth(c *cli.Context) error {
  735. if !c.IsSet("id") {
  736. return fmt.Errorf("--id flag is missing")
  737. }
  738. ctx, cancel := installSignals()
  739. defer cancel()
  740. if err := initDB(ctx); err != nil {
  741. return err
  742. }
  743. source, err := auth.GetSourceByID(c.Int64("id"))
  744. if err != nil {
  745. return err
  746. }
  747. return auth_service.DeleteSource(source)
  748. }