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