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

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