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

setting.go 47 kB

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