Commit 60d40fa9 by Marcus Efraimsson Committed by GitHub

Short URL: Update last seen at when visiting a short URL (#28565)

Ref #28248

Co-authored-by: Sofia Papagiannaki <papagian@users.noreply.github.com>
parent aa9134b3
......@@ -57,6 +57,11 @@ func (hs *HTTPServer) redirectFromShortURL(c *models.ReqContext) {
return
}
// Failure to update LastSeenAt should still allow to redirect
if err := hs.ShortURLService.UpdateLastSeenAt(c.Req.Context(), shortURL); err != nil {
hs.log.Error("Failed to update short URL last seen at", "error", err)
}
hs.log.Debug("Redirecting short URL", "path", shortURL.Path)
c.Redirect(setting.ToAbsUrl(shortURL.Path), 302)
}
......@@ -10,6 +10,8 @@ import (
"github.com/grafana/grafana/pkg/util"
)
var getTime = time.Now
func init() {
registry.RegisterService(&ShortURLService{})
}
......@@ -42,6 +44,18 @@ func (s ShortURLService) GetShortURLByUID(ctx context.Context, user *models.Sign
return &shortURL, nil
}
func (s ShortURLService) UpdateLastSeenAt(ctx context.Context, shortURL *models.ShortUrl) error {
shortURL.LastSeenAt = getTime().Unix()
return s.SQLStore.WithTransactionalDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
_, err := dbSession.ID(shortURL.Id).Update(shortURL)
if err != nil {
return err
}
return nil
})
}
func (s ShortURLService) CreateShortURL(ctx context.Context, user *models.SignedInUser, path string) (*models.ShortUrl, error) {
now := time.Now().Unix()
shortURL := models.ShortUrl{
......
......@@ -3,6 +3,7 @@ package shorturls
import (
"context"
"testing"
"time"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/sqlstore"
......@@ -27,6 +28,25 @@ func TestShortURLService(t *testing.T) {
require.NoError(t, err)
require.NotNil(t, existingShortURL)
require.Equal(t, refPath, existingShortURL.Path)
t.Run("and update last seen at", func(t *testing.T) {
origGetTime := getTime
t.Cleanup(func() {
getTime = origGetTime
})
expectedTime := time.Date(2020, time.November, 27, 6, 5, 1, 0, time.UTC)
getTime = func() time.Time {
return expectedTime
}
err := service.UpdateLastSeenAt(context.Background(), existingShortURL)
require.NoError(t, err)
updatedShortURL, err := service.GetShortURLByUID(context.Background(), user, existingShortURL.Uid)
require.NoError(t, err)
require.Equal(t, expectedTime.Unix(), updatedShortURL.LastSeenAt)
})
})
t.Run("User cannot look up nonexistent short URLs", func(t *testing.T) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment