cleanup, typos, ...

This commit is contained in:
Christoph Haas 2021-02-08 22:56:02 +01:00
parent dd47f84c3d
commit 53814dbc27
13 changed files with 69 additions and 78 deletions

View File

@ -5,6 +5,7 @@
![GitHub last commit](https://img.shields.io/github/last-commit/h44z/wg-portal) ![GitHub last commit](https://img.shields.io/github/last-commit/h44z/wg-portal)
![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/h44z/wg-portal) ![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/h44z/wg-portal)
![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/h44z/wg-portal) ![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/h44z/wg-portal)
[![Docker Pulls](https://img.shields.io/docker/pulls/h44z/wg-portal.svg)](https://hub.docker.com/r/h44z/wg-portal/)
A simple web base configuration portal for [WireGuard](https://wireguard.com). A simple web base configuration portal for [WireGuard](https://wireguard.com).
The portal uses the WireGuard [wgctrl](https://github.com/WireGuard/wgctrl-go) library to manage the VPN The portal uses the WireGuard [wgctrl](https://github.com/WireGuard/wgctrl-go) library to manage the VPN

View File

@ -54,7 +54,7 @@
<h3>Client's global configuration</h3> <h3>Client's global configuration</h3>
<div class="form-row"> <div class="form-row">
<div class="form-group required col-md-12"> <div class="form-group required col-md-12">
<label for="inputPublicEndpoint">Public Enpoint for Clients</label> <label for="inputPublicEndpoint">Public Endpoint for Clients</label>
<input type="text" name="endpoint" class="form-control" id="inputPublicEndpoint" placeholder="vpn.company.com:51820" value="{{.Device.Endpoint}}"> <input type="text" name="endpoint" class="form-control" id="inputPublicEndpoint" placeholder="vpn.company.com:51820" value="{{.Device.Endpoint}}">
</div> </div>
</div> </div>

View File

@ -1,5 +1,5 @@
<nav class="navbar navbar-expand-lg navbar-dark bg-primary"> <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#topNavbar" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#topNavbar" aria-controls="topNavbar" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span> <span class="navbar-toggler-icon"></span>
</button> </button>

View File

@ -6,11 +6,10 @@ import (
"reflect" "reflect"
"runtime" "runtime"
"github.com/h44z/wg-portal/internal/wireguard"
"github.com/h44z/wg-portal/internal/ldap" "github.com/h44z/wg-portal/internal/ldap"
"github.com/h44z/wg-portal/internal/wireguard"
"github.com/kelseyhightower/envconfig" "github.com/kelseyhightower/envconfig"
log "github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
@ -104,15 +103,15 @@ func NewConfig() *Config {
} }
err := loadConfigFile(cfg, cfgFile) err := loadConfigFile(cfg, cfgFile)
if err != nil { if err != nil {
log.Warnf("unable to load config.yml file: %v, using default configuration...", err) logrus.Warnf("unable to load config.yml file: %v, using default configuration...", err)
} }
err = loadConfigEnv(cfg) err = loadConfigEnv(cfg)
if err != nil { if err != nil {
log.Warnf("unable to load environment config: %v", err) logrus.Warnf("unable to load environment config: %v", err)
} }
if cfg.WG.ManageIPAddresses && runtime.GOOS != "linux" { if cfg.WG.ManageIPAddresses && runtime.GOOS != "linux" {
log.Warnf("Managing IP addresses only works on linux! Feature disabled.") logrus.Warnf("Managing IP addresses only works on linux! Feature disabled.")
cfg.WG.ManageIPAddresses = false cfg.WG.ManageIPAddresses = false
} }

View File

@ -11,7 +11,7 @@ import (
"time" "time"
"github.com/go-ldap/ldap/v3" "github.com/go-ldap/ldap/v3"
log "github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
var Fields = []string{"givenName", "sn", "mail", "department", "memberOf", "sAMAccountName", "telephoneNumber", var Fields = []string{"givenName", "sn", "mail", "department", "memberOf", "sAMAccountName", "telephoneNumber",
@ -214,9 +214,9 @@ func NewUserCache(config Config, store UserCacheHolder) *UserCache {
userData: store, userData: store,
} }
log.Infof("Filling user cache...") logrus.Infof("Filling user cache...")
err := uc.Update(true, true) err := uc.Update(true, true)
log.Infof("User cache filled!") logrus.Infof("User cache filled!")
uc.LastError = err uc.LastError = err
return uc return uc
@ -252,7 +252,7 @@ func (u UserCache) close(conn *ldap.Conn) {
// Update updates the user cache in background, minimal locking will happen // Update updates the user cache in background, minimal locking will happen
func (u *UserCache) Update(filter, withDisabledUsers bool) error { func (u *UserCache) Update(filter, withDisabledUsers bool) error {
log.Debugf("Updating ldap cache...") logrus.Debugf("Updating ldap cache...")
client, err := u.open() client, err := u.open()
if err != nil { if err != nil {
u.LastError = err u.LastError = err
@ -296,7 +296,7 @@ func (u *UserCache) Update(filter, withDisabledUsers bool) error {
} }
if entry.DN != dn { if entry.DN != dn {
log.Errorf("LDAP inconsistent: '%s' != '%s'", entry.DN, dn) logrus.Errorf("LDAP inconsistent: '%s' != '%s'", entry.DN, dn)
continue continue
} }
} }
@ -320,7 +320,7 @@ func (u *UserCache) Update(filter, withDisabledUsers bool) error {
u.UpdatedAt = time.Now() u.UpdatedAt = time.Now()
u.LastError = nil u.LastError = nil
log.Debug("Ldap cache updated...") logrus.Debug("Ldap cache updated...")
return nil return nil
} }

View File

@ -11,17 +11,14 @@ import (
"path/filepath" "path/filepath"
"time" "time"
"github.com/h44z/wg-portal/internal/wireguard"
"github.com/h44z/wg-portal/internal/common"
"github.com/h44z/wg-portal/internal/ldap"
log "github.com/sirupsen/logrus"
ginlogrus "github.com/toorop/gin-logrus"
"github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/memstore" "github.com/gin-contrib/sessions/memstore"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal/common"
"github.com/h44z/wg-portal/internal/ldap"
"github.com/h44z/wg-portal/internal/wireguard"
"github.com/sirupsen/logrus"
ginlogrus "github.com/toorop/gin-logrus"
) )
const SessionIdentifier = "wgPortalSession" const SessionIdentifier = "wgPortalSession"
@ -85,8 +82,8 @@ type Server struct {
func (s *Server) Setup() error { func (s *Server) Setup() error {
dir := s.getExecutableDirectory() dir := s.getExecutableDirectory()
rDir, _ := filepath.Abs(filepath.Dir(os.Args[0])) rDir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
log.Infof("Real working directory: %s", rDir) logrus.Infof("Real working directory: %s", rDir)
log.Infof("Current working directory: %s", dir) logrus.Infof("Current working directory: %s", dir)
// Init rand // Init rand
rand.Seed(time.Now().UnixNano()) rand.Seed(time.Now().UnixNano())
@ -99,8 +96,8 @@ func (s *Server) Setup() error {
s.ldapUsers.Init() s.ldapUsers.Init()
s.ldapCacheUpdater = ldap.NewUserCache(s.config.LDAP, s.ldapUsers) s.ldapCacheUpdater = ldap.NewUserCache(s.config.LDAP, s.ldapUsers)
if s.ldapCacheUpdater.LastError != nil { if s.ldapCacheUpdater.LastError != nil {
log.Warnf("LDAP error: %v", s.ldapCacheUpdater.LastError) logrus.Warnf("LDAP error: %v", s.ldapCacheUpdater.LastError)
log.Warnf("LDAP features disabled!") logrus.Warnf("LDAP features disabled!")
s.ldapDisabled = true s.ldapDisabled = true
} }
@ -118,7 +115,7 @@ func (s *Server) Setup() error {
return errors.New("unable to initialize user manager") return errors.New("unable to initialize user manager")
} }
if err := s.RestoreWireGuardInterface(); err != nil { if err := s.RestoreWireGuardInterface(); err != nil {
return errors.New("unable to restore wirguard state") return errors.New("unable to restore WireGuard state")
} }
// Setup mail template // Setup mail template
@ -132,14 +129,14 @@ func (s *Server) Setup() error {
gin.SetMode(gin.ReleaseMode) gin.SetMode(gin.ReleaseMode)
gin.DefaultWriter = ioutil.Discard gin.DefaultWriter = ioutil.Discard
s.server = gin.New() s.server = gin.New()
s.server.Use(ginlogrus.Logger(log.StandardLogger()), gin.Recovery()) s.server.Use(ginlogrus.Logger(logrus.StandardLogger()), gin.Recovery())
s.server.SetFuncMap(template.FuncMap{ s.server.SetFuncMap(template.FuncMap{
"formatBytes": common.ByteCountSI, "formatBytes": common.ByteCountSI,
"urlEncode": url.QueryEscape, "urlEncode": url.QueryEscape,
}) })
// Setup templates // Setup templates
log.Infof("Loading templates from: %s", filepath.Join(dir, "/assets/tpl/*.html")) logrus.Infof("Loading templates from: %s", filepath.Join(dir, "/assets/tpl/*.html"))
s.server.LoadHTMLGlob(filepath.Join(dir, "/assets/tpl/*.html")) s.server.LoadHTMLGlob(filepath.Join(dir, "/assets/tpl/*.html"))
s.server.Use(sessions.Sessions("authsession", memstore.NewStore([]byte("secret")))) // TODO: change key? s.server.Use(sessions.Sessions("authsession", memstore.NewStore([]byte("secret")))) // TODO: change key?
@ -152,7 +149,7 @@ func (s *Server) Setup() error {
// Setup all routes // Setup all routes
SetupRoutes(s) SetupRoutes(s)
log.Infof("Setup of service completed!") logrus.Infof("Setup of service completed!")
return nil return nil
} }
@ -163,9 +160,9 @@ func (s *Server) Run() {
for { for {
time.Sleep(CacheRefreshDuration) time.Sleep(CacheRefreshDuration)
if err := s.ldapCacheUpdater.Update(true, true); err != nil { if err := s.ldapCacheUpdater.Update(true, true); err != nil {
log.Warnf("Failed to update ldap group cache: %v", err) logrus.Warnf("Failed to update ldap group cache: %v", err)
} }
log.Debugf("Refreshed LDAP permissions!") logrus.Debugf("Refreshed LDAP permissions!")
} }
}(s) }(s)
} }
@ -175,9 +172,9 @@ func (s *Server) Run() {
for { for {
time.Sleep(CacheRefreshDuration) time.Sleep(CacheRefreshDuration)
if err := s.SyncLdapAttributesWithWireGuard(); err != nil { if err := s.SyncLdapAttributesWithWireGuard(); err != nil {
log.Warnf("Failed to synchronize ldap attributes: %v", err) logrus.Warnf("Failed to synchronize ldap attributes: %v", err)
} }
log.Debugf("Synced LDAP attributes!") logrus.Debugf("Synced LDAP attributes!")
} }
}(s) }(s)
} }
@ -185,14 +182,14 @@ func (s *Server) Run() {
// Run web service // Run web service
err := s.server.Run(s.config.Core.ListeningAddress) err := s.server.Run(s.config.Core.ListeningAddress)
if err != nil { if err != nil {
log.Errorf("Failed to listen and serve on %s: %v", s.config.Core.ListeningAddress, err) logrus.Errorf("Failed to listen and serve on %s: %v", s.config.Core.ListeningAddress, err)
} }
} }
func (s *Server) getExecutableDirectory() string { func (s *Server) getExecutableDirectory() string {
dir, err := filepath.Abs(filepath.Dir(os.Args[0])) dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil { if err != nil {
log.Errorf("Failed to get executable directory: %v", err) logrus.Errorf("Failed to get executable directory: %v", err)
} }
if _, err := os.Stat(filepath.Join(dir, "assets")); os.IsNotExist(err) { if _, err := os.Stat(filepath.Join(dir, "assets")); os.IsNotExist(err) {
@ -221,7 +218,7 @@ func (s *Server) getSessionData(c *gin.Context) SessionData {
} }
session.Set(SessionIdentifier, sessionData) session.Set(SessionIdentifier, sessionData)
if err := session.Save(); err != nil { if err := session.Save(); err != nil {
log.Errorf("Failed to store session: %v", err) logrus.Errorf("Failed to store session: %v", err)
} }
} }
@ -232,7 +229,7 @@ func (s *Server) getFlashes(c *gin.Context) []FlashData {
session := sessions.Default(c) session := sessions.Default(c)
flashes := session.Flashes() flashes := session.Flashes()
if err := session.Save(); err != nil { if err := session.Save(); err != nil {
log.Errorf("Failed to store session after setting flash: %v", err) logrus.Errorf("Failed to store session after setting flash: %v", err)
} }
flashData := make([]FlashData, len(flashes)) flashData := make([]FlashData, len(flashes))
@ -247,7 +244,7 @@ func (s *Server) updateSessionData(c *gin.Context, data SessionData) error {
session := sessions.Default(c) session := sessions.Default(c)
session.Set(SessionIdentifier, data) session.Set(SessionIdentifier, data)
if err := session.Save(); err != nil { if err := session.Save(); err != nil {
log.Errorf("Failed to store session: %v", err) logrus.Errorf("Failed to store session: %v", err)
return err return err
} }
return nil return nil
@ -257,7 +254,7 @@ func (s *Server) destroySessionData(c *gin.Context) error {
session := sessions.Default(c) session := sessions.Default(c)
session.Delete(SessionIdentifier) session.Delete(SessionIdentifier)
if err := session.Save(); err != nil { if err := session.Save(); err != nil {
log.Errorf("Failed to destroy session: %v", err) logrus.Errorf("Failed to destroy session: %v", err)
return err return err
} }
return nil return nil
@ -280,7 +277,7 @@ func (s *Server) setFlashMessage(c *gin.Context, message, typ string) {
Type: typ, Type: typ,
}) })
if err := session.Save(); err != nil { if err := session.Save(); err != nil {
log.Errorf("Failed to store session after setting flash: %v", err) logrus.Errorf("Failed to store session after setting flash: %v", err)
} }
} }

View File

@ -4,9 +4,8 @@ import (
"net/http" "net/http"
"strings" "strings"
log "github.com/sirupsen/logrus"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
) )
func (s *Server) GetLogin(c *gin.Context) { func (s *Server) GetLogin(c *gin.Context) {
@ -108,7 +107,7 @@ func (s *Server) PostLogin(c *gin.Context) {
CreatedBy: sessionData.Email, CreatedBy: sessionData.Email,
UpdatedBy: sessionData.Email, UpdatedBy: sessionData.Email,
}) })
log.Errorf("Failed to automatically create vpn peer for %s: %v", sessionData.Email, err) logrus.Errorf("Failed to automatically create vpn peer for %s: %v", sessionData.Email, err)
} }
} }

View File

@ -79,7 +79,7 @@ func (s *Server) PostAdminEditInterface(c *gin.Context) {
err = s.WriteWireGuardConfigFile() err = s.WriteWireGuardConfigFile()
if err != nil { if err != nil {
_ = s.updateFormInSession(c, formDevice) _ = s.updateFormInSession(c, formDevice)
s.setFlashMessage(c, "Failed to update wireguard config-file: "+err.Error(), "danger") s.setFlashMessage(c, "Failed to update WireGuard config-file: "+err.Error(), "danger")
c.Redirect(http.StatusSeeOther, "/admin/device/edit?formerr=update") c.Redirect(http.StatusSeeOther, "/admin/device/edit?formerr=update")
return return
} }
@ -134,7 +134,7 @@ func (s *Server) GetApplyGlobalConfig(c *gin.Context) {
} }
} }
s.setFlashMessage(c, "Allowed ip's updated for all clients.", "success") s.setFlashMessage(c, "Allowed IP's updated for all clients.", "success")
c.Redirect(http.StatusSeeOther, "/admin/device/edit") c.Redirect(http.StatusSeeOther, "/admin/device/edit")
return return
} }

View File

@ -11,7 +11,7 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal/common" "github.com/h44z/wg-portal/internal/common"
"github.com/h44z/wg-portal/internal/ldap" "github.com/h44z/wg-portal/internal/ldap"
log "github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/tatsushid/go-fastping" "github.com/tatsushid/go-fastping"
) )
@ -204,7 +204,7 @@ func (s *Server) PostAdminCreateLdapPeers(c *gin.Context) {
} }
} }
log.Infof("creating %d ldap peers", len(emails)) logrus.Infof("creating %d ldap peers", len(emails))
for i := range emails { for i := range emails {
if err := s.CreateUserByEmail(emails[i], formData.Identifier, false); err != nil { if err := s.CreateUserByEmail(emails[i], formData.Identifier, false); err != nil {

View File

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

View File

@ -4,7 +4,7 @@ import (
"time" "time"
"github.com/h44z/wg-portal/internal/ldap" "github.com/h44z/wg-portal/internal/ldap"
log "github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
// SyncLdapAttributesWithWireGuard starts to synchronize the "disabled" attribute from ldap. // SyncLdapAttributesWithWireGuard starts to synchronize the "disabled" attribute from ldap.
@ -26,7 +26,7 @@ func (s *Server) SyncLdapAttributesWithWireGuard() error {
now := time.Now() now := time.Now()
user.DeactivatedAt = &now user.DeactivatedAt = &now
if err := s.UpdateUser(user, now); err != nil { if err := s.UpdateUser(user, now); err != nil {
log.Errorf("Failed to disable user %s: %v", user.Email, err) logrus.Errorf("Failed to disable user %s: %v", user.Email, err)
} }
} }
} }

View File

@ -16,15 +16,11 @@ import (
"time" "time"
"github.com/gin-gonic/gin/binding" "github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
"github.com/h44z/wg-portal/internal/wireguard"
"github.com/h44z/wg-portal/internal/common" "github.com/h44z/wg-portal/internal/common"
"github.com/h44z/wg-portal/internal/ldap" "github.com/h44z/wg-portal/internal/ldap"
log "github.com/sirupsen/logrus" "github.com/h44z/wg-portal/internal/wireguard"
"github.com/sirupsen/logrus"
"github.com/skip2/go-qrcode" "github.com/skip2/go-qrcode"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes" "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
"gorm.io/driver/sqlite" "gorm.io/driver/sqlite"
@ -62,8 +58,8 @@ var ipList validator.Func = func(fl validator.FieldLevel) bool {
func init() { func init() {
if v, ok := binding.Validator.Engine().(*validator.Validate); ok { if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterValidation("cidrlist", cidrList) _ = v.RegisterValidation("cidrlist", cidrList)
v.RegisterValidation("iplist", ipList) _ = v.RegisterValidation("iplist", ipList)
} }
} }
@ -153,7 +149,7 @@ func (u User) GetPeerConfig() wgtypes.PeerConfig {
func (u User) GetQRCode() ([]byte, error) { func (u User) GetQRCode() ([]byte, error) {
png, err := qrcode.Encode(u.Config, qrcode.Medium, 250) png, err := qrcode.Encode(u.Config, qrcode.Medium, 250)
if err != nil { if err != nil {
log.WithFields(log.Fields{ logrus.WithFields(logrus.Fields{
"err": err, "err": err,
}).Error("failed to create qrcode") }).Error("failed to create qrcode")
return nil, err return nil, err
@ -289,19 +285,19 @@ func NewUserManager(dbPath string, wg *wireguard.Manager, ldapUsers *ldap.Synchr
var err error var err error
if _, err = os.Stat(filepath.Dir(dbPath)); os.IsNotExist(err) { if _, err = os.Stat(filepath.Dir(dbPath)); os.IsNotExist(err) {
if err = os.MkdirAll(filepath.Dir(dbPath), 0700); err != nil { if err = os.MkdirAll(filepath.Dir(dbPath), 0700); err != nil {
log.Errorf("failed to create database directory (%s): %v", filepath.Dir(dbPath), err) logrus.Errorf("failed to create database directory (%s): %v", filepath.Dir(dbPath), err)
return nil return nil
} }
} }
um.db, err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{}) um.db, err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
if err != nil { if err != nil {
log.Errorf("failed to open sqlite database (%s): %v", dbPath, err) logrus.Errorf("failed to open sqlite database (%s): %v", dbPath, err)
return nil return nil
} }
err = um.db.AutoMigrate(&User{}, &Device{}) err = um.db.AutoMigrate(&User{}, &Device{})
if err != nil { if err != nil {
log.Errorf("failed to migrate sqlite database: %v", err) logrus.Errorf("failed to migrate sqlite database: %v", err)
return nil return nil
} }
@ -311,23 +307,23 @@ func NewUserManager(dbPath string, wg *wireguard.Manager, ldapUsers *ldap.Synchr
func (u *UserManager) InitFromCurrentInterface() error { func (u *UserManager) InitFromCurrentInterface() error {
peers, err := u.wg.GetPeerList() peers, err := u.wg.GetPeerList()
if err != nil { if err != nil {
log.Errorf("failed to init user-manager from peers: %v", err) logrus.Errorf("failed to init user-manager from peers: %v", err)
return err return err
} }
device, err := u.wg.GetDeviceInfo() device, err := u.wg.GetDeviceInfo()
if err != nil { if err != nil {
log.Errorf("failed to init user-manager from device: %v", err) logrus.Errorf("failed to init user-manager from device: %v", err)
return err return err
} }
var ipAddresses []string var ipAddresses []string
var mtu int var mtu int
if u.wg.Cfg.ManageIPAddresses { if u.wg.Cfg.ManageIPAddresses {
if ipAddresses, err = u.wg.GetIPAddress(); err != nil { if ipAddresses, err = u.wg.GetIPAddress(); err != nil {
log.Errorf("failed to init user-manager from device: %v", err) logrus.Errorf("failed to init user-manager from device: %v", err)
return err return err
} }
if mtu, err = u.wg.GetMTU(); err != nil { if mtu, err = u.wg.GetMTU(); err != nil {
log.Errorf("failed to init user-manager from device: %v", err) logrus.Errorf("failed to init user-manager from device: %v", err)
return err return err
} }
} }
@ -370,7 +366,7 @@ func (u *UserManager) validateOrCreateUserForPeer(peer wgtypes.Peer) error {
res := u.db.Create(&user) res := u.db.Create(&user)
if res.Error != nil { if res.Error != nil {
log.Errorf("failed to create autodetected peer: %v", res.Error) logrus.Errorf("failed to create autodetected peer: %v", res.Error)
return res.Error return res.Error
} }
} }
@ -390,14 +386,14 @@ func (u *UserManager) validateOrCreateDevice(dev wgtypes.Device, ipAddresses []s
device.Mtu = 0 device.Mtu = 0
device.PersistentKeepalive = 16 // Default device.PersistentKeepalive = 16 // Default
device.IPsStr = strings.Join(ipAddresses, ", ") device.IPsStr = strings.Join(ipAddresses, ", ")
if mtu == wireguard.WireGuardDefaultMTU { if mtu == wireguard.DefaultMTU {
mtu = 0 mtu = 0
} }
device.Mtu = mtu device.Mtu = mtu
res := u.db.Create(&device) res := u.db.Create(&device)
if res.Error != nil { if res.Error != nil {
log.Errorf("failed to create autodetected device: %v", res.Error) logrus.Errorf("failed to create autodetected device: %v", res.Error)
return res.Error return res.Error
} }
} }
@ -603,7 +599,7 @@ func (u *UserManager) CreateUser(user User) error {
res := u.db.Create(&user) res := u.db.Create(&user)
if res.Error != nil { if res.Error != nil {
log.Errorf("failed to create user: %v", res.Error) logrus.Errorf("failed to create user: %v", res.Error)
return res.Error return res.Error
} }
@ -617,7 +613,7 @@ func (u *UserManager) UpdateUser(user User) error {
res := u.db.Save(&user) res := u.db.Save(&user)
if res.Error != nil { if res.Error != nil {
log.Errorf("failed to update user: %v", res.Error) logrus.Errorf("failed to update user: %v", res.Error)
return res.Error return res.Error
} }
@ -627,7 +623,7 @@ func (u *UserManager) UpdateUser(user User) error {
func (u *UserManager) DeleteUser(user User) error { func (u *UserManager) DeleteUser(user User) error {
res := u.db.Delete(&user) res := u.db.Delete(&user)
if res.Error != nil { if res.Error != nil {
log.Errorf("failed to delete user: %v", res.Error) logrus.Errorf("failed to delete user: %v", res.Error)
return res.Error return res.Error
} }
@ -642,7 +638,7 @@ func (u *UserManager) UpdateDevice(device Device) error {
res := u.db.Save(&device) res := u.db.Save(&device)
if res.Error != nil { if res.Error != nil {
log.Errorf("failed to update device: %v", res.Error) logrus.Errorf("failed to update device: %v", res.Error)
return res.Error return res.Error
} }

View File

@ -7,7 +7,7 @@ import (
"github.com/milosgajdos/tenus" "github.com/milosgajdos/tenus"
) )
const WireGuardDefaultMTU = 1420 const DefaultMTU = 1420
func (m *Manager) GetIPAddress() ([]string, error) { func (m *Manager) GetIPAddress() ([]string, error) {
wgInterface, err := tenus.NewLinkFrom(m.Cfg.DeviceName) wgInterface, err := tenus.NewLinkFrom(m.Cfg.DeviceName)
@ -38,7 +38,7 @@ func (m *Manager) GetIPAddress() ([]string, error) {
ip = v.IP ip = v.IP
mask = ip.DefaultMask() mask = ip.DefaultMask()
} }
if ip == nil { if ip == nil || mask == nil {
continue // something is wrong? continue // something is wrong?
} }
@ -72,7 +72,7 @@ func (m *Manager) SetIPAddress(cidrs []string) error {
} }
} }
// Next set new IP adrresses // Next set new IP addresses
for _, cidr := range cidrs { for _, cidr := range cidrs {
wgIp, wgIpNet, err := net.ParseCIDR(cidr) wgIp, wgIpNet, err := net.ParseCIDR(cidr)
if err != nil { if err != nil {
@ -109,7 +109,7 @@ func (m *Manager) SetMTU(mtu int) error {
} }
if mtu == 0 { if mtu == 0 {
mtu = WireGuardDefaultMTU mtu = DefaultMTU
} }
if err := wgInterface.SetLinkMTU(mtu); err != nil { if err := wgInterface.SetLinkMTU(mtu); err != nil {