You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

admin.go 14 kB

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