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.

397 lines
14 KiB

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
8 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
8 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>
7 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
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
8 years ago
10 years ago
10 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 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
8 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
8 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
8 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>
7 years ago
10 years ago
10 years ago
10 years ago
  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/filepath"
  10. "strings"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/auth"
  13. "code.gitea.io/gitea/modules/base"
  14. "code.gitea.io/gitea/modules/context"
  15. "code.gitea.io/gitea/modules/generate"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/setting"
  18. "code.gitea.io/gitea/modules/user"
  19. "github.com/unknwon/com"
  20. "gopkg.in/ini.v1"
  21. "xorm.io/xorm"
  22. )
  23. const (
  24. // tplInstall template for installation page
  25. tplInstall base.TplName = "install"
  26. )
  27. // InstallInit prepare for rendering installation page
  28. func InstallInit(ctx *context.Context) {
  29. if setting.InstallLock {
  30. ctx.NotFound("Install", errors.New("Installation is prohibited"))
  31. return
  32. }
  33. ctx.Data["Title"] = ctx.Tr("install.install")
  34. ctx.Data["PageIsInstall"] = true
  35. ctx.Data["DbOptions"] = setting.SupportedDatabases
  36. }
  37. // Install render installation page
  38. func Install(ctx *context.Context) {
  39. form := auth.InstallForm{}
  40. // Database settings
  41. form.DbHost = setting.Database.Host
  42. form.DbUser = setting.Database.User
  43. form.DbPasswd = setting.Database.Passwd
  44. form.DbName = setting.Database.Name
  45. form.DbPath = setting.Database.Path
  46. form.Charset = setting.Database.Charset
  47. ctx.Data["CurDbOption"] = "MySQL"
  48. switch setting.Database.Type {
  49. case "postgres":
  50. ctx.Data["CurDbOption"] = "PostgreSQL"
  51. case "mssql":
  52. ctx.Data["CurDbOption"] = "MSSQL"
  53. case "sqlite3":
  54. if setting.EnableSQLite3 {
  55. ctx.Data["CurDbOption"] = "SQLite3"
  56. }
  57. }
  58. // Application general settings
  59. form.AppName = setting.AppName
  60. form.RepoRootPath = setting.RepoRootPath
  61. form.LFSRootPath = setting.LFS.ContentPath
  62. // Note(unknown): it's hard for Windows users change a running user,
  63. // so just use current one if config says default.
  64. if setting.IsWindows && setting.RunUser == "git" {
  65. form.RunUser = user.CurrentUsername()
  66. } else {
  67. form.RunUser = setting.RunUser
  68. }
  69. form.Domain = setting.Domain
  70. form.SSHPort = setting.SSH.Port
  71. form.HTTPPort = setting.HTTPPort
  72. form.AppURL = setting.AppURL
  73. form.LogRootPath = setting.LogRootPath
  74. // E-mail service settings
  75. if setting.MailService != nil {
  76. form.SMTPHost = setting.MailService.Host
  77. form.SMTPFrom = setting.MailService.From
  78. form.SMTPUser = setting.MailService.User
  79. }
  80. form.RegisterConfirm = setting.Service.RegisterEmailConfirm
  81. form.MailNotify = setting.Service.EnableNotifyMail
  82. // Server and other services settings
  83. form.OfflineMode = setting.OfflineMode
  84. form.DisableGravatar = setting.DisableGravatar
  85. form.EnableFederatedAvatar = setting.EnableFederatedAvatar
  86. form.EnableOpenIDSignIn = setting.Service.EnableOpenIDSignIn
  87. form.EnableOpenIDSignUp = setting.Service.EnableOpenIDSignUp
  88. form.DisableRegistration = setting.Service.DisableRegistration
  89. form.AllowOnlyExternalRegistration = setting.Service.AllowOnlyExternalRegistration
  90. form.EnableCaptcha = setting.Service.EnableCaptcha
  91. form.RequireSignInView = setting.Service.RequireSignInView
  92. form.DefaultKeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  93. form.DefaultAllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization
  94. form.DefaultEnableTimetracking = setting.Service.DefaultEnableTimetracking
  95. form.NoReplyAddress = setting.Service.NoReplyAddress
  96. auth.AssignForm(form, ctx.Data)
  97. ctx.HTML(200, tplInstall)
  98. }
  99. // InstallPost response for submit install items
  100. func InstallPost(ctx *context.Context, form auth.InstallForm) {
  101. var err error
  102. ctx.Data["CurDbOption"] = form.DbType
  103. if ctx.HasError() {
  104. if ctx.HasValue("Err_SMTPUser") {
  105. ctx.Data["Err_SMTP"] = true
  106. }
  107. if ctx.HasValue("Err_AdminName") ||
  108. ctx.HasValue("Err_AdminPasswd") ||
  109. ctx.HasValue("Err_AdminEmail") {
  110. ctx.Data["Err_Admin"] = true
  111. }
  112. ctx.HTML(200, tplInstall)
  113. return
  114. }
  115. if _, err = exec.LookPath("git"); err != nil {
  116. ctx.RenderWithErr(ctx.Tr("install.test_git_failed", err), tplInstall, &form)
  117. return
  118. }
  119. // Pass basic check, now test configuration.
  120. // Test database setting.
  121. setting.Database.Type = setting.GetDBTypeByName(form.DbType)
  122. setting.Database.Host = form.DbHost
  123. setting.Database.User = form.DbUser
  124. setting.Database.Passwd = form.DbPasswd
  125. setting.Database.Name = form.DbName
  126. setting.Database.SSLMode = form.SSLMode
  127. setting.Database.Charset = form.Charset
  128. setting.Database.Path = form.DbPath
  129. if (setting.Database.Type == "sqlite3") &&
  130. len(setting.Database.Path) == 0 {
  131. ctx.Data["Err_DbPath"] = true
  132. ctx.RenderWithErr(ctx.Tr("install.err_empty_db_path"), tplInstall, &form)
  133. return
  134. }
  135. // Set test engine.
  136. var x *xorm.Engine
  137. if err = models.NewTestEngine(x); err != nil {
  138. if strings.Contains(err.Error(), `Unknown database type: sqlite3`) {
  139. ctx.Data["Err_DbType"] = true
  140. ctx.RenderWithErr(ctx.Tr("install.sqlite3_not_available", "https://docs.gitea.io/en-us/install-from-binary/"), tplInstall, &form)
  141. } else {
  142. ctx.Data["Err_DbSetting"] = true
  143. ctx.RenderWithErr(ctx.Tr("install.invalid_db_setting", err), tplInstall, &form)
  144. }
  145. return
  146. }
  147. // Test repository root path.
  148. form.RepoRootPath = strings.Replace(form.RepoRootPath, "\\", "/", -1)
  149. if err = os.MkdirAll(form.RepoRootPath, os.ModePerm); err != nil {
  150. ctx.Data["Err_RepoRootPath"] = true
  151. ctx.RenderWithErr(ctx.Tr("install.invalid_repo_path", err), tplInstall, &form)
  152. return
  153. }
  154. // Test LFS root path if not empty, empty meaning disable LFS
  155. if form.LFSRootPath != "" {
  156. form.LFSRootPath = strings.Replace(form.LFSRootPath, "\\", "/", -1)
  157. if err := os.MkdirAll(form.LFSRootPath, os.ModePerm); err != nil {
  158. ctx.Data["Err_LFSRootPath"] = true
  159. ctx.RenderWithErr(ctx.Tr("install.invalid_lfs_path", err), tplInstall, &form)
  160. return
  161. }
  162. }
  163. // Test log root path.
  164. form.LogRootPath = strings.Replace(form.LogRootPath, "\\", "/", -1)
  165. if err = os.MkdirAll(form.LogRootPath, os.ModePerm); err != nil {
  166. ctx.Data["Err_LogRootPath"] = true
  167. ctx.RenderWithErr(ctx.Tr("install.invalid_log_root_path", err), tplInstall, &form)
  168. return
  169. }
  170. currentUser, match := setting.IsRunUserMatchCurrentUser(form.RunUser)
  171. if !match {
  172. ctx.Data["Err_RunUser"] = true
  173. ctx.RenderWithErr(ctx.Tr("install.run_user_not_match", form.RunUser, currentUser), tplInstall, &form)
  174. return
  175. }
  176. // Check logic loophole between disable self-registration and no admin account.
  177. if form.DisableRegistration && len(form.AdminName) == 0 {
  178. ctx.Data["Err_Services"] = true
  179. ctx.Data["Err_Admin"] = true
  180. ctx.RenderWithErr(ctx.Tr("install.no_admin_and_disable_registration"), tplInstall, form)
  181. return
  182. }
  183. // Check admin user creation
  184. if len(form.AdminName) > 0 {
  185. // Ensure AdminName is valid
  186. if err := models.IsUsableUsername(form.AdminName); err != nil {
  187. ctx.Data["Err_Admin"] = true
  188. ctx.Data["Err_AdminName"] = true
  189. if models.IsErrNameReserved(err) {
  190. ctx.RenderWithErr(ctx.Tr("install.err_admin_name_is_reserved"), tplInstall, form)
  191. return
  192. } else if models.IsErrNamePatternNotAllowed(err) {
  193. ctx.RenderWithErr(ctx.Tr("install.err_admin_name_pattern_not_allowed"), tplInstall, form)
  194. return
  195. }
  196. ctx.RenderWithErr(ctx.Tr("install.err_admin_name_is_invalid"), tplInstall, form)
  197. return
  198. }
  199. // Check Admin email
  200. if len(form.AdminEmail) == 0 {
  201. ctx.Data["Err_Admin"] = true
  202. ctx.Data["Err_AdminEmail"] = true
  203. ctx.RenderWithErr(ctx.Tr("install.err_empty_admin_email"), tplInstall, form)
  204. return
  205. }
  206. // Check admin password.
  207. if len(form.AdminPasswd) == 0 {
  208. ctx.Data["Err_Admin"] = true
  209. ctx.Data["Err_AdminPasswd"] = true
  210. ctx.RenderWithErr(ctx.Tr("install.err_empty_admin_password"), tplInstall, form)
  211. return
  212. }
  213. if form.AdminPasswd != form.AdminConfirmPasswd {
  214. ctx.Data["Err_Admin"] = true
  215. ctx.Data["Err_AdminPasswd"] = true
  216. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplInstall, form)
  217. return
  218. }
  219. }
  220. if form.AppURL[len(form.AppURL)-1] != '/' {
  221. form.AppURL += "/"
  222. }
  223. // Save settings.
  224. cfg := ini.Empty()
  225. if com.IsFile(setting.CustomConf) {
  226. // Keeps custom settings if there is already something.
  227. if err = cfg.Append(setting.CustomConf); err != nil {
  228. log.Error("Failed to load custom conf '%s': %v", setting.CustomConf, err)
  229. }
  230. }
  231. cfg.Section("database").Key("DB_TYPE").SetValue(setting.Database.Type)
  232. cfg.Section("database").Key("HOST").SetValue(setting.Database.Host)
  233. cfg.Section("database").Key("NAME").SetValue(setting.Database.Name)
  234. cfg.Section("database").Key("USER").SetValue(setting.Database.User)
  235. cfg.Section("database").Key("PASSWD").SetValue(setting.Database.Passwd)
  236. cfg.Section("database").Key("SSL_MODE").SetValue(setting.Database.SSLMode)
  237. cfg.Section("database").Key("CHARSET").SetValue(setting.Database.Charset)
  238. cfg.Section("database").Key("PATH").SetValue(setting.Database.Path)
  239. cfg.Section("").Key("APP_NAME").SetValue(form.AppName)
  240. cfg.Section("repository").Key("ROOT").SetValue(form.RepoRootPath)
  241. cfg.Section("").Key("RUN_USER").SetValue(form.RunUser)
  242. cfg.Section("server").Key("SSH_DOMAIN").SetValue(form.Domain)
  243. cfg.Section("server").Key("DOMAIN").SetValue(form.Domain)
  244. cfg.Section("server").Key("HTTP_PORT").SetValue(form.HTTPPort)
  245. cfg.Section("server").Key("ROOT_URL").SetValue(form.AppURL)
  246. if form.SSHPort == 0 {
  247. cfg.Section("server").Key("DISABLE_SSH").SetValue("true")
  248. } else {
  249. cfg.Section("server").Key("DISABLE_SSH").SetValue("false")
  250. cfg.Section("server").Key("SSH_PORT").SetValue(com.ToStr(form.SSHPort))
  251. }
  252. if form.LFSRootPath != "" {
  253. cfg.Section("server").Key("LFS_START_SERVER").SetValue("true")
  254. cfg.Section("server").Key("LFS_CONTENT_PATH").SetValue(form.LFSRootPath)
  255. var secretKey string
  256. if secretKey, err = generate.NewJwtSecret(); err != nil {
  257. ctx.RenderWithErr(ctx.Tr("install.lfs_jwt_secret_failed", err), tplInstall, &form)
  258. return
  259. }
  260. cfg.Section("server").Key("LFS_JWT_SECRET").SetValue(secretKey)
  261. } else {
  262. cfg.Section("server").Key("LFS_START_SERVER").SetValue("false")
  263. }
  264. if len(strings.TrimSpace(form.SMTPHost)) > 0 {
  265. cfg.Section("mailer").Key("ENABLED").SetValue("true")
  266. cfg.Section("mailer").Key("HOST").SetValue(form.SMTPHost)
  267. cfg.Section("mailer").Key("FROM").SetValue(form.SMTPFrom)
  268. cfg.Section("mailer").Key("USER").SetValue(form.SMTPUser)
  269. cfg.Section("mailer").Key("PASSWD").SetValue(form.SMTPPasswd)
  270. } else {
  271. cfg.Section("mailer").Key("ENABLED").SetValue("false")
  272. }
  273. cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").SetValue(com.ToStr(form.RegisterConfirm))
  274. cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").SetValue(com.ToStr(form.MailNotify))
  275. cfg.Section("server").Key("OFFLINE_MODE").SetValue(com.ToStr(form.OfflineMode))
  276. cfg.Section("picture").Key("DISABLE_GRAVATAR").SetValue(com.ToStr(form.DisableGravatar))
  277. cfg.Section("picture").Key("ENABLE_FEDERATED_AVATAR").SetValue(com.ToStr(form.EnableFederatedAvatar))
  278. cfg.Section("openid").Key("ENABLE_OPENID_SIGNIN").SetValue(com.ToStr(form.EnableOpenIDSignIn))
  279. cfg.Section("openid").Key("ENABLE_OPENID_SIGNUP").SetValue(com.ToStr(form.EnableOpenIDSignUp))
  280. cfg.Section("service").Key("DISABLE_REGISTRATION").SetValue(com.ToStr(form.DisableRegistration))
  281. cfg.Section("service").Key("ALLOW_ONLY_EXTERNAL_REGISTRATION").SetValue(com.ToStr(form.AllowOnlyExternalRegistration))
  282. cfg.Section("service").Key("ENABLE_CAPTCHA").SetValue(com.ToStr(form.EnableCaptcha))
  283. cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").SetValue(com.ToStr(form.RequireSignInView))
  284. cfg.Section("service").Key("DEFAULT_KEEP_EMAIL_PRIVATE").SetValue(com.ToStr(form.DefaultKeepEmailPrivate))
  285. cfg.Section("service").Key("DEFAULT_ALLOW_CREATE_ORGANIZATION").SetValue(com.ToStr(form.DefaultAllowCreateOrganization))
  286. cfg.Section("service").Key("DEFAULT_ENABLE_TIMETRACKING").SetValue(com.ToStr(form.DefaultEnableTimetracking))
  287. cfg.Section("service").Key("NO_REPLY_ADDRESS").SetValue(com.ToStr(form.NoReplyAddress))
  288. cfg.Section("").Key("RUN_MODE").SetValue("prod")
  289. cfg.Section("session").Key("PROVIDER").SetValue("file")
  290. cfg.Section("log").Key("MODE").SetValue("file")
  291. cfg.Section("log").Key("LEVEL").SetValue(setting.LogLevel)
  292. cfg.Section("log").Key("ROOT_PATH").SetValue(form.LogRootPath)
  293. cfg.Section("security").Key("INSTALL_LOCK").SetValue("true")
  294. var secretKey string
  295. if secretKey, err = generate.NewSecretKey(); err != nil {
  296. ctx.RenderWithErr(ctx.Tr("install.secret_key_failed", err), tplInstall, &form)
  297. return
  298. }
  299. cfg.Section("security").Key("SECRET_KEY").SetValue(secretKey)
  300. err = os.MkdirAll(filepath.Dir(setting.CustomConf), os.ModePerm)
  301. if err != nil {
  302. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  303. return
  304. }
  305. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  306. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  307. return
  308. }
  309. GlobalInit()
  310. // Create admin account
  311. if len(form.AdminName) > 0 {
  312. u := &models.User{
  313. Name: form.AdminName,
  314. Email: form.AdminEmail,
  315. Passwd: form.AdminPasswd,
  316. IsAdmin: true,
  317. IsActive: true,
  318. }
  319. if err = models.CreateUser(u); err != nil {
  320. if !models.IsErrUserAlreadyExist(err) {
  321. setting.InstallLock = false
  322. ctx.Data["Err_AdminName"] = true
  323. ctx.Data["Err_AdminEmail"] = true
  324. ctx.RenderWithErr(ctx.Tr("install.invalid_admin_setting", err), tplInstall, &form)
  325. return
  326. }
  327. log.Info("Admin account already exist")
  328. u, _ = models.GetUserByName(u.Name)
  329. }
  330. // Auto-login for admin
  331. if err = ctx.Session.Set("uid", u.ID); err != nil {
  332. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  333. return
  334. }
  335. if err = ctx.Session.Set("uname", u.Name); err != nil {
  336. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  337. return
  338. }
  339. }
  340. log.Info("First-time run install finished!")
  341. // FIXME: This isn't really enough to completely take account of new configuration
  342. // We should really be restarting:
  343. // - On windows this is probably just a simple restart
  344. // - On linux we can't just use graceful.RestartProcess() everything that was passed in on LISTEN_FDS
  345. // (active or not) needs to be passed out and everything new passed out too.
  346. // This means we need to prevent the cleanup goroutine from running prior to the second GlobalInit
  347. ctx.Flash.Success(ctx.Tr("install.install_success"))
  348. ctx.Redirect(form.AppURL + "user/login")
  349. }