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.

install.go 13KB

10 years ago
10 years ago
10 years ago
10 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
10 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
7 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
6 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
9 years ago
8 years ago
9 years ago
10 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
7 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
6 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package routers
  5. import (
  6. "errors"
  7. "os"
  8. "os/exec"
  9. "path"
  10. "path/filepath"
  11. "strings"
  12. "github.com/Unknwon/com"
  13. "github.com/go-xorm/xorm"
  14. "gopkg.in/ini.v1"
  15. "code.gitea.io/gitea/models"
  16. "code.gitea.io/gitea/modules/auth"
  17. "code.gitea.io/gitea/modules/base"
  18. "code.gitea.io/gitea/modules/context"
  19. "code.gitea.io/gitea/modules/generate"
  20. "code.gitea.io/gitea/modules/log"
  21. "code.gitea.io/gitea/modules/setting"
  22. "code.gitea.io/gitea/modules/user"
  23. )
  24. const (
  25. // tplInstall template for installation page
  26. tplInstall base.TplName = "install"
  27. )
  28. // InstallInit prepare for rendering installation page
  29. func InstallInit(ctx *context.Context) {
  30. if setting.InstallLock {
  31. ctx.NotFound("Install", errors.New("Installation is prohibited"))
  32. return
  33. }
  34. ctx.Data["Title"] = ctx.Tr("install.install")
  35. ctx.Data["PageIsInstall"] = true
  36. dbOpts := []string{"MySQL", "PostgreSQL", "MSSQL"}
  37. if models.EnableSQLite3 {
  38. dbOpts = append(dbOpts, "SQLite3")
  39. }
  40. if models.EnableTiDB {
  41. dbOpts = append(dbOpts, "TiDB")
  42. }
  43. ctx.Data["DbOptions"] = dbOpts
  44. }
  45. // Install render installation page
  46. func Install(ctx *context.Context) {
  47. form := auth.InstallForm{}
  48. // Database settings
  49. form.DbHost = models.DbCfg.Host
  50. form.DbUser = models.DbCfg.User
  51. form.DbName = models.DbCfg.Name
  52. form.DbPath = models.DbCfg.Path
  53. ctx.Data["CurDbOption"] = "MySQL"
  54. switch models.DbCfg.Type {
  55. case "postgres":
  56. ctx.Data["CurDbOption"] = "PostgreSQL"
  57. case "mssql":
  58. ctx.Data["CurDbOption"] = "MSSQL"
  59. case "sqlite3":
  60. if models.EnableSQLite3 {
  61. ctx.Data["CurDbOption"] = "SQLite3"
  62. }
  63. case "tidb":
  64. if models.EnableTiDB {
  65. ctx.Data["CurDbOption"] = "TiDB"
  66. }
  67. }
  68. // Application general settings
  69. form.AppName = setting.AppName
  70. form.RepoRootPath = setting.RepoRootPath
  71. form.LFSRootPath = setting.LFS.ContentPath
  72. // Note(unknown): it's hard for Windows users change a running user,
  73. // so just use current one if config says default.
  74. if setting.IsWindows && setting.RunUser == "git" {
  75. form.RunUser = user.CurrentUsername()
  76. } else {
  77. form.RunUser = setting.RunUser
  78. }
  79. form.Domain = setting.Domain
  80. form.SSHPort = setting.SSH.Port
  81. form.HTTPPort = setting.HTTPPort
  82. form.AppURL = setting.AppURL
  83. form.LogRootPath = setting.LogRootPath
  84. // E-mail service settings
  85. if setting.MailService != nil {
  86. form.SMTPHost = setting.MailService.Host
  87. form.SMTPFrom = setting.MailService.From
  88. form.SMTPUser = setting.MailService.User
  89. }
  90. form.RegisterConfirm = setting.Service.RegisterEmailConfirm
  91. form.MailNotify = setting.Service.EnableNotifyMail
  92. // Server and other services settings
  93. form.OfflineMode = setting.OfflineMode
  94. form.DisableGravatar = setting.DisableGravatar
  95. form.EnableFederatedAvatar = setting.EnableFederatedAvatar
  96. form.EnableOpenIDSignIn = setting.Service.EnableOpenIDSignIn
  97. form.EnableOpenIDSignUp = setting.Service.EnableOpenIDSignUp
  98. form.DisableRegistration = setting.Service.DisableRegistration
  99. form.EnableCaptcha = setting.Service.EnableCaptcha
  100. form.RequireSignInView = setting.Service.RequireSignInView
  101. form.DefaultKeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  102. form.DefaultAllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization
  103. form.DefaultEnableTimetracking = setting.Service.DefaultEnableTimetracking
  104. form.NoReplyAddress = setting.Service.NoReplyAddress
  105. auth.AssignForm(form, ctx.Data)
  106. ctx.HTML(200, tplInstall)
  107. }
  108. // InstallPost response for submit install items
  109. func InstallPost(ctx *context.Context, form auth.InstallForm) {
  110. var err error
  111. ctx.Data["CurDbOption"] = form.DbType
  112. if ctx.HasError() {
  113. if ctx.HasValue("Err_SMTPUser") {
  114. ctx.Data["Err_SMTP"] = true
  115. }
  116. if ctx.HasValue("Err_AdminName") ||
  117. ctx.HasValue("Err_AdminPasswd") ||
  118. ctx.HasValue("Err_AdminEmail") {
  119. ctx.Data["Err_Admin"] = true
  120. }
  121. ctx.HTML(200, tplInstall)
  122. return
  123. }
  124. if _, err = exec.LookPath("git"); err != nil {
  125. ctx.RenderWithErr(ctx.Tr("install.test_git_failed", err), tplInstall, &form)
  126. return
  127. }
  128. // Pass basic check, now test configuration.
  129. // Test database setting.
  130. dbTypes := map[string]string{"MySQL": "mysql", "PostgreSQL": "postgres", "MSSQL": "mssql", "SQLite3": "sqlite3", "TiDB": "tidb"}
  131. models.DbCfg.Type = dbTypes[form.DbType]
  132. models.DbCfg.Host = form.DbHost
  133. models.DbCfg.User = form.DbUser
  134. models.DbCfg.Passwd = form.DbPasswd
  135. models.DbCfg.Name = form.DbName
  136. models.DbCfg.SSLMode = form.SSLMode
  137. models.DbCfg.Path = form.DbPath
  138. if (models.DbCfg.Type == "sqlite3" || models.DbCfg.Type == "tidb") &&
  139. len(models.DbCfg.Path) == 0 {
  140. ctx.Data["Err_DbPath"] = true
  141. ctx.RenderWithErr(ctx.Tr("install.err_empty_db_path"), tplInstall, &form)
  142. return
  143. } else if models.DbCfg.Type == "tidb" &&
  144. strings.ContainsAny(path.Base(models.DbCfg.Path), ".-") {
  145. ctx.Data["Err_DbPath"] = true
  146. ctx.RenderWithErr(ctx.Tr("install.err_invalid_tidb_name"), tplInstall, &form)
  147. return
  148. }
  149. // Set test engine.
  150. var x *xorm.Engine
  151. if err = models.NewTestEngine(x); err != nil {
  152. if strings.Contains(err.Error(), `Unknown database type: sqlite3`) {
  153. ctx.Data["Err_DbType"] = true
  154. ctx.RenderWithErr(ctx.Tr("install.sqlite3_not_available", "https://docs.gitea.io/installation/install_from_binary.html"), tplInstall, &form)
  155. } else {
  156. ctx.Data["Err_DbSetting"] = true
  157. ctx.RenderWithErr(ctx.Tr("install.invalid_db_setting", err), tplInstall, &form)
  158. }
  159. return
  160. }
  161. // Test repository root path.
  162. form.RepoRootPath = strings.Replace(form.RepoRootPath, "\\", "/", -1)
  163. if err = os.MkdirAll(form.RepoRootPath, os.ModePerm); err != nil {
  164. ctx.Data["Err_RepoRootPath"] = true
  165. ctx.RenderWithErr(ctx.Tr("install.invalid_repo_path", err), tplInstall, &form)
  166. return
  167. }
  168. // Test LFS root path if not empty, empty meaning disable LFS
  169. if form.LFSRootPath != "" {
  170. form.LFSRootPath = strings.Replace(form.LFSRootPath, "\\", "/", -1)
  171. if err := os.MkdirAll(form.LFSRootPath, os.ModePerm); err != nil {
  172. ctx.Data["Err_LFSRootPath"] = true
  173. ctx.RenderWithErr(ctx.Tr("install.invalid_lfs_path", err), tplInstall, &form)
  174. return
  175. }
  176. }
  177. // Test log root path.
  178. form.LogRootPath = strings.Replace(form.LogRootPath, "\\", "/", -1)
  179. if err = os.MkdirAll(form.LogRootPath, os.ModePerm); err != nil {
  180. ctx.Data["Err_LogRootPath"] = true
  181. ctx.RenderWithErr(ctx.Tr("install.invalid_log_root_path", err), tplInstall, &form)
  182. return
  183. }
  184. currentUser, match := setting.IsRunUserMatchCurrentUser(form.RunUser)
  185. if !match {
  186. ctx.Data["Err_RunUser"] = true
  187. ctx.RenderWithErr(ctx.Tr("install.run_user_not_match", form.RunUser, currentUser), tplInstall, &form)
  188. return
  189. }
  190. // Check logic loophole between disable self-registration and no admin account.
  191. if form.DisableRegistration && len(form.AdminName) == 0 {
  192. ctx.Data["Err_Services"] = true
  193. ctx.Data["Err_Admin"] = true
  194. ctx.RenderWithErr(ctx.Tr("install.no_admin_and_disable_registration"), tplInstall, form)
  195. return
  196. }
  197. // Check admin password.
  198. if len(form.AdminName) > 0 && len(form.AdminPasswd) == 0 {
  199. ctx.Data["Err_Admin"] = true
  200. ctx.Data["Err_AdminPasswd"] = true
  201. ctx.RenderWithErr(ctx.Tr("install.err_empty_admin_password"), tplInstall, form)
  202. return
  203. }
  204. if form.AdminPasswd != form.AdminConfirmPasswd {
  205. ctx.Data["Err_Admin"] = true
  206. ctx.Data["Err_AdminPasswd"] = true
  207. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplInstall, form)
  208. return
  209. }
  210. if form.AppURL[len(form.AppURL)-1] != '/' {
  211. form.AppURL += "/"
  212. }
  213. // Save settings.
  214. cfg := ini.Empty()
  215. if com.IsFile(setting.CustomConf) {
  216. // Keeps custom settings if there is already something.
  217. if err = cfg.Append(setting.CustomConf); err != nil {
  218. log.Error(4, "Failed to load custom conf '%s': %v", setting.CustomConf, err)
  219. }
  220. }
  221. cfg.Section("database").Key("DB_TYPE").SetValue(models.DbCfg.Type)
  222. cfg.Section("database").Key("HOST").SetValue(models.DbCfg.Host)
  223. cfg.Section("database").Key("NAME").SetValue(models.DbCfg.Name)
  224. cfg.Section("database").Key("USER").SetValue(models.DbCfg.User)
  225. cfg.Section("database").Key("PASSWD").SetValue(models.DbCfg.Passwd)
  226. cfg.Section("database").Key("SSL_MODE").SetValue(models.DbCfg.SSLMode)
  227. cfg.Section("database").Key("PATH").SetValue(models.DbCfg.Path)
  228. cfg.Section("").Key("APP_NAME").SetValue(form.AppName)
  229. cfg.Section("repository").Key("ROOT").SetValue(form.RepoRootPath)
  230. cfg.Section("").Key("RUN_USER").SetValue(form.RunUser)
  231. cfg.Section("server").Key("SSH_DOMAIN").SetValue(form.Domain)
  232. cfg.Section("server").Key("DOMAIN").SetValue(form.Domain)
  233. cfg.Section("server").Key("HTTP_PORT").SetValue(form.HTTPPort)
  234. cfg.Section("server").Key("ROOT_URL").SetValue(form.AppURL)
  235. if form.SSHPort == 0 {
  236. cfg.Section("server").Key("DISABLE_SSH").SetValue("true")
  237. } else {
  238. cfg.Section("server").Key("DISABLE_SSH").SetValue("false")
  239. cfg.Section("server").Key("SSH_PORT").SetValue(com.ToStr(form.SSHPort))
  240. }
  241. if form.LFSRootPath != "" {
  242. cfg.Section("server").Key("LFS_START_SERVER").SetValue("true")
  243. cfg.Section("server").Key("LFS_CONTENT_PATH").SetValue(form.LFSRootPath)
  244. var secretKey string
  245. if secretKey, err = generate.NewLfsJwtSecret(); err != nil {
  246. ctx.RenderWithErr(ctx.Tr("install.lfs_jwt_secret_failed", err), tplInstall, &form)
  247. return
  248. }
  249. cfg.Section("server").Key("LFS_JWT_SECRET").SetValue(secretKey)
  250. } else {
  251. cfg.Section("server").Key("LFS_START_SERVER").SetValue("false")
  252. }
  253. if len(strings.TrimSpace(form.SMTPHost)) > 0 {
  254. cfg.Section("mailer").Key("ENABLED").SetValue("true")
  255. cfg.Section("mailer").Key("HOST").SetValue(form.SMTPHost)
  256. cfg.Section("mailer").Key("FROM").SetValue(form.SMTPFrom)
  257. cfg.Section("mailer").Key("USER").SetValue(form.SMTPUser)
  258. cfg.Section("mailer").Key("PASSWD").SetValue(form.SMTPPasswd)
  259. } else {
  260. cfg.Section("mailer").Key("ENABLED").SetValue("false")
  261. }
  262. cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").SetValue(com.ToStr(form.RegisterConfirm))
  263. cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").SetValue(com.ToStr(form.MailNotify))
  264. cfg.Section("server").Key("OFFLINE_MODE").SetValue(com.ToStr(form.OfflineMode))
  265. cfg.Section("picture").Key("DISABLE_GRAVATAR").SetValue(com.ToStr(form.DisableGravatar))
  266. cfg.Section("picture").Key("ENABLE_FEDERATED_AVATAR").SetValue(com.ToStr(form.EnableFederatedAvatar))
  267. cfg.Section("openid").Key("ENABLE_OPENID_SIGNIN").SetValue(com.ToStr(form.EnableOpenIDSignIn))
  268. cfg.Section("openid").Key("ENABLE_OPENID_SIGNUP").SetValue(com.ToStr(form.EnableOpenIDSignUp))
  269. cfg.Section("service").Key("DISABLE_REGISTRATION").SetValue(com.ToStr(form.DisableRegistration))
  270. cfg.Section("service").Key("ENABLE_CAPTCHA").SetValue(com.ToStr(form.EnableCaptcha))
  271. cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").SetValue(com.ToStr(form.RequireSignInView))
  272. cfg.Section("service").Key("DEFAULT_KEEP_EMAIL_PRIVATE").SetValue(com.ToStr(form.DefaultKeepEmailPrivate))
  273. cfg.Section("service").Key("DEFAULT_ALLOW_CREATE_ORGANIZATION").SetValue(com.ToStr(form.DefaultAllowCreateOrganization))
  274. cfg.Section("service").Key("DEFAULT_ENABLE_TIMETRACKING").SetValue(com.ToStr(form.DefaultEnableTimetracking))
  275. cfg.Section("service").Key("NO_REPLY_ADDRESS").SetValue(com.ToStr(form.NoReplyAddress))
  276. cfg.Section("").Key("RUN_MODE").SetValue("prod")
  277. cfg.Section("session").Key("PROVIDER").SetValue("file")
  278. cfg.Section("log").Key("MODE").SetValue("file")
  279. cfg.Section("log").Key("LEVEL").SetValue(setting.LogLevel)
  280. cfg.Section("log").Key("ROOT_PATH").SetValue(form.LogRootPath)
  281. cfg.Section("security").Key("INSTALL_LOCK").SetValue("true")
  282. var secretKey string
  283. if secretKey, err = generate.NewSecretKey(); err != nil {
  284. ctx.RenderWithErr(ctx.Tr("install.secret_key_failed", err), tplInstall, &form)
  285. return
  286. }
  287. cfg.Section("security").Key("SECRET_KEY").SetValue(secretKey)
  288. err = os.MkdirAll(filepath.Dir(setting.CustomConf), os.ModePerm)
  289. if err != nil {
  290. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  291. return
  292. }
  293. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  294. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  295. return
  296. }
  297. GlobalInit()
  298. // Create admin account
  299. if len(form.AdminName) > 0 {
  300. u := &models.User{
  301. Name: form.AdminName,
  302. Email: form.AdminEmail,
  303. Passwd: form.AdminPasswd,
  304. IsAdmin: true,
  305. IsActive: true,
  306. }
  307. if err = models.CreateUser(u); err != nil {
  308. if !models.IsErrUserAlreadyExist(err) {
  309. setting.InstallLock = false
  310. ctx.Data["Err_AdminName"] = true
  311. ctx.Data["Err_AdminEmail"] = true
  312. ctx.RenderWithErr(ctx.Tr("install.invalid_admin_setting", err), tplInstall, &form)
  313. return
  314. }
  315. log.Info("Admin account already exist")
  316. u, _ = models.GetUserByName(u.Name)
  317. }
  318. // Auto-login for admin
  319. if err = ctx.Session.Set("uid", u.ID); err != nil {
  320. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  321. return
  322. }
  323. if err = ctx.Session.Set("uname", u.Name); err != nil {
  324. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  325. return
  326. }
  327. }
  328. log.Info("First-time run install finished!")
  329. ctx.Flash.Success(ctx.Tr("install.install_success"))
  330. ctx.Redirect(form.AppURL + "user/login")
  331. }