Example #1
0
func AddApiKey(c *middleware.Context, cmd m.AddApiKeyCommand) Response {
	if !cmd.Role.IsValid() {
		return ApiError(400, "Invalid role specified", nil)
	}

	cmd.OrgId = c.OrgId
	if cmd.IsAdmin {
		if !c.IsGrafanaAdmin {
			return ApiError(400, "Only GrafanaAdmins can add admin keys", nil)
		}
	}

	newKeyInfo := apikeygen.New(cmd.OrgId, cmd.Name)
	cmd.Key = newKeyInfo.HashedKey

	if err := bus.Dispatch(&cmd); err != nil {
		return ApiError(500, "Failed to add API key", err)
	}

	result := &dtos.NewApiKeyResult{
		Name: cmd.Result.Name,
		Key:  newKeyInfo.ClientSecret}

	return Json(200, result)
}
Example #2
0
func AddApiKey(cmd *m.AddApiKeyCommand) error {
	return inTransaction(func(sess *xorm.Session) error {
		t := m.ApiKey{
			OrgId:   cmd.OrgId,
			Name:    cmd.Name,
			Role:    cmd.Role,
			Key:     cmd.Key,
			Created: time.Now(),
			Updated: time.Now(),
		}

		if _, err := sess.Insert(&t); err != nil {
			return err
		}
		cmd.Result = &t
		return nil
	})
}