netmaker/logic/users.go

88 lines
2.4 KiB
Go
Raw Normal View History

2021-10-27 00:27:29 +08:00
package logic
import (
"encoding/json"
2023-04-04 02:36:38 +08:00
"sort"
2021-10-27 00:27:29 +08:00
"github.com/gravitl/netmaker/database"
2022-09-14 03:25:56 +08:00
"github.com/gravitl/netmaker/logger"
"github.com/gravitl/netmaker/logic/pro"
2021-10-27 00:27:29 +08:00
"github.com/gravitl/netmaker/models"
2022-09-14 03:25:56 +08:00
"github.com/gravitl/netmaker/models/promodels"
2021-10-27 00:27:29 +08:00
)
// GetUser - gets a user
func GetUser(username string) (*models.User, error) {
2021-10-27 00:27:29 +08:00
var user models.User
record, err := database.FetchRecord(database.USERS_TABLE_NAME, username)
if err != nil {
return &user, err
2021-10-27 00:27:29 +08:00
}
if err = json.Unmarshal([]byte(record), &user); err != nil {
return &models.User{}, err
2021-10-27 00:27:29 +08:00
}
return &user, err
2021-10-27 00:27:29 +08:00
}
2022-09-14 03:25:56 +08:00
// GetGroupUsers - gets users in a group
func GetGroupUsers(group string) ([]models.ReturnUser, error) {
var returnUsers []models.ReturnUser
users, err := GetUsers()
if err != nil {
return returnUsers, err
}
for _, user := range users {
if StringSliceContains(user.Groups, group) {
users = append(users, user)
}
}
return users, err
}
// == PRO ==
// InitializeNetUsers - intializes network users for all users/networks
func InitializeNetUsers(network *models.Network) error {
// == add all current users to network as network users ==
currentUsers, err := GetUsers()
if err != nil {
return err
}
for i := range currentUsers { // add all users to given network
newUser := promodels.NetworkUser{
ID: promodels.NetworkUserID(currentUsers[i].UserName),
Clients: []string{},
Nodes: []string{},
AccessLevel: pro.NO_ACCESS,
ClientLimit: 0,
NodeLimit: 0,
}
if pro.IsUserAllowed(network, currentUsers[i].UserName, currentUsers[i].Groups) {
newUser.AccessLevel = network.ProSettings.DefaultAccessLevel
newUser.ClientLimit = network.ProSettings.DefaultUserClientLimit
newUser.NodeLimit = network.ProSettings.DefaultUserNodeLimit
}
if err = pro.CreateNetworkUser(network, &newUser); err != nil {
logger.Log(0, "failed to add network user settings to user", string(newUser.ID), "on network", network.NetID)
}
}
return nil
}
2022-09-14 21:58:01 +08:00
// SetUserDefaults - sets the defaults of a user to avoid empty fields
func SetUserDefaults(user *models.User) {
if user.Groups == nil {
user.Groups = []string{pro.DEFAULT_ALLOWED_GROUPS}
}
}
2023-04-04 02:36:38 +08:00
// SortUsers - Sorts slice of Users by username
func SortUsers(unsortedUsers []models.ReturnUser) {
sort.Slice(unsortedUsers, func(i, j int) bool {
return unsortedUsers[i].UserName < unsortedUsers[j].UserName
})
}