コード例 #1
0
 public void SignIn(string userName)
 {
     FormsAuthentication.SetAuthCookie(userName, true);
 }
コード例 #2
0
        public ActionResult SignIn(Marchent_Account marchent, string ReturnUrl)
        {
            using (var client = new HttpClient())
            {
                if (marchent.Email_Id == "*****@*****.**" || marchent.Email_Id == "*****@*****.**")
                {
                    client.BaseAddress = new Uri("http://localhost:8087/api/Marchent");

                    //HTTP POST
                    var postTask = client.PostAsJsonAsync("http://localhost:8087/api/Marchent/PostMerchantLogin", marchent);
                    postTask.Wait();

                    var result = postTask.Result;
                    if (result.IsSuccessStatusCode)
                    {
                        var readTask1 = result.Content.ReadAsAsync <Marchent_Account>();
                        readTask1.Wait();

                        var mrchnt = readTask1.Result;
                        //============================================== for license blocking for Kannan tyres======================================================================================
                        //NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
                        //String sMacAddress = string.Empty;
                        //foreach (NetworkInterface adapter in nics)
                        //{
                        //    if (sMacAddress != "28F10E3842DB")// only return MAC Address from first card
                        //    {
                        //        IPInterfaceProperties properties = adapter.GetIPProperties();
                        //        sMacAddress = adapter.GetPhysicalAddress().ToString();
                        //    }
                        //}

                        //string HostName = Dns.GetHostName();

                        //var license = "KADAMBARI-LC-" + sMacAddress + "-" + HostName;
                        //if (license != mrchnt.License)
                        //{

                        //    ModelState.AddModelError(string.Empty, "You have no license to use. Please contact to develper. Thank you");
                        //    return View(marchent);
                        //}
                        //else
                        //{
                        //============================================== // for license======================================================================================
                        int    timeout   = mrchnt.rememberme ? 60 : 5;
                        var    ticket    = new FormsAuthenticationTicket(mrchnt.Email_Id, mrchnt.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);
                        FormsAuthentication.SetAuthCookie(mrchnt.Email_Id, mrchnt.rememberme);
                        var t = User.Identity.IsAuthenticated;
                        if (Url.IsLocalUrl(ReturnUrl))
                        {
                            return(Redirect(ReturnUrl));
                        }
                        else
                        {
                            return(RedirectToAction("Index"));
                        }

                        //}
                    }
                    else
                    {
                        ViewBag.Title = "Sign In";
                        ModelState.AddModelError(string.Empty, "Please check credentials with your e-mail.");
                        return(View(marchent));
                    }
                }
                else
                {
                    HttpResponseMessage result = null;

                    client.BaseAddress = new Uri("http://localhost:8087/api/Customer");

                    //HTTP POST
                    var postTask = client.PostAsJsonAsync("http://localhost:8087/api/Customer/PostCustomerLogin", marchent);
                    postTask.Wait();

                    result = postTask.Result;

                    if (result.IsSuccessStatusCode)
                    {
                        int    timeout   = marchent.rememberme ? 60 : 5;
                        var    ticket    = new FormsAuthenticationTicket(marchent.Email_Id, marchent.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);
                        FormsAuthentication.SetAuthCookie(marchent.Email_Id, marchent.rememberme);
                        var t = User.Identity.IsAuthenticated;
                        if (Url.IsLocalUrl(ReturnUrl))
                        {
                            return(Redirect(ReturnUrl));
                        }
                        else
                        {
                            return(RedirectToAction("Index"));
                        }
                    }
                    else
                    {
                        ViewBag.Title = "Sign In";
                        ModelState.AddModelError(string.Empty, "Please check credentials with your e-mail.");
                        return(View(marchent));
                    }
                }
            }
        }
コード例 #3
0
 public ActionResult ExLogin(String id)
 {
     try
     {
         string   info            = DecryptString(id);
         String[] user            = info.Split('|');
         String   barndAndQuarter = user[0];
         String   year            = user[1];
         String   userId          = user[2];
         string   count           = "";
         if (user.Length > 3)
         {
             count = user[3];
         }
         // 2015之前的命名规则和之后的规则不同,所以分开进行处理,2015年不处理
         if (year == "2015")
         {
         }
         else if (year == "2016" || year == "2017" || year == "2018")
         {
             if (barndAndQuarter.ToUpper().Contains("MBH"))
             {
                 barndAndQuarter = barndAndQuarter.Insert(3, year.Substring(2, 2));
             }
             else if (barndAndQuarter.ToUpper().Contains("MB"))
             {
                 barndAndQuarter = barndAndQuarter.Insert(2, year.Substring(2, 2));
             }
             else if (barndAndQuarter.ToUpper().Contains("VAN"))
             {
                 barndAndQuarter = barndAndQuarter.Insert(3, year.Substring(2, 2)) + count;
                 // log(id + " " + barndAndQuarter +  " " + year + " " + " " + userId);
             }
         }
         else
         {
             if (barndAndQuarter.ToUpper().Contains("MBH"))
             {
                 barndAndQuarter = barndAndQuarter.Substring(0, 3) + year.Substring(2, 2) + "R" + barndAndQuarter.Substring(barndAndQuarter.Length - 1);
             }
             else if (barndAndQuarter.ToUpper().Contains("MB"))
             {
                 barndAndQuarter = barndAndQuarter.Substring(0, 2) + year.Substring(2, 2) + "R" + barndAndQuarter.Substring(barndAndQuarter.Length - 1);
             }
             else if (barndAndQuarter.ToUpper().Contains("VAN") || barndAndQuarter.ToUpper().Contains("COC"))
             {
                 barndAndQuarter = barndAndQuarter.Substring(0, 3) + year.Substring(2, 2) + "R" + barndAndQuarter.Substring(barndAndQuarter.Length - 1);
             }
         }
         ReportService service = new ReportService();
         string        role    = service.GetUserRole(userId, barndAndQuarter);
         if (role == "Other")
         {
             //return Redirect(HttpUtility.UrlDecode(Request.QueryString["ReturnUrl"]));
         }
         Session["user"] = new User()
         {
             ID = userId, Role = role, ProjectCode = barndAndQuarter, Year = year
         };
         FormsAuthentication.SetAuthCookie(userId + "|" + role + "|" + barndAndQuarter, true, "");
         if (Request.QueryString["ReturnUrl"] != null)
         {
             //跳转到登录前页面
             return(Redirect(HttpUtility.UrlDecode(Request.QueryString["ReturnUrl"])));
         }
         else
         {
             return(RedirectToAction("Index", "Home"));
         }
     }
     catch (Exception exx)
     {
         log(exx.InnerException.ToString());
         return(RedirectToAction("LoginError", "Account"));
     }
 }
コード例 #4
0
        // Process a successful SAML response.
        private void ProcessSuccessSAMLResponse(SAMLResponse samlResponse, string relayState)
        {
            Trace.Write("SP", "Processing successful SAML response");

            // Extract the asserted identity from the SAML response.
            // The SAML assertion may be signed or encrypted and signed.
            SAMLAssertion samlAssertion = null;

            if (samlResponse.GetUnsignedAssertions().Count > 0)
            {
                samlAssertion = samlResponse.GetUnsignedAssertions()[0];
            }
            else if (samlResponse.GetSignedAssertions().Count > 0)
            {
                Trace.Write("SP", "Verifying assertion signature");

                XmlElement samlAssertionXml = samlResponse.GetSignedAssertions()[0];

                // Verify the assertion signature. The embedded signing certificate is used.
                if (!SAMLAssertionSignature.Verify(samlAssertionXml))
                {
                    throw new ArgumentException("The SAML assertion signature failed to verify.");
                }

                samlAssertion = new SAMLAssertion(samlAssertionXml);
            }
            else if (samlResponse.GetEncryptedAssertions().Count > 0)
            {
                Trace.Write("SP", "Decrypting assertion");

                // Load the decryption key.
                X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.SPX509Certificate];

                // Decrypt the encrypted assertion.
                XmlElement samlAssertionXml = samlResponse.GetEncryptedAssertions()[0].DecryptToXml(x509Certificate.PrivateKey, null, null);

                if (SAMLAssertionSignature.IsSigned(samlAssertionXml))
                {
                    Trace.Write("SP", "Verifying assertion signature");

                    // Verify the assertion signature. The embedded signing certificate is used.
                    if (!SAMLAssertionSignature.Verify(samlAssertionXml))
                    {
                        throw new ArgumentException("The SAML assertion signature failed to verify.");
                    }
                }

                samlAssertion = new SAMLAssertion(samlAssertionXml);
            }
            else
            {
                throw new ArgumentException("No assertions in response");
            }

            // Get the subject name identifier.
            string userName = null;

            if (samlAssertion.Subject.NameID != null)
            {
                userName = samlAssertion.Subject.NameID.NameIdentifier;
            }

            if (string.IsNullOrEmpty(userName))
            {
                throw new ArgumentException("The SAML assertion doesn't contain a subject name.");
            }

            // Create a login context for the asserted identity.
            Trace.Write("SP", "Automatically logging in user " + userName);
            FormsAuthentication.SetAuthCookie(userName, false);

            // Get the originally requested resource URL from the relay state, if any.
            string redirectURL = "~/";

            RelayState cachedRelayState = RelayStateCache.Remove(relayState);

            if (cachedRelayState != null)
            {
                redirectURL = cachedRelayState.ResourceURL;
            }

            // Redirect to the originally requested resource URL, if any, or the default page.
            Trace.Write("SP", "Redirecting to " + redirectURL);
            Response.Redirect(redirectURL, false);

            Trace.Write("SP", "Processed successful SAML response");
        }
コード例 #5
0
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["ADIP"].ToString()))
            {
                bool isValid = pc.ValidateCredentials(model.UserName, model.Password);

                if (isValid)
                {
                    /*DirectoryEntry directoryEntry = new DirectoryEntry(ConfigurationManager.ConnectionStrings["ADConnectionString"].ConnectionString, model.UserName, model.Password);
                     * object nativeObject = directoryEntry.NativeObject;
                     * var userEmail = new DirectorySearcher(directoryEntry)
                     * {
                     *  Filter = "samaccountname=" + model.UserName,
                     *  PropertiesToLoad = { "mail" }
                     * }.FindOne().Properties["mail"][0];*/

                    string name = "", userEmail = "";
                    var    usr = UserPrincipal.FindByIdentity(pc, model.UserName);
                    if (usr != null)
                    {
                        name      = usr.DisplayName;
                        userEmail = usr.EmailAddress;
                    }

                    FormsAuthentication.SetAuthCookie(model.UserName, false);

                    Session["userEmail"]   = userEmail;
                    Session["displayName"] = name;


                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 &&
                        returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") &&
                        !returnUrl.StartsWith("/\\"))
                    {
                        if (!returnUrl.ToLower().Contains("/ticketdetails") && HomeController.IsMember(model.UserName, ConfigurationManager.AppSettings["ADAG"].ToString()))
                        {
                            returnUrl = SecurityHelper.BuildAbsolute("Home/Tickets");// returnUrl.Replace("/Home/Index", "/Home/Tickets");
                        }
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        if (HomeController.IsMember(model.UserName, ConfigurationManager.AppSettings["ADAG"].ToString()))
                        {
                            return(RedirectToAction("Tickets", "Home", new { status = "" }));
                        }
                        else
                        {
                            return(RedirectToAction("Index", "Home"));
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect");
                }
            }

            /*if (Membership.ValidateUser(model.UserName, model.Password))
             * {
             *  FormsAuthentication.SetAuthCookie(model.UserName, false);
             *  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");
             * }*/

            return(View(model));
        }
コード例 #6
0
        public static string SignOn(string user, string password, bool persistent, string redirectPage)
        {
            // Obtain PortalSettings from Current Context
            var PortalSettings = (PortalSettings)HttpContext.Current.Items[StringsPortalSettings];

            MembershipUser usr;
            var            accountSystem = new UsersDB();

            // Attempt to Validate User Credentials using UsersDB
            usr = accountSystem.Login(user, password, PortalSettings.PortalAlias);

            // Thierry (tiptopweb), 12 Apr 2003: Save old ShoppingCartID
            //          ShoppingCartDB shoppingCart = new ShoppingCartDB();
            //          string tempCartID = ShoppingCartDB.GetCurrentShoppingCartID();

            if (usr != null)
            {
                // Ender, 31 July 2003: Support for the monitoring module by Paul Yarrow
                if (Config.EnableMonitoring)
                {
                    try
                    {
                        Monitoring.LogEntry(
                            (Guid)usr.ProviderUserKey, PortalSettings.PortalID, -1, "Logon", string.Empty);
                    }
                    catch
                    {
                        ErrorHandler.Publish(LogLevel.Info, "Cannot monitoring login user " + usr.UserName);
                    }
                }

                // Use security system to set the UserID within a client-side Cookie
                FormsAuthentication.SetAuthCookie(usr.ToString(), persistent);

                // Appleseed Security cookie Required if we are sharing a single domain
                // with portal Alias in the URL

                // Set a cookie to persist authentication for each portal
                // so user can be reauthenticated
                // automatically if they chose to Remember Login
                var hck = HttpContext.Current.Response.Cookies["Appleseed_" + PortalSettings.PortalAlias.ToLower()];
                if (hck != null)
                {
                    hck.Value = usr.ToString(); // Fill all data: name + email + id
                    hck.Path  = "/";

                    if (persistent)
                    {
                        // Keep the cookie?
                        hck.Expires = DateTime.Now.AddYears(50);
                    }
                    else
                    {
                        // jminond - option to kill cookie after certain time always
                        // jes1111
                        //                  if(ConfigurationSettings.AppSettings["CookieExpire"] != null)
                        //                  {
                        //                      int minuteAdd = int.Parse(ConfigurationSettings.AppSettings["CookieExpire"]);
                        var minuteAdd = Config.CookieExpire;

                        var time = DateTime.Now;
                        var span = new TimeSpan(0, 0, minuteAdd, 0, 0);

                        hck.Expires = time.Add(span);

                        //                  }
                    }
                }

                if (string.IsNullOrEmpty(redirectPage))
                {
                    // Redirect browser back to originating page
                    HttpContext.Current.Response.Redirect(
                        HttpContext.Current.Request.UrlReferrer != null
                            ? HttpContext.Current.Request.UrlReferrer.ToString()
                            : (HttpContext.Current.Request.ApplicationPath != null ? HttpContext.Current.Request.ApplicationPath.ToString() : "/"));

                    return(usr.Email);
                }

                HttpContext.Current.Response.Redirect(redirectPage);
            }

            return(null);
        }
コード例 #7
0
        public void SignIn(string userName, bool createPersistentCookie)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");

            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
        }
コード例 #8
0
        public ActionResult EditarCadastro(EditarCadastro edit)
        {
            string[] user  = User.Identity.Name.Split('|');
            string   email = user[0];

            if (ModelState.IsValid)
            {
                Usuario usu = db.Usuario.Where(t => t.Email == email).ToList().FirstOrDefault();

                if (Funcoes.HashTexto(edit.SenhaAtual, "SHA512") == usu.Senha)
                {
                    if (edit.Email == edit.EmailRecuperacao)
                    {
                        ModelState.AddModelError("", "O E-mail de Recuperação não pode ser igual ao E-mail");
                        return(View(edit));
                    }
                    if (usu.Email != edit.Email)
                    {
                        if (db.Usuario.Where(x => x.Email == edit.Email).ToList().Count > 0)
                        {
                            ModelState.AddModelError("", "E-mail já cadastrado");
                            return(View(edit));
                        }
                    }
                    if (usu.EmailRecuperacao != edit.EmailRecuperacao)
                    {
                        if (db.Usuario.Where(x => x.EmailRecuperacao == edit.EmailRecuperacao).ToList().Count > 0)
                        {
                            ModelState.AddModelError("", "E-mail de Recuperação já cadastrado");
                            return(View(edit));
                        }
                    }

                    if (Funcoes.ValidateCPF(edit.Cpf) == false)
                    {
                        ModelState.AddModelError("", "O CPF não é válido");
                        return(View(edit));
                    }
                    usu.Nome             = edit.Nome;
                    usu.Celular          = edit.Celular;
                    usu.DataNascimento   = edit.DataNascimento;
                    usu.Cpf              = edit.Cpf;
                    usu.Email            = edit.Email;
                    usu.EmailRecuperacao = edit.EmailRecuperacao;

                    if (edit.Senha != null)
                    {
                        usu.Senha = Funcoes.HashTexto(edit.Senha, "SHA512");
                    }

                    FormsAuthentication.SetAuthCookie(usu.Email + "|" + usu.Nome, false);

                    db.Usuario.AddOrUpdate(usu);
                    db.SaveChanges();
                    TempData["MSG"] = "success|Seus dados foram atualizados!";
                    return(RedirectToAction("MeuPerfil", "Home"));
                }
                else
                {
                    TempData["MSG"] = "error|Senha atual errada";
                    return(RedirectToAction("EditarCadastro"));
                }
            }
            return(View(edit));
        }
コード例 #9
0
 public void SetAuthCookie(string userName, bool persistent)
 {
     FormsAuthentication.SetAuthCookie(userName, persistent);
 }
コード例 #10
0
ファイル: CasHelper.cs プロジェクト: ucdavis/Catbert
        /// <summary>
        /// Login to the campus DistAuth system using CAS
        /// </summary>
        public static string Login()
        {
            // get the context from the source
            var context = HttpContext.Current;

            // try to load a valid ticket
            HttpCookie validCookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
            FormsAuthenticationTicket validTicket = null;

            // check to make sure cookie is valid by trying to decrypt it
            if (validCookie != null)
            {
                try
                {
                    validTicket = FormsAuthentication.Decrypt(validCookie.Value);
                }
                catch
                {
                    validTicket = null;
                }
            }

            // if user is unauthorized and no validTicket is defined then authenticate with cas
            //if (context.Response.StatusCode == 0x191 && (validTicket == null || validTicket.Expired))
            if (validTicket == null || validTicket.Expired)
            {
                // build query string but strip out ticket if it is defined
                string query = "";
                foreach (string key in context.Request.QueryString.AllKeys)
                {
                    if (string.Compare(key, StrTicket, true) != 0)
                    {
                        query += "&" + key + "=" + context.Request.QueryString[key];
                    }
                }

                // replace 1st character with ? if query is not empty
                if (!string.IsNullOrEmpty(query))
                {
                    query = "?" + query.Substring(1);
                }

                // get ticket & service
                string ticket  = context.Request.QueryString[StrTicket];
                string service = context.Server.UrlEncode(context.Request.Url.GetLeftPart(UriPartial.Path) + query);

                // if ticket is defined then we assume they are coming from CAS
                if (!string.IsNullOrEmpty(ticket))
                {
                    // validate ticket against cas
                    StreamReader sr = new StreamReader(new WebClient().OpenRead(StrCasUrl + "validate?ticket=" + ticket + "&service=" + service));

                    // parse text file
                    if (sr.ReadLine() == "yes")
                    {
                        // get kerberos id
                        string kerberos = sr.ReadLine();

                        // set forms authentication ticket
                        FormsAuthentication.SetAuthCookie(kerberos, false);

                        string returnUrl = GetReturnUrl();

                        return(!string.IsNullOrEmpty(returnUrl) ? returnUrl : FormsAuthentication.DefaultUrl);
                    }
                }

                // ticket doesn't exist or is invalid so redirect user to CAS login
                context.Response.Redirect(StrCasUrl + "login?service=" + service);
            }

            return(null);
        }
コード例 #11
0
        public virtual ActionResult LogOn(LogOnModel model, string returnUrl)
        {

            try
            {
                
                if (ModelState.IsValid)
                {
                    //string returnUrl = model.ReturnUrl;
                    string userid = HttpUtility.UrlDecode(model.UserID);
                    //string Domain = ConfigurationManager.AppSettings["Domain"];
                    //bool isValidUser = this._repo.ValidateCredentials(userid, model.Password, Domain);
                    if (Membership.ValidateUser(userid, model.Password))
                    {
                        string ApplicationKey = ConfigurationManager.AppSettings["ApplicationKey"];
                        Users us = new UsersRepository().GetUserDetailFromDatabase(userid);
                        Token token = new Token(userid, ControllerContext.HttpContext.Request.UserHostAddress, ApplicationKey, us.AccessFeatures);
                        string res = token.EncryptKey();
                        if (!string.IsNullOrWhiteSpace(res))
                        {
                            Response.Cookies.Add(new HttpCookie("AuthToken", HttpUtility.UrlEncode(res)) { Expires = DateTime.Now.AddDays(1) });
                            Response.Cookies.Add(new HttpCookie("UserID", userid) { Expires = DateTime.Now.AddDays(1) });

                            MasterRepository rep = new MasterRepository();
                            Company com = rep.GetCompanyInfo(1);// temp company id
                            
                            string userInfo = JsonConvert.SerializeObject(new UserInfo() 
                                                                            { 
                                                                                UserID = userid,
                                                                                CompanyID = com.CompanyID,
                                                                                CompanyName = com.Name,
                                                                                Name = us.Name, 
                                                                                Title = us.Title,
                                                                                Email = us.Email
                                                                            });
                            
                            Response.Cookies.Add(new HttpCookie("UserInfo", userInfo) { Expires = DateTime.Now.AddDays(1) });
                            
                            FormsAuthentication.SetAuthCookie(model.UserID, model.RememberMe);
                            string decodedUrl = "";
                            if (!string.IsNullOrEmpty(returnUrl))  decodedUrl = Server.UrlDecode(returnUrl);
                            if (Url.IsLocalUrl(decodedUrl))
                            {
                                return Redirect(decodedUrl.Replace("/home","/#"));
                            }
                            else
                            {
                                return RedirectToAction("Index", "Home");
                            }
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Invalid credentials. Please try again!");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Invalid input. Please enter correct fields and try again!");
                }

            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
            }
            // If we got this far, something failed, redisplay form
            return PartialView(model);
        }
コード例 #12
0
        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                //VERIFY THE NEW PASSWORD MEETS POLICY
                PasswordPolicy policy;
                if (_User.IsAdmin)
                {
                    policy = new MerchantPasswordPolicy();
                }
                else
                {
                    policy = new CustomerPasswordPolicy();
                }

                PasswordTestResult result = policy.TestPasswordWithFeedback(_User, Password.Text);
                if ((result & PasswordTestResult.Success) == PasswordTestResult.Success)
                {
                    // CHECK IF THERE IS ALREADY A USER WITH DESIRED USERNAME
                    if (_User.IsAnonymousOrGuest && UserDataSource.GetUserIdByUserName(_User.Email) == 0)
                    {
                        _User.UserName = _User.Email;
                    }

                    _User.SetPassword(Password.Text);
                    _User.Comment = string.Empty;
                    _User.Save();
                    CommerceBuilder.Users.User.Migrate(AbleContext.Current.User, _User);
                    FormsAuthentication.SetAuthCookie(_User.UserName, false);
                    Response.Redirect(AbleCommerce.Code.NavigationHelper.GetHomeUrl());
                }
                else
                {
                    //Your password did not meet the following minimum requirements
                    if ((result & PasswordTestResult.PasswordTooShort) == PasswordTestResult.PasswordTooShort)
                    {
                        AddPasswordValidator("Password length must be at least " + policy.MinLength.ToString() + " characters.");
                    }
                    if ((result & PasswordTestResult.RequireLower) == PasswordTestResult.RequireLower)
                    {
                        AddPasswordValidator("Password must contain at least one lowercase letter.<br/>");
                    }
                    if ((result & PasswordTestResult.RequireUpper) == PasswordTestResult.RequireUpper)
                    {
                        AddPasswordValidator("Password must contain at least one uppercase letter.<br/> ");
                    }
                    if ((result & PasswordTestResult.RequireNonAlpha) == PasswordTestResult.RequireNonAlpha)
                    {
                        AddPasswordValidator("Password must contain at least one non-letter.<br/> ");
                    }
                    if ((result & PasswordTestResult.RequireNumber) == PasswordTestResult.RequireNumber)
                    {
                        AddPasswordValidator("Password must contain at least one number.<br/> ");
                    }
                    if ((result & PasswordTestResult.RequireSymbol) == PasswordTestResult.RequireSymbol)
                    {
                        AddPasswordValidator("Password must contain at least one symbol.<br/> ");
                    }

                    if ((result & PasswordTestResult.PasswordHistoryLimitation) == PasswordTestResult.PasswordHistoryLimitation)
                    {
                        AddPasswordValidator("You have recently used this password.<br/>");
                    }
                }
            }
        }
コード例 #13
0
        //
        // GET: /Account/OAuth/

        public ActionResult OAuth(string code, string state)
        {
            FacebookOAuthResult oauthResult;

            if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
            {
                if (oauthResult.IsSuccess)
                {
                    var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current);
                    oAuthClient.RedirectUri = new Uri(redirectUrl);

                    dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
                    string  accessToken = tokenResult.access_token;

                    DateTime expiresOn = DateTime.MaxValue;

                    if (tokenResult.ContainsKey("expires"))
                    {
                        DateTimeConvertor.FromUnixTime(tokenResult.expires);
                    }

                    FacebookClient fbClient   = new FacebookClient(accessToken);
                    dynamic        me         = fbClient.Get("me?fields=id,name,email,birthday,gender");
                    long           facebookId = Convert.ToInt64(me.id);

                    InMemoryUserStore.Add(new FacebookUser
                    {
                        AccessToken = accessToken,
                        Expires     = expiresOn,
                        FacebookId  = facebookId,
                        Name        = (string)me.name,
                    });

                    var user = Membership.GetUser(facebookId.ToString());

                    FormsAuthentication.SetAuthCookie(facebookId.ToString(), false);

                    string      format   = "d";
                    CultureInfo provider = CultureInfo.InvariantCulture;
                    DateTime    birthday = new DateTime();
                    try
                    {
                        birthday = DateTime.ParseExact(me.birthday, format, provider);
                    }
                    catch
                    {
                    }

                    if (user == null)
                    {
                        var u = Membership.CreateUser(facebookId.ToString(), Guid.NewGuid().ToString());
                        using (BestPlaceEntities db = new BestPlaceEntities())
                        {
                            db.bp_Profile_Create((Guid)u.ProviderUserKey,
                                                 facebookId.ToString(),
                                                 (string)me.name,
                                                 Transfer.GetPictureUrl(facebookId.ToString()),
                                                 (string)me.email,
                                                 null,
                                                 birthday,
                                                 ((string)me.gender == "male") ? true : false,
                                                 null, null);
                        }
                    }
                    else
                    {
                        using (BestPlaceEntities db = new BestPlaceEntities())
                        {
                            db.bp_Profile_Update((Guid)user.ProviderUserKey,
                                                 (string)me.name,
                                                 (string)me.email,
                                                 null,
                                                 birthday,
                                                 ((string)me.gender == "male") ? true : false,
                                                 null, null);
                        }
                    }

                    // prevent open redirection attack by checking if the url is local.
                    if (Url.IsLocalUrl(state))
                    {
                        return(Redirect(state));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
コード例 #14
0
        public ActionResult CreateAccount(UserVM model, HttpPostedFileBase file)
        {
            // Init db
            Db db = new Db();

            // Cheack model state
            if (!ModelState.IsValid)
            {
                return(View("Index", model));
            }

            // Make sure username is unique
            if (db.Users.Any(x => x.Username.Equals(model.Username)))
            {
                ModelState.AddModelError("", "That Username: "******" is taken");
                model.Username = "";
                return(View("Index", model));
            }

            // Create UserDTO
            UserDTO userDTO = new UserDTO()
            {
                FirstName    = model.FirstName,
                LastName     = model.LastName,
                EmailAddress = model.EmailAddress,
                Username     = model.Username,
                Password     = model.Password
            };

            // Add to DTO
            db.Users.Add(userDTO);

            // Save
            db.SaveChanges();

            // Get Inserted id
            int userId = userDTO.Id;

            // Login User
            FormsAuthentication.SetAuthCookie(model.Username, false);

            // Set Uploads dir
            var uploadsDir = new DirectoryInfo(string.Format("{0}Uploads", Server.MapPath(@"\")));

            #region Upload Image
            // Check if a file was uploaded
            if (file != null && file.ContentLength > 0)
            {
                // Get extension
                string ext = file.ContentType.ToLower();

                // Verify extension
                if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png")
                {
                    ModelState.AddModelError("", "The image was not uploaded - wrong image extension.");
                    return(View("Index", model));
                }

                // Set Image name
                string imageName = userId + ".jpg";

                // Set image Path
                var path = string.Format("{0}\\{1}", uploadsDir, imageName);

                // Save Image
                file.SaveAs(path);
            }
            #endregion

            // Redirect
            return(Redirect("~/" + model.Username));
        }
コード例 #15
0
        public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                var host    = WebHelper.GetRealHost(Request);
                var culture = WebHelper.GetInterfaceCultureName(Request);
                var result  = Data.CheckAuthentication(model.UserName, model.Password, host, culture, true);

                if (!result.IsOk)
                {
                    ModelState.AddModelError("", ViewRes.User.LoginStrings.WrongPassword);

                    if (result.Error == LoginError.AccountPoisoned)
                    {
                        ipRuleManager.AddTempBannedIP(host, "Account poisoned");
                    }
                }
                else
                {
                    var user = result.User;

                    TempData.SetSuccessMessage(string.Format(ViewRes.User.LoginStrings.Welcome, user.Name));
                    FormsAuthentication.SetAuthCookie(user.Name, model.KeepLoggedIn);

                    string redirectUrl = null;
                    try {
                        redirectUrl = FormsAuthentication.GetRedirectUrl(model.UserName, true);
                    } catch (HttpException x) {
                        log.Warn(x, "Unable to get redirect URL");
                    }

                    string targetUrl;

                    // TODO: should not allow redirection to URLs outside the site
                    if (!string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        targetUrl = model.ReturnUrl;
                    }
                    else if (!string.IsNullOrEmpty(redirectUrl))
                    {
                        targetUrl = redirectUrl;
                    }
                    else
                    {
                        targetUrl = Url.Action("Index", "Home");
                    }

                    if (model.ReturnToMainSite)
                    {
                        targetUrl = VocaUriBuilder.AbsoluteFromUnknown(targetUrl, preserveAbsolute: true);
                    }

                    return(Redirect(targetUrl));
                }
            }

            if (model.ReturnToMainSite)
            {
                SaveErrorsToTempData();
                return(Redirect(VocaUriBuilder.Absolute(Url.Action("Login", new { model.ReturnUrl }))));
            }

            return(View(model));
        }
コード例 #16
0
 public void GuardarCookie(string username)
 {
     FormsAuthentication.SetAuthCookie(username, false);
 }
コード例 #17
0
        public ActionResult Create(RegisterModel model)
        {
            string restrictedErr = "Sorry, access from your host is restricted. It is possible this restriction is no longer valid. If you think this is the case, please contact support.";

            if (!ModelState.IsValidField("Extra"))
            {
                log.Warn("An attempt was made to fill the bot decoy field from {0} with the value '{1}'.", Hostname, ModelState["Extra"]);
                ipRuleManager.AddTempBannedIP(Hostname, "Attempt to fill the bot decoy field");
                return(View(model));
            }

            if (config.SiteSettings.SignupsDisabled)
            {
                ModelState.AddModelError(string.Empty, "Signups are disabled");
            }

            var recaptchaResult = ReCaptcha2.Validate(Request, AppConfig.ReCAPTCHAKey);

            if (!recaptchaResult.Success)
            {
                ErrorLogger.LogMessage(Request, string.Format("Invalid CAPTCHA (error {0})", recaptchaResult.Error), LogLevel.Warn);
                otherService.AuditLog("failed CAPTCHA", Hostname, AuditLogCategory.UserCreateFailCaptcha);
                ModelState.AddModelError("CAPTCHA", ViewRes.User.CreateStrings.CaptchaInvalid);
            }

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            if (!ipRuleManager.IsAllowed(Hostname))
            {
                log.Warn("Restricting blocked IP {0}.", Hostname);
                ModelState.AddModelError("Restricted", restrictedErr);
                return(View(model));
            }

            var time = TimeSpan.FromTicks(DateTime.Now.Ticks - model.EntryTime);

            // Attempt to register the user
            try {
                var url  = VocaUriBuilder.CreateAbsolute(Url.Action("VerifyEmail", "User")).ToString();
                var user = Data.Create(model.UserName, model.Password, model.Email ?? string.Empty, Hostname,
                                       WebHelper.GetInterfaceCultureName(Request),
                                       time, ipRuleManager.TempBannedIPs, url);
                FormsAuthentication.SetAuthCookie(user.Name, false);
                return(RedirectToAction("Index", "Home"));
            } catch (UserNameAlreadyExistsException) {
                ModelState.AddModelError("UserName", ViewRes.User.CreateStrings.UsernameTaken);
                return(View(model));
            } catch (UserEmailAlreadyExistsException) {
                ModelState.AddModelError("Email", ViewRes.User.CreateStrings.EmailTaken);
                return(View(model));
            } catch (InvalidEmailFormatException) {
                ModelState.AddModelError("Email", ViewRes.User.MySettingsStrings.InvalidEmail);
                return(View(model));
            } catch (TooFastRegistrationException) {
                ModelState.AddModelError("Restricted", restrictedErr);
                return(View(model));
            }
        }
コード例 #18
0
 private void FormAuth(string userName)
 {
     FormsAuthentication.SetAuthCookie(userName, false, FormsAuthentication.FormsCookiePath);
 }
コード例 #19
0
        private ActionResult Connect(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                enLoginResult remoteLoginResult = enLoginResult.NotExists;

                /* REMOTE LOGIN */
                var remoteLogin = bool.Parse(ApplicationSettingService.GetWebConfigKey("RemoteLogin"));
                if (remoteLogin)
                {
                    remoteLoginResult = _jsonApiClientService.ValidateCredentialsViaRemoteApi(model.Username, model.Password);
                }

                switch (remoteLoginResult)
                {
                case enLoginResult.Ok:
                case enLoginResult.NotExists:
                    var localLoginResult = _accountService.Login(model.Username, model.Password, true, (remoteLoginResult == enLoginResult.Ok));
                    if (localLoginResult.Result)
                    {
                        FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);
                        if (_contextService.InitializeContext())
                        {
                            ClearNotificationTable();
                            return(RedirectToLocal(returnUrl));
                        }

                        ModelState.AddModelError("", Resource.LoginProblem);
                    }

                    if (remoteLoginResult == enLoginResult.Ok && localLoginResult.Result == false)
                    {
                        ModelState.AddModelError("", Resource.NoMachine);
                    }
                    else
                    {
                        if (localLoginResult.Message == "User is not enabled")
                        {
                            ModelState.AddModelError("", Resource.UserNotEnabled);
                        }
                        else
                        {
                            ModelState.AddModelError("", Resource.PassNotValid);
                        }
                    }
                    break;

                case enLoginResult.Disabled:
                    ModelState.AddModelError("", Resource.UserExpired);
                    break;

                case enLoginResult.WrongPassword:
                    ModelState.AddModelError("", Resource.PassNotValid);
                    break;

                default:
                    ModelState.AddModelError("", Resource.LoginProblem);
                    break;
                }


                return(View(model));
            }

            ModelState.AddModelError("", Resource.UserPassNotValid);
            return(View(model));
        }
コード例 #20
0
        public ActionResult Login(Acc_Login model, string returnUrl, string customSelectForm)
        {
            if (ModelState.IsValid)
            {
                if (model.Password != null)
                {
                    if (model.Password.Length >= 0)
                    {
                        if (Account.ValidateUserPWD(model.UserName, model.Password))
                        {
                            Acc_Account iAccount = Account.ValidateUser(model.UserName, model.Password);

                            if (iAccount != null)
                            {
                                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                                //GAccountInfo uGa = GAccount.GetAccountInfo(model.UserName, customSelectForm);
                                HttpContextBase httpContext = new HttpContextWrapper(System.Web.HttpContext.Current);
                                //设置Session
                                httpContext.Session[GAccount.KEY_CACHEUSER] = iAccount;
                                //DALogWarnMan.AddLog("用户登录", strUserName, strUnitName);
                                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                                    !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                                {
                                    return(Redirect(returnUrl));
                                }
                                else
                                {
                                    //string Path = iAccount.Path;
                                    //if (Path.IndexOf(".31.") >= 0)
                                    //{
                                    return(RedirectToAction("SelectModuleYS", "Main"));
                                    //}
                                    //if (Path.IndexOf(".49.") >= 0)
                                    //{
                                    //    return RedirectToAction("SelectModuleFZ", "Main");
                                    //}
                                    //return RedirectToAction("SelectModule", "Main");
                                }
                            }
                            return(null);
                        }
                        else
                        {
                            ModelState.AddModelError("err", "用户名或密码输入错误");
                            return(View(model));
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "登录失败,密码应至少8位");
                        return(View(model));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "登录异常...");
                    return(View(model));
                }
            }
            else
            {
                ModelState.AddModelError("", "登录异常...");
                return(View(model));
            }
        }
コード例 #21
0
        public ActionResult ThemUser(UserValidate nv)
        {
            nv.XacNhanMatKhau = nv.MatKhau;
            if (ModelState.IsValid)
            {
                ViewBag.err = String.Empty;
                var checkMaNhanVien = db.NhanViens.Any(x => x.MaNhanVien == nv.MaNhanVien);

                if (checkMaNhanVien)
                {
                    ViewBag.err = "tài khoản đã tồn tại";
                    //ModelState.AddModelError("MaNhanVien", "Mã tài khoản đã tồn tại");
                    return(View(nv));
                }
                else
                {
                    Luong    luong = new Luong();
                    HopDong  hd    = new HopDong();
                    NhanVien nvAdd = new NhanVien();
                    nvAdd.MaNhanVien      = nv.MaNhanVien;
                    nvAdd.MatKhau         = nv.MatKhau;
                    nvAdd.HoTen           = nv.HoTen;
                    nvAdd.NgaySinh        = nv.NgaySinh;
                    nvAdd.QueQuan         = nv.QueQuan;
                    nvAdd.GioiTinh        = nv.GioiTinh;
                    nvAdd.DanToc          = nv.DanToc;
                    nvAdd.MaChucVuNV      = nv.MaChucVuNV;
                    nvAdd.MaPhongBan      = nv.MaPhongBan;
                    nvAdd.MaChuyenNganh   = nv.MaChuyenNganh;
                    nvAdd.MaTrinhDoHocVan = nv.MaTrinhDoHocVan;
                    nvAdd.MaHopDong       = nv.MaNhanVien;
                    nvAdd.TrangThai       = true;
                    nvAdd.HinhAnh         = "icon.jpg";

                    //add hop dong
                    hd.MaHopDong  = nv.MaNhanVien;
                    hd.NgayBatDau = DateTime.Now.Date;

                    //tao bang luong
                    luong.MaNhanVien    = nv.MaNhanVien;
                    luong.LuongToiThieu = 1150000;
                    luong.BHXH          = 8;
                    luong.BHYT          = 1.5;
                    luong.BHTN          = 1;
                    var trinhdo = db.TrinhDoHocVans.Where(n => n.MaTrinhDoHocVan.Equals(nv.MaTrinhDoHocVan)).FirstOrDefault();
                    var chucvu  = db.ChucVuNhanViens.Where(n => n.MaChucVuNV.Equals(nv.MaChucVuNV)).SingleOrDefault();

                    if (trinhdo.MaTrinhDoHocVan.Equals(nv.MaTrinhDoHocVan))
                    {
                        luong.HeSoLuong = (double)trinhdo.HeSoBac;
                    }


                    if (chucvu.MaChucVuNV.Equals(nv.MaChucVuNV))
                    {
                        if (chucvu.HSPC != null)
                        {
                            luong.PhuCap = (double)chucvu.HSPC;
                        }
                        else
                        {
                            luong.PhuCap = 0;
                        }
                    }



                    // tmp.Image = "~/Content/images/icon.jpg";
                    db.NhanViens.Add(nvAdd);
                    db.HopDongs.Add(hd);

                    db.Luongs.Add(luong);
                    // @ViewBag.add = "Đăng ký thành công";
                    db.SaveChanges();
                    //xác thực tài khoản trong ứng dụng
                    FormsAuthentication.SetAuthCookie(nvAdd.MaNhanVien, false);
                    //trả về trang quản lý

                    return(Redirect("/admin/quan-ly-nhan-vien"));
                }
            }
            else
            {
                return(View(nv));
            }
        }//end add nhan vien
        public ActionResult HandleLogin(LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(PartialView("Login", model));
            }

            //Member already logged in - redirect to home
            if (User?.Identity.IsAuthenticated == true)
            {
                return(Redirect("/"));
            }

            //Lets TRY to log the user in
            try
            {
                //Try and login the user... (IS THIS NESSECARY?, model should be validated by .net)
                if (Membership.ValidateUser(model.EmailAddress, model.Password))
                {
                    var ms = Services.MemberService;

                    //Get the member from their email address
                    var checkMember = ms.GetByEmail(model.EmailAddress);

                    //Check the member exists
                    if (checkMember != null)
                    {
                        //Let's check they have verified their email address
                        if (checkMember.GetValue <bool>("hasVerifiedEmail"))
                        {
                            //Update number of logins counter
                            int noLogins = checkMember.GetValue <int>("numberOfLogins");

                            //Update the counter
                            checkMember.SetValue("numberOfLogins", noLogins + 1);

                            //Update label with last login date to now
                            checkMember.SetValue("lastLoggedIn", DateTime.Now.ToString("dd/MM/yyyy @ HH:mm:ss"));

                            //Update label with last logged in IP address & Host Name
                            string hostName        = Dns.GetHostName();
                            string clientIPAddress = Dns.GetHostAddresses(hostName).GetValue(0).ToString();

                            checkMember.SetValue("hostNameOfLastLogin", hostName);
                            checkMember.SetValue("iPofLastLogin", clientIPAddress);

                            //Save the details
                            ms.Save(checkMember);

                            //If they have verified then lets log them in
                            //Set Auth cookie
                            FormsAuthentication.SetAuthCookie(model.EmailAddress, true);

                            //Once logged in - redirect them back to the return URL
                            return(new RedirectResult(model.ReturnUrl));
                        }
                        else
                        {
                            //User has not verified their email yet
                            ModelState.AddModelError("LoginForm.", "Email account has not been verified");
                            return(PartialView("Login", model));
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("LoginForm.", "Invalid details");
                    return(PartialView("Login", model));
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("LoginForm.", "Error: " + ex.ToString());
                return(PartialView("Login", model));
            }

            return(PartialView("Login", model));
        }
コード例 #23
0
 public void SignIn(string userName, bool createPersistentCookie)
 {
     FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
 }
コード例 #24
0
        protected void RegisterUser_CreatedUser(object sender, EventArgs e)
        {
            try
            {
                if (!Roles.IsUserInRole(RegisterUser.UserName, "Manager"))
                {
                    if (!Roles.RoleExists("Manager"))
                    {
                        Roles.CreateRole("Manager");
                        Roles.AddUserToRole(RegisterUser.UserName, "Manager");
                    }
                    else
                    {
                        Roles.AddUserToRole(RegisterUser.UserName, "Manager");
                    }
                }

                FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);


                Label  lblmsg       = (Label)RegisterUserWizardStep.ContentTemplateContainer.FindControl("lblErrorMessage");
                string Name         = ((TextBox)RegisterUserWizardStep.ContentTemplateContainer.FindControl("Name")).Text;
                string Designation  = ((TextBox)RegisterUserWizardStep.ContentTemplateContainer.FindControl("Designation")).Text;
                string Mobile       = ((TextBox)RegisterUserWizardStep.ContentTemplateContainer.FindControl("Mobile")).Text;
                string Industry     = ((DropDownList)RegisterUserWizardStep.ContentTemplateContainer.FindControl("Industry")).Text;
                string Orgnaisation = ((TextBox)RegisterUserWizardStep.ContentTemplateContainer.FindControl("Orgnaisation")).Text;
                string pwd          = ((TextBox)RegisterUserWizardStep.ContentTemplateContainer.FindControl("Password")).Text;
                clsESPSql.ExecNonQuery("update aspnet_Users set pwd='" + pwd + "', mobilealias='" + Mobile + "' where username='******'");
                try
                {
                    LIBtblOrgBasicInfo         objLIBtblOrgBasicInfo = new LIBtblOrgBasicInfo();
                    DALtblOrgBasicInfo         objDALtblOrgBasicInfo = new DALtblOrgBasicInfo();
                    MyCLS.TransportationPacket tp = new MyCLS.TransportationPacket();

                    objLIBtblOrgBasicInfo.id          = -1;
                    objLIBtblOrgBasicInfo.username    = RegisterUser.UserName;
                    objLIBtblOrgBasicInfo.Name        = Name;
                    objLIBtblOrgBasicInfo.Email       = RegisterUser.UserName;
                    objLIBtblOrgBasicInfo.phone       = Mobile;
                    objLIBtblOrgBasicInfo.designation = Designation;
                    objLIBtblOrgBasicInfo.OrgName     = Orgnaisation;
                    objLIBtblOrgBasicInfo.industry    = Industry;
                    objLIBtblOrgBasicInfo.dt          = DateTime.Now.ToShortDateString();
                    tp.MessagePacket = objLIBtblOrgBasicInfo;
                    tp = objDALtblOrgBasicInfo.InserttblOrgBasicInfo(tp);

                    //if (tp.MessageId > -1)
                    //{
                    //    string[] strOutParamValues = (string[])tp.MessageResultset;

                    Response.Redirect("Verification.aspx", false);
                    //}

                    // Page.ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>javascript:   document.getElementById('ahrfcreate').click();</script>");
                    RegisterUser.LoginCreatedUser = true;
                    // lblmsg.Text = " An email has been sent to your account. Please view the email and confirm your account to complete the registration process.";
                }
                catch (Exception ex)
                {
                    MyCLS.clsHandleException.HandleEx(ex, System.Reflection.MethodBase.GetCurrentMethod().ToString(), true);
                }
            }
            catch (Exception ex)
            {
            }
        }
コード例 #25
0
        private void CreateSession(LogOn.FormInfo formInfo)
        {
            string str;
            string applicationName;
            string str1;
            string originalString;
            WSManConnectionInfo wSManConnectionInfo = null;

            if (formInfo.ConfigurationName.Length == 0)
            {
                str = null;
            }
            else
            {
                str = string.Concat("http://schemas.microsoft.com/powershell/", formInfo.ConfigurationName);
            }
            string       str2         = str;
            PSCredential pSCredential = new PSCredential(formInfo.DestinationUserName, formInfo.DestinationPassword);

            if (!formInfo.IsUriConnection)
            {
                if (string.Compare(formInfo.ApplicationName, "WSMAN", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    applicationName = null;
                }
                else
                {
                    applicationName = formInfo.ApplicationName;
                }
                string str3 = applicationName;
                try
                {
                    wSManConnectionInfo = new WSManConnectionInfo(formInfo.UseSsl, formInfo.ComputerName, formInfo.Port, str3, str2, pSCredential);
                }
                catch (UriFormatException uriFormatException)
                {
                    throw PowwaException.CreateValidationErrorException(Resources.LogonError_InvalidComputerNameUriFormat);
                }
                wSManConnectionInfo.AuthenticationMechanism = formInfo.AuthenticationType;
                PowwaEvents.PowwaEVENT_DEBUG_CONNECT_USING_COMPUTERNAME(formInfo.DestinationUserName, wSManConnectionInfo.ComputerName, wSManConnectionInfo.Port, wSManConnectionInfo.AppName, wSManConnectionInfo.ShellUri, wSManConnectionInfo.AuthenticationMechanism.ToString());
            }
            else
            {
                wSManConnectionInfo = new WSManConnectionInfo(formInfo.ConnectionUri, str2, pSCredential);
                if (!formInfo.AllowRedirection)
                {
                    wSManConnectionInfo.MaximumConnectionRedirectionCount = 0;
                }
                PowwaEvents.PowwaEVENT_DEBUG_CONNECT_USING_URI(formInfo.DestinationUserName, wSManConnectionInfo.ConnectionUri.AbsoluteUri, wSManConnectionInfo.ShellUri);
            }
            string sourceIPAddressRemoteAddr        = SessionHelper.GetSourceIPAddressRemoteAddr();
            string sourceIPAddressHttpXForwardedFor = SessionHelper.GetSourceIPAddressHttpXForwardedFor();

            if (formInfo.IsUriConnection)
            {
                str1 = null;
            }
            else
            {
                str1 = PswaHelper.TranslateLocalComputerName(formInfo.ComputerName);
            }
            string str4 = str1;

            PowwaAuthorizationManager.Instance.CheckLogOnCredential(formInfo.UserName, formInfo.Password, str4, formInfo.ConnectionUri, formInfo.ConfigurationName, sourceIPAddressRemoteAddr, sourceIPAddressHttpXForwardedFor);
            ClientInfo   clientInfo   = new ClientInfo(HttpContext.Current.Request.UserAgent, CultureInfo.CurrentCulture, CultureInfo.CurrentUICulture);
            PowwaSession powwaSession = PowwaSessionManager.Instance.CreateSession(this.Session.SessionID, wSManConnectionInfo, clientInfo, formInfo.UserName);
            string       name         = powwaSession.Name;
            string       userName     = formInfo.UserName;
            string       str5         = sourceIPAddressRemoteAddr;
            string       str6         = sourceIPAddressHttpXForwardedFor;

            if (formInfo.IsUriConnection)
            {
                originalString = wSManConnectionInfo.ConnectionUri.OriginalString;
            }
            else
            {
                originalString = wSManConnectionInfo.ComputerName;
            }
            PowwaEvents.PowwaEVENT_SESSION_START(name, userName, str5, str6, originalString, formInfo.DestinationUserName, wSManConnectionInfo.Port, wSManConnectionInfo.AppName, wSManConnectionInfo.ShellUri);
            HttpCookie item = base.Request.Cookies["ASP.NET_SessionId"];

            if (FormsAuthentication.RequireSSL && item != null)
            {
                item.Secure = true;
            }
            FormsAuthentication.SetAuthCookie(formInfo.UserName, false, "/");
            base.Response.Redirect("~/default.aspx");
            //FormsAuthentication.RedirectFromLoginPage(formInfo.UserName, false);
        }
コード例 #26
0
        public async Task <ActionResult> Login(UserLoginModel model, string returnUrl = "")
        {
            if (ModelState.IsValid)
            {
                TempData["PasswordAgedMessage"] = "";

                var loginModel = new UserLoginModel();
                // find user by username first
                var user = loginModel.GetUserByUsername(model.UserName);
                if (user != null)
                {
                    MD5    md5Hash      = MD5.Create();
                    string hashPassword = GetMd5Hash(md5Hash, model.Password);
                    var    validUser    = loginModel.GetValidUserByPassword(model.UserName, hashPassword);
                    //var validCredentials = await UserManager.FindAsync(model.UserName, model.Password);
                    //if (loginModel.IsLockedOut(user.Id))
                    //{
                    //    ModelState.AddModelError("", string.Format("Your account has been locked out for {0} minutes due to multiple failed login attempts.", ConfigurationManager.AppSettings["DefaultAccountLockoutTimeSpan"].ToString()));
                    //}
                    //else if (loginModel.GetLockoutEnabled(user.Id) && validUser == null)
                    //{
                    //    loginModel.AccessFailed(user.Id);
                    //    string message;
                    //    if (loginModel.IsLockedOut(user.Id))
                    //    {
                    //        message = string.Format("Your account has been locked out for {0} minutes due to multiple failed login attempts.", ConfigurationManager.AppSettings["DefaultAccountLockoutTimeSpan"].ToString());
                    //    }
                    //    else
                    //    {
                    //        var accessFailedUser =loginModel.GetUserById(user.Id);
                    //        int accessFailedCount = loginModel.GetUserById(user.Id).AccessFailedCount??1;
                    //        int attemptsLeft =loginModel.GetMaxAccesFailedAttempt(user.Id) -accessFailedCount;

                    //        message = string.Format("Invalid password. You have {0} more attempt(s) before your account gets locked out.", attemptsLeft);

                    //    }
                    //    ModelState.AddModelError("", message);
                    //}
                    //else if (validUser == null)
                    //{
                    //    ModelState.AddModelError("", "Invalid credentials. Please try again.");
                    //}

                    if (validUser == null)
                    {
                        ModelState.AddModelError("", "Invalid credentials. Please try again.");
                    }
                    else
                    {
                        //loginModel.ResetAccesFailedCount(validUser.Id);
                        //if (loginModel.IsPasswordValidityExpired(validUser.Id))
                        //{
                        //    TempData["PasswordAgedMessage"] = "It seems your password not changed since more than 45 days! Please Change your password now.";
                        //    return RedirectToAction("ChangePassword", "User", new { userName = user.UserName.ToLower() });
                        //}
                        //if (loginModel.IsFirstLogin(validUser.Id))
                        //{

                        //    TempData["PasswordAgedMessage"] = "Please change password at first login.";
                        //    return RedirectToAction("ChangePassword", "User", new { userName = user.UserName.ToLower() });
                        //}

                        FormsAuthentication.SetAuthCookie(validUser.Id + "|" + validUser.UserName.ToUpper() + "|" + validUser.Name + "|" + validUser.ImageFile, model.RememberMe);;
                        Session["sessionid"] = System.Web.HttpContext.Current.Session.SessionID;
                        //loginModel.SaveLogin(validUser.UserName.ToUpper(), System.Web.HttpContext.Current.Session.SessionID.ToString(), true);

                        if (Url.IsLocalUrl(returnUrl))
                        {
                            return(Redirect(returnUrl));
                        }
                        else
                        {
                            return(RedirectToAction("Index", "Home"));
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
                ModelState.Remove("Password");
            }
            // If we got this far, something failed, redisplay form


            return(View(model));
        }
コード例 #27
0
        public ActionResult LogIn(LogInModel model)
        {
            try
            {
                // Ошибки в форме
                if (!ModelState.IsValid)
                {
                    return(View(model));
                }

                string _login    = model.Login;
                string _pass     = model.Pass;
                bool   _remember = model.RememberMe;

                AccountModel AccountInfo = _accountRepository.getCmsAccount(_login);

                // Если пользователь найден
                if (AccountInfo != null)
                {
                    if (AccountInfo.Disabled)
                    {
                        // Оповещение о блокировке
                        ModelState.AddModelError("", "Пользователь заблокирован и не имеет прав на доступ в систему администрирования");
                    }
                    else if (AccountInfo.CountError && AccountInfo.LockDate.Value.AddMinutes(15) >= DateTime.Now)
                    {
                        // Оповещение о блокировке
                        ModelState.AddModelError("", "После " + maxLoginError + " неудачных попыток авторизации Ваш пользователь временно заблокирован.");
                        ModelState.AddModelError("", "————");
                        ModelState.AddModelError("", "Вы можете повторить попытку через " + (AccountInfo.LockDate.Value.AddMinutes(16) - DateTime.Now).Minutes + " минут");
                    }
                    else
                    {
                        // Проверка на совпадение пароля
                        Cripto password = new Cripto(AccountInfo.Salt, AccountInfo.Hash);
                        if (password.Verify(_pass.ToCharArray()))
                        {
                            // Удачная попытка, Авторизация
                            FormsAuthentication.SetAuthCookie(AccountInfo.id.ToString(), _remember);

                            HttpCookie MyCookie = new HttpCookie(".ASPXAUTHMORE");
                            MyCookie.Value  = HttpUtility.UrlEncode(AccountInfo.id.ToString(), System.Text.Encoding.UTF8);
                            MyCookie.Domain = "." + Settings.BaseURL;
                            Response.Cookies.Add(MyCookie);


                            // Записываем данные об авторизации пользователя
                            _accountRepository.SuccessLogin(AccountInfo.id, RequestUserInfo.IP);

                            return(RedirectToAction("Index", "Main"));
                        }
                        else
                        {
                            // Неудачная попытка
                            // Записываем данные о попытке авторизации и плучаем кол-во неудавшихся попыток входа
                            int attemptNum = _accountRepository.FailedLogin(AccountInfo.id, RequestUserInfo.IP);
                            if (attemptNum == maxLoginError)
                            {
                                #region Оповещение о блокировке
                                // Формируем код востановления пароля
                                Guid RestoreCode = Guid.NewGuid();
                                _accountRepository.setRestorePassCode(AccountInfo.id, RestoreCode, RequestUserInfo.IP);

                                // оповещение на e-mail
                                string Massege = String.Empty;
                                Mailer Letter  = new Mailer();
                                Letter.Theme  = "Блокировка пользователя";
                                Massege       = "<p>Уважаемый " + AccountInfo.Surname + " " + AccountInfo.Name + ", в системе администрирования сайта " + Request.Url.Host + " было 5 неудачных попыток ввода пароля.<br />В целях безопасности, ваш аккаунт заблокирован.</p>";
                                Massege      += "<p>Для восстановления прав доступа мы сформировали для Вас ссылку, перейдя по которой, Вы сможете ввести новый пароль для вашего аккаунта и учетная запись будет разблокирована.</p>";
                                Massege      += "<p>Если вы вспомнили пароль и хотите ещё раз пропробовать авторизоваться, то подождите 15 минут. Спустя это время, система позволит Вам сделать ещё попытку.</p>";
                                Massege      += "<p><a href=\"http://" + Request.Url.Host + "/Admin/Account/ChangePass/" + RestoreCode + "/\">http://" + Request.Url.Host + "/Admin/Account/ChangePass/" + RestoreCode + "/</a></p>";
                                Massege      += "<p>С уважением, администрация сайта!</p>";
                                Massege      += "<hr><i><span style=\"font-size:11px\">Это сообщение отпралено роботом, на него не надо отвечать</i></span>";
                                Letter.MailTo = AccountInfo.Mail;
                                Letter.Text   = Massege;
                                string ErrorText = Letter.SendMail();
                                #endregion
                                ModelState.AddModelError("", "После " + maxLoginError + " неудачных попыток авторизации Ваш пользователь временно заблокирован.");
                                ModelState.AddModelError("", "Вам на почту отправлено сообщение с инструкцией по разблокировки и смене пароля.");
                                ModelState.AddModelError("", "---");
                                ModelState.AddModelError("", "Если вы хотите попробовать ещё раз, подождите 15 минут.");
                            }
                            else
                            {
                                // Оповещение об ошибке
                                string attemptCount = (maxLoginError - attemptNum == 1) ? "Осталась 1 попытка" : "Осталось " + (maxLoginError - attemptNum) + " попытки";
                                ModelState.AddModelError("", "Пара логин и пароль не подходят.");
                                ModelState.AddModelError("", attemptCount + " ввода пароля.");
                            }
                        }
                    }
                }
                else
                {
                    // Оповещение о неверном логине
                    ModelState.AddModelError("", "Такой пользователь не зарегистрирован в системе.");
                    ModelState.AddModelError("", "Проверьте правильность вводимых данных.");
                }


                return(View());
            }
            catch
            {
                return(View());
            }
        }
コード例 #28
0
ファイル: MembershipHelper.cs プロジェクト: SKDon/Triphulcas
 /// <summary>
 /// Logs in a member by their username
 /// </summary>
 /// <param name="username"></param>
 public static void LogInUser(string username)
 {
     FormsAuthentication.SetAuthCookie(username, false);
 }
コード例 #29
0
ファイル: LoginController.cs プロジェクト: tejamukka/MBASite
 /// <summary>
 /// Creates a cookie to save session data
 /// </summary>
 /// <param name="details"></param>
 private void CreateCookie(LoginDetails details)
 {
     StaticVariables.Role = GetRoleOfUser(int.Parse(details.Username));
     FormsAuthentication.SetAuthCookie(details.Username.ToString(), false);
 }
コード例 #30
0
 public void Authenticate(string username)
 {
     FormsAuthentication.SetAuthCookie(username, true);
 }