chore: replace gin with standard lib net/http

This commit is contained in:
Christoph Haas
2025-03-09 21:16:42 +01:00
parent 7473132932
commit 0206952182
58 changed files with 5302 additions and 1390 deletions

View File

@@ -1,24 +1,46 @@
package handlers
import (
"context"
"net/http"
"strings"
"github.com/gin-contrib/cors"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/memstore"
"github.com/gin-gonic/gin"
csrf "github.com/utrack/gin-csrf"
"github.com/go-pkgz/routegroup"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/app/api/core"
"github.com/h44z/wg-portal/internal/app/api/v0/model"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/app/api/core/middleware/cors"
"github.com/h44z/wg-portal/internal/app/api/core/middleware/csrf"
"github.com/h44z/wg-portal/internal/app/api/core/respond"
)
type handler interface {
type SessionMiddleware interface {
// SetData sets the session data for the given context.
SetData(ctx context.Context, val SessionData)
// GetData returns the session data for the given context. If no data is found, the default session data is returned.
GetData(ctx context.Context) SessionData
// DestroyData destroys the session data for the given context.
DestroyData(ctx context.Context)
// GetString returns the string value for the given key. If no value is found, an empty string is returned.
GetString(ctx context.Context, key string) string
// Put sets the value for the given key.
Put(ctx context.Context, key string, value any)
// LoadAndSave is a middleware that loads the session data for the given request and saves it after the request is
// finished.
LoadAndSave(next http.Handler) http.Handler
}
type Handler interface {
// GetName returns the name of the handler.
GetName() string
RegisterRoutes(g *gin.RouterGroup, authenticator *authenticationHandler)
// RegisterRoutes registers the routes for the handler. The session manager is passed to the handler.
RegisterRoutes(g *routegroup.Bundle)
}
type Authenticator interface {
// LoggedIn checks if a user is logged in. If scopes are given, they are validated as well.
LoggedIn(scopes ...Scope) func(next http.Handler) http.Handler
// UserIdMatch checks if the user id in the session matches the user id in the request. If not, the request is aborted.
UserIdMatch(idParameter string) func(next http.Handler) http.Handler
}
// To compile the API documentation use the
@@ -35,54 +57,33 @@ type handler interface {
// @BasePath /api/v0
// @query.collection.format multi
func NewRestApi(cfg *config.Config, app *app.App) core.ApiEndpointSetupFunc {
authenticator := &authenticationHandler{
app: app,
Session: GinSessionStore{sessionIdentifier: cfg.Web.SessionIdentifier},
}
handlers := make([]handler, 0, 1)
handlers = append(handlers, testEndpoint{})
handlers = append(handlers, userEndpoint{app: app, authenticator: authenticator})
handlers = append(handlers, newConfigEndpoint(app, authenticator))
handlers = append(handlers, authEndpoint{app: app, authenticator: authenticator})
handlers = append(handlers, interfaceEndpoint{app: app, authenticator: authenticator})
handlers = append(handlers, peerEndpoint{app: app, authenticator: authenticator})
func NewRestApi(
session SessionMiddleware,
handlers ...Handler,
) core.ApiEndpointSetupFunc {
return func() (core.ApiVersion, core.GroupSetupFn) {
return "v0", func(group *gin.RouterGroup) {
cookieStore := memstore.NewStore([]byte(cfg.Web.SessionSecret))
cookieStore.Options(sessions.Options{
Path: "/",
MaxAge: 86400, // auth session is valid for 1 day
Secure: strings.HasPrefix(cfg.Web.ExternalUrl, "https"),
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
return "v0", func(group *routegroup.Bundle) {
csrfMiddleware := csrf.New(func(r *http.Request) string {
return session.GetString(r.Context(), "csrf_token")
}, func(r *http.Request, token string) {
session.Put(r.Context(), "csrf_token", token)
})
group.Use(sessions.Sessions(cfg.Web.SessionIdentifier, cookieStore))
group.Use(cors.Default())
group.Use(csrf.Middleware(csrf.Options{
Secret: cfg.Web.CsrfSecret,
ErrorFunc: func(c *gin.Context) {
c.JSON(http.StatusBadRequest, model.Error{
Code: http.StatusBadRequest,
Message: "CSRF token mismatch",
})
c.Abort()
},
}))
group.GET("/csrf", handleCsrfGet())
group.Use(session.LoadAndSave)
group.Use(csrfMiddleware.Handler)
group.Use(cors.New().Handler)
group.With(csrfMiddleware.RefreshToken).HandleFunc("GET /csrf", handleCsrfGet())
// Handler functions
for _, h := range handlers {
h.RegisterRoutes(group, authenticator)
h.RegisterRoutes(group)
}
}
}
}
// handleCsrfGet returns a gorm handler function.
// handleCsrfGet returns a gorm Handler function.
//
// @ID base_handleCsrfGet
// @Tags Security
@@ -90,8 +91,12 @@ func NewRestApi(cfg *config.Config, app *app.App) core.ApiEndpointSetupFunc {
// @Produce json
// @Success 200 {object} string
// @Router /csrf [get]
func handleCsrfGet() gin.HandlerFunc {
return func(c *gin.Context) {
c.JSON(http.StatusOK, csrf.GetToken(c))
func handleCsrfGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
respond.JSON(w, http.StatusOK, csrf.GetToken(r.Context()))
}
}
// region session wrapper
// endregion session wrapper

View File

@@ -8,36 +8,62 @@ import (
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/go-pkgz/routegroup"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/app/api/core/request"
"github.com/h44z/wg-portal/internal/app/api/core/respond"
"github.com/h44z/wg-portal/internal/app/api/v0/model"
"github.com/h44z/wg-portal/internal/domain"
)
type authEndpoint struct {
app *app.App
authenticator *authenticationHandler
type Session interface {
// SetData sets the session data for the given context.
SetData(ctx context.Context, val SessionData)
// GetData returns the session data for the given context. If no data is found, the default session data is returned.
GetData(ctx context.Context) SessionData
// DestroyData destroys the session data for the given context.
DestroyData(ctx context.Context)
}
func (e authEndpoint) GetName() string {
type Validator interface {
Struct(s interface{}) error
}
type AuthEndpoint struct {
app *app.App
authenticator Authenticator
session Session
validate Validator
}
func NewAuthEndpoint(app *app.App, authenticator Authenticator, session Session, validator Validator) AuthEndpoint {
return AuthEndpoint{
app: app,
authenticator: authenticator,
session: session,
validate: validator,
}
}
func (e AuthEndpoint) GetName() string {
return "AuthEndpoint"
}
func (e authEndpoint) RegisterRoutes(g *gin.RouterGroup, authenticator *authenticationHandler) {
apiGroup := g.Group("/auth")
func (e AuthEndpoint) RegisterRoutes(g *routegroup.Bundle) {
apiGroup := g.Mount("/auth")
apiGroup.GET("/providers", e.handleExternalLoginProvidersGet())
apiGroup.GET("/session", e.handleSessionInfoGet())
apiGroup.HandleFunc("GET /providers", e.handleExternalLoginProvidersGet())
apiGroup.HandleFunc("GET /session", e.handleSessionInfoGet())
apiGroup.GET("/login/:provider/init", e.handleOauthInitiateGet())
apiGroup.GET("/login/:provider/callback", e.handleOauthCallbackGet())
apiGroup.HandleFunc("GET /login/{provider}/init", e.handleOauthInitiateGet())
apiGroup.HandleFunc("GET /login/{provider}/callback", e.handleOauthCallbackGet())
apiGroup.POST("/login", e.handleLoginPost())
apiGroup.POST("/logout", authenticator.LoggedIn(), e.handleLogoutPost())
apiGroup.HandleFunc("POST /login", e.handleLoginPost())
apiGroup.With(e.authenticator.LoggedIn()).HandleFunc("POST /logout", e.handleLogoutPost())
}
// handleExternalLoginProvidersGet returns a gorm handler function.
// handleExternalLoginProvidersGet returns a gorm Handler function.
//
// @ID auth_handleExternalLoginProvidersGet
// @Tags Authentication
@@ -45,16 +71,15 @@ func (e authEndpoint) RegisterRoutes(g *gin.RouterGroup, authenticator *authenti
// @Produce json
// @Success 200 {object} []model.LoginProviderInfo
// @Router /auth/providers [get]
func (e authEndpoint) handleExternalLoginProvidersGet() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
providers := e.app.Authenticator.GetExternalLoginProviders(ctx)
func (e AuthEndpoint) handleExternalLoginProvidersGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
providers := e.app.Authenticator.GetExternalLoginProviders(r.Context())
c.JSON(http.StatusOK, model.NewLoginProviderInfos(providers))
respond.JSON(w, http.StatusOK, model.NewLoginProviderInfos(providers))
}
}
// handleSessionInfoGet returns a gorm handler function.
// handleSessionInfoGet returns a gorm Handler function.
//
// @ID auth_handleSessionInfoGet
// @Tags Authentication
@@ -63,9 +88,9 @@ func (e authEndpoint) handleExternalLoginProvidersGet() gin.HandlerFunc {
// @Success 200 {object} []model.SessionInfo
// @Failure 500 {object} model.Error
// @Router /auth/session [get]
func (e authEndpoint) handleSessionInfoGet() gin.HandlerFunc {
return func(c *gin.Context) {
currentSession := e.authenticator.Session.GetData(c)
func (e AuthEndpoint) handleSessionInfoGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
currentSession := e.session.GetData(r.Context())
var loggedInUid *string
var firstname *string
@@ -83,7 +108,7 @@ func (e authEndpoint) handleSessionInfoGet() gin.HandlerFunc {
email = &e
}
c.JSON(http.StatusOK, model.SessionInfo{
respond.JSON(w, http.StatusOK, model.SessionInfo{
LoggedIn: currentSession.LoggedIn,
IsAdmin: currentSession.IsAdmin,
UserIdentifier: loggedInUid,
@@ -94,7 +119,7 @@ func (e authEndpoint) handleSessionInfoGet() gin.HandlerFunc {
}
}
// handleOauthInitiateGet returns a gorm handler function.
// handleOauthInitiateGet returns a gorm Handler function.
//
// @ID auth_handleOauthInitiateGet
// @Tags Authentication
@@ -102,23 +127,24 @@ func (e authEndpoint) handleSessionInfoGet() gin.HandlerFunc {
// @Produce json
// @Success 200 {object} []model.LoginProviderInfo
// @Router /auth/{provider}/init [get]
func (e authEndpoint) handleOauthInitiateGet() gin.HandlerFunc {
return func(c *gin.Context) {
currentSession := e.authenticator.Session.GetData(c)
func (e AuthEndpoint) handleOauthInitiateGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
currentSession := e.session.GetData(r.Context())
autoRedirect, _ := strconv.ParseBool(c.DefaultQuery("redirect", "false"))
returnTo := c.Query("return")
provider := c.Param("provider")
autoRedirect, _ := strconv.ParseBool(request.QueryDefault(r, "redirect", "false"))
returnTo := request.Query(r, "return")
provider := request.Path(r, "provider")
var returnUrl *url.URL
var returnParams string
redirectToReturn := func() {
c.Redirect(http.StatusFound, returnUrl.String()+"?"+returnParams)
respond.Redirect(w, r, http.StatusFound, returnUrl.String()+"?"+returnParams)
}
if returnTo != "" {
if !e.isValidReturnUrl(returnTo) {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "invalid return URL"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "invalid return URL"})
return
}
if u, err := url.Parse(returnTo); err == nil {
@@ -137,34 +163,34 @@ func (e authEndpoint) handleOauthInitiateGet() gin.HandlerFunc {
returnParams = queryParams.Encode()
redirectToReturn()
} else {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "already logged in"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "already logged in"})
}
return
}
ctx := domain.SetUserInfoFromGin(c)
authCodeUrl, state, nonce, err := e.app.Authenticator.OauthLoginStep1(ctx, provider)
authCodeUrl, state, nonce, err := e.app.Authenticator.OauthLoginStep1(context.Background(), provider)
if err != nil {
if autoRedirect && e.isValidReturnUrl(returnTo) {
redirectToReturn()
} else {
c.JSON(http.StatusInternalServerError,
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
}
return
}
authSession := e.authenticator.Session.DefaultSessionData()
authSession := e.session.GetData(r.Context())
authSession.OauthState = state
authSession.OauthNonce = nonce
authSession.OauthProvider = provider
authSession.OauthReturnTo = returnTo
e.authenticator.Session.SetData(c, authSession)
e.session.SetData(r.Context(), authSession)
if autoRedirect {
c.Redirect(http.StatusFound, authCodeUrl)
respond.Redirect(w, r, http.StatusFound, authCodeUrl)
} else {
c.JSON(http.StatusOK, model.OauthInitiationResponse{
respond.JSON(w, http.StatusOK, model.OauthInitiationResponse{
RedirectUrl: authCodeUrl,
State: state,
})
@@ -172,7 +198,7 @@ func (e authEndpoint) handleOauthInitiateGet() gin.HandlerFunc {
}
}
// handleOauthCallbackGet returns a gorm handler function.
// handleOauthCallbackGet returns a gorm Handler function.
//
// @ID auth_handleOauthCallbackGet
// @Tags Authentication
@@ -180,14 +206,14 @@ func (e authEndpoint) handleOauthInitiateGet() gin.HandlerFunc {
// @Produce json
// @Success 200 {object} []model.LoginProviderInfo
// @Router /auth/{provider}/callback [get]
func (e authEndpoint) handleOauthCallbackGet() gin.HandlerFunc {
return func(c *gin.Context) {
currentSession := e.authenticator.Session.GetData(c)
func (e AuthEndpoint) handleOauthCallbackGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
currentSession := e.session.GetData(r.Context())
var returnUrl *url.URL
var returnParams string
redirectToReturn := func() {
c.Redirect(http.StatusFound, returnUrl.String()+"?"+returnParams)
respond.Redirect(w, r, http.StatusFound, returnUrl.String()+"?"+returnParams)
}
if currentSession.OauthReturnTo != "" {
@@ -207,20 +233,20 @@ func (e authEndpoint) handleOauthCallbackGet() gin.HandlerFunc {
returnParams = queryParams.Encode()
redirectToReturn()
} else {
c.JSON(http.StatusBadRequest, model.Error{Message: "already logged in"})
respond.JSON(w, http.StatusBadRequest, model.Error{Message: "already logged in"})
}
return
}
provider := c.Param("provider")
oauthCode := c.Query("code")
oauthState := c.Query("state")
provider := request.Path(r, "provider")
oauthCode := request.Query(r, "code")
oauthState := request.Query(r, "state")
if provider != currentSession.OauthProvider {
if returnUrl != nil && e.isValidReturnUrl(returnUrl.String()) {
redirectToReturn()
} else {
c.JSON(http.StatusBadRequest,
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "invalid oauth provider"})
}
return
@@ -229,7 +255,8 @@ func (e authEndpoint) handleOauthCallbackGet() gin.HandlerFunc {
if returnUrl != nil && e.isValidReturnUrl(returnUrl.String()) {
redirectToReturn()
} else {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "invalid oauth state"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "invalid oauth state"})
}
return
}
@@ -241,12 +268,13 @@ func (e authEndpoint) handleOauthCallbackGet() gin.HandlerFunc {
if returnUrl != nil && e.isValidReturnUrl(returnUrl.String()) {
redirectToReturn()
} else {
c.JSON(http.StatusUnauthorized, model.Error{Code: http.StatusUnauthorized, Message: err.Error()})
respond.JSON(w, http.StatusUnauthorized,
model.Error{Code: http.StatusUnauthorized, Message: err.Error()})
}
return
}
e.setAuthenticatedUser(c, user)
e.setAuthenticatedUser(r, user)
if returnUrl != nil && e.isValidReturnUrl(returnUrl.String()) {
queryParams := returnUrl.Query()
@@ -254,13 +282,13 @@ func (e authEndpoint) handleOauthCallbackGet() gin.HandlerFunc {
returnParams = queryParams.Encode()
redirectToReturn()
} else {
c.JSON(http.StatusOK, user)
respond.JSON(w, http.StatusOK, user)
}
}
}
func (e authEndpoint) setAuthenticatedUser(c *gin.Context, user *domain.User) {
currentSession := e.authenticator.Session.GetData(c)
func (e AuthEndpoint) setAuthenticatedUser(r *http.Request, user *domain.User) {
currentSession := e.session.GetData(r.Context())
currentSession.LoggedIn = true
currentSession.IsAdmin = user.IsAdmin
@@ -274,10 +302,10 @@ func (e authEndpoint) setAuthenticatedUser(c *gin.Context, user *domain.User) {
currentSession.OauthProvider = ""
currentSession.OauthReturnTo = ""
e.authenticator.Session.SetData(c, currentSession)
e.session.SetData(r.Context(), currentSession)
}
// handleLoginPost returns a gorm handler function.
// handleLoginPost returns a gorm Handler function.
//
// @ID auth_handleLoginPost
// @Tags Authentication
@@ -285,11 +313,11 @@ func (e authEndpoint) setAuthenticatedUser(c *gin.Context, user *domain.User) {
// @Produce json
// @Success 200 {object} []model.LoginProviderInfo
// @Router /auth/login [post]
func (e authEndpoint) handleLoginPost() gin.HandlerFunc {
return func(c *gin.Context) {
currentSession := e.authenticator.Session.GetData(c)
func (e AuthEndpoint) handleLoginPost() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
currentSession := e.session.GetData(r.Context())
if currentSession.LoggedIn {
c.JSON(http.StatusOK, model.Error{Code: http.StatusOK, Message: "already logged in"})
respond.JSON(w, http.StatusOK, model.Error{Code: http.StatusOK, Message: "already logged in"})
return
}
@@ -298,25 +326,29 @@ func (e authEndpoint) handleLoginPost() gin.HandlerFunc {
Password string `json:"password" binding:"required,min=4"`
}
if err := c.ShouldBindJSON(&loginData); err != nil {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
if err := request.BodyJson(r, &loginData); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
if err := e.validate.Struct(loginData); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
ctx := domain.SetUserInfoFromGin(c)
user, err := e.app.Authenticator.PlainLogin(ctx, loginData.Username, loginData.Password)
user, err := e.app.Authenticator.PlainLogin(context.Background(), loginData.Username, loginData.Password)
if err != nil {
c.JSON(http.StatusUnauthorized, model.Error{Code: http.StatusUnauthorized, Message: "login failed"})
respond.JSON(w, http.StatusUnauthorized,
model.Error{Code: http.StatusUnauthorized, Message: "login failed"})
return
}
e.setAuthenticatedUser(c, user)
e.setAuthenticatedUser(r, user)
c.JSON(http.StatusOK, user)
respond.JSON(w, http.StatusOK, user)
}
}
// handleLogoutPost returns a gorm handler function.
// handleLogoutPost returns a gorm Handler function.
//
// @ID auth_handleLogoutGet
// @Tags Authentication
@@ -324,22 +356,22 @@ func (e authEndpoint) handleLoginPost() gin.HandlerFunc {
// @Produce json
// @Success 200 {object} []model.LoginProviderInfo
// @Router /auth/logout [get]
func (e authEndpoint) handleLogoutPost() gin.HandlerFunc {
return func(c *gin.Context) {
currentSession := e.authenticator.Session.GetData(c)
func (e AuthEndpoint) handleLogoutPost() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
currentSession := e.session.GetData(r.Context())
if !currentSession.LoggedIn { // Not logged in
c.JSON(http.StatusOK, model.Error{Code: http.StatusOK, Message: "not logged in"})
respond.JSON(w, http.StatusOK, model.Error{Code: http.StatusOK, Message: "not logged in"})
return
}
e.authenticator.Session.DestroyData(c)
c.JSON(http.StatusOK, model.Error{Code: http.StatusOK, Message: "logout ok"})
e.session.DestroyData(r.Context())
respond.JSON(w, http.StatusOK, model.Error{Code: http.StatusOK, Message: "logout ok"})
}
}
// isValidReturnUrl checks if the given return URL matches the configured external URL of the application.
func (e authEndpoint) isValidReturnUrl(returnUrl string) bool {
func (e AuthEndpoint) isValidReturnUrl(returnUrl string) bool {
if !strings.HasPrefix(returnUrl, e.app.Config.Web.ExternalUrl) {
return false
}

View File

@@ -1,7 +1,6 @@
package handlers
import (
"bytes"
"embed"
"fmt"
"html/template"
@@ -9,57 +8,61 @@ import (
"net/http"
"net/url"
"github.com/gin-gonic/gin"
"github.com/go-pkgz/routegroup"
"github.com/h44z/wg-portal/internal"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/app/api/core/request"
"github.com/h44z/wg-portal/internal/app/api/core/respond"
"github.com/h44z/wg-portal/internal/app/api/v0/model"
"github.com/h44z/wg-portal/internal/config"
)
//go:embed frontend_config.js.gotpl
var frontendJs embed.FS
type configEndpoint struct {
app *app.App
authenticator *authenticationHandler
type ConfigEndpoint struct {
cfg *config.Config
authenticator Authenticator
tpl *template.Template
tpl *respond.TemplateRenderer
}
func newConfigEndpoint(app *app.App, authenticator *authenticationHandler) configEndpoint {
ep := configEndpoint{
app: app,
func NewConfigEndpoint(cfg *config.Config, authenticator Authenticator) ConfigEndpoint {
ep := ConfigEndpoint{
cfg: cfg,
authenticator: authenticator,
tpl: template.Must(template.ParseFS(frontendJs, "frontend_config.js.gotpl")),
tpl: respond.NewTemplateRenderer(template.Must(template.ParseFS(frontendJs,
"frontend_config.js.gotpl"))),
}
return ep
}
func (e configEndpoint) GetName() string {
func (e ConfigEndpoint) GetName() string {
return "ConfigEndpoint"
}
func (e configEndpoint) RegisterRoutes(g *gin.RouterGroup, _ *authenticationHandler) {
apiGroup := g.Group("/config")
func (e ConfigEndpoint) RegisterRoutes(g *routegroup.Bundle) {
apiGroup := g.Mount("/config")
apiGroup.GET("/frontend.js", e.handleConfigJsGet())
apiGroup.GET("/settings", e.authenticator.LoggedIn(), e.handleSettingsGet())
apiGroup.HandleFunc("GET /frontend.js", e.handleConfigJsGet())
apiGroup.With(e.authenticator.LoggedIn()).HandleFunc("GET /settings", e.handleSettingsGet())
}
// handleConfigJsGet returns a gorm handler function.
// handleConfigJsGet returns a gorm Handler function.
//
// @ID config_handleConfigJsGet
// @Tags Configuration
// @Summary Get the dynamic frontend configuration javascript.
// @Produce text/javascript
// @Success 200 string javascript "The JavaScript contents"
// @Failure 500
// @Router /config/frontend.js [get]
func (e configEndpoint) handleConfigJsGet() gin.HandlerFunc {
return func(c *gin.Context) {
backendUrl := fmt.Sprintf("%s/api/v0", e.app.Config.Web.ExternalUrl)
if c.GetHeader("x-wg-dev") != "" {
referer := c.Request.Header.Get("Referer")
func (e ConfigEndpoint) handleConfigJsGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
backendUrl := fmt.Sprintf("%s/api/v0", e.cfg.Web.ExternalUrl)
if request.Header(r, "x-wg-dev") != "" {
referer := request.Header(r, "Referer")
host := "localhost"
port := "5000"
parsedReferer, err := url.Parse(referer)
@@ -69,23 +72,17 @@ func (e configEndpoint) handleConfigJsGet() gin.HandlerFunc {
backendUrl = fmt.Sprintf("http://%s:%s/api/v0", host,
port) // override if request comes from frontend started with npm run dev
}
buf := &bytes.Buffer{}
err := e.tpl.ExecuteTemplate(buf, "frontend_config.js.gotpl", gin.H{
e.tpl.Render(w, http.StatusOK, "frontend_config.js.gotpl", "text/javascript", map[string]any{
"BackendUrl": backendUrl,
"Version": internal.Version,
"SiteTitle": e.app.Config.Web.SiteTitle,
"SiteCompanyName": e.app.Config.Web.SiteCompanyName,
"SiteTitle": e.cfg.Web.SiteTitle,
"SiteCompanyName": e.cfg.Web.SiteCompanyName,
})
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
c.Data(http.StatusOK, "application/javascript", buf.Bytes())
}
}
// handleSettingsGet returns a gorm handler function.
// handleSettingsGet returns a gorm Handler function.
//
// @ID config_handleSettingsGet
// @Tags Configuration
@@ -94,13 +91,13 @@ func (e configEndpoint) handleConfigJsGet() gin.HandlerFunc {
// @Success 200 {object} model.Settings
// @Success 200 string javascript "The JavaScript contents"
// @Router /config/settings [get]
func (e configEndpoint) handleSettingsGet() gin.HandlerFunc {
return func(c *gin.Context) {
c.JSON(http.StatusOK, model.Settings{
MailLinkOnly: e.app.Config.Mail.LinkOnly,
PersistentConfigSupported: e.app.Config.Advanced.ConfigStoragePath != "",
SelfProvisioning: e.app.Config.Core.SelfProvisioningAllowed,
ApiAdminOnly: e.app.Config.Advanced.ApiAdminOnly,
func (e ConfigEndpoint) handleSettingsGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
respond.JSON(w, http.StatusOK, model.Settings{
MailLinkOnly: e.cfg.Mail.LinkOnly,
PersistentConfigSupported: e.cfg.Advanced.ConfigStoragePath != "",
SelfProvisioning: e.cfg.Core.SelfProvisioningAllowed,
ApiAdminOnly: e.cfg.Advanced.ApiAdminOnly,
})
}
}

View File

@@ -4,39 +4,51 @@ import (
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-pkgz/routegroup"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/app/api/core/request"
"github.com/h44z/wg-portal/internal/app/api/core/respond"
"github.com/h44z/wg-portal/internal/app/api/v0/model"
"github.com/h44z/wg-portal/internal/domain"
)
type interfaceEndpoint struct {
type InterfaceEndpoint struct {
app *app.App
authenticator *authenticationHandler
authenticator Authenticator
validator Validator
}
func (e interfaceEndpoint) GetName() string {
func NewInterfaceEndpoint(app *app.App, authenticator Authenticator, validator Validator) InterfaceEndpoint {
return InterfaceEndpoint{
app: app,
authenticator: authenticator,
validator: validator,
}
}
func (e InterfaceEndpoint) GetName() string {
return "InterfaceEndpoint"
}
func (e interfaceEndpoint) RegisterRoutes(g *gin.RouterGroup, _ *authenticationHandler) {
apiGroup := g.Group("/interface", e.authenticator.LoggedIn(ScopeAdmin))
func (e InterfaceEndpoint) RegisterRoutes(g *routegroup.Bundle) {
apiGroup := g.Mount("/interface")
apiGroup.Use(e.authenticator.LoggedIn(ScopeAdmin))
apiGroup.GET("/prepare", e.handlePrepareGet())
apiGroup.GET("/all", e.handleAllGet())
apiGroup.GET("/get/:id", e.handleSingleGet())
apiGroup.PUT("/:id", e.handleUpdatePut())
apiGroup.DELETE("/:id", e.handleDelete())
apiGroup.POST("/new", e.handleCreatePost())
apiGroup.GET("/config/:id", e.handleConfigGet())
apiGroup.POST("/:id/save-config", e.handleSaveConfigPost())
apiGroup.POST("/:id/apply-peer-defaults", e.handleApplyPeerDefaultsPost())
apiGroup.HandleFunc("GET /prepare", e.handlePrepareGet())
apiGroup.HandleFunc("GET /all", e.handleAllGet())
apiGroup.HandleFunc("GET /get/{id}", e.handleSingleGet())
apiGroup.HandleFunc("PUT /{id}", e.handleUpdatePut())
apiGroup.HandleFunc("DELETE /{id}", e.handleDelete())
apiGroup.HandleFunc("POST /new", e.handleCreatePost())
apiGroup.HandleFunc("GET /config/{id}", e.handleConfigGet())
apiGroup.HandleFunc("POST /{id}/save-config", e.handleSaveConfigPost())
apiGroup.HandleFunc("POST /{id}/apply-peer-defaults", e.handleApplyPeerDefaultsPost())
apiGroup.GET("/peers/:id", e.handlePeersGet())
apiGroup.HandleFunc("GET /peers/{id}", e.handlePeersGet())
}
// handlePrepareGet returns a gorm handler function.
// handlePrepareGet returns a gorm Handler function.
//
// @ID interfaces_handlePrepareGet
// @Tags Interface
@@ -45,22 +57,21 @@ func (e interfaceEndpoint) RegisterRoutes(g *gin.RouterGroup, _ *authenticationH
// @Success 200 {object} model.Interface
// @Failure 500 {object} model.Error
// @Router /interface/prepare [get]
func (e interfaceEndpoint) handlePrepareGet() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
in, err := e.app.PrepareInterface(ctx)
func (e InterfaceEndpoint) handlePrepareGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
in, err := e.app.PrepareInterface(r.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error{
respond.JSON(w, http.StatusInternalServerError, model.Error{
Code: http.StatusInternalServerError, Message: err.Error(),
})
return
}
c.JSON(http.StatusOK, model.NewInterface(in, nil))
respond.JSON(w, http.StatusOK, model.NewInterface(in, nil))
}
}
// handleAllGet returns a gorm handler function.
// handleAllGet returns a gorm Handler function.
//
// @ID interfaces_handleAllGet
// @Tags Interface
@@ -69,22 +80,21 @@ func (e interfaceEndpoint) handlePrepareGet() gin.HandlerFunc {
// @Success 200 {object} []model.Interface
// @Failure 500 {object} model.Error
// @Router /interface/all [get]
func (e interfaceEndpoint) handleAllGet() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
interfaces, peers, err := e.app.GetAllInterfacesAndPeers(ctx)
func (e InterfaceEndpoint) handleAllGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
interfaces, peers, err := e.app.GetAllInterfacesAndPeers(r.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error{
respond.JSON(w, http.StatusInternalServerError, model.Error{
Code: http.StatusInternalServerError, Message: err.Error(),
})
return
}
c.JSON(http.StatusOK, model.NewInterfaces(interfaces, peers))
respond.JSON(w, http.StatusOK, model.NewInterfaces(interfaces, peers))
}
}
// handleSingleGet returns a gorm handler function.
// handleSingleGet returns a gorm Handler function.
//
// @ID interfaces_handleSingleGet
// @Tags Interface
@@ -94,30 +104,29 @@ func (e interfaceEndpoint) handleAllGet() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /interface/get/{id} [get]
func (e interfaceEndpoint) handleSingleGet() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
id := Base64UrlDecode(c.Param("id"))
func (e InterfaceEndpoint) handleSingleGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := Base64UrlDecode(request.Path(r, "id"))
if id == "" {
c.JSON(http.StatusBadRequest, model.Error{
respond.JSON(w, http.StatusBadRequest, model.Error{
Code: http.StatusInternalServerError, Message: "missing id parameter",
})
return
}
iface, peers, err := e.app.GetInterfaceAndPeers(ctx, domain.InterfaceIdentifier(id))
iface, peers, err := e.app.GetInterfaceAndPeers(r.Context(), domain.InterfaceIdentifier(id))
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error{
respond.JSON(w, http.StatusInternalServerError, model.Error{
Code: http.StatusInternalServerError, Message: err.Error(),
})
return
}
c.JSON(http.StatusOK, model.NewInterface(iface, peers))
respond.JSON(w, http.StatusOK, model.NewInterface(iface, peers))
}
}
// handleConfigGet returns a gorm handler function.
// handleConfigGet returns a gorm Handler function.
//
// @ID interfaces_handleConfigGet
// @Tags Interface
@@ -127,20 +136,19 @@ func (e interfaceEndpoint) handleSingleGet() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /interface/config/{id} [get]
func (e interfaceEndpoint) handleConfigGet() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
id := Base64UrlDecode(c.Param("id"))
func (e InterfaceEndpoint) handleConfigGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := Base64UrlDecode(request.Path(r, "id"))
if id == "" {
c.JSON(http.StatusBadRequest, model.Error{
respond.JSON(w, http.StatusBadRequest, model.Error{
Code: http.StatusInternalServerError, Message: "missing id parameter",
})
return
}
config, err := e.app.GetInterfaceConfig(ctx, domain.InterfaceIdentifier(id))
config, err := e.app.GetInterfaceConfig(r.Context(), domain.InterfaceIdentifier(id))
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error{
respond.JSON(w, http.StatusInternalServerError, model.Error{
Code: http.StatusInternalServerError, Message: err.Error(),
})
return
@@ -148,17 +156,17 @@ func (e interfaceEndpoint) handleConfigGet() gin.HandlerFunc {
configString, err := io.ReadAll(config)
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error{
respond.JSON(w, http.StatusInternalServerError, model.Error{
Code: http.StatusInternalServerError, Message: err.Error(),
})
return
}
c.JSON(http.StatusOK, string(configString))
respond.JSON(w, http.StatusOK, string(configString))
}
}
// handleUpdatePut returns a gorm handler function.
// handleUpdatePut returns a gorm Handler function.
//
// @ID interfaces_handleUpdatePut
// @Tags Interface
@@ -170,41 +178,44 @@ func (e interfaceEndpoint) handleConfigGet() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /interface/{id} [put]
func (e interfaceEndpoint) handleUpdatePut() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
id := Base64UrlDecode(c.Param("id"))
func (e InterfaceEndpoint) handleUpdatePut() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := Base64UrlDecode(request.Path(r, "id"))
if id == "" {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing interface id"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "missing interface id"})
return
}
var in model.Interface
err := c.BindJSON(&in)
if err != nil {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
if err := request.BodyJson(r, &in); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
if err := e.validator.Struct(in); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
if id != in.Identifier {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "interface id mismatch"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "interface id mismatch"})
return
}
updatedInterface, peers, err := e.app.UpdateInterface(ctx, model.NewDomainInterface(&in))
updatedInterface, peers, err := e.app.UpdateInterface(r.Context(), model.NewDomainInterface(&in))
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error{
respond.JSON(w, http.StatusInternalServerError, model.Error{
Code: http.StatusInternalServerError, Message: err.Error(),
})
return
}
c.JSON(http.StatusOK, model.NewInterface(updatedInterface, peers))
respond.JSON(w, http.StatusOK, model.NewInterface(updatedInterface, peers))
}
}
// handleCreatePost returns a gorm handler function.
// handleCreatePost returns a gorm Handler function.
//
// @ID interfaces_handleCreatePost
// @Tags Interface
@@ -215,30 +226,31 @@ func (e interfaceEndpoint) handleUpdatePut() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /interface/new [post]
func (e interfaceEndpoint) handleCreatePost() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
func (e InterfaceEndpoint) handleCreatePost() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var in model.Interface
err := c.BindJSON(&in)
if err != nil {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
if err := request.BodyJson(r, &in); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
if err := e.validator.Struct(in); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
newInterface, err := e.app.CreateInterface(ctx, model.NewDomainInterface(&in))
newInterface, err := e.app.CreateInterface(r.Context(), model.NewDomainInterface(&in))
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error{
respond.JSON(w, http.StatusInternalServerError, model.Error{
Code: http.StatusInternalServerError, Message: err.Error(),
})
return
}
c.JSON(http.StatusOK, model.NewInterface(newInterface, nil))
respond.JSON(w, http.StatusOK, model.NewInterface(newInterface, nil))
}
}
// handlePeersGet returns a gorm handler function.
// handlePeersGet returns a gorm Handler function.
//
// @ID interfaces_handlePeersGet
// @Tags Interface
@@ -247,31 +259,29 @@ func (e interfaceEndpoint) handleCreatePost() gin.HandlerFunc {
// @Success 200 {object} []model.Peer
// @Failure 500 {object} model.Error
// @Router /interface/peers/{id} [get]
func (e interfaceEndpoint) handlePeersGet() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
id := Base64UrlDecode(c.Param("id"))
func (e InterfaceEndpoint) handlePeersGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := Base64UrlDecode(request.Path(r, "id"))
if id == "" {
c.JSON(http.StatusBadRequest, model.Error{
respond.JSON(w, http.StatusBadRequest, model.Error{
Code: http.StatusInternalServerError, Message: "missing id parameter",
})
return
}
_, peers, err := e.app.GetInterfaceAndPeers(ctx, domain.InterfaceIdentifier(id))
_, peers, err := e.app.GetInterfaceAndPeers(r.Context(), domain.InterfaceIdentifier(id))
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error{
respond.JSON(w, http.StatusInternalServerError, model.Error{
Code: http.StatusInternalServerError, Message: err.Error(),
})
return
}
c.JSON(http.StatusOK, model.NewPeers(peers))
respond.JSON(w, http.StatusOK, model.NewPeers(peers))
}
}
// handleDelete returns a gorm handler function.
// handleDelete returns a gorm Handler function.
//
// @ID interfaces_handleDelete
// @Tags Interface
@@ -282,29 +292,28 @@ func (e interfaceEndpoint) handlePeersGet() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /interface/{id} [delete]
func (e interfaceEndpoint) handleDelete() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
id := Base64UrlDecode(c.Param("id"))
func (e InterfaceEndpoint) handleDelete() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := Base64UrlDecode(request.Path(r, "id"))
if id == "" {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing interface id"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "missing interface id"})
return
}
err := e.app.DeleteInterface(ctx, domain.InterfaceIdentifier(id))
err := e.app.DeleteInterface(r.Context(), domain.InterfaceIdentifier(id))
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error{
respond.JSON(w, http.StatusInternalServerError, model.Error{
Code: http.StatusInternalServerError, Message: err.Error(),
})
return
}
c.Status(http.StatusNoContent)
respond.Status(w, http.StatusNoContent)
}
}
// handleSaveConfigPost returns a gorm handler function.
// handleSaveConfigPost returns a gorm Handler function.
//
// @ID interfaces_handleSaveConfigPost
// @Tags Interface
@@ -315,29 +324,28 @@ func (e interfaceEndpoint) handleDelete() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /interface/{id}/save-config [post]
func (e interfaceEndpoint) handleSaveConfigPost() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
id := Base64UrlDecode(c.Param("id"))
func (e InterfaceEndpoint) handleSaveConfigPost() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := Base64UrlDecode(request.Path(r, "id"))
if id == "" {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing interface id"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "missing interface id"})
return
}
err := e.app.PersistInterfaceConfig(ctx, domain.InterfaceIdentifier(id))
err := e.app.PersistInterfaceConfig(r.Context(), domain.InterfaceIdentifier(id))
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error{
respond.JSON(w, http.StatusInternalServerError, model.Error{
Code: http.StatusInternalServerError, Message: err.Error(),
})
return
}
c.Status(http.StatusNoContent)
respond.Status(w, http.StatusNoContent)
}
}
// handleApplyPeerDefaultsPost returns a gorm handler function.
// handleApplyPeerDefaultsPost returns a gorm Handler function.
//
// @ID interfaces_handleApplyPeerDefaultsPost
// @Tags Interface
@@ -349,36 +357,38 @@ func (e interfaceEndpoint) handleSaveConfigPost() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /interface/{id}/apply-peer-defaults [post]
func (e interfaceEndpoint) handleApplyPeerDefaultsPost() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
id := Base64UrlDecode(c.Param("id"))
func (e InterfaceEndpoint) handleApplyPeerDefaultsPost() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := Base64UrlDecode(request.Path(r, "id"))
if id == "" {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing interface id"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "missing interface id"})
return
}
var in model.Interface
err := c.BindJSON(&in)
if err != nil {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
if err := request.BodyJson(r, &in); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
if err := e.validator.Struct(in); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
if id != in.Identifier {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "interface id mismatch"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "interface id mismatch"})
return
}
err = e.app.ApplyPeerDefaults(ctx, model.NewDomainInterface(&in))
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error{
if err := e.app.ApplyPeerDefaults(r.Context(), model.NewDomainInterface(&in)); err != nil {
respond.JSON(w, http.StatusInternalServerError, model.Error{
Code: http.StatusInternalServerError, Message: err.Error(),
})
return
}
c.Status(http.StatusNoContent)
respond.Status(w, http.StatusNoContent)
}
}

View File

@@ -4,39 +4,52 @@ import (
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-pkgz/routegroup"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/app/api/core/request"
"github.com/h44z/wg-portal/internal/app/api/core/respond"
"github.com/h44z/wg-portal/internal/app/api/v0/model"
"github.com/h44z/wg-portal/internal/domain"
)
type peerEndpoint struct {
type PeerEndpoint struct {
app *app.App
authenticator *authenticationHandler
authenticator Authenticator
validator Validator
}
func (e peerEndpoint) GetName() string {
func NewPeerEndpoint(app *app.App, authenticator Authenticator, validator Validator) PeerEndpoint {
return PeerEndpoint{
app: app,
authenticator: authenticator,
validator: validator,
}
}
func (e PeerEndpoint) GetName() string {
return "PeerEndpoint"
}
func (e peerEndpoint) RegisterRoutes(g *gin.RouterGroup, _ *authenticationHandler) {
apiGroup := g.Group("/peer", e.authenticator.LoggedIn())
func (e PeerEndpoint) RegisterRoutes(g *routegroup.Bundle) {
apiGroup := g.Mount("/peer")
apiGroup.Use(e.authenticator.LoggedIn())
apiGroup.GET("/iface/:iface/all", e.authenticator.LoggedIn(ScopeAdmin), e.handleAllGet())
apiGroup.GET("/iface/:iface/stats", e.authenticator.LoggedIn(ScopeAdmin), e.handleStatsGet())
apiGroup.GET("/iface/:iface/prepare", e.authenticator.LoggedIn(), e.handlePrepareGet())
apiGroup.POST("/iface/:iface/new", e.authenticator.LoggedIn(), e.handleCreatePost())
apiGroup.POST("/iface/:iface/multiplenew", e.authenticator.LoggedIn(ScopeAdmin), e.handleCreateMultiplePost())
apiGroup.GET("/config-qr/:id", e.handleQrCodeGet())
apiGroup.POST("/config-mail", e.handleEmailPost())
apiGroup.GET("/config/:id", e.handleConfigGet())
apiGroup.GET("/:id", e.handleSingleGet())
apiGroup.PUT("/:id", e.handleUpdatePut())
apiGroup.DELETE("/:id", e.handleDelete())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin)).HandleFunc("GET /iface/{iface}/all", e.handleAllGet())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin)).HandleFunc("GET /iface/{iface}/stats", e.handleStatsGet())
apiGroup.HandleFunc("GET /iface/{iface}/prepare", e.handlePrepareGet())
apiGroup.HandleFunc("POST /iface/{iface}/new", e.handleCreatePost())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin)).HandleFunc("POST /iface/{iface}/multiplenew",
e.handleCreateMultiplePost())
apiGroup.HandleFunc("GET /config-qr/{id}", e.handleQrCodeGet())
apiGroup.HandleFunc("POST /config-mail", e.handleEmailPost())
apiGroup.HandleFunc("GET /config/{id}", e.handleConfigGet())
apiGroup.HandleFunc("GET /{id}", e.handleSingleGet())
apiGroup.HandleFunc("PUT /{id}", e.handleUpdatePut())
apiGroup.HandleFunc("DELETE /{id}", e.handleDelete())
}
// handleAllGet returns a gorm handler function.
// handleAllGet returns a gorm Handler function.
//
// @ID peers_handleAllGet
// @Tags Peer
@@ -47,28 +60,27 @@ func (e peerEndpoint) RegisterRoutes(g *gin.RouterGroup, _ *authenticationHandle
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /peer/iface/{iface}/all [get]
func (e peerEndpoint) handleAllGet() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
interfaceId := Base64UrlDecode(c.Param("iface"))
func (e PeerEndpoint) handleAllGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
interfaceId := Base64UrlDecode(request.Path(r, "iface"))
if interfaceId == "" {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing iface parameter"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "missing iface parameter"})
return
}
_, peers, err := e.app.GetInterfaceAndPeers(ctx, domain.InterfaceIdentifier(interfaceId))
_, peers, err := e.app.GetInterfaceAndPeers(r.Context(), domain.InterfaceIdentifier(interfaceId))
if err != nil {
c.JSON(http.StatusInternalServerError,
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
c.JSON(http.StatusOK, model.NewPeers(peers))
respond.JSON(w, http.StatusOK, model.NewPeers(peers))
}
}
// handleSingleGet returns a gorm handler function.
// handleSingleGet returns a gorm Handler function.
//
// @ID peers_handleSingleGet
// @Tags Peer
@@ -79,28 +91,27 @@ func (e peerEndpoint) handleAllGet() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /peer/{id} [get]
func (e peerEndpoint) handleSingleGet() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
peerId := Base64UrlDecode(c.Param("id"))
func (e PeerEndpoint) handleSingleGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
peerId := Base64UrlDecode(request.Path(r, "id"))
if peerId == "" {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing id parameter"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "missing id parameter"})
return
}
peer, err := e.app.GetPeer(ctx, domain.PeerIdentifier(peerId))
peer, err := e.app.GetPeer(r.Context(), domain.PeerIdentifier(peerId))
if err != nil {
c.JSON(http.StatusInternalServerError,
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
c.JSON(http.StatusOK, model.NewPeer(peer))
respond.JSON(w, http.StatusOK, model.NewPeer(peer))
}
}
// handlePrepareGet returns a gorm handler function.
// handlePrepareGet returns a gorm Handler function.
//
// @ID peers_handlePrepareGet
// @Tags Peer
@@ -111,28 +122,27 @@ func (e peerEndpoint) handleSingleGet() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /peer/iface/{iface}/prepare [get]
func (e peerEndpoint) handlePrepareGet() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
interfaceId := Base64UrlDecode(c.Param("iface"))
func (e PeerEndpoint) handlePrepareGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
interfaceId := Base64UrlDecode(request.Path(r, "iface"))
if interfaceId == "" {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing iface parameter"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "missing iface parameter"})
return
}
peer, err := e.app.PreparePeer(ctx, domain.InterfaceIdentifier(interfaceId))
peer, err := e.app.PreparePeer(r.Context(), domain.InterfaceIdentifier(interfaceId))
if err != nil {
c.JSON(http.StatusInternalServerError,
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
c.JSON(http.StatusOK, model.NewPeer(peer))
respond.JSON(w, http.StatusOK, model.NewPeer(peer))
}
}
// handleCreatePost returns a gorm handler function.
// handleCreatePost returns a gorm Handler function.
//
// @ID peers_handleCreatePost
// @Tags Peer
@@ -144,40 +154,43 @@ func (e peerEndpoint) handlePrepareGet() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /peer/iface/{iface}/new [post]
func (e peerEndpoint) handleCreatePost() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
interfaceId := Base64UrlDecode(c.Param("iface"))
func (e PeerEndpoint) handleCreatePost() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
interfaceId := Base64UrlDecode(request.Path(r, "iface"))
if interfaceId == "" {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing iface parameter"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "missing iface parameter"})
return
}
var p model.Peer
err := c.BindJSON(&p)
if err != nil {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
if err := request.BodyJson(r, &p); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
if err := e.validator.Struct(p); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
if p.InterfaceIdentifier != interfaceId {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "interface id mismatch"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "interface id mismatch"})
return
}
newPeer, err := e.app.CreatePeer(ctx, model.NewDomainPeer(&p))
newPeer, err := e.app.CreatePeer(r.Context(), model.NewDomainPeer(&p))
if err != nil {
c.JSON(http.StatusInternalServerError,
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
c.JSON(http.StatusOK, model.NewPeer(newPeer))
respond.JSON(w, http.StatusOK, model.NewPeer(newPeer))
}
}
// handleCreateMultiplePost returns a gorm handler function.
// handleCreateMultiplePost returns a gorm Handler function.
//
// @ID peers_handleCreateMultiplePost
// @Tags Peer
@@ -189,36 +202,38 @@ func (e peerEndpoint) handleCreatePost() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /peer/iface/{iface}/multiplenew [post]
func (e peerEndpoint) handleCreateMultiplePost() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
interfaceId := Base64UrlDecode(c.Param("iface"))
func (e PeerEndpoint) handleCreateMultiplePost() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
interfaceId := Base64UrlDecode(request.Path(r, "iface"))
if interfaceId == "" {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing iface parameter"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "missing iface parameter"})
return
}
var req model.MultiPeerRequest
err := c.BindJSON(&req)
if err != nil {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
if err := request.BodyJson(r, &req); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
if err := e.validator.Struct(req); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
newPeers, err := e.app.CreateMultiplePeers(ctx, domain.InterfaceIdentifier(interfaceId),
newPeers, err := e.app.CreateMultiplePeers(r.Context(), domain.InterfaceIdentifier(interfaceId),
model.NewDomainPeerCreationRequest(&req))
if err != nil {
c.JSON(http.StatusInternalServerError,
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
c.JSON(http.StatusOK, model.NewPeers(newPeers))
respond.JSON(w, http.StatusOK, model.NewPeers(newPeers))
}
}
// handleUpdatePut returns a gorm handler function.
// handleUpdatePut returns a gorm Handler function.
//
// @ID peers_handleUpdatePut
// @Tags Peer
@@ -230,40 +245,43 @@ func (e peerEndpoint) handleCreateMultiplePost() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /peer/{id} [put]
func (e peerEndpoint) handleUpdatePut() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
peerId := Base64UrlDecode(c.Param("id"))
func (e PeerEndpoint) handleUpdatePut() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
peerId := Base64UrlDecode(request.Path(r, "id"))
if peerId == "" {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing id parameter"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "missing id parameter"})
return
}
var p model.Peer
err := c.BindJSON(&p)
if err != nil {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
if err := request.BodyJson(r, &p); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
if err := e.validator.Struct(p); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
if p.Identifier != peerId {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "peer id mismatch"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "peer id mismatch"})
return
}
updatedPeer, err := e.app.UpdatePeer(ctx, model.NewDomainPeer(&p))
updatedPeer, err := e.app.UpdatePeer(r.Context(), model.NewDomainPeer(&p))
if err != nil {
c.JSON(http.StatusInternalServerError,
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
c.JSON(http.StatusOK, model.NewPeer(updatedPeer))
respond.JSON(w, http.StatusOK, model.NewPeer(updatedPeer))
}
}
// handleDelete returns a gorm handler function.
// handleDelete returns a gorm Handler function.
//
// @ID peers_handleDelete
// @Tags Peer
@@ -274,28 +292,26 @@ func (e peerEndpoint) handleUpdatePut() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /peer/{id} [delete]
func (e peerEndpoint) handleDelete() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
id := Base64UrlDecode(c.Param("id"))
func (e PeerEndpoint) handleDelete() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := Base64UrlDecode(request.Path(r, "id"))
if id == "" {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing peer id"})
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing peer id"})
return
}
err := e.app.DeletePeer(ctx, domain.PeerIdentifier(id))
err := e.app.DeletePeer(r.Context(), domain.PeerIdentifier(id))
if err != nil {
c.JSON(http.StatusInternalServerError,
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
c.Status(http.StatusNoContent)
respond.Status(w, http.StatusNoContent)
}
}
// handleConfigGet returns a gorm handler function.
// handleConfigGet returns a gorm Handler function.
//
// @ID peers_handleConfigGet
// @Tags Peer
@@ -306,21 +322,19 @@ func (e peerEndpoint) handleDelete() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /peer/config/{id} [get]
func (e peerEndpoint) handleConfigGet() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
id := Base64UrlDecode(c.Param("id"))
func (e PeerEndpoint) handleConfigGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := Base64UrlDecode(request.Path(r, "id"))
if id == "" {
c.JSON(http.StatusBadRequest, model.Error{
respond.JSON(w, http.StatusBadRequest, model.Error{
Code: http.StatusInternalServerError, Message: "missing id parameter",
})
return
}
config, err := e.app.GetPeerConfig(ctx, domain.PeerIdentifier(id))
config, err := e.app.GetPeerConfig(r.Context(), domain.PeerIdentifier(id))
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error{
respond.JSON(w, http.StatusInternalServerError, model.Error{
Code: http.StatusInternalServerError, Message: err.Error(),
})
return
@@ -328,17 +342,17 @@ func (e peerEndpoint) handleConfigGet() gin.HandlerFunc {
configString, err := io.ReadAll(config)
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error{
respond.JSON(w, http.StatusInternalServerError, model.Error{
Code: http.StatusInternalServerError, Message: err.Error(),
})
return
}
c.JSON(http.StatusOK, string(configString))
respond.JSON(w, http.StatusOK, string(configString))
}
}
// handleQrCodeGet returns a gorm handler function.
// handleQrCodeGet returns a gorm Handler function.
//
// @ID peers_handleQrCodeGet
// @Tags Peer
@@ -350,20 +364,19 @@ func (e peerEndpoint) handleConfigGet() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /peer/config-qr/{id} [get]
func (e peerEndpoint) handleQrCodeGet() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
id := Base64UrlDecode(c.Param("id"))
func (e PeerEndpoint) handleQrCodeGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := Base64UrlDecode(request.Path(r, "id"))
if id == "" {
c.JSON(http.StatusBadRequest, model.Error{
respond.JSON(w, http.StatusBadRequest, model.Error{
Code: http.StatusInternalServerError, Message: "missing id parameter",
})
return
}
config, err := e.app.GetPeerConfigQrCode(ctx, domain.PeerIdentifier(id))
config, err := e.app.GetPeerConfigQrCode(r.Context(), domain.PeerIdentifier(id))
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error{
respond.JSON(w, http.StatusInternalServerError, model.Error{
Code: http.StatusInternalServerError, Message: err.Error(),
})
return
@@ -371,17 +384,17 @@ func (e peerEndpoint) handleQrCodeGet() gin.HandlerFunc {
configData, err := io.ReadAll(config)
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error{
respond.JSON(w, http.StatusInternalServerError, model.Error{
Code: http.StatusInternalServerError, Message: err.Error(),
})
return
}
c.Data(http.StatusOK, "image/png", configData)
respond.Data(w, http.StatusOK, "image/png", configData)
}
}
// handleEmailPost returns a gorm handler function.
// handleEmailPost returns a gorm Handler function.
//
// @ID peers_handleEmailPost
// @Tags Peer
@@ -392,38 +405,39 @@ func (e peerEndpoint) handleQrCodeGet() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /peer/config-mail [post]
func (e peerEndpoint) handleEmailPost() gin.HandlerFunc {
return func(c *gin.Context) {
func (e PeerEndpoint) handleEmailPost() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req model.PeerMailRequest
err := c.BindJSON(&req)
if err != nil {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
if err := request.BodyJson(r, &req); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
if err := e.validator.Struct(req); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
if len(req.Identifiers) == 0 {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing peer identifiers"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "missing peer identifiers"})
return
}
ctx := domain.SetUserInfoFromGin(c)
peerIds := make([]domain.PeerIdentifier, len(req.Identifiers))
for i := range req.Identifiers {
peerIds[i] = domain.PeerIdentifier(req.Identifiers[i])
}
err = e.app.SendPeerEmail(ctx, req.LinkOnly, peerIds...)
if err != nil {
c.JSON(http.StatusInternalServerError,
if err := e.app.SendPeerEmail(r.Context(), req.LinkOnly, peerIds...); err != nil {
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
c.Status(http.StatusNoContent)
respond.Status(w, http.StatusNoContent)
}
}
// handleStatsGet returns a gorm handler function.
// handleStatsGet returns a gorm Handler function.
//
// @ID peers_handleStatsGet
// @Tags Peer
@@ -434,23 +448,22 @@ func (e peerEndpoint) handleEmailPost() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /peer/iface/{iface}/stats [get]
func (e peerEndpoint) handleStatsGet() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
interfaceId := Base64UrlDecode(c.Param("iface"))
func (e PeerEndpoint) handleStatsGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
interfaceId := Base64UrlDecode(request.Path(r, "iface"))
if interfaceId == "" {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing iface parameter"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "missing iface parameter"})
return
}
stats, err := e.app.GetPeerStats(ctx, domain.InterfaceIdentifier(interfaceId))
stats, err := e.app.GetPeerStats(r.Context(), domain.InterfaceIdentifier(interfaceId))
if err != nil {
c.JSON(http.StatusInternalServerError,
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
c.JSON(http.StatusOK, model.NewPeerStats(e.app.Config.Statistics.CollectPeerData, stats))
respond.JSON(w, http.StatusOK, model.NewPeerStats(e.app.Config.Statistics.CollectPeerData, stats))
}
}

View File

@@ -5,20 +5,29 @@ import (
"os"
"time"
"github.com/gin-gonic/gin"
"github.com/go-pkgz/routegroup"
"github.com/h44z/wg-portal/internal/app/api/core/respond"
"github.com/h44z/wg-portal/internal/app/api/v0/model"
)
type testEndpoint struct{}
type TestEndpoint struct {
authenticator Authenticator
}
func (e testEndpoint) GetName() string {
func NewTestEndpoint(authenticator Authenticator) TestEndpoint {
return TestEndpoint{
authenticator: authenticator,
}
}
func (e TestEndpoint) GetName() string {
return "TestEndpoint"
}
func (e testEndpoint) RegisterRoutes(g *gin.RouterGroup, _ *authenticationHandler) {
g.GET("/now", e.handleCurrentTimeGet())
g.GET("/hostname", e.handleHostnameGet())
func (e TestEndpoint) RegisterRoutes(g *routegroup.Bundle) {
g.HandleFunc("GET /now", e.handleCurrentTimeGet())
g.With(e.authenticator.LoggedIn(ScopeAdmin)).HandleFunc("GET /hostname", e.handleHostnameGet())
}
// handleCurrentTimeGet represents the GET endpoint that responds the current time
@@ -31,15 +40,15 @@ func (e testEndpoint) RegisterRoutes(g *gin.RouterGroup, _ *authenticationHandle
// @Success 200 {object} string
// @Failure 500 {object} model.Error
// @Router /now [get]
func (e testEndpoint) handleCurrentTimeGet() gin.HandlerFunc {
return func(c *gin.Context) {
func (e TestEndpoint) handleCurrentTimeGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if time.Now().Second() == 0 {
c.JSON(http.StatusInternalServerError, model.Error{
respond.JSON(w, http.StatusInternalServerError, model.Error{
Code: http.StatusInternalServerError,
Message: "invalid time",
})
}
c.JSON(http.StatusOK, time.Now().String())
respond.JSON(w, http.StatusOK, time.Now().String())
}
}
@@ -53,15 +62,15 @@ func (e testEndpoint) handleCurrentTimeGet() gin.HandlerFunc {
// @Success 200 {object} string
// @Failure 500 {object} model.Error
// @Router /hostname [get]
func (e testEndpoint) handleHostnameGet() gin.HandlerFunc {
return func(c *gin.Context) {
func (e TestEndpoint) handleHostnameGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
hostname, err := os.Hostname()
if err != nil {
c.JSON(http.StatusInternalServerError, model.Error{
respond.JSON(w, http.StatusInternalServerError, model.Error{
Code: http.StatusInternalServerError,
Message: err.Error(),
})
}
c.JSON(http.StatusOK, hostname)
respond.JSON(w, http.StatusOK, hostname)
}
}

View File

@@ -3,38 +3,50 @@ package handlers
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-pkgz/routegroup"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/app/api/core/request"
"github.com/h44z/wg-portal/internal/app/api/core/respond"
"github.com/h44z/wg-portal/internal/app/api/v0/model"
"github.com/h44z/wg-portal/internal/domain"
)
type userEndpoint struct {
type UserEndpoint struct {
app *app.App
authenticator *authenticationHandler
authenticator Authenticator
validator Validator
}
func (e userEndpoint) GetName() string {
func NewUserEndpoint(app *app.App, authenticator Authenticator, validator Validator) UserEndpoint {
return UserEndpoint{
app: app,
authenticator: authenticator,
validator: validator,
}
}
func (e UserEndpoint) GetName() string {
return "UserEndpoint"
}
func (e userEndpoint) RegisterRoutes(g *gin.RouterGroup, _ *authenticationHandler) {
apiGroup := g.Group("/user", e.authenticator.LoggedIn())
func (e UserEndpoint) RegisterRoutes(g *routegroup.Bundle) {
apiGroup := g.Mount("/user")
apiGroup.Use(e.authenticator.LoggedIn())
apiGroup.GET("/all", e.authenticator.LoggedIn(ScopeAdmin), e.handleAllGet())
apiGroup.GET("/:id", e.authenticator.UserIdMatch("id"), e.handleSingleGet())
apiGroup.PUT("/:id", e.authenticator.UserIdMatch("id"), e.handleUpdatePut())
apiGroup.DELETE("/:id", e.authenticator.UserIdMatch("id"), e.handleDelete())
apiGroup.POST("/new", e.authenticator.LoggedIn(ScopeAdmin), e.handleCreatePost())
apiGroup.GET("/:id/peers", e.authenticator.UserIdMatch("id"), e.handlePeersGet())
apiGroup.GET("/:id/stats", e.authenticator.UserIdMatch("id"), e.handleStatsGet())
apiGroup.GET("/:id/interfaces", e.authenticator.UserIdMatch("id"), e.handleInterfacesGet())
apiGroup.POST("/:id/api/enable", e.authenticator.UserIdMatch("id"), e.handleApiEnablePost())
apiGroup.POST("/:id/api/disable", e.authenticator.UserIdMatch("id"), e.handleApiDisablePost())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin)).HandleFunc("GET /all", e.handleAllGet())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("GET /{id}", e.handleSingleGet())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("PUT /{id}", e.handleUpdatePut())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("DELETE /{id}", e.handleDelete())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin)).HandleFunc("POST /new", e.handleCreatePost())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("GET /{id}/peers", e.handlePeersGet())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("GET /{id}/stats", e.handleStatsGet())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("GET /{id}/interfaces", e.handleInterfacesGet())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("POST /{id}/api/enable", e.handleApiEnablePost())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("POST /{id}/api/disable", e.handleApiDisablePost())
}
// handleAllGet returns a gorm handler function.
// handleAllGet returns a gorm Handler function.
//
// @ID users_handleAllGet
// @Tags Users
@@ -43,22 +55,20 @@ func (e userEndpoint) RegisterRoutes(g *gin.RouterGroup, _ *authenticationHandle
// @Success 200 {object} []model.User
// @Failure 500 {object} model.Error
// @Router /user/all [get]
func (e userEndpoint) handleAllGet() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
users, err := e.app.GetAllUsers(ctx)
func (e UserEndpoint) handleAllGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
users, err := e.app.GetAllUsers(r.Context())
if err != nil {
c.JSON(http.StatusInternalServerError,
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
c.JSON(http.StatusOK, model.NewUsers(users))
respond.JSON(w, http.StatusOK, model.NewUsers(users))
}
}
// handleSingleGet returns a gorm handler function.
// handleSingleGet returns a gorm Handler function.
//
// @ID users_handleSingleGet
// @Tags Users
@@ -68,28 +78,26 @@ func (e userEndpoint) handleAllGet() gin.HandlerFunc {
// @Success 200 {object} model.User
// @Failure 500 {object} model.Error
// @Router /user/{id} [get]
func (e userEndpoint) handleSingleGet() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
id := Base64UrlDecode(c.Param("id"))
func (e UserEndpoint) handleSingleGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := Base64UrlDecode(request.Path(r, "id"))
if id == "" {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing user id"})
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing user id"})
return
}
user, err := e.app.GetUser(ctx, domain.UserIdentifier(id))
user, err := e.app.GetUser(r.Context(), domain.UserIdentifier(id))
if err != nil {
c.JSON(http.StatusInternalServerError,
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
c.JSON(http.StatusOK, model.NewUser(user, true))
respond.JSON(w, http.StatusOK, model.NewUser(user, true))
}
}
// handleUpdatePut returns a gorm handler function.
// handleUpdatePut returns a gorm Handler function.
//
// @ID users_handleUpdatePut
// @Tags Users
@@ -101,40 +109,42 @@ func (e userEndpoint) handleSingleGet() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /user/{id} [put]
func (e userEndpoint) handleUpdatePut() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
id := Base64UrlDecode(c.Param("id"))
func (e UserEndpoint) handleUpdatePut() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := Base64UrlDecode(request.Path(r, "id"))
if id == "" {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing user id"})
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing user id"})
return
}
var user model.User
err := c.BindJSON(&user)
if err != nil {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
if err := request.BodyJson(r, &user); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
if err := e.validator.Struct(user); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
if id != user.Identifier {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "user id mismatch"})
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusBadRequest, Message: "user id mismatch"})
return
}
updateUser, err := e.app.UpdateUser(ctx, model.NewDomainUser(&user))
updateUser, err := e.app.UpdateUser(r.Context(), model.NewDomainUser(&user))
if err != nil {
c.JSON(http.StatusInternalServerError,
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
c.JSON(http.StatusOK, model.NewUser(updateUser, false))
respond.JSON(w, http.StatusOK, model.NewUser(updateUser, false))
}
}
// handleCreatePost returns a gorm handler function.
// handleCreatePost returns a gorm Handler function.
//
// @ID users_handleCreatePost
// @Tags Users
@@ -145,29 +155,30 @@ func (e userEndpoint) handleUpdatePut() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /user/new [post]
func (e userEndpoint) handleCreatePost() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
func (e UserEndpoint) handleCreatePost() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var user model.User
err := c.BindJSON(&user)
if err != nil {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
if err := request.BodyJson(r, &user); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
if err := e.validator.Struct(user); err != nil {
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
return
}
newUser, err := e.app.CreateUser(ctx, model.NewDomainUser(&user))
newUser, err := e.app.CreateUser(r.Context(), model.NewDomainUser(&user))
if err != nil {
c.JSON(http.StatusInternalServerError,
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
c.JSON(http.StatusOK, model.NewUser(newUser, false))
respond.JSON(w, http.StatusOK, model.NewUser(newUser, false))
}
}
// handlePeersGet returns a gorm handler function.
// handlePeersGet returns a gorm Handler function.
//
// @ID users_handlePeersGet
// @Tags Users
@@ -178,29 +189,27 @@ func (e userEndpoint) handleCreatePost() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /user/{id}/peers [get]
func (e userEndpoint) handlePeersGet() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
userId := Base64UrlDecode(c.Param("id"))
func (e UserEndpoint) handlePeersGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userId := Base64UrlDecode(request.Path(r, "id"))
if userId == "" {
c.JSON(http.StatusBadRequest,
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusInternalServerError, Message: "missing id parameter"})
return
}
peers, err := e.app.GetUserPeers(ctx, domain.UserIdentifier(userId))
peers, err := e.app.GetUserPeers(r.Context(), domain.UserIdentifier(userId))
if err != nil {
c.JSON(http.StatusInternalServerError,
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
c.JSON(http.StatusOK, model.NewPeers(peers))
respond.JSON(w, http.StatusOK, model.NewPeers(peers))
}
}
// handleStatsGet returns a gorm handler function.
// handleStatsGet returns a gorm Handler function.
//
// @ID users_handleStatsGet
// @Tags Users
@@ -211,29 +220,27 @@ func (e userEndpoint) handlePeersGet() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /user/{id}/stats [get]
func (e userEndpoint) handleStatsGet() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
userId := Base64UrlDecode(c.Param("id"))
func (e UserEndpoint) handleStatsGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userId := Base64UrlDecode(request.Path(r, "id"))
if userId == "" {
c.JSON(http.StatusBadRequest,
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusInternalServerError, Message: "missing id parameter"})
return
}
stats, err := e.app.GetUserPeerStats(ctx, domain.UserIdentifier(userId))
stats, err := e.app.GetUserPeerStats(r.Context(), domain.UserIdentifier(userId))
if err != nil {
c.JSON(http.StatusInternalServerError,
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
c.JSON(http.StatusOK, model.NewPeerStats(e.app.Config.Statistics.CollectPeerData, stats))
respond.JSON(w, http.StatusOK, model.NewPeerStats(e.app.Config.Statistics.CollectPeerData, stats))
}
}
// handleInterfacesGet returns a gorm handler function.
// handleInterfacesGet returns a gorm Handler function.
//
// @ID users_handleInterfacesGet
// @Tags Users
@@ -244,29 +251,27 @@ func (e userEndpoint) handleStatsGet() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /user/{id}/interfaces [get]
func (e userEndpoint) handleInterfacesGet() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
userId := Base64UrlDecode(c.Param("id"))
func (e UserEndpoint) handleInterfacesGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userId := Base64UrlDecode(request.Path(r, "id"))
if userId == "" {
c.JSON(http.StatusBadRequest,
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusInternalServerError, Message: "missing id parameter"})
return
}
peers, err := e.app.GetUserInterfaces(ctx, domain.UserIdentifier(userId))
peers, err := e.app.GetUserInterfaces(r.Context(), domain.UserIdentifier(userId))
if err != nil {
c.JSON(http.StatusInternalServerError,
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
c.JSON(http.StatusOK, model.NewInterfaces(peers, nil))
respond.JSON(w, http.StatusOK, model.NewInterfaces(peers, nil))
}
}
// handleDelete returns a gorm handler function.
// handleDelete returns a gorm Handler function.
//
// @ID users_handleDelete
// @Tags Users
@@ -277,28 +282,26 @@ func (e userEndpoint) handleInterfacesGet() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /user/{id} [delete]
func (e userEndpoint) handleDelete() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
id := Base64UrlDecode(c.Param("id"))
func (e UserEndpoint) handleDelete() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := Base64UrlDecode(request.Path(r, "id"))
if id == "" {
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing user id"})
respond.JSON(w, http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing user id"})
return
}
err := e.app.DeleteUser(ctx, domain.UserIdentifier(id))
err := e.app.DeleteUser(r.Context(), domain.UserIdentifier(id))
if err != nil {
c.JSON(http.StatusInternalServerError,
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
c.Status(http.StatusNoContent)
respond.Status(w, http.StatusNoContent)
}
}
// handleApiEnablePost returns a gorm handler function.
// handleApiEnablePost returns a gorm Handler function.
//
// @ID users_handleApiEnablePost
// @Tags Users
@@ -308,29 +311,27 @@ func (e userEndpoint) handleDelete() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /user/{id}/api/enable [post]
func (e userEndpoint) handleApiEnablePost() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
userId := Base64UrlDecode(c.Param("id"))
func (e UserEndpoint) handleApiEnablePost() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userId := Base64UrlDecode(request.Path(r, "id"))
if userId == "" {
c.JSON(http.StatusBadRequest,
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusInternalServerError, Message: "missing id parameter"})
return
}
user, err := e.app.ActivateApi(ctx, domain.UserIdentifier(userId))
user, err := e.app.ActivateApi(r.Context(), domain.UserIdentifier(userId))
if err != nil {
c.JSON(http.StatusInternalServerError,
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
c.JSON(http.StatusOK, model.NewUser(user, true))
respond.JSON(w, http.StatusOK, model.NewUser(user, true))
}
}
// handleApiDisablePost returns a gorm handler function.
// handleApiDisablePost returns a gorm Handler function.
//
// @ID users_handleApiDisablePost
// @Tags Users
@@ -340,24 +341,22 @@ func (e userEndpoint) handleApiEnablePost() gin.HandlerFunc {
// @Failure 400 {object} model.Error
// @Failure 500 {object} model.Error
// @Router /user/{id}/api/disable [post]
func (e userEndpoint) handleApiDisablePost() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := domain.SetUserInfoFromGin(c)
userId := Base64UrlDecode(c.Param("id"))
func (e UserEndpoint) handleApiDisablePost() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userId := Base64UrlDecode(request.Path(r, "id"))
if userId == "" {
c.JSON(http.StatusBadRequest,
respond.JSON(w, http.StatusBadRequest,
model.Error{Code: http.StatusInternalServerError, Message: "missing id parameter"})
return
}
user, err := e.app.DeactivateApi(ctx, domain.UserIdentifier(userId))
user, err := e.app.DeactivateApi(r.Context(), domain.UserIdentifier(userId))
if err != nil {
c.JSON(http.StatusInternalServerError,
respond.JSON(w, http.StatusInternalServerError,
model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
return
}
c.JSON(http.StatusOK, model.NewUser(user, false))
respond.JSON(w, http.StatusOK, model.NewUser(user, false))
}
}

View File

@@ -1,111 +0,0 @@
package handlers
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/app/api/v0/model"
"github.com/h44z/wg-portal/internal/domain"
)
type Scope string
const (
ScopeAdmin Scope = "ADMIN" // Admin scope contains all other scopes
)
type authenticationHandler struct {
app *app.App
Session SessionStore
}
// LoggedIn checks if a user is logged in. If scopes are given, they are validated as well.
func (h authenticationHandler) LoggedIn(scopes ...Scope) gin.HandlerFunc {
return func(c *gin.Context) {
session := h.Session.GetData(c)
if !session.LoggedIn {
// Abort the request with the appropriate error code
c.Abort()
c.JSON(http.StatusUnauthorized, model.Error{Code: http.StatusUnauthorized, Message: "not logged in"})
return
}
if !UserHasScopes(session, scopes...) {
// Abort the request with the appropriate error code
c.Abort()
c.JSON(http.StatusForbidden, model.Error{Code: http.StatusForbidden, Message: "not enough permissions"})
return
}
// Check if logged-in user is still valid
if !h.app.Authenticator.IsUserValid(c.Request.Context(), domain.UserIdentifier(session.UserIdentifier)) {
h.Session.DestroyData(c)
c.Abort()
c.JSON(http.StatusUnauthorized,
model.Error{Code: http.StatusUnauthorized, Message: "session no longer available"})
return
}
c.Set(domain.CtxUserInfo, &domain.ContextUserInfo{
Id: domain.UserIdentifier(session.UserIdentifier),
IsAdmin: session.IsAdmin,
})
// Continue down the chain to handler etc
c.Next()
}
}
// UserIdMatch checks if the user id in the session matches the user id in the request. If not, the request is aborted.
func (h authenticationHandler) UserIdMatch(idParameter string) gin.HandlerFunc {
return func(c *gin.Context) {
session := h.Session.GetData(c)
if session.IsAdmin {
c.Next() // Admins can do everything
return
}
sessionUserId := domain.UserIdentifier(session.UserIdentifier)
requestUserId := domain.UserIdentifier(Base64UrlDecode(c.Param(idParameter)))
if sessionUserId != requestUserId {
// Abort the request with the appropriate error code
c.Abort()
c.JSON(http.StatusForbidden, model.Error{Code: http.StatusForbidden, Message: "not enough permissions"})
return
}
// Continue down the chain to handler etc
c.Next()
}
}
func UserHasScopes(session SessionData, scopes ...Scope) bool {
// No scopes give, so the check should succeed
if len(scopes) == 0 {
return true
}
// check if user has admin scope
if session.IsAdmin {
return true
}
// Check if admin scope is required
for _, scope := range scopes {
if scope == ScopeAdmin {
return false
}
}
// For all other scopes, a logged-in user is sufficient (for now)
if session.LoggedIn {
return true
}
return false
}

View File

@@ -1,92 +0,0 @@
package handlers
import (
"encoding/gob"
"fmt"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)
func init() {
gob.Register(SessionData{})
}
type SessionData struct {
LoggedIn bool
IsAdmin bool
UserIdentifier string
Firstname string
Lastname string
Email string
OauthState string
OauthNonce string
OauthProvider string
OauthReturnTo string
}
type SessionStore interface {
DefaultSessionData() SessionData
GetData(c *gin.Context) SessionData
SetData(c *gin.Context, data SessionData)
DestroyData(c *gin.Context)
}
type GinSessionStore struct {
sessionIdentifier string
}
func (g GinSessionStore) GetData(c *gin.Context) SessionData {
session := sessions.Default(c)
rawSessionData := session.Get(g.sessionIdentifier)
var sessionData SessionData
if rawSessionData != nil {
sessionData = rawSessionData.(SessionData)
} else {
// init a new default session
sessionData = g.DefaultSessionData()
session.Set(g.sessionIdentifier, sessionData)
if err := session.Save(); err != nil {
panic(fmt.Sprintf("failed to store session: %v", err))
}
}
return sessionData
}
func (g GinSessionStore) DefaultSessionData() SessionData {
return SessionData{
LoggedIn: false,
IsAdmin: false,
UserIdentifier: "",
Firstname: "",
Lastname: "",
Email: "",
OauthState: "",
OauthNonce: "",
OauthProvider: "",
OauthReturnTo: "",
}
}
func (g GinSessionStore) SetData(c *gin.Context, data SessionData) {
session := sessions.Default(c)
session.Set(g.sessionIdentifier, data)
if err := session.Save(); err != nil {
panic(fmt.Sprintf("failed to store session: %v", err))
}
}
func (g GinSessionStore) DestroyData(c *gin.Context) {
session := sessions.Default(c)
session.Delete(g.sessionIdentifier)
if err := session.Save(); err != nil {
panic(fmt.Sprintf("failed to store session: %v", err))
}
}

View File

@@ -0,0 +1,126 @@
package handlers
import (
"context"
"net/http"
"github.com/h44z/wg-portal/internal/app/api/core/request"
"github.com/h44z/wg-portal/internal/app/api/core/respond"
"github.com/h44z/wg-portal/internal/app/api/v0/model"
"github.com/h44z/wg-portal/internal/domain"
)
type Scope string
const (
ScopeAdmin Scope = "ADMIN" // Admin scope contains all other scopes
)
type UserAuthenticator interface {
IsUserValid(ctx context.Context, id domain.UserIdentifier) bool
}
type AuthenticationHandler struct {
authenticator UserAuthenticator
session Session
}
func NewAuthenticationHandler(authenticator UserAuthenticator, session Session) AuthenticationHandler {
return AuthenticationHandler{
authenticator: authenticator,
session: session,
}
}
// LoggedIn checks if a user is logged in. If scopes are given, they are validated as well.
func (h AuthenticationHandler) LoggedIn(scopes ...Scope) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := h.session.GetData(r.Context())
if !session.LoggedIn {
// Abort the request with the appropriate error code
respond.JSON(w, http.StatusUnauthorized,
model.Error{Code: http.StatusUnauthorized, Message: "not logged in"})
return
}
if !UserHasScopes(session, scopes...) {
// Abort the request with the appropriate error code
respond.JSON(w, http.StatusForbidden,
model.Error{Code: http.StatusForbidden, Message: "not enough permissions"})
return
}
// Check if logged-in user is still valid
if !h.authenticator.IsUserValid(r.Context(), domain.UserIdentifier(session.UserIdentifier)) {
h.session.DestroyData(r.Context())
respond.JSON(w, http.StatusUnauthorized,
model.Error{Code: http.StatusUnauthorized, Message: "session no longer available"})
return
}
ctx := context.WithValue(r.Context(), domain.CtxUserInfo, &domain.ContextUserInfo{
Id: domain.UserIdentifier(session.UserIdentifier),
IsAdmin: session.IsAdmin,
})
r = r.WithContext(ctx)
// Continue down the chain to Handler etc
next.ServeHTTP(w, r)
})
}
}
// UserIdMatch checks if the user id in the session matches the user id in the request. If not, the request is aborted.
func (h AuthenticationHandler) UserIdMatch(idParameter string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := h.session.GetData(r.Context())
if session.IsAdmin {
next.ServeHTTP(w, r) // Admins can do everything
return
}
sessionUserId := domain.UserIdentifier(session.UserIdentifier)
requestUserId := domain.UserIdentifier(Base64UrlDecode(request.Path(r, idParameter)))
if sessionUserId != requestUserId {
// Abort the request with the appropriate error code
respond.JSON(w, http.StatusForbidden,
model.Error{Code: http.StatusForbidden, Message: "not enough permissions"})
return
}
// Continue down the chain to Handler etc
next.ServeHTTP(w, r)
})
}
}
func UserHasScopes(session SessionData, scopes ...Scope) bool {
// No scopes give, so the check should succeed
if len(scopes) == 0 {
return true
}
// check if user has admin scope
if session.IsAdmin {
return true
}
// Check if admin scope is required
for _, scope := range scopes {
if scope == ScopeAdmin {
return false
}
}
// For all other scopes, a logged-in user is sufficient (for now)
if session.LoggedIn {
return true
}
return false
}

View File

@@ -0,0 +1,88 @@
package handlers
import (
"context"
"encoding/gob"
"net/http"
"strings"
"time"
"github.com/alexedwards/scs/v2"
"github.com/h44z/wg-portal/internal/config"
)
func init() {
gob.Register(SessionData{})
}
type SessionData struct {
LoggedIn bool
IsAdmin bool
UserIdentifier string
Firstname string
Lastname string
Email string
OauthState string
OauthNonce string
OauthProvider string
OauthReturnTo string
CsrfToken string
}
const sessionApiV0Key = "session_api_v0"
type SessionWrapper struct {
*scs.SessionManager
}
func NewSessionWrapper(cfg *config.Config) *SessionWrapper {
sessionManager := scs.New()
sessionManager.Lifetime = 24 * time.Hour
sessionManager.IdleTimeout = 1 * time.Hour
sessionManager.Cookie.Name = cfg.Web.SessionIdentifier
sessionManager.Cookie.Secure = strings.HasPrefix(cfg.Web.ExternalUrl, "https")
sessionManager.Cookie.HttpOnly = true
sessionManager.Cookie.SameSite = http.SameSiteLaxMode
sessionManager.Cookie.Path = "/"
sessionManager.Cookie.Persist = false
wrappedSessionManager := &SessionWrapper{sessionManager}
return wrappedSessionManager
}
func (s *SessionWrapper) SetData(ctx context.Context, value SessionData) {
s.SessionManager.Put(ctx, sessionApiV0Key, value)
}
func (s *SessionWrapper) GetData(ctx context.Context) SessionData {
sessionData, ok := s.SessionManager.Get(ctx, sessionApiV0Key).(SessionData)
if !ok {
return s.defaultSessionData()
}
return sessionData
}
func (s *SessionWrapper) DestroyData(ctx context.Context) {
_ = s.SessionManager.Destroy(ctx)
}
func (s *SessionWrapper) defaultSessionData() SessionData {
return SessionData{
LoggedIn: false,
IsAdmin: false,
UserIdentifier: "",
Firstname: "",
Lastname: "",
Email: "",
OauthState: "",
OauthNonce: "",
OauthProvider: "",
OauthReturnTo: "",
}
}