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.

1544 lines
47 KiB

10 years ago
10 years ago
10 years ago
10 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
10 years ago
10 years ago
10 years ago
10 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
10 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
6 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
10 years ago
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
10 years ago
10 years ago
8 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
8 years ago
8 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
Squashed commit of the following: commit 0afcb843d7ffd596991c4885cab768273a6eb42c Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 17:13:29 2016 -0600 Removed Upload stats as the upload table is just a temporary table commit 7ecd73ff5535612d79d471409173ee7f1fcfa157 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:42:41 2016 -0600 Fix for CodeMirror mode commit c29b9ab531e2e7af0fb5db24dc17e51027dd1174 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:03:33 2016 -0600 Made tabbing in editor use spaces commit 23af384c53206a8a40e11e45bf49d7a149c4adcd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:56:46 2016 -0600 Fix for data-url commit cfb8a97591cb6fc0a92e49563b7b764c524db0e9 Merge: 7fc8a89 991ce42 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:42:53 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit 7fc8a89cb495478225b02d613e647f99a1489634 Merge: fd3d86c c03d040 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:40:00 2016 -0600 Merge branch 'feature-create-and-edit-repo-file' of github.com:richmahn/gogs into feature-create-and-edit-repo-file commit fd3d86ca6bbc02cfda566a504ffd6b03db4f75ef Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:39:44 2016 -0600 Code cleanup commit c03d0401c1049eeeccc32ab1f9c3303c130be5ee Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 29 15:38:23 2016 -0600 Code cleanup commit 98e1206ccf9f9a4503c020e3a7830cf9f861dfae Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:36:01 2016 -0600 Code cleanup and fixes commit c2895dc742f25f8412879c9fa15e18f27f42f194 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:24:04 2016 -0600 Fixes per Unknwon's requests commit 6aa7e46b21ad4c96e562daa2eac26a8fb408f8ef Merge: 889e9fa ad7ea88 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 17:13:43 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go modules/setting/setting.go commit 889e9faf1bd8559a4979c8f46005d488c1a234d4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:09:18 2016 -0600 Fix in gogs.js commit 47603edf223f147b114be65f3bd27bc1e88827a5 Merge: bb57912 cf85e9e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:07:36 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit bb5791255867a71c11a77b639db050ad09c597a4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:02:18 2016 -0600 Update for using CodeMirror mode addon commit d10d128c51039be19e2af9c66c63db66a9f2ec6d Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 16:12:57 2016 -0600 Update for Edit commit 34a34982025144e3225e389f7849eb6273c1d576 Merge: fa1b752 1c7dcdd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 11:52:02 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go commit fa1b752be29cd455c5184ddac2ffe80b3489763e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 15 18:35:42 2016 -0600 Feature for editing, creating, uploading and deleting files
7 years ago
9 years ago
9 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
7 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
7 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
7 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
7 years ago
9 years ago
9 years ago
10 years ago
10 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
6 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
6 years ago
10 years ago
10 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
6 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 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
10 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package setting
  6. import (
  7. "encoding/base64"
  8. "fmt"
  9. "net"
  10. "net/mail"
  11. "net/url"
  12. "os"
  13. "os/exec"
  14. "path"
  15. "path/filepath"
  16. "regexp"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "code.gitea.io/git"
  22. "code.gitea.io/gitea/modules/generate"
  23. "code.gitea.io/gitea/modules/log"
  24. _ "code.gitea.io/gitea/modules/minwinsvc" // import minwinsvc for windows services
  25. "code.gitea.io/gitea/modules/user"
  26. "github.com/Unknwon/com"
  27. _ "github.com/go-macaron/cache/memcache" // memcache plugin for cache
  28. _ "github.com/go-macaron/cache/redis"
  29. "github.com/go-macaron/session"
  30. _ "github.com/go-macaron/session/redis" // redis plugin for store session
  31. "github.com/go-xorm/core"
  32. "github.com/kballard/go-shellquote"
  33. "gopkg.in/ini.v1"
  34. "strk.kbt.io/projects/go/libravatar"
  35. )
  36. // Scheme describes protocol types
  37. type Scheme string
  38. // enumerates all the scheme types
  39. const (
  40. HTTP Scheme = "http"
  41. HTTPS Scheme = "https"
  42. FCGI Scheme = "fcgi"
  43. UnixSocket Scheme = "unix"
  44. )
  45. // LandingPage describes the default page
  46. type LandingPage string
  47. // enumerates all the landing page types
  48. const (
  49. LandingPageHome LandingPage = "/"
  50. LandingPageExplore LandingPage = "/explore"
  51. LandingPageOrganizations LandingPage = "/explore/organizations"
  52. )
  53. // MarkupParser defines the external parser configured in ini
  54. type MarkupParser struct {
  55. Enabled bool
  56. MarkupName string
  57. Command string
  58. FileExtensions []string
  59. IsInputFile bool
  60. }
  61. // enumerates all the policy repository creating
  62. const (
  63. RepoCreatingLastUserVisibility = "last"
  64. RepoCreatingPrivate = "private"
  65. RepoCreatingPublic = "public"
  66. )
  67. // settings
  68. var (
  69. // AppVer settings
  70. AppVer string
  71. AppBuiltWith string
  72. AppName string
  73. AppURL string
  74. AppSubURL string
  75. AppSubURLDepth int // Number of slashes
  76. AppPath string
  77. AppDataPath string
  78. AppWorkPath string
  79. // Server settings
  80. Protocol Scheme
  81. Domain string
  82. HTTPAddr string
  83. HTTPPort string
  84. LocalURL string
  85. RedirectOtherPort bool
  86. PortToRedirect string
  87. OfflineMode bool
  88. DisableRouterLog bool
  89. CertFile string
  90. KeyFile string
  91. StaticRootPath string
  92. EnableGzip bool
  93. LandingPageURL LandingPage
  94. UnixSocketPermission uint32
  95. EnablePprof bool
  96. SSH = struct {
  97. Disabled bool `ini:"DISABLE_SSH"`
  98. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  99. BuiltinServerUser string `ini:"BUILTIN_SSH_SERVER_USER"`
  100. Domain string `ini:"SSH_DOMAIN"`
  101. Port int `ini:"SSH_PORT"`
  102. ListenHost string `ini:"SSH_LISTEN_HOST"`
  103. ListenPort int `ini:"SSH_LISTEN_PORT"`
  104. RootPath string `ini:"SSH_ROOT_PATH"`
  105. ServerCiphers []string `ini:"SSH_SERVER_CIPHERS"`
  106. ServerKeyExchanges []string `ini:"SSH_SERVER_KEY_EXCHANGES"`
  107. ServerMACs []string `ini:"SSH_SERVER_MACS"`
  108. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  109. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  110. AuthorizedKeysBackup bool `ini:"SSH_AUTHORIZED_KEYS_BACKUP"`
  111. MinimumKeySizeCheck bool `ini:"-"`
  112. MinimumKeySizes map[string]int `ini:"-"`
  113. ExposeAnonymous bool `ini:"SSH_EXPOSE_ANONYMOUS"`
  114. }{
  115. Disabled: false,
  116. StartBuiltinServer: false,
  117. Domain: "",
  118. Port: 22,
  119. ServerCiphers: []string{"aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com", "arcfour256", "arcfour128"},
  120. ServerKeyExchanges: []string{"diffie-hellman-group1-sha1", "diffie-hellman-group14-sha1", "ecdh-sha2-nistp256", "ecdh-sha2-nistp384", "ecdh-sha2-nistp521", "curve25519-sha256@libssh.org"},
  121. ServerMACs: []string{"hmac-sha2-256-etm@openssh.com", "hmac-sha2-256", "hmac-sha1", "hmac-sha1-96"},
  122. KeygenPath: "ssh-keygen",
  123. }
  124. LFS struct {
  125. StartServer bool `ini:"LFS_START_SERVER"`
  126. ContentPath string `ini:"LFS_CONTENT_PATH"`
  127. JWTSecretBase64 string `ini:"LFS_JWT_SECRET"`
  128. JWTSecretBytes []byte `ini:"-"`
  129. }
  130. // Security settings
  131. InstallLock bool
  132. SecretKey string
  133. LogInRememberDays int
  134. CookieUserName string
  135. CookieRememberName string
  136. ReverseProxyAuthUser string
  137. MinPasswordLength int
  138. ImportLocalPaths bool
  139. DisableGitHooks bool
  140. // Database settings
  141. UseSQLite3 bool
  142. UseMySQL bool
  143. UseMSSQL bool
  144. UsePostgreSQL bool
  145. UseTiDB bool
  146. LogSQL bool
  147. // Indexer settings
  148. Indexer struct {
  149. IssuePath string
  150. RepoIndexerEnabled bool
  151. RepoPath string
  152. UpdateQueueLength int
  153. MaxIndexerFileSize int64
  154. }
  155. // Webhook settings
  156. Webhook = struct {
  157. QueueLength int
  158. DeliverTimeout int
  159. SkipTLSVerify bool
  160. Types []string
  161. PagingNum int
  162. }{
  163. QueueLength: 1000,
  164. DeliverTimeout: 5,
  165. SkipTLSVerify: false,
  166. PagingNum: 10,
  167. }
  168. // Repository settings
  169. Repository = struct {
  170. AnsiCharset string
  171. ForcePrivate bool
  172. DefaultPrivate string
  173. MaxCreationLimit int
  174. MirrorQueueLength int
  175. PullRequestQueueLength int
  176. PreferredLicenses []string
  177. DisableHTTPGit bool
  178. UseCompatSSHURI bool
  179. // Repository editor settings
  180. Editor struct {
  181. LineWrapExtensions []string
  182. PreviewableFileModes []string
  183. } `ini:"-"`
  184. // Repository upload settings
  185. Upload struct {
  186. Enabled bool
  187. TempPath string
  188. AllowedTypes []string `delim:"|"`
  189. FileMaxSize int64
  190. MaxFiles int
  191. } `ini:"-"`
  192. // Repository local settings
  193. Local struct {
  194. LocalCopyPath string
  195. LocalWikiPath string
  196. } `ini:"-"`
  197. }{
  198. AnsiCharset: "",
  199. ForcePrivate: false,
  200. DefaultPrivate: RepoCreatingLastUserVisibility,
  201. MaxCreationLimit: -1,
  202. MirrorQueueLength: 1000,
  203. PullRequestQueueLength: 1000,
  204. PreferredLicenses: []string{"Apache License 2.0,MIT License"},
  205. DisableHTTPGit: false,
  206. UseCompatSSHURI: false,
  207. // Repository editor settings
  208. Editor: struct {
  209. LineWrapExtensions []string
  210. PreviewableFileModes []string
  211. }{
  212. LineWrapExtensions: strings.Split(".txt,.md,.markdown,.mdown,.mkd,", ","),
  213. PreviewableFileModes: []string{"markdown"},
  214. },
  215. // Repository upload settings
  216. Upload: struct {
  217. Enabled bool
  218. TempPath string
  219. AllowedTypes []string `delim:"|"`
  220. FileMaxSize int64
  221. MaxFiles int
  222. }{
  223. Enabled: true,
  224. TempPath: "data/tmp/uploads",
  225. AllowedTypes: []string{},
  226. FileMaxSize: 3,
  227. MaxFiles: 5,
  228. },
  229. // Repository local settings
  230. Local: struct {
  231. LocalCopyPath string
  232. LocalWikiPath string
  233. }{
  234. LocalCopyPath: "tmp/local-repo",
  235. LocalWikiPath: "tmp/local-wiki",
  236. },
  237. }
  238. RepoRootPath string
  239. ScriptType = "bash"
  240. // UI settings
  241. UI = struct {
  242. ExplorePagingNum int
  243. IssuePagingNum int
  244. RepoSearchPagingNum int
  245. FeedMaxCommitNum int
  246. ReactionMaxUserNum int
  247. ThemeColorMetaTag string
  248. MaxDisplayFileSize int64
  249. ShowUserEmail bool
  250. Admin struct {
  251. UserPagingNum int
  252. RepoPagingNum int
  253. NoticePagingNum int
  254. OrgPagingNum int
  255. } `ini:"ui.admin"`
  256. User struct {
  257. RepoPagingNum int
  258. } `ini:"ui.user"`
  259. Meta struct {
  260. Author string
  261. Description string
  262. Keywords string
  263. } `ini:"ui.meta"`
  264. }{
  265. ExplorePagingNum: 20,
  266. IssuePagingNum: 10,
  267. RepoSearchPagingNum: 10,
  268. FeedMaxCommitNum: 5,
  269. ReactionMaxUserNum: 10,
  270. ThemeColorMetaTag: `#6cc644`,
  271. MaxDisplayFileSize: 8388608,
  272. Admin: struct {
  273. UserPagingNum int
  274. RepoPagingNum int
  275. NoticePagingNum int
  276. OrgPagingNum int
  277. }{
  278. UserPagingNum: 50,
  279. RepoPagingNum: 50,
  280. NoticePagingNum: 25,
  281. OrgPagingNum: 50,
  282. },
  283. User: struct {
  284. RepoPagingNum int
  285. }{
  286. RepoPagingNum: 15,
  287. },
  288. Meta: struct {
  289. Author string
  290. Description string
  291. Keywords string
  292. }{
  293. Author: "Gitea - Git with a cup of tea",
  294. Description: "Gitea (Git with a cup of tea) is a painless self-hosted Git service written in Go",
  295. Keywords: "go,git,self-hosted,gitea",
  296. },
  297. }
  298. // Markdown settings
  299. Markdown = struct {
  300. EnableHardLineBreak bool
  301. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  302. FileExtensions []string
  303. }{
  304. EnableHardLineBreak: false,
  305. FileExtensions: strings.Split(".md,.markdown,.mdown,.mkd", ","),
  306. }
  307. // Admin settings
  308. Admin struct {
  309. DisableRegularOrgCreation bool
  310. }
  311. // Picture settings
  312. AvatarUploadPath string
  313. GravatarSource string
  314. GravatarSourceURL *url.URL
  315. DisableGravatar bool
  316. EnableFederatedAvatar bool
  317. LibravatarService *libravatar.Libravatar
  318. // Log settings
  319. LogLevel string
  320. LogRootPath string
  321. LogModes []string
  322. LogConfigs []string
  323. // Attachment settings
  324. AttachmentPath string
  325. AttachmentAllowedTypes string
  326. AttachmentMaxSize int64
  327. AttachmentMaxFiles int
  328. AttachmentEnabled bool
  329. // Time settings
  330. TimeFormat string
  331. // Session settings
  332. SessionConfig session.Options
  333. CSRFCookieName = "_csrf"
  334. // Cron tasks
  335. Cron = struct {
  336. UpdateMirror struct {
  337. Enabled bool
  338. RunAtStart bool
  339. Schedule string
  340. } `ini:"cron.update_mirrors"`
  341. RepoHealthCheck struct {
  342. Enabled bool
  343. RunAtStart bool
  344. Schedule string
  345. Timeout time.Duration
  346. Args []string `delim:" "`
  347. } `ini:"cron.repo_health_check"`
  348. CheckRepoStats struct {
  349. Enabled bool
  350. RunAtStart bool
  351. Schedule string
  352. } `ini:"cron.check_repo_stats"`
  353. ArchiveCleanup struct {
  354. Enabled bool
  355. RunAtStart bool
  356. Schedule string
  357. OlderThan time.Duration
  358. } `ini:"cron.archive_cleanup"`
  359. SyncExternalUsers struct {
  360. Enabled bool
  361. RunAtStart bool
  362. Schedule string
  363. UpdateExisting bool
  364. } `ini:"cron.sync_external_users"`
  365. DeletedBranchesCleanup struct {
  366. Enabled bool
  367. RunAtStart bool
  368. Schedule string
  369. OlderThan time.Duration
  370. } `ini:"cron.deleted_branches_cleanup"`
  371. }{
  372. UpdateMirror: struct {
  373. Enabled bool
  374. RunAtStart bool
  375. Schedule string
  376. }{
  377. Enabled: true,
  378. RunAtStart: false,
  379. Schedule: "@every 10m",
  380. },
  381. RepoHealthCheck: struct {
  382. Enabled bool
  383. RunAtStart bool
  384. Schedule string
  385. Timeout time.Duration
  386. Args []string `delim:" "`
  387. }{
  388. Enabled: true,
  389. RunAtStart: false,
  390. Schedule: "@every 24h",
  391. Timeout: 60 * time.Second,
  392. Args: []string{},
  393. },
  394. CheckRepoStats: struct {
  395. Enabled bool
  396. RunAtStart bool
  397. Schedule string
  398. }{
  399. Enabled: true,
  400. RunAtStart: true,
  401. Schedule: "@every 24h",
  402. },
  403. ArchiveCleanup: struct {
  404. Enabled bool
  405. RunAtStart bool
  406. Schedule string
  407. OlderThan time.Duration
  408. }{
  409. Enabled: true,
  410. RunAtStart: true,
  411. Schedule: "@every 24h",
  412. OlderThan: 24 * time.Hour,
  413. },
  414. SyncExternalUsers: struct {
  415. Enabled bool
  416. RunAtStart bool
  417. Schedule string
  418. UpdateExisting bool
  419. }{
  420. Enabled: true,
  421. RunAtStart: false,
  422. Schedule: "@every 24h",
  423. UpdateExisting: true,
  424. },
  425. DeletedBranchesCleanup: struct {
  426. Enabled bool
  427. RunAtStart bool
  428. Schedule string
  429. OlderThan time.Duration
  430. }{
  431. Enabled: true,
  432. RunAtStart: true,
  433. Schedule: "@every 24h",
  434. OlderThan: 24 * time.Hour,
  435. },
  436. }
  437. // Git settings
  438. Git = struct {
  439. Version string `ini:"-"`
  440. DisableDiffHighlight bool
  441. MaxGitDiffLines int
  442. MaxGitDiffLineCharacters int
  443. MaxGitDiffFiles int
  444. GCArgs []string `delim:" "`
  445. Timeout struct {
  446. Migrate int
  447. Mirror int
  448. Clone int
  449. Pull int
  450. GC int `ini:"GC"`
  451. } `ini:"git.timeout"`
  452. }{
  453. DisableDiffHighlight: false,
  454. MaxGitDiffLines: 1000,
  455. MaxGitDiffLineCharacters: 5000,
  456. MaxGitDiffFiles: 100,
  457. GCArgs: []string{},
  458. Timeout: struct {
  459. Migrate int
  460. Mirror int
  461. Clone int
  462. Pull int
  463. GC int `ini:"GC"`
  464. }{
  465. Migrate: 600,
  466. Mirror: 300,
  467. Clone: 300,
  468. Pull: 300,
  469. GC: 60,
  470. },
  471. }
  472. // Mirror settings
  473. Mirror struct {
  474. DefaultInterval time.Duration
  475. MinInterval time.Duration
  476. }
  477. // API settings
  478. API = struct {
  479. EnableSwaggerEndpoint bool
  480. MaxResponseItems int
  481. }{
  482. EnableSwaggerEndpoint: true,
  483. MaxResponseItems: 50,
  484. }
  485. // I18n settings
  486. Langs []string
  487. Names []string
  488. dateLangs map[string]string
  489. // Highlight settings are loaded in modules/template/highlight.go
  490. // Other settings
  491. ShowFooterBranding bool
  492. ShowFooterVersion bool
  493. ShowFooterTemplateLoadTime bool
  494. // Global setting objects
  495. Cfg *ini.File
  496. CustomPath string // Custom directory path
  497. CustomConf string
  498. CustomPID string
  499. ProdMode bool
  500. RunUser string
  501. IsWindows bool
  502. HasRobotsTxt bool
  503. InternalToken string // internal access token
  504. IterateBufferSize int
  505. ExternalMarkupParsers []MarkupParser
  506. // UILocation is the location on the UI, so that we can display the time on UI.
  507. // Currently only show the default time.Local, it could be added to app.ini after UI is ready
  508. UILocation = time.Local
  509. )
  510. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  511. func DateLang(lang string) string {
  512. name, ok := dateLangs[lang]
  513. if ok {
  514. return name
  515. }
  516. return "en"
  517. }
  518. func getAppPath() (string, error) {
  519. var appPath string
  520. var err error
  521. if IsWindows && filepath.IsAbs(os.Args[0]) {
  522. appPath = filepath.Clean(os.Args[0])
  523. } else {
  524. appPath, err = exec.LookPath(os.Args[0])
  525. }
  526. if err != nil {
  527. return "", err
  528. }
  529. appPath, err = filepath.Abs(appPath)
  530. if err != nil {
  531. return "", err
  532. }
  533. // Note: we don't use path.Dir here because it does not handle case
  534. // which path starts with two "/" in Windows: "//psf/Home/..."
  535. return strings.Replace(appPath, "\\", "/", -1), err
  536. }
  537. func getWorkPath(appPath string) string {
  538. workPath := ""
  539. giteaWorkPath := os.Getenv("GITEA_WORK_DIR")
  540. if len(giteaWorkPath) > 0 {
  541. workPath = giteaWorkPath
  542. } else {
  543. i := strings.LastIndex(appPath, "/")
  544. if i == -1 {
  545. workPath = appPath
  546. } else {
  547. workPath = appPath[:i]
  548. }
  549. }
  550. return strings.Replace(workPath, "\\", "/", -1)
  551. }
  552. func init() {
  553. IsWindows = runtime.GOOS == "windows"
  554. log.NewLogger(0, "console", `{"level": 0}`)
  555. var err error
  556. if AppPath, err = getAppPath(); err != nil {
  557. log.Fatal(4, "Failed to get app path: %v", err)
  558. }
  559. AppWorkPath = getWorkPath(AppPath)
  560. }
  561. func forcePathSeparator(path string) {
  562. if strings.Contains(path, "\\") {
  563. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  564. }
  565. }
  566. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  567. // actual user that runs the app. The first return value is the actual user name.
  568. // This check is ignored under Windows since SSH remote login is not the main
  569. // method to login on Windows.
  570. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  571. if IsWindows {
  572. return "", true
  573. }
  574. currentUser := user.CurrentUsername()
  575. return currentUser, runUser == currentUser
  576. }
  577. func createPIDFile(pidPath string) {
  578. currentPid := os.Getpid()
  579. if err := os.MkdirAll(filepath.Dir(pidPath), os.ModePerm); err != nil {
  580. log.Fatal(4, "Failed to create PID folder: %v", err)
  581. }
  582. file, err := os.Create(pidPath)
  583. if err != nil {
  584. log.Fatal(4, "Failed to create PID file: %v", err)
  585. }
  586. defer file.Close()
  587. if _, err := file.WriteString(strconv.FormatInt(int64(currentPid), 10)); err != nil {
  588. log.Fatal(4, "Failed to write PID information: %v", err)
  589. }
  590. }
  591. // NewContext initializes configuration context.
  592. // NOTE: do not print any log except error.
  593. func NewContext() {
  594. Cfg = ini.Empty()
  595. CustomPath = os.Getenv("GITEA_CUSTOM")
  596. if len(CustomPath) == 0 {
  597. CustomPath = path.Join(AppWorkPath, "custom")
  598. } else if !filepath.IsAbs(CustomPath) {
  599. CustomPath = path.Join(AppWorkPath, CustomPath)
  600. }
  601. if len(CustomPID) > 0 {
  602. createPIDFile(CustomPID)
  603. }
  604. if len(CustomConf) == 0 {
  605. CustomConf = path.Join(CustomPath, "conf/app.ini")
  606. } else if !filepath.IsAbs(CustomConf) {
  607. CustomConf = path.Join(CustomPath, CustomConf)
  608. }
  609. if com.IsFile(CustomConf) {
  610. if err := Cfg.Append(CustomConf); err != nil {
  611. log.Fatal(4, "Failed to load custom conf '%s': %v", CustomConf, err)
  612. }
  613. } else {
  614. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  615. }
  616. Cfg.NameMapper = ini.AllCapsUnderscore
  617. homeDir, err := com.HomeDir()
  618. if err != nil {
  619. log.Fatal(4, "Failed to get home directory: %v", err)
  620. }
  621. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  622. LogLevel = getLogLevel("log", "LEVEL", "Info")
  623. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(AppWorkPath, "log"))
  624. forcePathSeparator(LogRootPath)
  625. sec := Cfg.Section("server")
  626. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gitea: Git with a cup of tea")
  627. Protocol = HTTP
  628. if sec.Key("PROTOCOL").String() == "https" {
  629. Protocol = HTTPS
  630. CertFile = sec.Key("CERT_FILE").String()
  631. KeyFile = sec.Key("KEY_FILE").String()
  632. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  633. Protocol = FCGI
  634. } else if sec.Key("PROTOCOL").String() == "unix" {
  635. Protocol = UnixSocket
  636. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  637. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  638. if err != nil || UnixSocketPermissionParsed > 0777 {
  639. log.Fatal(4, "Failed to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  640. }
  641. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  642. }
  643. Domain = sec.Key("DOMAIN").MustString("localhost")
  644. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  645. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  646. defaultAppURL := string(Protocol) + "://" + Domain
  647. if (Protocol == HTTP && HTTPPort != "80") || (Protocol == HTTPS && HTTPPort != "443") {
  648. defaultAppURL += ":" + HTTPPort
  649. }
  650. AppURL = sec.Key("ROOT_URL").MustString(defaultAppURL)
  651. AppURL = strings.TrimRight(AppURL, "/") + "/"
  652. // Check if has app suburl.
  653. url, err := url.Parse(AppURL)
  654. if err != nil {
  655. log.Fatal(4, "Invalid ROOT_URL '%s': %s", AppURL, err)
  656. }
  657. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  658. // This value is empty if site does not have sub-url.
  659. AppSubURL = strings.TrimSuffix(url.Path, "/")
  660. AppSubURLDepth = strings.Count(AppSubURL, "/")
  661. // Check if Domain differs from AppURL domain than update it to AppURL's domain
  662. // TODO: Can be replaced with url.Hostname() when minimal GoLang version is 1.8
  663. urlHostname := strings.SplitN(url.Host, ":", 2)[0]
  664. if urlHostname != Domain && net.ParseIP(urlHostname) == nil {
  665. Domain = urlHostname
  666. }
  667. var defaultLocalURL string
  668. switch Protocol {
  669. case UnixSocket:
  670. defaultLocalURL = "http://unix/"
  671. case FCGI:
  672. defaultLocalURL = AppURL
  673. default:
  674. defaultLocalURL = string(Protocol) + "://"
  675. if HTTPAddr == "0.0.0.0" {
  676. defaultLocalURL += "localhost"
  677. } else {
  678. defaultLocalURL += HTTPAddr
  679. }
  680. defaultLocalURL += ":" + HTTPPort + "/"
  681. }
  682. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(defaultLocalURL)
  683. RedirectOtherPort = sec.Key("REDIRECT_OTHER_PORT").MustBool(false)
  684. PortToRedirect = sec.Key("PORT_TO_REDIRECT").MustString("80")
  685. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  686. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  687. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(AppWorkPath)
  688. AppDataPath = sec.Key("APP_DATA_PATH").MustString(path.Join(AppWorkPath, "data"))
  689. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  690. EnablePprof = sec.Key("ENABLE_PPROF").MustBool(false)
  691. switch sec.Key("LANDING_PAGE").MustString("home") {
  692. case "explore":
  693. LandingPageURL = LandingPageExplore
  694. case "organizations":
  695. LandingPageURL = LandingPageOrganizations
  696. default:
  697. LandingPageURL = LandingPageHome
  698. }
  699. if len(SSH.Domain) == 0 {
  700. SSH.Domain = Domain
  701. }
  702. SSH.RootPath = path.Join(homeDir, ".ssh")
  703. serverCiphers := sec.Key("SSH_SERVER_CIPHERS").Strings(",")
  704. if len(serverCiphers) > 0 {
  705. SSH.ServerCiphers = serverCiphers
  706. }
  707. serverKeyExchanges := sec.Key("SSH_SERVER_KEY_EXCHANGES").Strings(",")
  708. if len(serverKeyExchanges) > 0 {
  709. SSH.ServerKeyExchanges = serverKeyExchanges
  710. }
  711. serverMACs := sec.Key("SSH_SERVER_MACS").Strings(",")
  712. if len(serverMACs) > 0 {
  713. SSH.ServerMACs = serverMACs
  714. }
  715. SSH.KeyTestPath = os.TempDir()
  716. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  717. log.Fatal(4, "Failed to map SSH settings: %v", err)
  718. }
  719. SSH.KeygenPath = sec.Key("SSH_KEYGEN_PATH").MustString("ssh-keygen")
  720. SSH.Port = sec.Key("SSH_PORT").MustInt(22)
  721. SSH.ListenPort = sec.Key("SSH_LISTEN_PORT").MustInt(SSH.Port)
  722. // When disable SSH, start builtin server value is ignored.
  723. if SSH.Disabled {
  724. SSH.StartBuiltinServer = false
  725. }
  726. if !SSH.Disabled && !SSH.StartBuiltinServer {
  727. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  728. log.Fatal(4, "Failed to create '%s': %v", SSH.RootPath, err)
  729. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  730. log.Fatal(4, "Failed to create '%s': %v", SSH.KeyTestPath, err)
  731. }
  732. }
  733. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool()
  734. SSH.MinimumKeySizes = map[string]int{}
  735. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  736. for _, key := range minimumKeySizes {
  737. if key.MustInt() != -1 {
  738. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  739. }
  740. }
  741. SSH.AuthorizedKeysBackup = sec.Key("SSH_AUTHORIZED_KEYS_BACKUP").MustBool(true)
  742. SSH.ExposeAnonymous = sec.Key("SSH_EXPOSE_ANONYMOUS").MustBool(false)
  743. sec = Cfg.Section("server")
  744. if err = sec.MapTo(&LFS); err != nil {
  745. log.Fatal(4, "Failed to map LFS settings: %v", err)
  746. }
  747. LFS.ContentPath = sec.Key("LFS_CONTENT_PATH").MustString(filepath.Join(AppDataPath, "lfs"))
  748. if !filepath.IsAbs(LFS.ContentPath) {
  749. LFS.ContentPath = filepath.Join(AppWorkPath, LFS.ContentPath)
  750. }
  751. if LFS.StartServer {
  752. if err := os.MkdirAll(LFS.ContentPath, 0700); err != nil {
  753. log.Fatal(4, "Failed to create '%s': %v", LFS.ContentPath, err)
  754. }
  755. LFS.JWTSecretBytes = make([]byte, 32)
  756. n, err := base64.RawURLEncoding.Decode(LFS.JWTSecretBytes, []byte(LFS.JWTSecretBase64))
  757. if err != nil || n != 32 {
  758. LFS.JWTSecretBase64, err = generate.NewLfsJwtSecret()
  759. if err != nil {
  760. log.Fatal(4, "Error generating JWT Secret for custom config: %v", err)
  761. return
  762. }
  763. // Save secret
  764. cfg := ini.Empty()
  765. if com.IsFile(CustomConf) {
  766. // Keeps custom settings if there is already something.
  767. if err := cfg.Append(CustomConf); err != nil {
  768. log.Error(4, "Failed to load custom conf '%s': %v", CustomConf, err)
  769. }
  770. }
  771. cfg.Section("server").Key("LFS_JWT_SECRET").SetValue(LFS.JWTSecretBase64)
  772. if err := os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm); err != nil {
  773. log.Fatal(4, "Failed to create '%s': %v", CustomConf, err)
  774. }
  775. if err := cfg.SaveTo(CustomConf); err != nil {
  776. log.Fatal(4, "Error saving generated JWT Secret to custom config: %v", err)
  777. return
  778. }
  779. }
  780. //Disable LFS client hooks if installed for the current OS user
  781. //Needs at least git v2.1.2
  782. binVersion, err := git.BinVersion()
  783. if err != nil {
  784. log.Fatal(4, "Error retrieving git version: %v", err)
  785. }
  786. splitVersion := strings.SplitN(binVersion, ".", 4)
  787. majorVersion, err := strconv.ParseUint(splitVersion[0], 10, 64)
  788. if err != nil {
  789. log.Fatal(4, "Error parsing git major version: %v", err)
  790. }
  791. minorVersion, err := strconv.ParseUint(splitVersion[1], 10, 64)
  792. if err != nil {
  793. log.Fatal(4, "Error parsing git minor version: %v", err)
  794. }
  795. revisionVersion, err := strconv.ParseUint(splitVersion[2], 10, 64)
  796. if err != nil {
  797. log.Fatal(4, "Error parsing git revision version: %v", err)
  798. }
  799. if !((majorVersion > 2) || (majorVersion == 2 && minorVersion > 1) ||
  800. (majorVersion == 2 && minorVersion == 1 && revisionVersion >= 2)) {
  801. LFS.StartServer = false
  802. log.Error(4, "LFS server support needs at least Git v2.1.2")
  803. } else {
  804. git.GlobalCommandArgs = append(git.GlobalCommandArgs, "-c", "filter.lfs.required=",
  805. "-c", "filter.lfs.smudge=", "-c", "filter.lfs.clean=")
  806. }
  807. }
  808. sec = Cfg.Section("security")
  809. InstallLock = sec.Key("INSTALL_LOCK").MustBool(false)
  810. SecretKey = sec.Key("SECRET_KEY").MustString("!#@FDEWREWR&*(")
  811. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt(7)
  812. CookieUserName = sec.Key("COOKIE_USERNAME").MustString("gitea_awesome")
  813. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").MustString("gitea_incredible")
  814. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  815. MinPasswordLength = sec.Key("MIN_PASSWORD_LENGTH").MustInt(6)
  816. ImportLocalPaths = sec.Key("IMPORT_LOCAL_PATHS").MustBool(false)
  817. DisableGitHooks = sec.Key("DISABLE_GIT_HOOKS").MustBool(false)
  818. InternalToken = sec.Key("INTERNAL_TOKEN").String()
  819. if len(InternalToken) == 0 {
  820. InternalToken, err = generate.NewInternalToken()
  821. if err != nil {
  822. log.Fatal(4, "Error generate internal token: %v", err)
  823. }
  824. // Save secret
  825. cfgSave := ini.Empty()
  826. if com.IsFile(CustomConf) {
  827. // Keeps custom settings if there is already something.
  828. if err := cfgSave.Append(CustomConf); err != nil {
  829. log.Error(4, "Failed to load custom conf '%s': %v", CustomConf, err)
  830. }
  831. }
  832. cfgSave.Section("security").Key("INTERNAL_TOKEN").SetValue(InternalToken)
  833. if err := os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm); err != nil {
  834. log.Fatal(4, "Failed to create '%s': %v", CustomConf, err)
  835. }
  836. if err := cfgSave.SaveTo(CustomConf); err != nil {
  837. log.Fatal(4, "Error saving generated JWT Secret to custom config: %v", err)
  838. }
  839. }
  840. IterateBufferSize = Cfg.Section("database").Key("ITERATE_BUFFER_SIZE").MustInt(50)
  841. LogSQL = Cfg.Section("database").Key("LOG_SQL").MustBool(true)
  842. sec = Cfg.Section("attachment")
  843. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  844. if !filepath.IsAbs(AttachmentPath) {
  845. AttachmentPath = path.Join(AppWorkPath, AttachmentPath)
  846. }
  847. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png,application/zip,application/gzip"), "|", ",", -1)
  848. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  849. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  850. AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
  851. TimeFormatKey := Cfg.Section("time").Key("FORMAT").MustString("RFC1123")
  852. TimeFormat = map[string]string{
  853. "ANSIC": time.ANSIC,
  854. "UnixDate": time.UnixDate,
  855. "RubyDate": time.RubyDate,
  856. "RFC822": time.RFC822,
  857. "RFC822Z": time.RFC822Z,
  858. "RFC850": time.RFC850,
  859. "RFC1123": time.RFC1123,
  860. "RFC1123Z": time.RFC1123Z,
  861. "RFC3339": time.RFC3339,
  862. "RFC3339Nano": time.RFC3339Nano,
  863. "Kitchen": time.Kitchen,
  864. "Stamp": time.Stamp,
  865. "StampMilli": time.StampMilli,
  866. "StampMicro": time.StampMicro,
  867. "StampNano": time.StampNano,
  868. }[TimeFormatKey]
  869. // When the TimeFormatKey does not exist in the previous map e.g.'2006-01-02 15:04:05'
  870. if len(TimeFormat) == 0 {
  871. TimeFormat = TimeFormatKey
  872. TestTimeFormat, _ := time.Parse(TimeFormat, TimeFormat)
  873. if TestTimeFormat.Format(time.RFC3339) != "2006-01-02T15:04:05Z" {
  874. log.Fatal(4, "Can't create time properly, please check your time format has 2006, 01, 02, 15, 04 and 05")
  875. }
  876. log.Trace("Custom TimeFormat: %s", TimeFormat)
  877. }
  878. RunUser = Cfg.Section("").Key("RUN_USER").MustString(user.CurrentUsername())
  879. // Does not check run user when the install lock is off.
  880. if InstallLock {
  881. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  882. if !match {
  883. log.Fatal(4, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  884. }
  885. }
  886. SSH.BuiltinServerUser = Cfg.Section("server").Key("BUILTIN_SSH_SERVER_USER").MustString(RunUser)
  887. // Determine and create root git repository path.
  888. sec = Cfg.Section("repository")
  889. Repository.DisableHTTPGit = sec.Key("DISABLE_HTTP_GIT").MustBool()
  890. Repository.UseCompatSSHURI = sec.Key("USE_COMPAT_SSH_URI").MustBool()
  891. Repository.MaxCreationLimit = sec.Key("MAX_CREATION_LIMIT").MustInt(-1)
  892. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gitea-repositories"))
  893. forcePathSeparator(RepoRootPath)
  894. if !filepath.IsAbs(RepoRootPath) {
  895. RepoRootPath = filepath.Join(AppWorkPath, RepoRootPath)
  896. } else {
  897. RepoRootPath = filepath.Clean(RepoRootPath)
  898. }
  899. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  900. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  901. log.Fatal(4, "Failed to map Repository settings: %v", err)
  902. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  903. log.Fatal(4, "Failed to map Repository.Editor settings: %v", err)
  904. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  905. log.Fatal(4, "Failed to map Repository.Upload settings: %v", err)
  906. } else if err = Cfg.Section("repository.local").MapTo(&Repository.Local); err != nil {
  907. log.Fatal(4, "Failed to map Repository.Local settings: %v", err)
  908. }
  909. if !filepath.IsAbs(Repository.Upload.TempPath) {
  910. Repository.Upload.TempPath = path.Join(AppWorkPath, Repository.Upload.TempPath)
  911. }
  912. sec = Cfg.Section("picture")
  913. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  914. forcePathSeparator(AvatarUploadPath)
  915. if !filepath.IsAbs(AvatarUploadPath) {
  916. AvatarUploadPath = path.Join(AppWorkPath, AvatarUploadPath)
  917. }
  918. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  919. case "duoshuo":
  920. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  921. case "gravatar":
  922. GravatarSource = "https://secure.gravatar.com/avatar/"
  923. case "libravatar":
  924. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  925. default:
  926. GravatarSource = source
  927. }
  928. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  929. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool(!InstallLock)
  930. if OfflineMode {
  931. DisableGravatar = true
  932. EnableFederatedAvatar = false
  933. }
  934. if DisableGravatar {
  935. EnableFederatedAvatar = false
  936. }
  937. if EnableFederatedAvatar || !DisableGravatar {
  938. GravatarSourceURL, err = url.Parse(GravatarSource)
  939. if err != nil {
  940. log.Fatal(4, "Failed to parse Gravatar URL(%s): %v",
  941. GravatarSource, err)
  942. }
  943. }
  944. if EnableFederatedAvatar {
  945. LibravatarService = libravatar.New()
  946. if GravatarSourceURL.Scheme == "https" {
  947. LibravatarService.SetUseHTTPS(true)
  948. LibravatarService.SetSecureFallbackHost(GravatarSourceURL.Host)
  949. } else {
  950. LibravatarService.SetUseHTTPS(false)
  951. LibravatarService.SetFallbackHost(GravatarSourceURL.Host)
  952. }
  953. }
  954. if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  955. log.Fatal(4, "Failed to map UI settings: %v", err)
  956. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  957. log.Fatal(4, "Failed to map Markdown settings: %v", err)
  958. } else if err = Cfg.Section("admin").MapTo(&Admin); err != nil {
  959. log.Fatal(4, "Fail to map Admin settings: %v", err)
  960. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  961. log.Fatal(4, "Failed to map Cron settings: %v", err)
  962. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  963. log.Fatal(4, "Failed to map Git settings: %v", err)
  964. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  965. log.Fatal(4, "Failed to map API settings: %v", err)
  966. }
  967. sec = Cfg.Section("mirror")
  968. Mirror.MinInterval = sec.Key("MIN_INTERVAL").MustDuration(10 * time.Minute)
  969. Mirror.DefaultInterval = sec.Key("DEFAULT_INTERVAL").MustDuration(8 * time.Hour)
  970. if Mirror.MinInterval.Minutes() < 1 {
  971. log.Warn("Mirror.MinInterval is too low")
  972. Mirror.MinInterval = 1 * time.Minute
  973. }
  974. if Mirror.DefaultInterval < Mirror.MinInterval {
  975. log.Warn("Mirror.DefaultInterval is less than Mirror.MinInterval")
  976. Mirror.DefaultInterval = time.Hour * 8
  977. }
  978. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  979. if len(Langs) == 0 {
  980. Langs = defaultLangs
  981. }
  982. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  983. if len(Names) == 0 {
  984. Names = defaultLangNames
  985. }
  986. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  987. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool(false)
  988. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool(true)
  989. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool(true)
  990. UI.ShowUserEmail = Cfg.Section("ui").Key("SHOW_USER_EMAIL").MustBool(true)
  991. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  992. extensionReg := regexp.MustCompile(`\.\w`)
  993. for _, sec := range Cfg.Section("markup").ChildSections() {
  994. name := strings.TrimLeft(sec.Name(), "markup.")
  995. if name == "" {
  996. log.Warn("name is empty, markup " + sec.Name() + "ignored")
  997. continue
  998. }
  999. extensions := sec.Key("FILE_EXTENSIONS").Strings(",")
  1000. var exts = make([]string, 0, len(extensions))
  1001. for _, extension := range extensions {
  1002. if !extensionReg.MatchString(extension) {
  1003. log.Warn(sec.Name() + " file extension " + extension + " is invalid. Extension ignored")
  1004. } else {
  1005. exts = append(exts, extension)
  1006. }
  1007. }
  1008. if len(exts) == 0 {
  1009. log.Warn(sec.Name() + " file extension is empty, markup " + name + " ignored")
  1010. continue
  1011. }
  1012. command := sec.Key("RENDER_COMMAND").MustString("")
  1013. if command == "" {
  1014. log.Warn(" RENDER_COMMAND is empty, markup " + name + " ignored")
  1015. continue
  1016. }
  1017. ExternalMarkupParsers = append(ExternalMarkupParsers, MarkupParser{
  1018. Enabled: sec.Key("ENABLED").MustBool(false),
  1019. MarkupName: name,
  1020. FileExtensions: exts,
  1021. Command: command,
  1022. IsInputFile: sec.Key("IS_INPUT_FILE").MustBool(false),
  1023. })
  1024. }
  1025. }
  1026. // Service settings
  1027. var Service struct {
  1028. ActiveCodeLives int
  1029. ResetPwdCodeLives int
  1030. RegisterEmailConfirm bool
  1031. DisableRegistration bool
  1032. ShowRegistrationButton bool
  1033. RequireSignInView bool
  1034. EnableNotifyMail bool
  1035. EnableReverseProxyAuth bool
  1036. EnableReverseProxyAutoRegister bool
  1037. EnableCaptcha bool
  1038. DefaultKeepEmailPrivate bool
  1039. DefaultAllowCreateOrganization bool
  1040. EnableTimetracking bool
  1041. DefaultEnableTimetracking bool
  1042. DefaultAllowOnlyContributorsToTrackTime bool
  1043. NoReplyAddress string
  1044. // OpenID settings
  1045. EnableOpenIDSignIn bool
  1046. EnableOpenIDSignUp bool
  1047. OpenIDWhitelist []*regexp.Regexp
  1048. OpenIDBlacklist []*regexp.Regexp
  1049. }
  1050. func newService() {
  1051. sec := Cfg.Section("service")
  1052. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  1053. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  1054. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  1055. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  1056. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  1057. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  1058. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  1059. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  1060. Service.DefaultKeepEmailPrivate = sec.Key("DEFAULT_KEEP_EMAIL_PRIVATE").MustBool()
  1061. Service.DefaultAllowCreateOrganization = sec.Key("DEFAULT_ALLOW_CREATE_ORGANIZATION").MustBool(true)
  1062. Service.EnableTimetracking = sec.Key("ENABLE_TIMETRACKING").MustBool(true)
  1063. if Service.EnableTimetracking {
  1064. Service.DefaultEnableTimetracking = sec.Key("DEFAULT_ENABLE_TIMETRACKING").MustBool(true)
  1065. }
  1066. Service.DefaultAllowOnlyContributorsToTrackTime = sec.Key("DEFAULT_ALLOW_ONLY_CONTRIBUTORS_TO_TRACK_TIME").MustBool(true)
  1067. Service.NoReplyAddress = sec.Key("NO_REPLY_ADDRESS").MustString("noreply.example.org")
  1068. sec = Cfg.Section("openid")
  1069. Service.EnableOpenIDSignIn = sec.Key("ENABLE_OPENID_SIGNIN").MustBool(!InstallLock)
  1070. Service.EnableOpenIDSignUp = sec.Key("ENABLE_OPENID_SIGNUP").MustBool(!Service.DisableRegistration && Service.EnableOpenIDSignIn)
  1071. pats := sec.Key("WHITELISTED_URIS").Strings(" ")
  1072. if len(pats) != 0 {
  1073. Service.OpenIDWhitelist = make([]*regexp.Regexp, len(pats))
  1074. for i, p := range pats {
  1075. Service.OpenIDWhitelist[i] = regexp.MustCompilePOSIX(p)
  1076. }
  1077. }
  1078. pats = sec.Key("BLACKLISTED_URIS").Strings(" ")
  1079. if len(pats) != 0 {
  1080. Service.OpenIDBlacklist = make([]*regexp.Regexp, len(pats))
  1081. for i, p := range pats {
  1082. Service.OpenIDBlacklist[i] = regexp.MustCompilePOSIX(p)
  1083. }
  1084. }
  1085. }
  1086. var logLevels = map[string]string{
  1087. "Trace": "0",
  1088. "Debug": "1",
  1089. "Info": "2",
  1090. "Warn": "3",
  1091. "Error": "4",
  1092. "Critical": "5",
  1093. }
  1094. func getLogLevel(section string, key string, defaultValue string) string {
  1095. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  1096. return Cfg.Section(section).Key(key).In(defaultValue, validLevels)
  1097. }
  1098. func newLogService() {
  1099. log.Info("Gitea v%s%s", AppVer, AppBuiltWith)
  1100. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  1101. LogConfigs = make([]string, len(LogModes))
  1102. useConsole := false
  1103. for i := 0; i < len(LogModes); i++ {
  1104. LogModes[i] = strings.TrimSpace(LogModes[i])
  1105. if LogModes[i] == "console" {
  1106. useConsole = true
  1107. }
  1108. }
  1109. if !useConsole {
  1110. log.DelLogger("console")
  1111. }
  1112. for i, mode := range LogModes {
  1113. sec, err := Cfg.GetSection("log." + mode)
  1114. if err != nil {
  1115. sec, _ = Cfg.NewSection("log." + mode)
  1116. }
  1117. // Log level.
  1118. levelName := getLogLevel("log."+mode, "LEVEL", LogLevel)
  1119. level, ok := logLevels[levelName]
  1120. if !ok {
  1121. log.Fatal(4, "Unknown log level: %s", levelName)
  1122. }
  1123. // Generate log configuration.
  1124. switch mode {
  1125. case "console":
  1126. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  1127. case "file":
  1128. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gitea.log"))
  1129. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  1130. panic(err.Error())
  1131. }
  1132. LogConfigs[i] = fmt.Sprintf(
  1133. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  1134. logPath,
  1135. sec.Key("LOG_ROTATE").MustBool(true),
  1136. sec.Key("MAX_LINES").MustInt(1000000),
  1137. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  1138. sec.Key("DAILY_ROTATE").MustBool(true),
  1139. sec.Key("MAX_DAYS").MustInt(7))
  1140. case "conn":
  1141. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  1142. sec.Key("RECONNECT_ON_MSG").MustBool(),
  1143. sec.Key("RECONNECT").MustBool(),
  1144. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  1145. sec.Key("ADDR").MustString(":7020"))
  1146. case "smtp":
  1147. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":["%s"],"subject":"%s"}`, level,
  1148. sec.Key("USER").MustString("example@example.com"),
  1149. sec.Key("PASSWD").MustString("******"),
  1150. sec.Key("HOST").MustString("127.0.0.1:25"),
  1151. strings.Replace(sec.Key("RECEIVERS").MustString("example@example.com"), ",", "\",\"", -1),
  1152. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  1153. case "database":
  1154. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  1155. sec.Key("DRIVER").String(),
  1156. sec.Key("CONN").String())
  1157. }
  1158. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  1159. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  1160. }
  1161. }
  1162. // NewXORMLogService initializes xorm logger service
  1163. func NewXORMLogService(disableConsole bool) {
  1164. logModes := strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  1165. var logConfigs string
  1166. for _, mode := range logModes {
  1167. mode = strings.TrimSpace(mode)
  1168. if disableConsole && mode == "console" {
  1169. continue
  1170. }
  1171. sec, err := Cfg.GetSection("log." + mode)
  1172. if err != nil {
  1173. sec, _ = Cfg.NewSection("log." + mode)
  1174. }
  1175. // Log level.
  1176. levelName := getLogLevel("log."+mode, "LEVEL", LogLevel)
  1177. level, ok := logLevels[levelName]
  1178. if !ok {
  1179. log.Fatal(4, "Unknown log level: %s", levelName)
  1180. }
  1181. // Generate log configuration.
  1182. switch mode {
  1183. case "console":
  1184. logConfigs = fmt.Sprintf(`{"level":%s}`, level)
  1185. case "file":
  1186. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "xorm.log"))
  1187. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  1188. panic(err.Error())
  1189. }
  1190. logPath = path.Join(filepath.Dir(logPath), "xorm.log")
  1191. logConfigs = fmt.Sprintf(
  1192. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  1193. logPath,
  1194. sec.Key("LOG_ROTATE").MustBool(true),
  1195. sec.Key("MAX_LINES").MustInt(1000000),
  1196. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  1197. sec.Key("DAILY_ROTATE").MustBool(true),
  1198. sec.Key("MAX_DAYS").MustInt(7))
  1199. case "conn":
  1200. logConfigs = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  1201. sec.Key("RECONNECT_ON_MSG").MustBool(),
  1202. sec.Key("RECONNECT").MustBool(),
  1203. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  1204. sec.Key("ADDR").MustString(":7020"))
  1205. case "smtp":
  1206. logConfigs = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  1207. sec.Key("USER").MustString("example@example.com"),
  1208. sec.Key("PASSWD").MustString("******"),
  1209. sec.Key("HOST").MustString("127.0.0.1:25"),
  1210. sec.Key("RECEIVERS").MustString("[]"),
  1211. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  1212. case "database":
  1213. logConfigs = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  1214. sec.Key("DRIVER").String(),
  1215. sec.Key("CONN").String())
  1216. }
  1217. log.NewXORMLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, logConfigs)
  1218. if !disableConsole {
  1219. log.Info("XORM Log Mode: %s(%s)", strings.Title(mode), levelName)
  1220. }
  1221. var lvl core.LogLevel
  1222. switch levelName {
  1223. case "Trace", "Debug":
  1224. lvl = core.LOG_DEBUG
  1225. case "Info":
  1226. lvl = core.LOG_INFO
  1227. case "Warn":
  1228. lvl = core.LOG_WARNING
  1229. case "Error", "Critical":
  1230. lvl = core.LOG_ERR
  1231. }
  1232. log.XORMLogger.SetLevel(lvl)
  1233. }
  1234. if len(logConfigs) == 0 {
  1235. log.DiscardXORMLogger()
  1236. }
  1237. }
  1238. // Cache represents cache settings
  1239. type Cache struct {
  1240. Adapter string
  1241. Interval int
  1242. Conn string
  1243. TTL time.Duration
  1244. }
  1245. var (
  1246. // CacheService the global cache
  1247. CacheService *Cache
  1248. )
  1249. func newCacheService() {
  1250. sec := Cfg.Section("cache")
  1251. CacheService = &Cache{
  1252. Adapter: sec.Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"}),
  1253. }
  1254. switch CacheService.Adapter {
  1255. case "memory":
  1256. CacheService.Interval = sec.Key("INTERVAL").MustInt(60)
  1257. case "redis", "memcache":
  1258. CacheService.Conn = strings.Trim(sec.Key("HOST").String(), "\" ")
  1259. default:
  1260. log.Fatal(4, "Unknown cache adapter: %s", CacheService.Adapter)
  1261. }
  1262. CacheService.TTL = sec.Key("ITEM_TTL").MustDuration(16 * time.Hour)
  1263. log.Info("Cache Service Enabled")
  1264. }
  1265. func newSessionService() {
  1266. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  1267. []string{"memory", "file", "redis", "mysql"})
  1268. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").MustString(path.Join(AppDataPath, "sessions")), "\" ")
  1269. if SessionConfig.Provider == "file" && !filepath.IsAbs(SessionConfig.ProviderConfig) {
  1270. SessionConfig.ProviderConfig = path.Join(AppWorkPath, SessionConfig.ProviderConfig)
  1271. }
  1272. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gitea")
  1273. SessionConfig.CookiePath = AppSubURL
  1274. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool(false)
  1275. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  1276. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  1277. log.Info("Session Service Enabled")
  1278. }
  1279. // Mailer represents mail service.
  1280. type Mailer struct {
  1281. // Mailer
  1282. QueueLength int
  1283. Name string
  1284. From string
  1285. FromName string
  1286. FromEmail string
  1287. SendAsPlainText bool
  1288. // SMTP sender
  1289. Host string
  1290. User, Passwd string
  1291. DisableHelo bool
  1292. HeloHostname string
  1293. SkipVerify bool
  1294. UseCertificate bool
  1295. CertFile, KeyFile string
  1296. // Sendmail sender
  1297. UseSendmail bool
  1298. SendmailPath string
  1299. SendmailArgs []string
  1300. }
  1301. var (
  1302. // MailService the global mailer
  1303. MailService *Mailer
  1304. )
  1305. func newMailService() {
  1306. sec := Cfg.Section("mailer")
  1307. // Check mailer setting.
  1308. if !sec.Key("ENABLED").MustBool() {
  1309. return
  1310. }
  1311. MailService = &Mailer{
  1312. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  1313. Name: sec.Key("NAME").MustString(AppName),
  1314. SendAsPlainText: sec.Key("SEND_AS_PLAIN_TEXT").MustBool(false),
  1315. Host: sec.Key("HOST").String(),
  1316. User: sec.Key("USER").String(),
  1317. Passwd: sec.Key("PASSWD").String(),
  1318. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  1319. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  1320. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  1321. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  1322. CertFile: sec.Key("CERT_FILE").String(),
  1323. KeyFile: sec.Key("KEY_FILE").String(),
  1324. UseSendmail: sec.Key("USE_SENDMAIL").MustBool(),
  1325. SendmailPath: sec.Key("SENDMAIL_PATH").MustString("sendmail"),
  1326. }
  1327. MailService.From = sec.Key("FROM").MustString(MailService.User)
  1328. if sec.HasKey("ENABLE_HTML_ALTERNATIVE") {
  1329. log.Warn("ENABLE_HTML_ALTERNATIVE is deprecated, use SEND_AS_PLAIN_TEXT")
  1330. MailService.SendAsPlainText = !sec.Key("ENABLE_HTML_ALTERNATIVE").MustBool(false)
  1331. }
  1332. parsed, err := mail.ParseAddress(MailService.From)
  1333. if err != nil {
  1334. log.Fatal(4, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  1335. }
  1336. MailService.FromName = parsed.Name
  1337. MailService.FromEmail = parsed.Address
  1338. if MailService.UseSendmail {
  1339. MailService.SendmailArgs, err = shellquote.Split(sec.Key("SENDMAIL_ARGS").String())
  1340. if err != nil {
  1341. log.Error(4, "Failed to parse Sendmail args: %v", CustomConf, err)
  1342. }
  1343. }
  1344. log.Info("Mail Service Enabled")
  1345. }
  1346. func newRegisterMailService() {
  1347. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  1348. return
  1349. } else if MailService == nil {
  1350. log.Warn("Register Mail Service: Mail Service is not enabled")
  1351. return
  1352. }
  1353. Service.RegisterEmailConfirm = true
  1354. log.Info("Register Mail Service Enabled")
  1355. }
  1356. func newNotifyMailService() {
  1357. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  1358. return
  1359. } else if MailService == nil {
  1360. log.Warn("Notify Mail Service: Mail Service is not enabled")
  1361. return
  1362. }
  1363. Service.EnableNotifyMail = true
  1364. log.Info("Notify Mail Service Enabled")
  1365. }
  1366. func newWebhookService() {
  1367. sec := Cfg.Section("webhook")
  1368. Webhook.QueueLength = sec.Key("QUEUE_LENGTH").MustInt(1000)
  1369. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  1370. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  1371. Webhook.Types = []string{"gitea", "gogs", "slack", "discord", "dingtalk"}
  1372. Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
  1373. }
  1374. // NewServices initializes the services
  1375. func NewServices() {
  1376. newService()
  1377. newLogService()
  1378. NewXORMLogService(false)
  1379. newCacheService()
  1380. newSessionService()
  1381. newMailService()
  1382. newRegisterMailService()
  1383. newNotifyMailService()
  1384. newWebhookService()
  1385. }