本站源代码
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.

557 lines
13KB

  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: "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. 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. continue
  338. }
  339. count, err = getReleaseCount(repo.ID)
  340. if err != nil {
  341. log.Warn(" GetReleaseCountByRepoID: %v", err)
  342. continue
  343. }
  344. log.Trace(" repo %s releases synchronized to tags: from %d to %d",
  345. repo.FullName(), oldnum, count)
  346. }
  347. }
  348. return nil
  349. }
  350. func getReleaseCount(id int64) (int64, error) {
  351. return models.GetReleaseCountByRepoID(
  352. id,
  353. models.FindReleasesOptions{
  354. IncludeTags: true,
  355. },
  356. )
  357. }
  358. func runRegenerateHooks(c *cli.Context) error {
  359. if err := initDB(); err != nil {
  360. return err
  361. }
  362. return models.SyncRepositoryHooks()
  363. }
  364. func runRegenerateKeys(c *cli.Context) error {
  365. if err := initDB(); err != nil {
  366. return err
  367. }
  368. return models.RewriteAllPublicKeys()
  369. }
  370. func parseOAuth2Config(c *cli.Context) *models.OAuth2Config {
  371. var customURLMapping *oauth2.CustomURLMapping
  372. if c.IsSet("use-custom-urls") {
  373. customURLMapping = &oauth2.CustomURLMapping{
  374. TokenURL: c.String("custom-token-url"),
  375. AuthURL: c.String("custom-auth-url"),
  376. ProfileURL: c.String("custom-profile-url"),
  377. EmailURL: c.String("custom-email-url"),
  378. }
  379. } else {
  380. customURLMapping = nil
  381. }
  382. return &models.OAuth2Config{
  383. Provider: c.String("provider"),
  384. ClientID: c.String("key"),
  385. ClientSecret: c.String("secret"),
  386. OpenIDConnectAutoDiscoveryURL: c.String("auto-discover-url"),
  387. CustomURLMapping: customURLMapping,
  388. }
  389. }
  390. func runAddOauth(c *cli.Context) error {
  391. if err := initDB(); err != nil {
  392. return err
  393. }
  394. return models.CreateLoginSource(&models.LoginSource{
  395. Type: models.LoginOAuth2,
  396. Name: c.String("name"),
  397. IsActived: true,
  398. Cfg: parseOAuth2Config(c),
  399. })
  400. }
  401. func runUpdateOauth(c *cli.Context) error {
  402. if !c.IsSet("id") {
  403. return fmt.Errorf("--id flag is missing")
  404. }
  405. if err := initDB(); err != nil {
  406. return err
  407. }
  408. source, err := models.GetLoginSourceByID(c.Int64("id"))
  409. if err != nil {
  410. return err
  411. }
  412. oAuth2Config := source.OAuth2()
  413. if c.IsSet("name") {
  414. source.Name = c.String("name")
  415. }
  416. if c.IsSet("provider") {
  417. oAuth2Config.Provider = c.String("provider")
  418. }
  419. if c.IsSet("key") {
  420. oAuth2Config.ClientID = c.String("key")
  421. }
  422. if c.IsSet("secret") {
  423. oAuth2Config.ClientSecret = c.String("secret")
  424. }
  425. if c.IsSet("auto-discover-url") {
  426. oAuth2Config.OpenIDConnectAutoDiscoveryURL = c.String("auto-discover-url")
  427. }
  428. // update custom URL mapping
  429. var customURLMapping = &oauth2.CustomURLMapping{}
  430. if oAuth2Config.CustomURLMapping != nil {
  431. customURLMapping.TokenURL = oAuth2Config.CustomURLMapping.TokenURL
  432. customURLMapping.AuthURL = oAuth2Config.CustomURLMapping.AuthURL
  433. customURLMapping.ProfileURL = oAuth2Config.CustomURLMapping.ProfileURL
  434. customURLMapping.EmailURL = oAuth2Config.CustomURLMapping.EmailURL
  435. }
  436. if c.IsSet("use-custom-urls") && c.IsSet("custom-token-url") {
  437. customURLMapping.TokenURL = c.String("custom-token-url")
  438. }
  439. if c.IsSet("use-custom-urls") && c.IsSet("custom-auth-url") {
  440. customURLMapping.AuthURL = c.String("custom-auth-url")
  441. }
  442. if c.IsSet("use-custom-urls") && c.IsSet("custom-profile-url") {
  443. customURLMapping.ProfileURL = c.String("custom-profile-url")
  444. }
  445. if c.IsSet("use-custom-urls") && c.IsSet("custom-email-url") {
  446. customURLMapping.EmailURL = c.String("custom-email-url")
  447. }
  448. oAuth2Config.CustomURLMapping = customURLMapping
  449. source.Cfg = oAuth2Config
  450. return models.UpdateSource(source)
  451. }
  452. func runListAuth(c *cli.Context) error {
  453. if err := initDB(); err != nil {
  454. return err
  455. }
  456. loginSources, err := models.LoginSources()
  457. if err != nil {
  458. return err
  459. }
  460. // loop through each source and print
  461. w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.AlignRight)
  462. fmt.Fprintf(w, "ID\tName\tType\tEnabled")
  463. for _, source := range loginSources {
  464. fmt.Fprintf(w, "%d\t%s\t%s\t%t", source.ID, source.Name, models.LoginNames[source.Type], source.IsActived)
  465. }
  466. w.Flush()
  467. return nil
  468. }
  469. func runDeleteAuth(c *cli.Context) error {
  470. if !c.IsSet("id") {
  471. return fmt.Errorf("--id flag is missing")
  472. }
  473. if err := initDB(); err != nil {
  474. return err
  475. }
  476. source, err := models.GetLoginSourceByID(c.Int64("id"))
  477. if err != nil {
  478. return err
  479. }
  480. return models.DeleteSource(source)
  481. }
上海开阖软件有限公司 沪ICP备12045867号-1