chore: cleanup code formatting

This commit is contained in:
Christoph Haas
2025-02-28 08:29:40 +01:00
parent f7d7038829
commit e24acfa57d
67 changed files with 232 additions and 489 deletions

View File

@@ -9,18 +9,18 @@ import (
"strings"
"time"
"github.com/sirupsen/logrus"
"gorm.io/gorm/clause"
"gorm.io/gorm/logger"
"gorm.io/gorm/utils"
"github.com/glebarez/sqlite"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
"github.com/sirupsen/logrus"
gormMySQL "gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlserver"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/logger"
"gorm.io/gorm/utils"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
)
// SchemaVersion describes the current database schema version. It must be incremented if a manual migration is needed.
@@ -60,21 +60,21 @@ func (l *GormLogger) LogMode(level logger.LogLevel) logger.Interface {
return l
}
func (l *GormLogger) Info(ctx context.Context, s string, args ...interface{}) {
func (l *GormLogger) Info(ctx context.Context, s string, args ...any) {
if l.Silent {
return
}
logrus.WithContext(ctx).Infof(s, args...)
}
func (l *GormLogger) Warn(ctx context.Context, s string, args ...interface{}) {
func (l *GormLogger) Warn(ctx context.Context, s string, args ...any) {
if l.Silent {
return
}
logrus.WithContext(ctx).Warnf(s, args...)
}
func (l *GormLogger) Error(ctx context.Context, s string, args ...interface{}) {
func (l *GormLogger) Error(ctx context.Context, s string, args ...any) {
if l.Silent {
return
}

View File

@@ -5,17 +5,14 @@ package adapters
import (
"database/sql"
"fmt"
"testing"
"github.com/glebarez/sqlite"
"github.com/stretchr/testify/assert"
"gorm.io/gorm"
"testing"
)
func tempSqliteDb(t *testing.T) *gorm.DB {
// github.com/mattn/go-sqlite3
db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{})
if err != nil {
t.Fatal(err)

View File

@@ -2,10 +2,11 @@ package adapters
import (
"fmt"
"github.com/sirupsen/logrus"
"io"
"os"
"path/filepath"
"github.com/sirupsen/logrus"
)
type FilesystemRepo struct {
@@ -36,7 +37,7 @@ func (r *FilesystemRepo) WriteFile(path string, contents io.Reader) error {
file, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, os.ModePerm)
if err != nil {
return fmt.Errorf("failed to open file %s: %w", file.Name(), err)
return fmt.Errorf("failed to open file %s: %w", filePath, err)
}
defer func(file *os.File) {
if err := file.Close(); err != nil {

View File

@@ -5,12 +5,14 @@ import (
"crypto/tls"
"errors"
"fmt"
"io"
"time"
mail "github.com/xhit/go-simple-mail/v2"
"github.com/h44z/wg-portal/internal"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
mail "github.com/xhit/go-simple-mail/v2"
"io"
"time"
)
type MailRepo struct {

View File

@@ -2,16 +2,18 @@ package adapters
import (
"context"
"errors"
"net/http"
"time"
"github.com/h44z/wg-portal/internal"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
"github.com/h44z/wg-portal/internal"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
)
type MetricsServer struct {
@@ -88,7 +90,7 @@ func NewMetricsServer(cfg *config.Config) *MetricsServer {
func (m *MetricsServer) Run(ctx context.Context) {
// Run the metrics server in a goroutine
go func() {
if err := m.ListenAndServe(); err != nil && err != http.ErrServerClosed {
if err := m.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
logrus.Errorf("metrics service on %s exited: %v", m.Addr, err)
}
}()

View File

@@ -6,9 +6,10 @@ import (
"os/exec"
"strings"
"github.com/sirupsen/logrus"
"github.com/h44z/wg-portal/internal"
"github.com/h44z/wg-portal/internal/domain"
"github.com/sirupsen/logrus"
)
// WgQuickRepo implements higher level wg-quick like interactions like setting DNS, routing tables or interface hooks.

View File

@@ -6,11 +6,12 @@ import (
"fmt"
"os"
"github.com/h44z/wg-portal/internal/domain"
"github.com/h44z/wg-portal/internal/lowlevel"
"github.com/vishvananda/netlink"
"golang.zx2c4.com/wireguard/wgctrl"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
"github.com/h44z/wg-portal/internal/domain"
"github.com/h44z/wg-portal/internal/lowlevel"
)
// WgRepo implements all low-level WireGuard interactions.

View File

@@ -12,11 +12,10 @@ import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/h44z/wg-portal/internal/domain"
"github.com/stretchr/testify/assert"
)
// setup WireGuard manager with no linked store
@@ -68,13 +67,14 @@ func TestWireGuardCreateInterface(t *testing.T) {
ipV6Address := "1337:d34d:b33f::2"
defer mgr.DeleteInterface(context.Background(), interfaceName)
err := mgr.SaveInterface(context.Background(), interfaceName, func(pi *domain.PhysicalInterface) (*domain.PhysicalInterface, error) {
pi.Addresses = []domain.Cidr{
domain.CidrFromIpNet(net.IPNet{IP: net.ParseIP(ipAddress), Mask: net.CIDRMask(24, 32)}),
domain.CidrFromIpNet(net.IPNet{IP: net.ParseIP(ipV6Address), Mask: net.CIDRMask(64, 128)}),
}
return pi, nil
})
err := mgr.SaveInterface(context.Background(), interfaceName,
func(pi *domain.PhysicalInterface) (*domain.PhysicalInterface, error) {
pi.Addresses = []domain.Cidr{
domain.CidrFromIpNet(net.IPNet{IP: net.ParseIP(ipAddress), Mask: net.CIDRMask(24, 32)}),
domain.CidrFromIpNet(net.IPNet{IP: net.ParseIP(ipV6Address), Mask: net.CIDRMask(64, 128)}),
}
return pi, nil
})
assert.NoError(t, err)
// Validate that the interface has been created
@@ -102,13 +102,14 @@ func TestWireGuardUpdateInterface(t *testing.T) {
ipAddress := "10.11.12.13"
ipV6Address := "1337:d34d:b33f::2"
err = mgr.SaveInterface(context.Background(), interfaceName, func(pi *domain.PhysicalInterface) (*domain.PhysicalInterface, error) {
pi.Addresses = []domain.Cidr{
domain.CidrFromIpNet(net.IPNet{IP: net.ParseIP(ipAddress), Mask: net.CIDRMask(24, 32)}),
domain.CidrFromIpNet(net.IPNet{IP: net.ParseIP(ipV6Address), Mask: net.CIDRMask(64, 128)}),
}
return pi, nil
})
err = mgr.SaveInterface(context.Background(), interfaceName,
func(pi *domain.PhysicalInterface) (*domain.PhysicalInterface, error) {
pi.Addresses = []domain.Cidr{
domain.CidrFromIpNet(net.IPNet{IP: net.ParseIP(ipAddress), Mask: net.CIDRMask(24, 32)}),
domain.CidrFromIpNet(net.IPNet{IP: net.ParseIP(ipV6Address), Mask: net.CIDRMask(64, 128)}),
}
return pi, nil
})
assert.NoError(t, err)
// Validate that the interface has been updated

View File

@@ -12,12 +12,12 @@ import (
"os"
"time"
"github.com/h44z/wg-portal/internal"
"github.com/h44z/wg-portal/internal/config"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
ginlogrus "github.com/toorop/gin-logrus"
"github.com/h44z/wg-portal/internal"
"github.com/h44z/wg-portal/internal/config"
)
var (

View File

@@ -8,11 +8,12 @@ import (
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/memstore"
"github.com/gin-gonic/gin"
csrf "github.com/utrack/gin-csrf"
"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"
)
type handler interface {

View File

@@ -9,6 +9,7 @@ import (
"time"
"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"

View File

@@ -10,6 +10,7 @@ import (
"net/url"
"github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/app/api/v0/model"

View File

@@ -1,12 +1,14 @@
package handlers
import (
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/app/api/v0/model"
"github.com/h44z/wg-portal/internal/domain"
"io"
"net/http"
)
type interfaceEndpoint struct {

View File

@@ -5,6 +5,7 @@ import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/app/api/v0/model"
"github.com/h44z/wg-portal/internal/domain"

View File

@@ -1,11 +1,13 @@
package handlers
import (
"github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal/app/api/v0/model"
"net/http"
"os"
"time"
"github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal/app/api/v0/model"
)
type testEndpoint struct{}

View File

@@ -4,6 +4,7 @@ import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/app/api/v0/model"
"github.com/h44z/wg-portal/internal/domain"

View File

@@ -1,11 +1,13 @@
package handlers
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/app/api/v0/model"
"github.com/h44z/wg-portal/internal/domain"
"net/http"
)
type Scope string
@@ -44,7 +46,8 @@ func (h authenticationHandler) LoggedIn(scopes ...Scope) gin.HandlerFunc {
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"})
c.JSON(http.StatusUnauthorized,
model.Error{Code: http.StatusUnauthorized, Message: "session no longer available"})
return
}

View File

@@ -4,7 +4,6 @@ import (
"time"
"github.com/h44z/wg-portal/internal"
"github.com/h44z/wg-portal/internal/domain"
)

View File

@@ -6,6 +6,7 @@ import (
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal/app/api/core"
"github.com/h44z/wg-portal/internal/app/api/v1/models"
"github.com/h44z/wg-portal/internal/domain"

View File

@@ -5,6 +5,7 @@ import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal/app/api/v1/models"
"github.com/h44z/wg-portal/internal/domain"
)

View File

@@ -5,6 +5,7 @@ import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal/app/api/v1/models"
"github.com/h44z/wg-portal/internal/domain"
)

View File

@@ -5,6 +5,7 @@ import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal/app/api/v1/models"
"github.com/h44z/wg-portal/internal/domain"
)

View File

@@ -6,6 +6,7 @@ import (
"strings"
"github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal/app/api/v1/models"
"github.com/h44z/wg-portal/internal/domain"
)

View File

@@ -5,6 +5,7 @@ import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal/app/api/v1/models"
"github.com/h44z/wg-portal/internal/domain"
)

View File

@@ -5,6 +5,7 @@ import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal/app/api/v0/model"
"github.com/h44z/wg-portal/internal/domain"
)

View File

@@ -6,10 +6,11 @@ import (
"fmt"
"time"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
"github.com/sirupsen/logrus"
evbus "github.com/vardius/message-bus"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
)
type App struct {

View File

@@ -3,12 +3,14 @@ package audit
import (
"context"
"fmt"
"time"
"github.com/sirupsen/logrus"
evbus "github.com/vardius/message-bus"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
"github.com/sirupsen/logrus"
evbus "github.com/vardius/message-bus"
"time"
)
type Recorder struct {

View File

@@ -2,6 +2,7 @@ package audit
import (
"context"
"github.com/h44z/wg-portal/internal/domain"
)

View File

@@ -13,11 +13,12 @@ import (
"time"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/sirupsen/logrus"
evbus "github.com/vardius/message-bus"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
"github.com/sirupsen/logrus"
evbus "github.com/vardius/message-bus"
)
type UserManager interface {
@@ -412,7 +413,7 @@ func (a *Authenticator) registerNewUser(
return user, nil
}
func (a *Authenticator) getAuthenticatorConfig(id string) (interface{}, error) {
func (a *Authenticator) getAuthenticatorConfig(id string) (any, error) {
for i := range a.cfg.OpenIDConnect {
if a.cfg.OpenIDConnect[i].ProviderName == id {
return a.cfg.OpenIDConnect[i], nil

View File

@@ -7,10 +7,11 @@ import (
"strings"
"github.com/go-ldap/ldap/v3"
"github.com/sirupsen/logrus"
"github.com/h44z/wg-portal/internal"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
"github.com/sirupsen/logrus"
)
type LdapAuthenticator struct {
@@ -81,7 +82,7 @@ func (l LdapAuthenticator) PlaintextAuthentication(userId domain.UserIdentifier,
}
func (l LdapAuthenticator) GetUserInfo(_ context.Context, userId domain.UserIdentifier) (
map[string]interface{},
map[string]any,
error,
) {
conn, err := internal.LdapConnect(l.cfg)
@@ -122,7 +123,7 @@ func (l LdapAuthenticator) GetUserInfo(_ context.Context, userId domain.UserIden
return users[0], nil
}
func (l LdapAuthenticator) ParseUserInfo(raw map[string]interface{}) (*domain.AuthenticatorUserInfo, error) {
func (l LdapAuthenticator) ParseUserInfo(raw map[string]any) (*domain.AuthenticatorUserInfo, error) {
isAdmin, err := internal.LdapIsMemberOf(raw[l.cfg.FieldMap.GroupMembership].([][]byte), l.cfg.ParsedAdminGroupDN)
if err != nil {
return nil, fmt.Errorf("failed to check admin group: %w", err)

View File

@@ -8,10 +8,12 @@ import (
"net/http"
"time"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
"github.com/sirupsen/logrus"
"golang.org/x/oauth2"
"github.com/h44z/wg-portal/internal"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
)
type PlainOauthAuthenticator struct {
@@ -84,7 +86,7 @@ func (p PlainOauthAuthenticator) GetUserInfo(
ctx context.Context,
token *oauth2.Token,
_ string,
) (map[string]interface{}, error) {
) (map[string]any, error) {
req, err := http.NewRequest("GET", p.userInfoEndpoint, nil)
if err != nil {
return nil, fmt.Errorf("failed to create user info get request: %w", err)
@@ -96,13 +98,13 @@ func (p PlainOauthAuthenticator) GetUserInfo(
if err != nil {
return nil, fmt.Errorf("failed to get user info: %w", err)
}
defer response.Body.Close()
defer internal.LogClose(response.Body)
contents, err := io.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
var userFields map[string]interface{}
var userFields map[string]any
err = json.Unmarshal(contents, &userFields)
if err != nil {
return nil, fmt.Errorf("failed to parse user info: %w", err)
@@ -115,6 +117,6 @@ func (p PlainOauthAuthenticator) GetUserInfo(
return userFields, nil
}
func (p PlainOauthAuthenticator) ParseUserInfo(raw map[string]interface{}) (*domain.AuthenticatorUserInfo, error) {
func (p PlainOauthAuthenticator) ParseUserInfo(raw map[string]any) (*domain.AuthenticatorUserInfo, error) {
return parseOauthUserInfo(p.userInfoMapping, p.userAdminMapping, raw)
}

View File

@@ -7,10 +7,11 @@ import (
"fmt"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
"github.com/sirupsen/logrus"
"golang.org/x/oauth2"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
)
type OidcAuthenticator struct {
@@ -83,7 +84,7 @@ func (o OidcAuthenticator) Exchange(ctx context.Context, code string, opts ...oa
}
func (o OidcAuthenticator) GetUserInfo(ctx context.Context, token *oauth2.Token, nonce string) (
map[string]interface{},
map[string]any,
error,
) {
rawIDToken, ok := token.Extra("id_token").(string)
@@ -98,7 +99,7 @@ func (o OidcAuthenticator) GetUserInfo(ctx context.Context, token *oauth2.Token,
return nil, errors.New("nonce mismatch")
}
var tokenFields map[string]interface{}
var tokenFields map[string]any
if err = idToken.Claims(&tokenFields); err != nil {
return nil, fmt.Errorf("failed to parse extra claims: %w", err)
}
@@ -111,6 +112,6 @@ func (o OidcAuthenticator) GetUserInfo(ctx context.Context, token *oauth2.Token,
return tokenFields, nil
}
func (o OidcAuthenticator) ParseUserInfo(raw map[string]interface{}) (*domain.AuthenticatorUserInfo, error) {
func (o OidcAuthenticator) ParseUserInfo(raw map[string]any) (*domain.AuthenticatorUserInfo, error) {
return parseOauthUserInfo(o.userInfoMapping, o.userAdminMapping, raw)
}

View File

@@ -12,7 +12,7 @@ import (
func parseOauthUserInfo(
mapping config.OauthFields,
adminMapping *config.OauthAdminMapping,
raw map[string]interface{},
raw map[string]any,
) (*domain.AuthenticatorUserInfo, error) {
var isAdmin bool

View File

@@ -4,9 +4,10 @@ import (
"encoding/json"
"testing"
"github.com/h44z/wg-portal/internal/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/h44z/wg-portal/internal/config"
)
func Test_parseOauthUserInfo_no_admin(t *testing.T) {
@@ -26,7 +27,7 @@ func Test_parseOauthUserInfo_no_admin(t *testing.T) {
}
`
userInfo := map[string]interface{}{}
userInfo := map[string]any{}
err := json.Unmarshal([]byte(userInfoStr), &userInfo)
require.NoError(t, err)
@@ -72,7 +73,7 @@ func Test_parseOauthUserInfo_admin_group(t *testing.T) {
}
`
userInfo := map[string]interface{}{}
userInfo := map[string]any{}
err := json.Unmarshal([]byte(userInfoStr), &userInfo)
require.NoError(t, err)
@@ -115,7 +116,7 @@ func Test_parseOauthUserInfo_admin_value(t *testing.T) {
}
`
userInfo := map[string]interface{}{}
userInfo := map[string]any{}
err := json.Unmarshal([]byte(userInfoStr), &userInfo)
require.NoError(t, err)
@@ -156,7 +157,7 @@ func Test_parseOauthUserInfo_admin_value_custom(t *testing.T) {
}
`
userInfo := map[string]interface{}{}
userInfo := map[string]any{}
err := json.Unmarshal([]byte(userInfoStr), &userInfo)
require.NoError(t, err)

View File

@@ -2,13 +2,16 @@ package app
import (
"flag"
"github.com/h44z/wg-portal/internal/config"
"gorm.io/gorm"
"github.com/h44z/wg-portal/internal/config"
)
func HandleProgramArgs(cfg *config.Config, db *gorm.DB) (exit bool, err error) {
migrationSource := flag.String("migrateFrom", "", "path to v1 database file or DSN")
migrationDbType := flag.String("migrateFromType", string(config.DatabaseSQLite), "old database type, either mysql, mssql, postgres or sqlite")
migrationDbType := flag.String("migrateFromType", string(config.DatabaseSQLite),
"old database type, either mysql, mssql, postgres or sqlite")
flag.Parse()
if *migrationSource != "" {

View File

@@ -9,13 +9,14 @@ import (
"os"
"strings"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
"github.com/sirupsen/logrus"
evbus "github.com/vardius/message-bus"
"github.com/yeqown/go-qrcode/v2"
"github.com/yeqown/go-qrcode/writer/compressed"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
)
type Manager struct {

View File

@@ -2,8 +2,9 @@ package configfile
import (
"context"
"github.com/h44z/wg-portal/internal/domain"
"io"
"github.com/h44z/wg-portal/internal/domain"
)
type UserDatabaseRepo interface {

View File

@@ -37,10 +37,10 @@ func newTemplateHandler() (*TemplateHandler, error) {
func (c TemplateHandler) GetInterfaceConfig(cfg *domain.Interface, peers []domain.Peer) (io.Reader, error) {
var tplBuff bytes.Buffer
err := c.templates.ExecuteTemplate(&tplBuff, "wg_interface.tpl", map[string]interface{}{
err := c.templates.ExecuteTemplate(&tplBuff, "wg_interface.tpl", map[string]any{
"Interface": cfg,
"Peers": peers,
"Portal": map[string]interface{}{
"Portal": map[string]any{
"Version": "unknown",
},
})
@@ -54,9 +54,9 @@ func (c TemplateHandler) GetInterfaceConfig(cfg *domain.Interface, peers []domai
func (c TemplateHandler) GetPeerConfig(peer *domain.Peer) (io.Reader, error) {
var tplBuff bytes.Buffer
err := c.templates.ExecuteTemplate(&tplBuff, "wg_peer.tpl", map[string]interface{}{
err := c.templates.ExecuteTemplate(&tplBuff, "wg_peer.tpl", map[string]any{
"Peer": peer,
"Portal": map[string]interface{}{
"Portal": map[string]any{
"Version": "unknown",
},
})

View File

@@ -3,10 +3,12 @@ package mail
import (
"context"
"fmt"
"io"
"github.com/sirupsen/logrus"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
"github.com/sirupsen/logrus"
"io"
)
type Manager struct {
@@ -19,7 +21,13 @@ type Manager struct {
wg WireguardDatabaseRepo
}
func NewMailManager(cfg *config.Config, mailer Mailer, configFiles ConfigFileManager, users UserDatabaseRepo, wg WireguardDatabaseRepo) (*Manager, error) {
func NewMailManager(
cfg *config.Config,
mailer Mailer,
configFiles ConfigFileManager,
users UserDatabaseRepo,
wg WireguardDatabaseRepo,
) (*Manager, error) {
tplHandler, err := newTemplateHandler(cfg.Web.ExternalUrl)
if err != nil {
return nil, fmt.Errorf("failed to initialize template handler: %w", err)

View File

@@ -2,8 +2,9 @@ package mail
import (
"context"
"github.com/h44z/wg-portal/internal/domain"
"io"
"github.com/h44z/wg-portal/internal/domain"
)
type Mailer interface {

View File

@@ -44,7 +44,7 @@ func (c TemplateHandler) GetConfigMail(user *domain.User, link string) (io.Reade
var tplBuff bytes.Buffer
var htmlTplBuff bytes.Buffer
err := c.textTemplates.ExecuteTemplate(&tplBuff, "mail_with_link.gotpl", map[string]interface{}{
err := c.textTemplates.ExecuteTemplate(&tplBuff, "mail_with_link.gotpl", map[string]any{
"User": user,
"Link": link,
"PortalUrl": c.portalUrl,
@@ -53,7 +53,7 @@ func (c TemplateHandler) GetConfigMail(user *domain.User, link string) (io.Reade
return nil, nil, fmt.Errorf("failed to execute template mail_with_link.gotpl: %w", err)
}
err = c.htmlTemplates.ExecuteTemplate(&htmlTplBuff, "mail_with_link.gohtml", map[string]interface{}{
err = c.htmlTemplates.ExecuteTemplate(&htmlTplBuff, "mail_with_link.gohtml", map[string]any{
"User": user,
"Link": link,
"PortalUrl": c.portalUrl,
@@ -65,11 +65,15 @@ func (c TemplateHandler) GetConfigMail(user *domain.User, link string) (io.Reade
return &tplBuff, &htmlTplBuff, nil
}
func (c TemplateHandler) GetConfigMailWithAttachment(user *domain.User, cfgName, qrName string) (io.Reader, io.Reader, error) {
func (c TemplateHandler) GetConfigMailWithAttachment(user *domain.User, cfgName, qrName string) (
io.Reader,
io.Reader,
error,
) {
var tplBuff bytes.Buffer
var htmlTplBuff bytes.Buffer
err := c.textTemplates.ExecuteTemplate(&tplBuff, "mail_with_attachment.gotpl", map[string]interface{}{
err := c.textTemplates.ExecuteTemplate(&tplBuff, "mail_with_attachment.gotpl", map[string]any{
"User": user,
"ConfigFileName": cfgName,
"QrcodePngName": qrName,
@@ -79,7 +83,7 @@ func (c TemplateHandler) GetConfigMailWithAttachment(user *domain.User, cfgName,
return nil, nil, fmt.Errorf("failed to execute template mail_with_attachment.gotpl: %w", err)
}
err = c.htmlTemplates.ExecuteTemplate(&htmlTplBuff, "mail_with_attachment.gohtml", map[string]interface{}{
err = c.htmlTemplates.ExecuteTemplate(&htmlTplBuff, "mail_with_attachment.gohtml", map[string]any{
"User": user,
"ConfigFileName": cfgName,
"QrcodePngName": qrName,

View File

@@ -6,11 +6,12 @@ import (
"os"
"time"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
"github.com/h44z/wg-portal/internal/adapters"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
)
func migrateFromV1(cfg *config.Config, db *gorm.DB, source, typ string) error {

View File

@@ -2,6 +2,7 @@ package route
import (
"context"
"github.com/h44z/wg-portal/internal/domain"
)

View File

@@ -4,16 +4,17 @@ import (
"context"
"fmt"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
"github.com/h44z/wg-portal/internal/lowlevel"
"github.com/sirupsen/logrus"
evbus "github.com/vardius/message-bus"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
"golang.zx2c4.com/wireguard/wgctrl"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
"github.com/h44z/wg-portal/internal/lowlevel"
)
type routeRuleInfo struct {

View File

@@ -6,6 +6,7 @@ import (
"time"
"github.com/go-ldap/ldap/v3"
"github.com/h44z/wg-portal/internal"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"

View File

@@ -8,17 +8,13 @@ import (
"sync"
"time"
"github.com/google/uuid"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal"
"github.com/go-ldap/ldap/v3"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
evbus "github.com/vardius/message-bus"
"github.com/h44z/wg-portal/internal"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
)
@@ -509,7 +505,7 @@ func (m Manager) updateLdapUsers(
if existingUser == nil {
// create new user
logrus.Tracef("creating new user %s from provider %s...", user.Identifier, provider.ProviderName)
err := m.NewUser(tctx, user)
if err != nil {
cancel()

View File

@@ -5,12 +5,13 @@ import (
"sync"
"time"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
probing "github.com/prometheus-community/pro-bing"
"github.com/sirupsen/logrus"
evbus "github.com/vardius/message-bus"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
)
type StatisticsCollector struct {

View File

@@ -4,11 +4,10 @@ import (
"context"
"time"
"github.com/h44z/wg-portal/internal/app"
"github.com/sirupsen/logrus"
evbus "github.com/vardius/message-bus"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
)

View File

@@ -5,12 +5,13 @@ import (
"errors"
"fmt"
"os"
"slices"
"time"
"github.com/h44z/wg-portal/internal"
"github.com/sirupsen/logrus"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/domain"
"github.com/sirupsen/logrus"
)
func (m Manager) GetImportableInterfaces(ctx context.Context) ([]domain.PhysicalInterface, error) {
@@ -120,11 +121,11 @@ func (m Manager) ImportNewInterfaces(ctx context.Context, filter ...domain.Inter
imported := 0
for _, physicalInterface := range physicalInterfaces {
if internal.SliceContains(excludedInterfaces, physicalInterface.Identifier) {
if slices.Contains(excludedInterfaces, physicalInterface.Identifier) {
continue
}
if len(filter) != 0 && !internal.SliceContains(filter, physicalInterface.Identifier) {
if len(filter) != 0 && !slices.Contains(filter, physicalInterface.Identifier) {
continue
}
@@ -193,7 +194,7 @@ func (m Manager) RestoreInterfaceState(
}
for _, iface := range interfaces {
if len(filter) != 0 && !internal.SliceContains(filter, iface.Identifier) {
if len(filter) != 0 && !slices.Contains(filter, iface.Identifier) {
continue // ignore filtered interface
}

View File

@@ -6,9 +6,10 @@ import (
"fmt"
"time"
"github.com/sirupsen/logrus"
"github.com/h44z/wg-portal/internal/app"
"github.com/h44z/wg-portal/internal/domain"
"github.com/sirupsen/logrus"
)
func (m Manager) CreateDefaultPeer(ctx context.Context, userId domain.UserIdentifier) error {

View File

@@ -7,7 +7,6 @@ import (
"github.com/a8m/envsubst"
"github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
)

View File

@@ -37,15 +37,15 @@ type OauthAuthenticator interface {
GetType() AuthenticatorType
AuthCodeURL(state string, opts ...oauth2.AuthCodeOption) string
Exchange(ctx context.Context, code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error)
GetUserInfo(ctx context.Context, token *oauth2.Token, nonce string) (map[string]interface{}, error)
ParseUserInfo(raw map[string]interface{}) (*AuthenticatorUserInfo, error)
GetUserInfo(ctx context.Context, token *oauth2.Token, nonce string) (map[string]any, error)
ParseUserInfo(raw map[string]any) (*AuthenticatorUserInfo, error)
RegistrationEnabled() bool
}
type LdapAuthenticator interface {
GetName() string
PlaintextAuthentication(userId UserIdentifier, plainPassword string) error
GetUserInfo(ctx context.Context, username UserIdentifier) (map[string]interface{}, error)
ParseUserInfo(raw map[string]interface{}) (*AuthenticatorUserInfo, error)
GetUserInfo(ctx context.Context, username UserIdentifier) (map[string]any, error)
ParseUserInfo(raw map[string]any) (*AuthenticatorUserInfo, error)
RegistrationEnabled() bool
}

View File

@@ -15,22 +15,25 @@ type BaseModel struct {
type PrivateString string
func (PrivateString) MarshalJSON() ([]byte, error) {
func (ps *PrivateString) MarshalJSON() ([]byte, error) {
return []byte(`""`), nil
}
func (PrivateString) String() string {
func (ps *PrivateString) String() string {
return ""
}
func (ps PrivateString) Value() (driver.Value, error) {
if len(ps) == 0 {
func (ps *PrivateString) Value() (driver.Value, error) {
if ps == nil {
return nil, nil
}
return string(ps), nil
if len(*ps) == 0 {
return nil, nil
}
return string(*ps), nil
}
func (ps *PrivateString) Scan(value interface{}) error {
func (ps *PrivateString) Scan(value any) error {
if value == nil {
*ps = ""
return nil

View File

@@ -4,9 +4,8 @@ import (
"context"
"fmt"
"github.com/sirupsen/logrus"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
const CtxUserInfo = "userInfo"

View File

@@ -54,10 +54,6 @@ func NewPreSharedKey() (PreSharedKey, error) {
return PreSharedKey(preSharedKey.String()), nil
}
func KeyBytesToString(key []byte) string {
return base64.StdEncoding.EncodeToString(key)
}
func PublicKeyFromPrivateKey(key string) string {
privKey, err := wgtypes.ParseKey(key)
if err != nil {

View File

@@ -9,8 +9,9 @@ import (
"strings"
"time"
"github.com/h44z/wg-portal/internal"
"github.com/sirupsen/logrus"
"github.com/h44z/wg-portal/internal"
)
const (
@@ -19,6 +20,8 @@ const (
InterfaceTypeAny InterfaceType = "any"
)
var allowedFileNameRegex = regexp.MustCompile("[^a-zA-Z0-9-_]+")
type InterfaceIdentifier string
type InterfaceType string
@@ -119,10 +122,8 @@ func (i *Interface) CopyCalculatedAttributes(src *Interface) {
}
func (i *Interface) GetConfigFileName() string {
reg := regexp.MustCompile("[^a-zA-Z0-9-_]+")
filename := internal.TruncateString(string(i.Identifier), 8)
filename = reg.ReplaceAllString(filename, "")
filename = allowedFileNameRegex.ReplaceAllString(filename, "")
filename += ".conf"
return filename

View File

@@ -1,10 +1,11 @@
package domain
import (
"github.com/vishvananda/netlink"
"net"
"net/netip"
"strings"
"github.com/vishvananda/netlink"
)
type Cidr struct {
@@ -48,14 +49,6 @@ func CidrsFromString(str string) ([]Cidr, error) {
return cidrs, nil
}
func CidrsMust(cidrs []Cidr, err error) []Cidr {
if err != nil {
panic(err)
}
return cidrs
}
func CidrsFromArray(strs []string) ([]Cidr, error) {
cidrs := make([]Cidr, len(strs))

View File

@@ -7,9 +7,9 @@ import (
"strings"
"time"
"github.com/h44z/wg-portal/internal"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
"github.com/h44z/wg-portal/internal"
)
type PeerIdentifier string

View File

@@ -83,8 +83,7 @@ func (u *User) EditAllowed(new *User) error {
}
// for users which are not database users, only the notes field and the disabled flag can be updated
updateOk := true
updateOk = updateOk && u.Identifier == new.Identifier
updateOk := u.Identifier == new.Identifier
updateOk = updateOk && u.Source == new.Source
updateOk = updateOk && u.IsAdmin == new.IsAdmin
updateOk = updateOk && u.Email == new.Email

View File

@@ -5,9 +5,9 @@ import (
"fmt"
"os"
"github.com/go-ldap/ldap/v3"
"github.com/sirupsen/logrus"
"github.com/go-ldap/ldap/v3"
"github.com/h44z/wg-portal/internal/config"
)

View File

@@ -1,157 +0,0 @@
// Code generated by mockery v2.10.0. DO NOT EDIT.
package mocks
import (
mock "github.com/stretchr/testify/mock"
netlink "github.com/vishvananda/netlink"
)
// NetlinkClient is an autogenerated mock type for the NetlinkClient type
type NetlinkClient struct {
mock.Mock
}
// AddrAdd provides a mock function with given fields: link, addr
func (_m *NetlinkClient) AddrAdd(link netlink.Link, addr *netlink.Addr) error {
ret := _m.Called(link, addr)
var r0 error
if rf, ok := ret.Get(0).(func(netlink.Link, *netlink.Addr) error); ok {
r0 = rf(link, addr)
} else {
r0 = ret.Error(0)
}
return r0
}
// AddrList provides a mock function with given fields: link
func (_m *NetlinkClient) AddrList(link netlink.Link) ([]netlink.Addr, error) {
ret := _m.Called(link)
var r0 []netlink.Addr
if rf, ok := ret.Get(0).(func(netlink.Link) []netlink.Addr); ok {
r0 = rf(link)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]netlink.Addr)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(netlink.Link) error); ok {
r1 = rf(link)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// AddrReplace provides a mock function with given fields: link, addr
func (_m *NetlinkClient) AddrReplace(link netlink.Link, addr *netlink.Addr) error {
ret := _m.Called(link, addr)
var r0 error
if rf, ok := ret.Get(0).(func(netlink.Link, *netlink.Addr) error); ok {
r0 = rf(link, addr)
} else {
r0 = ret.Error(0)
}
return r0
}
// LinkAdd provides a mock function with given fields: link
func (_m *NetlinkClient) LinkAdd(link netlink.Link) error {
ret := _m.Called(link)
var r0 error
if rf, ok := ret.Get(0).(func(netlink.Link) error); ok {
r0 = rf(link)
} else {
r0 = ret.Error(0)
}
return r0
}
// LinkByName provides a mock function with given fields: name
func (_m *NetlinkClient) LinkByName(name string) (netlink.Link, error) {
ret := _m.Called(name)
var r0 netlink.Link
if rf, ok := ret.Get(0).(func(string) netlink.Link); ok {
r0 = rf(name)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(netlink.Link)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(string) error); ok {
r1 = rf(name)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// LinkDel provides a mock function with given fields: link
func (_m *NetlinkClient) LinkDel(link netlink.Link) error {
ret := _m.Called(link)
var r0 error
if rf, ok := ret.Get(0).(func(netlink.Link) error); ok {
r0 = rf(link)
} else {
r0 = ret.Error(0)
}
return r0
}
// LinkSetDown provides a mock function with given fields: link
func (_m *NetlinkClient) LinkSetDown(link netlink.Link) error {
ret := _m.Called(link)
var r0 error
if rf, ok := ret.Get(0).(func(netlink.Link) error); ok {
r0 = rf(link)
} else {
r0 = ret.Error(0)
}
return r0
}
// LinkSetMTU provides a mock function with given fields: link, mtu
func (_m *NetlinkClient) LinkSetMTU(link netlink.Link, mtu int) error {
ret := _m.Called(link, mtu)
var r0 error
if rf, ok := ret.Get(0).(func(netlink.Link, int) error); ok {
r0 = rf(link, mtu)
} else {
r0 = ret.Error(0)
}
return r0
}
// LinkSetUp provides a mock function with given fields: link
func (_m *NetlinkClient) LinkSetUp(link netlink.Link) error {
ret := _m.Called(link)
var r0 error
if rf, ok := ret.Get(0).(func(netlink.Link) error); ok {
r0 = rf(link)
} else {
r0 = ret.Error(0)
}
return r0
}

View File

@@ -1,87 +0,0 @@
// Code generated by mockery v2.10.0. DO NOT EDIT.
package mocks
import (
mock "github.com/stretchr/testify/mock"
wgtypes "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
// WireGuardClient is an autogenerated mock type for the WireGuardClient type
type WireGuardClient struct {
mock.Mock
}
// Close provides a mock function with given fields:
func (_m *WireGuardClient) Close() error {
ret := _m.Called()
var r0 error
if rf, ok := ret.Get(0).(func() error); ok {
r0 = rf()
} else {
r0 = ret.Error(0)
}
return r0
}
// ConfigureDevice provides a mock function with given fields: name, cfg
func (_m *WireGuardClient) ConfigureDevice(name string, cfg wgtypes.Config) error {
ret := _m.Called(name, cfg)
var r0 error
if rf, ok := ret.Get(0).(func(string, wgtypes.Config) error); ok {
r0 = rf(name, cfg)
} else {
r0 = ret.Error(0)
}
return r0
}
// Device provides a mock function with given fields: name
func (_m *WireGuardClient) Device(name string) (*wgtypes.Device, error) {
ret := _m.Called(name)
var r0 *wgtypes.Device
if rf, ok := ret.Get(0).(func(string) *wgtypes.Device); ok {
r0 = rf(name)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*wgtypes.Device)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(string) error); ok {
r1 = rf(name)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// Devices provides a mock function with given fields:
func (_m *WireGuardClient) Devices() ([]*wgtypes.Device, error) {
ret := _m.Called()
var r0 []*wgtypes.Device
if rf, ok := ret.Get(0).(func() []*wgtypes.Device); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]*wgtypes.Device)
}
}
var r1 error
if rf, ok := ret.Get(1).(func() error); ok {
r1 = rf()
} else {
r1 = ret.Error(1)
}
return r0, r1
}

View File

@@ -3,12 +3,22 @@ package internal
import (
"context"
"fmt"
"io"
"os"
"os/signal"
"strings"
"syscall"
"github.com/sirupsen/logrus"
)
// LogClose closes the given Closer and logs any error that occurs
func LogClose(c io.Closer) {
if err := c.Close(); err != nil {
logrus.Errorf("error during Close(): %v", err)
}
}
// SignalAwareContext returns a context that gets closed once a given signal is retrieved.
// By default, the following signals are handled: syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP
func SignalAwareContext(ctx context.Context, sig ...os.Signal) context.Context {
@@ -45,23 +55,8 @@ func AssertNoError(err error) {
}
}
// ByteCountSI returns the byte count as string, see: https://yourbasic.org/golang/formatting-byte-size-to-human-readable-format/
func ByteCountSI(b int64) string {
const unit = 1000
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB",
float64(b)/float64(div), "kMGTPE"[exp])
}
// MapDefaultString returns the string value for the given key or a default value
func MapDefaultString(m map[string]interface{}, key string, dflt string) string {
func MapDefaultString(m map[string]any, key string, dflt string) string {
if m == nil {
return dflt
}
@@ -80,7 +75,7 @@ func MapDefaultString(m map[string]interface{}, key string, dflt string) string
}
// MapDefaultStringSlice returns the string slice value for the given key or a default value
func MapDefaultStringSlice(m map[string]interface{}, key string, dflt []string) []string {
func MapDefaultStringSlice(m map[string]any, key string, dflt []string) []string {
if m == nil {
return dflt
}
@@ -124,16 +119,7 @@ func UniqueStringSlice(slice []string) []string {
return uniqueSlice
}
func SliceContains[T comparable](slice []T, needle T) bool {
for _, elem := range slice {
if elem == needle {
return true
}
}
return false
}
// SliceString returns a string slice from a comma-separated string
func SliceString(str string) []string {
strParts := strings.Split(str, ",")
stringSlice := make([]string, 0, len(strParts))
@@ -148,10 +134,12 @@ func SliceString(str string) []string {
return stringSlice
}
// SliceToString returns a comma-separated string from a string slice
func SliceToString(slice []string) string {
return strings.Join(slice, ",")
}
// TruncateString returns a string truncated to the given length
func TruncateString(s string, max int) string {
if max > len(s) {
return s
@@ -159,6 +147,7 @@ func TruncateString(s string, max int) string {
return s[:max]
}
// BoolToFloat64 converts a boolean to a float64. True is 1.0, false is 0.0
func BoolToFloat64(b bool) float64 {
if b {
return 1.0