MCPcopy Index your code
hub / github.com/coder/coder / postAPIKey

Method postAPIKey

coderd/apikey.go:194–237  ·  view source on GitHub ↗

Creates a new session key, used for logging in via the CLI. @Summary Create new session key @ID create-new-session-key @Security CoderSessionToken @Produce json @Tags Users @Param user path string true "User ID, name, or me" @Success 201 {object} codersdk.GenerateAPIKeyResponse @Router /api/v2/user

(rw http.ResponseWriter, r *http.Request)

Source from the content-addressed store, hash-verified

192// @Success 201 {object} codersdk.GenerateAPIKeyResponse
193// @Router /api/v2/users/{user}/keys [post]
194func (api *API) postAPIKey(rw http.ResponseWriter, r *http.Request) {
195 var (
196 ctx = r.Context()
197 user = httpmw.UserParam(r)
198 auditor = api.Auditor.Load()
199 aReq, commitAudit = audit.InitRequest[database.APIKey](rw, &audit.RequestParams{
200 Audit: *auditor,
201 Log: api.Logger,
202 Request: r,
203 Action: database.AuditActionCreate,
204 })
205 )
206 aReq.Old = database.APIKey{}
207 defer commitAudit()
208
209 // TODO(Cian): System users technically just have the 'member' role
210 // and we don't want to disallow all members from creating API keys.
211 if user.IsSystem {
212 api.Logger.Warn(ctx, "disallowed creating api key for system user", slog.F("user_id", user.ID))
213 httpapi.Forbidden(rw)
214 return
215 }
216
217 cookie, key, err := api.createAPIKey(ctx, apikey.CreateParams{
218 UserID: user.ID,
219 DefaultLifetime: api.DeploymentValues.Sessions.DefaultTokenDuration.Value(),
220 LoginType: database.LoginTypePassword,
221 RemoteAddr: r.RemoteAddr,
222 })
223 if err != nil {
224 httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
225 Message: "Failed to create API key.",
226 Detail: err.Error(),
227 })
228 return
229 }
230
231 aReq.New = *key
232 // We intentionally do not set the cookie on the response here.
233 // Setting the cookie will couple the browser session to the API
234 // key we return here, meaning logging out of the website would
235 // invalid your CLI key.
236 httpapi.Write(ctx, rw, http.StatusCreated, codersdk.GenerateAPIKeyResponse{Key: cookie.Value})
237}
238
239// @Summary Get API key by ID
240// @ID get-api-key-by-id

Callers

nothing calls this directly

Calls 9

createAPIKeyMethod · 0.95
UserParamFunction · 0.92
InitRequestFunction · 0.92
ForbiddenFunction · 0.92
WriteFunction · 0.92
ContextMethod · 0.65
LoadMethod · 0.45
ValueMethod · 0.45
ErrorMethod · 0.45

Tested by

no test coverage detected