Docly

How to manager users ?

Estimated reading: 8 minutes 173 views

User Operations


Initialize the Visual-Guard Runtime

Add following namespaces in your code

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

VGSecurityRuntime runtime = VGSecurityManager.Runtime;

Authentication of users

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

     

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

     

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

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 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 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 VGMembershipCreateStatus createStatus; //Create Database account VGMembershipUser dbUser= runtime.Membership.AddDBUser(new VGDBUser(“sa”), out createStatus);
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

//changes the password of the user by old password
runtime.Membership.ChangePassword("jsmith", "oldpwd", "newpwd");
Caution note
Caution note


Force Password – Administrator can reset the password of any user

var user = runtime.Membership.GetUser("jsmith");

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


Update user details (like Firstname,Lastname, email, Description etc)

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 note


Delete users

var tempUser = runtime.Membership.GetUser("tempUser");

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


Get Users from storage

//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)

//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

  • Integer
  • Boolean
  • Double
  • DateTime
  • Image
  • BinaryData
  • DropDownItems
//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

//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.

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.

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

//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();

Leave a Comment

Share this Doc
CONTENTS