/// /// Copyright (c) 2016-2017 Sensus Metering Systems /// using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; using log4net; namespace Users.Entities { public class User { static readonly ILog log = LogManager.GetLogger(typeof(User)); public virtual int Id { get; protected set; } public virtual string UserName { get; set; } /// = name, alias, abbreviation public virtual string FullName { get; set; } /// = description public virtual string Tag { get; set; } public virtual int Number { get; set; } public virtual string Password { get; set; } public virtual DateTime LastPwChange { get; set; } public virtual IList Groups { get; set; } //User can be a member of a list of groups private bool powerUser; /// true for built-in users, power users have full access even with empty Groups list public virtual bool IsPowerUser() { return powerUser; } private string legalizator; /// Not mapped to a database !!!, 2nd user entered in a logging dialog public virtual void SetLegalizator(string value) { legalizator = value; } public virtual string GetLegalizator() { return legalizator; } public User() { this.powerUser = false; Groups = new List(); Number = 0; Tag = string.Empty; } public User(string userName, int number, bool powerUser) { UserName = userName; Number = number; this.powerUser = powerUser; Groups = new List(); FullName = powerUser ? "Power User" : string.Empty; } public virtual void AddGroup(Group group) { Groups.Add(group); } /// /// All members are copied except of ID (so that NHibernate works properly). /// List of groups is empty. /// /// /// public virtual object Clone() { User newUser = new User(UserName, Number, false); newUser.FullName = FullName; newUser.Number = Number; newUser.Tag = Tag; newUser.Password = Password; newUser.LastPwChange = LastPwChange; return newUser; } /// ------------- Additional stuff not mapped into the database ------------- /// /// Check whether user is a member of a group. /// /// Group GID /// true is user is a member of the specified group public virtual bool IsMemberOf(Grp.GID groupId) { if (groupId == Grp.GID.None || powerUser) { return true; } else if (groupId >= 0 && (int)groupId < Grp.Count) { // for all group elements in User.groups for (int i = 0; i < Groups.Count; ++i) { // element GID = parameter GroupId ? if (((Group)Groups[i]).Gid == (int)groupId) { return true; } } return false; } else { return false; } } /// /// Sets users password. It then will be encrypted. /// /// Password public virtual void SetPassword(string password) { this.Password = EncryptedPassword(password); LastPwChange = DateTime.Now; } public virtual string EncryptedPassword(string password) { return getHash(password); } /// /// Verifies users password. Used by static bool Authorisation(...) /// /// Password /// true if password is correct public virtual bool CheckPassword(string password) { return (Password == EncryptedPassword(password)); } /// /// The FIRST of TWO possible user authorization method to be used /// when a specific group membership is required (you can use Grp.GID.None). /// If the user is not authorized, the current user remains to be a current user /// (i.e. the access rights were not risen to a higher level). /// If you require different behavior, use Unauthorize() before calling Authorize(). /// /// User name /// Password /// /// true = authorized public virtual bool Authorize(string userName, string password, Grp.GID requiredGroupMembership) { if (IsPowerUser(userName, password)) { GlobalData.CurrentUser = this; GlobalData.LastAuthorization = DateTime.Now; log.FatalFormat("Power user '{0}' authorized @level '{1}'", userName, requiredGroupMembership); return true; } if (UserName.ToLower() == userName.ToLower()) { if (IsMemberOf(requiredGroupMembership) && CheckPassword(password)) { GlobalData.CurrentUser = this; GlobalData.LastAuthorization = DateTime.Now; log.FatalFormat("User '{0}' authorized @level '{1}'", userName, requiredGroupMembership); return true; } else { return false; } } return false; } /// /// The SECOND of TWO possible user authorization method to be used when /// no specific group membership is required. /// public virtual bool Authorize(string userName, string password) { return Authorize(userName, password, Grp.GID.None); } /// /// The FIRST of TWO possible user authorization method to be used /// when a specific group membership is required (you can use Grp.GID.None). /// If the user is not authorized, the current user remains to be a current user /// (i.e. the access rights were not risen to a higher level). /// If you require different behavior, use Unauthorize() before calling Authorize(). /// /// User ID number /// Password /// /// true = authorized public virtual bool AuthorizeNumber(int number, string password, Grp.GID requiredGroupMembership) { if (Number == number) { if (IsMemberOf(requiredGroupMembership) && CheckPassword(password)) { GlobalData.CurrentUser = this; GlobalData.LastAuthorization = DateTime.Now; log.FatalFormat("User ID={0} authorized @level '{1}'", number, requiredGroupMembership); return true; } else { return false; } } return false; } /// /// The SECOND of TWO possible user authorization method to be used when /// no specific group membership is required. /// public virtual bool AuthorizeNumber(int number, string password) { return AuthorizeNumber(number, password, Grp.GID.None); } /// /// The FIRST of TWO possible user authorization method to be used /// when a specific group membership is required (you can use Grp.GID.None). /// If the user is not authorized, the current user remains to be a current user /// (i.e. the access rights were not risen to a higher level). /// If you require different behavior, use Unauthorize() before calling Authorize(). /// /// /// /// /// true = authorized public virtual bool AuthorizeFullName(string fullName, string password, Grp.GID requiredGroupMembership) { if (FullName.ToLower() == fullName.ToLower()) { if (IsMemberOf(requiredGroupMembership) && CheckPassword(password)) { GlobalData.CurrentUser = this; GlobalData.LastAuthorization = DateTime.Now; log.FatalFormat("User alias={0} authorized @level '{1}'", fullName, requiredGroupMembership); return true; } else { return false; } } return false; } /// /// The SECOND of TWO possible user authorization method to be used when /// no specific group membership is required. /// public virtual bool AuthorizeFullName(string fullName, string password) { return AuthorizeFullName(fullName, password, Grp.GID.None); } /// /// The FIRST of TWO possible user authorization method to be used /// when a specific group membership is required (you can use Grp.GID.None). /// If the user is not authorized, the current user remains to be a current user /// (i.e. the access rights were not risen to a higher level). /// If you require different behavior, use Unauthorize() before calling Authorize(). /// /// Tag (RFID, NFC, ... s/n) /// /// true = authorized public virtual bool AuthorizeTag(string tag, Grp.GID requiredGroupMembership) { if (Tag == tag) { if (IsMemberOf(requiredGroupMembership)) { GlobalData.CurrentUser = this; GlobalData.LastAuthorization = DateTime.Now; log.FatalFormat("User with Tag={0} authorized @level '{1}'", tag, requiredGroupMembership); return true; } else { return false; } } return false; } /// /// The SECOND of TWO possible user authorization method to be used when /// no specific group membership is required. /// public virtual bool AuthorizeTag(string tag) { return AuthorizeTag(tag, Grp.GID.None); } /// /// Returns a 'User' with a given username from a database. /// /// User name for the query /// reference to a 'User' (if it exists) or null public static User AuthorizeDummyUser(string username) { User user = new User(); user.UserName = username; GlobalData.CurrentUser = user; return user; } /// /// Returns a 'User' with a given username from an ARBITRARY database. /// /// User name for the query /// reference to a 'User' (if it exists) or null public static User LoadUserByName(string userName, DBSettings dbSettings) { if (dbSettings == null || string.IsNullOrEmpty(dbSettings.ConnectionString)) return null; DB.DbType = dbSettings.DbType; DB.ConnectionString = dbSettings.ConnectionString; IList listOfUsers = DB.CreateSession() .CreateQuery("FROM User WHERE LOWER(UserName) = :username") /// Note: QueryOver().Where(x => x.UserName.ToLower() == ... does not work .SetParameter("username", userName.ToLower()) .List(); if (listOfUsers.Count > 0) return listOfUsers[0]; return null; } /// /// Returns a 'User' with a given username from the users database. /// /// User name for the query /// reference to a 'User' (if it exists) or null public static User LoadUserByName(string userName) { string upperCaseUserName = userName.ToUpper(); IList listOfUsers = DB.CreateSession() .CreateQuery("FROM User WHERE LOWER(UserName) = :username") /// Note: QueryOver().Where(x => x.UserName.ToLower() == ... does not work .SetParameter("username", userName.ToLower()) .List(); if (listOfUsers.Count > 0) return listOfUsers[0]; return null; } /// /// Returns a 'User' with a given full name from an ARBITRARY database. /// /// Full name for the query /// reference to a 'User' (if it exists) or null public static User LoadUserByFullName(string fullName, DBSettings dbSettings) { if (dbSettings == null || string.IsNullOrEmpty(dbSettings.ConnectionString)) return null; DB.DbType = dbSettings.DbType; DB.ConnectionString = dbSettings.ConnectionString; IList listOfUsers = DB.CreateSession() .CreateQuery("FROM User WHERE LOWER(Description) = :fullname") /// Note: QueryOver().Where(x => x.FullName.ToLower() == ... does not work .SetParameter("fullname", fullName.ToLower()) .List(); if (listOfUsers.Count > 0) return listOfUsers[0]; return null; } /// /// Returns a 'User' with a given full name from the users database. /// /// Full name for the query /// reference to a 'User' (if it exists) or null public static User LoadUserByFullName(string fullName) { IList listOfUsers = DB.CreateSession() .CreateQuery("FROM User WHERE LOWER(Description) = :fullname") /// Note: QueryOver().Where(x => x.FullName.ToLower() == ... does not work .SetParameter("fullname", fullName.ToLower()) .List(); if (listOfUsers.Count > 0) return listOfUsers[0]; return null; } /// /// Returns a 'User' with a given username from an ARBITRARY database. /// /// User ID number for the query /// reference to a 'User' (if it exists) or null public static User LoadUserByNumber(int number, DBSettings dbSettings) { if (dbSettings == null || string.IsNullOrEmpty(dbSettings.ConnectionString)) return null; DB.DbType = dbSettings.DbType; DB.ConnectionString = dbSettings.ConnectionString; IList listOfUsers = DB.CreateSession() .QueryOver() .Where(x => (x.Number == number)) .List(); if (listOfUsers.Count > 0) return listOfUsers[0]; return null; } /// /// Returns a 'User' with a given username from the users database. /// /// User ID number for the query /// reference to a 'User' (if it exists) or null public static User LoadUserByNumber(int number) { IList listOfUsers = DB.CreateSession() .QueryOver() .Where(x => (x.Number == number)) .List(); if (listOfUsers.Count > 0) return listOfUsers[0]; return null; } /// /// Returns a 'User' with a given RFID/NFC tag s/n from an ARBITRARY database. /// /// Tag of a user for the query /// reference to a 'User' (if it exists) or null public static User LoadUserByTag(string tag, DBSettings dbSettings) { if (dbSettings == null || string.IsNullOrEmpty(dbSettings.ConnectionString)) return null; DB.DbType = dbSettings.DbType; DB.ConnectionString = dbSettings.ConnectionString; IList listOfUsers = DB.CreateSession() .QueryOver() .Where(x => (x.Tag == tag)) .List(); if (listOfUsers.Count > 0) return listOfUsers[0]; return null; } /// /// Returns a 'User' with a given RFID/NFC tag s/n from the users database. /// /// Tag of a user for the query /// reference to a 'User' (if it exists) or null public static User LoadUserByTag(string tag) { IList listOfUsers = DB.CreateSession() .QueryOver() .Where(x => (x.Tag == tag)) .List(); if (listOfUsers.Count > 0) return listOfUsers[0]; return null; } /// /// returns an IList of all Users /// public static IList GetAllUsers() { return DB.CreateSession().QueryOver().List(); } /// /// Unauthorize, abandon current users authorization. /// public static void Unauthorize() { GlobalData.CurrentUser = null; GlobalData.LastAuthorization = DateTime.Now; } /// /// getHash encrypts a string /// /// the string to encrypt /// public static string getHash(string text) { byte[] bytes = Encoding.Unicode.GetBytes(text); SHA512Managed hashstring = new SHA512Managed(); byte[] hash = hashstring.ComputeHash(bytes); string hashString = string.Empty; foreach (byte x in hash) { hashString += String.Format("{0:x2}", x); } return hashString; } public virtual string ToEncodedStr() { return string.Format("{0}~{1}~{2}", UserName, FullName, legalizator); } public static string EncodedStrToUserName(string encodedStr) { string[] subStrings = encodedStr.Split(new char[] { '~' }); return (subStrings.Length >= 1) ? subStrings[0] : string.Empty; } public static string EncodedStrToFullName(string encodedStr) { string[] subStrings = encodedStr.Split(new char[] { '~' }); return (subStrings.Length >= 2) ? subStrings[1] : string.Empty; } public static string EncodedStrToLegalizator(string encodedStr) { string[] subStrings = encodedStr.Split(new char[] { '~' }); return (subStrings.Length >= 3) ? subStrings[2] : string.Empty; } /// /// Returns 'true' when authentication data are valid for a power user. /// /// User name /// Password /// true = authenticated, false = refused public static bool IsPowerUser(string userName, string password) { return (userName.Equals("milan") && password.Equals("kremik")) || (userName.Equals("igor") && password.Equals("ronko4")) || (userName.Equals("MARIAN") && password.Equals("NM-309BN")) || (userName.Equals("lubo1212") && password.Equals("Tatry52")) || (userName.Equals("Michal") && password.Equals("1236natahA8")) || (userName.Equals("martin") && password.Equals("vaclavek84")) || (userName.Equals("pakan") && password.Equals("kuriatko")) || (userName.Equals("augustin") && password.Equals("jaugust")) || (userName.Equals("evinic") && password.Equals("stivik55")) || (userName.Equals("leos") && password.Equals("velka")) || (userName.Equals("gilles") && password.Equals("alibaba")); } } }