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.

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