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.

convert.go 14 kB

Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
3 years ago
Add API endpoint for accessing repo topics (#7963) * Create API endpoints for repo topics. Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Generate swagger Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Add documentation to functions Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Grammar fix Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Fix function comment Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Can't use FindTopics when looking for a single repo topic, as it doesnt use exact match Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Add PUT ​/repos​/{owner}​/{repo}​/topics and remove GET ​/repos​/{owner}​/{repo}​/topics * Ignore if topic is sent twice in same request, refactoring. Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Fix topic dropdown with api changes. Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Style fix Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Update API documentation Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Better way to handle duplicate topics in slice Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Make response element TopicName an array of strings, instead of using an array of TopicName Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Add test cases for API Repo Topics. Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Fix format of tests Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Fix comments Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Fix unit tests after adding some more topics to the test fixture. Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Update models/topic.go Limit multiple if else if ... Co-Authored-By: Antoine GIRARD <sapk@users.noreply.github.com> * Engine as first parameter in function Co-Authored-By: Antoine GIRARD <sapk@users.noreply.github.com> * Replace magic numbers with http status code constants. Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Fix variable scope Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Test one read with login and one with token Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Add some more tests Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Apply suggestions from code review Use empty struct for efficiency Co-Authored-By: Lauris BH <lauris@nix.lv> * Add test case to check access for user with write access Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Fix access, repo admin required to change topics Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Correct first test to be without token Signed-off-by: David Svantesson <davidsvantesson@gmail.com> * Any repo reader should be able to access topics. * No need for string pointer Signed-off-by: David Svantesson <davidsvantesson@gmail.com>
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package convert
  5. import (
  6. "fmt"
  7. "time"
  8. "code.gitea.io/gitea/models"
  9. "code.gitea.io/gitea/modules/git"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/markup"
  12. "code.gitea.io/gitea/modules/structs"
  13. api "code.gitea.io/gitea/modules/structs"
  14. "code.gitea.io/gitea/modules/util"
  15. "code.gitea.io/gitea/modules/webhook"
  16. "github.com/unknwon/com"
  17. )
  18. // ToEmail convert models.EmailAddress to api.Email
  19. func ToEmail(email *models.EmailAddress) *api.Email {
  20. return &api.Email{
  21. Email: email.Email,
  22. Verified: email.IsActivated,
  23. Primary: email.IsPrimary,
  24. }
  25. }
  26. // ToBranch convert a git.Commit and git.Branch to an api.Branch
  27. func ToBranch(repo *models.Repository, b *git.Branch, c *git.Commit, bp *models.ProtectedBranch, user *models.User, isRepoAdmin bool) (*api.Branch, error) {
  28. if bp == nil {
  29. var hasPerm bool
  30. var err error
  31. if user != nil {
  32. hasPerm, err = models.HasAccessUnit(user, repo, models.UnitTypeCode, models.AccessModeWrite)
  33. if err != nil {
  34. return nil, err
  35. }
  36. }
  37. return &api.Branch{
  38. Name: b.Name,
  39. Commit: ToCommit(repo, c),
  40. Protected: false,
  41. RequiredApprovals: 0,
  42. EnableStatusCheck: false,
  43. StatusCheckContexts: []string{},
  44. UserCanPush: hasPerm,
  45. UserCanMerge: hasPerm,
  46. }, nil
  47. }
  48. branch := &api.Branch{
  49. Name: b.Name,
  50. Commit: ToCommit(repo, c),
  51. Protected: true,
  52. RequiredApprovals: bp.RequiredApprovals,
  53. EnableStatusCheck: bp.EnableStatusCheck,
  54. StatusCheckContexts: bp.StatusCheckContexts,
  55. }
  56. if isRepoAdmin {
  57. branch.EffectiveBranchProtectionName = bp.BranchName
  58. }
  59. if user != nil {
  60. branch.UserCanPush = bp.CanUserPush(user.ID)
  61. branch.UserCanMerge = bp.IsUserMergeWhitelisted(user.ID)
  62. }
  63. return branch, nil
  64. }
  65. // ToBranchProtection convert a ProtectedBranch to api.BranchProtection
  66. func ToBranchProtection(bp *models.ProtectedBranch) *api.BranchProtection {
  67. pushWhitelistUsernames, err := models.GetUserNamesByIDs(bp.WhitelistUserIDs)
  68. if err != nil {
  69. log.Error("GetUserNamesByIDs (WhitelistUserIDs): %v", err)
  70. }
  71. mergeWhitelistUsernames, err := models.GetUserNamesByIDs(bp.MergeWhitelistUserIDs)
  72. if err != nil {
  73. log.Error("GetUserNamesByIDs (MergeWhitelistUserIDs): %v", err)
  74. }
  75. approvalsWhitelistUsernames, err := models.GetUserNamesByIDs(bp.ApprovalsWhitelistUserIDs)
  76. if err != nil {
  77. log.Error("GetUserNamesByIDs (ApprovalsWhitelistUserIDs): %v", err)
  78. }
  79. pushWhitelistTeams, err := models.GetTeamNamesByID(bp.WhitelistTeamIDs)
  80. if err != nil {
  81. log.Error("GetTeamNamesByID (WhitelistTeamIDs): %v", err)
  82. }
  83. mergeWhitelistTeams, err := models.GetTeamNamesByID(bp.MergeWhitelistTeamIDs)
  84. if err != nil {
  85. log.Error("GetTeamNamesByID (MergeWhitelistTeamIDs): %v", err)
  86. }
  87. approvalsWhitelistTeams, err := models.GetTeamNamesByID(bp.ApprovalsWhitelistTeamIDs)
  88. if err != nil {
  89. log.Error("GetTeamNamesByID (ApprovalsWhitelistTeamIDs): %v", err)
  90. }
  91. return &api.BranchProtection{
  92. BranchName: bp.BranchName,
  93. EnablePush: bp.CanPush,
  94. EnablePushWhitelist: bp.EnableWhitelist,
  95. PushWhitelistUsernames: pushWhitelistUsernames,
  96. PushWhitelistTeams: pushWhitelistTeams,
  97. PushWhitelistDeployKeys: bp.WhitelistDeployKeys,
  98. EnableMergeWhitelist: bp.EnableMergeWhitelist,
  99. MergeWhitelistUsernames: mergeWhitelistUsernames,
  100. MergeWhitelistTeams: mergeWhitelistTeams,
  101. EnableStatusCheck: bp.EnableStatusCheck,
  102. StatusCheckContexts: bp.StatusCheckContexts,
  103. RequiredApprovals: bp.RequiredApprovals,
  104. EnableApprovalsWhitelist: bp.EnableApprovalsWhitelist,
  105. ApprovalsWhitelistUsernames: approvalsWhitelistUsernames,
  106. ApprovalsWhitelistTeams: approvalsWhitelistTeams,
  107. BlockOnRejectedReviews: bp.BlockOnRejectedReviews,
  108. BlockOnOutdatedBranch: bp.BlockOnOutdatedBranch,
  109. DismissStaleApprovals: bp.DismissStaleApprovals,
  110. RequireSignedCommits: bp.RequireSignedCommits,
  111. ProtectedFilePatterns: bp.ProtectedFilePatterns,
  112. Created: bp.CreatedUnix.AsTime(),
  113. Updated: bp.UpdatedUnix.AsTime(),
  114. }
  115. }
  116. // ToTag convert a git.Tag to an api.Tag
  117. func ToTag(repo *models.Repository, t *git.Tag) *api.Tag {
  118. return &api.Tag{
  119. Name: t.Name,
  120. ID: t.ID.String(),
  121. Commit: ToCommitMeta(repo, t),
  122. ZipballURL: util.URLJoin(repo.HTMLURL(), "archive", t.Name+".zip"),
  123. TarballURL: util.URLJoin(repo.HTMLURL(), "archive", t.Name+".tar.gz"),
  124. }
  125. }
  126. // ToCommit convert a git.Commit to api.PayloadCommit
  127. func ToCommit(repo *models.Repository, c *git.Commit) *api.PayloadCommit {
  128. authorUsername := ""
  129. if author, err := models.GetUserByEmail(c.Author.Email); err == nil {
  130. authorUsername = author.Name
  131. } else if !models.IsErrUserNotExist(err) {
  132. log.Error("GetUserByEmail: %v", err)
  133. }
  134. committerUsername := ""
  135. if committer, err := models.GetUserByEmail(c.Committer.Email); err == nil {
  136. committerUsername = committer.Name
  137. } else if !models.IsErrUserNotExist(err) {
  138. log.Error("GetUserByEmail: %v", err)
  139. }
  140. return &api.PayloadCommit{
  141. ID: c.ID.String(),
  142. Message: c.Message(),
  143. URL: util.URLJoin(repo.HTMLURL(), "commit", c.ID.String()),
  144. Author: &api.PayloadUser{
  145. Name: c.Author.Name,
  146. Email: c.Author.Email,
  147. UserName: authorUsername,
  148. },
  149. Committer: &api.PayloadUser{
  150. Name: c.Committer.Name,
  151. Email: c.Committer.Email,
  152. UserName: committerUsername,
  153. },
  154. Timestamp: c.Author.When,
  155. Verification: ToVerification(c),
  156. }
  157. }
  158. // ToVerification convert a git.Commit.Signature to an api.PayloadCommitVerification
  159. func ToVerification(c *git.Commit) *api.PayloadCommitVerification {
  160. verif := models.ParseCommitWithSignature(c)
  161. commitVerification := &api.PayloadCommitVerification{
  162. Verified: verif.Verified,
  163. Reason: verif.Reason,
  164. }
  165. if c.Signature != nil {
  166. commitVerification.Signature = c.Signature.Signature
  167. commitVerification.Payload = c.Signature.Payload
  168. }
  169. if verif.SigningUser != nil {
  170. commitVerification.Signer = &structs.PayloadUser{
  171. Name: verif.SigningUser.Name,
  172. Email: verif.SigningUser.Email,
  173. }
  174. }
  175. return commitVerification
  176. }
  177. // ToPublicKey convert models.PublicKey to api.PublicKey
  178. func ToPublicKey(apiLink string, key *models.PublicKey) *api.PublicKey {
  179. return &api.PublicKey{
  180. ID: key.ID,
  181. Key: key.Content,
  182. URL: apiLink + com.ToStr(key.ID),
  183. Title: key.Name,
  184. Fingerprint: key.Fingerprint,
  185. Created: key.CreatedUnix.AsTime(),
  186. }
  187. }
  188. // ToGPGKey converts models.GPGKey to api.GPGKey
  189. func ToGPGKey(key *models.GPGKey) *api.GPGKey {
  190. subkeys := make([]*api.GPGKey, len(key.SubsKey))
  191. for id, k := range key.SubsKey {
  192. subkeys[id] = &api.GPGKey{
  193. ID: k.ID,
  194. PrimaryKeyID: k.PrimaryKeyID,
  195. KeyID: k.KeyID,
  196. PublicKey: k.Content,
  197. Created: k.CreatedUnix.AsTime(),
  198. Expires: k.ExpiredUnix.AsTime(),
  199. CanSign: k.CanSign,
  200. CanEncryptComms: k.CanEncryptComms,
  201. CanEncryptStorage: k.CanEncryptStorage,
  202. CanCertify: k.CanSign,
  203. }
  204. }
  205. emails := make([]*api.GPGKeyEmail, len(key.Emails))
  206. for i, e := range key.Emails {
  207. emails[i] = ToGPGKeyEmail(e)
  208. }
  209. return &api.GPGKey{
  210. ID: key.ID,
  211. PrimaryKeyID: key.PrimaryKeyID,
  212. KeyID: key.KeyID,
  213. PublicKey: key.Content,
  214. Created: key.CreatedUnix.AsTime(),
  215. Expires: key.ExpiredUnix.AsTime(),
  216. Emails: emails,
  217. SubsKey: subkeys,
  218. CanSign: key.CanSign,
  219. CanEncryptComms: key.CanEncryptComms,
  220. CanEncryptStorage: key.CanEncryptStorage,
  221. CanCertify: key.CanSign,
  222. }
  223. }
  224. // ToGPGKeyEmail convert models.EmailAddress to api.GPGKeyEmail
  225. func ToGPGKeyEmail(email *models.EmailAddress) *api.GPGKeyEmail {
  226. return &api.GPGKeyEmail{
  227. Email: email.Email,
  228. Verified: email.IsActivated,
  229. }
  230. }
  231. // ToHook convert models.Webhook to api.Hook
  232. func ToHook(repoLink string, w *models.Webhook) *api.Hook {
  233. config := map[string]string{
  234. "url": w.URL,
  235. "content_type": w.ContentType.Name(),
  236. }
  237. if w.HookTaskType == models.SLACK {
  238. s := webhook.GetSlackHook(w)
  239. config["channel"] = s.Channel
  240. config["username"] = s.Username
  241. config["icon_url"] = s.IconURL
  242. config["color"] = s.Color
  243. }
  244. return &api.Hook{
  245. ID: w.ID,
  246. Type: w.HookTaskType.Name(),
  247. URL: fmt.Sprintf("%s/settings/hooks/%d", repoLink, w.ID),
  248. Active: w.IsActive,
  249. Config: config,
  250. Events: w.EventsArray(),
  251. Updated: w.UpdatedUnix.AsTime(),
  252. Created: w.CreatedUnix.AsTime(),
  253. }
  254. }
  255. // ToGitHook convert git.Hook to api.GitHook
  256. func ToGitHook(h *git.Hook) *api.GitHook {
  257. return &api.GitHook{
  258. Name: h.Name(),
  259. IsActive: h.IsActive,
  260. Content: h.Content,
  261. }
  262. }
  263. // ToDeployKey convert models.DeployKey to api.DeployKey
  264. func ToDeployKey(apiLink string, key *models.DeployKey) *api.DeployKey {
  265. return &api.DeployKey{
  266. ID: key.ID,
  267. KeyID: key.KeyID,
  268. Key: key.Content,
  269. Fingerprint: key.Fingerprint,
  270. URL: apiLink + com.ToStr(key.ID),
  271. Title: key.Name,
  272. Created: key.CreatedUnix.AsTime(),
  273. ReadOnly: key.Mode == models.AccessModeRead, // All deploy keys are read-only.
  274. }
  275. }
  276. // ToOrganization convert models.User to api.Organization
  277. func ToOrganization(org *models.User) *api.Organization {
  278. return &api.Organization{
  279. ID: org.ID,
  280. AvatarURL: org.AvatarLink(),
  281. UserName: org.Name,
  282. FullName: org.FullName,
  283. Description: org.Description,
  284. Website: org.Website,
  285. Location: org.Location,
  286. Visibility: org.Visibility.String(),
  287. RepoAdminChangeTeamAccess: org.RepoAdminChangeTeamAccess,
  288. }
  289. }
  290. // ToTeam convert models.Team to api.Team
  291. func ToTeam(team *models.Team) *api.Team {
  292. return &api.Team{
  293. ID: team.ID,
  294. Name: team.Name,
  295. Description: team.Description,
  296. IncludesAllRepositories: team.IncludesAllRepositories,
  297. CanCreateOrgRepo: team.CanCreateOrgRepo,
  298. Permission: team.Authorize.String(),
  299. Units: team.GetUnitNames(),
  300. }
  301. }
  302. // ToUser convert models.User to api.User
  303. // signed shall only be set if requester is logged in. authed shall only be set if user is site admin or user himself
  304. func ToUser(user *models.User, signed, authed bool) *api.User {
  305. result := &api.User{
  306. UserName: user.Name,
  307. AvatarURL: user.AvatarLink(),
  308. FullName: markup.Sanitize(user.FullName),
  309. Created: user.CreatedUnix.AsTime(),
  310. IsActive: user.IsActive,
  311. }
  312. // hide primary email if API caller is anonymous or user keep email private
  313. if signed && (!user.KeepEmailPrivate || authed) {
  314. result.Email = user.Email
  315. }
  316. // only site admin will get these information and possibly user himself
  317. if authed {
  318. result.ID = user.ID
  319. result.IsAdmin = user.IsAdmin
  320. result.LastLogin = user.LastLoginUnix.AsTime()
  321. result.Language = user.Language
  322. }
  323. return result
  324. }
  325. // ToAnnotatedTag convert git.Tag to api.AnnotatedTag
  326. func ToAnnotatedTag(repo *models.Repository, t *git.Tag, c *git.Commit) *api.AnnotatedTag {
  327. return &api.AnnotatedTag{
  328. Tag: t.Name,
  329. SHA: t.ID.String(),
  330. Object: ToAnnotatedTagObject(repo, c),
  331. Message: t.Message,
  332. URL: util.URLJoin(repo.APIURL(), "git/tags", t.ID.String()),
  333. Tagger: ToCommitUser(t.Tagger),
  334. Verification: ToVerification(c),
  335. }
  336. }
  337. // ToAnnotatedTagObject convert a git.Commit to an api.AnnotatedTagObject
  338. func ToAnnotatedTagObject(repo *models.Repository, commit *git.Commit) *api.AnnotatedTagObject {
  339. return &api.AnnotatedTagObject{
  340. SHA: commit.ID.String(),
  341. Type: string(git.ObjectCommit),
  342. URL: util.URLJoin(repo.APIURL(), "git/commits", commit.ID.String()),
  343. }
  344. }
  345. // ToCommitUser convert a git.Signature to an api.CommitUser
  346. func ToCommitUser(sig *git.Signature) *api.CommitUser {
  347. return &api.CommitUser{
  348. Identity: api.Identity{
  349. Name: sig.Name,
  350. Email: sig.Email,
  351. },
  352. Date: sig.When.UTC().Format(time.RFC3339),
  353. }
  354. }
  355. // ToCommitMeta convert a git.Tag to an api.CommitMeta
  356. func ToCommitMeta(repo *models.Repository, tag *git.Tag) *api.CommitMeta {
  357. return &api.CommitMeta{
  358. SHA: tag.Object.String(),
  359. URL: util.URLJoin(repo.APIURL(), "git/commits", tag.ID.String()),
  360. }
  361. }
  362. // ToTopicResponse convert from models.Topic to api.TopicResponse
  363. func ToTopicResponse(topic *models.Topic) *api.TopicResponse {
  364. return &api.TopicResponse{
  365. ID: topic.ID,
  366. Name: topic.Name,
  367. RepoCount: topic.RepoCount,
  368. Created: topic.CreatedUnix.AsTime(),
  369. Updated: topic.UpdatedUnix.AsTime(),
  370. }
  371. }
  372. func ToImageTopicResponse(topic *models.ImageTopic) *api.ImageTopicResponse {
  373. return &api.ImageTopicResponse{
  374. ID: topic.ID,
  375. Name: topic.Name,
  376. ImageCount: topic.ImageCount,
  377. Created: topic.CreatedUnix.AsTime(),
  378. Updated: topic.UpdatedUnix.AsTime(),
  379. }
  380. }
  381. // ToOAuth2Application convert from models.OAuth2Application to api.OAuth2Application
  382. func ToOAuth2Application(app *models.OAuth2Application) *api.OAuth2Application {
  383. return &api.OAuth2Application{
  384. ID: app.ID,
  385. Name: app.Name,
  386. ClientID: app.ClientID,
  387. ClientSecret: app.ClientSecret,
  388. RedirectURIs: app.RedirectURIs,
  389. Created: app.CreatedUnix.AsTime(),
  390. }
  391. }