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