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 13 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.
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
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.
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.
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.
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.
6 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>
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. DismissStaleApprovals: bp.DismissStaleApprovals,
  109. RequireSignedCommits: bp.RequireSignedCommits,
  110. Created: bp.CreatedUnix.AsTime(),
  111. Updated: bp.UpdatedUnix.AsTime(),
  112. }
  113. }
  114. // ToTag convert a git.Tag to an api.Tag
  115. func ToTag(repo *models.Repository, t *git.Tag) *api.Tag {
  116. return &api.Tag{
  117. Name: t.Name,
  118. ID: t.ID.String(),
  119. Commit: ToCommitMeta(repo, t),
  120. ZipballURL: util.URLJoin(repo.HTMLURL(), "archive", t.Name+".zip"),
  121. TarballURL: util.URLJoin(repo.HTMLURL(), "archive", t.Name+".tar.gz"),
  122. }
  123. }
  124. // ToCommit convert a git.Commit to api.PayloadCommit
  125. func ToCommit(repo *models.Repository, c *git.Commit) *api.PayloadCommit {
  126. authorUsername := ""
  127. if author, err := models.GetUserByEmail(c.Author.Email); err == nil {
  128. authorUsername = author.Name
  129. } else if !models.IsErrUserNotExist(err) {
  130. log.Error("GetUserByEmail: %v", err)
  131. }
  132. committerUsername := ""
  133. if committer, err := models.GetUserByEmail(c.Committer.Email); err == nil {
  134. committerUsername = committer.Name
  135. } else if !models.IsErrUserNotExist(err) {
  136. log.Error("GetUserByEmail: %v", err)
  137. }
  138. return &api.PayloadCommit{
  139. ID: c.ID.String(),
  140. Message: c.Message(),
  141. URL: util.URLJoin(repo.HTMLURL(), "commit", c.ID.String()),
  142. Author: &api.PayloadUser{
  143. Name: c.Author.Name,
  144. Email: c.Author.Email,
  145. UserName: authorUsername,
  146. },
  147. Committer: &api.PayloadUser{
  148. Name: c.Committer.Name,
  149. Email: c.Committer.Email,
  150. UserName: committerUsername,
  151. },
  152. Timestamp: c.Author.When,
  153. Verification: ToVerification(c),
  154. }
  155. }
  156. // ToVerification convert a git.Commit.Signature to an api.PayloadCommitVerification
  157. func ToVerification(c *git.Commit) *api.PayloadCommitVerification {
  158. verif := models.ParseCommitWithSignature(c)
  159. commitVerification := &api.PayloadCommitVerification{
  160. Verified: verif.Verified,
  161. Reason: verif.Reason,
  162. }
  163. if c.Signature != nil {
  164. commitVerification.Signature = c.Signature.Signature
  165. commitVerification.Payload = c.Signature.Payload
  166. }
  167. if verif.SigningUser != nil {
  168. commitVerification.Signer = &structs.PayloadUser{
  169. Name: verif.SigningUser.Name,
  170. Email: verif.SigningUser.Email,
  171. }
  172. }
  173. return commitVerification
  174. }
  175. // ToPublicKey convert models.PublicKey to api.PublicKey
  176. func ToPublicKey(apiLink string, key *models.PublicKey) *api.PublicKey {
  177. return &api.PublicKey{
  178. ID: key.ID,
  179. Key: key.Content,
  180. URL: apiLink + com.ToStr(key.ID),
  181. Title: key.Name,
  182. Fingerprint: key.Fingerprint,
  183. Created: key.CreatedUnix.AsTime(),
  184. }
  185. }
  186. // ToGPGKey converts models.GPGKey to api.GPGKey
  187. func ToGPGKey(key *models.GPGKey) *api.GPGKey {
  188. subkeys := make([]*api.GPGKey, len(key.SubsKey))
  189. for id, k := range key.SubsKey {
  190. subkeys[id] = &api.GPGKey{
  191. ID: k.ID,
  192. PrimaryKeyID: k.PrimaryKeyID,
  193. KeyID: k.KeyID,
  194. PublicKey: k.Content,
  195. Created: k.CreatedUnix.AsTime(),
  196. Expires: k.ExpiredUnix.AsTime(),
  197. CanSign: k.CanSign,
  198. CanEncryptComms: k.CanEncryptComms,
  199. CanEncryptStorage: k.CanEncryptStorage,
  200. CanCertify: k.CanSign,
  201. }
  202. }
  203. emails := make([]*api.GPGKeyEmail, len(key.Emails))
  204. for i, e := range key.Emails {
  205. emails[i] = ToGPGKeyEmail(e)
  206. }
  207. return &api.GPGKey{
  208. ID: key.ID,
  209. PrimaryKeyID: key.PrimaryKeyID,
  210. KeyID: key.KeyID,
  211. PublicKey: key.Content,
  212. Created: key.CreatedUnix.AsTime(),
  213. Expires: key.ExpiredUnix.AsTime(),
  214. Emails: emails,
  215. SubsKey: subkeys,
  216. CanSign: key.CanSign,
  217. CanEncryptComms: key.CanEncryptComms,
  218. CanEncryptStorage: key.CanEncryptStorage,
  219. CanCertify: key.CanSign,
  220. }
  221. }
  222. // ToGPGKeyEmail convert models.EmailAddress to api.GPGKeyEmail
  223. func ToGPGKeyEmail(email *models.EmailAddress) *api.GPGKeyEmail {
  224. return &api.GPGKeyEmail{
  225. Email: email.Email,
  226. Verified: email.IsActivated,
  227. }
  228. }
  229. // ToHook convert models.Webhook to api.Hook
  230. func ToHook(repoLink string, w *models.Webhook) *api.Hook {
  231. config := map[string]string{
  232. "url": w.URL,
  233. "content_type": w.ContentType.Name(),
  234. }
  235. if w.HookTaskType == models.SLACK {
  236. s := webhook.GetSlackHook(w)
  237. config["channel"] = s.Channel
  238. config["username"] = s.Username
  239. config["icon_url"] = s.IconURL
  240. config["color"] = s.Color
  241. }
  242. return &api.Hook{
  243. ID: w.ID,
  244. Type: w.HookTaskType.Name(),
  245. URL: fmt.Sprintf("%s/settings/hooks/%d", repoLink, w.ID),
  246. Active: w.IsActive,
  247. Config: config,
  248. Events: w.EventsArray(),
  249. Updated: w.UpdatedUnix.AsTime(),
  250. Created: w.CreatedUnix.AsTime(),
  251. }
  252. }
  253. // ToGitHook convert git.Hook to api.GitHook
  254. func ToGitHook(h *git.Hook) *api.GitHook {
  255. return &api.GitHook{
  256. Name: h.Name(),
  257. IsActive: h.IsActive,
  258. Content: h.Content,
  259. }
  260. }
  261. // ToDeployKey convert models.DeployKey to api.DeployKey
  262. func ToDeployKey(apiLink string, key *models.DeployKey) *api.DeployKey {
  263. return &api.DeployKey{
  264. ID: key.ID,
  265. KeyID: key.KeyID,
  266. Key: key.Content,
  267. Fingerprint: key.Fingerprint,
  268. URL: apiLink + com.ToStr(key.ID),
  269. Title: key.Name,
  270. Created: key.CreatedUnix.AsTime(),
  271. ReadOnly: key.Mode == models.AccessModeRead, // All deploy keys are read-only.
  272. }
  273. }
  274. // ToOrganization convert models.User to api.Organization
  275. func ToOrganization(org *models.User) *api.Organization {
  276. return &api.Organization{
  277. ID: org.ID,
  278. AvatarURL: org.AvatarLink(),
  279. UserName: org.Name,
  280. FullName: org.FullName,
  281. Description: org.Description,
  282. Website: org.Website,
  283. Location: org.Location,
  284. Visibility: org.Visibility.String(),
  285. RepoAdminChangeTeamAccess: org.RepoAdminChangeTeamAccess,
  286. }
  287. }
  288. // ToTeam convert models.Team to api.Team
  289. func ToTeam(team *models.Team) *api.Team {
  290. return &api.Team{
  291. ID: team.ID,
  292. Name: team.Name,
  293. Description: team.Description,
  294. IncludesAllRepositories: team.IncludesAllRepositories,
  295. CanCreateOrgRepo: team.CanCreateOrgRepo,
  296. Permission: team.Authorize.String(),
  297. Units: team.GetUnitNames(),
  298. }
  299. }
  300. // ToUser convert models.User to api.User
  301. // signed shall only be set if requester is logged in. authed shall only be set if user is site admin or user himself
  302. func ToUser(user *models.User, signed, authed bool) *api.User {
  303. result := &api.User{
  304. UserName: user.Name,
  305. AvatarURL: user.AvatarLink(),
  306. FullName: markup.Sanitize(user.FullName),
  307. Created: user.CreatedUnix.AsTime(),
  308. }
  309. // hide primary email if API caller is anonymous or user keep email private
  310. if signed && (!user.KeepEmailPrivate || authed) {
  311. result.Email = user.Email
  312. }
  313. // only site admin will get these information and possibly user himself
  314. if authed {
  315. result.ID = user.ID
  316. result.IsAdmin = user.IsAdmin
  317. result.LastLogin = user.LastLoginUnix.AsTime()
  318. result.Language = user.Language
  319. }
  320. return result
  321. }
  322. // ToAnnotatedTag convert git.Tag to api.AnnotatedTag
  323. func ToAnnotatedTag(repo *models.Repository, t *git.Tag, c *git.Commit) *api.AnnotatedTag {
  324. return &api.AnnotatedTag{
  325. Tag: t.Name,
  326. SHA: t.ID.String(),
  327. Object: ToAnnotatedTagObject(repo, c),
  328. Message: t.Message,
  329. URL: util.URLJoin(repo.APIURL(), "git/tags", t.ID.String()),
  330. Tagger: ToCommitUser(t.Tagger),
  331. Verification: ToVerification(c),
  332. }
  333. }
  334. // ToAnnotatedTagObject convert a git.Commit to an api.AnnotatedTagObject
  335. func ToAnnotatedTagObject(repo *models.Repository, commit *git.Commit) *api.AnnotatedTagObject {
  336. return &api.AnnotatedTagObject{
  337. SHA: commit.ID.String(),
  338. Type: string(git.ObjectCommit),
  339. URL: util.URLJoin(repo.APIURL(), "git/commits", commit.ID.String()),
  340. }
  341. }
  342. // ToCommitUser convert a git.Signature to an api.CommitUser
  343. func ToCommitUser(sig *git.Signature) *api.CommitUser {
  344. return &api.CommitUser{
  345. Identity: api.Identity{
  346. Name: sig.Name,
  347. Email: sig.Email,
  348. },
  349. Date: sig.When.UTC().Format(time.RFC3339),
  350. }
  351. }
  352. // ToCommitMeta convert a git.Tag to an api.CommitMeta
  353. func ToCommitMeta(repo *models.Repository, tag *git.Tag) *api.CommitMeta {
  354. return &api.CommitMeta{
  355. SHA: tag.Object.String(),
  356. // TODO: Add the /commits API endpoint and use it here (https://developer.github.com/v3/repos/commits/#get-a-single-commit)
  357. URL: util.URLJoin(repo.APIURL(), "git/commits", tag.ID.String()),
  358. }
  359. }
  360. // ToTopicResponse convert from models.Topic to api.TopicResponse
  361. func ToTopicResponse(topic *models.Topic) *api.TopicResponse {
  362. return &api.TopicResponse{
  363. ID: topic.ID,
  364. Name: topic.Name,
  365. RepoCount: topic.RepoCount,
  366. Created: topic.CreatedUnix.AsTime(),
  367. Updated: topic.UpdatedUnix.AsTime(),
  368. }
  369. }
  370. // ToOAuth2Application convert from models.OAuth2Application to api.OAuth2Application
  371. func ToOAuth2Application(app *models.OAuth2Application) *api.OAuth2Application {
  372. return &api.OAuth2Application{
  373. ID: app.ID,
  374. Name: app.Name,
  375. ClientID: app.ClientID,
  376. ClientSecret: app.ClientSecret,
  377. RedirectURIs: app.RedirectURIs,
  378. Created: app.CreatedUnix.AsTime(),
  379. }
  380. }