mirror of
https://github.com/h44z/wg-portal.git
synced 2025-08-25 06:22:23 +00:00
V2 alpha - initial version (#172)
Initial alpha codebase for version 2 of WireGuard Portal. This version is considered unstable and incomplete (for example, no public REST API)! Use with care! Fixes/Implements the following issues: - OAuth support #154, #1 - New Web UI with internationalisation support #98, #107, #89, #62 - Postgres Support #49 - Improved Email handling #47, #119 - DNS Search Domain support #46 - Bugfixes #94, #48 --------- Co-authored-by: Fabian Wechselberger <wechselbergerf@hotmail.com>
This commit is contained in:
95
internal/app/api/v0/handlers/base.go
Normal file
95
internal/app/api/v0/handlers/base.go
Normal file
@@ -0,0 +1,95 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-contrib/sessions/memstore"
|
||||
"github.com/gin-gonic/gin"
|
||||
"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"
|
||||
csrf "github.com/utrack/gin-csrf"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type handler interface {
|
||||
GetName() string
|
||||
RegisterRoutes(g *gin.RouterGroup, authenticator *authenticationHandler)
|
||||
}
|
||||
|
||||
// To compile the API documentation use the
|
||||
// build_tool
|
||||
// command that can be found in the $PROJECT_ROOT/internal/ports/api/build_tool directory.
|
||||
|
||||
// @title WireGuard Portal API
|
||||
// @version 0.0
|
||||
// @description WireGuard Portal API - a testing API endpoint
|
||||
|
||||
// @contact.name WireGuard Portal Developers
|
||||
// @contact.url https://github.com/h44z/wg-portal
|
||||
|
||||
// @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})
|
||||
|
||||
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,
|
||||
})
|
||||
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())
|
||||
|
||||
// Handler functions
|
||||
for _, h := range handlers {
|
||||
h.RegisterRoutes(group, authenticator)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleCsrfGet returns a gorm handler function.
|
||||
//
|
||||
// @ID base_handleCsrfGet
|
||||
// @Tags Security
|
||||
// @Summary Get a CSRF token for the current session.
|
||||
// @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))
|
||||
}
|
||||
}
|
15
internal/app/api/v0/handlers/encoding.go
Normal file
15
internal/app/api/v0/handlers/encoding.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func Base64UrlDecode(in string) string {
|
||||
in = strings.ReplaceAll(in, "-", "=")
|
||||
in = strings.ReplaceAll(in, "_", "/")
|
||||
in = strings.ReplaceAll(in, ".", "+")
|
||||
|
||||
output, _ := base64.StdEncoding.DecodeString(in)
|
||||
return string(output)
|
||||
}
|
327
internal/app/api/v0/handlers/endpoint_authentication.go
Normal file
327
internal/app/api/v0/handlers/endpoint_authentication.go
Normal file
@@ -0,0 +1,327 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type authEndpoint struct {
|
||||
app *app.App
|
||||
authenticator *authenticationHandler
|
||||
}
|
||||
|
||||
func (e authEndpoint) GetName() string {
|
||||
return "AuthEndpoint"
|
||||
}
|
||||
|
||||
func (e authEndpoint) RegisterRoutes(g *gin.RouterGroup, authenticator *authenticationHandler) {
|
||||
apiGroup := g.Group("/auth")
|
||||
|
||||
apiGroup.GET("/providers", e.handleExternalLoginProvidersGet())
|
||||
apiGroup.GET("/session", e.handleSessionInfoGet())
|
||||
|
||||
apiGroup.GET("/login/:provider/init", e.handleOauthInitiateGet())
|
||||
apiGroup.GET("/login/:provider/callback", e.handleOauthCallbackGet())
|
||||
|
||||
apiGroup.POST("/login", e.handleLoginPost())
|
||||
apiGroup.POST("/logout", authenticator.LoggedIn(), e.handleLogoutPost())
|
||||
}
|
||||
|
||||
// handleExternalLoginProvidersGet returns a gorm handler function.
|
||||
//
|
||||
// @ID auth_handleExternalLoginProvidersGet
|
||||
// @Tags Authentication
|
||||
// @Summary Get all available external login providers.
|
||||
// @Produce json
|
||||
// @Success 200 {object} []model.LoginProviderInfo
|
||||
// @Router /auth/providers [get]
|
||||
func (e authEndpoint) handleExternalLoginProvidersGet() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
providers := e.app.Authenticator.GetExternalLoginProviders(c.Request.Context())
|
||||
|
||||
c.JSON(http.StatusOK, model.NewLoginProviderInfos(providers))
|
||||
}
|
||||
}
|
||||
|
||||
// handleSessionInfoGet returns a gorm handler function.
|
||||
//
|
||||
// @ID auth_handleSessionInfoGet
|
||||
// @Tags Authentication
|
||||
// @Summary Get information about the currently logged-in user.
|
||||
// @Produce json
|
||||
// @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)
|
||||
|
||||
var loggedInUid *string
|
||||
var firstname *string
|
||||
var lastname *string
|
||||
var email *string
|
||||
|
||||
if currentSession.LoggedIn {
|
||||
uid := string(currentSession.UserIdentifier)
|
||||
f := currentSession.Firstname
|
||||
l := currentSession.Lastname
|
||||
e := currentSession.Email
|
||||
loggedInUid = &uid
|
||||
firstname = &f
|
||||
lastname = &l
|
||||
email = &e
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.SessionInfo{
|
||||
LoggedIn: currentSession.LoggedIn,
|
||||
IsAdmin: currentSession.IsAdmin,
|
||||
UserIdentifier: loggedInUid,
|
||||
UserFirstname: firstname,
|
||||
UserLastname: lastname,
|
||||
UserEmail: email,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// handleOauthInitiateGet returns a gorm handler function.
|
||||
//
|
||||
// @ID auth_handleOauthInitiateGet
|
||||
// @Tags Authentication
|
||||
// @Summary Initiate the OAuth login flow.
|
||||
// @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)
|
||||
|
||||
autoRedirect, _ := strconv.ParseBool(c.DefaultQuery("redirect", "false"))
|
||||
returnTo := c.Query("return")
|
||||
provider := c.Param("provider")
|
||||
|
||||
var returnUrl *url.URL
|
||||
var returnParams string
|
||||
redirectToReturn := func() {
|
||||
c.Redirect(http.StatusFound, returnUrl.String()+"?"+returnParams)
|
||||
}
|
||||
|
||||
if returnTo != "" {
|
||||
if u, err := url.Parse(returnTo); err == nil {
|
||||
returnUrl = u
|
||||
}
|
||||
queryParams := returnUrl.Query()
|
||||
queryParams.Set("wgLoginState", "err") // by default, we set the state to error
|
||||
returnUrl.RawQuery = "" // remove potential query params
|
||||
returnParams = queryParams.Encode()
|
||||
}
|
||||
|
||||
if currentSession.LoggedIn {
|
||||
if autoRedirect {
|
||||
queryParams := returnUrl.Query()
|
||||
queryParams.Set("wgLoginState", "success")
|
||||
returnParams = queryParams.Encode()
|
||||
redirectToReturn()
|
||||
} else {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "already logged in"})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
authCodeUrl, state, nonce, err := e.app.Authenticator.OauthLoginStep1(c.Request.Context(), provider)
|
||||
if err != nil {
|
||||
if autoRedirect {
|
||||
redirectToReturn()
|
||||
} else {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
authSession := e.authenticator.Session.DefaultSessionData()
|
||||
authSession.OauthState = state
|
||||
authSession.OauthNonce = nonce
|
||||
authSession.OauthProvider = provider
|
||||
authSession.OauthReturnTo = returnTo
|
||||
e.authenticator.Session.SetData(c, authSession)
|
||||
|
||||
if autoRedirect {
|
||||
c.Redirect(http.StatusFound, authCodeUrl)
|
||||
} else {
|
||||
c.JSON(http.StatusOK, model.OauthInitiationResponse{
|
||||
RedirectUrl: authCodeUrl,
|
||||
State: state,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleOauthCallbackGet returns a gorm handler function.
|
||||
//
|
||||
// @ID auth_handleOauthCallbackGet
|
||||
// @Tags Authentication
|
||||
// @Summary Handle the OAuth callback.
|
||||
// @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)
|
||||
|
||||
var returnUrl *url.URL
|
||||
var returnParams string
|
||||
redirectToReturn := func() {
|
||||
c.Redirect(http.StatusFound, returnUrl.String()+"?"+returnParams)
|
||||
}
|
||||
|
||||
if currentSession.OauthReturnTo != "" {
|
||||
if u, err := url.Parse(currentSession.OauthReturnTo); err == nil {
|
||||
returnUrl = u
|
||||
}
|
||||
queryParams := returnUrl.Query()
|
||||
queryParams.Set("wgLoginState", "err") // by default, we set the state to error
|
||||
returnUrl.RawQuery = "" // remove potential query params
|
||||
returnParams = queryParams.Encode()
|
||||
}
|
||||
|
||||
if currentSession.LoggedIn {
|
||||
if returnUrl != nil {
|
||||
queryParams := returnUrl.Query()
|
||||
queryParams.Set("wgLoginState", "success")
|
||||
returnParams = queryParams.Encode()
|
||||
redirectToReturn()
|
||||
} else {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Message: "already logged in"})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
provider := c.Param("provider")
|
||||
oauthCode := c.Query("code")
|
||||
oauthState := c.Query("state")
|
||||
|
||||
if provider != currentSession.OauthProvider {
|
||||
if returnUrl != nil {
|
||||
redirectToReturn()
|
||||
} else {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "invalid oauth provider"})
|
||||
}
|
||||
return
|
||||
}
|
||||
if oauthState != currentSession.OauthState {
|
||||
if returnUrl != nil {
|
||||
redirectToReturn()
|
||||
} else {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "invalid oauth state"})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
loginCtx, cancel := context.WithTimeout(context.Background(), 1000*time.Second)
|
||||
user, err := e.app.Authenticator.OauthLoginStep2(loginCtx, provider, currentSession.OauthNonce, oauthCode)
|
||||
cancel()
|
||||
if err != nil {
|
||||
if returnUrl != nil {
|
||||
redirectToReturn()
|
||||
} else {
|
||||
c.JSON(http.StatusUnauthorized, model.Error{Code: http.StatusUnauthorized, Message: err.Error()})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
e.setAuthenticatedUser(c, user)
|
||||
|
||||
if returnUrl != nil {
|
||||
queryParams := returnUrl.Query()
|
||||
queryParams.Set("wgLoginState", "success")
|
||||
returnParams = queryParams.Encode()
|
||||
redirectToReturn()
|
||||
} else {
|
||||
c.JSON(http.StatusOK, user)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (e authEndpoint) setAuthenticatedUser(c *gin.Context, user *domain.User) {
|
||||
currentSession := e.authenticator.Session.GetData(c)
|
||||
|
||||
currentSession.LoggedIn = true
|
||||
currentSession.IsAdmin = user.IsAdmin
|
||||
currentSession.UserIdentifier = string(user.Identifier)
|
||||
currentSession.Firstname = user.Firstname
|
||||
currentSession.Lastname = user.Lastname
|
||||
currentSession.Email = user.Email
|
||||
|
||||
currentSession.OauthState = ""
|
||||
currentSession.OauthNonce = ""
|
||||
currentSession.OauthProvider = ""
|
||||
currentSession.OauthReturnTo = ""
|
||||
|
||||
e.authenticator.Session.SetData(c, currentSession)
|
||||
}
|
||||
|
||||
// handleLoginPost returns a gorm handler function.
|
||||
//
|
||||
// @ID auth_handleLoginPost
|
||||
// @Tags Authentication
|
||||
// @Summary Get all available external login providers.
|
||||
// @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)
|
||||
if currentSession.LoggedIn {
|
||||
c.JSON(http.StatusOK, model.Error{Code: http.StatusOK, Message: "already logged in"})
|
||||
return
|
||||
}
|
||||
|
||||
var loginData struct {
|
||||
Username string `json:"username" binding:"required,min=2"`
|
||||
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()})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := e.app.Authenticator.PlainLogin(c.Request.Context(), loginData.Username, loginData.Password)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, model.Error{Code: http.StatusUnauthorized, Message: "login failed"})
|
||||
return
|
||||
}
|
||||
|
||||
e.setAuthenticatedUser(c, user)
|
||||
|
||||
c.JSON(http.StatusOK, user)
|
||||
}
|
||||
}
|
||||
|
||||
// handleLogoutPost returns a gorm handler function.
|
||||
//
|
||||
// @ID auth_handleLogoutGet
|
||||
// @Tags Authentication
|
||||
// @Summary Get all available external login providers.
|
||||
// @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)
|
||||
|
||||
if !currentSession.LoggedIn { // Not logged in
|
||||
c.JSON(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"})
|
||||
}
|
||||
}
|
101
internal/app/api/v0/handlers/endpoint_config.go
Normal file
101
internal/app/api/v0/handlers/endpoint_config.go
Normal file
@@ -0,0 +1,101 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"embed"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/h44z/wg-portal/internal/app"
|
||||
"github.com/h44z/wg-portal/internal/app/api/v0/model"
|
||||
"html/template"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
//go:embed frontend_config.js.gotpl
|
||||
var frontendJs embed.FS
|
||||
|
||||
type configEndpoint struct {
|
||||
app *app.App
|
||||
authenticator *authenticationHandler
|
||||
|
||||
tpl *template.Template
|
||||
}
|
||||
|
||||
func newConfigEndpoint(app *app.App, authenticator *authenticationHandler) configEndpoint {
|
||||
ep := configEndpoint{
|
||||
app: app,
|
||||
authenticator: authenticator,
|
||||
tpl: template.Must(template.ParseFS(frontendJs, "frontend_config.js.gotpl")),
|
||||
}
|
||||
|
||||
return ep
|
||||
}
|
||||
|
||||
func (e configEndpoint) GetName() string {
|
||||
return "ConfigEndpoint"
|
||||
}
|
||||
|
||||
func (e configEndpoint) RegisterRoutes(g *gin.RouterGroup, authenticator *authenticationHandler) {
|
||||
apiGroup := g.Group("/config")
|
||||
|
||||
apiGroup.GET("/frontend.js", e.handleConfigJsGet())
|
||||
apiGroup.GET("/settings", e.authenticator.LoggedIn(), e.handleSettingsGet())
|
||||
}
|
||||
|
||||
// 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"
|
||||
// @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")
|
||||
host := "localhost"
|
||||
port := "5000"
|
||||
parsedReferer, err := url.Parse(referer)
|
||||
if err == nil {
|
||||
host, port, _ = net.SplitHostPort(parsedReferer.Host)
|
||||
}
|
||||
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{
|
||||
"BackendUrl": backendUrl,
|
||||
"Version": "unknown",
|
||||
"SiteTitle": e.app.Config.Web.SiteTitle,
|
||||
"SiteCompanyName": e.app.Config.Web.SiteCompanyName,
|
||||
})
|
||||
if err != nil {
|
||||
c.Status(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
c.Data(http.StatusOK, "application/javascript", buf.Bytes())
|
||||
}
|
||||
}
|
||||
|
||||
// handleSettingsGet returns a gorm handler function.
|
||||
//
|
||||
// @ID config_handleSettingsGet
|
||||
// @Tags Configuration
|
||||
// @Summary Get the frontend settings object.
|
||||
// @Produce json
|
||||
// @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,
|
||||
})
|
||||
}
|
||||
}
|
378
internal/app/api/v0/handlers/endpoint_interfaces.go
Normal file
378
internal/app/api/v0/handlers/endpoint_interfaces.go
Normal file
@@ -0,0 +1,378 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"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"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type interfaceEndpoint struct {
|
||||
app *app.App
|
||||
authenticator *authenticationHandler
|
||||
}
|
||||
|
||||
func (e interfaceEndpoint) GetName() string {
|
||||
return "InterfaceEndpoint"
|
||||
}
|
||||
|
||||
func (e interfaceEndpoint) RegisterRoutes(g *gin.RouterGroup, authenticator *authenticationHandler) {
|
||||
apiGroup := g.Group("/interface", e.authenticator.LoggedIn())
|
||||
|
||||
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.GET("/peers/:id", e.handlePeersGet())
|
||||
}
|
||||
|
||||
// handlePrepareGet returns a gorm handler function.
|
||||
//
|
||||
// @ID interfaces_handlePrepareGet
|
||||
// @Tags Interface
|
||||
// @Summary Prepare a new interface.
|
||||
// @Produce json
|
||||
// @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) {
|
||||
in, err := e.app.PrepareInterface(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{
|
||||
Code: http.StatusInternalServerError, Message: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.NewInterface(in, nil))
|
||||
}
|
||||
}
|
||||
|
||||
// handleAllGet returns a gorm handler function.
|
||||
//
|
||||
// @ID interfaces_handleAllGet
|
||||
// @Tags Interface
|
||||
// @Summary Get all available interfaces.
|
||||
// @Produce json
|
||||
// @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) {
|
||||
interfaces, peers, err := e.app.GetAllInterfacesAndPeers(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{
|
||||
Code: http.StatusInternalServerError, Message: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.NewInterfaces(interfaces, peers))
|
||||
}
|
||||
}
|
||||
|
||||
// handleSingleGet returns a gorm handler function.
|
||||
//
|
||||
// @ID interfaces_handleSingleGet
|
||||
// @Tags Interface
|
||||
// @Summary Get single interface.
|
||||
// @Produce json
|
||||
// @Success 200 {object} model.Interface
|
||||
// @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) {
|
||||
id := Base64UrlDecode(c.Param("id"))
|
||||
if id == "" {
|
||||
c.JSON(http.StatusBadRequest, model.Error{
|
||||
Code: http.StatusInternalServerError, Message: "missing id parameter",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
iface, peers, err := e.app.GetInterfaceAndPeers(c.Request.Context(), domain.InterfaceIdentifier(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{
|
||||
Code: http.StatusInternalServerError, Message: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.NewInterface(iface, peers))
|
||||
}
|
||||
}
|
||||
|
||||
// handleConfigGet returns a gorm handler function.
|
||||
//
|
||||
// @ID interfaces_handleConfigGet
|
||||
// @Tags Interface
|
||||
// @Summary Get interface configuration as string.
|
||||
// @Produce json
|
||||
// @Success 200 {object} string
|
||||
// @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) {
|
||||
id := Base64UrlDecode(c.Param("id"))
|
||||
if id == "" {
|
||||
c.JSON(http.StatusBadRequest, model.Error{
|
||||
Code: http.StatusInternalServerError, Message: "missing id parameter",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
config, err := e.app.GetInterfaceConfig(c.Request.Context(), domain.InterfaceIdentifier(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{
|
||||
Code: http.StatusInternalServerError, Message: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
configString, err := io.ReadAll(config)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{
|
||||
Code: http.StatusInternalServerError, Message: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, string(configString))
|
||||
}
|
||||
}
|
||||
|
||||
// handleUpdatePut returns a gorm handler function.
|
||||
//
|
||||
// @ID interfaces_handleUpdatePut
|
||||
// @Tags Interface
|
||||
// @Summary Update the interface record.
|
||||
// @Produce json
|
||||
// @Param id path string true "The interface identifier"
|
||||
// @Param request body model.Interface true "The interface data"
|
||||
// @Success 200 {object} model.Interface
|
||||
// @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"))
|
||||
if id == "" {
|
||||
c.JSON(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()})
|
||||
return
|
||||
}
|
||||
|
||||
if id != in.Identifier {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "interface id mismatch"})
|
||||
return
|
||||
}
|
||||
|
||||
updatedInterface, peers, err := e.app.UpdateInterface(ctx, model.NewDomainInterface(&in))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{
|
||||
Code: http.StatusInternalServerError, Message: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.NewInterface(updatedInterface, peers))
|
||||
}
|
||||
}
|
||||
|
||||
// handleCreatePost returns a gorm handler function.
|
||||
//
|
||||
// @ID interfaces_handleCreatePost
|
||||
// @Tags Interface
|
||||
// @Summary Create the new interface record.
|
||||
// @Produce json
|
||||
// @Param request body model.Interface true "The interface data"
|
||||
// @Success 200 {object} model.Interface
|
||||
// @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)
|
||||
|
||||
var in model.Interface
|
||||
err := c.BindJSON(&in)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
newInterface, err := e.app.CreateInterface(ctx, model.NewDomainInterface(&in))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{
|
||||
Code: http.StatusInternalServerError, Message: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.NewInterface(newInterface, nil))
|
||||
}
|
||||
}
|
||||
|
||||
// handlePeersGet returns a gorm handler function.
|
||||
//
|
||||
// @ID interfaces_handlePeersGet
|
||||
// @Tags Interface
|
||||
// @Summary Get peers for the given interface.
|
||||
// @Produce json
|
||||
// @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"))
|
||||
if id == "" {
|
||||
c.JSON(http.StatusBadRequest, model.Error{
|
||||
Code: http.StatusInternalServerError, Message: "missing id parameter",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
_, peers, err := e.app.GetInterfaceAndPeers(ctx, domain.InterfaceIdentifier(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{
|
||||
Code: http.StatusInternalServerError, Message: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.NewPeers(peers))
|
||||
}
|
||||
}
|
||||
|
||||
// handleDelete returns a gorm handler function.
|
||||
//
|
||||
// @ID interfaces_handleDelete
|
||||
// @Tags Interface
|
||||
// @Summary Delete the interface record.
|
||||
// @Produce json
|
||||
// @Param id path string true "The interface identifier"
|
||||
// @Success 204 "No content if deletion was successful"
|
||||
// @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"))
|
||||
if id == "" {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing interface id"})
|
||||
return
|
||||
}
|
||||
|
||||
err := e.app.DeleteInterface(ctx, domain.InterfaceIdentifier(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{
|
||||
Code: http.StatusInternalServerError, Message: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
// handleSaveConfigPost returns a gorm handler function.
|
||||
//
|
||||
// @ID interfaces_handleSaveConfigPost
|
||||
// @Tags Interface
|
||||
// @Summary Save the interface configuration in wg-quick format to a file.
|
||||
// @Produce json
|
||||
// @Param id path string true "The interface identifier"
|
||||
// @Success 204 "No content if saving the configuration was successful"
|
||||
// @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"))
|
||||
if id == "" {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing interface id"})
|
||||
return
|
||||
}
|
||||
|
||||
err := e.app.PersistInterfaceConfig(ctx, domain.InterfaceIdentifier(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{
|
||||
Code: http.StatusInternalServerError, Message: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
// handleApplyPeerDefaultsPost returns a gorm handler function.
|
||||
//
|
||||
// @ID interfaces_handleApplyPeerDefaultsPost
|
||||
// @Tags Interface
|
||||
// @Summary Apply all peer defaults to the available peers.
|
||||
// @Produce json
|
||||
// @Param id path string true "The interface identifier"
|
||||
// @Param request body model.Interface true "The interface data"
|
||||
// @Success 204 "No content if applying peer defaults was successful"
|
||||
// @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"))
|
||||
if id == "" {
|
||||
c.JSON(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()})
|
||||
return
|
||||
}
|
||||
|
||||
if id != in.Identifier {
|
||||
c.JSON(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{
|
||||
Code: http.StatusInternalServerError, Message: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
438
internal/app/api/v0/handlers/endpoint_peers.go
Normal file
438
internal/app/api/v0/handlers/endpoint_peers.go
Normal file
@@ -0,0 +1,438 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"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"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type peerEndpoint struct {
|
||||
app *app.App
|
||||
authenticator *authenticationHandler
|
||||
}
|
||||
|
||||
func (e peerEndpoint) GetName() string {
|
||||
return "PeerEndpoint"
|
||||
}
|
||||
|
||||
func (e peerEndpoint) RegisterRoutes(g *gin.RouterGroup, authenticator *authenticationHandler) {
|
||||
apiGroup := g.Group("/peer", e.authenticator.LoggedIn())
|
||||
|
||||
apiGroup.GET("/iface/:iface/all", e.handleAllGet())
|
||||
apiGroup.GET("/iface/:iface/stats", e.handleStatsGet())
|
||||
apiGroup.GET("/iface/:iface/prepare", e.handlePrepareGet())
|
||||
apiGroup.POST("/iface/:iface/new", e.handleCreatePost())
|
||||
apiGroup.POST("/iface/:iface/multiplenew", 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())
|
||||
}
|
||||
|
||||
// handleAllGet returns a gorm handler function.
|
||||
//
|
||||
// @ID peers_handleAllGet
|
||||
// @Tags Peer
|
||||
// @Summary Get peers for the given interface.
|
||||
// @Produce json
|
||||
// @Param iface path string true "The interface identifier"
|
||||
// @Success 200 {object} []model.Peer
|
||||
// @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"))
|
||||
if interfaceId == "" {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing iface parameter"})
|
||||
return
|
||||
}
|
||||
|
||||
_, peers, err := e.app.GetInterfaceAndPeers(ctx, domain.InterfaceIdentifier(interfaceId))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.NewPeers(peers))
|
||||
}
|
||||
}
|
||||
|
||||
// handleSingleGet returns a gorm handler function.
|
||||
//
|
||||
// @ID peers_handleSingleGet
|
||||
// @Tags Peer
|
||||
// @Summary Get peer for the given identifier.
|
||||
// @Produce json
|
||||
// @Param id path string true "The peer identifier"
|
||||
// @Success 200 {object} model.Peer
|
||||
// @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"))
|
||||
if peerId == "" {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing id parameter"})
|
||||
return
|
||||
}
|
||||
|
||||
peer, err := e.app.GetPeer(ctx, domain.PeerIdentifier(peerId))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.NewPeer(peer))
|
||||
}
|
||||
}
|
||||
|
||||
// handlePrepareGet returns a gorm handler function.
|
||||
//
|
||||
// @ID peers_handlePrepareGet
|
||||
// @Tags Peer
|
||||
// @Summary Prepare a new peer for the given interface.
|
||||
// @Produce json
|
||||
// @Param iface path string true "The interface identifier"
|
||||
// @Success 200 {object} model.Peer
|
||||
// @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"))
|
||||
if interfaceId == "" {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing iface parameter"})
|
||||
return
|
||||
}
|
||||
|
||||
peer, err := e.app.PreparePeer(ctx, domain.InterfaceIdentifier(interfaceId))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.NewPeer(peer))
|
||||
}
|
||||
}
|
||||
|
||||
// handleCreatePost returns a gorm handler function.
|
||||
//
|
||||
// @ID peers_handleCreatePost
|
||||
// @Tags Peer
|
||||
// @Summary Prepare a new peer for the given interface.
|
||||
// @Produce json
|
||||
// @Param iface path string true "The interface identifier"
|
||||
// @Param request body model.Peer true "The peer data"
|
||||
// @Success 200 {object} model.Peer
|
||||
// @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"))
|
||||
if interfaceId == "" {
|
||||
c.JSON(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()})
|
||||
return
|
||||
}
|
||||
|
||||
if p.InterfaceIdentifier != interfaceId {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "interface id mismatch"})
|
||||
return
|
||||
}
|
||||
|
||||
newPeer, err := e.app.CreatePeer(ctx, model.NewDomainPeer(&p))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.NewPeer(newPeer))
|
||||
}
|
||||
}
|
||||
|
||||
// handleCreateMultiplePost returns a gorm handler function.
|
||||
//
|
||||
// @ID peers_handleCreateMultiplePost
|
||||
// @Tags Peer
|
||||
// @Summary Create multiple new peers for the given interface.
|
||||
// @Produce json
|
||||
// @Param iface path string true "The interface identifier"
|
||||
// @Param request body model.MultiPeerRequest true "The peer creation request data"
|
||||
// @Success 200 {object} []model.Peer
|
||||
// @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"))
|
||||
if interfaceId == "" {
|
||||
c.JSON(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()})
|
||||
return
|
||||
}
|
||||
|
||||
newPeers, err := e.app.CreateMultiplePeers(ctx, domain.InterfaceIdentifier(interfaceId), model.NewDomainPeerCreationRequest(&req))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.NewPeers(newPeers))
|
||||
}
|
||||
}
|
||||
|
||||
// handleUpdatePut returns a gorm handler function.
|
||||
//
|
||||
// @ID peers_handleUpdatePut
|
||||
// @Tags Peer
|
||||
// @Summary Update the given peer record.
|
||||
// @Produce json
|
||||
// @Param id path string true "The peer identifier"
|
||||
// @Param request body model.Peer true "The peer data"
|
||||
// @Success 200 {object} model.Peer
|
||||
// @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"))
|
||||
if peerId == "" {
|
||||
c.JSON(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()})
|
||||
return
|
||||
}
|
||||
|
||||
if p.Identifier != peerId {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "peer id mismatch"})
|
||||
return
|
||||
}
|
||||
|
||||
updatedPeer, err := e.app.UpdatePeer(ctx, model.NewDomainPeer(&p))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.NewPeer(updatedPeer))
|
||||
}
|
||||
}
|
||||
|
||||
// handleDelete returns a gorm handler function.
|
||||
//
|
||||
// @ID peers_handleDelete
|
||||
// @Tags Peer
|
||||
// @Summary Delete the peer record.
|
||||
// @Produce json
|
||||
// @Param id path string true "The peer identifier"
|
||||
// @Success 204 "No content if deletion was successful"
|
||||
// @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"))
|
||||
if id == "" {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing peer id"})
|
||||
return
|
||||
}
|
||||
|
||||
err := e.app.DeletePeer(ctx, domain.PeerIdentifier(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
// handleConfigGet returns a gorm handler function.
|
||||
//
|
||||
// @ID peers_handleConfigGet
|
||||
// @Tags Peer
|
||||
// @Summary Get peer configuration as string.
|
||||
// @Produce json
|
||||
// @Param id path string true "The peer identifier"
|
||||
// @Success 200 {object} string
|
||||
// @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) {
|
||||
id := Base64UrlDecode(c.Param("id"))
|
||||
if id == "" {
|
||||
c.JSON(http.StatusBadRequest, model.Error{
|
||||
Code: http.StatusInternalServerError, Message: "missing id parameter",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
config, err := e.app.GetPeerConfig(c.Request.Context(), domain.PeerIdentifier(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{
|
||||
Code: http.StatusInternalServerError, Message: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
configString, err := io.ReadAll(config)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{
|
||||
Code: http.StatusInternalServerError, Message: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, string(configString))
|
||||
}
|
||||
}
|
||||
|
||||
// handleQrCodeGet returns a gorm handler function.
|
||||
//
|
||||
// @ID peers_handleQrCodeGet
|
||||
// @Tags Peer
|
||||
// @Summary Get peer configuration as qr code.
|
||||
// @Produce json
|
||||
// @Param id path string true "The peer identifier"
|
||||
// @Success 200 {object} string
|
||||
// @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) {
|
||||
id := Base64UrlDecode(c.Param("id"))
|
||||
if id == "" {
|
||||
c.JSON(http.StatusBadRequest, model.Error{
|
||||
Code: http.StatusInternalServerError, Message: "missing id parameter",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
config, err := e.app.GetPeerConfigQrCode(c.Request.Context(), domain.PeerIdentifier(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{
|
||||
Code: http.StatusInternalServerError, Message: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
configData, err := io.ReadAll(config)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{
|
||||
Code: http.StatusInternalServerError, Message: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.Data(http.StatusOK, "image/png", configData)
|
||||
}
|
||||
}
|
||||
|
||||
// handleEmailPost returns a gorm handler function.
|
||||
//
|
||||
// @ID peers_handleEmailPost
|
||||
// @Tags Peer
|
||||
// @Summary Send peer configuration via email.
|
||||
// @Produce json
|
||||
// @Param request body model.PeerMailRequest true "The peer mail request data"
|
||||
// @Success 204 "No content if mail sending was successful"
|
||||
// @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) {
|
||||
var req model.PeerMailRequest
|
||||
err := c.BindJSON(&req)
|
||||
if err != nil {
|
||||
c.JSON(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"})
|
||||
return
|
||||
}
|
||||
|
||||
peerIds := make([]domain.PeerIdentifier, len(req.Identifiers))
|
||||
for i := range req.Identifiers {
|
||||
peerIds[i] = domain.PeerIdentifier(req.Identifiers[i])
|
||||
}
|
||||
err = e.app.SendPeerEmail(c.Request.Context(), req.LinkOnly, peerIds...)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
// handleStatsGet returns a gorm handler function.
|
||||
//
|
||||
// @ID peers_handleStatsGet
|
||||
// @Tags Peer
|
||||
// @Summary Get peer stats for the given interface.
|
||||
// @Produce json
|
||||
// @Param iface path string true "The interface identifier"
|
||||
// @Success 200 {object} model.PeerStats
|
||||
// @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"))
|
||||
if interfaceId == "" {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing iface parameter"})
|
||||
return
|
||||
}
|
||||
|
||||
stats, err := e.app.GetPeerStats(ctx, domain.InterfaceIdentifier(interfaceId))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.NewPeerStats(e.app.Config.Statistics.CollectPeerData, stats))
|
||||
}
|
||||
}
|
65
internal/app/api/v0/handlers/endpoint_testing.go
Normal file
65
internal/app/api/v0/handlers/endpoint_testing.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/h44z/wg-portal/internal/app/api/v0/model"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
type testEndpoint struct{}
|
||||
|
||||
func (e testEndpoint) GetName() string {
|
||||
return "TestEndpoint"
|
||||
}
|
||||
|
||||
func (e testEndpoint) RegisterRoutes(g *gin.RouterGroup, authenticator *authenticationHandler) {
|
||||
g.GET("/now", e.handleCurrentTimeGet())
|
||||
g.GET("/hostname", e.handleHostnameGet())
|
||||
}
|
||||
|
||||
// handleCurrentTimeGet represents the GET endpoint that responds the current time
|
||||
//
|
||||
// @ID test_handleCurrentTimeGet
|
||||
// @Tags Testing
|
||||
// @Summary Get the current local time.
|
||||
// @Description Nothing more to describe...
|
||||
// @Produce json
|
||||
// @Success 200 {object} string
|
||||
// @Failure 500 {object} model.Error
|
||||
// @Router /now [get]
|
||||
func (e testEndpoint) handleCurrentTimeGet() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if time.Now().Second() == 0 {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{
|
||||
Code: http.StatusInternalServerError,
|
||||
Message: "invalid time",
|
||||
})
|
||||
}
|
||||
c.JSON(http.StatusOK, time.Now().String())
|
||||
}
|
||||
}
|
||||
|
||||
// handleHostnameGet represents the GET endpoint that responds the current hostname
|
||||
//
|
||||
// @ID test_handleHostnameGet
|
||||
// @Tags Testing
|
||||
// @Summary Get the current host name.
|
||||
// @Description Nothing more to describe...
|
||||
// @Produce json
|
||||
// @Success 200 {object} string
|
||||
// @Failure 500 {object} model.Error
|
||||
// @Router /hostname [get]
|
||||
func (e testEndpoint) handleHostnameGet() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
hostname, err := os.Hostname()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{
|
||||
Code: http.StatusInternalServerError,
|
||||
Message: err.Error(),
|
||||
})
|
||||
}
|
||||
c.JSON(http.StatusOK, hostname)
|
||||
}
|
||||
}
|
250
internal/app/api/v0/handlers/endpoint_users.go
Normal file
250
internal/app/api/v0/handlers/endpoint_users.go
Normal file
@@ -0,0 +1,250 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"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"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type userEndpoint struct {
|
||||
app *app.App
|
||||
authenticator *authenticationHandler
|
||||
}
|
||||
|
||||
func (e userEndpoint) GetName() string {
|
||||
return "UserEndpoint"
|
||||
}
|
||||
|
||||
func (e userEndpoint) RegisterRoutes(g *gin.RouterGroup, authenticator *authenticationHandler) {
|
||||
apiGroup := g.Group("/user", e.authenticator.LoggedIn())
|
||||
|
||||
apiGroup.GET("/all", e.handleAllGet())
|
||||
apiGroup.GET("/:id", e.handleSingleGet())
|
||||
apiGroup.PUT("/:id", e.handleUpdatePut())
|
||||
apiGroup.DELETE("/:id", e.handleDelete())
|
||||
apiGroup.POST("/new", e.handleCreatePost())
|
||||
apiGroup.GET("/:id/peers", e.handlePeersGet())
|
||||
apiGroup.GET("/:id/stats", e.handleStatsGet())
|
||||
}
|
||||
|
||||
// handleAllGet returns a gorm handler function.
|
||||
//
|
||||
// @ID users_handleAllGet
|
||||
// @Tags Users
|
||||
// @Summary Get all user records.
|
||||
// @Produce json
|
||||
// @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)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.NewUsers(users))
|
||||
}
|
||||
}
|
||||
|
||||
// handleSingleGet returns a gorm handler function.
|
||||
//
|
||||
// @ID users_handleSingleGet
|
||||
// @Tags Users
|
||||
// @Summary Get a single user record.
|
||||
// @Produce json
|
||||
// @Param id path string true "The user identifier"
|
||||
// @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"))
|
||||
if id == "" {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing user id"})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := e.app.GetUser(ctx, domain.UserIdentifier(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.NewUser(user))
|
||||
}
|
||||
}
|
||||
|
||||
// handleUpdatePut returns a gorm handler function.
|
||||
//
|
||||
// @ID users_handleUpdatePut
|
||||
// @Tags Users
|
||||
// @Summary Update the user record.
|
||||
// @Produce json
|
||||
// @Param id path string true "The user identifier"
|
||||
// @Param request body model.User true "The user data"
|
||||
// @Success 200 {object} model.User
|
||||
// @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"))
|
||||
if id == "" {
|
||||
c.JSON(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()})
|
||||
return
|
||||
}
|
||||
|
||||
if id != user.Identifier {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "user id mismatch"})
|
||||
return
|
||||
}
|
||||
|
||||
updateUser, err := e.app.UpdateUser(ctx, model.NewDomainUser(&user))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.NewUser(updateUser))
|
||||
}
|
||||
}
|
||||
|
||||
// handleCreatePost returns a gorm handler function.
|
||||
//
|
||||
// @ID users_handleCreatePost
|
||||
// @Tags Users
|
||||
// @Summary Create the new user record.
|
||||
// @Produce json
|
||||
// @Param request body model.User true "The user data"
|
||||
// @Success 200 {object} model.User
|
||||
// @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)
|
||||
|
||||
var user model.User
|
||||
err := c.BindJSON(&user)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
newUser, err := e.app.CreateUser(ctx, model.NewDomainUser(&user))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.NewUser(newUser))
|
||||
}
|
||||
}
|
||||
|
||||
// handlePeersGet returns a gorm handler function.
|
||||
//
|
||||
// @ID users_handlePeersGet
|
||||
// @Tags Users
|
||||
// @Summary Get peers for the given user.
|
||||
// @Produce json
|
||||
// @Success 200 {object} []model.Peer
|
||||
// @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)
|
||||
|
||||
interfaceId := Base64UrlDecode(c.Param("id"))
|
||||
if interfaceId == "" {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusInternalServerError, Message: "missing id parameter"})
|
||||
return
|
||||
}
|
||||
|
||||
peers, err := e.app.GetUserPeers(ctx, domain.UserIdentifier(interfaceId))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.NewPeers(peers))
|
||||
}
|
||||
}
|
||||
|
||||
// handleStatsGet returns a gorm handler function.
|
||||
//
|
||||
// @ID users_handleStatsGet
|
||||
// @Tags Users
|
||||
// @Summary Get peer stats for the given user.
|
||||
// @Produce json
|
||||
// @Success 200 {object} model.PeerStats
|
||||
// @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"))
|
||||
if userId == "" {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusInternalServerError, Message: "missing id parameter"})
|
||||
return
|
||||
}
|
||||
|
||||
stats, err := e.app.GetUserPeerStats(ctx, domain.UserIdentifier(userId))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.NewPeerStats(e.app.Config.Statistics.CollectPeerData, stats))
|
||||
}
|
||||
}
|
||||
|
||||
// handleDelete returns a gorm handler function.
|
||||
//
|
||||
// @ID users_handleDelete
|
||||
// @Tags Users
|
||||
// @Summary Delete the user record.
|
||||
// @Produce json
|
||||
// @Param id path string true "The user identifier"
|
||||
// @Success 204 "No content if deletion was successful"
|
||||
// @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"))
|
||||
if id == "" {
|
||||
c.JSON(http.StatusBadRequest, model.Error{Code: http.StatusBadRequest, Message: "missing user id"})
|
||||
return
|
||||
}
|
||||
|
||||
err := e.app.DeleteUser(ctx, domain.UserIdentifier(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Error{Code: http.StatusInternalServerError, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
6
internal/app/api/v0/handlers/frontend_config.js.gotpl
Normal file
6
internal/app/api/v0/handlers/frontend_config.js.gotpl
Normal file
@@ -0,0 +1,6 @@
|
||||
WGPORTAL_BACKEND_BASE_URL="{{ $.BackendUrl }}";
|
||||
WGPORTAL_VERSION="{{ $.Version }}";
|
||||
WGPORTAL_SITE_TITLE="{{ $.SiteTitle }}";
|
||||
WGPORTAL_SITE_COMPANY_NAME="{{ $.SiteCompanyName }}";
|
||||
|
||||
document.title = "{{ $.SiteTitle }}";
|
85
internal/app/api/v0/handlers/middleware_authentication.go
Normal file
85
internal/app/api/v0/handlers/middleware_authentication.go
Normal file
@@ -0,0 +1,85 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"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"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Scope string
|
||||
|
||||
const (
|
||||
ScopeAdmin Scope = "ADMIN" // Admin scope contains all other scopes
|
||||
ScopeSwagger Scope = "SWAGGER"
|
||||
ScopeUser Scope = "USER"
|
||||
)
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
92
internal/app/api/v0/handlers/session.go
Normal file
92
internal/app/api/v0/handlers/session.go
Normal file
@@ -0,0 +1,92 @@
|
||||
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))
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user