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

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