2020-10-14 05:48:48 -05:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2020-10-16 02:22:24 -05:00
|
|
|
"fmt"
|
2020-10-14 05:48:48 -05:00
|
|
|
"path"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/grafana/grafana/pkg/api/dtos"
|
2021-01-15 07:43:20 -06:00
|
|
|
"github.com/grafana/grafana/pkg/api/response"
|
2020-10-14 05:48:48 -05:00
|
|
|
"github.com/grafana/grafana/pkg/models"
|
|
|
|
"github.com/grafana/grafana/pkg/setting"
|
|
|
|
"github.com/grafana/grafana/pkg/util"
|
|
|
|
)
|
|
|
|
|
|
|
|
// createShortURL handles requests to create short URLs.
|
2021-01-15 07:43:20 -06:00
|
|
|
func (hs *HTTPServer) createShortURL(c *models.ReqContext, cmd dtos.CreateShortURLCmd) response.Response {
|
2020-10-14 05:48:48 -05:00
|
|
|
hs.log.Debug("Received request to create short URL", "path", cmd.Path)
|
|
|
|
|
|
|
|
cmd.Path = strings.TrimSpace(cmd.Path)
|
|
|
|
|
|
|
|
if path.IsAbs(cmd.Path) {
|
|
|
|
hs.log.Error("Invalid short URL path", "path", cmd.Path)
|
2021-01-15 07:43:20 -06:00
|
|
|
return response.Error(400, "Path should be relative", nil)
|
2020-10-14 05:48:48 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
shortURL, err := hs.ShortURLService.CreateShortURL(c.Req.Context(), c.SignedInUser, cmd.Path)
|
|
|
|
if err != nil {
|
2021-01-15 07:43:20 -06:00
|
|
|
return response.Error(500, "Failed to create short URL", err)
|
2020-10-14 05:48:48 -05:00
|
|
|
}
|
|
|
|
|
2020-10-16 02:22:24 -05:00
|
|
|
url := fmt.Sprintf("%s/goto/%s", strings.TrimSuffix(setting.AppUrl, "/"), shortURL.Uid)
|
2020-10-14 05:48:48 -05:00
|
|
|
c.Logger.Debug("Created short URL", "url", url)
|
|
|
|
|
|
|
|
dto := dtos.ShortURL{
|
|
|
|
UID: shortURL.Uid,
|
|
|
|
URL: url,
|
|
|
|
}
|
|
|
|
|
2021-01-15 07:43:20 -06:00
|
|
|
return response.JSON(200, dto)
|
2020-10-14 05:48:48 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func (hs *HTTPServer) redirectFromShortURL(c *models.ReqContext) {
|
|
|
|
shortURLUID := c.Params(":uid")
|
|
|
|
|
|
|
|
if !util.IsValidShortUID(shortURLUID) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
shortURL, err := hs.ShortURLService.GetShortURLByUID(c.Req.Context(), c.SignedInUser, shortURLUID)
|
|
|
|
if err != nil {
|
|
|
|
if errors.Is(err, models.ErrShortURLNotFound) {
|
|
|
|
hs.log.Debug("Not redirecting short URL since not found")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
hs.log.Error("Short URL redirection error", "err", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-10-27 10:16:06 -05:00
|
|
|
// 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)
|
|
|
|
}
|
|
|
|
|
2020-10-14 05:48:48 -05:00
|
|
|
hs.log.Debug("Redirecting short URL", "path", shortURL.Path)
|
|
|
|
c.Redirect(setting.ToAbsUrl(shortURL.Path), 302)
|
|
|
|
}
|