gitea源码

key.go 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package user
  4. import (
  5. std_ctx "context"
  6. "errors"
  7. "net/http"
  8. asymkey_model "code.gitea.io/gitea/models/asymkey"
  9. "code.gitea.io/gitea/models/db"
  10. "code.gitea.io/gitea/models/perm"
  11. user_model "code.gitea.io/gitea/models/user"
  12. "code.gitea.io/gitea/modules/setting"
  13. api "code.gitea.io/gitea/modules/structs"
  14. "code.gitea.io/gitea/modules/web"
  15. "code.gitea.io/gitea/routers/api/v1/repo"
  16. "code.gitea.io/gitea/routers/api/v1/utils"
  17. asymkey_service "code.gitea.io/gitea/services/asymkey"
  18. "code.gitea.io/gitea/services/context"
  19. "code.gitea.io/gitea/services/convert"
  20. )
  21. // appendPrivateInformation appends the owner and key type information to api.PublicKey
  22. func appendPrivateInformation(ctx std_ctx.Context, apiKey *api.PublicKey, key *asymkey_model.PublicKey, defaultUser *user_model.User) (*api.PublicKey, error) {
  23. switch key.Type {
  24. case asymkey_model.KeyTypeDeploy:
  25. apiKey.KeyType = "deploy"
  26. case asymkey_model.KeyTypeUser:
  27. apiKey.KeyType = "user"
  28. if defaultUser.ID == key.OwnerID {
  29. apiKey.Owner = convert.ToUser(ctx, defaultUser, defaultUser)
  30. } else {
  31. user, err := user_model.GetUserByID(ctx, key.OwnerID)
  32. if err != nil {
  33. return apiKey, err
  34. }
  35. apiKey.Owner = convert.ToUser(ctx, user, user)
  36. }
  37. default:
  38. apiKey.KeyType = "unknown"
  39. }
  40. apiKey.ReadOnly = key.Mode == perm.AccessModeRead
  41. return apiKey, nil
  42. }
  43. func composePublicKeysAPILink() string {
  44. return setting.AppURL + "api/v1/user/keys/"
  45. }
  46. func listPublicKeys(ctx *context.APIContext, user *user_model.User) {
  47. var keys []*asymkey_model.PublicKey
  48. var err error
  49. var count int
  50. fingerprint := ctx.FormString("fingerprint")
  51. username := ctx.PathParam("username")
  52. if fingerprint != "" {
  53. var userID int64 // Unrestricted
  54. // Querying not just listing
  55. if username != "" {
  56. // Restrict to provided uid
  57. userID = user.ID
  58. }
  59. keys, err = db.Find[asymkey_model.PublicKey](ctx, asymkey_model.FindPublicKeyOptions{
  60. OwnerID: userID,
  61. Fingerprint: fingerprint,
  62. })
  63. count = len(keys)
  64. } else {
  65. var total int64
  66. // Use ListPublicKeys
  67. keys, total, err = db.FindAndCount[asymkey_model.PublicKey](ctx, asymkey_model.FindPublicKeyOptions{
  68. ListOptions: utils.GetListOptions(ctx),
  69. OwnerID: user.ID,
  70. NotKeytype: asymkey_model.KeyTypePrincipal,
  71. })
  72. count = int(total)
  73. }
  74. if err != nil {
  75. ctx.APIErrorInternal(err)
  76. return
  77. }
  78. apiLink := composePublicKeysAPILink()
  79. apiKeys := make([]*api.PublicKey, len(keys))
  80. for i := range keys {
  81. apiKeys[i] = convert.ToPublicKey(apiLink, keys[i])
  82. if ctx.Doer.IsAdmin || ctx.Doer.ID == keys[i].OwnerID {
  83. apiKeys[i], _ = appendPrivateInformation(ctx, apiKeys[i], keys[i], user)
  84. }
  85. }
  86. ctx.SetTotalCountHeader(int64(count))
  87. ctx.JSON(http.StatusOK, &apiKeys)
  88. }
  89. // ListMyPublicKeys list all of the authenticated user's public keys
  90. func ListMyPublicKeys(ctx *context.APIContext) {
  91. // swagger:operation GET /user/keys user userCurrentListKeys
  92. // ---
  93. // summary: List the authenticated user's public keys
  94. // parameters:
  95. // - name: fingerprint
  96. // in: query
  97. // description: fingerprint of the key
  98. // type: string
  99. // - name: page
  100. // in: query
  101. // description: page number of results to return (1-based)
  102. // type: integer
  103. // - name: limit
  104. // in: query
  105. // description: page size of results
  106. // type: integer
  107. // produces:
  108. // - application/json
  109. // responses:
  110. // "200":
  111. // "$ref": "#/responses/PublicKeyList"
  112. listPublicKeys(ctx, ctx.Doer)
  113. }
  114. // ListPublicKeys list the given user's public keys
  115. func ListPublicKeys(ctx *context.APIContext) {
  116. // swagger:operation GET /users/{username}/keys user userListKeys
  117. // ---
  118. // summary: List the given user's public keys
  119. // produces:
  120. // - application/json
  121. // parameters:
  122. // - name: username
  123. // in: path
  124. // description: username of the user whose public keys are to be listed
  125. // type: string
  126. // required: true
  127. // - name: fingerprint
  128. // in: query
  129. // description: fingerprint of the key
  130. // type: string
  131. // - name: page
  132. // in: query
  133. // description: page number of results to return (1-based)
  134. // type: integer
  135. // - name: limit
  136. // in: query
  137. // description: page size of results
  138. // type: integer
  139. // responses:
  140. // "200":
  141. // "$ref": "#/responses/PublicKeyList"
  142. // "404":
  143. // "$ref": "#/responses/notFound"
  144. listPublicKeys(ctx, ctx.ContextUser)
  145. }
  146. // GetPublicKey get a public key
  147. func GetPublicKey(ctx *context.APIContext) {
  148. // swagger:operation GET /user/keys/{id} user userCurrentGetKey
  149. // ---
  150. // summary: Get a public key
  151. // produces:
  152. // - application/json
  153. // parameters:
  154. // - name: id
  155. // in: path
  156. // description: id of key to get
  157. // type: integer
  158. // format: int64
  159. // required: true
  160. // responses:
  161. // "200":
  162. // "$ref": "#/responses/PublicKey"
  163. // "404":
  164. // "$ref": "#/responses/notFound"
  165. key, err := asymkey_model.GetPublicKeyByID(ctx, ctx.PathParamInt64("id"))
  166. if err != nil {
  167. if asymkey_model.IsErrKeyNotExist(err) {
  168. ctx.APIErrorNotFound()
  169. } else {
  170. ctx.APIErrorInternal(err)
  171. }
  172. return
  173. }
  174. apiLink := composePublicKeysAPILink()
  175. apiKey := convert.ToPublicKey(apiLink, key)
  176. if ctx.Doer.IsAdmin || ctx.Doer.ID == key.OwnerID {
  177. apiKey, _ = appendPrivateInformation(ctx, apiKey, key, ctx.Doer)
  178. }
  179. ctx.JSON(http.StatusOK, apiKey)
  180. }
  181. // CreateUserPublicKey creates new public key to given user by ID.
  182. func CreateUserPublicKey(ctx *context.APIContext, form api.CreateKeyOption, uid int64) {
  183. if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageSSHKeys) {
  184. ctx.APIErrorNotFound("Not Found", errors.New("ssh keys setting is not allowed to be visited"))
  185. return
  186. }
  187. content, err := asymkey_model.CheckPublicKeyString(form.Key)
  188. if err != nil {
  189. repo.HandleCheckKeyStringError(ctx, err)
  190. return
  191. }
  192. key, err := asymkey_model.AddPublicKey(ctx, uid, form.Title, content, 0)
  193. if err != nil {
  194. repo.HandleAddKeyError(ctx, err)
  195. return
  196. }
  197. apiLink := composePublicKeysAPILink()
  198. apiKey := convert.ToPublicKey(apiLink, key)
  199. if ctx.Doer.IsAdmin || ctx.Doer.ID == key.OwnerID {
  200. apiKey, _ = appendPrivateInformation(ctx, apiKey, key, ctx.Doer)
  201. }
  202. ctx.JSON(http.StatusCreated, apiKey)
  203. }
  204. // CreatePublicKey create one public key for me
  205. func CreatePublicKey(ctx *context.APIContext) {
  206. // swagger:operation POST /user/keys user userCurrentPostKey
  207. // ---
  208. // summary: Create a public key
  209. // consumes:
  210. // - application/json
  211. // produces:
  212. // - application/json
  213. // parameters:
  214. // - name: body
  215. // in: body
  216. // schema:
  217. // "$ref": "#/definitions/CreateKeyOption"
  218. // responses:
  219. // "201":
  220. // "$ref": "#/responses/PublicKey"
  221. // "422":
  222. // "$ref": "#/responses/validationError"
  223. form := web.GetForm(ctx).(*api.CreateKeyOption)
  224. CreateUserPublicKey(ctx, *form, ctx.Doer.ID)
  225. }
  226. // DeletePublicKey delete one public key
  227. func DeletePublicKey(ctx *context.APIContext) {
  228. // swagger:operation DELETE /user/keys/{id} user userCurrentDeleteKey
  229. // ---
  230. // summary: Delete a public key
  231. // produces:
  232. // - application/json
  233. // parameters:
  234. // - name: id
  235. // in: path
  236. // description: id of key to delete
  237. // type: integer
  238. // format: int64
  239. // required: true
  240. // responses:
  241. // "204":
  242. // "$ref": "#/responses/empty"
  243. // "403":
  244. // "$ref": "#/responses/forbidden"
  245. // "404":
  246. // "$ref": "#/responses/notFound"
  247. if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageSSHKeys) {
  248. ctx.APIErrorNotFound("Not Found", errors.New("ssh keys setting is not allowed to be visited"))
  249. return
  250. }
  251. id := ctx.PathParamInt64("id")
  252. externallyManaged, err := asymkey_model.PublicKeyIsExternallyManaged(ctx, id)
  253. if err != nil {
  254. if asymkey_model.IsErrKeyNotExist(err) {
  255. ctx.APIErrorNotFound()
  256. } else {
  257. ctx.APIErrorInternal(err)
  258. }
  259. return
  260. }
  261. if externallyManaged {
  262. ctx.APIError(http.StatusForbidden, "SSH Key is externally managed for this user")
  263. return
  264. }
  265. if err := asymkey_service.DeletePublicKey(ctx, ctx.Doer, id); err != nil {
  266. if asymkey_model.IsErrKeyAccessDenied(err) {
  267. ctx.APIError(http.StatusForbidden, "You do not have access to this key")
  268. } else {
  269. ctx.APIErrorInternal(err)
  270. }
  271. return
  272. }
  273. ctx.Status(http.StatusNoContent)
  274. }