public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    changePasswordSucceeded = CodeFirstSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return(RedirectToAction("ChangePasswordSuccess"));
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
示例#2
0
 public ActionResult ConfirmManually(ConfirmationModel model)
 {
     if (ModelState.IsValid)
     {
         User user = AccountServices.FindUser(usr => usr.Username == model.UserName);
         if (user == null)
         {
             ModelState.AddModelError("UserName", Resources.AppMessages.Error_User_Not_Exist);
             return(View(model));
         }
         else
         {
             if (user.IsConfirmed)
             {
                 ModelState.AddModelError("UserName", Resources.AppMessages.Error_User_Confirmed_Yet);
                 return(View(model));
             }
         }
         if (CodeFirstSecurity.ConfirmAccount(model.Token) == false)
         {
             ModelState.AddModelError("Token", Resources.AppMessages.Error_ConfirmationToken);
         }
         else
         {
             FormsAuthentication.SetAuthCookie(model.UserName, false);
             return(RedirectToRoute("Default", new { controller = "Account", action = "RegistrationSuccesfull" }));
         }
     }
     return(View());
 }
示例#3
0
 public ActionResult LogOn(LogOnModel model, string returnUrl)
 {
     if (ModelState.IsValid)
     {
         if (CodeFirstSecurity.Login(model.UserName, model.Password, model.RememberMe))
         {
             if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
             {
                 return(Redirect(returnUrl));
             }
             else
             {
                 if (TempData["returnUrl"] != null)
                 {
                     string url = TempData["returnUrl"].ToString();
                     TempData.Remove("returnUrl");
                     return(Redirect(url));
                 }
                 else
                 {
                     return(RedirectToRoute("Default", new { controller = "Home", action = "Index" }));
                 }
             }
         }
         else
         {
             ModelState.AddModelError("", "El usuario o contraseña son incorrectos");
         }
     }
     return(View(model));
 }
示例#4
0
        public ActionResult ConfirmResetAccount(ChangePasswordModel model)
        {
            ViewBag.Token = model.ConfirmationToken;
            ViewBag.User  = model.UserName;
            string recaptchaprivatekey = BgResources.Recaptcha_PrivateKeyHttp;

            try
            {
                if (!ReCaptcha.Validate(privateKey: recaptchaprivatekey))
                {
                    ModelState.AddModelError("recaptcha", Resources.AppMessages.Error_Recaptcha);
                }
            }
            catch (Exception)
            {
                ModelState.AddModelError("recaptcha", Resources.AppMessages.Error_Recaptcha_Key);
            }

            if (ModelState.IsValid)
            {
                if (CodeFirstSecurity.ResetPassword(model.ConfirmationToken, model.NewPassword))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false);
                    return(RedirectToRoute("Default", new { controller = "Account", action = "ResetAccountSuccesfull" }));
                }
                else
                {
                    ModelState.AddModelError("", Resources.AppMessages.Error_ResetAccount);
                }
                ViewBag.Token    = model.ConfirmationToken;
                ViewBag.UserName = model.UserName;
            }
            return(View());
        }
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (CodeFirstSecurity.Login(model.UserName, model.Password))
                {
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                        !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
示例#6
0
        public ActionResult ConfirmAccount(string id, string user)
        {
            //string confirmationToken = id.Replace("backslash", "/").Replace("percent", "%").Replace("ampersand", "&").Replace("space", " ");
            User userobj = AccountServices.FindUser(usr => usr.Username == user);

            if ((userobj != null) && (userobj.IsConfirmed == true))
            {
                throw new Exception(String.Format(Resources.AppMessages.Error_User_Is_Confirmed, user));
            }
            try
            {
                if (CodeFirstSecurity.ConfirmAccount(id))
                {
                    FormsAuthentication.SetAuthCookie(user, false);
                    return(RedirectToRoute("Default", new { controller = "Account", action = "RegistrationSuccesfull" }));
                }
                else
                {
                    throw new Exception(Resources.AppMessages.Error_ConfirmAccount);
                }
            }
            catch (Exception)
            {
                throw new Exception(Resources.AppMessages.Error_ConfirmAccount);
            }
        }
示例#7
0
        public ActionResult Login(FormCollection collection, string returnUrl)
        {
            string userMail, userPwd;

            userMail = collection["email"];
            userPwd  = collection["password"];
            bool rememberMe = (collection["forgetPWD"] == "on" ? true : false);

            if (ModelState.IsValid)
            {
                if (CodeFirstSecurity.Login(userMail, userPwd, rememberMe))
                {
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                        !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return(View());
        }
示例#8
0
    /// <summary>
    /// Create a new reply in an existing thread.
    /// Adding a reply to an existing thread will notify all subscribed and connected clients.
    /// </summary>
    /// <param name="parentId">Id of the parent comment.</param>
    /// <param name="replyText">Text of the reply.</param>
    public void NewReply(int parentId, string replyText)
    {
        User    currentUser   = db.Users.Find(CodeFirstSecurity.GetUserId(Context.User.Identity.Name));
        Comment comment       = new Comment(replyText, currentUser);
        Comment parentComment = db.Comments.Include("Comments").First(pc => pc.CommentId == parentId);

        if (parentComment.SubjectId != null)
        {
            comment.SubjectId = parentComment.SubjectId;
        }
        else
        {
            comment.SubjectId = parentComment.CommentId;
        }

        comment.ParentCommentId = parentComment.CommentId;

        Comment thread = db.Comments.Find(comment.SubjectId);

        thread.LastUpdatedTime = DateTime.UtcNow;

        parentComment.Comments.Add(comment);

        // For all subscribed users other than the current user, mark this comment as unread.
        List <Guid> subscribers = new List <Guid>();

        foreach (Subscription subscriber in db.Subscriptions.Include("User").Where(x => x.Subject.CommentId == comment.SubjectId))
        {
            subscribers.Add(subscriber.User.UserId);
            if (subscriber.User.UserId != currentUser.UserId)
            {
                db.UnreadItems.Add(new UnreadItem {
                    User = subscriber.User, Comment = comment
                });
            }
        }

        db.SaveChanges();

        Message sendMessage = new Message()
        {
            text       = Palaver2.Helpers.CustomHtmlHelpers.BuildComments(comment, null),
            parentId   = parentId,
            commentId  = comment.CommentId,
            userid     = currentUser.UserId.ToString(),
            threadId   = comment.SubjectId,
            authorName = comment.User.Username
        };

        // Loop through the connections and if they're subscribed to this
        // thread then update them.
        foreach (String connectionId in userIdsByConnection.Keys)
        {
            if (subscribers.Contains(userIdsByConnection[connectionId]))
            {
                Clients.Client(connectionId).addReply(sendMessage);
            }
        }
    }
示例#9
0
    /// <summary>
    /// Unsubscribe the current user from the specified thread.
    /// </summary>
    /// <param name="threadId"></param>
    public void Unsubscribe(int threadId)
    {
        User         currentUser = db.Users.Find(CodeFirstSecurity.GetUserId(Context.User.Identity.Name));
        Subscription sub         = db.Subscriptions.Where(x => x.Subject.CommentId == threadId && x.User.UserId == currentUser.UserId).Single();

        db.Subscriptions.Remove(sub);
        db.SaveChanges();
    }
示例#10
0
        public ActionResult Register(RegisterModel model)
        {
            string recaptchaprivatekey = BgResources.Recaptcha_PrivateKeyHttp;

            try
            {
                if (!ReCaptcha.Validate(privateKey: recaptchaprivatekey))
                {
                    ModelState.AddModelError("recaptcha", Resources.AppMessages.Error_Recaptcha);
                }
            }
            catch (Exception)
            {
                ModelState.AddModelError("recaptcha", Resources.AppMessages.Error_Recaptcha_Key);
            }

            if (ModelState.IsValid)
            {
                string token = null;
                try
                {
                    token = CodeFirstSecurity.CreateAccount(model.UserName, model.Password, model.Email, model.FirstName, model.LastName, model.TimeZone, model.Culture, requireConfirmationToken: true);
                    SmtpClient client = new SmtpClient {
                        Host = BgResources.Email_Server, Port = Int32.Parse(BgResources.Email_SmtpPort), EnableSsl = BgResources.Email_SSL, Credentials = new NetworkCredential(BgResources.Email_UserName, BgResources.Email_Password)
                    };
                    UserMailer.Register(token, model.Email, AccountServices.FindUser(usr => usr.Username == model.UserName)).Send(new SmtpClientWrapper {
                        InnerSmtpClient = client
                    });
                    ViewBag.Email = model.Email;
                    return(View("CompleteRegister"));
                }
                catch (MembershipCreateUserException ex)
                {
                    if ((ex.StatusCode == MembershipCreateStatus.DuplicateUserName) || (ex.StatusCode == MembershipCreateStatus.InvalidUserName))
                    {
                        ModelState.AddModelError("UserName", ErrorCodeToString(ex.StatusCode));
                    }
                    else if ((ex.StatusCode == MembershipCreateStatus.DuplicateEmail) || (ex.StatusCode == MembershipCreateStatus.InvalidEmail))
                    {
                        ModelState.AddModelError("Email", ErrorCodeToString(ex.StatusCode));
                    }
                    else if (ex.StatusCode == MembershipCreateStatus.InvalidPassword)
                    {
                        ModelState.AddModelError("Password", ErrorCodeToString(ex.StatusCode));
                    }
                    else
                    {
                        ModelState.AddModelError("", ErrorCodeToString(ex.StatusCode));
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(Resources.AppMessages.Error_SendMail);
                }
            }
            return(View(model));
        }
示例#11
0
        private void CheckForAdminUser()
        {
            var roles = CodeFirstRoleServices.GetUsersInRole(BgResources.Security_AdminRole);

            if (roles.Length == 0)
            {
                CodeFirstSecurity.CreateAccount(BgResources.Security_AdminRole, "admin", BgResources.Email_UserName, false);
                CodeFirstRoleServices.AddUsersToRoles(new string[] { "admin" }, new string[] { BgResources.Security_AdminRole, BgResources.Security_PremiumRole });
            }
        }
示例#12
0
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                CodeFirstSecurity.CreateAccount(model.UserName, model.Password, model.Email);

                FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                return(RedirectToAction("Index", "Home"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
示例#13
0
        public ActionResult ResetAccount(ResetAccountModel model)
        {
            string recaptchaprivatekey = BgResources.Recaptcha_PrivateKeyHttp;

            try
            {
                if (!ReCaptcha.Validate(privateKey: recaptchaprivatekey))
                {
                    ModelState.AddModelError("recaptcha", Resources.AppMessages.Error_Recaptcha);
                }
            }
            catch (Exception)
            {
                ModelState.AddModelError("recaptcha", Resources.AppMessages.Error_Recaptcha_Key);
            }

            if (ModelState.IsValid)
            {
                User user = AccountServices.FindUser(usr => usr.Email == model.Email);
                if (user == null)
                {
                    ModelState.AddModelError("Email", Resources.AppMessages.Error_Email_Not_Exist);
                    return(View(model));
                }
                try
                {
                    string token = null;
                    token = CodeFirstSecurity.GeneratePasswordResetToken(user.Username, tokenExpirationInMinutesFromNow: 1440);
                    SmtpClient client = new SmtpClient {
                        Host = BgResources.Email_Server, Port = Int32.Parse(BgResources.Email_SmtpPort), EnableSsl = BgResources.Email_SSL, Credentials = new NetworkCredential(BgResources.Email_UserName, BgResources.Email_Password)
                    };
                    UserMailer.PasswordReset(token, user).Send(new SmtpClientWrapper {
                        InnerSmtpClient = client
                    });
                    ViewBag.Email = model.Email;
                    return(View("CompleteResetAccount"));
                }
                catch (InvalidOperationException ex)
                {
                    ModelState.AddModelError("UserName", ex.Message);
                }
                catch (Exception ex)
                {
                    throw new SmtpException(Resources.AppMessages.Error_SendMail);
                }
            }
            return(View(model));
        }
示例#14
0
        /// <summary>
        /// Create new User in Blog
        /// </summary>
        /// <param name="username">Name of the user</param>
        /// <param name="password">Password</param>
        /// <param name="email">Email</param>
        /// <param name="firstname">The FirstName</param>
        /// <param name="lastname">The Lastname</param>
        /// <param name="timezone">The Time Zone for the user</param>
        /// <param name="culture">Culture</param>
        /// <param name="requireconfirmation">Always true because the acccount is confirmed inmediately</param>
        /// <param name="selectedroles">Bunch of roles for the user being created</param>
        public void CreateAccount(string username, string password, string email, string firstname, string lastname, string timezone, string culture, bool requireconfirmation, string[] selectedroles)
        {
            var token = CodeFirstSecurity.CreateAccount(username, password, email, firstname, lastname, timezone, culture, requireconfirmation);

            if (selectedroles.Length == 0)
            {
                CodeFirstRoleServices.RemoveUsersFromRoles(new string[1] {
                    username
                }, CodeFirstRoleServices.GetAllRoles());
            }
            else
            {
                CodeFirstRoleServices.RemoveUsersFromRoles(new string[1] {
                    username
                }, CodeFirstRoleServices.GetAllRoles());
                CodeFirstRoleServices.AddUsersToRoles(new string[1] {
                    username
                }, selectedroles);
            }
        }
示例#15
0
        public ActionResult ResetPassword(string username)
        {
            if (username != null && CodeFirstSecurity.UserExists(username))
            {
                MembershipUser user = Membership.GetUser(username);

                string token = CodeFirstSecurity.GeneratePasswordResetToken(username);

                SmtpClient smtp = new SmtpClient("localhost", 25);

                MailMessage message = new MailMessage();
                message.Body = "Go here to reset you password...  http://" + HttpContext.Request.Url.Authority + "/Account/ResetPasswordNew?token=" + Server.UrlEncode(token);
                message.From = new MailAddress("*****@*****.**");
                message.To.Add(new MailAddress(user.Email));
                message.Subject = "You suck!";

                smtp.Send(message);
            }

            return(RedirectToAction("ResetPasswordEmailSent"));
        }
示例#16
0
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                try
                {
                    CodeFirstSecurity.CreateAccount(model.UserName, model.Password, model.Email, false);

                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    return(RedirectToAction("Index", "Home"));
                }
                catch (MembershipCreateUserException ex)
                {
                    ModelState.AddModelError("", ErrorCodeToString(ex.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
示例#17
0
        public ActionResult ResetPasswordNew(ResetPasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            if (HttpContext.Session["passwordresettoken"] == null)
            {
                return(View("ResetPassword"));
            }

            string token = HttpContext.Session["passwordresettoken"].ToString();

            if (CodeFirstSecurity.ResetPassword(token, model.NewPassword))
            {
                return(RedirectToAction("ResetPasswordSuccess"));
            }
            else
            {
                return(RedirectToAction("ResetPassword"));
            }
        }
示例#18
0
 public override Task OnReconnected()
 {
     userIdsByConnection.Add(Context.ConnectionId, db.Users.Find(CodeFirstSecurity.GetUserId(Context.User.Identity.Name)).UserId);
     System.Diagnostics.Debug.WriteLine("Reonnected ConnectionId: " + Context.ConnectionId);
     return(base.OnReconnected());
 }
示例#19
0
 public ActionResult LogOff()
 {
     CodeFirstSecurity.Logout();
     return(RedirectToRoute("Default", new { controller = "Home", action = "Index" }));
 }