Files
BeWoPlaner/BeWo/LoginControl.xaml.cs
2025-09-17 11:02:35 +02:00

1542 lines
60 KiB
C#

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Deployment.Application;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Navigation;
using System.Windows.Threading;
using BS.Shared;
using BS.Shared.Extensions;
using BeWo.Core;
using BeWo.Security;
using BeWo.ServiceProxy;
using BeWo.View;
using BeWo.View.Detail;
using BS.Shared.Translation;
using Path = System.IO.Path;
using System.Linq;
namespace BeWo
{
/// <summary>
/// Interaktionslogik für LoginControl.xaml
/// </summary>
public partial class LoginControl : UserControl, INotifyPropertyChanged
{
private readonly Stack<Control> _ModalPopUpControls = new Stack<Control>();
private String GETSERVER_URL = "https://support.bewoplaner.de/api/getserver.php?k={0}&t=0";
private String GETSTATUSMESSAGE_URL = "https://support.bewoplaner.de/api/getstate.php?k={0}&t=0&v={1}";
private String GETNETMESSAGE_URL = "https://support.bewoplaner.de/api/getxmlstate.php?k={0}&t=0";
private Control _CurrentModalPopUp;
private Grid _ModalPopUpBackGround;
private readonly string _ProfilesFilePath;
private readonly string _ConfigFilePath;
public event EventHandler LoginSuccessful;
private bool isNet45OrNewer = false;
//proxy anmeldedaten
public string proxyname;
public string proxyUsername;
public string proxypasswd;
private List<BeWoProfile> _ProfileList;
public List<BeWoProfile> ProfileList
{
get { return _ProfileList; }
set { _ProfileList = value; }
}
public LoginControl()
{
InitializeComponent();
DateTime dt = new DateTime(2017, 1, 1);
if (DateTime.Now > dt)
dt = DateTime.Now;
txtCopyright.Text = String.Format("Copyright {0:yyyy} | ownSoft GmbH", dt);
var checkPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\profiles.txt";
if (File.Exists(checkPath))
{
//Nimm lokalen Profilpfad wenn er existiert. Wird z.B. bei Kunden mit Citrix Server genutzt, die keine Clickonce Installation vornehmen
_ProfilesFilePath = checkPath;
}
else
{
_ProfilesFilePath = Path.Combine(BeWoApp.GetAndCreateUserAppDataPath(), "profiles.txt");
}
_ConfigFilePath = Path.Combine(BeWoApp.GetAndCreateUserAppDataPath(), "bwp.config");
ProfileList = new List<BeWoProfile>();
BeWoProfile selectedProfile = null;
HeightFrom = gridLogin.Height;
HeightTo = gridLogin.Height + 64;
LineYCoordFrom = linkLine.Y1;
LineYCoordTo = linkLine.Y1 + 64;
DataContext = this;
ReadProxyName();
try
{
ReadProfileList();
#if DEBUG
var uri = new Uri("https://localhost/Host/?k=demo&s=localhost/service");
var paramDic = BeWoUtils.ParseQuery(uri.Query);
string v1, v2;
paramDic.TryGetValue("k", out v1);
paramDic.TryGetValue("s", out v2);
BeWoApp.Tenant = v1;
BeWoApp.ServerName = v2;
if(!ProfileList.Any(x => x.Tenant == v1))
{
if (ProfileList.Count > 0)
ProfileList.Insert(0, new BeWoProfile(v1, v2, v1));
else
ProfileList.Add(new BeWoProfile(v1, v2, v1));
SaveProfileListToFile();
}
#else
if (ApplicationDeployment.IsNetworkDeployed && ApplicationDeployment.CurrentDeployment.ActivationUri != null)
{
//Start über IE
//MessageBox.Show(String.Format("Start über IE.\nActivationUri: {0}\nUpdateLocation: {1}", ApplicationDeployment.CurrentDeployment.ActivationUri, ApplicationDeployment.CurrentDeployment.UpdateLocation));
BeWoProfile p = GenerateProfileFromUri(ApplicationDeployment.CurrentDeployment.ActivationUri);
if (!String.IsNullOrEmpty(p.Tenant) && !String.IsNullOrEmpty(p.Server))
{
BeWoApp.Tenant = p.Tenant;
if (ProfileList.Count > 0)
{
selectedProfile = ProfileList.Find(ip => ip.Tenant == p.Tenant);
}
if (selectedProfile == null)
{
if (ProfileList.Count > 0)
ProfileList.Insert(0, p);
else
ProfileList.Add(p);
}
else
{
ProfileList.Remove(selectedProfile);
selectedProfile.Server = p.Server;
ProfileList.Insert(0, selectedProfile);
}
SaveProfileListToFile();
}
else if (!String.IsNullOrEmpty(p.Tenant) && p.Tenant.ToLower() == "demo")
{
p.Server = "1";
ProfileList.Add(p);
}
}
else
{
//MessageBox.Show(String.Format("Start über Firefox oder über installiertes Desktop Icon.\nActivationUri: {0}\nUpdateLocation: {1}", ApplicationDeployment.CurrentDeployment.ActivationUri, ApplicationDeployment.CurrentDeployment.UpdateLocation));
}
#endif
}
catch (Exception ex)
{
}
//string ipaddress = "";
// --------------
if (ProfileList.Count == 0 || String.IsNullOrEmpty(ProfileList[0].Tenant))
ShowEnterTenantDialog();
//if (ProfileList.Count == 0)
//ProfileList.Add(new BeWoProfile("Ungültiges Profil", "Bitte geben Sie hier einen gültigen Server an. Z.B. app1", "Kundennummer"));
BeWoProfile firstProfile = null;
if (ProfileList.Count > 0)
firstProfile = ProfileList[0];
ProfileList.Sort((a, b) => a.Name.CompareTo(b.Name));
profileSelectionComboBox.ItemsSource = ProfileList;
if (ProfileList.Count > 0)
{
#if DEBUG
//selectedProfile = ReadSelectedProfile();
if (DebugConfig.CurrentConfig is DebugConfig current && !string.IsNullOrWhiteSpace(current.DefaultProfilename))
{
selectedProfile = ProfileList.FirstOrDefault(x => x.Name == current.DefaultProfilename);
}
#else
selectedProfile = ReadSelectedProfile();
#endif
if (selectedProfile == null || !ProfileList.Contains(selectedProfile))
{
//selectedProfile = profileSelectionComboBox.SelectedItem as BeWoProfile;
selectedProfile = firstProfile;
}
}
//if (profileSelectionComboBox.SelectedItem == null)
profileSelectionComboBox.SelectedItem = selectedProfile;
TextBox_Username.Focus();
if (selectedProfile != null && selectedProfile.Tenant == "demo")
{
TextBox_Username.Text = "demo";
PasswordBox_Password.Password = "demo";
}
//this.lblTenant.Content = BeWoApp.Tenant;
lblVersion.Content = BeWoApp.Version;
Loaded += LoginControl_Loaded;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
PinCertificate();
//linkLine.Margin = new Thickness(linkLine.Margin.Left, linkLine.Margin.Top + 25, linkLine.Margin.Right, linkLine.Margin.Bottom);
//gridLogin.Height += 25;
}
private void PinCertificate()
{
ServicePointManager.ServerCertificateValidationCallback = PinPublicKey;
}
//!!!!Wenn hier neue Keys hinzugefügt werden, muss das auch in der Klasse ChatController.HauptKlassen.Chat und im DatabaseTerminator gemacht werden!!
private static String PUB_KEY_X3 = "9CD30CF05AE52E47B7725D3783B3686330EAD735261925E1BDBE35F170922FB7B84B4105ABA99E350858ECB12AC468870BA3E375E4E6F3A76271BA7981601FD7919A9FF3D0786771C8690E9591CFFEE699E9603C48CC7ECA4D7712249D471B5AEBB9EC1E37001C9CAC7BA705EACE4AEBBD41E53698B9CBFD6D3C9668DF232A42900C867467C87FA59AB8526114133F65E98287CBDBFA0E56F68689F3853F9786AFB0DC1AEF6B0D95167DC42BA065B299043675806BAC4AF31B9049782FA2964F2A20252904C674C0D031CD8F31389516BAA833B843F1B11FC3307FA27931133D2D36F8E3FCF2336AB93931C5AFC48D0D1D641633AAFA8429B6D40BC0D87DC3930203010001";
private static String PUB_KEY_R3 = "BB021528CCF6A094D30F12EC8D5592C3F882F199A67A4288A75D26AAB52BB9C54CB1AF8E6BF975C8A3D70F4794145535578C9EA8A23919F5823C42A94E6EF53BC32EDB8DC0B05CF35938E7EDCF69F05A0B1BBEC094242587FA3771B313E71CACE19BEFDBE43B45524596A9C153CE34C852EEB5AEED8FDE6070E2A554ABB66D0E97A540346B2BD3BC66EB66347CFA6B8B8F572999F830175DBA726FFB81C5ADD286583D17C7E709BBF12BF786DCC1DA715DD446E3CCAD25C188BC60677566B3F118F7A25CE653FF3A88B647A5FF1318EA9809773F9D53F9CF01E5F5A6701714AF63A4FF99B3939DDC53A706FE48851DA169AE2575BB13CC5203F5ED51A18BDB150203010001";
private static String PUB_KEY_E1 = "245c2da22afd1c4ba65d97732731acb2a06962ef65e8a6b0f0ac4b9fff1c0b700fd3982f4dfc0f009b37f074055732972e05ef2a4325a3fb6e342713f64f7e69d302995eeb244792c1249be6b1218fc12481fc68cc1f69ba58f51922f774c616";
private static String PUB_KEY_E5 = "0d0b3a8a6b618eb6efdc5f58e7c6424554ab63f66661480a2e5975b481023750b73f1679dc98eca1289772201c2ccfd57c52204e54785b84146bc090ae85ecc051413c5a877f064dd4fe60d1fa6c2de17d951088a208540f991a4ce6ea0aacd8";
private static String PUB_KEY_E6 = "d9f19e4687f8217160a826eba3fab9eada1db912a7d426d95114b1617c7596bf220b391fd5bed10a46aa2d3c4a09842ebe409555e91940376675ed324e770449f8707bc318e7cef77110feac74d800d4ed6d1c731633109c3ab2ea6c62f4bdb8";
private static String PUB_KEY_R10 = "CF57E5E6C45412EDB447FEC92758764650288C1D3E88DF059DD5B51829BDDDB55ABFFAF6CEA3BEAF00214B625A5A3C012FC55803F689FF8E1143EBC1B5E01407968F6F1FD7E7BA8139097565B7C2AF185B372628E7A3F4072B6D1AFFAB58BC95AE40FFE9CB57C4B55B7F780D1861BC17E754C6BB4991CD6E18D18085EEA66536BC74EABC504CEAFC21F338169394BAB0D36B3806CD16127ACA5275C8AD76B2C29C5D98455C6F617BC62DEE3C13528601D957E6381CDF8DB51F92919AE74A1CCC45A87255F0B0E6A307ECFDA71B669E3F488B71847158C93AFAEF5EF25B442B3C74E78FB247C1076ACD9AB70D96F712812651540AEC61F6F7F5E2F28AC8950D8D0203010001";
private static String PUB_KEY_R11 = "BA87BC5C1B0039CBCA0ACDD46710F9013CA54EA561CB26CA52FB1501B7B928F5281EED27B324183967090C08ECE03AB03B770EBDF3E53954410C4EAE41D69974DE51DBEF7BFF58BDA8B713F6DE31D5F272C9726A0B8374959C4600641499F3B1D922D9CDA892AA1C267A3FFEEF58057B089581DB710F8EFBE33109BB09BE504D5F8F91763D5A9D9E83F2E9C466B3E106664348188065A037189A9B843297B1B2BDC4F815009D2788FBE26317966C9B27674BC4DB285E69C279F0495CE02450E1C4BCA105AC7B406D00B4C2413FA758B82FC55C9BA5BB099EF1FEEBB08539FDA80AEF45C478EB652AC2CF5F3CDEE35C4D1BF70B272BAA0B4277534F796A1D87D90203010001";
private static String PUB_KEY_R12 = "da982874adbe94fe3be01ee2e54b75ab2c127feda703327e3697ece8318fa5138d0b992e1ecd01513d4ce5286e095531aaa5225d72f42d07c24d403cdf0123b97837f51a653234e686719d04ef84085bbd021a99eba601009a73906d8fa207a0d097d3da456181353d14f9c4c05f6adc0b961ab09fe32aeabd2ad698c79b71ab3b740f3cdbb260be5a4b4e18e9db2a735c8961659efeed3ca6cb4e6fe49ef90046b3ff194d2a63b38e66c6188570c750656f3b74e548830f08585d2d239d5ea3fee8db00a1d2f4e3194df2ee7af6279ee5cd9c2da2f27f9c17adef133739d1b4c82c41d686c0e9ec21f8591b7fb93a7c9f5c019d6204c228bd0aad3cca10ec1b0203010001";
private static String PUB_KEY_R13 = "a567708dd0568164151761cdb906d4ad19908c2650379816639254dbd9cc840593ecd3ec081ba0605143487d2bc748969eb42dda9dc8273b57a19fabf0d60ed40e30ca6f9bb1d1d6a49d323e584e356f4558687117fc3ed85d82a02fb2516cb01a5db859ce3565c88ba1af1037ffe39c5dc2491734ff8c2b8b8df0bc712c930c1d05c4bac7cdaac95e7cd1c901f79c03f6fc0a5df4da7be6db764270ebf44d22da00776fd6c95f17fdda752ea5570cf6ea5cb6e073a568cfa174e275827e109fc1f5a2eb01e938b10a44ccd3c289f54935820a34b31ce988c2474e820e0a36f0474f8af1290475dacde19a5cff5e9d9895ba9a43d04aa21705010430d332b38f0203010001";
private bool PinPublicKey(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors)
{
try
{
if (certificate == null || chain == null)
return false;
bool chainContainsPk = false;
foreach (var element in chain.ChainElements)
{
String pk = element.Certificate.GetPublicKeyString().ToLower();
if (pk.Contains(PUB_KEY_X3.ToLower()) ||
pk.Contains(PUB_KEY_R3.ToLower()) ||
pk.Contains(PUB_KEY_E1.ToLower()) ||
pk.Contains(PUB_KEY_E5.ToLower()) ||
pk.Contains(PUB_KEY_E6.ToLower()) ||
pk.Contains(PUB_KEY_R10.ToLower()) ||
pk.Contains(PUB_KEY_R11.ToLower()) ||
pk.Contains(PUB_KEY_R12.ToLower()) ||
pk.Contains(PUB_KEY_R13.ToLower()))
{
chainContainsPk = true;
}
}
bool subjectAccepted = certificate.Subject.Trim().ToLower().EndsWith(".bewoplaner.de") ||
certificate.Subject.Trim().ToLower().EndsWith(".ownchat.de");
return chainContainsPk && subjectAccepted;
}
catch (Exception e)
{
return false;
}
}
private bool IsNet45OrNewer()
{
// Class "ReflectionContext" exists from .NET 4.5 onwards.
return Type.GetType("System.Reflection.ReflectionContext", false) != null;
}
private bool CheckStatusMessage(String url)
{
//try
//{
// using (WebClient client = new WebClient())
// {
// //MessageBox.Show(hostAddress);
// byte[] response = client.UploadValues(url, "POST", new NameValueCollection());
// String message = System.Text.Encoding.UTF8.GetString(response);
// //zum testen:
// //using (var myFile = new StreamReader("C:\\temp\\testxaml.txt", Encoding.Default))
// //{
// // message = myFile.ReadToEnd();
// // myFile.Close();
// //}
// if (!String.IsNullOrWhiteSpace(message) && message.Trim().Length > 2)
// {
// String ende = message.Substring(message.Length - 2);
// message = message.Replace("\\n", "\n");
// message = message.Substring(0, message.Length - 2);
// MessageDialog dlg = new MessageDialog();
// if (message.Contains("<") && message.Contains(">"))
// {
// dlg.SetXaml(message);
// }
// else
// {
// dlg.Message = message;
// }
// dlg.ShowDialog();
// if (ende.EndsWith(";0"))
// {
// return false;
// }
// }
// }
//}
//catch (Exception ex)
//{
// //MessageBox.Show(String.Format("Fehler beim Prüfen der Kundennummer: {0}\n\n{1}", ex.Message, ex.StackTrace));
//}
//return true;
#if DEBUG
//String message = @"Sehr geehrte Kundin, sehr geehrter Kunde,
// Ihr BeWoPlaner Nutzungszeitraum endet automatisch am 31.01.2020.
// Bitte wenden Sie sich an den BeWoPlaner - Support, sofern Sie den Nutzungszeitraum verlängern möchten.
// Vielen Dank.
// Ihr BeWoPlaner-Team;1";
//if (!String.IsNullOrWhiteSpace(message) && message.Trim().Length > 2)
//{
// String ende = message.Substring(message.Length - 2);
// message = message.Replace("\\n", "\n");
// message = message.Substring(0, message.Length - 2);
// MessageDialog dlg = new MessageDialog();
// if (message.Contains("<") && message.Contains(">"))
// {
// dlg.SetXaml(message);
// }
// else
// {
// dlg.Message = message;
// }
// dlg.Visibility = Visibility.Visible;
// dlg.ShowDialog();
// if (ende.EndsWith(";0"))
// {
// return false;
// }
//}
return true;
#else
try
{
using (WebClient client = new WebClient())
{
//MessageBox.Show(hostAddress);
byte[] response = client.UploadValues(url, "POST", new NameValueCollection());
String message = System.Text.Encoding.UTF8.GetString(response);
//zum testen:
//using (var myFile = new StreamReader("C:\\temp\\testxaml.txt", Encoding.Default))
//{
// message = myFile.ReadToEnd();
// myFile.Close();
//}
if (!String.IsNullOrWhiteSpace(message) && message.Trim().Length > 2)
{
String ende = message.Substring(message.Length - 2);
message = message.Replace("\\n", "\n");
message = message.Substring(0, message.Length - 2);
MessageDialog dlg = new MessageDialog();
if (message.Contains("<") && message.Contains(">"))
{
dlg.SetXaml(message);
}
else
{
dlg.Message = message;
}
dlg.ShowDialog();
if (ende.EndsWith(";0"))
{
return false;
}
}
}
}
catch (Exception ex)
{
//MessageBox.Show(String.Format("Fehler beim Prüfen der Kundennummer: {0}\n\n{1}", ex.Message, ex.StackTrace));
}
return true;
#endif
}
private BeWoProfile ReadSelectedProfile()
{
try
{
if (File.Exists(_ConfigFilePath))
{
using (var myFile = new StreamReader(_ConfigFilePath, Encoding.Default))
{
while (!myFile.EndOfStream)
{
var data = myFile.ReadLine();
if (!String.IsNullOrEmpty(data))
{
if (data.Contains("selected"))
{
var pos = data.IndexOf("=");
if (pos > 0)
{
var pData = data.Substring(pos + 1).Trim().Split('|');
if (pData.Length >= 3)
{
if (!String.IsNullOrEmpty(pData[1]) && !String.IsNullOrEmpty(pData[2]))
return new BeWoProfile(pData[0], pData[1], pData[2]);
}
}
}
}
}
}
}
}
catch (Exception e)
{
}
return null;
}
private void ReadProfileList()
{
try
{
if (File.Exists(_ProfilesFilePath))
{
var myFile = new StreamReader(_ProfilesFilePath, Encoding.Default);
while (!myFile.EndOfStream)
{
var data = myFile.ReadLine()?.Split('|');
if (data?.Length >= 3)
{
if (!String.IsNullOrEmpty(data[1]) && !String.IsNullOrEmpty(data[2]))
ProfileList.Add(new BeWoProfile(data[0], data[1], data[2]));
}
}
myFile.Close();
}
}
catch (Exception e)
{
}
}
private string GetNumericServerName(string serverName)
{
if (!String.IsNullOrEmpty(serverName))
{
int snOut = 0;
if (!Int32.TryParse(serverName, out snOut))
{
String nname = serverName.Replace("app", "");
if (nname.IndexOf('.') > 0)
{
return nname.Substring(0, nname.IndexOf('.'));
}
}
}
return serverName;
}
private void ShowEnterTenantDialog()
{
BeWoProfile p = null;
var cancel = false;
var tenant = String.Empty;
while (p == null && !cancel)
{
var dlg = new EnterTenantDialog { Tenant = tenant };
var result = dlg.ShowDialog();
if (result.HasValue && result.Value)
{
tenant = dlg.Tenant;
if (!String.IsNullOrWhiteSpace(tenant))
{
tenant = tenant.Trim();
}
var server = GetServerFromTenant(tenant);
if (!String.IsNullOrEmpty(server))
{
p = new BeWoProfile(tenant, server, tenant);
if (ProfileList.Count > 0)
ProfileList.Insert(0, p);
else
ProfileList.Add(p);
SaveProfileListToFile();
}
else
{
MessageBox.Show("Unbekannte Kundennummer '" + tenant + "'", "BeWoPlaner");
}
}
else
{
cancel = true;
}
}
}
private string GetServerFromTenant(string tenant)
{
try
{
if (tenant == "demo")
{
return "app1.bewoplaner.de";
}
//Server URL über Kundennummer:
//https://bewoplaner.beyondsoft.de/getserver.php?CustomerID=1234567890
//Lizenzstatus über Kundennummer (Lizenzzahlen und aktivierte Module)
//Nur Testdaten. Weiß gar nicht mehr so genau wofür das gut war…
//https://bewoplaner.beyondsoft.de/getcontractstate.php?CustomerID=1234567890
String url = String.Format(GETSERVER_URL, tenant);
using (WebClient client = new WebClient())
{
//MessageBox.Show(hostAddress);
byte[] response = client.UploadValues(url, "POST", new NameValueCollection());
String server = System.Text.Encoding.ASCII.GetString(response);
return server;
}
}
catch (Exception ex)
{
//MessageBox.Show(String.Format("Fehler beim Prüfen der Kundennummer: {0}\n\n{1}", ex.Message, ex.StackTrace));
return null;
}
return null;
}
private BeWoProfile GenerateProfileFromUri(Uri uri)
{
var paramDic = BeWoUtils.ParseQuery(uri.Query);
string v1, v2;
paramDic.TryGetValue("k", out v1);
paramDic.TryGetValue("s", out v2);
//if (String.IsNullOrEmpty(v1))
//{
// v1 = "demo";
//}
//if (String.IsNullOrEmpty(v2))
//{
// v2 = "Ungültiger Server";
// String uriStr = uri.ToString();
// if (!String.IsNullOrEmpty(uriStr))
// {
// v2 = uriStr;
// if (uriStr.IndexOf("://") >= 0)
// v2 = uriStr.Substring(uriStr.IndexOf("://") + 3);
// if (v2.ToLower().IndexOf("/bewo.application") > 0)
// v2 = v2.Substring(0, v2.ToLower().IndexOf("/bewo.application"));
// }
//}
return new BeWoProfile(v1, v2, v1);
}
public void CloseCurrentPopUp()
{
if (this._ModalPopUpBackGround != null)
{
this.Dispatcher.BeginInvoke(
DispatcherPriority.Normal,
(Action)delegate
{
this.grid_root.Children.Remove(this._CurrentModalPopUp);
this._CurrentModalPopUp = null;
if (this._ModalPopUpControls.Count == 0)
{
this.grid_root.Children.Remove(this._ModalPopUpBackGround);
this._ModalPopUpBackGround = null;
}
else
{
var control = this._ModalPopUpControls.Pop();
this._CurrentModalPopUp = control;
this.grid_root.Children.Add(control);
Panel.SetZIndex(control, int.MaxValue);
}
});
}
}
public void ShowControlAsModalPopUp(Control control)
{
this.ShowControlAsModalPopUp(control, HorizontalAlignment.Center, VerticalAlignment.Center);
}
public void ShowControlAsModalPopUp(Control control, HorizontalAlignment ha, VerticalAlignment va)
{
this.Dispatcher.BeginInvoke(
DispatcherPriority.Normal,
(Action)delegate
{
if (this._CurrentModalPopUp != null)
{
this.grid_root.Children.Remove(this._CurrentModalPopUp);
this._ModalPopUpControls.Push(this._CurrentModalPopUp);
}
else
{
this.ShowModalBackground();
}
this._CurrentModalPopUp = control;
control.HorizontalAlignment = ha;
control.VerticalAlignment = va;
Grid.SetColumnSpan(control, 3);
Grid.SetRowSpan(control, 3);
this.grid_root.Children.Add(control);
Panel.SetZIndex(control, int.MaxValue);
});
}
private void LoginControl_Loaded(object sender, RoutedEventArgs e)
{
double top = (this.ActualHeight - 400) / 3;
this.gridLogin.Margin = new Thickness(0, top, 0, 0);
BeWoApp.LoginControl = this;
if (TextBox_Username != null && String.IsNullOrEmpty(TextBox_Username.Text))
{
TextBox_Username.Focus();
}
#if DEBUG
if (DebugConfig.CurrentConfig is DebugConfig current)
{
if (!string.IsNullOrWhiteSpace(current.DefaultLoginUsername))
TextBox_Username.Text = current.DefaultLoginUsername;
if (!string.IsNullOrWhiteSpace(current.DefaultLoginPassword))
PasswordBox_Password.Password = current.DefaultLoginPassword;
if (current.AutoLogin)
button_login_Click(this, new RoutedEventArgs());
}
#endif
}
private void ShowModalBackground()
{
this._ModalPopUpBackGround = new Grid();
this._ModalPopUpBackGround.IsHitTestVisible = true;
this._ModalPopUpBackGround.Background = Brushes.White;
this._ModalPopUpBackGround.Opacity = .5;
Grid.SetColumnSpan(this._ModalPopUpBackGround, 3);
Grid.SetRowSpan(this._ModalPopUpBackGround, 3);
this.grid_root.Children.Add(this._ModalPopUpBackGround);
Panel.SetZIndex(this._ModalPopUpBackGround, int.MaxValue - 1);
}
private void button_login_Click(object sender, RoutedEventArgs e)
{
if (!String.IsNullOrEmpty(proxyname))
{
var webProxy = WebProxy.GetDefaultProxy();
webProxy.UseDefaultCredentials = true;
System.Net.WebRequest.DefaultWebProxy = new WebProxy(proxyname, true);
if (String.IsNullOrEmpty(proxyUsername))
{
WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;
}
else
{
WebRequest.DefaultWebProxy.Credentials = new NetworkCredential(proxyUsername, proxypasswd);
}
}
if (ProfileList.Count == 0 || profileSelectionComboBox.SelectedItem == null)
{
MessageBox.Show(
"Es wurde kein gültiges Profil gefunden. Bitte erstellen Sie zunächst ein Profil. Klicken Sie dazu auf 'Erweitert' und anschließend auf den Button 'Profile bearbeiten'",
"Ungültiges Profil", MessageBoxButton.OK, MessageBoxImage.Warning);
}
else
{
var profile = profileSelectionComboBox.SelectedItem as BeWoProfile;
isNet45OrNewer = IsNet45OrNewer();
if (!isNet45OrNewer)
{
if (!CheckStatusMessage(String.Format(GETNETMESSAGE_URL, profile.Tenant, BeWoApp.ShortVersion)))
{
return;
}
}
#if DEBUG
if (!CheckStatusMessage(String.Format(GETSTATUSMESSAGE_URL + "&pre", profile.Tenant, BeWoApp.ShortVersion)))
{
return;
}
#else
if (!CheckStatusMessage(String.Format(GETSTATUSMESSAGE_URL + "&pre", profile.Tenant, BeWoApp.ShortVersion)))
{
return;
}
#endif
ChangeServerAndTenant(profile);
var lWaitLayer = new WaitLayer2();
grid_root.Children.Add(lWaitLayer);
string lUserName = TextBox_Username.Text;
string lPassword = PasswordBox_Password.Password;
string lPIN = PINTextBox.Text;
string lTenant = BeWoApp.Tenant;
if (!String.IsNullOrEmpty(lPIN))
{
lPIN += "_" + System.Environment.MachineName;
}
Action<WaitLayer2, String, String, String, String> action = Login;
action.BeginInvoke(lWaitLayer, lUserName, lPassword, lTenant, lPIN, cb => { }, null);
}
}
private void Login(WaitLayer2 lWaitLayer, String lUserName, String lPassword, String lTenant, String lPIN)
{
try
{
//1. Versuch
UserValidationResult result = TryLogin(lWaitLayer, lUserName, lPassword, lTenant, lPIN);
//2. Versuch
if (result == UserValidationResult.UnkownError)
{
ServiceFacade.DoOperationsServiceAsync(op => op.ResetTenant(lTenant),
delegate
{
result = TryLogin(lWaitLayer, lUserName, lPassword, lTenant, lPIN);
if (result == UserValidationResult.UnkownError)
{
//3. Versuch
ServiceFacade.DoOperationsServiceAsync(op => op.ResetAllTenants(),
delegate
{
result = TryLogin(lWaitLayer, lUserName, lPassword, lTenant, lPIN);
if (result == UserValidationResult.UnkownError)
{
this.Dispatch(delegate
{
grid_root.Children.Remove(lWaitLayer);
MessageBox.Show("Fehler beim Verbinden mit dem Server. Bitte überprüfen Sie Ihre Internetverbindung oder schreiben Sie eine E-Mail an den Support support@bewoplaner.de.", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
});
}
});
}
});
}
if (result == UserValidationResult.UserUnknown)
{
this.Dispatch(delegate
{
grid_root.Children.Remove(lWaitLayer);
MessageBox.Show("Anmeldeinformationen nicht bekannt. Bitte überprüfen Sie den " + BS.Shared.Translation.Translator.Translate("Benutzernamen") + " und das Passwort!", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
});
}
if (result == UserValidationResult.EmployeeDeleted)
{
this.Dispatch(delegate
{
grid_root.Children.Remove(lWaitLayer);
MessageBox.Show("Der zugeordnete " + Translator.Translate("Mitarbeiterdatensatz") + " wurde gelöscht oder archiviert! Anmeldung nicht möglich.", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
});
}
if (result == UserValidationResult.TenantUnknown)
{
this.Dispatch(delegate
{
grid_root.Children.Remove(lWaitLayer);
MessageBox.Show("Die Kundennummer '" + lTenant + "' ist ungültig.", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
});
}
String pin = lPIN;
if (!String.IsNullOrEmpty(lPIN) && lPIN.IndexOf('_') >= 0)
{
pin = lPIN.Substring(0, lPIN.IndexOf('_'));
}
if (result == UserValidationResult.IncorrectPin)
{
this.Dispatch(delegate
{
grid_root.Children.Remove(lWaitLayer);
MessageBox.Show("Die Pin '" + pin + "' ist unbekannt!", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
});
}
if (result == UserValidationResult.PinAlreadyUsed)
{
this.Dispatch(delegate
{
grid_root.Children.Remove(lWaitLayer);
MessageBox.Show("Die Pin '" + pin + "' wurde bereits verwendet!", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
});
}
if (result == UserValidationResult.PinExpired)
{
this.Dispatch(delegate
{
grid_root.Children.Remove(lWaitLayer);
MessageBox.Show("Die Pin '" + pin + "' ist bereits abgelaufen!", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
});
}
if (result == UserValidationResult.PasswordExpired)
{
//this.Dispatch(delegate
//{
// grid_root.Children.Remove(lWaitLayer);
// //MessageBox.Show("Das Passwort ist abgelaufen!", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
// //var pav = new PasswortAenderungsView();
// //pav.ShowDialog();
//});
}
// Wegen fehlerhaftem Profil, sonst wird lWaitLayer nicht entfernt und eine Korrektur des Profils ist unmöglich ohne den BeWoPlaner neuzustarten.
if (result == UserValidationResult.UnkownError)
{
Thread.Sleep(2000);
this.Dispatch(delegate { grid_root.Children.Remove(lWaitLayer); });
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private UserValidationResult TryLogin(WaitLayer2 lWaitLayer, string lUserName, string lPassword, string tenant, string lPin)
{
UserValidationResult? result = null;
if (!string.IsNullOrEmpty(lUserName) && !string.IsNullOrEmpty(lPassword))
{
String tempUsername = lUserName;
String version = "unbekannt";
String clr = "unbekannt";
var bewoVersion = BeWoApp.Version;
try
{
version = Environment.OSVersion.VersionString;
}
catch (Exception e)
{
version = e.Message;
}
try
{
clr = Environment.Version.ToString();
}
catch (Exception e)
{
clr = e.Message;
}
tempUsername = String.Format("{0}//Version={1};CLRVersion={2};BeWoVersion={3};IsNet45OrNewer={4}", lUserName, version, clr, bewoVersion, isNet45OrNewer);
try
{
ServiceFacade.DoUserServiceAsync(s =>
{
try
{
return s.IsUserValid(tempUsername, lPassword, lPin);
}
catch (Exception e)
{
return UserValidationResult.UnkownError;
}
},
r =>
{
result = r;
this.Dispatch(delegate
{
LoginResult(lWaitLayer, r, lUserName, lPassword, tenant, lPin);
});
}, true);
}
catch (FaultException<BeWoFault>)
{
result = UserValidationResult.UnkownError;
}
}
else
{
if (result == null)
result = UserValidationResult.UserUnknown;
}
while (!result.HasValue)
{
Thread.Sleep(100);
}
return result.Value;
}
private void LoginResult(WaitLayer2 lWaitLayer, UserValidationResult result, String lUserName, String lPassword, String tenant, String lPIN)
{
if (result == UserValidationResult.UserValid || result == UserValidationResult.UserValidTwoFactorAuthenticationNeeded || result == UserValidationResult.TwoFactorAuthenticationFailedNoChatCodeAllowLogin)
{
if (result == UserValidationResult.UserValidTwoFactorAuthenticationNeeded || result == UserValidationResult.TwoFactorAuthenticationFailedNoChatCodeAllowLogin)
{
Translator t = new Translator(new MultiLanguage.ServiceTranslator());
grid_root.Children.Remove(lWaitLayer);
var dlg = new TwoFactorAuthMessageDialog(lUserName, lPassword);
var message = Translator.Translate("Zwei Faktor Authentifizierung erforderlich");
dlg.ShowCodeField = true;
if (result == UserValidationResult.TwoFactorAuthenticationFailedNoChatCodeAllowLogin)
{
message = Translator.Translate("Kein Chat Code für die Zwei Faktor Authentifizierung gefunden");
dlg.ShowCodeField = false;
}
if (message.Contains("<") && message.Contains(">"))
{
dlg.SetXaml(message);
}
else
{
dlg.Message = message;
}
dlg.Owner = BeWoApp.Current.MainWindow;
var dr = dlg.ShowDialog();
if (!dr.HasValue || !dr.Value)
{
return;
}
}
if (!CheckStatusMessage(String.Format(GETSTATUSMESSAGE_URL, tenant, BeWoApp.ShortVersion)))
{
grid_root.Children.Remove(lWaitLayer);
return;
}
BeWoApp.UserName = lUserName;
BeWoApp.UserPassword = lPassword;
BeWoApp.PasswortStrength = BeWoUtils.CheckPasswordSecurity(lPassword);
ServiceFacade.DoUserServiceAsync(s2 => s2.LoadUserByNameAndPassword(lUserName, lPassword),
r2 =>
{
BeWoApp.LoggedOnUser = r2;
ServiceFacade.DoOperationsServiceAsync(s => s.GetMandator(),
m =>
{
this.Dispatch(delegate
{
BeWoApp.Mandator = m;
LoginSuccessful?.Invoke(this, new EventArgs());
});
});
}, true);
}
else if (result == UserValidationResult.PasswordExpired || result == UserValidationResult.BeWoPasswordNotAllowed || result == UserValidationResult.TwoFactorAuthenticationFailedNoChatCodeDontAllowLogin)
{
BeWoApp.UserName = lUserName;
BeWoApp.UserPassword = lPassword;
ServiceFacade.DoUserServiceAsync(s2 => s2.LoadUserByNameAndPassword(lUserName, lPassword),
r2 =>
{
BeWoApp.LoggedOnUser = r2;
ServiceFacade.DoOperationsServiceAsync(s => s.GetMandator(),
m =>
{
this.Dispatch(delegate
{
BeWoApp.Mandator = m;
String msg = Translator.Translate("Das Passwort ist abgelaufen!");
if (result == UserValidationResult.BeWoPasswordNotAllowed)
{
msg = Translator.Translate("Das Passwort ist leider unsicher und muss zwingend geändert werden!");
}
grid_root.Children.Remove(lWaitLayer);
MessageBox.Show(msg, "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
var pav = new PasswortAenderungsView();
pav.ShowDialog();
if (pav.abr == 1)
{
}
else
{
LoginSuccessful?.Invoke(this, new EventArgs());
}
});
});
}, true);
}
}
private void Hyperlink_OnRequestNavigate(object sender, RequestNavigateEventArgs e)
{
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo((sender as Hyperlink).NavigateUri.ToString()));
}
private void TextBox_Username_OnGotFocus(object sender, RoutedEventArgs e)
{
TextBox_Username.SelectAll();
}
private void PasswordBox_Password_OnGotFocus(object sender, RoutedEventArgs e)
{
PasswordBox_Password.SelectAll();
}
private void button_addProfile_Click(object sender, RoutedEventArgs rea)
{
var newProfileList = new List<BeWoProfile>();
newProfileList.AddRange(ProfileList);
try
{
Mouse.OverrideCursor = Cursors.Wait;
var p = new ProfileEditView { Profiles = newProfileList };
profileEditPopUp.Child = p;
if (p.CommandBindings.Count != 0)
return;
p.CommandBindings.Add(
new CommandBinding(
ApplicationCommands.Close,
(s, e) =>
{
profileEditPopUp.Child = null;
}));
p.CommandBindings.Add(
new CommandBinding(
ApplicationCommands.Save,
(s, e) =>
{
ProfileList = p.Profiles;
SaveProfileListToFile();
profileEditPopUp.Child = null;
//BeWoProfile profile = profileSelectionComboBox.SelectedItem as BeWoProfile;
//ChangeServerAndTenant(profile);
}));
}
finally
{
Mouse.OverrideCursor = null;
}
}
private void button_configureProxy_Click(object sender, RoutedEventArgs rea)
{
ProxyLoginView proxyLogin = new ProxyLoginView();
proxyLogin.WindowStartupLocation = WindowStartupLocation.CenterScreen;
proxyLogin.ShowDialog();
ReadProxyName();
}
// TODO: Verschlüsselung einbauen!
private void ReadProxyName()
{
int counter = 0;
string line;
string[] datai = new string[3];
try
{
var filePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\proxy.dat";
if (!File.Exists(filePath))
{
filePath = Path.Combine(BeWoApp.GetAndCreateUserAppDataPath(), "proxy.dat");
}
var allLines = File.ReadAllLines(filePath);
foreach (var linex in allLines)
{
var decryptedLine = EncryptionUtils.DecryptString(linex);
datai[counter] = decryptedLine;
counter++;
}
//var file = new StreamReader(filePath);
//while ((line = file.ReadLine()) != null)
//{
// datai[counter] = Encoding.UTF8.GetString(Convert.FromBase64String(line));
// counter++;
//}
//file.Close();
proxyname = datai[0];
proxyUsername = datai[1];
proxypasswd = datai[2];
proxyTextBox.Text = proxyname;
}
catch (IOException i)
{
//Fehlermeldung
}
}
private void SaveSelectedProfile(BeWoProfile profile)
{
try
{
using (var sw = new StreamWriter(new FileStream(_ConfigFilePath, FileMode.Create), Encoding.UTF8))
{
#if DEBUG
sw.WriteLine("selected={0}|{1}|{2}", profile.Name, profile.Server, profile.Tenant);
#else
if (profile.Tenant != "demo")
{
sw.WriteLine("selected={0}|{1}|{2}", profile.Name, profile.Server, profile.Tenant);
}
#endif
}
}
catch (Exception ex)
{
//ignore read/write errors
}
}
private void SaveProfileListToFile()
{
try
{
var sw = new StreamWriter(new FileStream(_ProfilesFilePath, FileMode.Create), Encoding.UTF8);
foreach (var profile in ProfileList)
{
if (profile.Tenant != "demo")
{
if (!String.IsNullOrWhiteSpace(profile.Tenant))
{
profile.Tenant = profile.Tenant.Trim();
}
sw.WriteLine("{0}|{1}|{2}", profile.Name, profile.Server, profile.Tenant);
}
}
sw.Flush();
sw.Close();
profileSelectionComboBox.ItemsSource = ProfileList;
profileSelectionComboBox.Items.Refresh();
// Workaround, um profileSelectionComboBox.SelectedItem zu aktualisieren
if (profileSelectionComboBox.ItemsSource == null)
return;
//ChangeServerAndTenant(profileSelectionComboBox.SelectedItem as BeWoProfile);
//int itemssourcecount = ((List<BeWoProfile>) profileSelectionComboBox.ItemsSource).Count;
//int si = profileSelectionComboBox.SelectedIndex;
//profileSelectionComboBox.SelectedIndex = (si + 1) % itemssourcecount;
//profileSelectionComboBox.SelectedIndex = itemssourcecount == 1 || si == -1 ? 0 : si;
}
catch (Exception ex)
{
//ignore read/write errors
}
}
private void ChangeServerAndTenant(BeWoProfile profile)
{
try
{
//button_login.IsEnabled = false;
if (profile != null)
{
if (String.IsNullOrEmpty(profile.Server))
{
MessageBox.Show(
String.Format("Das gewählte Profil '{0}' enthält einen ungültigen Servernamen.",
profile.Name),
"Ungültiges Profil", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
if (String.IsNullOrEmpty(profile.Tenant))
{
MessageBox.Show(
String.Format("Das gewählte Profil '{0}' enthält eine ungültige Kundennummer.", profile.Name),
"Ungültiges Profil", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
profile.Tenant = profile.Tenant.Trim();
//if (BeWoApp.Tenant == "7635986435")
//{
// if (profile.Server != "3")
// {
// profile.Server = "3";
// SaveProfileListToFile();
// }
//}
var server = GetServerFromTenant(profile.Tenant);
#if !DEBUG
if (!String.IsNullOrEmpty(server) && server != profile.Server)
{
profile.Server = server;
SaveProfileListToFile();
}
#endif
BeWoApp.Tenant = profile.Tenant;
BeWoApp.ServerName = GetNumericServerName(profile.Server);
BeWoApp.ServerAddress = profile.Server;
#if DEBUG
//CB ZUM TESTEN
//BeWoApp.Tenant = "6000000000";
//BeWoApp.ServerName = "6";
//BeWoApp.ServerAddress = "app6.bewoplaner.de";
#endif
SaveSelectedProfile(profile);
//button_login.IsEnabled = true;
}
}
catch (UriFormatException ex)
{
MessageBox.Show(
"Die angegebene Serveradresse ist nicht korrekt. Bitte bearbeiten Sie das verwendete Profil. Klicken Sie dazu auf 'Erweitert' und anschließend auf den Button 'Profile bearbeiten'",
"Ungültiges Profil", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
private void ShowProfileStackPanel(object sender, RoutedEventArgs e)
{
if (profileLabel.Visibility == Visibility.Visible)
{
profileLabel.Visibility = Visibility.Collapsed;
profileStackPanel.Visibility = Visibility.Collapsed;
proxyLabel.Visibility = Visibility.Collapsed;
proxyStackPanel.Visibility = Visibility.Collapsed;
}
}
private double lineYCoordTo;
private double lineYCoordFrom;
private double heightFrom;
private double heightTo;
public double HeightFrom
{
get { return heightFrom; }
set
{
heightFrom = value;
OnPropertyChanged("HeightFrom");
}
}
public double HeightTo
{
get { return heightTo; }
set
{
heightTo = value;
OnPropertyChanged("HeightTo");
}
}
public double LineYCoordFrom
{
get { return lineYCoordFrom; }
set
{
lineYCoordFrom = value;
OnPropertyChanged("LineYCoordFrom");
}
}
public double LineYCoordTo
{
get { return lineYCoordTo; }
set
{
lineYCoordTo = value;
OnPropertyChanged("LineYCoordTo");
}
}
private void AnimationComplete(object sender, EventArgs e)
{
double tmp = HeightFrom;
HeightFrom = HeightTo;
HeightTo = tmp;
if (HeightFrom > HeightTo)
{
showProfileSelectionBtn.Content = "Ausblenden";
profileLabel.Visibility = Visibility.Visible;
profileStackPanel.Visibility = Visibility.Visible;
proxyLabel.Visibility = Visibility.Visible;
proxyStackPanel.Visibility = Visibility.Visible;
}
else
{
showProfileSelectionBtn.Content = "Erweitert";
}
}
private void Animation2Complete(object sender, EventArgs e)
{
double tmp2 = LineYCoordFrom;
LineYCoordFrom = LineYCoordTo;
LineYCoordTo = tmp2;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
private bool pwvViewOffen;
private void PasswortVergessenLinkOnRequestNavigate(object sender, RequestNavigateEventArgs e)
{
if (pwvViewOffen) return;
var p = new PwVergessenView();
p.Closed += (s, ex) => { pwvViewOffen = false; };
p.Show();
pwvViewOffen = true;
}
private void UIElement_OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.P)
{
if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl) && Keyboard.IsKeyDown(Key.LeftAlt))
{
PinEinblenden();
}
}
}
private void PinEinblenden()
{
if (PINTextBox.Visibility != Visibility.Visible)
{
PINTextBox.Visibility = Visibility.Visible;
lblPin.Visibility = Visibility.Visible;
linkLine.Margin = new Thickness(linkLine.Margin.Left, linkLine.Margin.Top + 25, linkLine.Margin.Right,
linkLine.Margin.Bottom);
gridLogin.Height += 25;
PINTextBox.Focus();
}
}
}
public class BeWoProfile
{
public string Name { get; set; }
public string Server { get; set; }
public string Tenant { get; set; }
public BeWoProfile(string pname, string pserver, string ptenant)
{
Name = pname;
Server = pserver;
Tenant = ptenant;
if (Name == null)
Name = String.Empty;
if (!String.IsNullOrEmpty(Tenant))
{
Tenant = Tenant.Trim();
}
}
public override string ToString()
{
return Name;
}
public override int GetHashCode()
{
String key = String.Format("{0}_{1}_{2}", Name, Server, Tenant);
return key.GetHashCode();
}
public override bool Equals(object obj)
{
var profile = obj as BeWoProfile;
if (profile == null)
{
return false;
}
String key1 = String.Format("{0}_{1}_{2}", Name, Server, Tenant);
String key2 = String.Format("{0}_{1}_{2}", profile.Name, profile.Server, profile.Tenant);
return key1.Equals(key2);
}
}
}