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.

555 lines
13 KiB

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