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.

admin.go 13KB

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