rename user to peer

This commit is contained in:
Christoph Haas 2021-02-21 23:23:58 +01:00
parent 53814dbc27
commit 984f744548
7 changed files with 222 additions and 222 deletions

View File

@ -27,7 +27,7 @@ const CacheRefreshDuration = 5 * time.Minute
func init() { func init() {
gob.Register(SessionData{}) gob.Register(SessionData{})
gob.Register(FlashData{}) gob.Register(FlashData{})
gob.Register(User{}) gob.Register(Peer{})
gob.Register(Device{}) gob.Register(Device{})
gob.Register(LdapCreateForm{}) gob.Register(LdapCreateForm{})
} }

View File

@ -101,7 +101,7 @@ func (s *Server) PostLogin(c *gin.Context) {
users := s.users.GetUsersByMail(sessionData.Email) users := s.users.GetUsersByMail(sessionData.Email)
if len(users) == 0 { // Create vpn peer if len(users) == 0 { // Create vpn peer
err := s.CreateUser(User{ err := s.CreateUser(Peer{
Identifier: sessionData.Firstname + " " + sessionData.Lastname + " (Default)", Identifier: sessionData.Firstname + " " + sessionData.Lastname + " (Default)",
Email: sessionData.Email, Email: sessionData.Email,
CreatedBy: sessionData.Email, CreatedBy: sessionData.Email,

View File

@ -80,7 +80,7 @@ func (s *Server) GetAdminIndex(c *gin.Context) {
Alerts []FlashData Alerts []FlashData
Session SessionData Session SessionData
Static StaticData Static StaticData
Peers []User Peers []Peer
TotalPeers int TotalPeers int
Device Device Device Device
LdapDisabled bool LdapDisabled bool
@ -128,7 +128,7 @@ func (s *Server) GetUserIndex(c *gin.Context) {
Alerts []FlashData Alerts []FlashData
Session SessionData Session SessionData
Static StaticData Static StaticData
Peers []User Peers []Peer
TotalPeers int TotalPeers int
Device Device Device Device
}{ }{

View File

@ -23,7 +23,7 @@ func (s *Server) GetAdminEditInterface(c *gin.Context) {
Alerts []FlashData Alerts []FlashData
Session SessionData Session SessionData
Static StaticData Static StaticData
Peers []User Peers []Peer
Device Device Device Device
EditableKeys bool EditableKeys bool
}{ }{
@ -58,7 +58,7 @@ func (s *Server) PostAdminEditInterface(c *gin.Context) {
formDevice.DNSStr = common.ListToString(formDevice.DNS) formDevice.DNSStr = common.ListToString(formDevice.DNS)
// Update WireGuard device // Update WireGuard device
err := s.wg.UpdateDevice(formDevice.DeviceName, formDevice.GetDeviceConfig()) err := s.wg.UpdateDevice(formDevice.DeviceName, formDevice.GetConfig())
if err != nil { if err != nil {
_ = s.updateFormInSession(c, formDevice) _ = s.updateFormInSession(c, formDevice)
s.setFlashMessage(c, "Failed to update device in WireGuard: "+err.Error(), "danger") s.setFlashMessage(c, "Failed to update device in WireGuard: "+err.Error(), "danger")
@ -108,7 +108,7 @@ func (s *Server) PostAdminEditInterface(c *gin.Context) {
func (s *Server) GetInterfaceConfig(c *gin.Context) { func (s *Server) GetInterfaceConfig(c *gin.Context) {
device := s.users.GetDevice() device := s.users.GetDevice()
users := s.users.GetActiveUsers() users := s.users.GetActiveUsers()
cfg, err := device.GetDeviceConfigFile(users) cfg, err := device.GetConfigFile(users)
if err != nil { if err != nil {
s.GetHandleError(c, http.StatusInternalServerError, "ConfigFile error", err.Error()) s.GetHandleError(c, http.StatusInternalServerError, "ConfigFile error", err.Error())
return return

View File

@ -35,7 +35,7 @@ func (s *Server) GetAdminEditPeer(c *gin.Context) {
Alerts []FlashData Alerts []FlashData
Session SessionData Session SessionData
Static StaticData Static StaticData
Peer User Peer Peer
Device Device Device Device
EditableKeys bool EditableKeys bool
}{ }{
@ -43,7 +43,7 @@ func (s *Server) GetAdminEditPeer(c *gin.Context) {
Alerts: s.getFlashes(c), Alerts: s.getFlashes(c),
Session: currentSession, Session: currentSession,
Static: s.getStaticData(), Static: s.getStaticData(),
Peer: currentSession.FormData.(User), Peer: currentSession.FormData.(Peer),
Device: device, Device: device,
EditableKeys: s.config.Core.EditableKeys, EditableKeys: s.config.Core.EditableKeys,
}) })
@ -54,34 +54,34 @@ func (s *Server) PostAdminEditPeer(c *gin.Context) {
urlEncodedKey := url.QueryEscape(c.Query("pkey")) urlEncodedKey := url.QueryEscape(c.Query("pkey"))
currentSession := s.getSessionData(c) currentSession := s.getSessionData(c)
var formUser User var formPeer Peer
if currentSession.FormData != nil { if currentSession.FormData != nil {
formUser = currentSession.FormData.(User) formPeer = currentSession.FormData.(Peer)
} }
if err := c.ShouldBind(&formUser); err != nil { if err := c.ShouldBind(&formPeer); err != nil {
_ = s.updateFormInSession(c, formUser) _ = s.updateFormInSession(c, formPeer)
s.setFlashMessage(c, "failed to bind form data: "+err.Error(), "danger") s.setFlashMessage(c, "failed to bind form data: "+err.Error(), "danger")
c.Redirect(http.StatusSeeOther, "/admin/peer/edit?pkey="+urlEncodedKey+"&formerr=bind") c.Redirect(http.StatusSeeOther, "/admin/peer/edit?pkey="+urlEncodedKey+"&formerr=bind")
return return
} }
// Clean list input // Clean list input
formUser.IPs = common.ParseStringList(formUser.IPsStr) formPeer.IPs = common.ParseStringList(formPeer.IPsStr)
formUser.AllowedIPs = common.ParseStringList(formUser.AllowedIPsStr) formPeer.AllowedIPs = common.ParseStringList(formPeer.AllowedIPsStr)
formUser.IPsStr = common.ListToString(formUser.IPs) formPeer.IPsStr = common.ListToString(formPeer.IPs)
formUser.AllowedIPsStr = common.ListToString(formUser.AllowedIPs) formPeer.AllowedIPsStr = common.ListToString(formPeer.AllowedIPs)
disabled := c.PostForm("isdisabled") != "" disabled := c.PostForm("isdisabled") != ""
now := time.Now() now := time.Now()
if disabled && currentUser.DeactivatedAt == nil { if disabled && currentUser.DeactivatedAt == nil {
formUser.DeactivatedAt = &now formPeer.DeactivatedAt = &now
} else if !disabled { } else if !disabled {
formUser.DeactivatedAt = nil formPeer.DeactivatedAt = nil
} }
// Update in database // Update in database
if err := s.UpdateUser(formUser, now); err != nil { if err := s.UpdateUser(formPeer, now); err != nil {
_ = s.updateFormInSession(c, formUser) _ = s.updateFormInSession(c, formPeer)
s.setFlashMessage(c, "failed to update user: "+err.Error(), "danger") s.setFlashMessage(c, "failed to update user: "+err.Error(), "danger")
c.Redirect(http.StatusSeeOther, "/admin/peer/edit?pkey="+urlEncodedKey+"&formerr=update") c.Redirect(http.StatusSeeOther, "/admin/peer/edit?pkey="+urlEncodedKey+"&formerr=update")
return return
@ -104,7 +104,7 @@ func (s *Server) GetAdminCreatePeer(c *gin.Context) {
Alerts []FlashData Alerts []FlashData
Session SessionData Session SessionData
Static StaticData Static StaticData
Peer User Peer Peer
Device Device Device Device
EditableKeys bool EditableKeys bool
}{ }{
@ -112,7 +112,7 @@ func (s *Server) GetAdminCreatePeer(c *gin.Context) {
Alerts: s.getFlashes(c), Alerts: s.getFlashes(c),
Session: currentSession, Session: currentSession,
Static: s.getStaticData(), Static: s.getStaticData(),
Peer: currentSession.FormData.(User), Peer: currentSession.FormData.(Peer),
Device: device, Device: device,
EditableKeys: s.config.Core.EditableKeys, EditableKeys: s.config.Core.EditableKeys,
}) })
@ -120,31 +120,31 @@ func (s *Server) GetAdminCreatePeer(c *gin.Context) {
func (s *Server) PostAdminCreatePeer(c *gin.Context) { func (s *Server) PostAdminCreatePeer(c *gin.Context) {
currentSession := s.getSessionData(c) currentSession := s.getSessionData(c)
var formUser User var formPeer Peer
if currentSession.FormData != nil { if currentSession.FormData != nil {
formUser = currentSession.FormData.(User) formPeer = currentSession.FormData.(Peer)
} }
if err := c.ShouldBind(&formUser); err != nil { if err := c.ShouldBind(&formPeer); err != nil {
_ = s.updateFormInSession(c, formUser) _ = s.updateFormInSession(c, formPeer)
s.setFlashMessage(c, "failed to bind form data: "+err.Error(), "danger") s.setFlashMessage(c, "failed to bind form data: "+err.Error(), "danger")
c.Redirect(http.StatusSeeOther, "/admin/peer/create?formerr=bind") c.Redirect(http.StatusSeeOther, "/admin/peer/create?formerr=bind")
return return
} }
// Clean list input // Clean list input
formUser.IPs = common.ParseStringList(formUser.IPsStr) formPeer.IPs = common.ParseStringList(formPeer.IPsStr)
formUser.AllowedIPs = common.ParseStringList(formUser.AllowedIPsStr) formPeer.AllowedIPs = common.ParseStringList(formPeer.AllowedIPsStr)
formUser.IPsStr = common.ListToString(formUser.IPs) formPeer.IPsStr = common.ListToString(formPeer.IPs)
formUser.AllowedIPsStr = common.ListToString(formUser.AllowedIPs) formPeer.AllowedIPsStr = common.ListToString(formPeer.AllowedIPs)
disabled := c.PostForm("isdisabled") != "" disabled := c.PostForm("isdisabled") != ""
now := time.Now() now := time.Now()
if disabled { if disabled {
formUser.DeactivatedAt = &now formPeer.DeactivatedAt = &now
} }
if err := s.CreateUser(formUser); err != nil { if err := s.CreateUser(formPeer); err != nil {
_ = s.updateFormInSession(c, formUser) _ = s.updateFormInSession(c, formPeer)
s.setFlashMessage(c, "failed to add user: "+err.Error(), "danger") s.setFlashMessage(c, "failed to add user: "+err.Error(), "danger")
c.Redirect(http.StatusSeeOther, "/admin/peer/create?formerr=create") c.Redirect(http.StatusSeeOther, "/admin/peer/create?formerr=create")
return return
@ -254,7 +254,7 @@ func (s *Server) GetPeerConfig(c *gin.Context) {
return return
} }
cfg, err := user.GetClientConfigFile(s.users.GetDevice()) cfg, err := user.GetConfigFile(s.users.GetDevice())
if err != nil { if err != nil {
s.GetHandleError(c, http.StatusInternalServerError, "ConfigFile error", err.Error()) s.GetHandleError(c, http.StatusInternalServerError, "ConfigFile error", err.Error())
return return
@ -273,7 +273,7 @@ func (s *Server) GetPeerConfigMail(c *gin.Context) {
return return
} }
cfg, err := user.GetClientConfigFile(s.users.GetDevice()) cfg, err := user.GetConfigFile(s.users.GetDevice())
if err != nil { if err != nil {
s.GetHandleError(c, http.StatusInternalServerError, "ConfigFile error", err.Error()) s.GetHandleError(c, http.StatusInternalServerError, "ConfigFile error", err.Error())
return return
@ -286,7 +286,7 @@ func (s *Server) GetPeerConfigMail(c *gin.Context) {
// Apply mail template // Apply mail template
var tplBuff bytes.Buffer var tplBuff bytes.Buffer
if err := s.mailTpl.Execute(&tplBuff, struct { if err := s.mailTpl.Execute(&tplBuff, struct {
Client User Client Peer
QrcodePngName string QrcodePngName string
PortalUrl string PortalUrl string
}{ }{

View File

@ -12,55 +12,55 @@ import (
"golang.zx2c4.com/wireguard/wgctrl/wgtypes" "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
) )
func (s *Server) PrepareNewUser() (User, error) { func (s *Server) PrepareNewUser() (Peer, error) {
device := s.users.GetDevice() device := s.users.GetDevice()
user := User{} peer := Peer{}
user.IsNew = true peer.IsNew = true
user.AllowedIPsStr = device.AllowedIPsStr peer.AllowedIPsStr = device.AllowedIPsStr
user.IPs = make([]string, len(device.IPs)) peer.IPs = make([]string, len(device.IPs))
for i := range device.IPs { for i := range device.IPs {
freeIP, err := s.users.GetAvailableIp(device.IPs[i]) freeIP, err := s.users.GetAvailableIp(device.IPs[i])
if err != nil { if err != nil {
return User{}, err return Peer{}, err
} }
user.IPs[i] = freeIP peer.IPs[i] = freeIP
} }
user.IPsStr = common.ListToString(user.IPs) peer.IPsStr = common.ListToString(peer.IPs)
psk, err := wgtypes.GenerateKey() psk, err := wgtypes.GenerateKey()
if err != nil { if err != nil {
return User{}, err return Peer{}, err
} }
key, err := wgtypes.GeneratePrivateKey() key, err := wgtypes.GeneratePrivateKey()
if err != nil { if err != nil {
return User{}, err return Peer{}, err
} }
user.PresharedKey = psk.String() peer.PresharedKey = psk.String()
user.PrivateKey = key.String() peer.PrivateKey = key.String()
user.PublicKey = key.PublicKey().String() peer.PublicKey = key.PublicKey().String()
user.UID = fmt.Sprintf("u%x", md5.Sum([]byte(user.PublicKey))) peer.UID = fmt.Sprintf("u%x", md5.Sum([]byte(peer.PublicKey)))
return user, nil return peer, nil
} }
func (s *Server) CreateUserByEmail(email, identifierSuffix string, disabled bool) error { func (s *Server) CreateUserByEmail(email, identifierSuffix string, disabled bool) error {
ldapUser := s.ldapUsers.GetUserData(s.ldapUsers.GetUserDNByMail(email)) ldapUser := s.ldapUsers.GetUserData(s.ldapUsers.GetUserDNByMail(email))
if ldapUser.DN == "" { if ldapUser.DN == "" {
return errors.New("no user with email " + email + " found") return errors.New("no peer with email " + email + " found")
} }
device := s.users.GetDevice() device := s.users.GetDevice()
user := User{} peer := Peer{}
user.AllowedIPsStr = device.AllowedIPsStr peer.AllowedIPsStr = device.AllowedIPsStr
user.IPs = make([]string, len(device.IPs)) peer.IPs = make([]string, len(device.IPs))
for i := range device.IPs { for i := range device.IPs {
freeIP, err := s.users.GetAvailableIp(device.IPs[i]) freeIP, err := s.users.GetAvailableIp(device.IPs[i])
if err != nil { if err != nil {
return err return err
} }
user.IPs[i] = freeIP peer.IPs[i] = freeIP
} }
user.IPsStr = common.ListToString(user.IPs) peer.IPsStr = common.ListToString(peer.IPs)
psk, err := wgtypes.GenerateKey() psk, err := wgtypes.GenerateKey()
if err != nil { if err != nil {
return err return err
@ -69,21 +69,21 @@ func (s *Server) CreateUserByEmail(email, identifierSuffix string, disabled bool
if err != nil { if err != nil {
return err return err
} }
user.PresharedKey = psk.String() peer.PresharedKey = psk.String()
user.PrivateKey = key.String() peer.PrivateKey = key.String()
user.PublicKey = key.PublicKey().String() peer.PublicKey = key.PublicKey().String()
user.UID = fmt.Sprintf("u%x", md5.Sum([]byte(user.PublicKey))) peer.UID = fmt.Sprintf("u%x", md5.Sum([]byte(peer.PublicKey)))
user.Email = email peer.Email = email
user.Identifier = fmt.Sprintf("%s %s (%s)", ldapUser.Firstname, ldapUser.Lastname, identifierSuffix) peer.Identifier = fmt.Sprintf("%s %s (%s)", ldapUser.Firstname, ldapUser.Lastname, identifierSuffix)
now := time.Now() now := time.Now()
if disabled { if disabled {
user.DeactivatedAt = &now peer.DeactivatedAt = &now
} }
return s.CreateUser(user) return s.CreateUser(peer)
} }
func (s *Server) CreateUser(user User) error { func (s *Server) CreateUser(user Peer) error {
device := s.users.GetDevice() device := s.users.GetDevice()
user.AllowedIPsStr = device.AllowedIPsStr user.AllowedIPsStr = device.AllowedIPsStr
@ -114,7 +114,7 @@ func (s *Server) CreateUser(user User) error {
// Create WireGuard interface // Create WireGuard interface
if user.DeactivatedAt == nil { if user.DeactivatedAt == nil {
if err := s.wg.AddPeer(user.GetPeerConfig()); err != nil { if err := s.wg.AddPeer(user.GetConfig()); err != nil {
return err return err
} }
} }
@ -127,7 +127,7 @@ func (s *Server) CreateUser(user User) error {
return s.WriteWireGuardConfigFile() return s.WriteWireGuardConfigFile()
} }
func (s *Server) UpdateUser(user User, updateTime time.Time) error { func (s *Server) UpdateUser(user Peer, updateTime time.Time) error {
currentUser := s.users.GetUserByKey(user.PublicKey) currentUser := s.users.GetUserByKey(user.PublicKey)
// Update WireGuard device // Update WireGuard device
@ -136,9 +136,9 @@ func (s *Server) UpdateUser(user User, updateTime time.Time) error {
case user.DeactivatedAt == &updateTime: case user.DeactivatedAt == &updateTime:
err = s.wg.RemovePeer(user.PublicKey) err = s.wg.RemovePeer(user.PublicKey)
case user.DeactivatedAt == nil && currentUser.Peer != nil: case user.DeactivatedAt == nil && currentUser.Peer != nil:
err = s.wg.UpdatePeer(user.GetPeerConfig()) err = s.wg.UpdatePeer(user.GetConfig())
case user.DeactivatedAt == nil && currentUser.Peer == nil: case user.DeactivatedAt == nil && currentUser.Peer == nil:
err = s.wg.AddPeer(user.GetPeerConfig()) err = s.wg.AddPeer(user.GetConfig())
} }
if err != nil { if err != nil {
return err return err
@ -152,7 +152,7 @@ func (s *Server) UpdateUser(user User, updateTime time.Time) error {
return s.WriteWireGuardConfigFile() return s.WriteWireGuardConfigFile()
} }
func (s *Server) DeleteUser(user User) error { func (s *Server) DeleteUser(user Peer) error {
// Delete WireGuard peer // Delete WireGuard peer
if err := s.wg.RemovePeer(user.PublicKey); err != nil { if err := s.wg.RemovePeer(user.PublicKey); err != nil {
return err return err
@ -171,7 +171,7 @@ func (s *Server) RestoreWireGuardInterface() error {
for i := range activeUsers { for i := range activeUsers {
if activeUsers[i].Peer == nil { if activeUsers[i].Peer == nil {
if err := s.wg.AddPeer(activeUsers[i].GetPeerConfig()); err != nil { if err := s.wg.AddPeer(activeUsers[i].GetConfig()); err != nil {
return err return err
} }
} }
@ -189,7 +189,7 @@ func (s *Server) WriteWireGuardConfigFile() error {
} }
device := s.users.GetDevice() device := s.users.GetDevice()
cfg, err := device.GetDeviceConfigFile(s.users.GetActiveUsers()) cfg, err := device.GetConfigFile(s.users.GetActiveUsers())
if err != nil { if err != nil {
return err return err
} }

View File

@ -64,10 +64,10 @@ func init() {
} }
// //
// USER ---------------------------------------------------------------------------------------- // PEER ----------------------------------------------------------------------------------------
// //
type User struct { type Peer struct {
Peer *wgtypes.Peer `gorm:"-"` Peer *wgtypes.Peer `gorm:"-"`
LdapUser *ldap.UserCacheHolderEntry `gorm:"-"` // optional, it is still possible to have users without ldap LdapUser *ldap.UserCacheHolderEntry `gorm:"-"` // optional, it is still possible to have users without ldap
Config string `gorm:"-"` Config string `gorm:"-"`
@ -96,33 +96,11 @@ type User struct {
UpdatedAt time.Time UpdatedAt time.Time
} }
func (u User) GetClientConfigFile(device Device) ([]byte, error) { func (p Peer) GetConfig() wgtypes.PeerConfig {
tpl, err := template.New("client").Funcs(template.FuncMap{"StringsJoin": strings.Join}).Parse(wireguard.ClientCfgTpl) publicKey, _ := wgtypes.ParseKey(p.PublicKey)
if err != nil {
return nil, err
}
var tplBuff bytes.Buffer
err = tpl.Execute(&tplBuff, struct {
Client User
Server Device
}{
Client: u,
Server: device,
})
if err != nil {
return nil, err
}
return tplBuff.Bytes(), nil
}
func (u User) GetPeerConfig() wgtypes.PeerConfig {
publicKey, _ := wgtypes.ParseKey(u.PublicKey)
var presharedKey *wgtypes.Key var presharedKey *wgtypes.Key
if u.PresharedKey != "" { if p.PresharedKey != "" {
presharedKeyTmp, _ := wgtypes.ParseKey(u.PresharedKey) presharedKeyTmp, _ := wgtypes.ParseKey(p.PresharedKey)
presharedKey = &presharedKeyTmp presharedKey = &presharedKeyTmp
} }
@ -134,9 +112,9 @@ func (u User) GetPeerConfig() wgtypes.PeerConfig {
Endpoint: nil, Endpoint: nil,
PersistentKeepaliveInterval: nil, PersistentKeepaliveInterval: nil,
ReplaceAllowedIPs: true, ReplaceAllowedIPs: true,
AllowedIPs: make([]net.IPNet, len(u.IPs)), AllowedIPs: make([]net.IPNet, len(p.IPs)),
} }
for i, ip := range u.IPs { for i, ip := range p.IPs {
_, ipNet, err := net.ParseCIDR(ip) _, ipNet, err := net.ParseCIDR(ip)
if err == nil { if err == nil {
cfg.AllowedIPs[i] = *ipNet cfg.AllowedIPs[i] = *ipNet
@ -146,8 +124,30 @@ func (u User) GetPeerConfig() wgtypes.PeerConfig {
return cfg return cfg
} }
func (u User) GetQRCode() ([]byte, error) { func (p Peer) GetConfigFile(device Device) ([]byte, error) {
png, err := qrcode.Encode(u.Config, qrcode.Medium, 250) tpl, err := template.New("client").Funcs(template.FuncMap{"StringsJoin": strings.Join}).Parse(wireguard.ClientCfgTpl)
if err != nil {
return nil, err
}
var tplBuff bytes.Buffer
err = tpl.Execute(&tplBuff, struct {
Client Peer
Server Device
}{
Client: p,
Server: device,
})
if err != nil {
return nil, err
}
return tplBuff.Bytes(), nil
}
func (p Peer) GetQRCode() ([]byte, error) {
png, err := qrcode.Encode(p.Config, qrcode.Medium, 250)
if err != nil { if err != nil {
logrus.WithFields(logrus.Fields{ logrus.WithFields(logrus.Fields{
"err": err, "err": err,
@ -157,18 +157,18 @@ func (u User) GetQRCode() ([]byte, error) {
return png, nil return png, nil
} }
func (u User) IsValid() bool { func (p Peer) IsValid() bool {
if u.PublicKey == "" { if p.PublicKey == "" {
return false return false
} }
return true return true
} }
func (u User) ToMap() map[string]string { func (p Peer) ToMap() map[string]string {
out := make(map[string]string) out := make(map[string]string)
v := reflect.ValueOf(u) v := reflect.ValueOf(p)
if v.Kind() == reflect.Ptr { if v.Kind() == reflect.Ptr {
v = v.Elem() v = v.Elem()
} }
@ -185,9 +185,9 @@ func (u User) ToMap() map[string]string {
return out return out
} }
func (u User) GetConfigFileName() string { func (p Peer) GetConfigFileName() string {
reg := regexp.MustCompile("[^a-zA-Z0-9_-]+") reg := regexp.MustCompile("[^a-zA-Z0-9_-]+")
return reg.ReplaceAllString(strings.ReplaceAll(u.Identifier, " ", "-"), "") + ".conf" return reg.ReplaceAllString(strings.ReplaceAll(p.Identifier, " ", "-"), "") + ".conf"
} }
// //
@ -232,7 +232,7 @@ func (d Device) IsValid() bool {
return true return true
} }
func (d Device) GetDeviceConfig() wgtypes.Config { func (d Device) GetConfig() wgtypes.Config {
var privateKey *wgtypes.Key var privateKey *wgtypes.Key
if d.PrivateKey != "" { if d.PrivateKey != "" {
pKey, _ := wgtypes.ParseKey(d.PrivateKey) pKey, _ := wgtypes.ParseKey(d.PrivateKey)
@ -247,7 +247,7 @@ func (d Device) GetDeviceConfig() wgtypes.Config {
return cfg return cfg
} }
func (d Device) GetDeviceConfigFile(clients []User) ([]byte, error) { func (d Device) GetConfigFile(clients []Peer) ([]byte, error) {
tpl, err := template.New("server").Funcs(template.FuncMap{"StringsJoin": strings.Join}).Parse(wireguard.DeviceCfgTpl) tpl, err := template.New("server").Funcs(template.FuncMap{"StringsJoin": strings.Join}).Parse(wireguard.DeviceCfgTpl)
if err != nil { if err != nil {
return nil, err return nil, err
@ -256,7 +256,7 @@ func (d Device) GetDeviceConfigFile(clients []User) ([]byte, error) {
var tplBuff bytes.Buffer var tplBuff bytes.Buffer
err = tpl.Execute(&tplBuff, struct { err = tpl.Execute(&tplBuff, struct {
Clients []User Clients []Peer
Server Device Server Device
}{ }{
Clients: clients, Clients: clients,
@ -295,7 +295,7 @@ func NewUserManager(dbPath string, wg *wireguard.Manager, ldapUsers *ldap.Synchr
return nil return nil
} }
err = um.db.AutoMigrate(&User{}, &Device{}) err = um.db.AutoMigrate(&Peer{}, &Device{})
if err != nil { if err != nil {
logrus.Errorf("failed to migrate sqlite database: %v", err) logrus.Errorf("failed to migrate sqlite database: %v", err)
return nil return nil
@ -341,32 +341,32 @@ func (u *UserManager) InitFromCurrentInterface() error {
return nil return nil
} }
func (u *UserManager) validateOrCreateUserForPeer(peer wgtypes.Peer) error { func (u *UserManager) validateOrCreateUserForPeer(wgPeer wgtypes.Peer) error {
user := User{} peer := Peer{}
u.db.Where("public_key = ?", peer.PublicKey.String()).FirstOrInit(&user) u.db.Where("public_key = ?", wgPeer.PublicKey.String()).FirstOrInit(&peer)
if user.PublicKey == "" { // user not found, create if peer.PublicKey == "" { // peer not found, create
user.UID = fmt.Sprintf("u%x", md5.Sum([]byte(peer.PublicKey.String()))) peer.UID = fmt.Sprintf("u%x", md5.Sum([]byte(wgPeer.PublicKey.String())))
user.PublicKey = peer.PublicKey.String() peer.PublicKey = wgPeer.PublicKey.String()
user.PrivateKey = "" // UNKNOWN peer.PrivateKey = "" // UNKNOWN
if peer.PresharedKey != (wgtypes.Key{}) { if wgPeer.PresharedKey != (wgtypes.Key{}) {
user.PresharedKey = peer.PresharedKey.String() peer.PresharedKey = wgPeer.PresharedKey.String()
} }
user.Email = "autodetected@example.com" peer.Email = "autodetected@example.com"
user.Identifier = "Autodetected (" + user.PublicKey[0:8] + ")" peer.Identifier = "Autodetected (" + peer.PublicKey[0:8] + ")"
user.UpdatedAt = time.Now() peer.UpdatedAt = time.Now()
user.CreatedAt = time.Now() peer.CreatedAt = time.Now()
user.AllowedIPs = make([]string, 0) // UNKNOWN peer.AllowedIPs = make([]string, 0) // UNKNOWN
user.IPs = make([]string, len(peer.AllowedIPs)) peer.IPs = make([]string, len(wgPeer.AllowedIPs))
for i, ip := range peer.AllowedIPs { for i, ip := range wgPeer.AllowedIPs {
user.IPs[i] = ip.String() peer.IPs[i] = ip.String()
} }
user.AllowedIPsStr = strings.Join(user.AllowedIPs, ", ") peer.AllowedIPsStr = strings.Join(peer.AllowedIPs, ", ")
user.IPsStr = strings.Join(user.IPs, ", ") peer.IPsStr = strings.Join(peer.IPs, ", ")
res := u.db.Create(&user) res := u.db.Create(&peer)
if res.Error != nil { if res.Error != nil {
logrus.Errorf("failed to create autodetected peer: %v", res.Error) logrus.Errorf("failed to create autodetected wgPeer: %v", res.Error)
return res.Error return res.Error
} }
} }
@ -401,11 +401,11 @@ func (u *UserManager) validateOrCreateDevice(dev wgtypes.Device, ipAddresses []s
return nil return nil
} }
func (u *UserManager) populateUserData(user *User) { func (u *UserManager) populateUserData(user *Peer) {
user.AllowedIPs = strings.Split(user.AllowedIPsStr, ", ") user.AllowedIPs = strings.Split(user.AllowedIPsStr, ", ")
user.IPs = strings.Split(user.IPsStr, ", ") user.IPs = strings.Split(user.IPsStr, ", ")
// Set config file // Set config file
tmpCfg, _ := user.GetClientConfigFile(u.GetDevice()) tmpCfg, _ := user.GetConfigFile(u.GetDevice())
user.Config = string(tmpCfg) user.Config = string(tmpCfg)
// set data from WireGuard interface // set data from WireGuard interface
@ -442,69 +442,69 @@ func (u *UserManager) populateDeviceData(device *Device) {
device.Interface, _ = u.wg.GetDeviceInfo() device.Interface, _ = u.wg.GetDeviceInfo()
} }
func (u *UserManager) GetAllUsers() []User { func (u *UserManager) GetAllUsers() []Peer {
users := make([]User, 0) peers := make([]Peer, 0)
u.db.Find(&users) u.db.Find(&peers)
for i := range users { for i := range peers {
u.populateUserData(&users[i]) u.populateUserData(&peers[i])
} }
return users return peers
} }
func (u *UserManager) GetActiveUsers() []User { func (u *UserManager) GetActiveUsers() []Peer {
users := make([]User, 0) peers := make([]Peer, 0)
u.db.Where("deactivated_at IS NULL").Find(&users) u.db.Where("deactivated_at IS NULL").Find(&peers)
for i := range users { for i := range peers {
u.populateUserData(&users[i]) u.populateUserData(&peers[i])
} }
return users return peers
} }
func (u *UserManager) GetFilteredAndSortedUsers(sortKey, sortDirection, search string) []User { func (u *UserManager) GetFilteredAndSortedUsers(sortKey, sortDirection, search string) []Peer {
users := make([]User, 0) peers := make([]Peer, 0)
u.db.Find(&users) u.db.Find(&peers)
filteredUsers := make([]User, 0, len(users)) filteredPeers := make([]Peer, 0, len(peers))
for i := range users { for i := range peers {
u.populateUserData(&users[i]) u.populateUserData(&peers[i])
if search == "" || if search == "" ||
strings.Contains(users[i].Email, search) || strings.Contains(peers[i].Email, search) ||
strings.Contains(users[i].Identifier, search) || strings.Contains(peers[i].Identifier, search) ||
strings.Contains(users[i].PublicKey, search) { strings.Contains(peers[i].PublicKey, search) {
filteredUsers = append(filteredUsers, users[i]) filteredPeers = append(filteredPeers, peers[i])
} }
} }
sort.Slice(filteredUsers, func(i, j int) bool { sort.Slice(filteredPeers, func(i, j int) bool {
var sortValueLeft string var sortValueLeft string
var sortValueRight string var sortValueRight string
switch sortKey { switch sortKey {
case "id": case "id":
sortValueLeft = filteredUsers[i].Identifier sortValueLeft = filteredPeers[i].Identifier
sortValueRight = filteredUsers[j].Identifier sortValueRight = filteredPeers[j].Identifier
case "pubKey": case "pubKey":
sortValueLeft = filteredUsers[i].PublicKey sortValueLeft = filteredPeers[i].PublicKey
sortValueRight = filteredUsers[j].PublicKey sortValueRight = filteredPeers[j].PublicKey
case "mail": case "mail":
sortValueLeft = filteredUsers[i].Email sortValueLeft = filteredPeers[i].Email
sortValueRight = filteredUsers[j].Email sortValueRight = filteredPeers[j].Email
case "ip": case "ip":
sortValueLeft = filteredUsers[i].IPsStr sortValueLeft = filteredPeers[i].IPsStr
sortValueRight = filteredUsers[j].IPsStr sortValueRight = filteredPeers[j].IPsStr
case "handshake": case "handshake":
if filteredUsers[i].Peer == nil { if filteredPeers[i].Peer == nil {
return false return false
} else if filteredUsers[j].Peer == nil { } else if filteredPeers[j].Peer == nil {
return true return true
} }
sortValueLeft = filteredUsers[i].Peer.LastHandshakeTime.Format(time.RFC3339) sortValueLeft = filteredPeers[i].Peer.LastHandshakeTime.Format(time.RFC3339)
sortValueRight = filteredUsers[j].Peer.LastHandshakeTime.Format(time.RFC3339) sortValueRight = filteredPeers[j].Peer.LastHandshakeTime.Format(time.RFC3339)
} }
if sortDirection == "asc" { if sortDirection == "asc" {
@ -514,42 +514,42 @@ func (u *UserManager) GetFilteredAndSortedUsers(sortKey, sortDirection, search s
} }
}) })
return filteredUsers return filteredPeers
} }
func (u *UserManager) GetSortedUsersForEmail(sortKey, sortDirection, email string) []User { func (u *UserManager) GetSortedUsersForEmail(sortKey, sortDirection, email string) []Peer {
users := make([]User, 0) peers := make([]Peer, 0)
u.db.Where("email = ?", email).Find(&users) u.db.Where("email = ?", email).Find(&peers)
for i := range users { for i := range peers {
u.populateUserData(&users[i]) u.populateUserData(&peers[i])
} }
sort.Slice(users, func(i, j int) bool { sort.Slice(peers, func(i, j int) bool {
var sortValueLeft string var sortValueLeft string
var sortValueRight string var sortValueRight string
switch sortKey { switch sortKey {
case "id": case "id":
sortValueLeft = users[i].Identifier sortValueLeft = peers[i].Identifier
sortValueRight = users[j].Identifier sortValueRight = peers[j].Identifier
case "pubKey": case "pubKey":
sortValueLeft = users[i].PublicKey sortValueLeft = peers[i].PublicKey
sortValueRight = users[j].PublicKey sortValueRight = peers[j].PublicKey
case "mail": case "mail":
sortValueLeft = users[i].Email sortValueLeft = peers[i].Email
sortValueRight = users[j].Email sortValueRight = peers[j].Email
case "ip": case "ip":
sortValueLeft = users[i].IPsStr sortValueLeft = peers[i].IPsStr
sortValueRight = users[j].IPsStr sortValueRight = peers[j].IPsStr
case "handshake": case "handshake":
if users[i].Peer == nil { if peers[i].Peer == nil {
return true return true
} else if users[j].Peer == nil { } else if peers[j].Peer == nil {
return false return false
} }
sortValueLeft = users[i].Peer.LastHandshakeTime.Format(time.RFC3339) sortValueLeft = peers[i].Peer.LastHandshakeTime.Format(time.RFC3339)
sortValueRight = users[j].Peer.LastHandshakeTime.Format(time.RFC3339) sortValueRight = peers[j].Peer.LastHandshakeTime.Format(time.RFC3339)
} }
if sortDirection == "asc" { if sortDirection == "asc" {
@ -559,7 +559,7 @@ func (u *UserManager) GetSortedUsersForEmail(sortKey, sortDirection, email strin
} }
}) })
return users return peers
} }
func (u *UserManager) GetDevice() Device { func (u *UserManager) GetDevice() Device {
@ -573,57 +573,57 @@ func (u *UserManager) GetDevice() Device {
return devices[0] // use first device for now... more to come? return devices[0] // use first device for now... more to come?
} }
func (u *UserManager) GetUserByKey(publicKey string) User { func (u *UserManager) GetUserByKey(publicKey string) Peer {
user := User{} peer := Peer{}
u.db.Where("public_key = ?", publicKey).FirstOrInit(&user) u.db.Where("public_key = ?", publicKey).FirstOrInit(&peer)
u.populateUserData(&user) u.populateUserData(&peer)
return user return peer
} }
func (u *UserManager) GetUsersByMail(mail string) []User { func (u *UserManager) GetUsersByMail(mail string) []Peer {
var users []User var peers []Peer
u.db.Where("email = ?", mail).Find(&users) u.db.Where("email = ?", mail).Find(&peers)
for i := range users { for i := range peers {
u.populateUserData(&users[i]) u.populateUserData(&peers[i])
} }
return users return peers
} }
func (u *UserManager) CreateUser(user User) error { func (u *UserManager) CreateUser(peer Peer) error {
user.UID = fmt.Sprintf("u%x", md5.Sum([]byte(user.PublicKey))) peer.UID = fmt.Sprintf("u%x", md5.Sum([]byte(peer.PublicKey)))
user.UpdatedAt = time.Now() peer.UpdatedAt = time.Now()
user.CreatedAt = time.Now() peer.CreatedAt = time.Now()
user.AllowedIPsStr = strings.Join(user.AllowedIPs, ", ") peer.AllowedIPsStr = strings.Join(peer.AllowedIPs, ", ")
user.IPsStr = strings.Join(user.IPs, ", ") peer.IPsStr = strings.Join(peer.IPs, ", ")
res := u.db.Create(&user) res := u.db.Create(&peer)
if res.Error != nil { if res.Error != nil {
logrus.Errorf("failed to create user: %v", res.Error) logrus.Errorf("failed to create peer: %v", res.Error)
return res.Error return res.Error
} }
return nil return nil
} }
func (u *UserManager) UpdateUser(user User) error { func (u *UserManager) UpdateUser(peer Peer) error {
user.UpdatedAt = time.Now() peer.UpdatedAt = time.Now()
user.AllowedIPsStr = strings.Join(user.AllowedIPs, ", ") peer.AllowedIPsStr = strings.Join(peer.AllowedIPs, ", ")
user.IPsStr = strings.Join(user.IPs, ", ") peer.IPsStr = strings.Join(peer.IPs, ", ")
res := u.db.Save(&user) res := u.db.Save(&peer)
if res.Error != nil { if res.Error != nil {
logrus.Errorf("failed to update user: %v", res.Error) logrus.Errorf("failed to update peer: %v", res.Error)
return res.Error return res.Error
} }
return nil return nil
} }
func (u *UserManager) DeleteUser(user User) error { func (u *UserManager) DeleteUser(peer Peer) error {
res := u.db.Delete(&user) res := u.db.Delete(&peer)
if res.Error != nil { if res.Error != nil {
logrus.Errorf("failed to delete user: %v", res.Error) logrus.Errorf("failed to delete peer: %v", res.Error)
return res.Error return res.Error
} }