public bool IsUsernameTaken(string username)
 {
     using (var db = new SleepLogAppEntities())
     {
         return(db.User.Any(x => x.Username == username));
     }
 }
 public bool IsEmailTaken(string email)
 {
     using (var db = new SleepLogAppEntities())
     {
         return(db.User.Any(x => x.Email == email));
     }
 }
        public ActionResult VerifyAccount(string id)
        {
            bool Status = false;

            using (var db = new SleepLogAppEntities())
            {
                db.Configuration.ValidateOnSaveEnabled = false; //to avoid confirm password does not match on save in db
                User verifyUser = db.User.Where(x => x.ActivationCode == new Guid(id)).FirstOrDefault();
                if (verifyUser != null)
                {
                    verifyUser.IsEmailVerified = true;
                    Status = true;

                    #region //sleep deInitializer

                    for (int i = 0; i < verifyUser.Sleep.Count; i++)
                    {
                        //verifyUser.Sleep.Remove(verifyUser.Sleep.ToList()[i]);
                        db.Sleep.Remove(verifyUser.Sleep.ToList()[i]);
                    }
                    #endregion

                    db.SaveChanges();
                }
                ViewBag.Status = Status;
            }
            return(View());
        }
        public ActionResult Login(UserLogin userLogin, string returnUrl = "")
        {
            int REMEMBER_ME_TIME     = 525600; //YEAR IN MINUTES
            int NOT_REMEMBER_ME_TIME = 20;

            string Message = string.Empty;

            using (var db = new SleepLogAppEntities())
            {
                var user = db.User.Where(x => x.Username == userLogin.Username).FirstOrDefault();
                if (user != null)
                {
                    bool userAndPasswordMatch = string.Compare(Crypto.Hash(userLogin.Password), user.Password) == 0;
                    if (userAndPasswordMatch)
                    {
                        int    timeout   = userLogin.RememberMe ? REMEMBER_ME_TIME : NOT_REMEMBER_ME_TIME;
                        var    ticket    = new FormsAuthenticationTicket(userLogin.Username, userLogin.RememberMe, timeout);
                        string encrypted = FormsAuthentication.Encrypt(ticket);
                        var    cookie    = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
                        cookie.Expires  = DateTime.Now.AddMinutes(timeout);
                        cookie.HttpOnly = true;
                        Response.Cookies.Add(cookie);
                        //Session["userId"] = user.UserId;

                        if (Url.IsLocalUrl(returnUrl))
                        {
                            return(Redirect(returnUrl));
                        }
                        else
                        {
                            return(RedirectToAction("Index", "Home"));
                        }
                    }
                    else
                    {
                        Message = "Username and password not match.";
                        ModelState.AddModelError("UserValidation", "Username and password not match.");
                    }
                }
                else
                {
                    Message = string.Format("We don't know username called {0}", userLogin.Username);
                }
            }

            ViewBag.Message = Message;
            return(View());
        }
Пример #5
0
        public ActionResult Stats()
        {
            var db = new SleepLogAppEntities();

            //int userId = (int)Session["userId"];
            string username = HttpContext.User.Identity.Name;

            int?userId = db.User.Where(x => x.Username == username).FirstOrDefault().UserId;

            if (userId != null)
            {
                int          LOGS_TO_STATS = 7;
                List <Sleep> sleepList     = new List <Sleep>();

                var sleeps = db.Sleep.Where(sleep => sleep.UserId == userId).ToList();

                if (sleeps.Count < LOGS_TO_STATS)
                {
                    LOGS_TO_STATS = sleeps.Count;
                }
                for (int i = 1; i <= LOGS_TO_STATS; i++)
                {
                    sleepList.Add(sleeps[sleeps.Count - i]);
                }

                sleepList.Reverse();

                List <ChartInfo> chartList = new List <ChartInfo>();
                TimeSpan         mean      = new TimeSpan();
                TimeSpan         sum       = new TimeSpan();
                foreach (Sleep item in sleepList)
                {
                    sum += (TimeSpan)item.AmountOfSleep;
                    chartList.Add(new ChartInfo(item.AmountOfSleep, item.StartSleep.Date));
                }

                var meanTicks = sum.Ticks / chartList.Count;
                mean = TimeSpan.FromTicks(meanTicks);
                string meanString = string.Format("{0:00}h {1:00}m", mean.Hours, mean.Minutes);

                ViewBag.Mean = meanString;
                return(View(chartList));
            }
            return(RedirectToAction("Login", "User"));
        }
Пример #6
0
        public ActionResult Index()
        {
            // Po nicku dużo wolniej niż po id, ale trzeba zastosować
            //mechanizm Sesji albo wystarczy Viebag?

            //int? id = (int?)Session["userId"];
            //int id = int.Parse(HttpContext.Session["userId"].ToString());
            string username = HttpContext.User.Identity.Name;

            var db = new SleepLogAppEntities();

            if (db.User.Any(u => u.Username == username))
            {
                User user = db.User.First(u => u.Username == username);
                return(View(user));
            }
            else
            {
                return(RedirectToAction("Login", "User"));
            }
        }
        public ActionResult Registration(
            [Bind(Exclude = "IsEmailVerified, LastLoginDate, ActivationCode, " +
                            "SleepTemporary, Sleep")] User user)
        {
            bool   Status  = false;
            string Message = string.Empty;

            //Model Validation
            if (ModelState.IsValid)
            {
                user.IsEmailVerified = false;
                user.CreatedDate     = DateTime.Now;

                #region //Email is taken
                bool isEmailTaken = IsEmailTaken(user.Email);
                if (isEmailTaken)
                {
                    ModelState.AddModelError("EmailExist", "Email already exist");
                    return(View(user));
                }
                #endregion
                #region //username is taken
                bool isUsernameTaken = IsUsernameTaken(user.Username);
                if (isUsernameTaken)
                {
                    ModelState.AddModelError("UsernameExist", "Username already exist");
                    return(View(user));
                }
                #endregion

                #region //Generate activation code
                user.ActivationCode = Guid.NewGuid();
                #endregion

                #region //Password Hashing
                user.Password        = Crypto.Hash(user.Password);
                user.ConfirmPassword = Crypto.Hash(user.ConfirmPassword);
                #endregion

                #region //Save to db and initialize sleeps
                using (var db = new SleepLogAppEntities())
                {
                    db.User.Add(user);

                    #region //sleep initializer
                    var SleepList = SleepsInitializer.SleepsInitialize();
                    foreach (Sleep sleep in SleepList)
                    {
                        sleep.SetAmountOfSleep(); //możnaby przerzucić do SleepInitializer
                        user.Sleep.Add(sleep);
                    }
                    #endregion

                    db.SaveChanges();
                }
                #endregion

                #region //Send activation mail to user
                SendVeryficationLinkEmail(user.Email, user.ActivationCode.ToString());
                Message = "Registration succesfully done. Account activation link "
                          + "has been sent to your email adress:" + user.Email;
                Status = true;
                #endregion
            }
            else
            {
                Message = "Invalid Request";
            }

            ViewBag.Message = Message;
            ViewBag.Status  = Status;
            return(View(user));
        }