/// /// Copyright (c) 2017-2018 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using NHibernate; using Users.Entities; using Users.Resources; using GemCard; using System.Drawing; namespace Users.Forms { public partial class EditSelectedUser : Form { NHibernate.ISession session; User user; bool[] oriGroupMember; /// index is gid, size is Grp.Count /// Smart card support, card S/N is used as user.Tag GemCard.CardNative card; string[] cardReaders; string smartCardReader; public EditSelectedUser() { InitializeComponent(); this.toolTip1.SetToolTip(this.txtName, string.Format(Strings.max_0_alphanum_chars, 20)); oriGroupMember = new bool[Grp.Count]; okBtn.Enabled = false; } public EditSelectedUser(NHibernate.ISession session, User user) : this() { this.session = session; this.user = user; } private void EditSelectedUser_Load(object sender, EventArgs e) { Localize(); txtName.Text = user.UserName; txtCode.Text = user.Number.ToString(); txtTag.Text = string.IsNullOrEmpty(user.Tag) ? string.Empty : user.Tag; txtDescription.Text = user.FullName; txtPassword.Text = string.Empty; txtRepeatPassword.Text = string.Empty; ShowGroups(); smartCardReader = null; /// null = No smart card reader detected #if TURA_IPERL || TURA_SPECIAL try { card = new CardNative(); /// Find NFC smart card reader cardReaders = card.ListReaders(); foreach (var crd in cardReaders) { if (crd.Contains("NFC")) { smartCardReader = crd; /// NFC smart card reader detected break; } } if (!string.IsNullOrEmpty(smartCardReader)) { /// Reader found, initialize NFC smart card reader card.OnCardInserted += delegate(object sndr, CardInsertedEventArgs args) { if (InvokeRequired) { Invoke(new EventHandler(OnCardInserted), sndr, args); } else OnCardInserted(sndr, args); }; card.OnCardRemoved += delegate(object sndr, CardRemovedEventArgs args) { if (InvokeRequired) { Invoke(new EventHandler(OnCardRemoved), sndr, args); } else OnCardRemoved(sndr, args); }; card.StartCardEvents(smartCardReader); Text += " (NFC)"; txtTag.Enabled = true; } } catch (Exception) { smartCardReader = null; } #endif } void Localize() { Text = Strings.Edit_User; nameLabel.Text = Strings.Name; passwordLabel.Text = Strings.Password; repeatPasswordLabel.Text = Strings.Repeat_password; codeLabel.Text = Strings.User_code; tagLabel.Text = Strings.Tag; descriptionLabel.Text = Strings.DescriptionColHdr; groupsLabel.Text = Strings.Groups; okBtn.Text = Strings.OkBtnText; cancelBtn.Text = Strings.CancelBtnText; } public void ShowGroups() { checkedListBoxGroups.Items.Clear(); for (int i= 0; i < Grp.Count; i++) { Group group = Grp.FromId((Grp.GID)i); bool boolIsMember = oriGroupMember[i] = user.IsMemberOf((Grp.GID)group.Gid); checkedListBoxGroups.Items.Add(Grp.Gid2Str(i)); checkedListBoxGroups.SetItemCheckState(i, boolIsMember ? CheckState.Checked : CheckState.Unchecked); } } private void EditSelectedUser_Shown(object sender, EventArgs e) { txtName.Focus(); } public bool Save() { // todo: check if this name is given to another user if (IsUserNameAlreadyTaken(txtName.Text)) { MessageBox.Show(Strings.Username_taken); return false; } if (IsTagAlreadyTaken(txtTag.Text)) { MessageBox.Show(Strings.Tag_taken); return false; } ITransaction transaction = session.BeginTransaction(); try { Cursor.Current = Cursors.WaitCursor; user.UserName = txtName.Text; user.FullName = txtDescription.Text; user.Number = int.Parse(txtCode.Text); user.Tag = string.IsNullOrEmpty(txtTag.Text) ? null : txtTag.Text; if (txtPassword.Text != string.Empty) { user.SetPassword(txtPassword.Text); } /// Groups IList groups = user.Groups; /// = session.QueryOver().Where(x => (x.User.Id == user.Id)).List(); for (int gid = 0; gid < Grp.Count; gid++) { bool newIsMember = checkedListBoxGroups.GetItemChecked(gid); if (!newIsMember && oriGroupMember[gid]) { for (int j = 0; j < user.Groups.Count; j++) { if (user.Groups[j].Gid == gid) { session.Delete(user.Groups[j]); user.Groups.RemoveAt(j); break; } } } else if (newIsMember && !oriGroupMember[gid]) { Group newGroup = new Group(gid, ((Grp.GID)gid).ToString()); user.Groups.Add(newGroup); } } session.SaveOrUpdate(user); transaction.Commit(); session.Flush(); Cursor.Current = Cursors.Default; return true; } catch (Exception exc) { transaction.Rollback(); MessageBox.Show(string.Format("{0}{1}{2}", Strings.Save_or_update_user_failed, Environment.NewLine, exc.Message), Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); Cursor.Current = Cursors.Default; return false; } } /// /// returns true if the username allready exists for another user /// private bool IsUserNameAlreadyTaken(string userName) { // Have a look into all other users IList ListOfUsers = User.GetAllUsers(); foreach (var person in ListOfUsers) { if (person.Id != user.Id) { /// Other user then the current one if (person.UserName.ToLower() == userName.ToLower()) { return true; // Name is equal = already taken } } } return false; } /// /// returns true if the username allready exists for another user /// private bool IsTagAlreadyTaken(string tag) { if (string.IsNullOrEmpty(tag)) return false; /// No tag // Have a look into all other users IList ListOfUsers = User.GetAllUsers(); foreach (var person in ListOfUsers) { if (person.Id != user.Id) { // Other user then the current one if (person.Tag == tag) { return true; // Tag is equal = already taken } } } return false; } private void okBtn_Click(object sender, EventArgs e) { if (Save()) { DialogResult = DialogResult.OK; this.Close(); } } private void cancelBtn_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; this.Close(); } private void txtName_Validated(object sender, EventArgs e) { UpdateOKButton(); } private void txtName_KeyPress(object sender, KeyPressEventArgs e) { UpdateOKButton(); } private void txtName_TextChanged(object sender, EventArgs e) { UpdateOKButton(); } private void txtPassword_TextChanged(object sender, EventArgs e) { UpdateOKButton(); } private void txtRepeatPassword_TextChanged(object sender, EventArgs e) { UpdateOKButton(); } private void txtDescription_TextChanged(object sender, EventArgs e) { UpdateOKButton(); } private void txtDescription_KeyPress(object sender, KeyPressEventArgs e) { UpdateOKButton(); } private void checkedListBoxGroups_Click(object sender, EventArgs e) { UpdateOKButton(); } private void txtCode_TextChanged(object sender, EventArgs e) { UpdateOKButton(); } private void UpdateOKButton() { int userCode; okBtn.Enabled = (txtName.Text != string.Empty) && int.TryParse(txtCode.Text, out userCode) && (txtPassword.Text == txtRepeatPassword.Text); } void OnCardInserted(object sender, CardInsertedEventArgs args) { BackColor = Color.Green; card.Connect(smartCardReader, SHARE.Shared, PROTOCOL.T0orT1); /// Read the serial number of the card APDUResponse response = card.Transmit(new APDUCommand(0xFF, 0xCA, 0x00, 0x00, null, 7)); txtTag.Text = response.ToString(); card.Disconnect(DISCONNECT.Leave); } void OnCardRemoved(object sender, CardRemovedEventArgs args) { BackColor = SystemColors.Control; } private void EditSelectedUser_FormClosing(object sender, FormClosingEventArgs e) { if (!string.IsNullOrEmpty(smartCardReader)) { card.StopCardEvents(); } } } }