Ejemplo n.º 1
0
        public ActionStatus Register()
        {
            using (var db = new ProjectDbContext())
            {
                var accountCreationTime = DateTime.Now;
                try
                {
                    Id               = Guid.NewGuid();
                    UserName         = UserName;
                    Password         = ComputeHash(Password, HashAlgorithmType.SHA512);
                    Email            = Email;
                    ActivationEmail  = Email;
                    RegistrationDate = accountCreationTime;
                    IsLocked         = 0;
                    IsActivated      = 0;
                    LockedDateTime   = accountCreationTime;
                    RetryAttempts    = null;

                    db.Users.Add(this);
                    db.SaveChanges();

                    return(ActionStatus.Success);
                }
                catch (Exception)
                {
                    return(ActionStatus.DatabaseError);
                }
                finally
                {
                    if (db.Database.Connection.State == ConnectionState.Open)
                    {
                        db.Database.Connection.Close();
                    }
                }
            }
        }
Ejemplo n.º 2
0
        // wywoływany w JS, otrzymuje po kolei itemy pobrane z bazy danych
        public PartialViewResult GetAutocompleteItem(string item)
        {
            var js = new JavaScriptSerializer();
            var dictItem = (Dictionary<string, object>)js.DeserializeObject(item);
            var db = new ProjectDbContext();
            //var users = db.Users.ToList();
            var authorGuid = new Guid(dictItem["AuthorId"].ToString());

            var book = new Book
            {
                Id = new Guid(dictItem["Id"].ToString()),
                Title = dictItem["Title"].ToString(),
                Category = dictItem["Category"].ToString(),
                AuthorId = authorGuid,
                Description = dictItem["Description"].ToString(),
                AdditionDate = Convert.ToDateTime(dictItem["AdditionDate"].ToString()),
                Thumbnail = dictItem["Thumbnail"].ToString(),
                IsPublic = Convert.ToBoolean(dictItem["IsPublic"]),
                // Navigation Properties - (added with include)
                Author = db.Users.Single(u => u.Id == authorGuid)
            };

            return PartialView("_AutocompleteItem", book);
        }
Ejemplo n.º 3
0
        public string IsRemindPasswordCodeValid(string remindPasswordCode, string remindPasswordEmail)
        {
            using (var db = new ProjectDbContext())
            {
                try
                {
                    if (db.Users.Any(u => u.Email == remindPasswordEmail))
                    {
                        var currUserId = db.Users.Single(u => u.Email == remindPasswordEmail).Id;
                        var userRequestsDesc =
                            db.RemindPasswordRequests.Where(x => x.UserId == currUserId)
                                .OrderByDescending(x => x.RemindPasswordRequestDateTime);
                        db.RemindPasswordRequests.RemoveRange(userRequestsDesc.Skip(1));
                        db.SaveChanges();

                        if (userRequestsDesc.Count() == 1)
                        {
                            var lastReq = userRequestsDesc.Single();
                            var isActivationCodeValid = remindPasswordCode == lastReq.Id.ToString();

                            if (isActivationCodeValid)
                            {
                                return JsonConvert.SerializeObject(new
                                {
                                    Message = "",
                                    Result = UserActionResult.Success,
                                    ResultString = Enum.GetName(typeof(UserActionResult), UserActionResult.Success)
                                });
                            }
                        }
                    }

                    return JsonConvert.SerializeObject(new
                    {
                        Message = "Kod Weryfikacyjny dla podanego Emaila jest błędny",
                        Result = UserActionResult.Failure,
                        ResultString = Enum.GetName(typeof(UserActionResult), UserActionResult.Failure)
                    });
                }
                catch (Exception)
                {
                    return JsonConvert.SerializeObject(new
                    {
                        Message = "Baza Danych nie odpowiada",
                        Result = UserActionResult.DatabaseError,
                        ResultString = Enum.GetName(typeof(UserActionResult), UserActionResult.DatabaseError)
                    });
                }
                finally
                {
                    if (db.Database.Connection.State == ConnectionState.Open)
                        db.Database.Connection.Close();
                }
            }
        }
Ejemplo n.º 4
0
 public string IsEmailInDatabase(string email)
 {
     //Thread.Sleep(2000);
     using (var db = new ProjectDbContext())
     {
         try
         {
             var isEmailInDatabase = db.Users.Any(x => x.Email == email);
             return JsonConvert.SerializeObject(new
             {
                 Message = isEmailInDatabase ? "" : "Email nie znajduje się w Bazie Danych",
                 Result = isEmailInDatabase ? UserActionResult.Success : UserActionResult.Failure,
                 ResultString = isEmailInDatabase ? Enum.GetName(typeof (UserActionResult), UserActionResult.Success) : Enum.GetName(typeof (UserActionResult), UserActionResult.Failure)
             });
         }
         catch (Exception)
         {
             return JsonConvert.SerializeObject(new
             {
                 Message = "Baza Danych nie odpowiada",
                 Result = UserActionResult.DatabaseError,
                 ResultString = Enum.GetName(typeof (UserActionResult), UserActionResult.DatabaseError)
             });
         }
         finally
         {
             if (db.Database.Connection.State == ConnectionState.Open)
                 db.Database.Connection.Close();
         }
     }
 }
Ejemplo n.º 5
0
        public UserActionResult SendRemindPasswordRequest()
        {
            using (var db = new ProjectDbContext())
            {
                var vaerificationTime = DateTime.Now;
                var varificationRequestGuid = Guid.NewGuid();

                try
                {
                    var dbUser = db.Users.Single(u => u.Email == RemindPasswordEmail);

                    AutoMapperConfiguration.Mapper.Map(dbUser, this);

                    var sbEmailBody = new StringBuilder();
                    sbEmailBody.Append("Witaj Użytkowniku: " + UserName + ",<br/><br/>");
                    sbEmailBody.Append("Poniżej znajdziesz kod weryfikacyjny do zmiany Hasła dla Twojego konta na naszej stronie:");
                    sbEmailBody.Append("<br/><br/>");
                    sbEmailBody.Append("Twój Kod Weryfikacyjny:");
                    sbEmailBody.Append("<br/>");
                    sbEmailBody.Append("<b>" + varificationRequestGuid + "</b>");
                    sbEmailBody.Append("<br/><br/>");
                    sbEmailBody.Append("Pozdrawiamy");
                    sbEmailBody.Append("<br/>");
                    sbEmailBody.Append("Strona Interaktywne Książki");

                    var sendEmailResult = SendEmail("Interaktywne Książki - Zmiana Hasła", sbEmailBody.ToString());

                    if (sendEmailResult == UserActionResult.SendingEmailFailure)
                        return sendEmailResult;

                    db.RemindPasswordRequests.Add(new RemindPasswordRequest()
                    {
                        Id = varificationRequestGuid,
                        UserId = Id,
                        RemindPasswordRequestDateTime = vaerificationTime
                    });
                    db.SaveChanges();

                    return UserActionResult.Success;
                }
                catch (Exception)
                {
                    return UserActionResult.DatabaseError;
                }
                finally
                {
                    if (db.Database.Connection.State == ConnectionState.Open)
                        db.Database.Connection.Close();
                }
            }
        }
Ejemplo n.º 6
0
        public UserActionResult SendActivationLink()
        {
            using (var db = new ProjectDbContext())
            {
                var activationTime = DateTime.Now;
                var activationRequestGuid = Guid.NewGuid();

                try
                {
                    var dbUser = db.Users.Single(u => u.Email == ActivationEmail);
                    if (Convert.ToBoolean(dbUser.IsActivated))
                        return UserActionResult.AccountAlreadyActivated;

                    Id = dbUser.Id;
                    UserName = dbUser.UserName;
                    Email = dbUser.Email;

                    var sbEmailBody = new StringBuilder();
                    sbEmailBody.Append("Witaj Użytkowniku: " + UserName + ",<br/><br/>");
                    sbEmailBody.Append("Poprosiłeś o aktywację konta na naszej stronie. Aktywacji możesz dokonać poprzez wpisanie Kodu Atywacyjnego na stronie Rejestracji.");
                    sbEmailBody.Append("<br/><br/>");
                    sbEmailBody.Append("Twój Kod Aktywacyjny:");
                    sbEmailBody.Append("<br/>");
                    sbEmailBody.Append("<b>" + activationRequestGuid + "</b>");
                    sbEmailBody.Append("<br/><br/>");
                    sbEmailBody.Append("Pozdrawiamy");
                    sbEmailBody.Append("<br/>");
                    sbEmailBody.Append("Strona Interaktywne Książki");

                    var sendEmailResult = SendEmail("Interaktywne Książki - Aktywacja Konta", sbEmailBody.ToString());

                    if (sendEmailResult == UserActionResult.SendingEmailFailure)
                        return sendEmailResult;

                    db.ActivationRequests.Add(new ActivationRequest()
                    {
                        Id = activationRequestGuid,
                        UserId = Id,
                        ActivationRequestDateTime = activationTime
                    });
                    db.SaveChanges();

                    return UserActionResult.Success;
                }
                catch (Exception)
                {
                    return UserActionResult.DatabaseError;
                }
                finally
                {
                    if (db.Database.Connection.State == ConnectionState.Open)
                        db.Database.Connection.Close();
                }
            }
        }
Ejemplo n.º 7
0
        public UserActionResult RemindPassword()
        {
            using (var db = new ProjectDbContext())
            {
                try
                {
                    var lastReq = db.RemindPasswordRequests.Single(ar => ar.Id.ToString() == RemindPasswordCode);
                    var dbUser = db.Users.Single(u => u.Id == lastReq.UserId);

                    dbUser.Password = Encryption.ComputeHash(RemindPasswordNewPassword, HashAlgorithmType.SHA512);

                    AutoMapperConfiguration.Mapper.Map(dbUser, this);

                    db.RemindPasswordRequests.Remove(lastReq);
                    db.SaveChanges();

                    return UserActionResult.Success;
                }
                catch (Exception)
                {
                    return UserActionResult.DatabaseError;
                }
                finally
                {
                    if (db.Database.Connection.State == ConnectionState.Open)
                        db.Database.Connection.Close();
                }
            }
        }
Ejemplo n.º 8
0
        public UserActionResult Register()
        {
            using (var db = new ProjectDbContext())
            {
                var accountCreationTime = DateTime.Now;
                try
                {
                    Id = Guid.NewGuid();
                    UserName = UserName;
                    Password = Encryption.ComputeHash(Password, HashAlgorithmType.SHA512);
                    Email = Email;
                    ActivationEmail = Email;
                    RegistrationDate = accountCreationTime;
                    IsLocked = 0;
                    IsActivated = 0;
                    LockedDateTime = accountCreationTime;
                    RetryAttempts = null;

                    db.Users.Add(this);
                    db.SaveChanges();

                    return UserActionResult.Success;
                }
                catch (Exception ex)
                {
                    return UserActionResult.DatabaseError;
                }
                finally
                {
                    if (db.Database.Connection.State == ConnectionState.Open)
                        db.Database.Connection.Close();
                }
            }
        }
Ejemplo n.º 9
0
        public UserActionResult Activate()
        {
            using (var db = new ProjectDbContext())
            {
                try
                {
                    var lastReq = db.ActivationRequests.Single(ar => ar.Id.ToString() == ActivationCode);
                    var dbUser = db.Users.Single(u => u.Id == lastReq.UserId);

                    if (Convert.ToBoolean(dbUser.IsActivated))
                        return UserActionResult.AccountAlreadyActivated;

                    dbUser.IsActivated = 1;

                    Id = dbUser.Id;
                    UserName = dbUser.UserName;
                    Password = dbUser.Password;
                    Email = dbUser.Email;
                    RegistrationDate = dbUser.RegistrationDate;
                    IsLocked = dbUser.IsLocked;
                    IsActivated = dbUser.IsActivated;
                    LockedDateTime = dbUser.LockedDateTime;
                    RetryAttempts = dbUser.RetryAttempts;

                    db.ActivationRequests.Remove(lastReq);
                    db.SaveChanges();

                    return UserActionResult.Success;
                }
                catch (Exception)
                {
                    return UserActionResult.DatabaseError;
                }
                finally
                {
                    if (db.Database.Connection.State == ConnectionState.Open)
                        db.Database.Connection.Close();
                }
            }
        }
Ejemplo n.º 10
0
        // NIEUŻYWANE
        protected List<Book> GetBooksDynamicLinqExpressions(Search search)
        {
            var db = new ProjectDbContext();
            var books = db.Books;//.Include(b => b.Author);

            var listTerms = search.SearchTerm.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)
                .Where(s => s.Length >= 3).ToList().ConvertAll(t => t.ToLower().Replace("|", ""));

            var searchedBooks = books;
            //.AsQueryable().Where(delegate (Book book)
            //{
            //    if (book.IsPublic != true)
            //        return false;

            //    if (listTerms.Count <= 0)
            //        return true;

            //    var sbWhereToSearch = new StringBuilder();
            //    var titleValue = book.Title;
            //    var authorValue = db.Users.Single(u => u.Id == book.AuthorId).UserName;
            //    var categoryValue = book.Category;
            //    var descriptionValue = book.Description;

            //    if (search.IncludeTitle)
            //        sbWhereToSearch.Append(titleValue + " ");

            //    if (search.IncludeAuthor)
            //        sbWhereToSearch.Append(authorValue + " ");

            //    if (search.IncludeCategory)
            //        sbWhereToSearch.Append(categoryValue + " ");

            //    if (search.IncludeDescription)
            //        sbWhereToSearch.Append(descriptionValue + " ");

            //    if (sbWhereToSearch.Length == 0) // jeśli nic nie zostało wybrane
            //        sbWhereToSearch.Append(titleValue + " ");

            //    return listTerms.All(s => sbWhereToSearch.ToString().ToLower().Contains(s));
            //});

            //// Drzewo wyrażenia reprezentujące parametr predykatu
            //ParameterExpression pe = Expression.Parameter(typeof(Book), "book");
            //LabelTarget returnTarget = Expression.Label(typeof(bool));

            //// if (book.IsPublic != true)
            ////     return false;
            //Expression ifBookNotPublic = Expression.IfThen(
            //    Expression.NotEqual(
            //        Expression.Property(pe, typeof(Book).GetProperty("IsPublic")),
            //        Expression.Constant(true)),
            //    Expression.Return(returnTarget, Expression.Constant(false)));

            //// if (listTerms.Count <= 0)
            ////     return true;
            //Expression paramListTerms = Expression.Constant(listTerms);
            //Expression ifListTermsCountLessOrEqualThanZero = Expression.IfThen(
            //    Expression.LessThanOrEqual(
            //        Expression.Property(paramListTerms, typeof(List<string>).GetProperty("Count")),
            //        Expression.Constant(0, typeof(int))),
            //    Expression.Return(returnTarget, Expression.Constant(true)));

            //// listTerms.All(s => sbWhereToSearch.ToString().ToLower().Contains(s));
            //ParameterExpression pTerm = Expression.Parameter(typeof(string), "s");
            //Expression paramSearch = Expression.Constant(search);

            //// if (search.IncludeTitle)
            ////     sbWhereToSearch.Append(titleValue + " ");
            //Expression ifSearchIncludeTitleThenConcat = Expression.IfThen(
            //    Expression.Equal(
            //        Expression.Property(paramSearch, typeof(Search).GetProperty("IncludeTitle")),
            //        Expression.Constant(true)),
            //    Expression. WHAT NOW? );

            //// ===================================
            //var exprBlock = Expression.Block(); // Expression Calls here
            //var searchedBooks = books.AsQueryable().Where(Expression.Lambda<Func<Book, bool>>(exprBlock, pe)); // książki, takie dla których cały blok zwraca true

            var sortedBooks = searchedBooks.OrderBy(search.SortBy + " " + search.SortOrder.ToLower()); // dynamic LINQ query helper

            var pagedBooks = search.HowMuchSkip >= 0 ?
                sortedBooks.Skip(search.HowMuchSkip).Take(search.HowMuchTake) :
                Enumerable.Empty<Book>().AsQueryable();

            //var sql = ((ObjectQuery)pagedBooks).ToTraceString();
            //var linq = pagedBooks.ToString();

            // całe procedurą z LIMIT search.HowMuchSkip OFFSET search.HowMuchTake
            // E:\Program Files\XAMPP\mysql\data\Szymon.log

            return pagedBooks.ToList(); // Error: LINQ to Entities does not recognize the method 'Boolean CheckWhatToSearch(MVCDemo.Models.Book, MVCDemo.Models.Search, System.Collections.Generic.List`1[System.String])' method, and this method cannot be translated into a store expression.
        }
Ejemplo n.º 11
0
        // NIEUŻYWANE
        protected List<Book> GetBooksAlternate(Search search)
        {
            var db = new ProjectDbContext();
            var books = db.Books;

            var listTerms = search.SearchTerm.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)
                .Where(s => s.Length >= 3).ToList().ConvertAll(t => t.ToLower().Replace("|", ""));

            var searchedBooks = books
                .Where(delegate (Book book)
                {
                    if (book.IsPublic != true)
                        return false;

                    if (listTerms.Count <= 0)
                        return true;

                    var sbWhereToSearch = new StringBuilder();
                    var titleValue = book.Title;
                    var authorValue = db.Users.Single(u => u.Id == book.AuthorId).UserName;
                    var categoryValue = book.Category;
                    var descriptionValue = book.Description;

                    if (search.IncludeTitle)
                        sbWhereToSearch.Append(titleValue + " ");

                    if (search.IncludeAuthor)
                        sbWhereToSearch.Append(authorValue + " ");

                    if (search.IncludeCategory)
                        sbWhereToSearch.Append(categoryValue + " ");

                    if (search.IncludeDescription)
                        sbWhereToSearch.Append(descriptionValue + " ");

                    if (sbWhereToSearch.Length == 0) // jeśli nic nie zostało wybrane
                        sbWhereToSearch.Append(titleValue + " ");

                    return listTerms.All(sbWhereToSearch.ToString().ToLower().Contains); // true jeśli zawiera wszystkie elementy z wpisanych przez usera
                });

            var sortedBooks = searchedBooks.OrderBy(search.SortBy + " " + search.SortOrder.ToLower()); // dynamic LINQ query helper

            var pagedBooks = search.HowMuchSkip >= 0 ?
                sortedBooks.Skip(search.HowMuchSkip).Take(search.HowMuchTake) :
                Enumerable.Empty<Book>().AsQueryable();

            return pagedBooks.ToList();
        }
Ejemplo n.º 12
0
        protected List<Book> GetBooks(Search search, out string resultsCounter, out bool error)
        {
            error = false;
            resultsCounter = "n/a";
            var books = Enumerable.Empty<Book>().ToList();

            using (var db = new ProjectDbContext())
            {
                db.Database.Initialize(force: false); // MODEL MUSI BYĆ ZBUDOWANY ZANIM OTWORZYMY POŁĄCZENIE, INACZEJ BĘDZIE BŁĄD, CANNOT USE CONTEXT DURING MODEL CREATING

                var paramSearchTerms = new MySqlParameter { ParameterName = "p_SearchTerms", Value = search.SearchTerm };
                var paramIncludeTitle = new MySqlParameter { ParameterName = "p_IncludeTitle", Value = search.IncludeTitle };
                var paramIncludeAuthor = new MySqlParameter { ParameterName = "p_IncludeAuthor", Value = search.IncludeAuthor };
                var paramIncludeCategory = new MySqlParameter { ParameterName = "p_IncludeCategory", Value = search.IncludeCategory };
                var paramIncludeDescription = new MySqlParameter { ParameterName = "p_IncludeDescription", Value = search.IncludeDescription };
                var paramHowMuchSkip = new MySqlParameter { ParameterName = "p_HowMuchSkip", Value = search.HowMuchSkip };
                var paramHowMuchTake = new MySqlParameter { ParameterName = "p_HowMuchTake", Value = search.HowMuchTake };
                var paramSortBy = new MySqlParameter { ParameterName = "p_SortBy", Value = search.SortBy };
                var paramSortOrder = new MySqlParameter { ParameterName = "p_SortOrder", Value = search.SortOrder };

                var cmd = db.Database.Connection.CreateCommand();
                cmd.CommandText = "sp_SearchBooks";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(paramSearchTerms);
                cmd.Parameters.Add(paramIncludeTitle);
                cmd.Parameters.Add(paramIncludeAuthor);
                cmd.Parameters.Add(paramIncludeCategory);
                cmd.Parameters.Add(paramIncludeDescription);
                cmd.Parameters.Add(paramHowMuchSkip);
                cmd.Parameters.Add(paramHowMuchTake);
                cmd.Parameters.Add(paramSortBy);
                cmd.Parameters.Add(paramSortOrder);

                try
                {
                    if (search.HowMuchSkip >= 0)
                    {
                        db.Database.Connection.Open();
                        var reader = cmd.ExecuteReader();

                        resultsCounter = ((IObjectContextAdapter)db)
                            .ObjectContext
                            .Translate<string>(reader).SingleOrDefault();

                        reader.NextResult();
                        books = ((IObjectContextAdapter)db)
                            .ObjectContext
                            .Translate<Book>(reader).ToList(); //.AsQueryable().Include(b => b.Author)
                        reader.Close();

                        var loadedUsers = new List<User>();
                        foreach (var b in books)
                        {
                            var loadedCurrAuthor = loadedUsers.SingleOrDefault(u => b.AuthorId == u.Id);

                            if (loadedCurrAuthor == null)
                                loadedUsers.Add(db.Users.Single(u => b.AuthorId == u.Id));

                            b.Author = loadedUsers.Single(u => b.AuthorId == u.Id);
                        }
                    }
                }
                catch (Exception ex)
                {
                    error = true;
                    return books; // fallback, zwróć pusty zestaw
                }
                finally
                {
                    if (db.Database.Connection.State == ConnectionState.Open)
                        db.Database.Connection.Close();
                }

                return books;
            }
        }
Ejemplo n.º 13
0
        private ActionStatus SendEmail(string emailSubject, string emailBody)
        {
            using (var db = new ProjectDbContext())
            {
                try
                {
                    var dbPrivateKey = db.Keys.SingleOrDefault(k => k.Id == "email_private");
                    var privateKey   = dbPrivateKey?.Value;
                    var xmlPath      = $@"{AppDomain.CurrentDomain.BaseDirectory}Data\Email.xml";

                    var doc     = XDocument.Load(xmlPath);
                    var smtp    = doc.Element("smtp");
                    var network = smtp?.Element("network");

                    var host        = network?.Attribute("host")?.Value;
                    var port        = Convert.ToInt32(network?.Attribute("port")?.Value);
                    var address     = smtp?.Attribute("from")?.Value ?? "";
                    var userName    = network?.Attribute("userName")?.Value;
                    var rawPassword = network?.Attribute("rawpassword")?.Value;
                    var password    = rawPassword ?? RsaDecryptWithPrivate(network?.Attribute("password")?.Value, privateKey);
                    var enableSsl   = network?.Attribute("enableSsl")?.Value;

                    var keys = RsaGenerateKeys();
                    network?.SetAttributeValue("password", RsaEncryptWithPublic(password, keys.Public));
                    network?.Attribute("rawpassword")?.Remove();
                    doc.Save(xmlPath);

                    db.Keys.AddOrUpdate(new Key {
                        Id = "email_private", Value = keys.Private
                    });
                    db.Keys.AddOrUpdate(new Key {
                        Id = "email_public", Value = keys.Public
                    });
                    db.SaveChanges();

                    var mailMessage = new MailMessage(address, Email)
                    {
                        IsBodyHtml = true,
                        Body       = emailBody,
                        Subject    = emailSubject
                    };

                    var smtpClient = new SmtpClient(host, port)
                    {
                        Credentials = new NetworkCredential()
                        {
                            UserName = userName,
                            Password = password
                        },
                        EnableSsl = Convert.ToBoolean(enableSsl)
                    };

                    smtpClient.Send(mailMessage);
                    return(ActionStatus.Success);
                }
                catch (Exception)
                {
                    if (db.Database.Connection.State == ConnectionState.Open)
                    {
                        db.Database.Connection.Close();
                    }
                    return(ActionStatus.SendingEmailFailure);
                }
            }
        }
Ejemplo n.º 14
0
        public ActionStatus SendActivationLink()
        {
            using (var db = new ProjectDbContext())
            {
                var activationTime        = DateTime.Now;
                var activationRequestGuid = Guid.NewGuid();

                try
                {
                    var dbUser = db.Users.Single(u => u.Email == ActivationEmail);
                    if (Convert.ToBoolean(dbUser.IsActivated))
                    {
                        return(ActionStatus.AccountAlreadyActivated);
                    }

                    Id       = dbUser.Id;
                    UserName = dbUser.UserName;
                    Email    = dbUser.Email;

                    var sbEmailBody = new StringBuilder();
                    sbEmailBody.Append("Witaj Użytkowniku: " + UserName + ",<br/><br/>");
                    sbEmailBody.Append("Poprosiłeś o aktywację konta na naszej stronie. Aktywacji możesz dokonać poprzez wpisanie Kodu Atywacyjnego na stronie Rejestracji.");
                    sbEmailBody.Append("<br/><br/>");
                    sbEmailBody.Append("Twój Kod Aktywacyjny:");
                    sbEmailBody.Append("<br/>");
                    sbEmailBody.Append("<b>" + activationRequestGuid + "</b>");
                    sbEmailBody.Append("<br/><br/>");
                    sbEmailBody.Append("Pozdrawiamy");
                    sbEmailBody.Append("<br/>");
                    sbEmailBody.Append("Imprezy Wokół Nas");

                    var sendEmailResult = SendEmail("Imprezy Wokół Nas - Aktywacja Konta", sbEmailBody.ToString());

                    if (sendEmailResult == ActionStatus.SendingEmailFailure)
                    {
                        return(sendEmailResult);
                    }

                    db.ActivationRequests.Add(new ActivationRequest()
                    {
                        Id     = activationRequestGuid,
                        UserId = Id,
                        ActivationRequestDateTime = activationTime
                    });
                    db.SaveChanges();

                    return(ActionStatus.Success);
                }
                catch (Exception)
                {
                    return(ActionStatus.DatabaseError);
                }
                finally
                {
                    if (db.Database.Connection.State == ConnectionState.Open)
                    {
                        db.Database.Connection.Close();
                    }
                }
            }
        }
Ejemplo n.º 15
0
        public string IsRemindPasswordOldPasswordValid(string remindPasswordOldPassword, string remindPasswordEmail)
        {
            using (var db = new ProjectDbContext())
            {
                try
                {
                    if (db.Users.Any(u => u.Email == remindPasswordEmail))
                    {
                        var currUser = db.Users.Single(u => u.Email == remindPasswordEmail);
                        var userRequestsDesc =
                            db.RemindPasswordRequests.Where(x => x.UserId == currUser.Id)
                                .OrderByDescending(x => x.RemindPasswordRequestDateTime);
                        db.RemindPasswordRequests.RemoveRange(userRequestsDesc.Skip(1));
                        db.SaveChanges();

                        if (userRequestsDesc.Count() == 1)
                        {
                            //var lastReq = userRequestsDesc.Single();
                            var isOldPasswordValid = Encryption.VerifyHash(remindPasswordOldPassword, HashAlgorithmType.SHA512, currUser.Password) == currUser.Password;

                            if (isOldPasswordValid)
                            {
                                return JsonConvert.SerializeObject(new
                                {
                                    Message = "",
                                    Result = UserActionResult.Success,
                                    ResultString = Enum.GetName(typeof(UserActionResult), UserActionResult.Success)
                                });
                            }
                        }
                    }

                    return JsonConvert.SerializeObject(new
                    {
                        Message = "Stare Hasło dla użytkownika o podanym Emailu jest błędne",
                        Result = UserActionResult.Failure,
                        ResultString = Enum.GetName(typeof(UserActionResult), UserActionResult.Failure)
                    });
                }
                catch (Exception)
                {
                    return JsonConvert.SerializeObject(new
                    {
                        Message = "Baza Danych nie odpowiada",
                        Result = UserActionResult.DatabaseError,
                        ResultString = Enum.GetName(typeof(UserActionResult), UserActionResult.DatabaseError)
                    });
                }
                finally
                {
                    if (db.Database.Connection.State == ConnectionState.Open)
                        db.Database.Connection.Close();
                }
            }
        }
Ejemplo n.º 16
0
        public UserActionResult Authenticate(bool useHash = false)
        {
            using (var db = new ProjectDbContext())
            {
                try
                {
                    db.Configuration.ValidateOnSaveEnabled = false; // wyłącz walidację pól podczas logowania
                    var dbUsers = db.Users.Where(u => u.UserName.Equals(UserName)).ToList();
                    var dbUserCount = dbUsers.Count;

                    if (dbUserCount < 1)
                        return UserActionResult.UserDoesNotExist;
                    if (dbUserCount > 1)
                        throw new Exception("Istnieje więcej niż jeden użytkownik o podanej nazwie");

                    var dbUser = dbUsers.Single();

                    var password = !useHash ? Encryption.VerifyHash(Password ?? "", HashAlgorithmType.SHA512, dbUser.Password) : Password;

                    Id = dbUser.Id;
                    UserName = dbUser.UserName;
                    Password = dbUser.Password;
                    Email = dbUser.Email;
                    RegistrationDate = dbUser.RegistrationDate;
                    RetryAttempts = dbUser.RetryAttempts;
                    IsLocked = dbUser.IsLocked;
                    LockedDateTime = dbUser.LockedDateTime;
                    IsActivated = dbUser.IsActivated;

                    if (Convert.ToBoolean(dbUser.IsLocked)) // Konto Zablokowane
                    {
                        int secondsToUnlock;
                        if (LockedDateTime != null)
                            secondsToUnlock = (int) (15 * 60 - DateTime.Now.Subtract((DateTime)LockedDateTime).TotalSeconds);
                        else
                            throw new NullReferenceException();

                        if (secondsToUnlock >= 0)
                            return UserActionResult.AccountLocked;

                        dbUser.IsLocked = 0;
                        dbUser.RetryAttempts = 0;
                        IsLocked = dbUser.IsLocked;
                        RetryAttempts = dbUser.RetryAttempts;
                    }

                    if (!Convert.ToBoolean(dbUser.IsActivated)) // Konto Nieaktywowane
                        return UserActionResult.AccountNotActivated;

                    if (dbUser.Password == password) // Hasło Poprawne i Konto bez flag
                    {
                        dbUser.RetryAttempts = 0;
                        dbUser.IsLocked = 0;
                        IsLocked = dbUser.IsLocked;
                        RetryAttempts = dbUser.RetryAttempts;
                        db.SaveChanges();

                        Password = password;

                        return UserActionResult.Success;
                    }

                    if (dbUser.RetryAttempts == null)
                        dbUser.RetryAttempts = 0;

                    dbUser.RetryAttempts++;
                    RetryAttempts = dbUser.RetryAttempts;

                    if (dbUser.RetryAttempts <= 3) // Hasło Niepoprawne i liczba prób mniejsza lub równa 3
                    {
                        db.SaveChanges();
                        return UserActionResult.Failure;
                    }

                    dbUser.LockedDateTime = DateTime.Now; // Hasło Niepoprawne i liczba prób większa niż 3
                    dbUser.IsLocked = 1;
                    LockedDateTime = dbUser.LockedDateTime;
                    IsLocked = dbUser.IsLocked;
                    db.SaveChanges();
                    db.Configuration.ValidateOnSaveEnabled = true;
                    return UserActionResult.AccountLocked;
                }
                catch (Exception)
                {
                    return UserActionResult.DatabaseError;
                }
                finally
                {
                    if (db.Database.Connection.State == ConnectionState.Open)
                        db.Database.Connection.Close();
                }
            }
        }
Ejemplo n.º 17
0
 public string IsUserNameAvailable(string userName)
 {
     //Thread.Sleep(3000);
     using (var db = new ProjectDbContext())
     {
         try
         {
             var isUserNameAvailable = !db.Users.Any(x => x.UserName == userName); // nie wymaga case sensitive, bo jest porównywany w bd
             return JsonConvert.SerializeObject(new
             {
                 Message = isUserNameAvailable ? "" : "Nazwa Użytkownika jest już używana",
                 Result = isUserNameAvailable ? UserActionResult.Success : UserActionResult.Failure,
                 ResultString = isUserNameAvailable ? Enum.GetName(typeof (UserActionResult), UserActionResult.Success) : Enum.GetName(typeof (UserActionResult), UserActionResult.Failure)
             });
         }
         catch (Exception ex)
         {
             return JsonConvert.SerializeObject(new
             {
                 Message = "Baza Danych nie odpowiada",
                 Result = UserActionResult.DatabaseError,
                 ResultString = Enum.GetName(typeof (UserActionResult), UserActionResult.DatabaseError)
             });
         }
         finally
         {
             if (db.Database.Connection.State == ConnectionState.Open)
                 db.Database.Connection.Close();
         }
     }
 }
Ejemplo n.º 18
0
        public ActionStatus Authenticate(bool useHash = false)
        {
            using (var db = new ProjectDbContext())
            {
                try
                {
                    db.Configuration.ValidateOnSaveEnabled = false; // wyłącz walidację pól podczas logowania
                    var dbUsers     = db.Users.Where(u => u.UserName.Equals(UserName)).ToList();
                    var dbUserCount = dbUsers.Count;

                    if (dbUserCount < 1)
                    {
                        return(ActionStatus.UserDoesNotExist);
                    }
                    if (dbUserCount > 1)
                    {
                        throw new Exception("Istnieje więcej niż jeden użytkownik o podanej nazwie");
                    }

                    var dbUser = dbUsers.Single();

                    var password = !useHash?VerifyHash(Password ?? "", HashAlgorithmType.SHA512, dbUser.Password) : Password;

                    Id               = dbUser.Id;
                    UserName         = dbUser.UserName;
                    Password         = dbUser.Password;
                    Email            = dbUser.Email;
                    RegistrationDate = dbUser.RegistrationDate;
                    RetryAttempts    = dbUser.RetryAttempts;
                    IsLocked         = dbUser.IsLocked;
                    LockedDateTime   = dbUser.LockedDateTime;
                    IsActivated      = dbUser.IsActivated;

                    if (Convert.ToBoolean(dbUser.IsLocked)) // Konto Zablokowane
                    {
                        int secondsToUnlock;
                        if (LockedDateTime != null)
                        {
                            secondsToUnlock = (int)(15 * 60 - DateTime.Now.Subtract((DateTime)LockedDateTime).TotalSeconds);
                        }
                        else
                        {
                            throw new NullReferenceException();
                        }

                        if (secondsToUnlock >= 0)
                        {
                            return(ActionStatus.AccountLocked);
                        }

                        dbUser.IsLocked      = 0;
                        dbUser.RetryAttempts = 0;
                        IsLocked             = dbUser.IsLocked;
                        RetryAttempts        = dbUser.RetryAttempts;
                    }

                    if (!Convert.ToBoolean(dbUser.IsActivated)) // Konto Nieaktywowane
                    {
                        return(ActionStatus.AccountNotActivated);
                    }

                    if (dbUser.Password == password) // Hasło Poprawne i Konto bez flag
                    {
                        dbUser.RetryAttempts = 0;
                        dbUser.IsLocked      = 0;
                        IsLocked             = dbUser.IsLocked;
                        RetryAttempts        = dbUser.RetryAttempts;
                        dbUser.CurrentIp     = ConvertIpToUint(GetIpAddress());
                        db.SaveChanges();

                        Password = password;

                        return(ActionStatus.Success);
                    }

                    if (dbUser.RetryAttempts == null)
                    {
                        dbUser.RetryAttempts = 0;
                    }

                    dbUser.RetryAttempts++;
                    RetryAttempts = dbUser.RetryAttempts;

                    if (dbUser.RetryAttempts <= 3) // Hasło Niepoprawne i liczba prób mniejsza lub równa 3
                    {
                        db.SaveChanges();
                        return(ActionStatus.Failure);
                    }

                    dbUser.LockedDateTime = DateTime.Now; // Hasło Niepoprawne i liczba prób większa niż 3
                    dbUser.IsLocked       = 1;
                    LockedDateTime        = dbUser.LockedDateTime;
                    IsLocked = dbUser.IsLocked;
                    db.SaveChanges();
                    db.Configuration.ValidateOnSaveEnabled = true;
                    return(ActionStatus.AccountLocked);
                }
                catch (Exception)
                {
                    return(ActionStatus.DatabaseError);
                }
                finally
                {
                    if (db.Database.Connection.State == ConnectionState.Open)
                    {
                        db.Database.Connection.Close();
                    }
                }
            }
        }