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.

398 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/graceful"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/setting"
  19. "code.gitea.io/gitea/modules/user"
  20. "github.com/unknwon/com"
  21. "gopkg.in/ini.v1"
  22. "xorm.io/xorm"
  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. ctx.Data["DbOptions"] = setting.SupportedDatabases
  37. }
  38. // Install render installation page
  39. func Install(ctx *context.Context) {
  40. form := auth.InstallForm{}
  41. // Database settings
  42. form.DbHost = setting.Database.Host
  43. form.DbUser = setting.Database.User
  44. form.DbPasswd = setting.Database.Passwd
  45. form.DbName = setting.Database.Name
  46. form.DbPath = setting.Database.Path
  47. form.Charset = setting.Database.Charset
  48. ctx.Data["CurDbOption"] = "MySQL"
  49. switch setting.Database.Type {
  50. case "postgres":
  51. ctx.Data["CurDbOption"] = "PostgreSQL"
  52. case "mssql":
  53. ctx.Data["CurDbOption"] = "MSSQL"
  54. case "sqlite3":
  55. if setting.EnableSQLite3 {
  56. ctx.Data["CurDbOption"] = "SQLite3"
  57. }
  58. }
  59. // Application general settings
  60. form.AppName = setting.AppName
  61. form.RepoRootPath = setting.RepoRootPath
  62. form.LFSRootPath = setting.LFS.ContentPath
  63. // Note(unknown): it's hard for Windows users change a running user,
  64. // so just use current one if config says default.
  65. if setting.IsWindows && setting.RunUser == "git" {
  66. form.RunUser = user.CurrentUsername()
  67. } else {
  68. form.RunUser = setting.RunUser
  69. }
  70. form.Domain = setting.Domain
  71. form.SSHPort = setting.SSH.Port
  72. form.HTTPPort = setting.HTTPPort
  73. form.AppURL = setting.AppURL
  74. form.LogRootPath = setting.LogRootPath
  75. // E-mail service settings
  76. if setting.MailService != nil {
  77. form.SMTPHost = setting.MailService.Host
  78. form.SMTPFrom = setting.MailService.From
  79. form.SMTPUser = setting.MailService.User
  80. }
  81. form.RegisterConfirm = setting.Service.RegisterEmailConfirm
  82. form.MailNotify = setting.Service.EnableNotifyMail
  83. // Server and other services settings
  84. form.OfflineMode = setting.OfflineMode
  85. form.DisableGravatar = setting.DisableGravatar
  86. form.EnableFederatedAvatar = setting.EnableFederatedAvatar
  87. form.EnableOpenIDSignIn = setting.Service.EnableOpenIDSignIn
  88. form.EnableOpenIDSignUp = setting.Service.EnableOpenIDSignUp
  89. form.DisableRegistration = setting.Service.DisableRegistration
  90. form.AllowOnlyExternalRegistration = setting.Service.AllowOnlyExternalRegistration
  91. form.EnableCaptcha = setting.Service.EnableCaptcha
  92. form.RequireSignInView = setting.Service.RequireSignInView
  93. form.DefaultKeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  94. form.DefaultAllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization
  95. form.DefaultEnableTimetracking = setting.Service.DefaultEnableTimetracking
  96. form.NoReplyAddress = setting.Service.NoReplyAddress
  97. auth.AssignForm(form, ctx.Data)
  98. ctx.HTML(200, tplInstall)
  99. }
  100. // InstallPost response for submit install items
  101. func InstallPost(ctx *context.Context, form auth.InstallForm) {
  102. var err error
  103. ctx.Data["CurDbOption"] = form.DbType
  104. if ctx.HasError() {
  105. if ctx.HasValue("Err_SMTPUser") {
  106. ctx.Data["Err_SMTP"] = true
  107. }
  108. if ctx.HasValue("Err_AdminName") ||
  109. ctx.HasValue("Err_AdminPasswd") ||
  110. ctx.HasValue("Err_AdminEmail") {
  111. ctx.Data["Err_Admin"] = true
  112. }
  113. ctx.HTML(200, tplInstall)
  114. return
  115. }
  116. if _, err = exec.LookPath("git"); err != nil {
  117. ctx.RenderWithErr(ctx.Tr("install.test_git_failed", err), tplInstall, &form)
  118. return
  119. }
  120. // Pass basic check, now test configuration.
  121. // Test database setting.
  122. setting.Database.Type = setting.GetDBTypeByName(form.DbType)
  123. setting.Database.Host = form.DbHost
  124. setting.Database.User = form.DbUser
  125. setting.Database.Passwd = form.DbPasswd
  126. setting.Database.Name = form.DbName
  127. setting.Database.SSLMode = form.SSLMode
  128. setting.Database.Charset = form.Charset
  129. setting.Database.Path = form.DbPath
  130. if (setting.Database.Type == "sqlite3") &&
  131. len(setting.Database.Path) == 0 {
  132. ctx.Data["Err_DbPath"] = true
  133. ctx.RenderWithErr(ctx.Tr("install.err_empty_db_path"), tplInstall, &form)
  134. return
  135. }
  136. // Set test engine.
  137. var x *xorm.Engine
  138. if err = models.NewTestEngine(x); err != nil {
  139. if strings.Contains(err.Error(), `Unknown database type: sqlite3`) {
  140. ctx.Data["Err_DbType"] = true
  141. ctx.RenderWithErr(ctx.Tr("install.sqlite3_not_available", "https://docs.gitea.io/en-us/install-from-binary/"), tplInstall, &form)
  142. } else {
  143. ctx.Data["Err_DbSetting"] = true
  144. ctx.RenderWithErr(ctx.Tr("install.invalid_db_setting", err), tplInstall, &form)
  145. }
  146. return
  147. }
  148. // Test repository root path.
  149. form.RepoRootPath = strings.Replace(form.RepoRootPath, "\\", "/", -1)
  150. if err = os.MkdirAll(form.RepoRootPath, os.ModePerm); err != nil {
  151. ctx.Data["Err_RepoRootPath"] = true
  152. ctx.RenderWithErr(ctx.Tr("install.invalid_repo_path", err), tplInstall, &form)
  153. return
  154. }
  155. // Test LFS root path if not empty, empty meaning disable LFS
  156. if form.LFSRootPath != "" {
  157. form.LFSRootPath = strings.Replace(form.LFSRootPath, "\\", "/", -1)
  158. if err := os.MkdirAll(form.LFSRootPath, os.ModePerm); err != nil {
  159. ctx.Data["Err_LFSRootPath"] = true
  160. ctx.RenderWithErr(ctx.Tr("install.invalid_lfs_path", err), tplInstall, &form)
  161. return
  162. }
  163. }
  164. // Test log root path.
  165. form.LogRootPath = strings.Replace(form.LogRootPath, "\\", "/", -1)
  166. if err = os.MkdirAll(form.LogRootPath, os.ModePerm); err != nil {
  167. ctx.Data["Err_LogRootPath"] = true
  168. ctx.RenderWithErr(ctx.Tr("install.invalid_log_root_path", err), tplInstall, &form)
  169. return
  170. }
  171. currentUser, match := setting.IsRunUserMatchCurrentUser(form.RunUser)
  172. if !match {
  173. ctx.Data["Err_RunUser"] = true
  174. ctx.RenderWithErr(ctx.Tr("install.run_user_not_match", form.RunUser, currentUser), tplInstall, &form)
  175. return
  176. }
  177. // Check logic loophole between disable self-registration and no admin account.
  178. if form.DisableRegistration && len(form.AdminName) == 0 {
  179. ctx.Data["Err_Services"] = true
  180. ctx.Data["Err_Admin"] = true
  181. ctx.RenderWithErr(ctx.Tr("install.no_admin_and_disable_registration"), tplInstall, form)
  182. return
  183. }
  184. // Check admin user creation
  185. if len(form.AdminName) > 0 {
  186. // Ensure AdminName is valid
  187. if err := models.IsUsableUsername(form.AdminName); err != nil {
  188. ctx.Data["Err_Admin"] = true
  189. ctx.Data["Err_AdminName"] = true
  190. if models.IsErrNameReserved(err) {
  191. ctx.RenderWithErr(ctx.Tr("install.err_admin_name_is_reserved"), tplInstall, form)
  192. return
  193. } else if models.IsErrNamePatternNotAllowed(err) {
  194. ctx.RenderWithErr(ctx.Tr("install.err_admin_name_pattern_not_allowed"), tplInstall, form)
  195. return
  196. }
  197. ctx.RenderWithErr(ctx.Tr("install.err_admin_name_is_invalid"), tplInstall, form)
  198. return
  199. }
  200. // Check Admin email
  201. if len(form.AdminEmail) == 0 {
  202. ctx.Data["Err_Admin"] = true
  203. ctx.Data["Err_AdminEmail"] = true
  204. ctx.RenderWithErr(ctx.Tr("install.err_empty_admin_email"), tplInstall, form)
  205. return
  206. }
  207. // Check admin password.
  208. if len(form.AdminPasswd) == 0 {
  209. ctx.Data["Err_Admin"] = true
  210. ctx.Data["Err_AdminPasswd"] = true
  211. ctx.RenderWithErr(ctx.Tr("install.err_empty_admin_password"), tplInstall, form)
  212. return
  213. }
  214. if form.AdminPasswd != form.AdminConfirmPasswd {
  215. ctx.Data["Err_Admin"] = true
  216. ctx.Data["Err_AdminPasswd"] = true
  217. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplInstall, form)
  218. return
  219. }
  220. }
  221. if form.AppURL[len(form.AppURL)-1] != '/' {
  222. form.AppURL += "/"
  223. }
  224. // Save settings.
  225. cfg := ini.Empty()
  226. if com.IsFile(setting.CustomConf) {
  227. // Keeps custom settings if there is already something.
  228. if err = cfg.Append(setting.CustomConf); err != nil {
  229. log.Error("Failed to load custom conf '%s': %v", setting.CustomConf, err)
  230. }
  231. }
  232. cfg.Section("database").Key("DB_TYPE").SetValue(setting.Database.Type)
  233. cfg.Section("database").Key("HOST").SetValue(setting.Database.Host)
  234. cfg.Section("database").Key("NAME").SetValue(setting.Database.Name)
  235. cfg.Section("database").Key("USER").SetValue(setting.Database.User)
  236. cfg.Section("database").Key("PASSWD").SetValue(setting.Database.Passwd)
  237. cfg.Section("database").Key("SSL_MODE").SetValue(setting.Database.SSLMode)
  238. cfg.Section("database").Key("CHARSET").SetValue(setting.Database.Charset)
  239. cfg.Section("database").Key("PATH").SetValue(setting.Database.Path)
  240. cfg.Section("").Key("APP_NAME").SetValue(form.AppName)
  241. cfg.Section("repository").Key("ROOT").SetValue(form.RepoRootPath)
  242. cfg.Section("").Key("RUN_USER").SetValue(form.RunUser)
  243. cfg.Section("server").Key("SSH_DOMAIN").SetValue(form.Domain)
  244. cfg.Section("server").Key("DOMAIN").SetValue(form.Domain)
  245. cfg.Section("server").Key("HTTP_PORT").SetValue(form.HTTPPort)
  246. cfg.Section("server").Key("ROOT_URL").SetValue(form.AppURL)
  247. if form.SSHPort == 0 {
  248. cfg.Section("server").Key("DISABLE_SSH").SetValue("true")
  249. } else {
  250. cfg.Section("server").Key("DISABLE_SSH").SetValue("false")
  251. cfg.Section("server").Key("SSH_PORT").SetValue(com.ToStr(form.SSHPort))
  252. }
  253. if form.LFSRootPath != "" {
  254. cfg.Section("server").Key("LFS_START_SERVER").SetValue("true")
  255. cfg.Section("server").Key("LFS_CONTENT_PATH").SetValue(form.LFSRootPath)
  256. var secretKey string
  257. if secretKey, err = generate.NewJwtSecret(); err != nil {
  258. ctx.RenderWithErr(ctx.Tr("install.lfs_jwt_secret_failed", err), tplInstall, &form)
  259. return
  260. }
  261. cfg.Section("server").Key("LFS_JWT_SECRET").SetValue(secretKey)
  262. } else {
  263. cfg.Section("server").Key("LFS_START_SERVER").SetValue("false")
  264. }
  265. if len(strings.TrimSpace(form.SMTPHost)) > 0 {
  266. cfg.Section("mailer").Key("ENABLED").SetValue("true")
  267. cfg.Section("mailer").Key("HOST").SetValue(form.SMTPHost)
  268. cfg.Section("mailer").Key("FROM").SetValue(form.SMTPFrom)
  269. cfg.Section("mailer").Key("USER").SetValue(form.SMTPUser)
  270. cfg.Section("mailer").Key("PASSWD").SetValue(form.SMTPPasswd)
  271. } else {
  272. cfg.Section("mailer").Key("ENABLED").SetValue("false")
  273. }
  274. cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").SetValue(com.ToStr(form.RegisterConfirm))
  275. cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").SetValue(com.ToStr(form.MailNotify))
  276. cfg.Section("server").Key("OFFLINE_MODE").SetValue(com.ToStr(form.OfflineMode))
  277. cfg.Section("picture").Key("DISABLE_GRAVATAR").SetValue(com.ToStr(form.DisableGravatar))
  278. cfg.Section("picture").Key("ENABLE_FEDERATED_AVATAR").SetValue(com.ToStr(form.EnableFederatedAvatar))
  279. cfg.Section("openid").Key("ENABLE_OPENID_SIGNIN").SetValue(com.ToStr(form.EnableOpenIDSignIn))
  280. cfg.Section("openid").Key("ENABLE_OPENID_SIGNUP").SetValue(com.ToStr(form.EnableOpenIDSignUp))
  281. cfg.Section("service").Key("DISABLE_REGISTRATION").SetValue(com.ToStr(form.DisableRegistration))
  282. cfg.Section("service").Key("ALLOW_ONLY_EXTERNAL_REGISTRATION").SetValue(com.ToStr(form.AllowOnlyExternalRegistration))
  283. cfg.Section("service").Key("ENABLE_CAPTCHA").SetValue(com.ToStr(form.EnableCaptcha))
  284. cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").SetValue(com.ToStr(form.RequireSignInView))
  285. cfg.Section("service").Key("DEFAULT_KEEP_EMAIL_PRIVATE").SetValue(com.ToStr(form.DefaultKeepEmailPrivate))
  286. cfg.Section("service").Key("DEFAULT_ALLOW_CREATE_ORGANIZATION").SetValue(com.ToStr(form.DefaultAllowCreateOrganization))
  287. cfg.Section("service").Key("DEFAULT_ENABLE_TIMETRACKING").SetValue(com.ToStr(form.DefaultEnableTimetracking))
  288. cfg.Section("service").Key("NO_REPLY_ADDRESS").SetValue(com.ToStr(form.NoReplyAddress))
  289. cfg.Section("").Key("RUN_MODE").SetValue("prod")
  290. cfg.Section("session").Key("PROVIDER").SetValue("file")
  291. cfg.Section("log").Key("MODE").SetValue("file")
  292. cfg.Section("log").Key("LEVEL").SetValue(setting.LogLevel)
  293. cfg.Section("log").Key("ROOT_PATH").SetValue(form.LogRootPath)
  294. cfg.Section("security").Key("INSTALL_LOCK").SetValue("true")
  295. var secretKey string
  296. if secretKey, err = generate.NewSecretKey(); err != nil {
  297. ctx.RenderWithErr(ctx.Tr("install.secret_key_failed", err), tplInstall, &form)
  298. return
  299. }
  300. cfg.Section("security").Key("SECRET_KEY").SetValue(secretKey)
  301. err = os.MkdirAll(filepath.Dir(setting.CustomConf), os.ModePerm)
  302. if err != nil {
  303. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  304. return
  305. }
  306. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  307. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  308. return
  309. }
  310. GlobalInit(graceful.GetManager().HammerContext())
  311. // Create admin account
  312. if len(form.AdminName) > 0 {
  313. u := &models.User{
  314. Name: form.AdminName,
  315. Email: form.AdminEmail,
  316. Passwd: form.AdminPasswd,
  317. IsAdmin: true,
  318. IsActive: true,
  319. }
  320. if err = models.CreateUser(u); err != nil {
  321. if !models.IsErrUserAlreadyExist(err) {
  322. setting.InstallLock = false
  323. ctx.Data["Err_AdminName"] = true
  324. ctx.Data["Err_AdminEmail"] = true
  325. ctx.RenderWithErr(ctx.Tr("install.invalid_admin_setting", err), tplInstall, &form)
  326. return
  327. }
  328. log.Info("Admin account already exist")
  329. u, _ = models.GetUserByName(u.Name)
  330. }
  331. // Auto-login for admin
  332. if err = ctx.Session.Set("uid", u.ID); err != nil {
  333. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  334. return
  335. }
  336. if err = ctx.Session.Set("uname", u.Name); err != nil {
  337. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form)
  338. return
  339. }
  340. }
  341. log.Info("First-time run install finished!")
  342. // FIXME: This isn't really enough to completely take account of new configuration
  343. // We should really be restarting:
  344. // - On windows this is probably just a simple restart
  345. // - On linux we can't just use graceful.RestartProcess() everything that was passed in on LISTEN_FDS
  346. // (active or not) needs to be passed out and everything new passed out too.
  347. // This means we need to prevent the cleanup goroutine from running prior to the second GlobalInit
  348. ctx.Flash.Success(ctx.Tr("install.install_success"))
  349. ctx.Redirect(form.AppURL + "user/login")
  350. }