Click or drag to resize

Manage user operations

You can perform various user operations via API.

User operations
Add following namespaces in your code
C#
using Novalys.VisualGuard.Security;
using Novalys.VisualGuard.Security.Common;
using Novalys.VisualGuard.Security.CommonProfileAttribute;
using Novalys.VisualGuard.Security.Database;
using Novalys.VisualGuard.Security.Membership;
using Novalys.VisualGuard.Security.UserProfile;
using System;
using System.Collections.Generic;
Define VisualGuard runtime
C#
VGSecurityRuntime runtime = VGSecurityManager.Runtime;
Authentication of users.
  • Authenticate a VisualGuard user

    C#
      //authenticate visualGuard user
    var authenticationState = runtime.Authenticate("jsmith", "pwd", VGAuthenticationMode.VisualGuard);
  • Authenticate a Database user

    C#
      //authenticate database user
    authenticationState = runtime.Authenticate("sa", "pwd", VGAuthenticationMode.Database);
  • Authenticate current window account

    C#
      //authenticate current window account
    authenticationState = runtime.Authenticate(@"", "", VGAuthenticationMode.Windows);
  • Authenticate window account by credentials

    C#
      //authenticate window account by credential
    authenticationState = runtime.Authenticate(@"novalys\jsmith", "pwd", VGAuthenticationMode.WindowsByCredential);

These authentication methods returns Novalys.VisualGuard.SecurityVGAuthenticationState.

You can use this result in your code, as shown below to identity different cases and inform users accordingly.

C#
var authenticationStatus = authenticationState.Status;
if ((authenticationStatus & VGAuthenticationStatus.Failure) == VGAuthenticationStatus.Failure)
{
    #region Status is Failure along with other status

    if ((authenticationStatus & VGAuthenticationStatus.UserAccountNotYetAvailable) == VGAuthenticationStatus.UserAccountNotYetAvailable)
    {
        //Status is failure as user account is not yet available
    }
    else if ((authenticationStatus & VGAuthenticationStatus.UserAccountDisabled) == VGAuthenticationStatus.UserAccountDisabled)
    {
        //status is failure as user account is disabled
    }
    else if ((authenticationStatus & VGAuthenticationStatus.UserAccountExpired) == VGAuthenticationStatus.UserAccountExpired)
    {
        //status is failure as user account is expired
    }
    else if ((authenticationStatus & VGAuthenticationStatus.UserNotAuthorized) == VGAuthenticationStatus.UserNotAuthorized)
    {
        //status is failure as user account is not authorized for access
    }
    else if ((authenticationStatus & VGAuthenticationStatus.ProcessCanceled) == VGAuthenticationStatus.ProcessCanceled)
    {
        //Status - failure authentication Process is Canceled
    }
    else if ((authenticationStatus & VGAuthenticationStatus.UserAccountLocked) == VGAuthenticationStatus.UserAccountLocked)
    {
        //status is failure as user account is locked out
    }
    else if ((authenticationStatus & VGAuthenticationStatus.PasswordIsLocked) == VGAuthenticationStatus.PasswordIsLocked)
    {
        //status is failure as user account is locked out
    }
    else if ((authenticationStatus & VGAuthenticationStatus.NotApproved) == VGAuthenticationStatus.NotApproved)
    {
        //status is failure as user account is not approved
    }
    else if ((authenticationStatus & VGAuthenticationStatus.UserNotFoundInCustomStorage) == VGAuthenticationStatus.UserNotFoundInCustomStorage)
    {
        //status is failure as user account not found in custom storage
    }
    else if ((authenticationStatus & VGAuthenticationStatus.MustChangePasswordAtNextLogon) == VGAuthenticationStatus.MustChangePasswordAtNextLogon)
    {
        #region Case - When Password is expired or password doesn't pass validation, and grace logins are completed
        string message;
        if ((authenticationStatus & VGAuthenticationStatus.PasswordExpired) == VGAuthenticationStatus.PasswordExpired)
        {
            //status is failure. User must change his/her password as password is expired
        }
        else if ((authenticationStatus & VGAuthenticationStatus.PasswordDoesNotPassValidation) == VGAuthenticationStatus.PasswordDoesNotPassValidation)
        {
            //status is failure. User must change his/her password as password does not pass validations as per password policy
        }
        else
        {
            //status is failure. User must change his/her password.
        }
        #endregion
    }
    else
    {
        //write your code here to show authentication is failed
        //User is not authenticated, status is failure due to Invalid username or password


        if ((authenticationStatus & VGAuthenticationStatus.LastBadLogin) == VGAuthenticationStatus.LastBadLogin)
        {
            //Last bad login, next bad login will lock this user account
        }
        else if ((authenticationStatus & VGAuthenticationStatus.PasswordWillBeLocked) == VGAuthenticationStatus.PasswordWillBeLocked)
        {
            //user account is locked
        }
    }
    #endregion
}
else
{
    #region If Status is Success, but along With other status also(password expired or password not pass validation).

    if (authenticationStatus != VGAuthenticationStatus.Success)
    {
        if ((authenticationStatus & VGAuthenticationStatus.PasswordExpired) == VGAuthenticationStatus.PasswordExpired)
        {
            //status is success but password is expired.
        }
        else if ((authenticationStatus & VGAuthenticationStatus.PasswordDoesNotPassValidation) == VGAuthenticationStatus.PasswordDoesNotPassValidation)
        {
            //status is success but password does not pass validations of password policy. 
        }
    }
    else
    {
        //status is success -> Successful login -
        //write your code to procceed after successful authentication
    }

    #endregion
}
Create users
  • Create VisualGuard user

    C#
    VGMembershipCreateStatus createStatus;
    
     //Create VisualGuard user 
    VGMembershipUser jsmithUser = runtime.Membership.CreateUser("jsmith", "pwd", "jsmith@xyz.com", string.Empty, string.Empty, true, "user description", "John", "Smith", out createStatus);
    
    VGMembershipUser tempUser = runtime.Membership.CreateUser("mytestuser", "pwd");
  • Create Window account user

    C#
    var domains = runtime.Domains.GetAllActiveDirectoryDomains();
    var selectedDomain = domains[0];
    
    //provide the domain in which the window account need to be created
    //Create windows account
     VGMembershipUser windowUser = runtime.Membership.CreateActiveDirectoryUser(selectedDomain, @"novalys\firstuser", "pwd", null,out createStatus);
  • Create Database account user

    C#
    VGMembershipCreateStatus createStatus;
    
    //Create Database account
    VGMembershipUser dbUser= runtime.Membership.AddDBUser(new VGDBUser("sa"), out createStatus);

These methods returns Novalys.VisualGuard.Security.MembershipVGMembershipCreateStatus as out parameter. You can use this result in your application as shown below to identify different cases and inform users accordingly.

C#
if (createStatus == VGMembershipCreateStatus.Success)
  {
      //user creation is successful
      //write your code 
  }
  else
  {
      switch (createStatus)
      {
          case VGMembershipCreateStatus.DuplicateUserName:
              //User is not created as username already exists
              break;

          case VGMembershipCreateStatus.DuplicateEmail:
              //User is not created as user with same email address already exist
              break;

          case VGMembershipCreateStatus.TooManyUsers:
              //User is not created as user count has been reached to maximum as per license.
              break;

          case VGMembershipCreateStatus.InvalidComment:
              //User is not created as invalid comments
              break;

          case VGMembershipCreateStatus.InvalidEmail:
              //User is not created due to invalid emailaddress
              break;

          case VGMembershipCreateStatus.InvalidPassword:
              //User is not created due to invalid password
              break;

          case VGMembershipCreateStatus.InvalidQuestion:
              //User is not created due to invalid question                        
              break;

          case VGMembershipCreateStatus.InvalidAnswer:
              //User is not created as invalid answer
              break;


          case VGMembershipCreateStatus.InvalidUserName:
              //User is not created as username is invalid
              break;

          case VGMembershipCreateStatus.InvalidWindowsAccount:
              //User is not created due to invalid window account
              break;

          case VGMembershipCreateStatus.UserRejected:
              //User creation is rejected
              break;

          case VGMembershipCreateStatus.ProviderError:
              //User is not created as there is some issue in identity module
              break;

          default:
              break;

      }
  }
Change Password - User can change his/her password
C#
//changes the password of the user by old password
 runtime.Membership.ChangePassword("jsmith", "oldpwd", "newpwd");
Caution note Caution

This method is not supported for database user. (ex.SQL User, Oracle user)

Caution note Caution

Changing password of windows account user depends on the rights of the user on Active directory.

Force Password - Administrator can reset the password of any user
C#
var user = runtime.Membership.GetUser("jsmith");

//reset the password of the user
runtime.Membership.ForcePassword(user, "newpwd");
Caution note Caution

This method is not supported for database user (ex.SQL User, Oracle user)

Caution note Caution

Reset password of windows account user depends on the rights of the user on Active directory.

Update user details (like Firstname,Lastname, email, Description etc)
C#
var user = runtime.Membership.GetUser("jsmith");

//Edit user
//you can update the details of the user
user.FirstName = "Johny";
user.Title = "Mr";
user.Comment = "User from IT Team";
user.Email = "modified@xyz.com";

//Lock/Unlock user
user.IsLockedOut = true;

//Approve/Unapprove user
user.IsApproved = false;

//update user details
runtime.Membership.UpdateUser(user);
Caution note Caution

This method is not supported for database user (ex.SQL User, Oracle user)

Caution note Caution

Updating windows account user depends on the rights of the user on Active directory.

Delete users
C#
var tempUser = runtime.Membership.GetUser("tempUser");

//Delete user 
runtime.Membership.DeleteUser(tempUser);
Caution note Caution

This method is not supported for database user (ex.SQL User, Oracle user)

Caution note Caution

Deleting windows account user depends on the rights of the user on Active directory.

Get Users from storage
C#
//Get all users from the storage sorted by given columns            
int totalrecords;
var allusers= runtime.Membership.GetAllUsers(0, int.MaxValue, Security.Common.VGPrincipalSortByColumnType.LastModificationDate, Security.Common.VGSortOrderType.Descending, out totalrecords);
Find users by user information (ex. email, username, locked, approved, user attributes etc)
C#
//you can find users by various criterias.

//Find users by authentication mode
var findUsers = runtime.Membership.FindUsersByAuthenticationMode(VGAuthenticationMode.Windows);

//Find users by email
findUsers = runtime.Membership.FindUsersByEmail("jsmith@xyz.com");
findUsers = runtime.Membership.FindUsersByEmail("%@novalys.com");

//Find users by firstname, lastname
findUsers = runtime.Membership.FindUsersByFirstName("John");
findUsers = runtime.Membership.FindUsersByLastName("Smith");

//Find users by locked,unlocked, approved, unapproved  
findUsers = runtime.Membership.FindUsersByState(VGMemberShipUserState.IsLocked);
findUsers = runtime.Membership.FindUsersByState(VGMemberShipUserState.IsApprouved);

//Find users by name            
findUsers = runtime.Membership.FindUsersByName("jsmith");
Create user profile attributes

You can create user profile attributes with various supported datatypes.

  • Integer

  • Boolean

  • Double

  • DateTime

  • Image

  • BinaryData

  • DropDownItems

Few Examples:

C#
//you can create user profile attribute for various datatypes

//string
 VGProfileAttribute attrCompany= runtime.Profile.CreateProfileAttribute("CompanyName", VGProfileDataType.String, "Company Name", "This attribute represents company name of the user");

//DateTime
VGProfileAttribute attrBirthDate = runtime.Profile.CreateProfileAttribute("BirthDate", VGProfileDataType.DateTime, "BirthDate", "This attribute represents BirthDate of the user");

//Integer
VGProfileAttribute attrAge = runtime.Profile.CreateProfileAttribute("Age", VGProfileDataType.Integer, "Age", "This attribute represents an age of the user", 150, string.Empty, true, false, false, true, 0, "Primary Information", string.Empty, VGAttribute_InformationType.None);

//BinaryData
VGProfileAttribute attrBinaryData = runtime.Profile.CreateBinaryDataProfileAttribute("BinaryData", "BinaryData", "This attribute represents certificate binarydata", null);

//DropDownList
VGProfileAttribute attrDropDown = runtime.Profile.CreateDropDownProfileAttribute("Contry", "Contry", "This attribute represents country of the user", new List<string> { "France", "US", "India", "Canada" },"India");

//Image
VGProfileAttribute attrProfilePic = runtime.Profile.CreateProfileAttribute("ProfilePic", VGProfileDataType.Image, "ProfilePicture", "This attribute represents a profile picture of the user");
Find users by profile attributes
C#
//various prototypes are available to find users with attribute values.
//attributeId - is the Guid of the attribute which need to be searched

//few examples

//search users for which, this attribute's value is between 15 and 20.
findUsers = runtime.Membership.FindUsersByProfileAttributeValue(attributeId, 15, 20);

//search users for which, this attribute's value is 15 
findUsers = runtime.Membership.FindUsersByProfileAttributeValue(attributeId, 15);

//search users for which, this attribute's value is today's Date 
findUsers = runtime.Membership.FindUsersByProfileAttributeValue(attributeId, DateTime.Now.Date);

//search users for which, this attribute's value is true
findUsers = runtime.Membership.FindUsersByProfileAttributeValue(attributeId, true);
Get user profile values.
C#
var user = runtime.Membership.GetUser("jsmith");

string companyName = user.GetValue<string>("CompanyName");
int age = user.GetValue<int>("Age");
DateTime dtBirthDae = user.GetValue<DateTime>("BirthDate");
Save/Update user profile values.
C#
var user = runtime.Membership.GetUser("jsmith");

user.SetValue<string>("CompanyName", "Novalys");
user.SetValue<int>("Age", 35);
user.SetValue<DateTime>("BirthDate", DateTime.Now.Date);

runtime.Membership.UpdateUser(user);
Scoping of principal
C#
 //Once user is authenticated in runtime, you can access current principal using runtime.Principal.
var currentPrincipal = runtime.Principal;

//list of roles granted to the user for current application
var grantedRoles = currentPrincipal.Roles;

//list of permissions granted to the user for current application
var permissions = currentPrincipal.GetAllCurrentPermissions();

//list of selectable contextual groups
var contextualGroups = currentPrincipal.ContextualGroups;

//list of groups which are directly assigned to users
var grantedGroups = currentPrincipal.GrantedGroups

//list of groups which are directly assigned and also their descendant groups
var allgroups = currentPrincipal.Groups

//gets a list of profile values for current principal
var profileValues = currentPrincipal.ProfileValues 

//change profile values for principal
//where attributeId is propertyId of attribute
currentPrincipal.ProfileValues.SetValue(attributeId, 15);
currentPrincipal.ProfileValues.SetValue(attributeId, "HelloWorld");

//save/update profilevalues for current principal
currentPrincipal.ProfileValues.Save();