//Читает из реестра, сколько дней прошло с активации private int DaysFromActivation(RegistryKey key) { int errResult = Convert.ToInt32(DateTime.Now.Subtract(Different.MinDate).TotalDays); try { DateTime insDate = DateTime.FromOADate(Crypting.Decrypt(key.GetValue("id").ToString()).ToDouble()); return(Convert.ToInt32(DateTime.Now.Subtract(insDate).TotalDays)); } catch { return(errResult); } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { var tokenEncripted = filterContext.HttpContext.Request.Headers["token"]; var userName = filterContext.HttpContext.Request.Headers["userName"]; var rolesList = AllowedUserTypes.Replace(" ", string.Empty).Split(',').ToList(); if (rolesList.Contains("GUEST")) { if (userName == null || userName.Equals(string.Empty)) { CurentUserName = "******"; } else { CurentUserName = userName; } } else { try { string token = Crypting.Decrypt(tokenEncripted); string[] tokenArr = token.Split('|'); string tokenRole = tokenArr[1]; string tokenUsername = tokenArr[tokenArr.Length - 1]; if (!rolesList.Contains(tokenRole)) { returnUnauthorized(); } if (!tokenUsername.Equals(userName)) { returnUnauthenticated(); } CurentUserName = userName; } catch (Exception err) { // somebody messed with the token on client returnUnauthenticated(); } } // TODO: For greater security ask the database for users role // also possible to put token in the database (per user) and bunch other data }
/// <summary> /// Save data to file /// </summary> /// <param name="Attempts">Number of attempts</param> /// <returns>True, if save was succesful</returns> protected async Task <bool> SaveDataAsync(int Attempts = 0) { try { foreach (var item in ItemsSource.Where(x => x.Secured && !x.Encrypted)) { item.Name = Crypting.Encrypt(item.Name); item.Description = Crypting.Encrypt(item.Description); item.Encrypted = true; } var typeOfItemList = System.Enum.GetValues(typeof(ItemTypeEnum)).Cast <ItemTypeEnum>().ToList(); ItemStorage <T> itemStorage = new ItemStorage <T>() { Items = GetFinalCollection(), TypeOfItem = typeOfItemList[typeOfItemList.IndexOf(typeOfItemList.FirstOrDefault(x => x.ToString() == nameof(T)))] }; XmlSerializer Serializ = new XmlSerializer(typeof(ItemStorage <T>)); using (Stream XmlStream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(FileName, CreationCollisionOption.ReplaceExisting)) { Serializ.Serialize(XmlStream, /*DeliveredData*/ itemStorage); } foreach (var item in ItemsSource.Where(x => x.Secured && x.Encrypted)) { item.Name = Crypting.Decrypt(item.Name); item.Description = Crypting.Decrypt(item.Description); item.Encrypted = false; } return(true); } // When file is unavailable catch (Exception e) when((e.Message.Contains("denied") || e.Message.Contains("is in use")) && (Attempts < 10)) { return(await SaveDataAsync(Attempts + 1)); } catch (Exception e) { Debug.WriteLine(e.Message); return(false); } }
/// <summary> /// Get all items by async /// </summary> /// <typeparam name="T">Item type</typeparam> /// <returns>Collection of items</returns> public virtual async Task <List <T> > GetItemsAsync <T>() where T : BaseItem { var itemSource = dbAccess.GetAllItems <T>(); foreach (var item in itemSource) { if (item.Secured && item.Encrypted) { item.Name = Crypting.Decrypt(item.Name); item.Description = Crypting.Decrypt(item.Description); item.Encrypted = false; } } return(itemSource); }
//Возвращает номер лицензии указанного приложения или сообщает, что нет лицензии public string ANumber(string app) { int c = ACheck(app, true); if (c <= 1) { return("Нет лицензии"); } RegistryKey UAIKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\UAI"); try { return(Crypting.Decrypt(UAIKey.GetValue("un").ToString())); } catch { return("Нет лицензии"); } finally { UAIKey.Close(); } }
//Возвращает пользователя указанного приложения или сообщает о пробном периоде public string AUser(string app) { int c = ACheck(app, true); if (c <= 0) { return("Приложение не активировано. Пробный период истек."); } if (c == 1) { return("Приложение не активировано. Осталось " + _leftDays + " дней до окончания пробного периода."); } RegistryKey UAIKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\UAI"); try { return(Crypting.Decrypt(UAIKey.GetValue("cp").ToString())); } catch { return(""); } finally { UAIKey.Close(); } }
/// <summary> /// Get collection of valid items /// </summary> /// <param name="reloadItems">Reload collection after changing security</param> /// <returns>Collection of items</returns> public virtual async Task <ObservableCollection <T> > GetItemsAsync(bool reloadItems = false) { if (ItemsSource == null || reloadItems) { ItemsSource = await ReadDataAsync(); } foreach (var item in ItemsSource) { item.ManagerID = ID; if (item.Secured && item.Encrypted) { item.Name = Crypting.Decrypt(item.Name); item.Description = Crypting.Decrypt(item.Description); item.Encrypted = false; } } return(ItemsSource); }
private void BtnSubmit_OnClick(object sender, RoutedEventArgs e) { ConnectionStringHolder.Username = txtUsername.Text; string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SqlRUsers;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; SqlConnection connection = new SqlConnection(connectionString); try { if (connection.State == ConnectionState.Closed) { connection.Open(); } string querySalt = "SELECT Salt FROM Users WHERE UserName=@Username"; SqlCommand sqlCmdSalt = new SqlCommand(querySalt, connection); sqlCmdSalt.CommandType = CommandType.Text; sqlCmdSalt.Parameters.AddWithValue("@Username", txtUsername.Text); var salt = Convert.ToString(sqlCmdSalt.ExecuteScalar()); string queryConn = "SELECT ConnectionString FROM Users WHERE UserName=@Username"; SqlCommand sqlCmdConn = new SqlCommand(queryConn, connection); sqlCmdConn.CommandType = CommandType.Text; sqlCmdConn.Parameters.AddWithValue("@Username", txtUsername.Text); ConnectionStringHolder.ConString = Crypting.Decrypt(Convert.ToString(sqlCmdConn.ExecuteScalar())); Hashing hashing = new Hashing(); var hashedPassword = hashing.GetHash(salt, txtPassword.Password); string query = "SELECT COUNT(1) FROM Users WHERE UserName=@Username AND Password=@Password"; SqlCommand sqlCmd = new SqlCommand(query, connection); sqlCmd.CommandType = CommandType.Text; sqlCmd.Parameters.AddWithValue("@Username", txtUsername.Text); sqlCmd.Parameters.AddWithValue("@Password", hashedPassword); int count = Convert.ToInt32(sqlCmd.ExecuteScalar()); if (count == 1) { MainWindow dashboard = new MainWindow(); dashboard.Show(); this.Close(); } else { MessageBox.Show("Username or Password is incorrect."); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { connection.Close(); } }
//Возвращает, зарегистрировано ли приложение (код приложения изменен) private bool IsReg(string app, RegistryKey key) { return(key.GetValue(app) != null && Crypting.Decrypt(key.GetValue(app).ToString()).ToLower() == "true"); }
protected override async void ShowModal(ShowModalActivationMsg obj) { var file = obj.Files[0]; try { string fileXmlString = await FileIO.ReadTextAsync((IStorageFile)file); ItemTypeEnum?itemType = CategoryDecode(fileXmlString); MessageDialog importMoreItemsMessage = new MessageDialog("You are trying to import more than one item.\n\n" + "Import all items?", "Importing more items", MessageDialogButtonsEnum.YesNo); TextBlock itemSecuredMessage = new TextBlock() { Text = "One or more items are secured.\n\n" + "Please, log in and repeat action.", FontSize = 30 }; TextBlock importingMessage = new TextBlock() { Text = "Importing items\n\n" + "Please wait.", FontSize = 30 }; if (itemType == null) { return; } switch (itemType) { case ItemTypeEnum.Activity: var activityFile = DecodeItemFile <Activity>(fileXmlString); ActivitiesManager actiMan = new ActivitiesManager(); await actiMan.GetItemsAsync(); App.ManaLoc.AddManager(actiMan, actiMan.ID); if (activityFile != null) { foreach (var item in activityFile.Items) { item.ID = -1; if (item.Secured) { item.Name = Crypting.Decrypt(item.Name); item.Description = Crypting.Decrypt(item.Description); } } } else { return; } if (activityFile.Items.Count(x => x.Secured) != 0 && !CustomSettings.IsUserLogged) { ModalWindow.SetVisibility(true, itemSecuredMessage); } else if (activityFile.Items.Count > 1) { if (await importMoreItemsMessage.ShowAsync() == MessageDialogResultEnum.Yes) { ModalWindow.SetVisibility(true, importingMessage, false); actiMan = (ActivitiesManager)App.ManaLoc.GetManager(actiMan.ID); await actiMan.AddItemRange(activityFile.Items.ToList()).ContinueWith((res) => { Messenger.Send(new ItemAddSavedMsg() { ItemType = ItemTypeEnum.Activity, MoreItemsAdded = true }); }); ModalWindow.SetVisibility(false, importingMessage, false); } } else { ModalWindow.SetVisibility(true, new ActivityAdd(true, activityFile.Items[0]), false); } break; case ItemTypeEnum.Note: var noteFile = DecodeItemFile <Note>(fileXmlString); NotesManager noMan = new NotesManager(); await noMan.GetItemsAsync(); App.ManaLoc.AddManager(noMan, noMan.ID); if (noteFile != null) { foreach (var item in noteFile.Items) { item.ID = -1; if (item.Secured) { item.Name = Crypting.Decrypt(item.Name); item.Description = Crypting.Decrypt(item.Description); } } } else { return; } if (noteFile.Items.Count(x => x.Secured) != 0 && !CustomSettings.IsUserLogged) { ModalWindow.SetVisibility(true, itemSecuredMessage); } else if (noteFile.Items.Count > 1) { if (await importMoreItemsMessage.ShowAsync() == MessageDialogResultEnum.Yes) { ModalWindow.SetVisibility(true, importingMessage, false); noMan = (NotesManager)App.ManaLoc.GetManager(noMan.ID); await noMan.AddItemRange(noteFile.Items.ToList()).ContinueWith((res) => { Messenger.Send(new ItemAddSavedMsg() { ItemType = ItemTypeEnum.Note, MoreItemsAdded = true }); }); ModalWindow.SetVisibility(false, importingMessage, false); } } else { ModalWindow.SetVisibility(true, new NoteAdd(true, noteFile.Items[0]), false); } break; default: return; } } catch (Exception e) { Debug.WriteLine(e.Message); } }