mirror of
https://github.com/h44z/wg-portal.git
synced 2025-09-13 06:21:15 +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))
|
||||
}
|
||||
}
|
136
internal/app/api/v0/model/model_options.go
Normal file
136
internal/app/api/v0/model/model_options.go
Normal file
@@ -0,0 +1,136 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"github.com/h44z/wg-portal/internal"
|
||||
"github.com/h44z/wg-portal/internal/domain"
|
||||
)
|
||||
|
||||
type StringConfigOption struct {
|
||||
Value string `json:"Value"`
|
||||
Overridable bool `json:"Overridable"`
|
||||
}
|
||||
|
||||
func NewStringConfigOption(value string, overridable bool) StringConfigOption {
|
||||
return StringConfigOption{
|
||||
Value: value,
|
||||
Overridable: overridable,
|
||||
}
|
||||
}
|
||||
|
||||
func StringConfigOptionFromDomain(opt domain.StringConfigOption) StringConfigOption {
|
||||
return StringConfigOption{
|
||||
Value: opt.Value,
|
||||
Overridable: opt.Overridable,
|
||||
}
|
||||
}
|
||||
|
||||
func StringConfigOptionToDomain(opt StringConfigOption) domain.StringConfigOption {
|
||||
return domain.StringConfigOption{
|
||||
Value: opt.Value,
|
||||
Overridable: opt.Overridable,
|
||||
}
|
||||
}
|
||||
|
||||
type StringSliceConfigOption struct {
|
||||
Value []string `json:"Value"`
|
||||
Overridable bool `json:"Overridable"`
|
||||
}
|
||||
|
||||
func NewStringSliceConfigOption(value []string, overridable bool) StringSliceConfigOption {
|
||||
return StringSliceConfigOption{
|
||||
Value: value,
|
||||
Overridable: overridable,
|
||||
}
|
||||
}
|
||||
|
||||
func StringSliceConfigOptionFromDomain(opt domain.StringConfigOption) StringSliceConfigOption {
|
||||
return StringSliceConfigOption{
|
||||
Value: internal.SliceString(opt.Value),
|
||||
Overridable: opt.Overridable,
|
||||
}
|
||||
}
|
||||
|
||||
func StringSliceConfigOptionToDomain(opt StringSliceConfigOption) domain.StringConfigOption {
|
||||
return domain.StringConfigOption{
|
||||
Value: internal.SliceToString(opt.Value),
|
||||
Overridable: opt.Overridable,
|
||||
}
|
||||
}
|
||||
|
||||
type IntConfigOption struct {
|
||||
Value int `json:"Value"`
|
||||
Overridable bool `json:"Overridable"`
|
||||
}
|
||||
|
||||
func NewIntConfigOption(value int, overridable bool) IntConfigOption {
|
||||
return IntConfigOption{
|
||||
Value: value,
|
||||
Overridable: overridable,
|
||||
}
|
||||
}
|
||||
|
||||
func IntConfigOptionFromDomain(opt domain.IntConfigOption) IntConfigOption {
|
||||
return IntConfigOption{
|
||||
Value: opt.Value,
|
||||
Overridable: opt.Overridable,
|
||||
}
|
||||
}
|
||||
|
||||
func IntConfigOptionToDomain(opt IntConfigOption) domain.IntConfigOption {
|
||||
return domain.IntConfigOption{
|
||||
Value: opt.Value,
|
||||
Overridable: opt.Overridable,
|
||||
}
|
||||
}
|
||||
|
||||
type Int32ConfigOption struct {
|
||||
Value int32 `json:"Value"`
|
||||
Overridable bool `json:"Overridable"`
|
||||
}
|
||||
|
||||
func NewInt32ConfigOption(value int32, overridable bool) Int32ConfigOption {
|
||||
return Int32ConfigOption{
|
||||
Value: value,
|
||||
Overridable: overridable,
|
||||
}
|
||||
}
|
||||
|
||||
func Int32ConfigOptionFromDomain(opt domain.Int32ConfigOption) Int32ConfigOption {
|
||||
return Int32ConfigOption{
|
||||
Value: opt.Value,
|
||||
Overridable: opt.Overridable,
|
||||
}
|
||||
}
|
||||
|
||||
func Int32ConfigOptionToDomain(opt Int32ConfigOption) domain.Int32ConfigOption {
|
||||
return domain.Int32ConfigOption{
|
||||
Value: opt.Value,
|
||||
Overridable: opt.Overridable,
|
||||
}
|
||||
}
|
||||
|
||||
type BoolConfigOption struct {
|
||||
Value bool `json:"Value"`
|
||||
Overridable bool `json:"Overridable"`
|
||||
}
|
||||
|
||||
func NewBoolConfigOption(value bool, overridable bool) BoolConfigOption {
|
||||
return BoolConfigOption{
|
||||
Value: value,
|
||||
Overridable: overridable,
|
||||
}
|
||||
}
|
||||
|
||||
func BoolConfigOptionFromDomain(opt domain.BoolConfigOption) BoolConfigOption {
|
||||
return BoolConfigOption{
|
||||
Value: opt.Value,
|
||||
Overridable: opt.Overridable,
|
||||
}
|
||||
}
|
||||
|
||||
func BoolConfigOptionToDomain(opt BoolConfigOption) domain.BoolConfigOption {
|
||||
return domain.BoolConfigOption{
|
||||
Value: opt.Value,
|
||||
Overridable: opt.Overridable,
|
||||
}
|
||||
}
|
12
internal/app/api/v0/model/models.go
Normal file
12
internal/app/api/v0/model/models.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package model
|
||||
|
||||
type Error struct {
|
||||
Code int `json:"Code"`
|
||||
Message string `json:"Message"`
|
||||
}
|
||||
|
||||
type Settings struct {
|
||||
MailLinkOnly bool `json:"MailLinkOnly"`
|
||||
PersistentConfigSupported bool `json:"PersistentConfigSupported"`
|
||||
SelfProvisioning bool `json:"SelfProvisioning"`
|
||||
}
|
41
internal/app/api/v0/model/models_authentication.go
Normal file
41
internal/app/api/v0/model/models_authentication.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package model
|
||||
|
||||
import "github.com/h44z/wg-portal/internal/domain"
|
||||
|
||||
type LoginProviderInfo struct {
|
||||
Identifier string `json:"Identifier" example:"google"`
|
||||
Name string `json:"Name" example:"Login with Google"`
|
||||
ProviderUrl string `json:"ProviderUrl" example:"/auth/google/login"`
|
||||
CallbackUrl string `json:"CallbackUrl" example:"/auth/google/callback"`
|
||||
}
|
||||
|
||||
func NewLoginProviderInfo(src *domain.LoginProviderInfo) *LoginProviderInfo {
|
||||
return &LoginProviderInfo{
|
||||
Identifier: src.Identifier,
|
||||
Name: src.Name,
|
||||
ProviderUrl: src.ProviderUrl,
|
||||
CallbackUrl: src.CallbackUrl,
|
||||
}
|
||||
}
|
||||
|
||||
func NewLoginProviderInfos(src []domain.LoginProviderInfo) []LoginProviderInfo {
|
||||
accessories := make([]LoginProviderInfo, len(src))
|
||||
for i := range src {
|
||||
accessories[i] = *NewLoginProviderInfo(&src[i])
|
||||
}
|
||||
return accessories
|
||||
}
|
||||
|
||||
type SessionInfo struct {
|
||||
LoggedIn bool `json:"LoggedIn"`
|
||||
IsAdmin bool `json:"IsAdmin,omitempty"`
|
||||
UserIdentifier *string `json:"UserIdentifier,omitempty"`
|
||||
UserFirstname *string `json:"UserFirstname,omitempty"`
|
||||
UserLastname *string `json:"UserLastname,omitempty"`
|
||||
UserEmail *string `json:"UserEmail,omitempty"`
|
||||
}
|
||||
|
||||
type OauthInitiationResponse struct {
|
||||
RedirectUrl string
|
||||
State string
|
||||
}
|
166
internal/app/api/v0/model/models_interface.go
Normal file
166
internal/app/api/v0/model/models_interface.go
Normal file
@@ -0,0 +1,166 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"github.com/h44z/wg-portal/internal"
|
||||
"time"
|
||||
|
||||
"github.com/h44z/wg-portal/internal/domain"
|
||||
)
|
||||
|
||||
type Interface struct {
|
||||
Identifier string `json:"Identifier" example:"wg0"` // device name, for example: wg0
|
||||
DisplayName string `json:"DisplayName"` // a nice display name/ description for the interface
|
||||
Mode string `json:"Mode" example:"server"` // the interface type, either 'server', 'client' or 'any'
|
||||
PrivateKey string `json:"PrivateKey" example:"abcdef=="` // private Key of the server interface
|
||||
PublicKey string `json:"PublicKey" example:"abcdef=="` // public Key of the server interface
|
||||
Disabled bool `json:"Disabled"` // flag that specifies if the interface is enabled (up) or not (down)
|
||||
DisabledReason string `json:"DisabledReason"` // the reason why the interface has been disabled
|
||||
SaveConfig bool `json:"SaveConfig"` // automatically persist config changes to the wgX.conf file
|
||||
|
||||
ListenPort int `json:"ListenPort"` // the listening port, for example: 51820
|
||||
Addresses []string `json:"Addresses"` // the interface ip addresses
|
||||
Dns []string `json:"Dns"` // the dns server that should be set if the interface is up, comma separated
|
||||
DnsSearch []string `json:"DnsSearch"` // the dns search option string that should be set if the interface is up, will be appended to DnsStr
|
||||
Mtu int `json:"Mtu"` // the device MTU
|
||||
FirewallMark int32 `json:"FirewallMark"` // a firewall mark
|
||||
RoutingTable string `json:"RoutingTable"` // the routing table
|
||||
|
||||
PreUp string `json:"PreUp"` // action that is executed before the device is up
|
||||
PostUp string `json:"PostUp"` // action that is executed after the device is up
|
||||
PreDown string `json:"PreDown"` // action that is executed before the device is down
|
||||
PostDown string `json:"PostDown"` // action that is executed after the device is down
|
||||
|
||||
PeerDefNetwork []string `json:"PeerDefNetwork"` // the default subnets from which peers will get their IP addresses, comma seperated
|
||||
PeerDefDns []string `json:"PeerDefDns"` // the default dns server for the peer
|
||||
PeerDefDnsSearch []string `json:"PeerDefDnsSearch"` // the default dns search options for the peer
|
||||
PeerDefEndpoint string `json:"PeerDefEndpoint"` // the default endpoint for the peer
|
||||
PeerDefAllowedIPs []string `json:"PeerDefAllowedIPs"` // the default allowed IP string for the peer
|
||||
PeerDefMtu int `json:"PeerDefMtu"` // the default device MTU
|
||||
PeerDefPersistentKeepalive int `json:"PeerDefPersistentKeepalive"` // the default persistent keep-alive Value
|
||||
PeerDefFirewallMark int32 `json:"PeerDefFirewallMark"` // default firewall mark
|
||||
PeerDefRoutingTable string `json:"PeerDefRoutingTable"` // the default routing table
|
||||
|
||||
PeerDefPreUp string `json:"PeerDefPreUp"` // default action that is executed before the device is up
|
||||
PeerDefPostUp string `json:"PeerDefPostUp"` // default action that is executed after the device is up
|
||||
PeerDefPreDown string `json:"PeerDefPreDown"` // default action that is executed before the device is down
|
||||
PeerDefPostDown string `json:"PeerDefPostDown"` // default action that is executed after the device is down
|
||||
|
||||
// Calculated values
|
||||
|
||||
EnabledPeers int `json:"EnabledPeers"`
|
||||
TotalPeers int `json:"TotalPeers"`
|
||||
}
|
||||
|
||||
func NewInterface(src *domain.Interface, peers []domain.Peer) *Interface {
|
||||
iface := &Interface{
|
||||
Identifier: string(src.Identifier),
|
||||
DisplayName: src.DisplayName,
|
||||
Mode: string(src.Type),
|
||||
PrivateKey: src.PrivateKey,
|
||||
PublicKey: src.PublicKey,
|
||||
Disabled: src.IsDisabled(),
|
||||
DisabledReason: src.DisabledReason,
|
||||
SaveConfig: src.SaveConfig,
|
||||
ListenPort: src.ListenPort,
|
||||
Addresses: domain.CidrsToStringSlice(src.Addresses),
|
||||
Dns: internal.SliceString(src.DnsStr),
|
||||
DnsSearch: internal.SliceString(src.DnsSearchStr),
|
||||
Mtu: src.Mtu,
|
||||
FirewallMark: src.FirewallMark,
|
||||
RoutingTable: src.RoutingTable,
|
||||
PreUp: src.PreUp,
|
||||
PostUp: src.PostUp,
|
||||
PreDown: src.PreDown,
|
||||
PostDown: src.PostDown,
|
||||
PeerDefNetwork: internal.SliceString(src.PeerDefNetworkStr),
|
||||
PeerDefDns: internal.SliceString(src.PeerDefDnsStr),
|
||||
PeerDefDnsSearch: internal.SliceString(src.PeerDefDnsSearchStr),
|
||||
PeerDefEndpoint: src.PeerDefEndpoint,
|
||||
PeerDefAllowedIPs: internal.SliceString(src.PeerDefAllowedIPsStr),
|
||||
PeerDefMtu: src.PeerDefMtu,
|
||||
PeerDefPersistentKeepalive: src.PeerDefPersistentKeepalive,
|
||||
PeerDefFirewallMark: src.PeerDefFirewallMark,
|
||||
PeerDefRoutingTable: src.PeerDefRoutingTable,
|
||||
PeerDefPreUp: src.PeerDefPreUp,
|
||||
PeerDefPostUp: src.PeerDefPostUp,
|
||||
PeerDefPreDown: src.PeerDefPreDown,
|
||||
PeerDefPostDown: src.PeerDefPostDown,
|
||||
|
||||
EnabledPeers: 0,
|
||||
TotalPeers: 0,
|
||||
}
|
||||
|
||||
if len(peers) > 0 {
|
||||
iface.TotalPeers = len(peers)
|
||||
|
||||
activePeers := 0
|
||||
for _, peer := range peers {
|
||||
if !peer.IsDisabled() {
|
||||
activePeers++
|
||||
}
|
||||
}
|
||||
iface.EnabledPeers = activePeers
|
||||
}
|
||||
|
||||
return iface
|
||||
}
|
||||
|
||||
func NewInterfaces(src []domain.Interface, srcPeers [][]domain.Peer) []Interface {
|
||||
results := make([]Interface, len(src))
|
||||
for i := range src {
|
||||
results[i] = *NewInterface(&src[i], srcPeers[i])
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
func NewDomainInterface(src *Interface) *domain.Interface {
|
||||
now := time.Now()
|
||||
|
||||
cidrs, _ := domain.CidrsFromArray(src.Addresses)
|
||||
|
||||
res := &domain.Interface{
|
||||
BaseModel: domain.BaseModel{},
|
||||
Identifier: domain.InterfaceIdentifier(src.Identifier),
|
||||
KeyPair: domain.KeyPair{
|
||||
PrivateKey: src.PrivateKey,
|
||||
PublicKey: src.PublicKey,
|
||||
},
|
||||
ListenPort: src.ListenPort,
|
||||
Addresses: cidrs,
|
||||
DnsStr: internal.SliceToString(src.Dns),
|
||||
DnsSearchStr: internal.SliceToString(src.DnsSearch),
|
||||
Mtu: src.Mtu,
|
||||
FirewallMark: src.FirewallMark,
|
||||
RoutingTable: src.RoutingTable,
|
||||
PreUp: src.PreUp,
|
||||
PostUp: src.PostUp,
|
||||
PreDown: src.PreDown,
|
||||
PostDown: src.PostDown,
|
||||
SaveConfig: src.SaveConfig,
|
||||
DisplayName: src.DisplayName,
|
||||
Type: domain.InterfaceType(src.Mode),
|
||||
DriverType: "", // currently unused
|
||||
Disabled: nil, // set below
|
||||
DisabledReason: src.DisabledReason,
|
||||
PeerDefNetworkStr: internal.SliceToString(src.PeerDefNetwork),
|
||||
PeerDefDnsStr: internal.SliceToString(src.PeerDefDns),
|
||||
PeerDefDnsSearchStr: internal.SliceToString(src.PeerDefDnsSearch),
|
||||
PeerDefEndpoint: src.PeerDefEndpoint,
|
||||
PeerDefAllowedIPsStr: internal.SliceToString(src.PeerDefAllowedIPs),
|
||||
PeerDefMtu: src.PeerDefMtu,
|
||||
PeerDefPersistentKeepalive: src.PeerDefPersistentKeepalive,
|
||||
PeerDefFirewallMark: src.PeerDefFirewallMark,
|
||||
PeerDefRoutingTable: src.PeerDefRoutingTable,
|
||||
PeerDefPreUp: src.PeerDefPreUp,
|
||||
PeerDefPostUp: src.PeerDefPostUp,
|
||||
PeerDefPreDown: src.PeerDefPreDown,
|
||||
PeerDefPostDown: src.PeerDefPostDown,
|
||||
}
|
||||
|
||||
if src.Disabled {
|
||||
res.Disabled = &now
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
224
internal/app/api/v0/model/models_peer.go
Normal file
224
internal/app/api/v0/model/models_peer.go
Normal file
@@ -0,0 +1,224 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"github.com/h44z/wg-portal/internal"
|
||||
"github.com/h44z/wg-portal/internal/domain"
|
||||
"time"
|
||||
)
|
||||
|
||||
const ExpiryDateTimeLayout = "\"2006-01-02\""
|
||||
|
||||
type ExpiryDate struct {
|
||||
*time.Time
|
||||
}
|
||||
|
||||
// UnmarshalJSON will unmarshal using 2006-01-02 layout
|
||||
func (d *ExpiryDate) UnmarshalJSON(b []byte) error {
|
||||
if len(b) == 0 || string(b) == "null" || string(b) == "\"\"" {
|
||||
return nil
|
||||
}
|
||||
parsed, err := time.Parse(ExpiryDateTimeLayout, string(b))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !parsed.IsZero() {
|
||||
d.Time = &parsed
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON will marshal using 2006-01-02 layout
|
||||
func (d *ExpiryDate) MarshalJSON() ([]byte, error) {
|
||||
if d == nil || d.Time == nil {
|
||||
return []byte("null"), nil
|
||||
}
|
||||
|
||||
s := d.Format(ExpiryDateTimeLayout)
|
||||
return []byte(s), nil
|
||||
}
|
||||
|
||||
type Peer struct {
|
||||
Identifier string `json:"Identifier" example:"super_nice_peer"` // peer unique identifier
|
||||
DisplayName string `json:"DisplayName"` // a nice display name/ description for the peer
|
||||
UserIdentifier string `json:"UserIdentifier"` // the owner
|
||||
InterfaceIdentifier string `json:"InterfaceIdentifier"` // the interface id
|
||||
Disabled bool `json:"Disabled"` // flag that specifies if the peer is enabled (up) or not (down)
|
||||
DisabledReason string `json:"DisabledReason"` // the reason why the peer has been disabled
|
||||
ExpiresAt ExpiryDate `json:"ExpiresAt,omitempty"` // expiry dates for peers
|
||||
Notes string `json:"Notes"` // a note field for peers
|
||||
|
||||
Endpoint StringConfigOption `json:"Endpoint"` // the endpoint address
|
||||
EndpointPublicKey StringConfigOption `json:"EndpointPublicKey"` // the endpoint public key
|
||||
AllowedIPs StringSliceConfigOption `json:"AllowedIPs"` // all allowed ip subnets, comma seperated
|
||||
ExtraAllowedIPs []string `json:"ExtraAllowedIPs"` // all allowed ip subnets on the server side, comma seperated
|
||||
PresharedKey string `json:"PresharedKey"` // the pre-shared Key of the peer
|
||||
PersistentKeepalive IntConfigOption `json:"PersistentKeepalive"` // the persistent keep-alive interval
|
||||
|
||||
PrivateKey string `json:"PrivateKey" example:"abcdef=="` // private Key of the server peer
|
||||
PublicKey string `json:"PublicKey" example:"abcdef=="` // public Key of the server peer
|
||||
|
||||
Mode string // the peer interface type (server, client, any)
|
||||
|
||||
Addresses []string `json:"Addresses"` // the interface ip addresses
|
||||
CheckAliveAddress string `json:"CheckAliveAddress"` // optional ip address or DNS name that is used for ping checks
|
||||
Dns StringSliceConfigOption `json:"Dns"` // the dns server that should be set if the interface is up, comma separated
|
||||
DnsSearch StringSliceConfigOption `json:"DnsSearch"` // the dns search option string that should be set if the interface is up, will be appended to DnsStr
|
||||
Mtu IntConfigOption `json:"Mtu"` // the device MTU
|
||||
FirewallMark Int32ConfigOption `json:"FirewallMark"` // a firewall mark
|
||||
RoutingTable StringConfigOption `json:"RoutingTable"` // the routing table
|
||||
|
||||
PreUp StringConfigOption `json:"PreUp"` // action that is executed before the device is up
|
||||
PostUp StringConfigOption `json:"PostUp"` // action that is executed after the device is up
|
||||
PreDown StringConfigOption `json:"PreDown"` // action that is executed before the device is down
|
||||
PostDown StringConfigOption `json:"PostDown"` // action that is executed after the device is down
|
||||
}
|
||||
|
||||
func NewPeer(src *domain.Peer) *Peer {
|
||||
return &Peer{
|
||||
Identifier: string(src.Identifier),
|
||||
DisplayName: src.DisplayName,
|
||||
UserIdentifier: string(src.UserIdentifier),
|
||||
InterfaceIdentifier: string(src.InterfaceIdentifier),
|
||||
Disabled: src.IsDisabled(),
|
||||
DisabledReason: src.DisabledReason,
|
||||
ExpiresAt: ExpiryDate{src.ExpiresAt},
|
||||
Notes: src.Notes,
|
||||
Endpoint: StringConfigOptionFromDomain(src.Endpoint),
|
||||
EndpointPublicKey: StringConfigOptionFromDomain(src.EndpointPublicKey),
|
||||
AllowedIPs: StringSliceConfigOptionFromDomain(src.AllowedIPsStr),
|
||||
ExtraAllowedIPs: internal.SliceString(src.ExtraAllowedIPsStr),
|
||||
PresharedKey: string(src.PresharedKey),
|
||||
PersistentKeepalive: IntConfigOptionFromDomain(src.PersistentKeepalive),
|
||||
PrivateKey: src.Interface.PrivateKey,
|
||||
PublicKey: src.Interface.PublicKey,
|
||||
Mode: string(src.Interface.Type),
|
||||
Addresses: domain.CidrsToStringSlice(src.Interface.Addresses),
|
||||
CheckAliveAddress: src.Interface.CheckAliveAddress,
|
||||
Dns: StringSliceConfigOptionFromDomain(src.Interface.DnsStr),
|
||||
DnsSearch: StringSliceConfigOptionFromDomain(src.Interface.DnsSearchStr),
|
||||
Mtu: IntConfigOptionFromDomain(src.Interface.Mtu),
|
||||
FirewallMark: Int32ConfigOptionFromDomain(src.Interface.FirewallMark),
|
||||
RoutingTable: StringConfigOptionFromDomain(src.Interface.RoutingTable),
|
||||
PreUp: StringConfigOptionFromDomain(src.Interface.PreUp),
|
||||
PostUp: StringConfigOptionFromDomain(src.Interface.PostUp),
|
||||
PreDown: StringConfigOptionFromDomain(src.Interface.PreDown),
|
||||
PostDown: StringConfigOptionFromDomain(src.Interface.PostDown),
|
||||
}
|
||||
}
|
||||
|
||||
func NewPeers(src []domain.Peer) []Peer {
|
||||
results := make([]Peer, len(src))
|
||||
for i := range src {
|
||||
results[i] = *NewPeer(&src[i])
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
func NewDomainPeer(src *Peer) *domain.Peer {
|
||||
now := time.Now()
|
||||
|
||||
cidrs, _ := domain.CidrsFromArray(src.Addresses)
|
||||
|
||||
res := &domain.Peer{
|
||||
BaseModel: domain.BaseModel{},
|
||||
Endpoint: StringConfigOptionToDomain(src.Endpoint),
|
||||
EndpointPublicKey: StringConfigOptionToDomain(src.EndpointPublicKey),
|
||||
AllowedIPsStr: StringSliceConfigOptionToDomain(src.AllowedIPs),
|
||||
ExtraAllowedIPsStr: internal.SliceToString(src.ExtraAllowedIPs),
|
||||
PresharedKey: domain.PreSharedKey(src.PresharedKey),
|
||||
PersistentKeepalive: IntConfigOptionToDomain(src.PersistentKeepalive),
|
||||
DisplayName: src.DisplayName,
|
||||
Identifier: domain.PeerIdentifier(src.Identifier),
|
||||
UserIdentifier: domain.UserIdentifier(src.UserIdentifier),
|
||||
InterfaceIdentifier: domain.InterfaceIdentifier(src.InterfaceIdentifier),
|
||||
Disabled: nil, // set below
|
||||
DisabledReason: src.DisabledReason,
|
||||
ExpiresAt: src.ExpiresAt.Time,
|
||||
Notes: src.Notes,
|
||||
Interface: domain.PeerInterfaceConfig{
|
||||
KeyPair: domain.KeyPair{
|
||||
PrivateKey: src.PrivateKey,
|
||||
PublicKey: src.PublicKey,
|
||||
},
|
||||
Type: domain.InterfaceType(src.Mode),
|
||||
Addresses: cidrs,
|
||||
CheckAliveAddress: src.CheckAliveAddress,
|
||||
DnsStr: StringSliceConfigOptionToDomain(src.Dns),
|
||||
DnsSearchStr: StringSliceConfigOptionToDomain(src.DnsSearch),
|
||||
Mtu: IntConfigOptionToDomain(src.Mtu),
|
||||
FirewallMark: Int32ConfigOptionToDomain(src.FirewallMark),
|
||||
RoutingTable: StringConfigOptionToDomain(src.RoutingTable),
|
||||
PreUp: StringConfigOptionToDomain(src.PreUp),
|
||||
PostUp: StringConfigOptionToDomain(src.PostUp),
|
||||
PreDown: StringConfigOptionToDomain(src.PreDown),
|
||||
PostDown: StringConfigOptionToDomain(src.PostDown),
|
||||
},
|
||||
}
|
||||
|
||||
if src.Disabled {
|
||||
res.Disabled = &now
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
type MultiPeerRequest struct {
|
||||
Identifiers []string `json:"Identifiers"`
|
||||
Suffix string `json:"Suffix"`
|
||||
}
|
||||
|
||||
func NewDomainPeerCreationRequest(src *MultiPeerRequest) *domain.PeerCreationRequest {
|
||||
return &domain.PeerCreationRequest{
|
||||
UserIdentifiers: src.Identifiers,
|
||||
Suffix: src.Suffix,
|
||||
}
|
||||
}
|
||||
|
||||
type PeerMailRequest struct {
|
||||
Identifiers []string `json:"Identifiers"`
|
||||
LinkOnly bool `json:"LinkOnly"`
|
||||
}
|
||||
|
||||
type PeerStats struct {
|
||||
Enabled bool `json:"Enabled" example:"true"` // peer stats tracking enabled
|
||||
|
||||
Stats map[string]PeerStatData `json:"Stats"` // stats, map key = Peer identifier
|
||||
}
|
||||
|
||||
func NewPeerStats(enabled bool, src []domain.PeerStatus) *PeerStats {
|
||||
stats := make(map[string]PeerStatData, len(src))
|
||||
|
||||
for _, srcStat := range src {
|
||||
stats[string(srcStat.PeerId)] = PeerStatData{
|
||||
IsConnected: srcStat.IsConnected(),
|
||||
IsPingable: srcStat.IsPingable,
|
||||
LastPing: srcStat.LastPing,
|
||||
BytesReceived: srcStat.BytesReceived,
|
||||
BytesTransmitted: srcStat.BytesTransmitted,
|
||||
LastHandshake: srcStat.LastHandshake,
|
||||
EndpointAddress: srcStat.Endpoint,
|
||||
LastSessionStart: srcStat.LastSessionStart,
|
||||
}
|
||||
}
|
||||
|
||||
return &PeerStats{
|
||||
Enabled: enabled,
|
||||
Stats: stats,
|
||||
}
|
||||
}
|
||||
|
||||
type PeerStatData struct {
|
||||
IsConnected bool `json:"IsConnected"`
|
||||
|
||||
IsPingable bool `json:"IsPingable"`
|
||||
LastPing *time.Time `json:"LastPing"`
|
||||
|
||||
BytesReceived uint64 `json:"BytesReceived"`
|
||||
BytesTransmitted uint64 `json:"BytesTransmitted"`
|
||||
|
||||
LastHandshake *time.Time `json:"LastHandshake"`
|
||||
EndpointAddress string `json:"EndpointAddress"`
|
||||
LastSessionStart *time.Time `json:"LastSessionStart"`
|
||||
}
|
94
internal/app/api/v0/model/models_user.go
Normal file
94
internal/app/api/v0/model/models_user.go
Normal file
@@ -0,0 +1,94 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/h44z/wg-portal/internal/domain"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
Identifier string `json:"Identifier"`
|
||||
Email string `json:"Email"`
|
||||
Source string `json:"Source"`
|
||||
ProviderName string `json:"ProviderName"`
|
||||
IsAdmin bool `json:"IsAdmin"`
|
||||
|
||||
Firstname string `json:"Firstname"`
|
||||
Lastname string `json:"Lastname"`
|
||||
Phone string `json:"Phone"`
|
||||
Department string `json:"Department"`
|
||||
Notes string `json:"Notes"`
|
||||
|
||||
Password string `json:"Password,omitempty"`
|
||||
Disabled bool `json:"Disabled"` // if this field is set, the user is disabled
|
||||
DisabledReason string `json:"DisabledReason"` // the reason why the user has been disabled
|
||||
Locked bool `json:"Locked"` // if this field is set, the user is locked
|
||||
LockedReason string `json:"LockedReason"` // the reason why the user has been locked
|
||||
|
||||
// Calculated
|
||||
|
||||
PeerCount int `json:"PeerCount"`
|
||||
}
|
||||
|
||||
func NewUser(src *domain.User) *User {
|
||||
return &User{
|
||||
Identifier: string(src.Identifier),
|
||||
Email: src.Email,
|
||||
Source: string(src.Source),
|
||||
ProviderName: src.ProviderName,
|
||||
IsAdmin: src.IsAdmin,
|
||||
Firstname: src.Firstname,
|
||||
Lastname: src.Lastname,
|
||||
Phone: src.Phone,
|
||||
Department: src.Department,
|
||||
Notes: src.Notes,
|
||||
Password: "", // never fill password
|
||||
Disabled: src.IsDisabled(),
|
||||
DisabledReason: src.DisabledReason,
|
||||
Locked: src.IsLocked(),
|
||||
LockedReason: src.LockedReason,
|
||||
|
||||
PeerCount: src.LinkedPeerCount,
|
||||
}
|
||||
}
|
||||
|
||||
func NewUsers(src []domain.User) []User {
|
||||
results := make([]User, len(src))
|
||||
for i := range src {
|
||||
results[i] = *NewUser(&src[i])
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
func NewDomainUser(src *User) *domain.User {
|
||||
now := time.Now()
|
||||
res := &domain.User{
|
||||
Identifier: domain.UserIdentifier(src.Identifier),
|
||||
Email: src.Email,
|
||||
Source: domain.UserSource(src.Source),
|
||||
ProviderName: src.ProviderName,
|
||||
IsAdmin: src.IsAdmin,
|
||||
Firstname: src.Firstname,
|
||||
Lastname: src.Lastname,
|
||||
Phone: src.Phone,
|
||||
Department: src.Department,
|
||||
Notes: src.Notes,
|
||||
Password: domain.PrivateString(src.Password),
|
||||
Disabled: nil, // set below
|
||||
DisabledReason: src.DisabledReason,
|
||||
Locked: nil, // set below
|
||||
LockedReason: src.LockedReason,
|
||||
LinkedPeerCount: src.PeerCount,
|
||||
}
|
||||
|
||||
if src.Disabled {
|
||||
res.Disabled = &now
|
||||
}
|
||||
|
||||
if src.Locked {
|
||||
res.Locked = &now
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
Reference in New Issue
Block a user