//-----------------------------------------------------------------------
//
// Copyright (C) 2011 Microsoft Corporation
//
//-----------------------------------------------------------------------
namespace Microsoft.Samples.Management.OData.RoleBasedPlugins
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
///
/// Custom Session configuration implementation
///
public class SessionConfiguration : PSSessionConfiguration
{
///
/// Gets application private data
///
/// Sender information
/// Always returns null
public override PSPrimitiveDictionary GetApplicationPrivateData(PSSenderInfo senderInfo)
{
return null;
}
///
/// Gets custom initial session state
/// It relies on the RBAC system to give list of commands allowed for a user
/// and creates Initial Session state from that
///
/// Sender information
/// Custom initial Session state
public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo)
{
if (senderInfo == null)
{
throw new ArgumentNullException("senderInfo");
}
if (senderInfo.UserInfo == null)
{
throw new ArgumentException("senderInfo.UserInfo is null");
}
InitialSessionState initialSessionState = InitialSessionState.CreateDefault();
foreach (SessionStateCommandEntry command in initialSessionState.Commands)
{
command.Visibility = SessionStateEntryVisibility.Private;
}
List scripts = RbacSystem.Current.GetScripts(senderInfo.UserInfo);
foreach (string script in scripts)
{
initialSessionState.Commands.Add(new SessionStateScriptEntry(script));
}
List modules = RbacSystem.Current.GetModules(senderInfo.UserInfo);
if (modules.Count > 0)
{
initialSessionState.ImportPSModule(modules.ToArray());
}
// enable execution of scripts in this process
System.Environment.SetEnvironmentVariable("PSExecutionPolicyPreference", "unrestricted");
List cmdletsFromRbac = RbacSystem.Current.GetCmdlets(senderInfo.UserInfo);
// Add all commands from Rbac system to Initial Session State commands
foreach (string cmdlet in cmdletsFromRbac)
{
SessionStateCommandEntry cmdletFromRbac = initialSessionState.Commands.FirstOrDefault(item => string.Equals(item.Name, cmdlet, StringComparison.OrdinalIgnoreCase));
if (cmdletFromRbac == null)
{
throw new ArgumentException("Command not found in InitialSessionState " + cmdlet);
}
cmdletFromRbac.Visibility = SessionStateEntryVisibility.Public;
}
return initialSessionState;
}
}
}