@@ -55,6 +55,11 @@ type LoginWithPasswordResponse struct {
55
55
SessionToken string `json:"session_token" validate:"required"`
56
56
}
57
57
58
+ // GenerateAPIKeyResponse contains an API key for a user.
59
+ type GenerateAPIKeyResponse struct {
60
+ Key string `json:"key"`
61
+ }
62
+
58
63
// Returns whether the initial user has been created or not.
59
64
func (api * api ) user (rw http.ResponseWriter , r * http.Request ) {
60
65
userCount , err := api .Database .GetUserCount (r .Context ())
@@ -312,6 +317,43 @@ func (api *api) postLogin(rw http.ResponseWriter, r *http.Request) {
312
317
})
313
318
}
314
319
320
+ // Creates a new API key, used for logging in via the CLI
321
+ func (api * api ) postApiKey (rw http.ResponseWriter , r * http.Request ) {
322
+ apiKey := httpmw .APIKey (r )
323
+ userID := apiKey .UserID
324
+
325
+ keyID , keySecret , err := generateAPIKeyIDSecret ()
326
+ if err != nil {
327
+ httpapi .Write (rw , http .StatusInternalServerError , httpapi.Response {
328
+ Message : fmt .Sprintf ("generate api key parts: %s" , err .Error ()),
329
+ })
330
+ return
331
+ }
332
+ hashed := sha256 .Sum256 ([]byte (keySecret ))
333
+
334
+ _ , err = api .Database .InsertAPIKey (r .Context (), database.InsertAPIKeyParams {
335
+ ID : keyID ,
336
+ UserID : userID ,
337
+ ExpiresAt : database .Now ().AddDate (1 , 0 , 0 ), // Expire after 1 year (same as v1)
338
+ CreatedAt : database .Now (),
339
+ UpdatedAt : database .Now (),
340
+ HashedSecret : hashed [:],
341
+ LoginType : database .LoginTypeBuiltIn ,
342
+ })
343
+ if err != nil {
344
+ httpapi .Write (rw , http .StatusInternalServerError , httpapi.Response {
345
+ Message : fmt .Sprintf ("insert api key: %s" , err .Error ()),
346
+ })
347
+ return
348
+ }
349
+
350
+ // This format is consumed by the APIKey middleware.
351
+ generatedApiKey := fmt .Sprintf ("%s-%s" , keyID , keySecret )
352
+
353
+ render .Status (r , http .StatusCreated )
354
+ render .JSON (rw , r , GenerateAPIKeyResponse {Key : generatedApiKey })
355
+ }
356
+
315
357
// Clear the user's session cookie
316
358
func (* api ) postLogout (rw http.ResponseWriter , r * http.Request ) {
317
359
// Get a blank token cookie
0 commit comments