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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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. "errors"
  8. "fmt"
  9. "os"
  10. "text/tabwriter"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/auth/oauth2"
  13. "code.gitea.io/gitea/modules/generate"
  14. "code.gitea.io/gitea/modules/git"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. "github.com/urfave/cli"
  18. )
  19. var (
  20. // CmdAdmin represents the available admin sub-command.
  21. CmdAdmin = cli.Command{
  22. Name: "admin",
  23. Usage: "Command line interface to perform common administrative operations",
  24. Subcommands: []cli.Command{
  25. subcmdCreateUser,
  26. subcmdChangePassword,
  27. subcmdRepoSyncReleases,
  28. subcmdRegenerate,
  29. subcmdAuth,
  30. },
  31. }
  32. subcmdCreateUser = cli.Command{
  33. Name: "create-user",
  34. Usage: "Create a new user in database",
  35. Action: runCreateUser,
  36. Flags: []cli.Flag{
  37. cli.StringFlag{
  38. Name: "name",
  39. Usage: "Username. DEPRECATED: use username instead",
  40. },
  41. cli.StringFlag{
  42. Name: "username",
  43. Usage: "Username",
  44. },
  45. cli.StringFlag{
  46. Name: "password",
  47. Usage: "User password",
  48. },
  49. cli.StringFlag{
  50. Name: "email",
  51. Usage: "User email address",
  52. },
  53. cli.BoolFlag{
  54. Name: "admin",
  55. Usage: "User is an admin",
  56. },
  57. cli.StringFlag{
  58. Name: "config, c",
  59. Value: "custom/conf/app.ini",
  60. Usage: "Custom configuration file path",
  61. },
  62. cli.BoolFlag{
  63. Name: "random-password",
  64. Usage: "Generate a random password for the user",
  65. },
  66. cli.BoolFlag{
  67. Name: "must-change-password",
  68. Usage: "Force the user to change his/her password after initial login",
  69. },
  70. cli.IntFlag{
  71. Name: "random-password-length",
  72. Usage: "Length of the random password to be generated",
  73. Value: 12,
  74. },
  75. },
  76. }
  77. subcmdChangePassword = cli.Command{
  78. Name: "change-password",
  79. Usage: "Change a user's password",
  80. Action: runChangePassword,
  81. Flags: []cli.Flag{
  82. cli.StringFlag{
  83. Name: "username,u",
  84. Value: "",
  85. Usage: "The user to change password for",
  86. },
  87. cli.StringFlag{
  88. Name: "password,p",
  89. Value: "",
  90. Usage: "New password to set for user",
  91. },
  92. cli.StringFlag{
  93. Name: "config, c",
  94. Value: "custom/conf/app.ini",
  95. Usage: "Custom configuration file path",
  96. },
  97. },
  98. }
  99. subcmdRepoSyncReleases = cli.Command{
  100. Name: "repo-sync-releases",
  101. Usage: "Synchronize repository releases with tags",
  102. Action: runRepoSyncReleases,
  103. }
  104. subcmdRegenerate = cli.Command{
  105. Name: "regenerate",
  106. Usage: "Regenerate specific files",
  107. Subcommands: []cli.Command{
  108. microcmdRegenHooks,
  109. microcmdRegenKeys,
  110. },
  111. }
  112. microcmdRegenHooks = cli.Command{
  113. Name: "hooks",
  114. Usage: "Regenerate git-hooks",
  115. Action: runRegenerateHooks,
  116. Flags: []cli.Flag{
  117. cli.StringFlag{
  118. Name: "config, c",
  119. Value: "custom/conf/app.ini",
  120. Usage: "Custom configuration file path",
  121. },
  122. },
  123. }
  124. microcmdRegenKeys = cli.Command{
  125. Name: "keys",
  126. Usage: "Regenerate authorized_keys file",
  127. Action: runRegenerateKeys,
  128. Flags: []cli.Flag{
  129. cli.StringFlag{
  130. Name: "config, c",
  131. Value: "custom/conf/app.ini",
  132. Usage: "Custom configuration file path",
  133. },
  134. },
  135. }
  136. subcmdAuth = cli.Command{
  137. Name: "auth",
  138. Usage: "Modify external auth providers",
  139. Subcommands: []cli.Command{
  140. microcmdAuthAddOauth,
  141. microcmdAuthUpdateOauth,
  142. microcmdAuthList,
  143. microcmdAuthDelete,
  144. },
  145. }
  146. microcmdAuthList = cli.Command{
  147. Name: "list",
  148. Usage: "List auth sources",
  149. Action: runListAuth,
  150. Flags: []cli.Flag{
  151. cli.StringFlag{
  152. Name: "config, c",
  153. Value: "custom/conf/app.ini",
  154. Usage: "Custom configuration file path",
  155. },
  156. },
  157. }
  158. idFlag = cli.Int64Flag{
  159. Name: "id",
  160. Usage: "ID of OAuth authentication source",
  161. }
  162. microcmdAuthDelete = cli.Command{
  163. Name: "delete",
  164. Usage: "Delete specific auth source",
  165. Action: runDeleteAuth,
  166. Flags: []cli.Flag{
  167. cli.StringFlag{
  168. Name: "config, c",
  169. Value: "custom/conf/app.ini",
  170. Usage: "Custom configuration file path",
  171. },
  172. idFlag,
  173. },
  174. }
  175. oauthCLIFlags = []cli.Flag{
  176. cli.StringFlag{
  177. Name: "config, c",
  178. Value: "custom/conf/app.ini",
  179. Usage: "Custom configuration file path",
  180. },
  181. cli.StringFlag{
  182. Name: "name",
  183. Value: "",
  184. Usage: "Application Name",
  185. },
  186. cli.StringFlag{
  187. Name: "provider",
  188. Value: "",
  189. Usage: "OAuth2 Provider",
  190. },
  191. cli.StringFlag{
  192. Name: "key",
  193. Value: "",
  194. Usage: "Client ID (Key)",
  195. },
  196. cli.StringFlag{
  197. Name: "secret",
  198. Value: "",
  199. Usage: "Client Secret",
  200. },
  201. cli.StringFlag{
  202. Name: "auto-discover-url",
  203. Value: "",
  204. Usage: "OpenID Connect Auto Discovery URL (only required when using OpenID Connect as provider)",
  205. },
  206. cli.StringFlag{
  207. Name: "use-custom-urls",
  208. Value: "false",
  209. Usage: "Use custom URLs for GitLab/GitHub OAuth endpoints",
  210. },
  211. cli.StringFlag{
  212. Name: "custom-auth-url",
  213. Value: "",
  214. Usage: "Use a custom Authorization URL (option for GitLab/GitHub)",
  215. },
  216. cli.StringFlag{
  217. Name: "custom-token-url",
  218. Value: "",
  219. Usage: "Use a custom Token URL (option for GitLab/GitHub)",
  220. },
  221. cli.StringFlag{
  222. Name: "custom-profile-url",
  223. Value: "",
  224. Usage: "Use a custom Profile URL (option for GitLab/GitHub)",
  225. },
  226. cli.StringFlag{
  227. Name: "custom-email-url",
  228. Value: "",
  229. Usage: "Use a custom Email URL (option for GitHub)",
  230. },
  231. }
  232. microcmdAuthUpdateOauth = cli.Command{
  233. Name: "update-oauth",
  234. Usage: "Update existing Oauth authentication source",
  235. Action: runUpdateOauth,
  236. Flags: append(oauthCLIFlags[:1], append([]cli.Flag{idFlag}, oauthCLIFlags[1:]...)...),
  237. }
  238. microcmdAuthAddOauth = cli.Command{
  239. Name: "add-oauth",
  240. Usage: "Add new Oauth authentication source",
  241. Action: runAddOauth,
  242. Flags: oauthCLIFlags,
  243. }
  244. )
  245. func runChangePassword(c *cli.Context) error {
  246. if err := argsSet(c, "username", "password"); err != nil {
  247. return err
  248. }
  249. if c.IsSet("config") {
  250. setting.CustomConf = c.String("config")
  251. }
  252. if err := initDB(); err != nil {
  253. return err
  254. }
  255. uname := c.String("username")
  256. user, err := models.GetUserByName(uname)
  257. if err != nil {
  258. return err
  259. }
  260. if user.Salt, err = models.GetUserSalt(); err != nil {
  261. return err
  262. }
  263. user.HashPassword(c.String("password"))
  264. if err := models.UpdateUserCols(user, "passwd", "salt"); err != nil {
  265. return err
  266. }
  267. fmt.Printf("%s's password has been successfully updated!\n", user.Name)
  268. return nil
  269. }
  270. func runCreateUser(c *cli.Context) error {
  271. if err := argsSet(c, "email"); err != nil {
  272. return err
  273. }
  274. if c.IsSet("name") && c.IsSet("username") {
  275. return errors.New("Cannot set both --name and --username flags")
  276. }
  277. if !c.IsSet("name") && !c.IsSet("username") {
  278. return errors.New("One of --name or --username flags must be set")
  279. }
  280. if c.IsSet("password") && c.IsSet("random-password") {
  281. return errors.New("cannot set both -random-password and -password flags")
  282. }
  283. var username string
  284. if c.IsSet("username") {
  285. username = c.String("username")
  286. } else {
  287. username = c.String("name")
  288. fmt.Fprintf(os.Stderr, "--name flag is deprecated. Use --username instead.\n")
  289. }
  290. var password string
  291. if c.IsSet("password") {
  292. password = c.String("password")
  293. } else if c.IsSet("random-password") {
  294. var err error
  295. password, err = generate.GetRandomString(c.Int("random-password-length"))
  296. if err != nil {
  297. return err
  298. }
  299. fmt.Printf("generated random password is '%s'\n", password)
  300. } else {
  301. return errors.New("must set either password or random-password flag")
  302. }
  303. if c.IsSet("config") {
  304. setting.CustomConf = c.String("config")
  305. }
  306. if err := initDB(); err != nil {
  307. return err
  308. }
  309. // always default to true
  310. var changePassword = true
  311. // If this is the first user being created.
  312. // Take it as the admin and don't force a password update.
  313. if n := models.CountUsers(); n == 0 {
  314. changePassword = false
  315. }
  316. if c.IsSet("must-change-password") {
  317. changePassword = c.Bool("must-change-password")
  318. }
  319. if err := models.CreateUser(&models.User{
  320. Name: username,
  321. Email: c.String("email"),
  322. Passwd: password,
  323. IsActive: true,
  324. IsAdmin: c.Bool("admin"),
  325. MustChangePassword: changePassword,
  326. Theme: setting.UI.DefaultTheme,
  327. }); err != nil {
  328. return fmt.Errorf("CreateUser: %v", err)
  329. }
  330. fmt.Printf("New user '%s' has been successfully created!\n", username)
  331. return nil
  332. }
  333. func runRepoSyncReleases(c *cli.Context) error {
  334. if err := initDB(); err != nil {
  335. return err
  336. }
  337. log.Trace("Synchronizing repository releases (this may take a while)")
  338. for page := 1; ; page++ {
  339. repos, count, err := models.SearchRepositoryByName(&models.SearchRepoOptions{
  340. Page: page,
  341. PageSize: models.RepositoryListDefaultPageSize,
  342. Private: true,
  343. })
  344. if err != nil {
  345. return fmt.Errorf("SearchRepositoryByName: %v", err)
  346. }
  347. if len(repos) == 0 {
  348. break
  349. }
  350. log.Trace("Processing next %d repos of %d", len(repos), count)
  351. for _, repo := range repos {
  352. log.Trace("Synchronizing repo %s with path %s", repo.FullName(), repo.RepoPath())
  353. gitRepo, err := git.OpenRepository(repo.RepoPath())
  354. if err != nil {
  355. log.Warn("OpenRepository: %v", err)
  356. continue
  357. }
  358. oldnum, err := getReleaseCount(repo.ID)
  359. if err != nil {
  360. log.Warn(" GetReleaseCountByRepoID: %v", err)
  361. }
  362. log.Trace(" currentNumReleases is %d, running SyncReleasesWithTags", oldnum)
  363. if err = models.SyncReleasesWithTags(repo, gitRepo); err != nil {
  364. log.Warn(" SyncReleasesWithTags: %v", err)
  365. continue
  366. }
  367. count, err = getReleaseCount(repo.ID)
  368. if err != nil {
  369. log.Warn(" GetReleaseCountByRepoID: %v", err)
  370. continue
  371. }
  372. log.Trace(" repo %s releases synchronized to tags: from %d to %d",
  373. repo.FullName(), oldnum, count)
  374. }
  375. }
  376. return nil
  377. }
  378. func getReleaseCount(id int64) (int64, error) {
  379. return models.GetReleaseCountByRepoID(
  380. id,
  381. models.FindReleasesOptions{
  382. IncludeTags: true,
  383. },
  384. )
  385. }
  386. func runRegenerateHooks(c *cli.Context) error {
  387. if c.IsSet("config") {
  388. setting.CustomConf = c.String("config")
  389. }
  390. if err := initDB(); err != nil {
  391. return err
  392. }
  393. return models.SyncRepositoryHooks()
  394. }
  395. func runRegenerateKeys(c *cli.Context) error {
  396. if c.IsSet("config") {
  397. setting.CustomConf = c.String("config")
  398. }
  399. if err := initDB(); err != nil {
  400. return err
  401. }
  402. return models.RewriteAllPublicKeys()
  403. }
  404. func parseOAuth2Config(c *cli.Context) *models.OAuth2Config {
  405. var customURLMapping *oauth2.CustomURLMapping
  406. if c.IsSet("use-custom-urls") {
  407. customURLMapping = &oauth2.CustomURLMapping{
  408. TokenURL: c.String("custom-token-url"),
  409. AuthURL: c.String("custom-auth-url"),
  410. ProfileURL: c.String("custom-profile-url"),
  411. EmailURL: c.String("custom-email-url"),
  412. }
  413. } else {
  414. customURLMapping = nil
  415. }
  416. return &models.OAuth2Config{
  417. Provider: c.String("provider"),
  418. ClientID: c.String("key"),
  419. ClientSecret: c.String("secret"),
  420. OpenIDConnectAutoDiscoveryURL: c.String("auto-discover-url"),
  421. CustomURLMapping: customURLMapping,
  422. }
  423. }
  424. func runAddOauth(c *cli.Context) error {
  425. if c.IsSet("config") {
  426. setting.CustomConf = c.String("config")
  427. }
  428. if err := initDB(); err != nil {
  429. return err
  430. }
  431. return models.CreateLoginSource(&models.LoginSource{
  432. Type: models.LoginOAuth2,
  433. Name: c.String("name"),
  434. IsActived: true,
  435. Cfg: parseOAuth2Config(c),
  436. })
  437. }
  438. func runUpdateOauth(c *cli.Context) error {
  439. if c.IsSet("config") {
  440. setting.CustomConf = c.String("config")
  441. }
  442. if !c.IsSet("id") {
  443. return fmt.Errorf("--id flag is missing")
  444. }
  445. if err := initDB(); err != nil {
  446. return err
  447. }
  448. source, err := models.GetLoginSourceByID(c.Int64("id"))
  449. if err != nil {
  450. return err
  451. }
  452. oAuth2Config := source.OAuth2()
  453. if c.IsSet("name") {
  454. source.Name = c.String("name")
  455. }
  456. if c.IsSet("provider") {
  457. oAuth2Config.Provider = c.String("provider")
  458. }
  459. if c.IsSet("key") {
  460. oAuth2Config.ClientID = c.String("key")
  461. }
  462. if c.IsSet("secret") {
  463. oAuth2Config.ClientSecret = c.String("secret")
  464. }
  465. if c.IsSet("auto-discover-url") {
  466. oAuth2Config.OpenIDConnectAutoDiscoveryURL = c.String("auto-discover-url")
  467. }
  468. // update custom URL mapping
  469. var customURLMapping *oauth2.CustomURLMapping
  470. if oAuth2Config.CustomURLMapping != nil {
  471. customURLMapping.TokenURL = oAuth2Config.CustomURLMapping.TokenURL
  472. customURLMapping.AuthURL = oAuth2Config.CustomURLMapping.AuthURL
  473. customURLMapping.ProfileURL = oAuth2Config.CustomURLMapping.ProfileURL
  474. customURLMapping.EmailURL = oAuth2Config.CustomURLMapping.EmailURL
  475. }
  476. if c.IsSet("use-custom-urls") && c.IsSet("custom-token-url") {
  477. customURLMapping.TokenURL = c.String("custom-token-url")
  478. }
  479. if c.IsSet("use-custom-urls") && c.IsSet("custom-auth-url") {
  480. customURLMapping.AuthURL = c.String("custom-auth-url")
  481. }
  482. if c.IsSet("use-custom-urls") && c.IsSet("custom-profile-url") {
  483. customURLMapping.ProfileURL = c.String("custom-profile-url")
  484. }
  485. if c.IsSet("use-custom-urls") && c.IsSet("custom-email-url") {
  486. customURLMapping.EmailURL = c.String("custom-email-url")
  487. }
  488. oAuth2Config.CustomURLMapping = customURLMapping
  489. source.Cfg = oAuth2Config
  490. return models.UpdateSource(source)
  491. }
  492. func runListAuth(c *cli.Context) error {
  493. if c.IsSet("config") {
  494. setting.CustomConf = c.String("config")
  495. }
  496. if err := initDB(); err != nil {
  497. return err
  498. }
  499. loginSources, err := models.LoginSources()
  500. if err != nil {
  501. return err
  502. }
  503. // loop through each source and print
  504. w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.AlignRight)
  505. fmt.Fprintf(w, "ID\tName\tType\tEnabled")
  506. for _, source := range loginSources {
  507. fmt.Fprintf(w, "%d\t%s\t%s\t%t", source.ID, source.Name, models.LoginNames[source.Type], source.IsActived)
  508. }
  509. w.Flush()
  510. return nil
  511. }
  512. func runDeleteAuth(c *cli.Context) error {
  513. if c.IsSet("config") {
  514. setting.CustomConf = c.String("config")
  515. }
  516. if !c.IsSet("id") {
  517. return fmt.Errorf("--id flag is missing")
  518. }
  519. if err := initDB(); err != nil {
  520. return err
  521. }
  522. source, err := models.GetLoginSourceByID(c.Int64("id"))
  523. if err != nil {
  524. return err
  525. }
  526. return models.DeleteSource(source)
  527. }