2020-10-14 05:48:48 -05:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
2020-10-16 02:22:24 -05:00
|
|
|
"fmt"
|
2021-11-29 03:18:01 -06:00
|
|
|
"net/http"
|
2020-10-14 05:48:48 -05:00
|
|
|
"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"
|
2021-10-11 07:30:59 -05:00
|
|
|
"github.com/grafana/grafana/pkg/web"
|
2020-10-14 05:48:48 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
// createShortURL handles requests to create short URLs.
|
2021-11-29 03:18:01 -06:00
|
|
|
func (hs *HTTPServer) createShortURL(c *models.ReqContext) response.Response {
|
|
|
|
cmd := dtos.CreateShortURLCmd{}
|
|
|
|
if err := web.Bind(c.Req, &cmd); err != nil {
|
2022-06-15 08:11:36 -05:00
|
|
|
return response.Err(models.ErrShortURLBadRequest.Errorf("bad request data: %w", err))
|
2021-11-29 03:18:01 -06:00
|
|
|
}
|
2020-10-14 05:48:48 -05:00
|
|
|
hs.log.Debug("Received request to create short URL", "path", cmd.Path)
|
|
|
|
shortURL, err := hs.ShortURLService.CreateShortURL(c.Req.Context(), c.SignedInUser, cmd.Path)
|
|
|
|
if err != nil {
|
2022-06-15 08:11:36 -05:00
|
|
|
return response.Err(err)
|
2020-10-14 05:48:48 -05:00
|
|
|
}
|
|
|
|
|
2022-08-11 06:28:55 -05:00
|
|
|
url := fmt.Sprintf("%s/goto/%s?orgId=%d", strings.TrimSuffix(setting.AppUrl, "/"), shortURL.Uid, c.OrgID)
|
2020-10-14 05:48:48 -05:00
|
|
|
c.Logger.Debug("Created short URL", "url", url)
|
|
|
|
|
|
|
|
dto := dtos.ShortURL{
|
|
|
|
UID: shortURL.Uid,
|
|
|
|
URL: url,
|
|
|
|
}
|
|
|
|
|
2022-04-15 07:01:58 -05:00
|
|
|
return response.JSON(http.StatusOK, dto)
|
2020-10-14 05:48:48 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func (hs *HTTPServer) redirectFromShortURL(c *models.ReqContext) {
|
2021-10-11 07:30:59 -05:00
|
|
|
shortURLUID := web.Params(c.Req)[":uid"]
|
2020-10-14 05:48:48 -05:00
|
|
|
|
|
|
|
if !util.IsValidShortUID(shortURLUID) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
shortURL, err := hs.ShortURLService.GetShortURLByUID(c.Req.Context(), c.SignedInUser, shortURLUID)
|
|
|
|
if err != nil {
|
2022-06-15 08:11:36 -05:00
|
|
|
if models.ErrShortURLNotFound.Is(err) {
|
2020-10-14 05:48:48 -05:00
|
|
|
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)
|
|
|
|
}
|