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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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. Theme: setting.UI.DefaultTheme,
  310. }); err != nil {
  311. return fmt.Errorf("CreateUser: %v", err)
  312. }
  313. fmt.Printf("New user '%s' has been successfully created!\n", c.String("name"))
  314. return nil
  315. }
  316. func runRepoSyncReleases(c *cli.Context) error {
  317. if err := initDB(); err != nil {
  318. return err
  319. }
  320. log.Trace("Synchronizing repository releases (this may take a while)")
  321. for page := 1; ; page++ {
  322. repos, count, err := models.SearchRepositoryByName(&models.SearchRepoOptions{
  323. Page: page,
  324. PageSize: models.RepositoryListDefaultPageSize,
  325. Private: true,
  326. })
  327. if err != nil {
  328. return fmt.Errorf("SearchRepositoryByName: %v", err)
  329. }
  330. if len(repos) == 0 {
  331. break
  332. }
  333. log.Trace("Processing next %d repos of %d", len(repos), count)
  334. for _, repo := range repos {
  335. log.Trace("Synchronizing repo %s with path %s", repo.FullName(), repo.RepoPath())
  336. gitRepo, err := git.OpenRepository(repo.RepoPath())
  337. if err != nil {
  338. log.Warn("OpenRepository: %v", err)
  339. continue
  340. }
  341. oldnum, err := getReleaseCount(repo.ID)
  342. if err != nil {
  343. log.Warn(" GetReleaseCountByRepoID: %v", err)
  344. }
  345. log.Trace(" currentNumReleases is %d, running SyncReleasesWithTags", oldnum)
  346. if err = models.SyncReleasesWithTags(repo, gitRepo); err != nil {
  347. log.Warn(" SyncReleasesWithTags: %v", err)
  348. continue
  349. }
  350. count, err = getReleaseCount(repo.ID)
  351. if err != nil {
  352. log.Warn(" GetReleaseCountByRepoID: %v", err)
  353. continue
  354. }
  355. log.Trace(" repo %s releases synchronized to tags: from %d to %d",
  356. repo.FullName(), oldnum, count)
  357. }
  358. }
  359. return nil
  360. }
  361. func getReleaseCount(id int64) (int64, error) {
  362. return models.GetReleaseCountByRepoID(
  363. id,
  364. models.FindReleasesOptions{
  365. IncludeTags: true,
  366. },
  367. )
  368. }
  369. func runRegenerateHooks(c *cli.Context) error {
  370. if c.IsSet("config") {
  371. setting.CustomConf = c.String("config")
  372. }
  373. if err := initDB(); err != nil {
  374. return err
  375. }
  376. return models.SyncRepositoryHooks()
  377. }
  378. func runRegenerateKeys(c *cli.Context) error {
  379. if c.IsSet("config") {
  380. setting.CustomConf = c.String("config")
  381. }
  382. if err := initDB(); err != nil {
  383. return err
  384. }
  385. return models.RewriteAllPublicKeys()
  386. }
  387. func parseOAuth2Config(c *cli.Context) *models.OAuth2Config {
  388. var customURLMapping *oauth2.CustomURLMapping
  389. if c.IsSet("use-custom-urls") {
  390. customURLMapping = &oauth2.CustomURLMapping{
  391. TokenURL: c.String("custom-token-url"),
  392. AuthURL: c.String("custom-auth-url"),
  393. ProfileURL: c.String("custom-profile-url"),
  394. EmailURL: c.String("custom-email-url"),
  395. }
  396. } else {
  397. customURLMapping = nil
  398. }
  399. return &models.OAuth2Config{
  400. Provider: c.String("provider"),
  401. ClientID: c.String("key"),
  402. ClientSecret: c.String("secret"),
  403. OpenIDConnectAutoDiscoveryURL: c.String("auto-discover-url"),
  404. CustomURLMapping: customURLMapping,
  405. }
  406. }
  407. func runAddOauth(c *cli.Context) error {
  408. if c.IsSet("config") {
  409. setting.CustomConf = c.String("config")
  410. }
  411. if err := initDB(); err != nil {
  412. return err
  413. }
  414. return models.CreateLoginSource(&models.LoginSource{
  415. Type: models.LoginOAuth2,
  416. Name: c.String("name"),
  417. IsActived: true,
  418. Cfg: parseOAuth2Config(c),
  419. })
  420. }
  421. func runUpdateOauth(c *cli.Context) error {
  422. if c.IsSet("config") {
  423. setting.CustomConf = c.String("config")
  424. }
  425. if !c.IsSet("id") {
  426. return fmt.Errorf("--id flag is missing")
  427. }
  428. if err := initDB(); err != nil {
  429. return err
  430. }
  431. source, err := models.GetLoginSourceByID(c.Int64("id"))
  432. if err != nil {
  433. return err
  434. }
  435. oAuth2Config := source.OAuth2()
  436. if c.IsSet("name") {
  437. source.Name = c.String("name")
  438. }
  439. if c.IsSet("provider") {
  440. oAuth2Config.Provider = c.String("provider")
  441. }
  442. if c.IsSet("key") {
  443. oAuth2Config.ClientID = c.String("key")
  444. }
  445. if c.IsSet("secret") {
  446. oAuth2Config.ClientSecret = c.String("secret")
  447. }
  448. if c.IsSet("auto-discover-url") {
  449. oAuth2Config.OpenIDConnectAutoDiscoveryURL = c.String("auto-discover-url")
  450. }
  451. // update custom URL mapping
  452. var customURLMapping *oauth2.CustomURLMapping
  453. if oAuth2Config.CustomURLMapping != nil {
  454. customURLMapping.TokenURL = oAuth2Config.CustomURLMapping.TokenURL
  455. customURLMapping.AuthURL = oAuth2Config.CustomURLMapping.AuthURL
  456. customURLMapping.ProfileURL = oAuth2Config.CustomURLMapping.ProfileURL
  457. customURLMapping.EmailURL = oAuth2Config.CustomURLMapping.EmailURL
  458. }
  459. if c.IsSet("use-custom-urls") && c.IsSet("custom-token-url") {
  460. customURLMapping.TokenURL = c.String("custom-token-url")
  461. }
  462. if c.IsSet("use-custom-urls") && c.IsSet("custom-auth-url") {
  463. customURLMapping.AuthURL = c.String("custom-auth-url")
  464. }
  465. if c.IsSet("use-custom-urls") && c.IsSet("custom-profile-url") {
  466. customURLMapping.ProfileURL = c.String("custom-profile-url")
  467. }
  468. if c.IsSet("use-custom-urls") && c.IsSet("custom-email-url") {
  469. customURLMapping.EmailURL = c.String("custom-email-url")
  470. }
  471. oAuth2Config.CustomURLMapping = customURLMapping
  472. source.Cfg = oAuth2Config
  473. return models.UpdateSource(source)
  474. }
  475. func runListAuth(c *cli.Context) error {
  476. if c.IsSet("config") {
  477. setting.CustomConf = c.String("config")
  478. }
  479. if err := initDB(); err != nil {
  480. return err
  481. }
  482. loginSources, err := models.LoginSources()
  483. if err != nil {
  484. return err
  485. }
  486. // loop through each source and print
  487. w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.AlignRight)
  488. fmt.Fprintf(w, "ID\tName\tType\tEnabled")
  489. for _, source := range loginSources {
  490. fmt.Fprintf(w, "%d\t%s\t%s\t%t", source.ID, source.Name, models.LoginNames[source.Type], source.IsActived)
  491. }
  492. w.Flush()
  493. return nil
  494. }
  495. func runDeleteAuth(c *cli.Context) error {
  496. if c.IsSet("config") {
  497. setting.CustomConf = c.String("config")
  498. }
  499. if !c.IsSet("id") {
  500. return fmt.Errorf("--id flag is missing")
  501. }
  502. if err := initDB(); err != nil {
  503. return err
  504. }
  505. source, err := models.GetLoginSourceByID(c.Int64("id"))
  506. if err != nil {
  507. return err
  508. }
  509. return models.DeleteSource(source)
  510. }