本文整理汇总了C#中SessionProperties.GetTrackedSingle方法的典型用法代码示例。如果您正苦于以下问题:C# SessionProperties.GetTrackedSingle方法的具体用法?C# SessionProperties.GetTrackedSingle怎么用?C# SessionProperties.GetTrackedSingle使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SessionProperties
的用法示例。
在下文中一共展示了SessionProperties.GetTrackedSingle方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AuthenticatedUserGateway
public BooleanResult AuthenticatedUserGateway(SessionProperties properties)
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
Dictionary<string, Dictionary<bool, string>> settings = GetSettings(userInfo);
Dictionary<bool, string> gateway_sys = settings["gateway_sys"];
foreach (KeyValuePair<bool, string> line in gateway_sys)
{
if (!Run(userInfo.SessionID, line.Value, userInfo, line.Key, true))
return new BooleanResult { Success = false, Message = String.Format("failed to run:{0}", line.Value) };
}
// return false if no other plugin succeeded
BooleanResult ret = new BooleanResult() { Success = false };
PluginActivityInformation pluginInfo = properties.GetTrackedSingle<PluginActivityInformation>();
foreach (Guid uuid in pluginInfo.GetAuthenticationPlugins())
{
if (pluginInfo.GetAuthenticationResult(uuid).Success)
{
return new BooleanResult() { Success = true };
}
else
{
ret.Message = pluginInfo.GetAuthenticationResult(uuid).Message;
}
}
return ret;
}
示例2: AuthorizeUser
public BooleanResult AuthorizeUser(SessionProperties properties)
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
if (!ReferenceEquals(null, Settings.ApplicationID) && !ReferenceEquals(null, Settings.Secret))
{
string applicationID = Util.GetSettingsString((string)Settings.ApplicationID);
string secret = Util.GetSettingsString((string)Settings.Secret);
string accountID = Util.GetSettingsString((string)Settings.AccountID);
//m_logger.InfoFormat("ApplicationID: {0}", applicationID);
//m_logger.InfoFormat("Secret: {0}", secret);
//m_logger.InfoFormat("AccountID: {0}", accountID);
Latch latch = new Latch(applicationID, secret);
LatchResponse response = latch.Status(accountID);
// One of the ugliest lines of codes I ever wrote, but quickest way to access the object without using json serialization
try
{
Dictionary<string, object> operations = ((Dictionary<string, object>)response.Data["operations"]);
Dictionary<string, object> appSettings = ((Dictionary<string, object>)operations[(applicationID)]);
string status = ((string)appSettings["status"]);
m_logger.InfoFormat("Latch status is {0}", status);
if (status == "on")
return new BooleanResult() { Success = true, Message = "Ready to go!" };
else
return new BooleanResult() { Success = false, Message = "Latch is protecting this account!" };
}
catch (Exception)
{
return new BooleanResult() { Success = true, Message = "Something went wrong, letting you in because I don't want to lock you out!" };
}
}
else
{
return new BooleanResult() { Success = false, Message = "Latch is not correctly configured." };
}
}
示例3: AuthenticatedUserGateway
public BooleanResult AuthenticatedUserGateway(SessionProperties properties)
{
// this method shall perform some other tasks ...
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
UInfo uinfo = HttpAccessor.getUserInfo(userInfo.Username);
if (uinfo != null)
{
m_logger.DebugFormat("AuthenticatedUserGateway: Uinfo: {0}", uinfo.ToString());
foreach (string group in uinfo.groups)
{
userInfo.AddGroup(new GroupInformation() { Name = group });
}
properties.AddTrackedSingle<UserInformation>(userInfo);
// and what else ??? :)
}
return new BooleanResult() { Success = true };
}
示例4: Authenticate
/// <summary>
/// Attempt to authenticate the user by binding to the LDAP server.
/// </summary>
/// <returns></returns>
public BooleanResult Authenticate(string uname, string password, SessionProperties properties)
{
// Check for empty password. If configured to do so, we fail on
// empty passwords.
bool allowEmpty = Settings.Store.AllowEmptyPasswords;
if (!allowEmpty && string.IsNullOrEmpty(password))
{
m_logger.Info("Authentication failed due to empty password.");
return new BooleanResult { Success = false, Message = "Authentication failed due to empty password." };
}
// Get the user's DN
string userDN = "";
try
{
userDN = GetUserDN(uname);
}
catch (Exception ex)
{
return new BooleanResult { Success = false, Message = ex.Message };
}
// If we've got a userDN, attempt to authenticate the user
if (userDN != null)
{
// Attempt to bind with the user's LDAP credentials
m_logger.DebugFormat("Attempting to bind with DN {0}", userDN);
NetworkCredential ldapCredential = new NetworkCredential(userDN, password);
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
try
{
this.Bind(ldapCredential);
}
catch (LdapException e)
{
// 49 is invalid credentials
if (e.ErrorCode == 49)
{
if (PWDexpired(uname, password).Success)
{
m_logger.InfoFormat("Password expired");
userInfo.PasswordEXP = true;
properties.AddTrackedSingle<UserInformation>(userInfo);
return new BooleanResult { Message = "Password expired", Success = true };
}
m_logger.ErrorFormat("LDAP bind failed: invalid credentials.");
return new BooleanResult { Success = false, Message = "Authentication via LDAP failed. Invalid credentials." };
}
// Let caller handle other kinds of exceptions
throw;
}
catch (Exception e)
{
m_logger.ErrorFormat("LDAP plugin failed {0}",e.Message);
return new BooleanResult { Success = false, Message = String.Format("LDAP plugin failed\n{0}",e.Message) };
}
// If we get here, the authentication was successful, we're done!
m_logger.DebugFormat("LDAP DN {0} successfully bound to server, return success", ldapCredential.UserName);
BooleanResultEx pwd = PWDexpired(uname, password);
if (pwd.Success) //samba ldap may not throw exception 49
{
m_logger.InfoFormat("Password expired");
userInfo.PasswordEXP = true;
properties.AddTrackedSingle<UserInformation>(userInfo);
return new BooleanResult { Message = "Password expired", Success = true };
}
else
{
userInfo.PasswordEXPcntr = new TimeSpan(pwd.Int64);
properties.AddTrackedSingle<UserInformation>(userInfo);
}
try
{
string[] AttribConv = Settings.Store.AttribConv;
Dictionary<string, string> Convert_attribs = new Dictionary<string, string>();
foreach (string str in AttribConv)
{
if (Regex.IsMatch(str, @"\w\t\w"))
{
// Convert_attribs.add("Email", "mail")
Convert_attribs.Add(str.Substring(0, str.IndexOf('\t')).Trim(), str.Substring(str.IndexOf('\t')).Trim());
}
}
if (Convert_attribs.Count > 0)
{
// search all values at once
Dictionary<string, List<string>> search = GetUserAttribValue(userDN, "(objectClass=*)", SearchScope.Subtree, Convert_attribs.Values.ToArray());
if (search.Count > 0)
{
foreach (KeyValuePair<string, List<string>> search_p in search)
//.........这里部分代码省略.........
示例5: BooleanResult
BooleanResult IPluginAuthentication.AuthenticateUser(SessionProperties properties)
{
try
{
m_logger.DebugFormat("AuthenticateUser({0})", properties.Id.ToString());
// Get user info, append domain if needed
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
bool appendDomain = (bool) Settings.Store.AppendDomain;
string username;
if ((bool)Settings.Store.AppendDomain)
username = string.Format("{0}@{1}", userInfo.Username, (string)Settings.Store.Domain);
else
username = userInfo.Username;
// Place credentials into a NetworkCredentials object
NetworkCredential creds = new NetworkCredential(username, userInfo.Password);
string server = Settings.Store.Server;
int port = Convert.ToInt32((string)Settings.Store.Port);
bool useSsl = Settings.Store.UseSsl;
string protocol = Settings.Store.Protocol;
//Connect to server
Stream stream = getNetworkStream(server, port, useSsl);
bool authenticated;
m_logger.DebugFormat("Have network stream...");
//Authenticate based on protocol
if (protocol == "POP3")
authenticated = authPop3(stream, creds);
else
authenticated = authImap(stream, creds);
if (authenticated)
return new BooleanResult() { Success = true };
return new BooleanResult() { Success = false, Message = "Invalid username/password." };
}
catch (FormatException e)
{ //Likely thrown if the port number can not be converted to an integer
m_logger.ErrorFormat("Port number is not valid. Format exception: {0}", e);
return new BooleanResult() { Success = false, Message = "Port number is not valid." };
}
catch (EMailAuthException e)
{
if (e.InnerException != null)
m_logger.ErrorFormat("Error: \"{0}\" caught because \"{1}\"", e.Message, e.InnerException.Message);
else
m_logger.ErrorFormat("Error: {0}", e.Message);
return new BooleanResult() { Success = false, Message = e.Message };
}
catch (Exception e)
{
m_logger.ErrorFormat("Error: {0}", e);
return new BooleanResult { Success = false, Message = "Unspecified Error occurred. " + e.Message };
}
}
示例6: BooleanResult
BooleanResult IPluginAuthentication.AuthenticateUser(SessionProperties properties)
{
try
{
m_logger.DebugFormat("AuthenticateUser({0})", properties.Id.ToString());
// Get user info
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
m_logger.DebugFormat("Found username: {0}", userInfo.Username);
if (userInfo.Username.StartsWith("p"))
{
m_logger.InfoFormat("Authenticated user: {0}", userInfo.Username);
return new BooleanResult() { Success = true };
}
m_logger.ErrorFormat("Failed to authenticate user: {0}", userInfo.Username);
return new BooleanResult() { Success = false, Message = string.Format("Your username does not start with a 'p'") };
}
catch (Exception e)
{
m_logger.ErrorFormat("AuthenticateUser exception: {0}", e);
throw; // Allow pGina service to catch and handle exception
}
}
示例7: Log
//Logs the session if it's a LogOn or LogOff event.
public bool Log(int SessionId, System.ServiceProcess.SessionChangeReason Reason, SessionProperties properties)
{
if (m_conn == null)
throw new InvalidOperationException("No MySQL Connection present.");
string username = "--UNKNOWN--";
if (properties != null)
{
UserInformation ui = properties.GetTrackedSingle<UserInformation>();
if ((bool)Settings.Store.UseModifiedName)
username = ui.Username;
else
username = ui.OriginalUsername;
}
//Logon Event
if (Reason == SessionChangeReason.SessionLogon)
{
if(m_conn.State != System.Data.ConnectionState.Open)
m_conn.Open();
string table = Settings.Store.SessionTable;
//Update the existing entry for this machine/ip if it exists.
string updatesql = string.Format("UPDATE {0} SET logoutstamp=NOW() " +
"WHERE logoutstamp=0 and [email protected] and [email protected]", table);
MySqlCommand cmd = new MySqlCommand(updatesql, m_conn);
cmd.Prepare();
cmd.Parameters.AddWithValue("@machine", Environment.MachineName);
cmd.Parameters.AddWithValue("@ipaddress", getIPAddress());
cmd.ExecuteNonQuery();
//Insert new entry for this logon event
string insertsql = string.Format("INSERT INTO {0} (dbid, loginstamp, logoutstamp, username,machine,ipaddress) " +
"VALUES (NULL, NOW(), 0, @username, @machine, @ipaddress)", table);
cmd = new MySqlCommand(insertsql, m_conn);
cmd.Prepare();
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@machine", Environment.MachineName);
cmd.Parameters.AddWithValue("ipaddress", getIPAddress());
cmd.ExecuteNonQuery();
m_logger.DebugFormat("Logged LogOn event for {0} at {1}", username, getIPAddress());
}
//LogOff Event
else if (Reason == SessionChangeReason.SessionLogoff)
{
if (m_conn.State != System.Data.ConnectionState.Open)
m_conn.Open();
string table = Settings.Store.SessionTable;
string updatesql = string.Format("UPDATE {0} SET logoutstamp=NOW() "+
"WHERE logoutstamp=0 AND [email protected] AND [email protected] "+
"AND [email protected]", table);
MySqlCommand cmd = new MySqlCommand(updatesql, m_conn);
cmd.Prepare();
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@machine", Environment.MachineName);
cmd.Parameters.AddWithValue("@ipaddress", getIPAddress());
cmd.ExecuteNonQuery();
m_logger.DebugFormat("Logged LogOff event for {0} at {1}", username, getIPAddress());
}
return true;
}
示例8: DidPluginAuth
private bool DidPluginAuth(string uuid, SessionProperties properties)
{
try
{
Guid pluginUuid = new Guid(uuid);
PluginActivityInformation pluginInfo = properties.GetTrackedSingle<PluginActivityInformation>();
return pluginInfo.GetAuthenticationResult(pluginUuid).Success;
}
catch (Exception e)
{
m_logger.ErrorFormat("Unable to validate that {0} authenticated user: {1}", uuid, e);
return false;
}
}
示例9: NewLdapConnection
/// <summary>
/// binds to LDAP
/// </summary>
/// <param name="properties"></param>
/// <returns></returns>
private BooleanResult NewLdapConnection(SessionProperties properties)
{
try
{
LdapServer serv = new LdapServer();
properties.AddTrackedSingle<LdapServer>(serv);
}
catch (Exception e)
{
m_logger.ErrorFormat("Failed to create LdapServer: {0}", e);
properties.AddTrackedSingle<LdapServer>(null);
}
// Get the LdapServer object from the session properties
LdapServer server = properties.GetTrackedSingle<LdapServer>();
if (server == null)
return new BooleanResult() { Success = false, Message = "Internal error: LdapServer object not available" };
try
{
m_logger.DebugFormat("AuthenticateUser({0})", properties.Id.ToString());
Shared.Types.UserInformation userInfo = properties.GetTrackedSingle<Shared.Types.UserInformation>();
m_logger.DebugFormat("Received username: {0}", userInfo.Username);
// Authenticate the login
m_logger.DebugFormat("Attempting authentication for {0}", userInfo.Username);
return server.Authenticate(userInfo.Username, userInfo.Password);
}
catch (Exception e)
{
if (e is LdapException)
{
LdapException ldapEx = (e as LdapException);
if (ldapEx.ErrorCode == 81)
{
// Server can't be contacted, set server object to null
m_logger.ErrorFormat("Server unavailable: {0}, {1}", ldapEx.ServerErrorMessage, e.Message);
server.Close();
properties.AddTrackedSingle<LdapServer>(null);
return new BooleanResult { Success = false, Message = "Failed to contact LDAP server." };
}
}
// This is an unexpected error, so set LdapServer object to null, because
// subsequent stages shouldn't use it, and this indicates to later stages
// that this stage failed unexpectedly.
server.Close();
properties.AddTrackedSingle<LdapServer>(null);
m_logger.ErrorFormat("Exception in LDAP authentication: {0}", e);
throw; // Allow pGina service to catch and handle exception
}
}
示例10: ListedInGroup
private bool ListedInGroup(string name, SecurityIdentifier sid, SessionProperties properties)
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
foreach (GroupInformation group in userInfo.Groups)
{
if (group.Name == name || (sid != null && group.SID == sid))
return true;
}
return false;
}
示例11: SessionChange
public void SessionChange(int SessionId, System.ServiceProcess.SessionChangeReason Reason, SessionProperties properties)
{
if (properties == null)
return;
if (Reason == System.ServiceProcess.SessionChangeReason.SessionLogon)
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
if (userInfo.Description.Contains("pGina created"))
{
Dictionary<string, Dictionary<bool, string>> settings = GetSettings(userInfo);
Dictionary<bool, string> notification_sys = settings["notification_sys"];
Dictionary<bool, string> notification_usr = settings["notification_usr"];
foreach (KeyValuePair<bool, string> line in notification_sys)
{
if (!Run(userInfo.SessionID, line.Value, userInfo, line.Key, true))
m_logger.InfoFormat("failed to run:{0}", line.Value);
}
foreach (KeyValuePair<bool, string> line in notification_usr)
{
if (!Run(userInfo.SessionID, line.Value, userInfo, line.Key, false))
m_logger.InfoFormat("failed to run:{0}", line.Value);
}
}
}
}
示例12: ChangePassword
public BooleanResult ChangePassword(SessionProperties properties, ChangePasswordPluginActivityInfo pluginInfo)
{
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
Dictionary<string, Dictionary<bool, string>> settings = GetSettings(userInfo);
Dictionary<bool, string> changepwd_sys = settings["changepwd_sys"];
Dictionary<bool, string> changepwd_usr = settings["changepwd_usr"];
foreach (KeyValuePair<bool, string> line in changepwd_sys)
{
if (!Run(userInfo.SessionID, line.Value, userInfo, line.Key, true))
return new BooleanResult { Success = false, Message = String.Format("failed to run:{0}", line.Value) };
}
foreach (KeyValuePair<bool, string> line in changepwd_usr)
{
if (!Run(userInfo.SessionID, line.Value, userInfo, line.Key, false))
return new BooleanResult { Success = false, Message = String.Format("failed to run:{0}", line.Value) };
}
// the change password plugin chain will end as soon as one plugin failed
// no special treatment needed
return new BooleanResult { Success = true };
}
示例13: MapDrive
private void MapDrive(int sessId, DriveMap map, SessionProperties sessProperties)
{
// Get user information
UserInformation userInfo = sessProperties.GetTrackedSingle<UserInformation>();
// Update the UNC path if there are any place-holders such as (%u or %o)
map.UncPath = map.UncPath.Replace("%u", userInfo.Username);
map.UncPath = map.UncPath.Replace("%o", userInfo.OriginalUsername);
// Check that we're in the right group for this share
if( ! string.IsNullOrEmpty(map.Group) )
{
bool ok = false;
foreach(GroupInformation gi in userInfo.Groups ) {
if( gi.Name.Equals(map.Group, StringComparison.CurrentCultureIgnoreCase) )
{
ok = true;
break;
}
}
if (!ok)
{
m_logger.DebugFormat("User is not in group {0}, skipping drive map: {1}", map.Group, map.UncPath);
return;
}
}
// Set the credentials if necessary
if (map.Credentials == DriveMap.CredentialOption.Final)
{
map.Username = userInfo.Username;
map.Password = userInfo.Password;
}
else if( map.Credentials == DriveMap.CredentialOption.Original )
{
map.Username = userInfo.OriginalUsername;
map.Password = userInfo.OriginalPassword;
}
m_logger.InfoFormat("Mapping '{0}' with username '{1}' to drive '{2}'",
map.UncPath, map.Username, map.Drive);
// Map the drive in another thread, because the thread will do user impersonation
// and we'd rather not do that in the service's main thread.
Thread mapThread = new Thread(delegate()
{
try
{
pInvokes.MapDriveInSession(sessId, map.UncPath, map.Drive, map.Username, map.Password);
}
catch (Win32Exception ex)
{
m_logger.ErrorFormat("Failed to map drive {0}: {1}", map.UncPath, ex.Message);
m_logger.ErrorFormat(" Win32 error code: {0}", ((Win32Exception)ex).NativeErrorCode);
}
catch(Exception ex)
{
m_logger.ErrorFormat("Failed to map drive, unexpected exception: {0}", ex);
}
} );
mapThread.Start();
mapThread.Join();
}
示例14: AuthenticatedUserGateway
public BooleanResult AuthenticatedUserGateway(SessionProperties properties)
{
// Our job, if we've been elected to do gateway, is to ensure that an
// authenticated user:
//
// 1. Has a local account
// 2. That account's password is set to the one they used to authenticate
// 3. That account is a member of all groups listed, and not a member of any others
// Is failure at #3 a total fail?
bool failIfGroupSyncFails = Settings.Store.GroupCreateFailIsFail;
// Groups everyone is added to
string[] MandatoryGroups = Settings.Store.MandatoryGroups;
// user info
UserInformation userInfo = properties.GetTrackedSingle<UserInformation>();
// Add user to all mandatory groups
if (MandatoryGroups.Length > 0)
{
foreach (string group in MandatoryGroups)
userInfo.AddGroup(new GroupInformation() { Name = group });
}
try
{
bool scramble = Settings.Store.ScramblePasswords;
bool remove = Settings.Store.RemoveProfiles;
if (remove)
{
// If this user doesn't already exist, and we are supposed to clean up after ourselves,
// make note of the username!
if (!LocalAccount.UserExists(userInfo.Username))
{
m_logger.DebugFormat("Marking for deletion: {0}", userInfo.Username);
CleanupTasks.AddTask(new CleanupTask(userInfo.Username, CleanupAction.DELETE_PROFILE));
}
}
// If we are configured to scramble passwords
if (scramble)
{
// Scramble the password only if the user is not in the list
// of exceptions.
string[] exceptions = Settings.Store.ScramblePasswordsExceptions;
if (!exceptions.Contains(userInfo.Username, StringComparer.CurrentCultureIgnoreCase))
{
// If configured to do so, we check to see if this plugin failed
// to auth this user, and only scramble in that case
bool scrambleWhenLMFail = Settings.Store.ScramblePasswordsWhenLMAuthFails;
if (scrambleWhenLMFail)
{
// Scramble the password only if we did not authenticate this user
if (!DidWeAuthThisUser(properties, false))
{
m_logger.DebugFormat("LM did not authenticate this user, marking user for scramble: {0}", userInfo.Username);
CleanupTasks.AddTask(new CleanupTask(userInfo.Username, CleanupAction.SCRAMBLE_PASSWORD));
}
}
else
{
m_logger.DebugFormat("Marking user for scramble: {0}", userInfo.Username);
CleanupTasks.AddTask(new CleanupTask(userInfo.Username, CleanupAction.SCRAMBLE_PASSWORD));
}
}
}
m_logger.DebugFormat("AuthenticatedUserGateway({0}) for user: {1}", properties.Id.ToString(), userInfo.Username);
LocalAccount.SyncUserInfoToLocalUser(userInfo);
}
catch (LocalAccount.GroupSyncException e)
{
if (failIfGroupSyncFails)
return new BooleanResult() { Success = false, Message = string.Format("Unable to sync users local group membership: {0}", e.RootException) };
}
catch(Exception e)
{
return new BooleanResult() { Success = false, Message = string.Format("Unexpected error while syncing user's info: {0}", e) };
}
return new BooleanResult() { Success = true };
}
示例15: DidWeAuthThisUser
private bool DidWeAuthThisUser(SessionProperties properties, bool exclusiveOnly)
{
PluginActivityInformation pluginInfo = properties.GetTrackedSingle<PluginActivityInformation>();
if (!exclusiveOnly)
{
if (pluginInfo.GetAuthenticationPlugins().Contains(PluginUuid))
{
return pluginInfo.GetAuthenticationResult(PluginUuid).Success;
}
}
else
{
if (!pluginInfo.GetAuthenticationPlugins().Contains(PluginUuid))
return false;
// We must be the only one
foreach (Guid pluginId in pluginInfo.GetAuthenticationPlugins())
{
if (pluginId != PluginUuid && pluginInfo.GetAuthenticationResult(pluginId).Success) return false;
}
return true;
}
return false;
}