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

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