tbf/Users/CurrentUser.cs

112 lines
3.3 KiB
C#

///
/// Copyright (c) 2016-2022 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Common;
using Users.Entities;
namespace Users
{
class UserAndForm
{
public readonly User User;
public readonly Form Form;
public UserAndForm(User user, Form form)
{
User = user;
Form = form;
}
}
public class CurrentUser
{
public static DBSettings RemoteUsersDB = null;
public static DBSettings LocalUsersDB = null;
static readonly Stack<UserAndForm> userStack = new Stack<UserAndForm>();
public static AuthorizedAs AuthorizedAs;
public static DateTime LastAuthorization = DateTime.Now;
public static int MinPasswdLength = 0;
public static int PasswdExpirationPeriodDays = 0;
/// <summary>
/// Push a new user into the stack of users and form references.
/// Prevent double user stack entry for the same Windows form.
/// </summary>
/// <param name="newUser">New user</param>
/// <param name="currentForm">Reference to the current form</param>
public static void Change(User newUser, Form currentForm)
{
if (userStack.Count > 0 && userStack.Peek().Form == currentForm)
{
userStack.Pop();
}
userStack.Push(new UserAndForm(newUser, currentForm));
}
/// <summary>
/// Restore an original user from the stack of users - remove user at the top of the stack.
/// Prevent restoring when there is no entry for the form currently being closed.
/// </summary>
/// <param name="formBeingClosed">Reference to the form currently being closed</param>
/// <returns>true = current user was restored, false = no current user change</returns>
public static bool Restore(Form formBeingClosed)
{
if (userStack.Count > 0 && userStack.Peek().Form == formBeingClosed)
{
userStack.Pop();
return true;
}
return false;
}
/// <summary>
/// Return the user currenty at the top of the stack of users.
/// </summary>
public static User User()
{
return (userStack.Count > 0) ? userStack.Peek().User : null; /// TODO: Return default user when stack is empty
}
/// <summary>
/// Return the current user name or an empty string
/// </summary>
public static string UserName()
{
return (User() != null) ? User().UserName : string.Empty;
}
/// <summary>
/// Return the current user number or 0
/// </summary>
public static int Number()
{
return (User() != null) ? User().Number : 0;
}
public static bool IsPowerUser()
{
return (User() != null) ? User().IsPowerUser() : false;
}
public static bool IsMemberOf(GID groupId)
{
return (User() != null) ? User().IsMemberOf(groupId) : false;
}
public static bool IsMemberOf(GID[] groupIds)
{
return (User() != null) ? User().IsMemberOf(groupIds) : (groupIds == null);
}
}
}