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

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