mirror of
https://github.com/aykhans/slash-e.git
synced 2025-07-03 20:21:40 +00:00
feat: implement redirector api
This commit is contained in:
37
api/v1/redirector.go
Normal file
37
api/v1/redirector.go
Normal file
@ -0,0 +1,37 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/boojack/shortify/store"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
func (s *APIV1Service) registerRedirectorRoutes(g *echo.Group) {
|
||||
g.GET("/*", func(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
if len(c.ParamValues()) == 0 {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, "Invalid shortcut name")
|
||||
}
|
||||
shortcutName := c.ParamValues()[0]
|
||||
shortcut, err := s.Store.GetShortcut(ctx, &store.FindShortcut{
|
||||
Name: &shortcutName,
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get shortcut").SetInternal(err)
|
||||
}
|
||||
if shortcut == nil {
|
||||
return echo.NewHTTPError(http.StatusNotFound, "Shortcut not found")
|
||||
}
|
||||
if shortcut.Visibility != store.VisibilityPublic {
|
||||
userID, ok := c.Get(getUserIDContextKey()).(int)
|
||||
if !ok {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized")
|
||||
}
|
||||
if shortcut.Visibility == store.VisibilityPrivate && shortcut.CreatorID != userID {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized")
|
||||
}
|
||||
}
|
||||
return c.Redirect(http.StatusSeeOther, shortcut.Link)
|
||||
})
|
||||
}
|
@ -19,9 +19,13 @@ func NewAPIV1Service(profile *profile.Profile, store *store.Store) *APIV1Service
|
||||
}
|
||||
}
|
||||
|
||||
func (s *APIV1Service) Start(apiV1Group *echo.Group, secret string) {
|
||||
func (s *APIV1Service) Start(apiGroup *echo.Group, secret string) {
|
||||
apiV1Group := apiGroup.Group("/api/v1")
|
||||
s.registerSystemRoutes(apiV1Group)
|
||||
s.registerAuthRoutes(apiV1Group, secret)
|
||||
s.registerUserRoutes(apiV1Group)
|
||||
s.registerShortcutRoutes(apiV1Group)
|
||||
|
||||
redirectorGroup := apiGroup.Group("/o")
|
||||
s.registerRedirectorRoutes(redirectorGroup)
|
||||
}
|
||||
|
Reference in New Issue
Block a user