NET-1227: User Mgmt V2 (#3055)

* user mgmt models

* define user roles

* define models for new user mgmt and groups

* oauth debug log

* initialize user role after db conn

* print oauth token in debug log

* user roles CRUD apis

* user groups CRUD Apis

* additional api checks

* add additional scopes

* add additional scopes url

* add additional scopes url

* rm additional scopes url

* setup middlleware permission checks

* integrate permission check into middleware

* integrate permission check into middleware

* check for headers for subjects

* refactor user role models

* refactor user groups models

* add new user to pending user via RAC login

* untracked

* allow multiple groups for an user

* change json tag

* add debug headers

* refer network controls form roles, add debug headers

* refer network controls form roles, add debug headers

* replace auth checks, add network id to role model

* nodes handler

* migration funcs

* invoke sync users migration func

* add debug logs

* comment middleware

* fix get all nodes api

* add debug logs

* fix middleware error nil check

* add new func to get username from jwt

* fix jwt parsing

* abort on error

* allow multiple network roles

* allow multiple network roles

* add migration func

* return err if jwt parsing fails

* set global check to true when accessing user apis

* set netid for acls api calls

* set netid for acls api calls

* update role and groups routes

* add validation checks

* add invite flow apis and magic links

* add invited user via oauth signup automatically

* create invited user on oauth signup, with groups in the invite

* add group validation for user invite

* update create user handler with new role mgmt

* add validation checks

* create user invites tables

* add error logging for email invite

* fix invite singup url

* debug log

* get query params from url

* get query params from url

* add query escape

* debug log

* debug log

* fix user signup via invite api

* set admin field for backward compatbility

* use new role id for user apis

* deprecate use of old admin fields

* deprecate usage of old user fields

* add user role as service user if empty

* setup email sender

* delete invite after user singup

* add plaform user role

* redirect on invite verification link

* fix invite redirect

* temporary redirect

* fix invite redirect

* point invite link to frontend

* fix query params lookup

* add resend support, configure email interface types

* fix groups and user creation

* validate user groups, add check for metrics api in middleware

* add invite url to invite model

* migrate rac apis to new user mgmt

* handle network nodes

* add platform user to default role

* fix user role migration

* add default on rag creation and cleanup after deletion

* fix rac apis

* change to invite code param

* filter nodes and hosts based on user network access

* extend create user group req to accomodate users

* filter network based on user access

* format oauth error

* move user roles and groups

* fix get user v1 api

* move user mgmt func to pro

* add user auth type to user model

* fix roles init

* remove platform role from group object

* list only platform roles

* add network roles to invite req

* create default groups and roles

* fix middleware for global access

* create default role

* fix nodes filter with global network roles

* block selfupdate of groups and network roles

* delete netID if net roles are empty

* validate user roles nd groups on update

* set extclient permission scope when rag vpn access is set

* allow deletion of roles and groups

* replace _ with - in role naming convention

* fix failover middleware mgmt

* format oauth templates

* fetch route temaplate

* return err if user wrong login type

* check user groups on rac apis

* fix rac apis

* fix resp msg

* add validation checks for admin invite

* return oauth type

* format group err msg

* fix html tag

* clean up default groups

* create default rag role

* add UI name to roles

* remove default net group from user when deleted

* reorder migration funcs

* fix duplicacy of hosts

* check old field for migration

* from pro to ce make all secondary users admins

* from pro to ce make all secondary users admins

* revert: from pro to ce make all secondary users admins

* make sure downgrades work

* fix pending users approval

* fix duplicate hosts

* fix duplicate hosts entries

* fix cache reference issue

* feat: configure FRONTEND_URL during installation

* disable user vpn access when network roles are modified

* rm vpn acces when roles or groups are deleted

* add http to frontend url

* revert crypto version

* downgrade crytpo version

* add platform id check on user invites

---------

Co-authored-by: the_aceix <aceixsmartx@gmail.com>
This commit is contained in:
Abhishek K
2024-08-20 17:08:56 +05:30
committed by GitHub
parent fb40cd7d56
commit 2e8d95e80e
49 changed files with 4279 additions and 860 deletions

View File

@@ -49,8 +49,7 @@ func HasSuperAdmin() (bool, error) {
if err != nil {
continue
}
if user.IsSuperAdmin {
superUser = user
if user.PlatformRoleID == models.SuperAdminRole || user.IsSuperAdmin {
return true, nil
}
}
@@ -106,18 +105,58 @@ func GetUsers() ([]models.ReturnUser, error) {
return users, err
}
// IsOauthUser - returns
func IsOauthUser(user *models.User) error {
var currentValue, err = FetchPassValue("")
if err != nil {
return err
}
var bCryptErr = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(currentValue))
return bCryptErr
}
func FetchPassValue(newValue string) (string, error) {
type valueHolder struct {
Value string `json:"value" bson:"value"`
}
newValueHolder := valueHolder{}
var currentValue, err = FetchAuthSecret()
if err != nil {
return "", err
}
var unmarshErr = json.Unmarshal([]byte(currentValue), &newValueHolder)
if unmarshErr != nil {
return "", unmarshErr
}
var b64CurrentValue, b64Err = base64.StdEncoding.DecodeString(newValueHolder.Value)
if b64Err != nil {
logger.Log(0, "could not decode pass")
return "", nil
}
return string(b64CurrentValue), nil
}
// CreateUser - creates a user
func CreateUser(user *models.User) error {
// check if user exists
if _, err := GetUser(user.UserName); err == nil {
return errors.New("user exists")
}
SetUserDefaults(user)
if err := IsGroupsValid(user.UserGroups); err != nil {
return errors.New("invalid groups: " + err.Error())
}
if err := IsNetworkRolesValid(user.NetworkRoles); err != nil {
return errors.New("invalid network roles: " + err.Error())
}
var err = ValidateUser(user)
if err != nil {
logger.Log(0, "failed to validate user", err.Error())
return err
}
// encrypt that password so we never see it again
hash, err := bcrypt.GenerateFromPassword([]byte(user.Password), 5)
if err != nil {
@@ -126,15 +165,16 @@ func CreateUser(user *models.User) error {
}
// set password to encrypted password
user.Password = string(hash)
tokenString, _ := CreateUserJWT(user.UserName, user.IsSuperAdmin, user.IsAdmin)
if tokenString == "" {
logger.Log(0, "failed to generate token")
user.AuthType = models.BasicAuth
if IsOauthUser(user) == nil {
user.AuthType = models.OAuth
}
_, err = CreateUserJWT(user.UserName, user.PlatformRoleID)
if err != nil {
logger.Log(0, "failed to generate token", err.Error())
return err
}
SetUserDefaults(user)
// connect db
data, err := json.Marshal(user)
if err != nil {
@@ -159,8 +199,7 @@ func CreateSuperAdmin(u *models.User) error {
if hassuperadmin {
return errors.New("superadmin user already exists")
}
u.IsSuperAdmin = true
u.IsAdmin = false
u.PlatformRoleID = models.SuperAdminRole
return CreateUser(u)
}
@@ -189,7 +228,7 @@ func VerifyAuthRequest(authRequest models.UserAuthParams) (string, error) {
}
// Create a new JWT for the node
tokenString, err := CreateUserJWT(authRequest.UserName, result.IsSuperAdmin, result.IsAdmin)
tokenString, err := CreateUserJWT(authRequest.UserName, result.PlatformRoleID)
if err != nil {
slog.Error("error creating jwt", "error", err)
return "", err
@@ -250,8 +289,17 @@ func UpdateUser(userchange, user *models.User) (*models.User, error) {
user.Password = userchange.Password
}
user.IsAdmin = userchange.IsAdmin
if err := IsGroupsValid(userchange.UserGroups); err != nil {
return userchange, errors.New("invalid groups: " + err.Error())
}
if err := IsNetworkRolesValid(userchange.NetworkRoles); err != nil {
return userchange, errors.New("invalid network roles: " + err.Error())
}
// Reset Gw Access for service users
go UpdateUserGwAccess(*user, *userchange)
user.PlatformRoleID = userchange.PlatformRoleID
user.UserGroups = userchange.UserGroups
user.NetworkRoles = userchange.NetworkRoles
err := ValidateUser(user)
if err != nil {
return &models.User{}, err
@@ -274,12 +322,17 @@ func UpdateUser(userchange, user *models.User) (*models.User, error) {
// ValidateUser - validates a user model
func ValidateUser(user *models.User) error {
// check if role is valid
_, err := GetRole(user.PlatformRoleID)
if err != nil {
return err
}
v := validator.New()
_ = v.RegisterValidation("in_charset", func(fl validator.FieldLevel) bool {
isgood := user.NameInCharSet()
return isgood
})
err := v.Struct(user)
err = v.Struct(user)
if err != nil {
for _, e := range err.(validator.ValidationErrors) {