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