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