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.

559 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/git"
  14. "code.gitea.io/gitea/modules/log"
  15. pwd "code.gitea.io/gitea/modules/password"
  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: "Set this option to false to prevent forcing the user to change their password after initial login, (Default: true)",
  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. if !pwd.IsComplexEnough(c.String("password")) {
  217. return errors.New("Password does not meet complexity requirements")
  218. }
  219. uname := c.String("username")
  220. user, err := models.GetUserByName(uname)
  221. if err != nil {
  222. return err
  223. }
  224. if user.Salt, err = models.GetUserSalt(); err != nil {
  225. return err
  226. }
  227. user.HashPassword(c.String("password"))
  228. if err := models.UpdateUserCols(user, "passwd", "salt"); err != nil {
  229. return err
  230. }
  231. fmt.Printf("%s's password has been successfully updated!\n", user.Name)
  232. return nil
  233. }
  234. func runCreateUser(c *cli.Context) error {
  235. if err := argsSet(c, "email"); err != nil {
  236. return err
  237. }
  238. if c.IsSet("name") && c.IsSet("username") {
  239. return errors.New("Cannot set both --name and --username flags")
  240. }
  241. if !c.IsSet("name") && !c.IsSet("username") {
  242. return errors.New("One of --name or --username flags must be set")
  243. }
  244. if c.IsSet("password") && c.IsSet("random-password") {
  245. return errors.New("cannot set both -random-password and -password flags")
  246. }
  247. var username string
  248. if c.IsSet("username") {
  249. username = c.String("username")
  250. } else {
  251. username = c.String("name")
  252. fmt.Fprintf(os.Stderr, "--name flag is deprecated. Use --username instead.\n")
  253. }
  254. if err := initDB(); err != nil {
  255. return err
  256. }
  257. var password string
  258. if c.IsSet("password") {
  259. password = c.String("password")
  260. } else if c.IsSet("random-password") {
  261. var err error
  262. password, err = pwd.Generate(c.Int("random-password-length"))
  263. if err != nil {
  264. return err
  265. }
  266. fmt.Printf("generated random password is '%s'\n", password)
  267. } else {
  268. return errors.New("must set either password or random-password flag")
  269. }
  270. // always default to true
  271. var changePassword = true
  272. // If this is the first user being created.
  273. // Take it as the admin and don't force a password update.
  274. if n := models.CountUsers(); n == 0 {
  275. changePassword = false
  276. }
  277. if c.IsSet("must-change-password") {
  278. changePassword = c.Bool("must-change-password")
  279. }
  280. u := &models.User{
  281. Name: username,
  282. Email: c.String("email"),
  283. Passwd: password,
  284. IsActive: true,
  285. IsAdmin: c.Bool("admin"),
  286. MustChangePassword: changePassword,
  287. Theme: setting.UI.DefaultTheme,
  288. }
  289. if err := models.CreateUser(u); err != nil {
  290. return fmt.Errorf("CreateUser: %v", err)
  291. }
  292. if c.Bool("access-token") {
  293. t := &models.AccessToken{
  294. Name: "gitea-admin",
  295. UID: u.ID,
  296. }
  297. if err := models.NewAccessToken(t); err != nil {
  298. return err
  299. }
  300. fmt.Printf("Access token was successfully created... %s\n", t.Token)
  301. }
  302. fmt.Printf("New user '%s' has been successfully created!\n", username)
  303. return nil
  304. }
  305. func runRepoSyncReleases(c *cli.Context) error {
  306. if err := initDB(); err != nil {
  307. return err
  308. }
  309. log.Trace("Synchronizing repository releases (this may take a while)")
  310. for page := 1; ; page++ {
  311. repos, count, err := models.SearchRepositoryByName(&models.SearchRepoOptions{
  312. Page: page,
  313. PageSize: models.RepositoryListDefaultPageSize,
  314. Private: true,
  315. })
  316. if err != nil {
  317. return fmt.Errorf("SearchRepositoryByName: %v", err)
  318. }
  319. if len(repos) == 0 {
  320. break
  321. }
  322. log.Trace("Processing next %d repos of %d", len(repos), count)
  323. for _, repo := range repos {
  324. log.Trace("Synchronizing repo %s with path %s", repo.FullName(), repo.RepoPath())
  325. gitRepo, err := git.OpenRepository(repo.RepoPath())
  326. if err != nil {
  327. log.Warn("OpenRepository: %v", err)
  328. continue
  329. }
  330. oldnum, err := getReleaseCount(repo.ID)
  331. if err != nil {
  332. log.Warn(" GetReleaseCountByRepoID: %v", err)
  333. }
  334. log.Trace(" currentNumReleases is %d, running SyncReleasesWithTags", oldnum)
  335. if err = models.SyncReleasesWithTags(repo, gitRepo); err != nil {
  336. log.Warn(" SyncReleasesWithTags: %v", err)
  337. gitRepo.Close()
  338. continue
  339. }
  340. count, err = getReleaseCount(repo.ID)
  341. if err != nil {
  342. log.Warn(" GetReleaseCountByRepoID: %v", err)
  343. gitRepo.Close()
  344. continue
  345. }
  346. log.Trace(" repo %s releases synchronized to tags: from %d to %d",
  347. repo.FullName(), oldnum, count)
  348. gitRepo.Close()
  349. }
  350. }
  351. return nil
  352. }
  353. func getReleaseCount(id int64) (int64, error) {
  354. return models.GetReleaseCountByRepoID(
  355. id,
  356. models.FindReleasesOptions{
  357. IncludeTags: true,
  358. },
  359. )
  360. }
  361. func runRegenerateHooks(c *cli.Context) error {
  362. if err := initDB(); err != nil {
  363. return err
  364. }
  365. return models.SyncRepositoryHooks()
  366. }
  367. func runRegenerateKeys(c *cli.Context) error {
  368. if err := initDB(); err != nil {
  369. return err
  370. }
  371. return models.RewriteAllPublicKeys()
  372. }
  373. func parseOAuth2Config(c *cli.Context) *models.OAuth2Config {
  374. var customURLMapping *oauth2.CustomURLMapping
  375. if c.IsSet("use-custom-urls") {
  376. customURLMapping = &oauth2.CustomURLMapping{
  377. TokenURL: c.String("custom-token-url"),
  378. AuthURL: c.String("custom-auth-url"),
  379. ProfileURL: c.String("custom-profile-url"),
  380. EmailURL: c.String("custom-email-url"),
  381. }
  382. } else {
  383. customURLMapping = nil
  384. }
  385. return &models.OAuth2Config{
  386. Provider: c.String("provider"),
  387. ClientID: c.String("key"),
  388. ClientSecret: c.String("secret"),
  389. OpenIDConnectAutoDiscoveryURL: c.String("auto-discover-url"),
  390. CustomURLMapping: customURLMapping,
  391. }
  392. }
  393. func runAddOauth(c *cli.Context) error {
  394. if err := initDB(); err != nil {
  395. return err
  396. }
  397. return models.CreateLoginSource(&models.LoginSource{
  398. Type: models.LoginOAuth2,
  399. Name: c.String("name"),
  400. IsActived: true,
  401. Cfg: parseOAuth2Config(c),
  402. })
  403. }
  404. func runUpdateOauth(c *cli.Context) error {
  405. if !c.IsSet("id") {
  406. return fmt.Errorf("--id flag is missing")
  407. }
  408. if err := initDB(); err != nil {
  409. return err
  410. }
  411. source, err := models.GetLoginSourceByID(c.Int64("id"))
  412. if err != nil {
  413. return err
  414. }
  415. oAuth2Config := source.OAuth2()
  416. if c.IsSet("name") {
  417. source.Name = c.String("name")
  418. }
  419. if c.IsSet("provider") {
  420. oAuth2Config.Provider = c.String("provider")
  421. }
  422. if c.IsSet("key") {
  423. oAuth2Config.ClientID = c.String("key")
  424. }
  425. if c.IsSet("secret") {
  426. oAuth2Config.ClientSecret = c.String("secret")
  427. }
  428. if c.IsSet("auto-discover-url") {
  429. oAuth2Config.OpenIDConnectAutoDiscoveryURL = c.String("auto-discover-url")
  430. }
  431. // update custom URL mapping
  432. var customURLMapping = &oauth2.CustomURLMapping{}
  433. if oAuth2Config.CustomURLMapping != nil {
  434. customURLMapping.TokenURL = oAuth2Config.CustomURLMapping.TokenURL
  435. customURLMapping.AuthURL = oAuth2Config.CustomURLMapping.AuthURL
  436. customURLMapping.ProfileURL = oAuth2Config.CustomURLMapping.ProfileURL
  437. customURLMapping.EmailURL = oAuth2Config.CustomURLMapping.EmailURL
  438. }
  439. if c.IsSet("use-custom-urls") && c.IsSet("custom-token-url") {
  440. customURLMapping.TokenURL = c.String("custom-token-url")
  441. }
  442. if c.IsSet("use-custom-urls") && c.IsSet("custom-auth-url") {
  443. customURLMapping.AuthURL = c.String("custom-auth-url")
  444. }
  445. if c.IsSet("use-custom-urls") && c.IsSet("custom-profile-url") {
  446. customURLMapping.ProfileURL = c.String("custom-profile-url")
  447. }
  448. if c.IsSet("use-custom-urls") && c.IsSet("custom-email-url") {
  449. customURLMapping.EmailURL = c.String("custom-email-url")
  450. }
  451. oAuth2Config.CustomURLMapping = customURLMapping
  452. source.Cfg = oAuth2Config
  453. return models.UpdateSource(source)
  454. }
  455. func runListAuth(c *cli.Context) error {
  456. if err := initDB(); err != nil {
  457. return err
  458. }
  459. loginSources, err := models.LoginSources()
  460. if err != nil {
  461. return err
  462. }
  463. // loop through each source and print
  464. w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.AlignRight)
  465. fmt.Fprintf(w, "ID\tName\tType\tEnabled")
  466. for _, source := range loginSources {
  467. fmt.Fprintf(w, "%d\t%s\t%s\t%t", source.ID, source.Name, models.LoginNames[source.Type], source.IsActived)
  468. }
  469. w.Flush()
  470. return nil
  471. }
  472. func runDeleteAuth(c *cli.Context) error {
  473. if !c.IsSet("id") {
  474. return fmt.Errorf("--id flag is missing")
  475. }
  476. if err := initDB(); err != nil {
  477. return err
  478. }
  479. source, err := models.GetLoginSourceByID(c.Int64("id"))
  480. if err != nil {
  481. return err
  482. }
  483. return models.DeleteSource(source)
  484. }