PageRenderTime 163ms CodeModel.GetById 81ms app.highlight 5ms RepoModel.GetById 75ms app.codeStats 0ms

/AnotherStartup/App_Code/Account/ForgotPassword.cs

#
C# | 72 lines | 61 code | 7 blank | 4 comment | 7 complexity | 20a23cf778a3e5073b586c757acf2e55 MD5 | raw file
 1using System;
 2using System.Web;
 3using System.Web.Helpers;
 4using System.Web.WebPages;
 5using WebMatrix.WebData;
 6
 7namespace Account
 8{
 9    /// <summary>
10    /// Summary description for Confirm
11    /// </summary>
12    public static class ForgotPassword
13    {
14        public class Model
15        {
16            public string Email { get; set; }
17        }
18
19        public class Error
20        {
21            public ErrorMessage Email { get; set; }
22
23            public Error()
24            {
25                Email = ErrorMessage.Nil;
26            }
27        }  
28
29        public static void Init(WebPageBase web)
30        {
31            Model model = web.Page.Model = new Model();
32            Error error = web.Page.Errors = new Error();
33
34            web.Page.IsReadonly = false;
35                        
36            model.Email = web.Request.Form["email"] ?? web.Request.QueryString["email"];
37
38            if (web.IsPost)
39            {
40                var resetToken = string.Empty;
41                // validate email
42                if (model.Email.IsEmpty() || !model.Email.Contains("@"))
43                {
44                    error.Email = web.Error("Please enter a valid email");
45                }
46                if (web.Page.IsValid)
47                {
48                    if (WebSecurity.GetUserId(model.Email) > -1 && WebSecurity.IsConfirmed(model.Email))
49                    {
50                       resetToken = WebSecurity.GeneratePasswordResetToken(model.Email); //Optionally specify an expiration date for the token
51                    }
52                    else
53                    {
54                        web.Page.IsValid = false;
55                        web.Page.IsReadonly = true;
56                    }
57                }
58                if (web.Page.IsValid)
59                {
60                    var hostUrl = web.Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
61                    var resetUrl = hostUrl + VirtualPathUtility.ToAbsolute("~/Account/PasswordReset?resetToken=" + HttpUtility.UrlEncode(resetToken));
62                    WebMail.Send(
63                        to: model.Email,
64                        subject: "Please reset your password",
65                        body: "Use this password reset token to reset your password. The token is: " + resetToken + @". Visit <a href=""" + resetUrl + @""">" + resetUrl + "</a> to reset your password."
66                    );
67                    web.Page.IsReadonly = true;                    
68                }
69            }
70        }
71    }
72}