diff --git a/internal/server/core.go b/internal/server/core.go index 925127f..36aa368 100644 --- a/internal/server/core.go +++ b/internal/server/core.go @@ -27,7 +27,7 @@ const CacheRefreshDuration = 5 * time.Minute func init() { gob.Register(SessionData{}) gob.Register(FlashData{}) - gob.Register(User{}) + gob.Register(Peer{}) gob.Register(Device{}) gob.Register(LdapCreateForm{}) } diff --git a/internal/server/handlers_auth.go b/internal/server/handlers_auth.go index 3c3f702..e10d143 100644 --- a/internal/server/handlers_auth.go +++ b/internal/server/handlers_auth.go @@ -101,7 +101,7 @@ func (s *Server) PostLogin(c *gin.Context) { users := s.users.GetUsersByMail(sessionData.Email) if len(users) == 0 { // Create vpn peer - err := s.CreateUser(User{ + err := s.CreateUser(Peer{ Identifier: sessionData.Firstname + " " + sessionData.Lastname + " (Default)", Email: sessionData.Email, CreatedBy: sessionData.Email, diff --git a/internal/server/handlers_common.go b/internal/server/handlers_common.go index 90c60f5..192f195 100644 --- a/internal/server/handlers_common.go +++ b/internal/server/handlers_common.go @@ -80,7 +80,7 @@ func (s *Server) GetAdminIndex(c *gin.Context) { Alerts []FlashData Session SessionData Static StaticData - Peers []User + Peers []Peer TotalPeers int Device Device LdapDisabled bool @@ -128,7 +128,7 @@ func (s *Server) GetUserIndex(c *gin.Context) { Alerts []FlashData Session SessionData Static StaticData - Peers []User + Peers []Peer TotalPeers int Device Device }{ diff --git a/internal/server/handlers_interface.go b/internal/server/handlers_interface.go index c442a57..1269c5b 100644 --- a/internal/server/handlers_interface.go +++ b/internal/server/handlers_interface.go @@ -23,7 +23,7 @@ func (s *Server) GetAdminEditInterface(c *gin.Context) { Alerts []FlashData Session SessionData Static StaticData - Peers []User + Peers []Peer Device Device EditableKeys bool }{ @@ -58,7 +58,7 @@ func (s *Server) PostAdminEditInterface(c *gin.Context) { formDevice.DNSStr = common.ListToString(formDevice.DNS) // Update WireGuard device - err := s.wg.UpdateDevice(formDevice.DeviceName, formDevice.GetDeviceConfig()) + err := s.wg.UpdateDevice(formDevice.DeviceName, formDevice.GetConfig()) if err != nil { _ = s.updateFormInSession(c, formDevice) 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) { device := s.users.GetDevice() users := s.users.GetActiveUsers() - cfg, err := device.GetDeviceConfigFile(users) + cfg, err := device.GetConfigFile(users) if err != nil { s.GetHandleError(c, http.StatusInternalServerError, "ConfigFile error", err.Error()) return diff --git a/internal/server/handlers_peer.go b/internal/server/handlers_peer.go index 393b0bc..598b10b 100644 --- a/internal/server/handlers_peer.go +++ b/internal/server/handlers_peer.go @@ -35,7 +35,7 @@ func (s *Server) GetAdminEditPeer(c *gin.Context) { Alerts []FlashData Session SessionData Static StaticData - Peer User + Peer Peer Device Device EditableKeys bool }{ @@ -43,7 +43,7 @@ func (s *Server) GetAdminEditPeer(c *gin.Context) { Alerts: s.getFlashes(c), Session: currentSession, Static: s.getStaticData(), - Peer: currentSession.FormData.(User), + Peer: currentSession.FormData.(Peer), Device: device, EditableKeys: s.config.Core.EditableKeys, }) @@ -54,34 +54,34 @@ func (s *Server) PostAdminEditPeer(c *gin.Context) { urlEncodedKey := url.QueryEscape(c.Query("pkey")) currentSession := s.getSessionData(c) - var formUser User + var formPeer Peer if currentSession.FormData != nil { - formUser = currentSession.FormData.(User) + formPeer = currentSession.FormData.(Peer) } - if err := c.ShouldBind(&formUser); err != nil { - _ = s.updateFormInSession(c, formUser) + if err := c.ShouldBind(&formPeer); err != nil { + _ = s.updateFormInSession(c, formPeer) s.setFlashMessage(c, "failed to bind form data: "+err.Error(), "danger") c.Redirect(http.StatusSeeOther, "/admin/peer/edit?pkey="+urlEncodedKey+"&formerr=bind") return } // Clean list input - formUser.IPs = common.ParseStringList(formUser.IPsStr) - formUser.AllowedIPs = common.ParseStringList(formUser.AllowedIPsStr) - formUser.IPsStr = common.ListToString(formUser.IPs) - formUser.AllowedIPsStr = common.ListToString(formUser.AllowedIPs) + formPeer.IPs = common.ParseStringList(formPeer.IPsStr) + formPeer.AllowedIPs = common.ParseStringList(formPeer.AllowedIPsStr) + formPeer.IPsStr = common.ListToString(formPeer.IPs) + formPeer.AllowedIPsStr = common.ListToString(formPeer.AllowedIPs) disabled := c.PostForm("isdisabled") != "" now := time.Now() if disabled && currentUser.DeactivatedAt == nil { - formUser.DeactivatedAt = &now + formPeer.DeactivatedAt = &now } else if !disabled { - formUser.DeactivatedAt = nil + formPeer.DeactivatedAt = nil } // Update in database - if err := s.UpdateUser(formUser, now); err != nil { - _ = s.updateFormInSession(c, formUser) + if err := s.UpdateUser(formPeer, now); err != nil { + _ = s.updateFormInSession(c, formPeer) s.setFlashMessage(c, "failed to update user: "+err.Error(), "danger") c.Redirect(http.StatusSeeOther, "/admin/peer/edit?pkey="+urlEncodedKey+"&formerr=update") return @@ -104,7 +104,7 @@ func (s *Server) GetAdminCreatePeer(c *gin.Context) { Alerts []FlashData Session SessionData Static StaticData - Peer User + Peer Peer Device Device EditableKeys bool }{ @@ -112,7 +112,7 @@ func (s *Server) GetAdminCreatePeer(c *gin.Context) { Alerts: s.getFlashes(c), Session: currentSession, Static: s.getStaticData(), - Peer: currentSession.FormData.(User), + Peer: currentSession.FormData.(Peer), Device: device, EditableKeys: s.config.Core.EditableKeys, }) @@ -120,31 +120,31 @@ func (s *Server) GetAdminCreatePeer(c *gin.Context) { func (s *Server) PostAdminCreatePeer(c *gin.Context) { currentSession := s.getSessionData(c) - var formUser User + var formPeer Peer if currentSession.FormData != nil { - formUser = currentSession.FormData.(User) + formPeer = currentSession.FormData.(Peer) } - if err := c.ShouldBind(&formUser); err != nil { - _ = s.updateFormInSession(c, formUser) + if err := c.ShouldBind(&formPeer); err != nil { + _ = s.updateFormInSession(c, formPeer) s.setFlashMessage(c, "failed to bind form data: "+err.Error(), "danger") c.Redirect(http.StatusSeeOther, "/admin/peer/create?formerr=bind") return } // Clean list input - formUser.IPs = common.ParseStringList(formUser.IPsStr) - formUser.AllowedIPs = common.ParseStringList(formUser.AllowedIPsStr) - formUser.IPsStr = common.ListToString(formUser.IPs) - formUser.AllowedIPsStr = common.ListToString(formUser.AllowedIPs) + formPeer.IPs = common.ParseStringList(formPeer.IPsStr) + formPeer.AllowedIPs = common.ParseStringList(formPeer.AllowedIPsStr) + formPeer.IPsStr = common.ListToString(formPeer.IPs) + formPeer.AllowedIPsStr = common.ListToString(formPeer.AllowedIPs) disabled := c.PostForm("isdisabled") != "" now := time.Now() if disabled { - formUser.DeactivatedAt = &now + formPeer.DeactivatedAt = &now } - if err := s.CreateUser(formUser); err != nil { - _ = s.updateFormInSession(c, formUser) + if err := s.CreateUser(formPeer); err != nil { + _ = s.updateFormInSession(c, formPeer) s.setFlashMessage(c, "failed to add user: "+err.Error(), "danger") c.Redirect(http.StatusSeeOther, "/admin/peer/create?formerr=create") return @@ -254,7 +254,7 @@ func (s *Server) GetPeerConfig(c *gin.Context) { return } - cfg, err := user.GetClientConfigFile(s.users.GetDevice()) + cfg, err := user.GetConfigFile(s.users.GetDevice()) if err != nil { s.GetHandleError(c, http.StatusInternalServerError, "ConfigFile error", err.Error()) return @@ -273,7 +273,7 @@ func (s *Server) GetPeerConfigMail(c *gin.Context) { return } - cfg, err := user.GetClientConfigFile(s.users.GetDevice()) + cfg, err := user.GetConfigFile(s.users.GetDevice()) if err != nil { s.GetHandleError(c, http.StatusInternalServerError, "ConfigFile error", err.Error()) return @@ -286,7 +286,7 @@ func (s *Server) GetPeerConfigMail(c *gin.Context) { // Apply mail template var tplBuff bytes.Buffer if err := s.mailTpl.Execute(&tplBuff, struct { - Client User + Client Peer QrcodePngName string PortalUrl string }{ diff --git a/internal/server/helper.go b/internal/server/helper.go index 065d6d0..ab3d579 100644 --- a/internal/server/helper.go +++ b/internal/server/helper.go @@ -12,55 +12,55 @@ import ( "golang.zx2c4.com/wireguard/wgctrl/wgtypes" ) -func (s *Server) PrepareNewUser() (User, error) { +func (s *Server) PrepareNewUser() (Peer, error) { device := s.users.GetDevice() - user := User{} - user.IsNew = true - user.AllowedIPsStr = device.AllowedIPsStr - user.IPs = make([]string, len(device.IPs)) + peer := Peer{} + peer.IsNew = true + peer.AllowedIPsStr = device.AllowedIPsStr + peer.IPs = make([]string, len(device.IPs)) for i := range device.IPs { freeIP, err := s.users.GetAvailableIp(device.IPs[i]) 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() if err != nil { - return User{}, err + return Peer{}, err } key, err := wgtypes.GeneratePrivateKey() if err != nil { - return User{}, err + return Peer{}, err } - user.PresharedKey = psk.String() - user.PrivateKey = key.String() - user.PublicKey = key.PublicKey().String() - user.UID = fmt.Sprintf("u%x", md5.Sum([]byte(user.PublicKey))) + peer.PresharedKey = psk.String() + peer.PrivateKey = key.String() + peer.PublicKey = key.PublicKey().String() + 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 { ldapUser := s.ldapUsers.GetUserData(s.ldapUsers.GetUserDNByMail(email)) 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() - user := User{} - user.AllowedIPsStr = device.AllowedIPsStr - user.IPs = make([]string, len(device.IPs)) + peer := Peer{} + peer.AllowedIPsStr = device.AllowedIPsStr + peer.IPs = make([]string, len(device.IPs)) for i := range device.IPs { freeIP, err := s.users.GetAvailableIp(device.IPs[i]) if err != nil { 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() if err != nil { return err @@ -69,21 +69,21 @@ func (s *Server) CreateUserByEmail(email, identifierSuffix string, disabled bool if err != nil { return err } - user.PresharedKey = psk.String() - user.PrivateKey = key.String() - user.PublicKey = key.PublicKey().String() - user.UID = fmt.Sprintf("u%x", md5.Sum([]byte(user.PublicKey))) - user.Email = email - user.Identifier = fmt.Sprintf("%s %s (%s)", ldapUser.Firstname, ldapUser.Lastname, identifierSuffix) + peer.PresharedKey = psk.String() + peer.PrivateKey = key.String() + peer.PublicKey = key.PublicKey().String() + peer.UID = fmt.Sprintf("u%x", md5.Sum([]byte(peer.PublicKey))) + peer.Email = email + peer.Identifier = fmt.Sprintf("%s %s (%s)", ldapUser.Firstname, ldapUser.Lastname, identifierSuffix) now := time.Now() 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() user.AllowedIPsStr = device.AllowedIPsStr @@ -114,7 +114,7 @@ func (s *Server) CreateUser(user User) error { // Create WireGuard interface if user.DeactivatedAt == nil { - if err := s.wg.AddPeer(user.GetPeerConfig()); err != nil { + if err := s.wg.AddPeer(user.GetConfig()); err != nil { return err } } @@ -127,7 +127,7 @@ func (s *Server) CreateUser(user User) error { 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) // Update WireGuard device @@ -136,9 +136,9 @@ func (s *Server) UpdateUser(user User, updateTime time.Time) error { case user.DeactivatedAt == &updateTime: err = s.wg.RemovePeer(user.PublicKey) 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: - err = s.wg.AddPeer(user.GetPeerConfig()) + err = s.wg.AddPeer(user.GetConfig()) } if err != nil { return err @@ -152,7 +152,7 @@ func (s *Server) UpdateUser(user User, updateTime time.Time) error { return s.WriteWireGuardConfigFile() } -func (s *Server) DeleteUser(user User) error { +func (s *Server) DeleteUser(user Peer) error { // Delete WireGuard peer if err := s.wg.RemovePeer(user.PublicKey); err != nil { return err @@ -171,7 +171,7 @@ func (s *Server) RestoreWireGuardInterface() error { for i := range activeUsers { 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 } } @@ -189,7 +189,7 @@ func (s *Server) WriteWireGuardConfigFile() error { } device := s.users.GetDevice() - cfg, err := device.GetDeviceConfigFile(s.users.GetActiveUsers()) + cfg, err := device.GetConfigFile(s.users.GetActiveUsers()) if err != nil { return err } diff --git a/internal/server/usermanager.go b/internal/server/usermanager.go index d7a10b1..ec0ed6a 100644 --- a/internal/server/usermanager.go +++ b/internal/server/usermanager.go @@ -64,10 +64,10 @@ func init() { } // -// USER ---------------------------------------------------------------------------------------- +// PEER ---------------------------------------------------------------------------------------- // -type User struct { +type Peer struct { Peer *wgtypes.Peer `gorm:"-"` LdapUser *ldap.UserCacheHolderEntry `gorm:"-"` // optional, it is still possible to have users without ldap Config string `gorm:"-"` @@ -96,33 +96,11 @@ type User struct { UpdatedAt time.Time } -func (u User) GetClientConfigFile(device Device) ([]byte, error) { - 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 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) +func (p Peer) GetConfig() wgtypes.PeerConfig { + publicKey, _ := wgtypes.ParseKey(p.PublicKey) var presharedKey *wgtypes.Key - if u.PresharedKey != "" { - presharedKeyTmp, _ := wgtypes.ParseKey(u.PresharedKey) + if p.PresharedKey != "" { + presharedKeyTmp, _ := wgtypes.ParseKey(p.PresharedKey) presharedKey = &presharedKeyTmp } @@ -134,9 +112,9 @@ func (u User) GetPeerConfig() wgtypes.PeerConfig { Endpoint: nil, PersistentKeepaliveInterval: nil, 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) if err == nil { cfg.AllowedIPs[i] = *ipNet @@ -146,8 +124,30 @@ func (u User) GetPeerConfig() wgtypes.PeerConfig { return cfg } -func (u User) GetQRCode() ([]byte, error) { - png, err := qrcode.Encode(u.Config, qrcode.Medium, 250) +func (p Peer) GetConfigFile(device Device) ([]byte, error) { + 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 { logrus.WithFields(logrus.Fields{ "err": err, @@ -157,18 +157,18 @@ func (u User) GetQRCode() ([]byte, error) { return png, nil } -func (u User) IsValid() bool { - if u.PublicKey == "" { +func (p Peer) IsValid() bool { + if p.PublicKey == "" { return false } return true } -func (u User) ToMap() map[string]string { +func (p Peer) ToMap() map[string]string { out := make(map[string]string) - v := reflect.ValueOf(u) + v := reflect.ValueOf(p) if v.Kind() == reflect.Ptr { v = v.Elem() } @@ -185,9 +185,9 @@ func (u User) ToMap() map[string]string { return out } -func (u User) GetConfigFileName() string { +func (p Peer) GetConfigFileName() string { 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 } -func (d Device) GetDeviceConfig() wgtypes.Config { +func (d Device) GetConfig() wgtypes.Config { var privateKey *wgtypes.Key if d.PrivateKey != "" { pKey, _ := wgtypes.ParseKey(d.PrivateKey) @@ -247,7 +247,7 @@ func (d Device) GetDeviceConfig() wgtypes.Config { 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) if err != nil { return nil, err @@ -256,7 +256,7 @@ func (d Device) GetDeviceConfigFile(clients []User) ([]byte, error) { var tplBuff bytes.Buffer err = tpl.Execute(&tplBuff, struct { - Clients []User + Clients []Peer Server Device }{ Clients: clients, @@ -295,7 +295,7 @@ func NewUserManager(dbPath string, wg *wireguard.Manager, ldapUsers *ldap.Synchr return nil } - err = um.db.AutoMigrate(&User{}, &Device{}) + err = um.db.AutoMigrate(&Peer{}, &Device{}) if err != nil { logrus.Errorf("failed to migrate sqlite database: %v", err) return nil @@ -341,32 +341,32 @@ func (u *UserManager) InitFromCurrentInterface() error { return nil } -func (u *UserManager) validateOrCreateUserForPeer(peer wgtypes.Peer) error { - user := User{} - u.db.Where("public_key = ?", peer.PublicKey.String()).FirstOrInit(&user) +func (u *UserManager) validateOrCreateUserForPeer(wgPeer wgtypes.Peer) error { + peer := Peer{} + u.db.Where("public_key = ?", wgPeer.PublicKey.String()).FirstOrInit(&peer) - if user.PublicKey == "" { // user not found, create - user.UID = fmt.Sprintf("u%x", md5.Sum([]byte(peer.PublicKey.String()))) - user.PublicKey = peer.PublicKey.String() - user.PrivateKey = "" // UNKNOWN - if peer.PresharedKey != (wgtypes.Key{}) { - user.PresharedKey = peer.PresharedKey.String() + if peer.PublicKey == "" { // peer not found, create + peer.UID = fmt.Sprintf("u%x", md5.Sum([]byte(wgPeer.PublicKey.String()))) + peer.PublicKey = wgPeer.PublicKey.String() + peer.PrivateKey = "" // UNKNOWN + if wgPeer.PresharedKey != (wgtypes.Key{}) { + peer.PresharedKey = wgPeer.PresharedKey.String() } - user.Email = "autodetected@example.com" - user.Identifier = "Autodetected (" + user.PublicKey[0:8] + ")" - user.UpdatedAt = time.Now() - user.CreatedAt = time.Now() - user.AllowedIPs = make([]string, 0) // UNKNOWN - user.IPs = make([]string, len(peer.AllowedIPs)) - for i, ip := range peer.AllowedIPs { - user.IPs[i] = ip.String() + peer.Email = "autodetected@example.com" + peer.Identifier = "Autodetected (" + peer.PublicKey[0:8] + ")" + peer.UpdatedAt = time.Now() + peer.CreatedAt = time.Now() + peer.AllowedIPs = make([]string, 0) // UNKNOWN + peer.IPs = make([]string, len(wgPeer.AllowedIPs)) + for i, ip := range wgPeer.AllowedIPs { + peer.IPs[i] = ip.String() } - user.AllowedIPsStr = strings.Join(user.AllowedIPs, ", ") - user.IPsStr = strings.Join(user.IPs, ", ") + peer.AllowedIPsStr = strings.Join(peer.AllowedIPs, ", ") + peer.IPsStr = strings.Join(peer.IPs, ", ") - res := u.db.Create(&user) + res := u.db.Create(&peer) 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 } } @@ -401,11 +401,11 @@ func (u *UserManager) validateOrCreateDevice(dev wgtypes.Device, ipAddresses []s return nil } -func (u *UserManager) populateUserData(user *User) { +func (u *UserManager) populateUserData(user *Peer) { user.AllowedIPs = strings.Split(user.AllowedIPsStr, ", ") user.IPs = strings.Split(user.IPsStr, ", ") // Set config file - tmpCfg, _ := user.GetClientConfigFile(u.GetDevice()) + tmpCfg, _ := user.GetConfigFile(u.GetDevice()) user.Config = string(tmpCfg) // set data from WireGuard interface @@ -442,69 +442,69 @@ func (u *UserManager) populateDeviceData(device *Device) { device.Interface, _ = u.wg.GetDeviceInfo() } -func (u *UserManager) GetAllUsers() []User { - users := make([]User, 0) - u.db.Find(&users) +func (u *UserManager) GetAllUsers() []Peer { + peers := make([]Peer, 0) + u.db.Find(&peers) - for i := range users { - u.populateUserData(&users[i]) + for i := range peers { + u.populateUserData(&peers[i]) } - return users + return peers } -func (u *UserManager) GetActiveUsers() []User { - users := make([]User, 0) - u.db.Where("deactivated_at IS NULL").Find(&users) +func (u *UserManager) GetActiveUsers() []Peer { + peers := make([]Peer, 0) + u.db.Where("deactivated_at IS NULL").Find(&peers) - for i := range users { - u.populateUserData(&users[i]) + for i := range peers { + u.populateUserData(&peers[i]) } - return users + return peers } -func (u *UserManager) GetFilteredAndSortedUsers(sortKey, sortDirection, search string) []User { - users := make([]User, 0) - u.db.Find(&users) +func (u *UserManager) GetFilteredAndSortedUsers(sortKey, sortDirection, search string) []Peer { + peers := make([]Peer, 0) + u.db.Find(&peers) - filteredUsers := make([]User, 0, len(users)) - for i := range users { - u.populateUserData(&users[i]) + filteredPeers := make([]Peer, 0, len(peers)) + for i := range peers { + u.populateUserData(&peers[i]) if search == "" || - strings.Contains(users[i].Email, search) || - strings.Contains(users[i].Identifier, search) || - strings.Contains(users[i].PublicKey, search) { - filteredUsers = append(filteredUsers, users[i]) + strings.Contains(peers[i].Email, search) || + strings.Contains(peers[i].Identifier, search) || + strings.Contains(peers[i].PublicKey, search) { + 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 sortValueRight string switch sortKey { case "id": - sortValueLeft = filteredUsers[i].Identifier - sortValueRight = filteredUsers[j].Identifier + sortValueLeft = filteredPeers[i].Identifier + sortValueRight = filteredPeers[j].Identifier case "pubKey": - sortValueLeft = filteredUsers[i].PublicKey - sortValueRight = filteredUsers[j].PublicKey + sortValueLeft = filteredPeers[i].PublicKey + sortValueRight = filteredPeers[j].PublicKey case "mail": - sortValueLeft = filteredUsers[i].Email - sortValueRight = filteredUsers[j].Email + sortValueLeft = filteredPeers[i].Email + sortValueRight = filteredPeers[j].Email case "ip": - sortValueLeft = filteredUsers[i].IPsStr - sortValueRight = filteredUsers[j].IPsStr + sortValueLeft = filteredPeers[i].IPsStr + sortValueRight = filteredPeers[j].IPsStr case "handshake": - if filteredUsers[i].Peer == nil { + if filteredPeers[i].Peer == nil { return false - } else if filteredUsers[j].Peer == nil { + } else if filteredPeers[j].Peer == nil { return true } - sortValueLeft = filteredUsers[i].Peer.LastHandshakeTime.Format(time.RFC3339) - sortValueRight = filteredUsers[j].Peer.LastHandshakeTime.Format(time.RFC3339) + sortValueLeft = filteredPeers[i].Peer.LastHandshakeTime.Format(time.RFC3339) + sortValueRight = filteredPeers[j].Peer.LastHandshakeTime.Format(time.RFC3339) } 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 { - users := make([]User, 0) - u.db.Where("email = ?", email).Find(&users) +func (u *UserManager) GetSortedUsersForEmail(sortKey, sortDirection, email string) []Peer { + peers := make([]Peer, 0) + u.db.Where("email = ?", email).Find(&peers) - for i := range users { - u.populateUserData(&users[i]) + for i := range peers { + u.populateUserData(&peers[i]) } - sort.Slice(users, func(i, j int) bool { + sort.Slice(peers, func(i, j int) bool { var sortValueLeft string var sortValueRight string switch sortKey { case "id": - sortValueLeft = users[i].Identifier - sortValueRight = users[j].Identifier + sortValueLeft = peers[i].Identifier + sortValueRight = peers[j].Identifier case "pubKey": - sortValueLeft = users[i].PublicKey - sortValueRight = users[j].PublicKey + sortValueLeft = peers[i].PublicKey + sortValueRight = peers[j].PublicKey case "mail": - sortValueLeft = users[i].Email - sortValueRight = users[j].Email + sortValueLeft = peers[i].Email + sortValueRight = peers[j].Email case "ip": - sortValueLeft = users[i].IPsStr - sortValueRight = users[j].IPsStr + sortValueLeft = peers[i].IPsStr + sortValueRight = peers[j].IPsStr case "handshake": - if users[i].Peer == nil { + if peers[i].Peer == nil { return true - } else if users[j].Peer == nil { + } else if peers[j].Peer == nil { return false } - sortValueLeft = users[i].Peer.LastHandshakeTime.Format(time.RFC3339) - sortValueRight = users[j].Peer.LastHandshakeTime.Format(time.RFC3339) + sortValueLeft = peers[i].Peer.LastHandshakeTime.Format(time.RFC3339) + sortValueRight = peers[j].Peer.LastHandshakeTime.Format(time.RFC3339) } if sortDirection == "asc" { @@ -559,7 +559,7 @@ func (u *UserManager) GetSortedUsersForEmail(sortKey, sortDirection, email strin } }) - return users + return peers } 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? } -func (u *UserManager) GetUserByKey(publicKey string) User { - user := User{} - u.db.Where("public_key = ?", publicKey).FirstOrInit(&user) - u.populateUserData(&user) - return user +func (u *UserManager) GetUserByKey(publicKey string) Peer { + peer := Peer{} + u.db.Where("public_key = ?", publicKey).FirstOrInit(&peer) + u.populateUserData(&peer) + return peer } -func (u *UserManager) GetUsersByMail(mail string) []User { - var users []User - u.db.Where("email = ?", mail).Find(&users) - for i := range users { - u.populateUserData(&users[i]) +func (u *UserManager) GetUsersByMail(mail string) []Peer { + var peers []Peer + u.db.Where("email = ?", mail).Find(&peers) + for i := range peers { + u.populateUserData(&peers[i]) } - return users + return peers } -func (u *UserManager) CreateUser(user User) error { - user.UID = fmt.Sprintf("u%x", md5.Sum([]byte(user.PublicKey))) - user.UpdatedAt = time.Now() - user.CreatedAt = time.Now() - user.AllowedIPsStr = strings.Join(user.AllowedIPs, ", ") - user.IPsStr = strings.Join(user.IPs, ", ") +func (u *UserManager) CreateUser(peer Peer) error { + peer.UID = fmt.Sprintf("u%x", md5.Sum([]byte(peer.PublicKey))) + peer.UpdatedAt = time.Now() + peer.CreatedAt = time.Now() + peer.AllowedIPsStr = strings.Join(peer.AllowedIPs, ", ") + peer.IPsStr = strings.Join(peer.IPs, ", ") - res := u.db.Create(&user) + res := u.db.Create(&peer) 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 nil } -func (u *UserManager) UpdateUser(user User) error { - user.UpdatedAt = time.Now() - user.AllowedIPsStr = strings.Join(user.AllowedIPs, ", ") - user.IPsStr = strings.Join(user.IPs, ", ") +func (u *UserManager) UpdateUser(peer Peer) error { + peer.UpdatedAt = time.Now() + peer.AllowedIPsStr = strings.Join(peer.AllowedIPs, ", ") + peer.IPsStr = strings.Join(peer.IPs, ", ") - res := u.db.Save(&user) + res := u.db.Save(&peer) 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 nil } -func (u *UserManager) DeleteUser(user User) error { - res := u.db.Delete(&user) +func (u *UserManager) DeleteUser(peer Peer) error { + res := u.db.Delete(&peer) 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 }