You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

setting.go 46 kB

11 years ago
11 years ago
11 years ago
11 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
9 years ago
11 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
9 years ago
11 years ago
11 years ago
11 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
9 years ago
11 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>
8 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 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
9 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 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
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
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
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
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
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
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
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
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
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
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
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 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
9 years ago
11 years ago
11 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
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
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
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
9 years ago
11 years ago
11 years ago
11 years ago
11 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>
8 years ago
11 years ago
11 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>
8 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480
  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. "crypto/rand"
  8. "encoding/base64"
  9. "fmt"
  10. "io"
  11. "net"
  12. "net/mail"
  13. "net/url"
  14. "os"
  15. "os/exec"
  16. "path"
  17. "path/filepath"
  18. "regexp"
  19. "runtime"
  20. "strconv"
  21. "strings"
  22. "time"
  23. "code.gitea.io/git"
  24. "code.gitea.io/gitea/modules/log"
  25. _ "code.gitea.io/gitea/modules/minwinsvc" // import minwinsvc for windows services
  26. "code.gitea.io/gitea/modules/user"
  27. "github.com/Unknwon/com"
  28. "github.com/dgrijalva/jwt-go"
  29. _ "github.com/go-macaron/cache/memcache" // memcache plugin for cache
  30. _ "github.com/go-macaron/cache/redis"
  31. "github.com/go-macaron/session"
  32. _ "github.com/go-macaron/session/redis" // redis plugin for store session
  33. "github.com/go-xorm/core"
  34. "github.com/kballard/go-shellquote"
  35. "gopkg.in/ini.v1"
  36. "strk.kbt.io/projects/go/libravatar"
  37. )
  38. // Scheme describes protocol types
  39. type Scheme string
  40. // enumerates all the scheme types
  41. const (
  42. HTTP Scheme = "http"
  43. HTTPS Scheme = "https"
  44. FCGI Scheme = "fcgi"
  45. UnixSocket Scheme = "unix"
  46. )
  47. // LandingPage describes the default page
  48. type LandingPage string
  49. // enumerates all the landing page types
  50. const (
  51. LandingPageHome LandingPage = "/"
  52. LandingPageExplore LandingPage = "/explore"
  53. )
  54. // settings
  55. var (
  56. // AppVer settings
  57. AppVer string
  58. AppBuiltWith string
  59. AppName string
  60. AppURL string
  61. AppSubURL string
  62. AppSubURLDepth int // Number of slashes
  63. AppPath string
  64. AppDataPath string
  65. AppWorkPath string
  66. // Server settings
  67. Protocol Scheme
  68. Domain string
  69. HTTPAddr string
  70. HTTPPort string
  71. LocalURL string
  72. OfflineMode bool
  73. DisableRouterLog bool
  74. CertFile string
  75. KeyFile string
  76. StaticRootPath string
  77. EnableGzip bool
  78. LandingPageURL LandingPage
  79. UnixSocketPermission uint32
  80. EnablePprof bool
  81. SSH = struct {
  82. Disabled bool `ini:"DISABLE_SSH"`
  83. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  84. BuiltinServerUser string `ini:"BUILTIN_SSH_SERVER_USER"`
  85. Domain string `ini:"SSH_DOMAIN"`
  86. Port int `ini:"SSH_PORT"`
  87. ListenHost string `ini:"SSH_LISTEN_HOST"`
  88. ListenPort int `ini:"SSH_LISTEN_PORT"`
  89. RootPath string `ini:"SSH_ROOT_PATH"`
  90. ServerCiphers []string `ini:"SSH_SERVER_CIPHERS"`
  91. ServerKeyExchanges []string `ini:"SSH_SERVER_KEY_EXCHANGES"`
  92. ServerMACs []string `ini:"SSH_SERVER_MACS"`
  93. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  94. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  95. AuthorizedKeysBackup bool `ini:"SSH_AUTHORIZED_KEYS_BACKUP"`
  96. MinimumKeySizeCheck bool `ini:"-"`
  97. MinimumKeySizes map[string]int `ini:"-"`
  98. ExposeAnonymous bool `ini:"SSH_EXPOSE_ANONYMOUS"`
  99. }{
  100. Disabled: false,
  101. StartBuiltinServer: false,
  102. Domain: "",
  103. Port: 22,
  104. ServerCiphers: []string{"aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com", "arcfour256", "arcfour128"},
  105. ServerKeyExchanges: []string{"diffie-hellman-group1-sha1", "diffie-hellman-group14-sha1", "ecdh-sha2-nistp256", "ecdh-sha2-nistp384", "ecdh-sha2-nistp521", "curve25519-sha256@libssh.org"},
  106. ServerMACs: []string{"hmac-sha2-256-etm@openssh.com", "hmac-sha2-256", "hmac-sha1", "hmac-sha1-96"},
  107. KeygenPath: "ssh-keygen",
  108. }
  109. LFS struct {
  110. StartServer bool `ini:"LFS_START_SERVER"`
  111. ContentPath string `ini:"LFS_CONTENT_PATH"`
  112. JWTSecretBase64 string `ini:"LFS_JWT_SECRET"`
  113. JWTSecretBytes []byte `ini:"-"`
  114. }
  115. // Security settings
  116. InstallLock bool
  117. SecretKey string
  118. LogInRememberDays int
  119. CookieUserName string
  120. CookieRememberName string
  121. ReverseProxyAuthUser string
  122. MinPasswordLength int
  123. ImportLocalPaths bool
  124. DisableGitHooks bool
  125. // Database settings
  126. UseSQLite3 bool
  127. UseMySQL bool
  128. UseMSSQL bool
  129. UsePostgreSQL bool
  130. UseTiDB bool
  131. // Indexer settings
  132. Indexer struct {
  133. IssuePath string
  134. RepoIndexerEnabled bool
  135. RepoPath string
  136. UpdateQueueLength int
  137. MaxIndexerFileSize int64
  138. }
  139. // Webhook settings
  140. Webhook = struct {
  141. QueueLength int
  142. DeliverTimeout int
  143. SkipTLSVerify bool
  144. Types []string
  145. PagingNum int
  146. }{
  147. QueueLength: 1000,
  148. DeliverTimeout: 5,
  149. SkipTLSVerify: false,
  150. PagingNum: 10,
  151. }
  152. // Repository settings
  153. Repository = struct {
  154. AnsiCharset string
  155. ForcePrivate bool
  156. MaxCreationLimit int
  157. MirrorQueueLength int
  158. PullRequestQueueLength int
  159. PreferredLicenses []string
  160. DisableHTTPGit bool
  161. UseCompatSSHURI bool
  162. // Repository editor settings
  163. Editor struct {
  164. LineWrapExtensions []string
  165. PreviewableFileModes []string
  166. } `ini:"-"`
  167. // Repository upload settings
  168. Upload struct {
  169. Enabled bool
  170. TempPath string
  171. AllowedTypes []string `delim:"|"`
  172. FileMaxSize int64
  173. MaxFiles int
  174. } `ini:"-"`
  175. // Repository local settings
  176. Local struct {
  177. LocalCopyPath string
  178. } `ini:"-"`
  179. }{
  180. AnsiCharset: "",
  181. ForcePrivate: false,
  182. MaxCreationLimit: -1,
  183. MirrorQueueLength: 1000,
  184. PullRequestQueueLength: 1000,
  185. PreferredLicenses: []string{"Apache License 2.0,MIT License"},
  186. DisableHTTPGit: false,
  187. UseCompatSSHURI: false,
  188. // Repository editor settings
  189. Editor: struct {
  190. LineWrapExtensions []string
  191. PreviewableFileModes []string
  192. }{
  193. LineWrapExtensions: strings.Split(".txt,.md,.markdown,.mdown,.mkd,", ","),
  194. PreviewableFileModes: []string{"markdown"},
  195. },
  196. // Repository upload settings
  197. Upload: struct {
  198. Enabled bool
  199. TempPath string
  200. AllowedTypes []string `delim:"|"`
  201. FileMaxSize int64
  202. MaxFiles int
  203. }{
  204. Enabled: true,
  205. TempPath: "data/tmp/uploads",
  206. AllowedTypes: []string{},
  207. FileMaxSize: 3,
  208. MaxFiles: 5,
  209. },
  210. // Repository local settings
  211. Local: struct {
  212. LocalCopyPath string
  213. }{
  214. LocalCopyPath: "tmp/local-repo",
  215. },
  216. }
  217. RepoRootPath string
  218. ScriptType = "bash"
  219. // UI settings
  220. UI = struct {
  221. ExplorePagingNum int
  222. IssuePagingNum int
  223. RepoSearchPagingNum int
  224. FeedMaxCommitNum int
  225. ThemeColorMetaTag string
  226. MaxDisplayFileSize int64
  227. ShowUserEmail bool
  228. Admin struct {
  229. UserPagingNum int
  230. RepoPagingNum int
  231. NoticePagingNum int
  232. OrgPagingNum int
  233. } `ini:"ui.admin"`
  234. User struct {
  235. RepoPagingNum int
  236. } `ini:"ui.user"`
  237. Meta struct {
  238. Author string
  239. Description string
  240. Keywords string
  241. } `ini:"ui.meta"`
  242. }{
  243. ExplorePagingNum: 20,
  244. IssuePagingNum: 10,
  245. RepoSearchPagingNum: 10,
  246. FeedMaxCommitNum: 5,
  247. ThemeColorMetaTag: `#6cc644`,
  248. MaxDisplayFileSize: 8388608,
  249. Admin: struct {
  250. UserPagingNum int
  251. RepoPagingNum int
  252. NoticePagingNum int
  253. OrgPagingNum int
  254. }{
  255. UserPagingNum: 50,
  256. RepoPagingNum: 50,
  257. NoticePagingNum: 25,
  258. OrgPagingNum: 50,
  259. },
  260. User: struct {
  261. RepoPagingNum int
  262. }{
  263. RepoPagingNum: 15,
  264. },
  265. Meta: struct {
  266. Author string
  267. Description string
  268. Keywords string
  269. }{
  270. Author: "Gitea - Git with a cup of tea",
  271. Description: "Gitea (Git with a cup of tea) is a painless self-hosted Git service written in Go",
  272. Keywords: "go,git,self-hosted,gitea",
  273. },
  274. }
  275. // Markdown settings
  276. Markdown = struct {
  277. EnableHardLineBreak bool
  278. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  279. FileExtensions []string
  280. }{
  281. EnableHardLineBreak: false,
  282. FileExtensions: strings.Split(".md,.markdown,.mdown,.mkd", ","),
  283. }
  284. // Admin settings
  285. Admin struct {
  286. DisableRegularOrgCreation bool
  287. }
  288. // Picture settings
  289. AvatarUploadPath string
  290. GravatarSource string
  291. DisableGravatar bool
  292. EnableFederatedAvatar bool
  293. LibravatarService *libravatar.Libravatar
  294. // Log settings
  295. LogRootPath string
  296. LogModes []string
  297. LogConfigs []string
  298. // Attachment settings
  299. AttachmentPath string
  300. AttachmentAllowedTypes string
  301. AttachmentMaxSize int64
  302. AttachmentMaxFiles int
  303. AttachmentEnabled bool
  304. // Time settings
  305. TimeFormat string
  306. // Session settings
  307. SessionConfig session.Options
  308. CSRFCookieName = "_csrf"
  309. // Cron tasks
  310. Cron = struct {
  311. UpdateMirror struct {
  312. Enabled bool
  313. RunAtStart bool
  314. Schedule string
  315. } `ini:"cron.update_mirrors"`
  316. RepoHealthCheck struct {
  317. Enabled bool
  318. RunAtStart bool
  319. Schedule string
  320. Timeout time.Duration
  321. Args []string `delim:" "`
  322. } `ini:"cron.repo_health_check"`
  323. CheckRepoStats struct {
  324. Enabled bool
  325. RunAtStart bool
  326. Schedule string
  327. } `ini:"cron.check_repo_stats"`
  328. ArchiveCleanup struct {
  329. Enabled bool
  330. RunAtStart bool
  331. Schedule string
  332. OlderThan time.Duration
  333. } `ini:"cron.archive_cleanup"`
  334. SyncExternalUsers struct {
  335. Enabled bool
  336. RunAtStart bool
  337. Schedule string
  338. UpdateExisting bool
  339. } `ini:"cron.sync_external_users"`
  340. DeletedBranchesCleanup struct {
  341. Enabled bool
  342. RunAtStart bool
  343. Schedule string
  344. OlderThan time.Duration
  345. } `ini:"cron.deleted_branches_cleanup"`
  346. }{
  347. UpdateMirror: struct {
  348. Enabled bool
  349. RunAtStart bool
  350. Schedule string
  351. }{
  352. Enabled: true,
  353. RunAtStart: false,
  354. Schedule: "@every 10m",
  355. },
  356. RepoHealthCheck: struct {
  357. Enabled bool
  358. RunAtStart bool
  359. Schedule string
  360. Timeout time.Duration
  361. Args []string `delim:" "`
  362. }{
  363. Enabled: true,
  364. RunAtStart: false,
  365. Schedule: "@every 24h",
  366. Timeout: 60 * time.Second,
  367. Args: []string{},
  368. },
  369. CheckRepoStats: struct {
  370. Enabled bool
  371. RunAtStart bool
  372. Schedule string
  373. }{
  374. Enabled: true,
  375. RunAtStart: true,
  376. Schedule: "@every 24h",
  377. },
  378. ArchiveCleanup: struct {
  379. Enabled bool
  380. RunAtStart bool
  381. Schedule string
  382. OlderThan time.Duration
  383. }{
  384. Enabled: true,
  385. RunAtStart: true,
  386. Schedule: "@every 24h",
  387. OlderThan: 24 * time.Hour,
  388. },
  389. SyncExternalUsers: struct {
  390. Enabled bool
  391. RunAtStart bool
  392. Schedule string
  393. UpdateExisting bool
  394. }{
  395. Enabled: true,
  396. RunAtStart: false,
  397. Schedule: "@every 24h",
  398. UpdateExisting: true,
  399. },
  400. DeletedBranchesCleanup: struct {
  401. Enabled bool
  402. RunAtStart bool
  403. Schedule string
  404. OlderThan time.Duration
  405. }{
  406. Enabled: true,
  407. RunAtStart: true,
  408. Schedule: "@every 24h",
  409. OlderThan: 24 * time.Hour,
  410. },
  411. }
  412. // Git settings
  413. Git = struct {
  414. Version string `ini:"-"`
  415. DisableDiffHighlight bool
  416. MaxGitDiffLines int
  417. MaxGitDiffLineCharacters int
  418. MaxGitDiffFiles int
  419. GCArgs []string `delim:" "`
  420. Timeout struct {
  421. Migrate int
  422. Mirror int
  423. Clone int
  424. Pull int
  425. GC int `ini:"GC"`
  426. } `ini:"git.timeout"`
  427. }{
  428. DisableDiffHighlight: false,
  429. MaxGitDiffLines: 1000,
  430. MaxGitDiffLineCharacters: 5000,
  431. MaxGitDiffFiles: 100,
  432. GCArgs: []string{},
  433. Timeout: struct {
  434. Migrate int
  435. Mirror int
  436. Clone int
  437. Pull int
  438. GC int `ini:"GC"`
  439. }{
  440. Migrate: 600,
  441. Mirror: 300,
  442. Clone: 300,
  443. Pull: 300,
  444. GC: 60,
  445. },
  446. }
  447. // Mirror settings
  448. Mirror struct {
  449. DefaultInterval time.Duration
  450. MinInterval time.Duration
  451. }
  452. // API settings
  453. API = struct {
  454. MaxResponseItems int
  455. }{
  456. MaxResponseItems: 50,
  457. }
  458. // I18n settings
  459. Langs []string
  460. Names []string
  461. dateLangs map[string]string
  462. // Highlight settings are loaded in modules/template/highlight.go
  463. // Other settings
  464. ShowFooterBranding bool
  465. ShowFooterVersion bool
  466. ShowFooterTemplateLoadTime bool
  467. // Global setting objects
  468. Cfg *ini.File
  469. CustomPath string // Custom directory path
  470. CustomConf string
  471. CustomPID string
  472. ProdMode bool
  473. RunUser string
  474. IsWindows bool
  475. HasRobotsTxt bool
  476. InternalToken string // internal access token
  477. IterateBufferSize int
  478. )
  479. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  480. func DateLang(lang string) string {
  481. name, ok := dateLangs[lang]
  482. if ok {
  483. return name
  484. }
  485. return "en"
  486. }
  487. func getAppPath() (string, error) {
  488. var appPath string
  489. var err error
  490. if IsWindows && filepath.IsAbs(os.Args[0]) {
  491. appPath = filepath.Clean(os.Args[0])
  492. } else {
  493. appPath, err = exec.LookPath(os.Args[0])
  494. }
  495. if err != nil {
  496. return "", err
  497. }
  498. appPath, err = filepath.Abs(appPath)
  499. if err != nil {
  500. return "", err
  501. }
  502. // Note: we don't use path.Dir here because it does not handle case
  503. // which path starts with two "/" in Windows: "//psf/Home/..."
  504. return strings.Replace(appPath, "\\", "/", -1), err
  505. }
  506. func getWorkPath(appPath string) string {
  507. workPath := ""
  508. giteaWorkPath := os.Getenv("GITEA_WORK_DIR")
  509. gogsWorkPath := os.Getenv("GOGS_WORK_DIR")
  510. if len(giteaWorkPath) > 0 {
  511. workPath = giteaWorkPath
  512. } else if len(gogsWorkPath) > 0 {
  513. log.Warn(`Usage of GOGS_WORK_DIR is deprecated and will be *removed* in a future release, please consider changing to GITEA_WORK_DIR`)
  514. workPath = gogsWorkPath
  515. } else {
  516. i := strings.LastIndex(appPath, "/")
  517. if i == -1 {
  518. workPath = appPath
  519. } else {
  520. workPath = appPath[:i]
  521. }
  522. }
  523. return strings.Replace(workPath, "\\", "/", -1)
  524. }
  525. func init() {
  526. IsWindows = runtime.GOOS == "windows"
  527. log.NewLogger(0, "console", `{"level": 0}`)
  528. var err error
  529. if AppPath, err = getAppPath(); err != nil {
  530. log.Fatal(4, "Failed to get app path: %v", err)
  531. }
  532. AppWorkPath = getWorkPath(AppPath)
  533. }
  534. func forcePathSeparator(path string) {
  535. if strings.Contains(path, "\\") {
  536. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  537. }
  538. }
  539. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  540. // actual user that runs the app. The first return value is the actual user name.
  541. // This check is ignored under Windows since SSH remote login is not the main
  542. // method to login on Windows.
  543. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  544. if IsWindows {
  545. return "", true
  546. }
  547. currentUser := user.CurrentUsername()
  548. return currentUser, runUser == currentUser
  549. }
  550. func createPIDFile(pidPath string) {
  551. currentPid := os.Getpid()
  552. if err := os.MkdirAll(filepath.Dir(pidPath), os.ModePerm); err != nil {
  553. log.Fatal(4, "Failed to create PID folder: %v", err)
  554. }
  555. file, err := os.Create(pidPath)
  556. if err != nil {
  557. log.Fatal(4, "Failed to create PID file: %v", err)
  558. }
  559. defer file.Close()
  560. if _, err := file.WriteString(strconv.FormatInt(int64(currentPid), 10)); err != nil {
  561. log.Fatal(4, "Failed to write PID information: %v", err)
  562. }
  563. }
  564. // NewContext initializes configuration context.
  565. // NOTE: do not print any log except error.
  566. func NewContext() {
  567. Cfg = ini.Empty()
  568. CustomPath = os.Getenv("GITEA_CUSTOM")
  569. if len(CustomPath) == 0 {
  570. CustomPath = path.Join(AppWorkPath, "custom")
  571. } else if !filepath.IsAbs(CustomPath) {
  572. CustomPath = path.Join(AppWorkPath, CustomPath)
  573. }
  574. if len(CustomPID) > 0 {
  575. createPIDFile(CustomPID)
  576. }
  577. if len(CustomConf) == 0 {
  578. CustomConf = path.Join(CustomPath, "conf/app.ini")
  579. } else if !filepath.IsAbs(CustomConf) {
  580. CustomConf = path.Join(CustomPath, CustomConf)
  581. }
  582. if com.IsFile(CustomConf) {
  583. if err := Cfg.Append(CustomConf); err != nil {
  584. log.Fatal(4, "Failed to load custom conf '%s': %v", CustomConf, err)
  585. }
  586. } else {
  587. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  588. }
  589. Cfg.NameMapper = ini.AllCapsUnderscore
  590. homeDir, err := com.HomeDir()
  591. if err != nil {
  592. log.Fatal(4, "Failed to get home directory: %v", err)
  593. }
  594. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  595. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(AppWorkPath, "log"))
  596. forcePathSeparator(LogRootPath)
  597. sec := Cfg.Section("server")
  598. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gitea: Git with a cup of tea")
  599. Protocol = HTTP
  600. if sec.Key("PROTOCOL").String() == "https" {
  601. Protocol = HTTPS
  602. CertFile = sec.Key("CERT_FILE").String()
  603. KeyFile = sec.Key("KEY_FILE").String()
  604. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  605. Protocol = FCGI
  606. } else if sec.Key("PROTOCOL").String() == "unix" {
  607. Protocol = UnixSocket
  608. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  609. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  610. if err != nil || UnixSocketPermissionParsed > 0777 {
  611. log.Fatal(4, "Failed to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  612. }
  613. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  614. }
  615. Domain = sec.Key("DOMAIN").MustString("localhost")
  616. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  617. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  618. defaultAppURL := string(Protocol) + "://" + Domain
  619. if (Protocol == HTTP && HTTPPort != "80") || (Protocol == HTTPS && HTTPPort != "443") {
  620. defaultAppURL += ":" + HTTPPort
  621. }
  622. AppURL = sec.Key("ROOT_URL").MustString(defaultAppURL)
  623. AppURL = strings.TrimRight(AppURL, "/") + "/"
  624. // Check if has app suburl.
  625. url, err := url.Parse(AppURL)
  626. if err != nil {
  627. log.Fatal(4, "Invalid ROOT_URL '%s': %s", AppURL, err)
  628. }
  629. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  630. // This value is empty if site does not have sub-url.
  631. AppSubURL = strings.TrimSuffix(url.Path, "/")
  632. AppSubURLDepth = strings.Count(AppSubURL, "/")
  633. // Check if Domain differs from AppURL domain than update it to AppURL's domain
  634. // TODO: Can be replaced with url.Hostname() when minimal GoLang version is 1.8
  635. urlHostname := strings.SplitN(url.Host, ":", 2)[0]
  636. if urlHostname != Domain && net.ParseIP(urlHostname) == nil {
  637. Domain = urlHostname
  638. }
  639. var defaultLocalURL string
  640. switch Protocol {
  641. case UnixSocket:
  642. defaultLocalURL = "http://unix/"
  643. case FCGI:
  644. defaultLocalURL = AppURL
  645. default:
  646. defaultLocalURL = string(Protocol) + "://"
  647. if HTTPAddr == "0.0.0.0" {
  648. defaultLocalURL += "localhost"
  649. } else {
  650. defaultLocalURL += HTTPAddr
  651. }
  652. defaultLocalURL += ":" + HTTPPort + "/"
  653. }
  654. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(defaultLocalURL)
  655. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  656. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  657. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(AppWorkPath)
  658. AppDataPath = sec.Key("APP_DATA_PATH").MustString(path.Join(AppWorkPath, "data"))
  659. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  660. EnablePprof = sec.Key("ENABLE_PPROF").MustBool(false)
  661. switch sec.Key("LANDING_PAGE").MustString("home") {
  662. case "explore":
  663. LandingPageURL = LandingPageExplore
  664. default:
  665. LandingPageURL = LandingPageHome
  666. }
  667. if len(SSH.Domain) == 0 {
  668. SSH.Domain = Domain
  669. }
  670. SSH.RootPath = path.Join(homeDir, ".ssh")
  671. serverCiphers := sec.Key("SSH_SERVER_CIPHERS").Strings(",")
  672. if len(serverCiphers) > 0 {
  673. SSH.ServerCiphers = serverCiphers
  674. }
  675. serverKeyExchanges := sec.Key("SSH_SERVER_KEY_EXCHANGES").Strings(",")
  676. if len(serverKeyExchanges) > 0 {
  677. SSH.ServerKeyExchanges = serverKeyExchanges
  678. }
  679. serverMACs := sec.Key("SSH_SERVER_MACS").Strings(",")
  680. if len(serverMACs) > 0 {
  681. SSH.ServerMACs = serverMACs
  682. }
  683. SSH.KeyTestPath = os.TempDir()
  684. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  685. log.Fatal(4, "Failed to map SSH settings: %v", err)
  686. }
  687. SSH.KeygenPath = sec.Key("SSH_KEYGEN_PATH").MustString("ssh-keygen")
  688. SSH.Port = sec.Key("SSH_PORT").MustInt(22)
  689. SSH.ListenPort = sec.Key("SSH_LISTEN_PORT").MustInt(SSH.Port)
  690. // When disable SSH, start builtin server value is ignored.
  691. if SSH.Disabled {
  692. SSH.StartBuiltinServer = false
  693. }
  694. if !SSH.Disabled && !SSH.StartBuiltinServer {
  695. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  696. log.Fatal(4, "Failed to create '%s': %v", SSH.RootPath, err)
  697. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  698. log.Fatal(4, "Failed to create '%s': %v", SSH.KeyTestPath, err)
  699. }
  700. }
  701. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool()
  702. SSH.MinimumKeySizes = map[string]int{}
  703. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  704. for _, key := range minimumKeySizes {
  705. if key.MustInt() != -1 {
  706. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  707. }
  708. }
  709. SSH.AuthorizedKeysBackup = sec.Key("SSH_AUTHORIZED_KEYS_BACKUP").MustBool(true)
  710. SSH.ExposeAnonymous = sec.Key("SSH_EXPOSE_ANONYMOUS").MustBool(false)
  711. sec = Cfg.Section("server")
  712. if err = sec.MapTo(&LFS); err != nil {
  713. log.Fatal(4, "Failed to map LFS settings: %v", err)
  714. }
  715. LFS.ContentPath = sec.Key("LFS_CONTENT_PATH").MustString(filepath.Join(AppDataPath, "lfs"))
  716. if !filepath.IsAbs(LFS.ContentPath) {
  717. LFS.ContentPath = filepath.Join(AppWorkPath, LFS.ContentPath)
  718. }
  719. if LFS.StartServer {
  720. if err := os.MkdirAll(LFS.ContentPath, 0700); err != nil {
  721. log.Fatal(4, "Failed to create '%s': %v", LFS.ContentPath, err)
  722. }
  723. LFS.JWTSecretBytes = make([]byte, 32)
  724. n, err := base64.RawURLEncoding.Decode(LFS.JWTSecretBytes, []byte(LFS.JWTSecretBase64))
  725. if err != nil || n != 32 {
  726. //Generate new secret and save to config
  727. _, err := io.ReadFull(rand.Reader, LFS.JWTSecretBytes)
  728. if err != nil {
  729. log.Fatal(4, "Error reading random bytes: %v", err)
  730. }
  731. LFS.JWTSecretBase64 = base64.RawURLEncoding.EncodeToString(LFS.JWTSecretBytes)
  732. // Save secret
  733. cfg := ini.Empty()
  734. if com.IsFile(CustomConf) {
  735. // Keeps custom settings if there is already something.
  736. if err := cfg.Append(CustomConf); err != nil {
  737. log.Error(4, "Failed to load custom conf '%s': %v", CustomConf, err)
  738. }
  739. }
  740. cfg.Section("server").Key("LFS_JWT_SECRET").SetValue(LFS.JWTSecretBase64)
  741. if err := os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm); err != nil {
  742. log.Fatal(4, "Failed to create '%s': %v", CustomConf, err)
  743. }
  744. if err := cfg.SaveTo(CustomConf); err != nil {
  745. log.Fatal(4, "Error saving generated JWT Secret to custom config: %v", err)
  746. return
  747. }
  748. }
  749. //Disable LFS client hooks if installed for the current OS user
  750. //Needs at least git v2.1.2
  751. binVersion, err := git.BinVersion()
  752. if err != nil {
  753. log.Fatal(4, "Error retrieving git version: %v", err)
  754. }
  755. splitVersion := strings.SplitN(binVersion, ".", 4)
  756. majorVersion, err := strconv.ParseUint(splitVersion[0], 10, 64)
  757. if err != nil {
  758. log.Fatal(4, "Error parsing git major version: %v", err)
  759. }
  760. minorVersion, err := strconv.ParseUint(splitVersion[1], 10, 64)
  761. if err != nil {
  762. log.Fatal(4, "Error parsing git minor version: %v", err)
  763. }
  764. revisionVersion, err := strconv.ParseUint(splitVersion[2], 10, 64)
  765. if err != nil {
  766. log.Fatal(4, "Error parsing git revision version: %v", err)
  767. }
  768. if !((majorVersion > 2) || (majorVersion == 2 && minorVersion > 1) ||
  769. (majorVersion == 2 && minorVersion == 1 && revisionVersion >= 2)) {
  770. LFS.StartServer = false
  771. log.Error(4, "LFS server support needs at least Git v2.1.2")
  772. } else {
  773. git.GlobalCommandArgs = append(git.GlobalCommandArgs, "-c", "filter.lfs.required=",
  774. "-c", "filter.lfs.smudge=", "-c", "filter.lfs.clean=")
  775. }
  776. }
  777. sec = Cfg.Section("security")
  778. InstallLock = sec.Key("INSTALL_LOCK").MustBool(false)
  779. SecretKey = sec.Key("SECRET_KEY").MustString("!#@FDEWREWR&*(")
  780. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt(7)
  781. CookieUserName = sec.Key("COOKIE_USERNAME").MustString("gitea_awesome")
  782. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").MustString("gitea_incredible")
  783. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  784. MinPasswordLength = sec.Key("MIN_PASSWORD_LENGTH").MustInt(6)
  785. ImportLocalPaths = sec.Key("IMPORT_LOCAL_PATHS").MustBool(false)
  786. DisableGitHooks = sec.Key("DISABLE_GIT_HOOKS").MustBool(false)
  787. InternalToken = sec.Key("INTERNAL_TOKEN").String()
  788. if len(InternalToken) == 0 {
  789. secretBytes := make([]byte, 32)
  790. _, err := io.ReadFull(rand.Reader, secretBytes)
  791. if err != nil {
  792. log.Fatal(4, "Error reading random bytes: %v", err)
  793. }
  794. secretKey := base64.RawURLEncoding.EncodeToString(secretBytes)
  795. now := time.Now()
  796. InternalToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
  797. "nbf": now.Unix(),
  798. }).SignedString([]byte(secretKey))
  799. if err != nil {
  800. log.Fatal(4, "Error generate internal token: %v", err)
  801. }
  802. // Save secret
  803. cfgSave := ini.Empty()
  804. if com.IsFile(CustomConf) {
  805. // Keeps custom settings if there is already something.
  806. if err := cfgSave.Append(CustomConf); err != nil {
  807. log.Error(4, "Failed to load custom conf '%s': %v", CustomConf, err)
  808. }
  809. }
  810. cfgSave.Section("security").Key("INTERNAL_TOKEN").SetValue(InternalToken)
  811. if err := os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm); err != nil {
  812. log.Fatal(4, "Failed to create '%s': %v", CustomConf, err)
  813. }
  814. if err := cfgSave.SaveTo(CustomConf); err != nil {
  815. log.Fatal(4, "Error saving generated JWT Secret to custom config: %v", err)
  816. }
  817. }
  818. IterateBufferSize = Cfg.Section("database").Key("ITERATE_BUFFER_SIZE").MustInt(50)
  819. sec = Cfg.Section("attachment")
  820. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  821. if !filepath.IsAbs(AttachmentPath) {
  822. AttachmentPath = path.Join(AppWorkPath, AttachmentPath)
  823. }
  824. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png,application/zip,application/gzip"), "|", ",", -1)
  825. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  826. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  827. AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
  828. TimeFormatKey := Cfg.Section("time").Key("FORMAT").MustString("RFC1123")
  829. TimeFormat = map[string]string{
  830. "ANSIC": time.ANSIC,
  831. "UnixDate": time.UnixDate,
  832. "RubyDate": time.RubyDate,
  833. "RFC822": time.RFC822,
  834. "RFC822Z": time.RFC822Z,
  835. "RFC850": time.RFC850,
  836. "RFC1123": time.RFC1123,
  837. "RFC1123Z": time.RFC1123Z,
  838. "RFC3339": time.RFC3339,
  839. "RFC3339Nano": time.RFC3339Nano,
  840. "Kitchen": time.Kitchen,
  841. "Stamp": time.Stamp,
  842. "StampMilli": time.StampMilli,
  843. "StampMicro": time.StampMicro,
  844. "StampNano": time.StampNano,
  845. }[TimeFormatKey]
  846. // When the TimeFormatKey does not exist in the previous map e.g.'2006-01-02 15:04:05'
  847. if len(TimeFormat) == 0 {
  848. TimeFormat = TimeFormatKey
  849. TestTimeFormat, _ := time.Parse(TimeFormat, TimeFormat)
  850. if TestTimeFormat.Format(time.RFC3339) != "2006-01-02T15:04:05Z" {
  851. log.Fatal(4, "Can't create time properly, please check your time format has 2006, 01, 02, 15, 04 and 05")
  852. }
  853. log.Trace("Custom TimeFormat: %s", TimeFormat)
  854. }
  855. RunUser = Cfg.Section("").Key("RUN_USER").MustString(user.CurrentUsername())
  856. // Does not check run user when the install lock is off.
  857. if InstallLock {
  858. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  859. if !match {
  860. log.Fatal(4, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  861. }
  862. }
  863. SSH.BuiltinServerUser = Cfg.Section("server").Key("BUILTIN_SSH_SERVER_USER").MustString(RunUser)
  864. // Determine and create root git repository path.
  865. sec = Cfg.Section("repository")
  866. Repository.DisableHTTPGit = sec.Key("DISABLE_HTTP_GIT").MustBool()
  867. Repository.UseCompatSSHURI = sec.Key("USE_COMPAT_SSH_URI").MustBool()
  868. Repository.MaxCreationLimit = sec.Key("MAX_CREATION_LIMIT").MustInt(-1)
  869. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gitea-repositories"))
  870. forcePathSeparator(RepoRootPath)
  871. if !filepath.IsAbs(RepoRootPath) {
  872. RepoRootPath = path.Join(AppWorkPath, RepoRootPath)
  873. } else {
  874. RepoRootPath = path.Clean(RepoRootPath)
  875. }
  876. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  877. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  878. log.Fatal(4, "Failed to map Repository settings: %v", err)
  879. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  880. log.Fatal(4, "Failed to map Repository.Editor settings: %v", err)
  881. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  882. log.Fatal(4, "Failed to map Repository.Upload settings: %v", err)
  883. } else if err = Cfg.Section("repository.local").MapTo(&Repository.Local); err != nil {
  884. log.Fatal(4, "Failed to map Repository.Local settings: %v", err)
  885. }
  886. if !filepath.IsAbs(Repository.Upload.TempPath) {
  887. Repository.Upload.TempPath = path.Join(AppWorkPath, Repository.Upload.TempPath)
  888. }
  889. sec = Cfg.Section("picture")
  890. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  891. forcePathSeparator(AvatarUploadPath)
  892. if !filepath.IsAbs(AvatarUploadPath) {
  893. AvatarUploadPath = path.Join(AppWorkPath, AvatarUploadPath)
  894. }
  895. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  896. case "duoshuo":
  897. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  898. case "gravatar":
  899. GravatarSource = "https://secure.gravatar.com/avatar/"
  900. case "libravatar":
  901. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  902. default:
  903. GravatarSource = source
  904. }
  905. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  906. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool()
  907. if OfflineMode {
  908. DisableGravatar = true
  909. EnableFederatedAvatar = false
  910. }
  911. if DisableGravatar {
  912. EnableFederatedAvatar = false
  913. }
  914. if EnableFederatedAvatar {
  915. LibravatarService = libravatar.New()
  916. parts := strings.Split(GravatarSource, "/")
  917. if len(parts) >= 3 {
  918. if parts[0] == "https:" {
  919. LibravatarService.SetUseHTTPS(true)
  920. LibravatarService.SetSecureFallbackHost(parts[2])
  921. } else {
  922. LibravatarService.SetUseHTTPS(false)
  923. LibravatarService.SetFallbackHost(parts[2])
  924. }
  925. }
  926. }
  927. if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  928. log.Fatal(4, "Failed to map UI settings: %v", err)
  929. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  930. log.Fatal(4, "Failed to map Markdown settings: %v", err)
  931. } else if err = Cfg.Section("admin").MapTo(&Admin); err != nil {
  932. log.Fatal(4, "Fail to map Admin settings: %v", err)
  933. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  934. log.Fatal(4, "Failed to map Cron settings: %v", err)
  935. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  936. log.Fatal(4, "Failed to map Git settings: %v", err)
  937. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  938. log.Fatal(4, "Failed to map API settings: %v", err)
  939. }
  940. sec = Cfg.Section("mirror")
  941. Mirror.MinInterval = sec.Key("MIN_INTERVAL").MustDuration(10 * time.Minute)
  942. Mirror.DefaultInterval = sec.Key("DEFAULT_INTERVAL").MustDuration(8 * time.Hour)
  943. if Mirror.MinInterval.Minutes() < 1 {
  944. log.Warn("Mirror.MinInterval is too low")
  945. Mirror.MinInterval = 1 * time.Minute
  946. }
  947. if Mirror.DefaultInterval < Mirror.MinInterval {
  948. log.Warn("Mirror.DefaultInterval is less than Mirror.MinInterval")
  949. Mirror.DefaultInterval = time.Hour * 8
  950. }
  951. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  952. if len(Langs) == 0 {
  953. Langs = defaultLangs
  954. }
  955. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  956. if len(Names) == 0 {
  957. Names = defaultLangNames
  958. }
  959. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  960. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool(false)
  961. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool(true)
  962. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool(true)
  963. UI.ShowUserEmail = Cfg.Section("ui").Key("SHOW_USER_EMAIL").MustBool(true)
  964. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  965. }
  966. // Service settings
  967. var Service struct {
  968. ActiveCodeLives int
  969. ResetPwdCodeLives int
  970. RegisterEmailConfirm bool
  971. DisableRegistration bool
  972. ShowRegistrationButton bool
  973. RequireSignInView bool
  974. EnableNotifyMail bool
  975. EnableReverseProxyAuth bool
  976. EnableReverseProxyAutoRegister bool
  977. EnableCaptcha bool
  978. DefaultKeepEmailPrivate bool
  979. DefaultAllowCreateOrganization bool
  980. DefaultEnableTimetracking bool
  981. DefaultAllowOnlyContributorsToTrackTime bool
  982. NoReplyAddress string
  983. // OpenID settings
  984. EnableOpenIDSignIn bool
  985. EnableOpenIDSignUp bool
  986. OpenIDWhitelist []*regexp.Regexp
  987. OpenIDBlacklist []*regexp.Regexp
  988. }
  989. func newService() {
  990. sec := Cfg.Section("service")
  991. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  992. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  993. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  994. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  995. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  996. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  997. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  998. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  999. Service.DefaultKeepEmailPrivate = sec.Key("DEFAULT_KEEP_EMAIL_PRIVATE").MustBool()
  1000. Service.DefaultAllowCreateOrganization = sec.Key("DEFAULT_ALLOW_CREATE_ORGANIZATION").MustBool(true)
  1001. Service.DefaultEnableTimetracking = sec.Key("DEFAULT_ENABLE_TIMETRACKING").MustBool(true)
  1002. Service.DefaultAllowOnlyContributorsToTrackTime = sec.Key("DEFAULT_ALLOW_ONLY_CONTRIBUTORS_TO_TRACK_TIME").MustBool(true)
  1003. Service.NoReplyAddress = sec.Key("NO_REPLY_ADDRESS").MustString("noreply.example.org")
  1004. sec = Cfg.Section("openid")
  1005. Service.EnableOpenIDSignIn = sec.Key("ENABLE_OPENID_SIGNIN").MustBool(false)
  1006. Service.EnableOpenIDSignUp = sec.Key("ENABLE_OPENID_SIGNUP").MustBool(!Service.DisableRegistration && Service.EnableOpenIDSignIn)
  1007. pats := sec.Key("WHITELISTED_URIS").Strings(" ")
  1008. if len(pats) != 0 {
  1009. Service.OpenIDWhitelist = make([]*regexp.Regexp, len(pats))
  1010. for i, p := range pats {
  1011. Service.OpenIDWhitelist[i] = regexp.MustCompilePOSIX(p)
  1012. }
  1013. }
  1014. pats = sec.Key("BLACKLISTED_URIS").Strings(" ")
  1015. if len(pats) != 0 {
  1016. Service.OpenIDBlacklist = make([]*regexp.Regexp, len(pats))
  1017. for i, p := range pats {
  1018. Service.OpenIDBlacklist[i] = regexp.MustCompilePOSIX(p)
  1019. }
  1020. }
  1021. }
  1022. var logLevels = map[string]string{
  1023. "Trace": "0",
  1024. "Debug": "1",
  1025. "Info": "2",
  1026. "Warn": "3",
  1027. "Error": "4",
  1028. "Critical": "5",
  1029. }
  1030. func newLogService() {
  1031. log.Info("Gitea v%s%s", AppVer, AppBuiltWith)
  1032. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  1033. LogConfigs = make([]string, len(LogModes))
  1034. useConsole := false
  1035. for i := 0; i < len(LogModes); i++ {
  1036. LogModes[i] = strings.TrimSpace(LogModes[i])
  1037. if LogModes[i] == "console" {
  1038. useConsole = true
  1039. }
  1040. }
  1041. if !useConsole {
  1042. log.DelLogger("console")
  1043. }
  1044. for i, mode := range LogModes {
  1045. sec, err := Cfg.GetSection("log." + mode)
  1046. if err != nil {
  1047. sec, _ = Cfg.NewSection("log." + mode)
  1048. }
  1049. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  1050. // Log level.
  1051. levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
  1052. Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
  1053. validLevels)
  1054. level, ok := logLevels[levelName]
  1055. if !ok {
  1056. log.Fatal(4, "Unknown log level: %s", levelName)
  1057. }
  1058. // Generate log configuration.
  1059. switch mode {
  1060. case "console":
  1061. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  1062. case "file":
  1063. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gitea.log"))
  1064. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  1065. panic(err.Error())
  1066. }
  1067. LogConfigs[i] = fmt.Sprintf(
  1068. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  1069. logPath,
  1070. sec.Key("LOG_ROTATE").MustBool(true),
  1071. sec.Key("MAX_LINES").MustInt(1000000),
  1072. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  1073. sec.Key("DAILY_ROTATE").MustBool(true),
  1074. sec.Key("MAX_DAYS").MustInt(7))
  1075. case "conn":
  1076. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  1077. sec.Key("RECONNECT_ON_MSG").MustBool(),
  1078. sec.Key("RECONNECT").MustBool(),
  1079. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  1080. sec.Key("ADDR").MustString(":7020"))
  1081. case "smtp":
  1082. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":["%s"],"subject":"%s"}`, level,
  1083. sec.Key("USER").MustString("example@example.com"),
  1084. sec.Key("PASSWD").MustString("******"),
  1085. sec.Key("HOST").MustString("127.0.0.1:25"),
  1086. strings.Replace(sec.Key("RECEIVERS").MustString("example@example.com"), ",", "\",\"", -1),
  1087. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  1088. case "database":
  1089. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  1090. sec.Key("DRIVER").String(),
  1091. sec.Key("CONN").String())
  1092. }
  1093. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  1094. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  1095. }
  1096. }
  1097. // NewXORMLogService initializes xorm logger service
  1098. func NewXORMLogService(disableConsole bool) {
  1099. logModes := strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  1100. var logConfigs string
  1101. for _, mode := range logModes {
  1102. mode = strings.TrimSpace(mode)
  1103. if disableConsole && mode == "console" {
  1104. continue
  1105. }
  1106. sec, err := Cfg.GetSection("log." + mode)
  1107. if err != nil {
  1108. sec, _ = Cfg.NewSection("log." + mode)
  1109. }
  1110. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  1111. // Log level.
  1112. levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
  1113. Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
  1114. validLevels)
  1115. level, ok := logLevels[levelName]
  1116. if !ok {
  1117. log.Fatal(4, "Unknown log level: %s", levelName)
  1118. }
  1119. // Generate log configuration.
  1120. switch mode {
  1121. case "console":
  1122. logConfigs = fmt.Sprintf(`{"level":%s}`, level)
  1123. case "file":
  1124. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "xorm.log"))
  1125. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  1126. panic(err.Error())
  1127. }
  1128. logPath = path.Join(filepath.Dir(logPath), "xorm.log")
  1129. logConfigs = fmt.Sprintf(
  1130. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  1131. logPath,
  1132. sec.Key("LOG_ROTATE").MustBool(true),
  1133. sec.Key("MAX_LINES").MustInt(1000000),
  1134. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  1135. sec.Key("DAILY_ROTATE").MustBool(true),
  1136. sec.Key("MAX_DAYS").MustInt(7))
  1137. case "conn":
  1138. logConfigs = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  1139. sec.Key("RECONNECT_ON_MSG").MustBool(),
  1140. sec.Key("RECONNECT").MustBool(),
  1141. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  1142. sec.Key("ADDR").MustString(":7020"))
  1143. case "smtp":
  1144. logConfigs = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  1145. sec.Key("USER").MustString("example@example.com"),
  1146. sec.Key("PASSWD").MustString("******"),
  1147. sec.Key("HOST").MustString("127.0.0.1:25"),
  1148. sec.Key("RECEIVERS").MustString("[]"),
  1149. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  1150. case "database":
  1151. logConfigs = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  1152. sec.Key("DRIVER").String(),
  1153. sec.Key("CONN").String())
  1154. }
  1155. log.NewXORMLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, logConfigs)
  1156. if !disableConsole {
  1157. log.Info("XORM Log Mode: %s(%s)", strings.Title(mode), levelName)
  1158. }
  1159. var lvl core.LogLevel
  1160. switch levelName {
  1161. case "Trace", "Debug":
  1162. lvl = core.LOG_DEBUG
  1163. case "Info":
  1164. lvl = core.LOG_INFO
  1165. case "Warn":
  1166. lvl = core.LOG_WARNING
  1167. case "Error", "Critical":
  1168. lvl = core.LOG_ERR
  1169. }
  1170. log.XORMLogger.SetLevel(lvl)
  1171. }
  1172. if len(logConfigs) == 0 {
  1173. log.DiscardXORMLogger()
  1174. }
  1175. }
  1176. // Cache represents cache settings
  1177. type Cache struct {
  1178. Adapter string
  1179. Interval int
  1180. Conn string
  1181. TTL time.Duration
  1182. }
  1183. var (
  1184. // CacheService the global cache
  1185. CacheService *Cache
  1186. )
  1187. func newCacheService() {
  1188. sec := Cfg.Section("cache")
  1189. CacheService = &Cache{
  1190. Adapter: sec.Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"}),
  1191. }
  1192. switch CacheService.Adapter {
  1193. case "memory":
  1194. CacheService.Interval = sec.Key("INTERVAL").MustInt(60)
  1195. case "redis", "memcache":
  1196. CacheService.Conn = strings.Trim(sec.Key("HOST").String(), "\" ")
  1197. default:
  1198. log.Fatal(4, "Unknown cache adapter: %s", CacheService.Adapter)
  1199. }
  1200. CacheService.TTL = sec.Key("ITEM_TTL").MustDuration(16 * time.Hour)
  1201. log.Info("Cache Service Enabled")
  1202. }
  1203. func newSessionService() {
  1204. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  1205. []string{"memory", "file", "redis", "mysql"})
  1206. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").MustString(path.Join(AppDataPath, "sessions")), "\" ")
  1207. if !filepath.IsAbs(SessionConfig.ProviderConfig) {
  1208. SessionConfig.ProviderConfig = path.Join(AppWorkPath, SessionConfig.ProviderConfig)
  1209. }
  1210. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gitea")
  1211. SessionConfig.CookiePath = AppSubURL
  1212. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool(false)
  1213. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  1214. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  1215. log.Info("Session Service Enabled")
  1216. }
  1217. // Mailer represents mail service.
  1218. type Mailer struct {
  1219. // Mailer
  1220. QueueLength int
  1221. Name string
  1222. From string
  1223. FromName string
  1224. FromEmail string
  1225. SendAsPlainText bool
  1226. // SMTP sender
  1227. Host string
  1228. User, Passwd string
  1229. DisableHelo bool
  1230. HeloHostname string
  1231. SkipVerify bool
  1232. UseCertificate bool
  1233. CertFile, KeyFile string
  1234. // Sendmail sender
  1235. UseSendmail bool
  1236. SendmailPath string
  1237. SendmailArgs []string
  1238. }
  1239. var (
  1240. // MailService the global mailer
  1241. MailService *Mailer
  1242. )
  1243. func newMailService() {
  1244. sec := Cfg.Section("mailer")
  1245. // Check mailer setting.
  1246. if !sec.Key("ENABLED").MustBool() {
  1247. return
  1248. }
  1249. MailService = &Mailer{
  1250. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  1251. Name: sec.Key("NAME").MustString(AppName),
  1252. SendAsPlainText: sec.Key("SEND_AS_PLAIN_TEXT").MustBool(false),
  1253. Host: sec.Key("HOST").String(),
  1254. User: sec.Key("USER").String(),
  1255. Passwd: sec.Key("PASSWD").String(),
  1256. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  1257. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  1258. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  1259. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  1260. CertFile: sec.Key("CERT_FILE").String(),
  1261. KeyFile: sec.Key("KEY_FILE").String(),
  1262. UseSendmail: sec.Key("USE_SENDMAIL").MustBool(),
  1263. SendmailPath: sec.Key("SENDMAIL_PATH").MustString("sendmail"),
  1264. }
  1265. MailService.From = sec.Key("FROM").MustString(MailService.User)
  1266. if sec.HasKey("ENABLE_HTML_ALTERNATIVE") {
  1267. log.Warn("ENABLE_HTML_ALTERNATIVE is deprecated, use SEND_AS_PLAIN_TEXT")
  1268. MailService.SendAsPlainText = !sec.Key("ENABLE_HTML_ALTERNATIVE").MustBool(false)
  1269. }
  1270. parsed, err := mail.ParseAddress(MailService.From)
  1271. if err != nil {
  1272. log.Fatal(4, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  1273. }
  1274. MailService.FromName = parsed.Name
  1275. MailService.FromEmail = parsed.Address
  1276. if MailService.UseSendmail {
  1277. MailService.SendmailArgs, err = shellquote.Split(sec.Key("SENDMAIL_ARGS").String())
  1278. if err != nil {
  1279. log.Error(4, "Failed to parse Sendmail args: %v", CustomConf, err)
  1280. }
  1281. }
  1282. log.Info("Mail Service Enabled")
  1283. }
  1284. func newRegisterMailService() {
  1285. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  1286. return
  1287. } else if MailService == nil {
  1288. log.Warn("Register Mail Service: Mail Service is not enabled")
  1289. return
  1290. }
  1291. Service.RegisterEmailConfirm = true
  1292. log.Info("Register Mail Service Enabled")
  1293. }
  1294. func newNotifyMailService() {
  1295. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  1296. return
  1297. } else if MailService == nil {
  1298. log.Warn("Notify Mail Service: Mail Service is not enabled")
  1299. return
  1300. }
  1301. Service.EnableNotifyMail = true
  1302. log.Info("Notify Mail Service Enabled")
  1303. }
  1304. func newWebhookService() {
  1305. sec := Cfg.Section("webhook")
  1306. Webhook.QueueLength = sec.Key("QUEUE_LENGTH").MustInt(1000)
  1307. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  1308. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  1309. Webhook.Types = []string{"gitea", "gogs", "slack", "discord"}
  1310. Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
  1311. }
  1312. // NewServices initializes the services
  1313. func NewServices() {
  1314. newService()
  1315. newLogService()
  1316. NewXORMLogService(false)
  1317. newCacheService()
  1318. newSessionService()
  1319. newMailService()
  1320. newRegisterMailService()
  1321. newNotifyMailService()
  1322. newWebhookService()
  1323. }