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.

588 lines
13 KiB

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