Example #1
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            HttpCookie cookie = HiContext.Current.Context.Request.Cookies["Token_" + HiContext.Current.User.UserId.ToString()];

            if ((cookie != null) && !string.IsNullOrEmpty(cookie.Value))
            {
                cookie.Expires = DateTime.Now;
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
            if (this.Context.Request.IsAuthenticated)
            {
                FormsAuthentication.SignOut();
                HttpCookie  authCookie = FormsAuthentication.GetAuthCookie(HiContext.Current.User.Username, true);
                IUserCookie userCookie = HiContext.Current.User.GetUserCookie();
                if (userCookie != null)
                {
                    userCookie.DeleteCookie(authCookie);
                }
                RoleHelper.SignOut(HiContext.Current.User.Username);
                this.Context.Response.Cookies["hishopLoginStatus"].Value = "";
            }
            this.Context.Response.Redirect(Globals.GetSiteUrls().Home, true);
        }
Example #2
0
        public HttpResponseMessage Authenticate(LoginData login)
        {
            //var username = form.Get("Username");
            //var password = form.Get("Password");

            string username = login.Username;
            string password = login.Password;

            bool authenticated = FormsAuthentication.Authenticate(username, password);
            var  cookie        = FormsAuthentication.GetAuthCookie(username, false);

            if (!authenticated)
            {
                return(Request.CreateResponse <bool>(HttpStatusCode.Unauthorized, false));
            }

            var response = Request.CreateResponse <bool>(HttpStatusCode.OK, true);

            response.Headers.AddCookies(new CookieHeaderValue[1] {
                new CookieHeaderValue(cookie.Name, cookie.Value)
            });

            return(response);
        }
Example #3
0
        //控件初始经事件
        protected override void OnInit(EventArgs e)
        {
            SiteSettings masterSettings = SettingsManager.GetMasterSettings(false);

            //验证域名
            if (HiContext.Current.SiteUrl != masterSettings.SiteUrl)
            {
                Context.Response.Redirect(Globals.GetSiteUrls().Home, true);
            }


            if (Page.Request.IsAuthenticated)
            {
                FormsAuthentication.SignOut();
                HttpCookie  authCookie = FormsAuthentication.GetAuthCookie(HiContext.Current.User.Username, true);
                IUserCookie userCookie = HiContext.Current.User.GetUserCookie();
                if (userCookie != null)
                {
                    userCookie.DeleteCookie(authCookie);
                }
                RoleHelper.SignOut(HiContext.Current.User.Username);
            }
            base.OnInit(e);
        }
Example #4
0
    public void RaiseCallbackEvent(string eventArgument)
    {
        String[] arguments   = eventArgument.Split(',');
        String   userAccount = arguments[0];
        String   password    = FormsAuthentication.HashPasswordForStoringInConfigFile(arguments[1], "MD5");

        using (SysUserBusiness user = new SysUserBusiness()) {
            bool passed = user.Authentication(userAccount, password);
            if (passed)
            {
                FormsAuthentication.SetAuthCookie(userAccount, true);
                HttpCookie authCookie               = FormsAuthentication.GetAuthCookie(userAccount, true);
                FormsAuthenticationTicket ticket    = FormsAuthentication.Decrypt(authCookie.Value);
                FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, "");
                authCookie.Value = FormsAuthentication.Encrypt(newTicket);
                Response.Cookies.Remove(authCookie.Name);
                Response.Cookies.Add(authCookie);
                callBackResult = FormsAuthentication.DefaultUrl;
            }
        }
        //FormsAuthentication.SetAuthCookie("Admin", true);
        //Server.Transfer(FormsAuthentication.DefaultUrl);
        //callBackResult = FormsAuthentication.DefaultUrl;
    }
        private void SignIn(string userName, bool createPersistentCookie)
        {
            Logger.Trace("认证Local用户: " + userName);
            Logger.Trace("给Local用户添加包含UserData的认证票据, 重发送至首页");

            // 生成UserData
            string userDataString = string.Concat(userName, "|", "/Content/Images/tinyHead.gif");

            // 创建包含认证用户信息的Cookie
            HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userName, createPersistentCookie);

            // 获得解密后的认证票据
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

            // 创建一个新的包含UserData的认证票据
            FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name,
                                                                                ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userDataString);

            // 加密新的认证票据
            authCookie.Value = FormsAuthentication.Encrypt(newTicket);

            // 手工将认证票据加入Cookie
            Response.Cookies.Add(authCookie);
        }
        public ActionResult Create()
        {
            var userId    = Session["UserId"].ToString();
            var profileId = Session["ProfileId"].ToString();

            Users user = SqlHelper.GetUser(userId);

            HttpCookie cookie = FormsAuthentication.GetAuthCookie(user.UserName, true);
            var        ticket = FormsAuthentication.Decrypt(cookie.Value);

            FormsAuthenticationTicket authTicket = new
                                                   FormsAuthenticationTicket(1,                           //version
                                                                             ticket.Name,
                                                                             DateTime.Now,                //creation
                                                                             DateTime.Now.AddMinutes(60), //Expiration
                                                                             true, "");
            // Encrypt the ticket.
            string encTicket = FormsAuthentication.Encrypt(authTicket);

            // Create the cookie.
            Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

            return(View(layoutViewModel.LayoutViewModelBuilder(profileId, userId)));
        }
Example #7
0
        private string Post(string apiBaseUri, string requestUrl, object data = null)
        {
            var restClient = new RestSharp.RestClient(apiBaseUri);
            var request    = new RestSharp.RestRequest(requestUrl, RestSharp.Method.POST);

            request.RequestFormat = RestSharp.DataFormat.Json;
            //if (data != null)
            //{
            //    foreach (var key in data.Keys)
            //    {
            //        request.AddParameter(key, data[key]);
            //    }
            //}
            request.AddBody(data);

            // 追加登录Cookie
            var cookie = FormsAuthentication.GetAuthCookie(User.Identity.Name, true);

            request.AddCookie(FormsAuthentication.FormsCookieName, cookie.Value);
            request.Timeout = 36000;
            var response = restClient.Execute(request);

            return(response.Content);
        }
        private void SetAuthCookie(long accountId, string accountName, int deviceId, int userType = 0)
        {
            //NLogManager.LogMessage(HttpContext.Current.Request.Url.Host);
            string cookieUsername = $"{accountId}|{accountName}|{deviceId}|{userType}";
            string cookieDomain   = HttpContext.Current.Request.Url.Host;

            if (cookieDomain.StartsWith("services"))
            {
                cookieDomain = cookieDomain.Substring(8, cookieDomain.Length - 8);
            }
            else if (cookieDomain.StartsWith("api"))
            {
                cookieDomain = cookieDomain.Substring(3, cookieDomain.Length - 3);
            }
            FormsAuthentication.SetAuthCookie(cookieUsername, false, FormsAuthentication.FormsCookiePath);
            HttpCookie cookie = FormsAuthentication.GetAuthCookie(cookieUsername, false, FormsAuthentication.FormsCookiePath);

            cookie.HttpOnly = false;
            cookie.Domain   = cookieDomain;
            //NLogManager.LogMessage($"{cookieDomain}|{accountId}|{accountName}|{deviceId}|{userType}");
            // cookie.Domain = ConfigurationManager.AppSettings["domain"];

            HttpContext.Current.Response.Cookies.Add(cookie);
        }
Example #9
0
        public static void UserLogin(string loginName, string UserData, bool RememberMe, string cookieDomain)
        {
            //设置用户的 cookie 的值
            FormsAuthentication.SetAuthCookie(loginName, RememberMe);

            //获取用户的 cookie
            HttpCookie cookie = FormsAuthentication.GetAuthCookie(loginName, false, FormsAuthentication.FormsCookiePath);

            //给用户的 cookie 的值加上 cookie 的域 和 过期日期
            //向客户端重写同名的 用户 cookie
            FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(cookie.Value);
            FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(
                1,
                oldTicket.Name,
                oldTicket.IssueDate,
                oldTicket.Expiration,
                oldTicket.IsPersistent,
                UserData == string.Empty ? oldTicket.UserData : UserData,
                FormsAuthentication.FormsCookiePath);

            cookie.Domain = cookieDomain;
            cookie.Value  = FormsAuthentication.Encrypt(newTicket);
            System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
        }
Example #10
0
        public JsonResult Login(LoginModel oUserAccount)
        {
            var cStatus = "error";
            var cMsg    = "User Name or Password invalid";

            if (string.IsNullOrEmpty(oUserAccount.Email) || string.IsNullOrEmpty(oUserAccount.Password))
            {
                return(Json(new { cStatus = "error", cMsg = "You cant Enter empty username or password !!" }));
            }

            var getUserAccount = db.UserAccounts.Where(x => (x.Email == oUserAccount.Email || x.Name == oUserAccount.Email) && x.Pass == oUserAccount.Password).ToList();

            if (getUserAccount.Count > 0)
            {
                // ReSharper disable once AssignNullToNotNullAttribute
                var getUserAccountResult = getUserAccount.FirstOrDefault();
                cStatus = "success";
                cMsg    = "انتهت العملية بنجاح";
                if (getUserAccountResult?.IsActive != null && getUserAccountResult.IsActive && !getUserAccountResult.IsDeleted)
                {
                    CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
                    serializeModel.Id       = getUserAccountResult.Id;
                    serializeModel.Name     = getUserAccountResult.Name;
                    serializeModel.Password = getUserAccountResult.Pass;
                    if (getUserAccountResult.UserTypeId != null)
                    {
                        serializeModel.UserTypeId = getUserAccountResult.UserTypeId.Value;
                    }
                    //if (getUserAccountResult.BranchId != null)
                    //    serializeModel.BranchId = getUserAccountResult.BranchId.Value;
                    serializeModel.Email  = getUserAccountResult.Email;
                    serializeModel.Avatar = getUserAccountResult.Avatar;
                    //serializeModel.UserTypeName = getUserAccountResult.UserTypeName;
                    serializeModel.IsActive      = getUserAccountResult.IsActive;
                    serializeModel.IsDeleted     = getUserAccountResult.IsDeleted;
                    serializeModel.Gender        = getUserAccountResult.Gender;
                    serializeModel.Mobile        = getUserAccountResult.Mobile;
                    serializeModel.EmailPassword = getUserAccountResult.EmailPassword;

                    string     userData = JsonConvert.SerializeObject(serializeModel);
                    HttpCookie cookie   = FormsAuthentication.GetAuthCookie(serializeModel.Name, false);
                    var        ticket   = FormsAuthentication.Decrypt(cookie.Value);
                    if (ticket != null)
                    {
                        var newticket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, true, userData, ticket.CookiePath);
                        cookie.Value = FormsAuthentication.Encrypt(newticket);
                        if (oUserAccount.Remember == 1)
                        {
                            cookie.Expires = newticket.Expiration.AddYears(2);
                        }
                    }

                    string url = "";
                    HttpContext.Response.Cookies.Set(cookie);

                    url = Url.Action("index", "ControlPanel");

                    //if (getUserAccountResult.userType == 9 || LogInUser.userType == 14)
                    //{
                    //    URL = Url.Action("Index", "CMProducts");
                    //}
                    //FormsAuthentication.RedirectFromLoginPage(LogInUser.Account + "\n" + LogInUser.Type + "\n" + LogInUser.isActive, false);
                    return(Json(new { cStatus, cMsg, isRedirect = true, redirectUrl = (string.IsNullOrEmpty(oUserAccount.ReturnUrl) ? url : oUserAccount.ReturnUrl) }, JsonRequestBehavior.AllowGet));
                }
                else if (getUserAccountResult != null && getUserAccountResult.IsDeleted)
                {
                    cStatus = "error";
                    cMsg    = "The account is deactivated, please contact Admin";
                }
                else
                {
                    cStatus = "error";
                    cMsg    = "The account is deactivated, please contact Admin";
                }
            }
            return(Json(new { cStatus, cMsg }, JsonRequestBehavior.AllowGet));
        }
        public JsonResult LoginFn(LoginModel oVisitor)
        {
            var cStatus = "error";
            var cMsg    = "User Name or Password invalid";

            if (string.IsNullOrEmpty(oVisitor.Email) || string.IsNullOrEmpty(oVisitor.Password))
            {
                return(Json(new { cStatus = "error", cMsg = "You cant Enter empty username or password !!" }));
            }

            var getVisitorResult = new Visitors();
            var getVisitor       = DAL.News.Visitors.VisitorLogin(oVisitor);

            if (getVisitor.HasResult)
            {
                // ReSharper disable once AssignNullToNotNullAttribute
                getVisitorResult = getVisitor.Results.FirstOrDefault();
                cStatus          = "success";
                cMsg             = "انتهت العملية بنجاح";
                if (getVisitorResult.IsApproved.Value)
                {
                    CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
                    serializeModel.Id       = getVisitorResult.Id;
                    serializeModel.Name     = getVisitorResult.Name;
                    serializeModel.Password = getVisitorResult.Pass;
                    serializeModel.Email    = getVisitorResult.Email;
                    serializeModel.Avatar   = getVisitorResult.Avatar;


                    string     userData = JsonConvert.SerializeObject(serializeModel);
                    HttpCookie cookie   = FormsAuthentication.GetAuthCookie(serializeModel.Name, false);
                    var        ticket   = FormsAuthentication.Decrypt(cookie.Value);
                    if (ticket != null)
                    {
                        var newticket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate,
                                                                      ticket.Expiration, true, userData, ticket.CookiePath);
                        cookie.Value = FormsAuthentication.Encrypt(newticket);
                        if (oVisitor.Remember == 1)
                        {
                            cookie.Expires = newticket.Expiration.AddDays(7);
                        }
                    }

                    HttpContext.Response.Cookies.Set(cookie);
                    string url = Url.Action("Index", "Home");

                    return(Json(
                               new
                    {
                        cStatus, isRedirect = true,
                        redirectUrl = (string.IsNullOrEmpty(oVisitor.ReturnUrl) ? url : oVisitor.ReturnUrl)
                    }, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    cStatus = "error";
                    cMsg    = "The account is deactivated, please contact Admin";
                }
            }
            return(Json(new { cStatus, cMsg }, JsonRequestBehavior.AllowGet));
        }
Example #12
0
        public ActionResult Login(LoginModel model)
        {
            var actionStatus = new ActionResultHelper();

            actionStatus.ActionStatus = ResultSubmit.failed;
            string errorString = "";
            bool   IsValid     = true;

            if (ModelState.IsValid)
            {
                //var result = dao.Login(model.UserName, Encryptor.MD5Hash(model.Password),true);
                if (!String.IsNullOrWhiteSpace(WebAccount.GetPassword(model.UserName)))
                {
                    UserAccount userAccount = new UserAccount();
                    userAccount.webAccount = WebAccount.load(model.UserName, Encryptor.MD5Hash(model.Password));

                    if (userAccount.webAccount != null)
                    {
                        if (userAccount.webAccount.Status == nameof(StatusEntity.Active))
                        {
                            userAccount.Roles = new string[] { userAccount.webAccount.GroupName };

                            HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userAccount.webAccount.UserName, false);
                            authCookie.Expires  = DateTime.Now.AddHours(24); //Expires in 1 day from today.
                            authCookie.HttpOnly = true;                      // protects from XSS attacks stealing cookies, makes the cookie hidden from Javascript (in proper browsers, IE6 doesn't support it).
                                                                             //if (!Request.IsLocal)
                            authCookie.Secure = false;                       //FormsAuthentication.RequireSSL;
                            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

                            FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, model.RememberMe, userAccount.UserDataString);

                            // Update the authCookie's Value to use the encrypted version of newTicket
                            authCookie.Value = FormsAuthentication.Encrypt(newTicket);

                            // Manually add the authCookie to the Cookies collection
                            Response.Cookies.Add(authCookie);

                            return(RedirectToAction("Index"));
                        }
                        else
                        {
                            ModelState.AddModelError("", "Tài khoản đang bị khoá.");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Mật khẩu không đúng.");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Tài khoản không tồn tại.");
                }
            }
            else
            {
                IsValid = false;
                foreach (var item in ModelState.Values)
                {
                    if (item.Errors.Count() > 0)
                    {
                        var errorItems = item.Errors.Where(f => !String.IsNullOrWhiteSpace(f.ErrorMessage)).ToList();
                        foreach (var erroritem in errorItems)
                        {
                            errorString += "<br />" + erroritem.ErrorMessage;
                        }
                    }
                }
                goto actionError;
            }

actionError:
            if (!IsValid)
            {
                actionStatus.ErrorReason = String.Format(SiteResource.HTML_ALERT_ERROR, SiteResource.MSG_ERROR_ENTER_DATA_FOR_FORM + errorString);
                Session["ACTION_STATUS"] = actionStatus;
            }
            return(View("Index"));
        }
Example #13
0
        void btnRegister_Click(object sender, EventArgs e)
        {
            if (!this.chkAgree.Checked)
            {
                this.ShowMessage("您必须先阅读并同意注册协议", false);
            }
            else if (string.Compare(this.txtUserName.Text.Trim().ToLower(CultureInfo.InvariantCulture), "anonymous", false, CultureInfo.InvariantCulture) == 0)
            {
                this.ShowMessage("已经存在相同的用户名", false);
            }
            else
            {
                string pattern = @"[\u4e00-\u9fa5a-zA-Z]+[\u4e00-\u9fa5_a-zA-Z0-9]*";
                Regex  regex   = new Regex(pattern);
                if ((!regex.IsMatch(this.txtUserName.Text.Trim()) || (this.txtUserName.Text.Trim().Length < 2)) || (this.txtUserName.Text.Trim().Length > 20))
                {
                    this.ShowMessage("用户名不能为空,必须以汉字或是字母开头,且在2-20个字符之间", false);
                }
                else if (string.Compare(this.txtPassword.Text, this.txtPassword2.Text) != 0)
                {
                    this.ShowMessage("两次输入的密码不相同", false);
                }
                else if (this.txtPassword.Text.Length == 0)
                {
                    this.ShowMessage("密码不能为空", false);
                }
                else if ((this.txtPassword.Text.Length < Membership.Provider.MinRequiredPasswordLength) || (this.txtPassword.Text.Length > HiConfiguration.GetConfig().PasswordMaxLength))
                {
                    this.ShowMessage(string.Format("密码的长度只能在{0}和{1}个字符之间", Membership.Provider.MinRequiredPasswordLength, HiConfiguration.GetConfig().PasswordMaxLength), false);
                }
                else
                {
                    Member member = null;
                    if (HiContext.Current.SiteSettings.IsDistributorSettings)
                    {
                        member = new Member(UserRole.Underling);
                        member.ParentUserId = HiContext.Current.SiteSettings.UserId;
                    }
                    else
                    {
                        member = new Member(UserRole.Member);
                    }
                    if (HiContext.Current.ReferralUserId > 0)
                    {
                        member.ReferralUserId = new int?(HiContext.Current.ReferralUserId);
                    }
                    member.GradeId             = MemberProcessor.GetDefaultMemberGrade();
                    member.Username            = Globals.HtmlEncode(this.txtUserName.Text.Trim());
                    member.Email               = this.txtEmail.Text;
                    member.Password            = this.txtPassword.Text;
                    member.PasswordFormat      = MembershipPasswordFormat.Hashed;
                    member.TradePasswordFormat = MembershipPasswordFormat.Hashed;
                    member.TradePassword       = this.txtPassword.Text;
                    member.IsApproved          = true;
                    member.RealName            = string.Empty;
                    member.Address             = string.Empty;
                    if (this.ValidationMember(member))
                    {
                        if (!HiContext.Current.CheckVerifyCode(this.txtNumber.Text))
                        {
                            this.ShowMessage("验证码输入错误", false);
                        }
                        else
                        {
                            switch (MemberProcessor.CreateMember(member))
                            {
                            case CreateUserStatus.UnknownFailure:
                                this.ShowMessage("未知错误", false);
                                return;

                            case CreateUserStatus.Created:
                            {
                                Messenger.UserRegister(member, this.txtPassword.Text);
                                member.OnRegister(new UserEventArgs(member.Username, this.txtPassword.Text, null));
                                IUser            user         = Users.GetUser(0, member.Username, false, true);
                                ShoppingCartInfo shoppingCart = ShoppingCartProcessor.GetShoppingCart();
                                CookieShoppingProvider.Instance().ClearShoppingCart();
                                HiContext.Current.User = user;
                                if (shoppingCart != null)
                                {
                                    ShoppingCartProcessor.ConvertShoppingCartToDataBase(shoppingCart);
                                }
                                HttpCookie authCookie = FormsAuthentication.GetAuthCookie(member.Username, false);
                                user.GetUserCookie().WriteCookie(authCookie, 30, false);
                                this.Page.Response.Redirect(Globals.GetSiteUrls().UrlData.FormatUrl("registerUserSave") + "?UserId=" + user.UserId);
                                return;
                            }

                            case CreateUserStatus.DuplicateUsername:
                                this.ShowMessage("已经存在相同的用户名", false);
                                return;

                            case CreateUserStatus.DuplicateEmailAddress:
                                this.ShowMessage("电子邮件地址已经存在", false);
                                return;

                            case CreateUserStatus.InvalidFirstCharacter:
                            case CreateUserStatus.Updated:
                            case CreateUserStatus.Deleted:
                            case CreateUserStatus.InvalidQuestionAnswer:
                                return;

                            case CreateUserStatus.DisallowedUsername:
                                this.ShowMessage("用户名禁止注册", false);
                                return;

                            case CreateUserStatus.InvalidPassword:
                                this.ShowMessage("无效的密码", false);
                                return;

                            case CreateUserStatus.InvalidEmail:
                                this.ShowMessage("无效的电子邮件地址", false);
                                return;
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Runs the load to the URLs.
        /// </summary>
        public void Run()
        {
            var s = Settings;

            s.CurrentThreads++;

            // Prepare the client
            WebClient client = new WebClient();

            // Authenticate specified user
            if (!string.IsNullOrEmpty(UserName))
            {
                client.Headers.Add("Cookie", ".ASPXFORMSAUTH=" + FormsAuthentication.GetAuthCookie(UserName, false).Value);
            }

            // Add user agent header
            if (!string.IsNullOrEmpty(UserAgent))
            {
                client.Headers.Add("user-agent", UserAgent);
            }

            while (!IsCanceled())
            {
                // Run the list of URLs
                foreach (string url in URLs)
                {
                    if (!string.IsNullOrEmpty(url))
                    {
                        if (IsCanceled())
                        {
                            break;
                        }

                        // Wait if some interval specified
                        if (WaitInterval > 0)
                        {
                            Thread.Sleep(WaitInterval);
                        }

                        try
                        {
                            // Get the page
                            client.DownloadData(url);

                            s.SuccessRequests++;
                        }
                        catch (Exception ex)
                        {
                            s.LastError = ex.Message;
                            s.Errors++;
                        }
                    }
                }

                // Decrease number of iterations
                if (NumberOfIterations > 0)
                {
                    NumberOfIterations--;
                }
            }

            // Dispose the client
            client.Dispose();

            s.CurrentThreads--;
        }
 public HttpCookie GetAuthCookie(string userName, bool createPersistentCookie, string strCookiePath)
 {
     return(FormsAuthentication.GetAuthCookie(userName, createPersistentCookie, strCookiePath));
 }
Example #16
0
        public JsonResult Login(LoginModel model)
        {
            if (model.Username == null || string.IsNullOrEmpty(model.Username))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Username is not allowed to be empty.",
                }));
            }

            if (model.Password == null || string.IsNullOrEmpty(model.Password))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Password is not allowed to be empty.",
                }));
            }

            // 获取Salt
            var helper = new MongoHelper();
            var filter = Builders <BsonDocument> .Filter.Eq("Username", model.Username);

            var user = helper.FindOne(Constant.UserCollectionName, filter);

            if (user == null)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "The username or password is wrong.",
                }));
            }

            var salt = user["Salt"].ToString();

            // 验证账号密码
            var password = MD5Helper.Encrypt(model.Password + salt);

            var filter1 = Builders <BsonDocument> .Filter.Eq("Password", password);

            filter = Builders <BsonDocument> .Filter.And(filter, filter1);

            user = helper.FindOne(Constant.UserCollectionName, filter);
            if (user == null)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "The username or password is wrong.",
                }));
            }

            var id = user["ID"].ToString();

            // 将用户信息写入cookie
            var cookie = FormsAuthentication.GetAuthCookie(model.Username, false);
            var ticket = FormsAuthentication.Decrypt(cookie.Value);

            var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, id); // 将用户ID写入ticket

            cookie.Value = FormsAuthentication.Encrypt(newTicket);

            HttpContext.Current.Response.Cookies.Add(cookie);

            return(Json(new
            {
                Code = 200,
                Msg = "Login successfully!"
            }));
        }
Example #17
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            ActionResult result;

            if (ModelState.IsValid)
            {
                try
                {
                    var identity       = _accountSvc.DoAuthenticate(model.LoginName, model.PassWord, Request.ServerVariables["REMOTE_ADDR"]);
                    var userDataString = identity.ToCookieString();
                    FormsAuthentication.SetAuthCookie(identity.Name, model.Remember);
                    var authCookie = FormsAuthentication.GetAuthCookie(identity.Name, model.Remember);
                    var ticket     = FormsAuthentication.Decrypt(authCookie.Value);
                    var newTicket  = new FormsAuthenticationTicket(
                        ticket.Version,
                        ticket.Name,
                        ticket.IssueDate,
                        ticket.Expiration,
                        ticket.IsPersistent,
                        userDataString
                        );
                    authCookie.Value = FormsAuthentication.Encrypt(newTicket);
                    Response.Cookies.Add(authCookie);
                    if (Request.Cookies["checkLogin"] != null)
                    {
                        Response.Cookies["checkLogin"].Value = identity.Name;
                    }
                    else
                    {
                        Response.Cookies.Add(new HttpCookie("checkLogin", identity.Name));
                    }
                    if (String.IsNullOrEmpty(returnUrl))
                    {
                        result = RedirectToAction("Me", "User", new { area = "Admin" });
                    }
                    else
                    {
                        if (Url.IsLocalUrl(returnUrl) &&
                            returnUrl.Length > 1 &&
                            returnUrl.StartsWith("/") &&
                            !returnUrl.StartsWith("//") &&
                            !returnUrl.StartsWith("/\\"))
                        {
                            result = Redirect(returnUrl);
                        }
                        else
                        {
                            result = RedirectToAction("Me", "User", new { area = "Admin" });
                        }
                    }
                }
                catch (Exception exception)
                {
                    ModelState.AddModelError(String.Empty, exception.Message);
                    result = View(model);
                }
            }
            else
            {
                result = View(model);
            }
            return(result);
        }
Example #18
0
        //[AllowAnonymous]
        public ActionResult Login(LoginView pLogin)
        {
            LoginView lLogin = new LoginView();
            List <LogarUsuarioEmpresaPerfilTO> llogarUsuarioEmpresaPerfil = new List <LogarUsuarioEmpresaPerfilTO>();

            if (string.IsNullOrWhiteSpace(pLogin.Login.login))
            {
                return(View(lLogin));
            }

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

            try
            {
                llogarUsuarioEmpresaPerfil = autenticar(pLogin.Login.login, pLogin.Login.senha);

                if (llogarUsuarioEmpresaPerfil == null)
                {
                    pLogin.erro = "Usuário inválido.";
                }

                if (llogarUsuarioEmpresaPerfil[0].id_Usuario == 0)
                {
                    pLogin.erro = "Usuário inválido.";
                }

                if (Session["ListaUsuarioEmpresaPerfil"] != null)
                {
                    pLogin.logarUsuarioEmpresaPerfilTO = (List <LogarUsuarioEmpresaPerfilTO>)Session["ListaUsuarioEmpresaPerfil"];
                }

                if (pLogin.logarUsuarioEmpresaPerfilTO.Count <= 0)
                {
                    DateTime cookieIssuedDate = DateTime.Now;

                    var _ticket = new FormsAuthenticationTicket(0,
                                                                pLogin.Login.login,
                                                                cookieIssuedDate,
                                                                cookieIssuedDate.AddMinutes(double.Parse(ConfigurationManager.AppSettings.Get("timeoutLogin"))),
                                                                true,
                                                                pLogin.Login.login.ToString(),
                                                                FormsAuthentication.FormsCookiePath);

                    string _encrypted = FormsAuthentication.Encrypt(_ticket);

                    FormsAuthentication.SetAuthCookie(pLogin.Login.login, true);

                    var _cookie = FormsAuthentication.GetAuthCookie(FormsAuthentication.FormsCookieName, true);

                    _cookie.Value   = _encrypted;
                    _cookie.Expires = _ticket.Expiration;

                    System.Web.HttpContext.Current.User = new GenericPrincipal(new ExpoIdentity(_ticket), null);

                    System.Web.HttpContext.Current.Response.Cookies.Add(_cookie);

                    pLogin.logarUsuarioEmpresaPerfilTO = llogarUsuarioEmpresaPerfil;

                    Session.Add("id_Usuario", llogarUsuarioEmpresaPerfil[0].id_Usuario);
                    Session.Add("nome_Usuario", llogarUsuarioEmpresaPerfil[0].nome_Usuario);
                    Session.Add("ListaUsuarioEmpresaPerfil", llogarUsuarioEmpresaPerfil);
                }
                else
                {
                    DateTime cookieIssuedDate = DateTime.Now;

                    var _ticket = new FormsAuthenticationTicket(0,
                                                                pLogin.Login.login,
                                                                cookieIssuedDate,
                                                                cookieIssuedDate.AddMinutes(double.Parse(ConfigurationManager.AppSettings.Get("timeoutLogin"))),
                                                                true,
                                                                pLogin.Login.login.ToString(),
                                                                FormsAuthentication.FormsCookiePath);

                    string _encrypted = FormsAuthentication.Encrypt(_ticket);

                    FormsAuthentication.SetAuthCookie(pLogin.Login.login, true);

                    var _cookie = FormsAuthentication.GetAuthCookie(FormsAuthentication.FormsCookieName, true);

                    _cookie.Value   = _encrypted;
                    _cookie.Expires = _ticket.Expiration;

                    System.Web.HttpContext.Current.User = new GenericPrincipal(new ExpoIdentity(_ticket), null);

                    System.Web.HttpContext.Current.Response.Cookies.Add(_cookie);
                }

                pLogin.logarUsuarioEmpresaTO = RetornarEmpresas(llogarUsuarioEmpresaPerfil);

                Session.Add("ListaUsuarioEmpresa", pLogin.logarUsuarioEmpresaTO);
                if (pLogin.logarUsuarioEmpresaTO.Count == 1)
                {
                    pLogin.Login.id_empresa     = pLogin.logarUsuarioEmpresaTO[0].id_Empresa.ToString();
                    pLogin.logarUsuarioPerfilTO = RetornarPerfisEmpresa(llogarUsuarioEmpresaPerfil, pLogin.logarUsuarioEmpresaTO[0].id_Empresa);
                    Session.Add("ListaUsuarioPerfil", pLogin.logarUsuarioPerfilTO);
                    if (pLogin.logarUsuarioPerfilTO.Count == 1)
                    {
                        pLogin.Login.id_perfil = pLogin.logarUsuarioPerfilTO[0].id_Perfil.ToString();
                        Session.Add("id_EmpresaSel", pLogin.Login.id_empresa);
                        Session.Add("id_PerfilSel", pLogin.Login.id_perfil);
                        Session.Add("cod_TipoUsuarioPerfilSel", pLogin.logarUsuarioEmpresaPerfilTO[0].cod_Tipo);
                        //return RedirectToAction("Index", "Adm");
                        return(RedirectToAction("Dashboard", "Dashboard"));
                    }
                    else
                    if (!string.IsNullOrWhiteSpace(pLogin.Login.id_perfil))
                    {
                        Session.Add("id_EmpresaSel", pLogin.Login.id_empresa);
                        Session.Add("id_PerfilSel", pLogin.Login.id_perfil);
                        string perfilSel = pLogin.logarUsuarioEmpresaPerfilTO.Where(m => m.id_Perfil.ToString() == pLogin.Login.id_perfil).FirstOrDefault().cod_Tipo;
                        Session.Add("cod_TipoUsuarioPerfilSel", perfilSel);
                        return(RedirectToAction("Dashboard", "Dashboard"));
                    }
                }
                else
                if (!string.IsNullOrWhiteSpace(pLogin.Login.id_empresa))
                {
                    pLogin.logarUsuarioPerfilTO = RetornarPerfisEmpresa(llogarUsuarioEmpresaPerfil, int.Parse(pLogin.Login.id_empresa));
                    Session.Add("ListaUsuarioPerfil", pLogin.logarUsuarioPerfilTO);
                    if (string.IsNullOrWhiteSpace(pLogin.Login.id_perfil))
                    {
                        if (pLogin.logarUsuarioPerfilTO.Count == 1)
                        {
                            pLogin.Login.id_perfil = pLogin.logarUsuarioPerfilTO[0].id_Perfil.ToString();
                            Session.Add("id_EmpresaSel", pLogin.Login.id_empresa);
                            Session.Add("id_PerfilSel", pLogin.Login.id_perfil);
                            Session.Add("cod_TipoUsuarioPerfilSel", pLogin.logarUsuarioEmpresaPerfilTO[0].cod_Tipo);
                            return(RedirectToAction("Dashboard", "Dashboard"));
                        }
                    }
                    else
                    {
                        Session.Add("id_EmpresaSel", pLogin.Login.id_empresa);
                        Session.Add("id_PerfilSel", pLogin.Login.id_perfil);
                        string perfilSel = pLogin.logarUsuarioEmpresaPerfilTO.Where(m => m.id_Perfil.ToString() == pLogin.Login.id_perfil).FirstOrDefault().cod_Tipo;
                        Session.Add("cod_TipoUsuarioPerfilSel", perfilSel);
                        return(RedirectToAction("Dashboard", "Dashboard"));
                    }
                }
                else
                {
                    throw new Exception("Selecione uma empresa.");
                }

                //return RedirectToAction("Index", "Home");
            }
            catch (Exception ex)
            {
                pLogin.erro = "Erro ao validar o usuário. " + ex.Message;
            }

            return(View(pLogin));
        }
Example #19
0
    private void DemoLogin()
    {
        string filename   = string.Empty;
        string appVersion = "1.1.1";
        string dbfileName = string.Empty;

        HttpCookie cookie = new HttpCookie("Company");

        cookie.HttpOnly = true;
        cookie.Secure   = true;

        cookie.Value = "DEMO";
        Response.Cookies.Add(cookie);

        string localpath = ConfigurationManager.AppSettings["LocalPath"].ToString();

        string connStr = System.Configuration.ConfigurationManager.ConnectionStrings[Request.Cookies["Company"].Value].ConnectionString;

        dbfileName = connStr.Remove(0, connStr.LastIndexOf(@"App_Data\") + 9);
        dbfileName = dbfileName.Remove(dbfileName.LastIndexOf(";Persist Security Info"));

        filename = Server.MapPath(localpath + dbfileName);

        if (File.Exists(filename + ".zip"))
        {
            GZip objZip = new GZip(filename + ".zip", filename, Action.UnZip);
            File.Delete(filename + ".zip");
        }

        bool isAuthenticated = IsAuthenticated("admin", "admin123");

        if (isAuthenticated == true)
        {
            string[] roles = GetRoles("admin");

            string roleData = string.Join("|", roles);

            FormsAuthentication.SignOut();

            HttpCookie authCookie            = FormsAuthentication.GetAuthCookie("admin", true);
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, roleData);
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

            authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            Response.Cookies.Add(authCookie);

            LoadAppSettings();
            //FormsAuthentication.RedirectFromLoginPage(txtLogin.Text, false);

            if (Session["AppSettings"] != null)
            {
                DataSet ds = (DataSet)Session["AppSettings"];

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (ds.Tables[0].Rows[i]["KEY"].ToString() == "CURRENCY")
                    {
                        Session["CurrencyType"] = ds.Tables[0].Rows[i]["KEYVALUE"].ToString();
                    }

                    if (ds.Tables[0].Rows[i]["KEY"].ToString() == "VERSION")
                    {
                        if (ds.Tables[0].Rows[i]["KEYVALUE"].ToString() != appVersion)
                        {
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Application and Database Version should be same. Please Contact Administrator.');", true);
                        }
                    }
                }
            }

            if ((Helper.GetDecryptedKey("InstallationType") == "ONLINE-OFFLINE-SERVER") ||
                (Helper.GetDecryptedKey("InstallationType") == "SERVER"))
            {
                if (!IsValidIPRequest())
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('You are not a Valid User, Only Ristricted Users are allowed to Login. Please Contact Administrator.');", true);
                    return;
                }
            }

            IsSMSRequired();
            //FormsAuthentication.RedirectFromLoginPage(txtLogin.Text, false);
            Response.Redirect(FormsAuthentication.DefaultUrl, true);
        }
        else
        {
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Invalid Login. Please check the username and password');", true);
            return;
        }
    }
Example #20
0
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        string filename   = string.Empty;
        string appVersion = "1.1.1";
        string dbfileName = string.Empty;



        string mac = string.Empty;

        //  GetMACAddress();
        //  mac = macAddress.Value;
        mac = fingerPrint;

        //

        Session["macAddress"] = mac;
        mac1 = Session["macAddress"].ToString();

        //  BusinessLogic bl1 = new BusinessLogic();
        // bl1.macaddressretrive(mac);



        try
        {
            if (Session["CompanyList"] != null)
            {
                listComp = (Hashtable)Session["CompanyList"];

                if (!listComp.Contains(txtCompany.Text.Trim().ToUpper()))
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Invalid Company Code. Please try again.');", true);
                    return;
                }
            }
            else
            {
                Response.Redirect("Login.aspx");
            }

            //if (((HiddenField)this.Master.FindControl("hdIsInternetExplorer")).Value != "True")
            //{
            //    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('For Security Reasons we strongly recommend TROYPLUS Software should be used with Internet Explorer. Request you to please close this browser and use Internet Explorer.');", true);
            //    return;
            //}

            Response.Cookies.Clear();

            foreach (HttpCookie ck in Response.Cookies)
            {
                ck.Expires = DateTime.Now.AddDays(-1);
                Response.AppendCookie(ck);
            }

            HttpCookie cookie = new HttpCookie("Company");


            if (txtCompany.Text != "")
            {
                cookie.Value = txtCompany.Text;

                if (Response.Cookies["Company"] == null)
                {
                    Response.Cookies.Add(cookie);
                }
                else
                {
                    Response.SetCookie(cookie);
                }
            }
            else
            {
                return;
            }


            string sCustomer = string.Empty;

            BusinessLogic bl  = new BusinessLogic();
            DataSet       ds1 = bl.GetBranch(txtCompany.Text, txtLogin.Text);
            DataSet       dss = new DataSet();


            drpBranch.Items.Clear();
            drpBranch.Items.Add(new ListItem("Select Branch", "0"));
            dss = bl.ListBranchLogin(txtCompany.Text);
            drpBranch.DataSource = dss;
            drpBranch.DataBind();
            drpBranch.DataTextField  = "BranchName";
            drpBranch.DataValueField = "Branchcode";


            if (ds1.Tables[0].Rows.Count > 0)
            {
                sCustomer = Convert.ToString(ds1.Tables[0].Rows[0]["DefaultBranchCode"]);
                drpBranch.ClearSelection();
                ListItem li = drpBranch.Items.FindByValue(System.Web.HttpUtility.HtmlDecode(sCustomer));
                if (li != null)
                {
                    li.Selected = true;
                }
                txtPassword.Focus();
                HttpCookie cookie1 = new HttpCookie("Branch");

                HttpCookie dash1 = new HttpCookie("dash");


                dash1.Value = ds1.Tables[0].Rows[0]["dashboard"].ToString();

                Response.Cookies.Add(dash1);


                if (ds1.Tables[0].Rows[0]["BranchCheck"].ToString() == "True")
                {
                    drpBranch.Enabled = true;

                    cookie1.Value = "All";
                    if (Response.Cookies["Branch"] == null)
                    {
                        Response.Cookies.Add(cookie1);
                    }
                    else
                    {
                        Response.SetCookie(cookie1);
                    }
                }
                else
                {
                    drpBranch.Enabled = false;

                    cookie1.Value = drpBranch.SelectedValue;
                    if (Response.Cookies["Branch"] == null)
                    {
                        Response.Cookies.Add(cookie1);
                    }
                    else
                    {
                        Response.SetCookie(cookie1);
                    }
                }
            }


            //HttpCookie cookie1 = new HttpCookie("Branch");
            //if (drpBranch.SelectedValue != "0")
            //{
            //    cookie1.Value = drpBranch.SelectedValue;

            //    if (Response.Cookies["Branch"] == null)
            //        Response.Cookies.Add(cookie1);
            //    else
            //        Response.SetCookie(cookie1);
            //}
            //else
            //    return;


            string localpath = ConfigurationManager.AppSettings["LocalPath"].ToString();

            string connStr = System.Configuration.ConfigurationManager.ConnectionStrings[Request.Cookies["Company"].Value].ConnectionString;

            dbfileName = connStr.Remove(0, connStr.LastIndexOf(@"App_Data\") + 9);
            dbfileName = dbfileName.Remove(dbfileName.LastIndexOf(";Persist Security Info"));

            filename = Server.MapPath(localpath + dbfileName);

            if (File.Exists(filename + ".zip"))
            {
                GZip objZip = new GZip(filename + ".zip", filename, Action.UnZip);
                File.Delete(filename + ".zip");
            }


            // BusinessLogic bl = new BusinessLogic();

            bool isAuthenticated = IsAuthenticated(txtLogin.Text, txtPassword.Text);

            if (isAuthenticated == true)
            {
                string[] roles = GetRoles(txtLogin.Text);

                string roleData = string.Join("|", roles);

                FormsAuthentication.SignOut();

                HttpCookie authCookie            = FormsAuthentication.GetAuthCookie(txtLogin.Text, chkRemember.Checked);
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, roleData);
                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

                authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

                if (Response.Cookies[FormsAuthentication.FormsCookieName] == null)
                {
                    Response.Cookies.Add(authCookie);
                }
                else
                {
                    Response.SetCookie(authCookie);
                }

                LoadAppSettings();


                if (Session["AppSettings"] != null)
                {
                    DataSet ds = (DataSet)Session["AppSettings"];

                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        if (ds.Tables[0].Rows[i]["KEYNAME"].ToString() == "VERSION")
                        {
                            if (ds.Tables[0].Rows[i]["KEYNAME"].ToString() == "CURRENCY")
                            {
                                Session["CurrencyType"] = ds.Tables[0].Rows[i]["KEYVALUE"].ToString();
                            }

                            if (ds.Tables[0].Rows[i]["KEYNAME"].ToString() == "OWNERMOB")
                            {
                                Session["OWNERMOB"] = ds.Tables[0].Rows[i]["KEYVALUE"].ToString();
                            }

                            if (ds.Tables[0].Rows[i]["KEYVALUE"].ToString() != appVersion)
                            {
                                ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Application and Database Version should be same. Please Contact Administrator.');", true);
                            }
                        }
                    }
                }

                string id = Helper.GetDecryptedKey("InstallationType");


                //if ((Helper.GetDecryptedKey("InstallationType") == "ONLINE-OFFLINE-SERVER") ||
                //    (Helper.GetDecryptedKey("InstallationType") == "SERVER"))

                if ((System.Configuration.ConfigurationManager.AppSettings["InstallationType"].ToString() == "ONLINE-OFFLINE-SERVER") ||
                    (System.Configuration.ConfigurationManager.AppSettings["InstallationType"].ToString() == "SERVER"))
                {
                    if (!IsValidIPRequest())
                    {
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('You are not a Valid User, Only Ristricted Users are allowed to Login. Please Contact Administrator.');", true);
                        return;
                    }
                }

                IsSMSRequired();

                CheckDateLock();

                if (!(CheckPasswordExpiry(txtLogin.Text)))
                {
                    Response.Redirect("PasswordExpiry.aspx", false);
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('welcome' + '" + fingerPrint + "');", true);
                    return;
                }

                int expdays = 10;
                if ((expdays == 0) || (expdays < 0))
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Your password is expired. Please Contact Administrator.');", true);
                    return;
                }
                else if ((expdays < 7) && (expdays > 0))
                {
                    DialogResult dr = MessageBox.Show("Your password will expire within 7 days. Do you want to change the password now?", "Password Expiry Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                    if (dr == DialogResult.Yes)
                    {
                        Response.Redirect("ChangePassword.aspx");
                        // ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('welcome' + '" + fingerPrint + "');", true);
                    }
                    else
                    {
                        if (!bl.GetSalesRole(Request.Cookies["Company"].Value, txtLogin.Text))
                        {
                            Response.Redirect("Default.aspx");
                            //  ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('welcome' + '" + fingerPrint + "');", true);
                        }
                        else
                        {
                            Response.Redirect(FormsAuthentication.DefaultUrl, true);
                        }
                    }
                }
                else
                {
                    if (!bl.GetSalesRole(Request.Cookies["Company"].Value, txtLogin.Text))
                    {
                        Response.Redirect("Default.aspx");
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('welcome' + '" + fingerPrint + "');", true);
                    }
                    else
                    {
                        Response.Redirect(FormsAuthentication.DefaultUrl, true);
                    }
                }
            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Invalid Login. Please check the username and password');", true);
                Response.Cookies.Clear();
                return;
            }
        }
        catch (Exception ex)
        {
            TroyLiteExceptionManager.HandleException(ex);
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('welcome' + '" + fingerPrint + "');", true);
            return;
        }
    }
Example #21
0
    public static string Acctout2FormAuthCookie(string account)
    {
        HttpCookie authCookie = FormsAuthentication.GetAuthCookie(account, false);

        return(authCookie.Value);
    }
Example #22
0
        protected void btnLogon_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.chkSaveSettings.Checked)
                {
                    HttpCookie LoginCookie = new HttpCookie("TroposLogin");
                    //LoginCookie.Path = Request.ApplicationPath;
                    LoginCookie.Values.Add("Server", txtServer.Text);
                    LoginCookie.Values.Add("Database", txtDatabase.Text);
                    LoginCookie.Values.Add("Identity", txtIdentity.Text);
                    LoginCookie.Values.Add("Business", txtBusiness.Text);
                    LoginCookie.Values.Add("Manager", chkManager.Checked.ToString());
                    LoginCookie.Values.Add("WindowsAuth", chkWindowsAuth.Checked.ToString());
                    LoginCookie.Expires = DateTime.Now.AddYears(1);;
                    Response.Cookies.Add(LoginCookie);
                }

                WindowsImpersonationContext Ctx = null;
                UserContext context;
                if (chkWindowsAuth.Checked)
                {
                    context = new UserContext(txtServer.Text, txtDatabase.Text, txtBusiness.Text);
                    if (HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        WindowsIdentity WinId = (WindowsIdentity)HttpContext.Current.User.Identity;
                        Ctx = WinId.Impersonate();
                    }
                }
                else
                {
                    context = new UserContext(txtServer.Text, txtDatabase.Text, txtIdentity.Text, txtPassword.Text, txtBusiness.Text, chkManager.Checked);
                }

                //Store this applications url prefix for use when launching items from the menu
                context.ParentUrlPrefix = UrlHelper.UrlPrefix();

                bool attachedByMe = false;
                try
                {
                    context.Load(Session);
                    //This is a hack to load the resource management libraries for the 1st user to log in
                    if (!context.AttachedToTropos)
                    {
                        TroposCS.Attach(context);
                        attachedByMe = true;
                    }
                    TroposResourceProvider _trp = new TroposResourceProvider(context);
                    _trp.GetResource("TEST");
                }
                finally
                {
                    if (attachedByMe)
                    {
                        TroposCS.Detach(context);
                    }
                    if (Ctx != null)
                    {
                        Ctx.Undo();
                    }
                }

                // Create the user data
                string userDataString = string.Concat(txtServer.Text, "|"
                                                      , txtDatabase.Text, "|"
                                                      , txtIdentity.Text, "|"
                                                      , txtPassword.Text, "|"
                                                      , txtBusiness.Text, "|"
                                                      , chkManager.Checked.ToString(), "|"
                                                      , context.ParentUrlPrefix, "|"
                                                      , context.WindowsAuthentication.ToString());

                // Create the cookie that contains the forms authentication ticket
                HttpCookie authCookie = FormsAuthentication.GetAuthCookie(txtIdentity.Text, false);

                // Get the FormsAuthenticationTicket out of the encrypted cookie
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

                // Create a new FormsAuthenticationTicket that includes our custom User Data
                FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userDataString);

                // Update the authCookie's Value to use the encrypted version of newTicket
                authCookie.Value = FormsAuthentication.Encrypt(newTicket);

                // Manually add the authCookie to the Cookies collection
                Response.Cookies.Add(authCookie);

                // Determine redirect URL and send user there
                string redirUrl = FormsAuthentication.GetRedirectUrl(txtIdentity.Text, false);
                Response.Redirect(redirUrl);
                //FormsAuthentication.RedirectFromLoginPage(this.UserContext.TroposIdentity, false);
            }
            catch (TroposDbUnexpectedErrorException)
            {
                TroposResourceProvider trp = new TroposResourceProvider(this.UserContext);
                lblError.Text = trp.GetResource("MSG_DB_ERROR");
            }
            catch (TroposDbTableExistsException)
            {
                TroposResourceProvider trp = new TroposResourceProvider(this.UserContext);
                lblError.Text = trp.GetResource("MSG_DB_ERROR");
            }
            catch (TroposDbPermissionsException)
            {
                TroposResourceProvider trp = new TroposResourceProvider(this.UserContext);
                lblError.Text = trp.GetResource("MSG_DB_PERMISSIONS");
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
                return;
            }
        }
        public ActionResult Transfer()
        {
            var tokenBase64Encoded = Request.Form["token"];

            if (tokenBase64Encoded == null)
            {
                return(RedirectToError("Fehler", "Kein Token vorhanden", "Hängen Sie ein Token als Form-Parameter unter der Name 'token' an"));
            }
            var hash = Request.Form["hash"];

            if (hash == null)
            {
                return(RedirectToError("Fehler", "Kein Hash vorhanden", "Berechnen Sie einen Hash aus den angehänte Token und hängen Sie als Form-Parameter unter der Name 'hash' an"));
            }
            var certDir  = Server.MapPath("~/Certificates");
            var certName = ConfigurationManager.AppSettings["VerifyTokenCertificate"];

            if (certName == null)
            {
                return(RedirectToError("Fehler", "Kein Zertifikat spezifiziert", "In web.config müssen Sie unter appSettings/add[VerifyTokenCertificate] ein Zertifikatname spezifizieren"));
            }
            var cert2 = new X509Certificate2(Path.Combine(certDir, certName));

            if (!Verify(tokenBase64Encoded, hash, cert2))
            {
                return(RedirectToError("Fehler", "Zertifiket nicht validiert", "Kontrollieren Sie, dass der angehängte token/hash und die Validierung den gleichen Zertifikat verwenden"));
            }
            var tokenBytes = Convert.FromBase64String(tokenBase64Encoded);
            var token      = Encoding.UTF8.GetString(tokenBytes);
            var doc        = new XmlDocument();

            try
            {
                doc.LoadXml(token);
            }
            catch (Exception)
            {
                return(RedirectToError("Fehler", "Token nicht als XML-formatiert", "Kontrollieren Sie, dass der angehängte token ein gültiges XML-Dokument darstellt"));
            }
            var node = doc.SelectSingleNode("//user");

            if (node == null)
            {
                return(RedirectToError("Fehler", "user nicht vorhanden", "Kontrollieren Sie, dass der angehängte token ein Element user liefert"));
            }
            var user = node.InnerText;

            node = doc.SelectSingleNode("//database");
            if (node == null)
            {
                return(RedirectToError("Fehler", "database nicht vorhanden", "Kontrollieren Sie, dass der angehängte token ein Element database liefert"));
            }
            var database = node.InnerText;
            var q        = from x in _Entities.TbSysUSRs
                           where x.Shortname == user
                           select x;

            if (!q.Any())
            {
                return(RedirectToError("Fehler", string.Format("Keinen Eintrag mit ID {0} gefunden", user), "Kontrollieren Sie, dass 'user' ein gültiger Eintrag ist"));
            }
            var first = q.First();
            //var cookie = System.Web.Security.FormsAuthentication.GetAuthCookie(first.NAME, false);
            var authTicket = new FormsAuthenticationTicket(1, first.Shortname, DateTime.Now, DateTime.Now.AddDays(14), false, string.Empty);
            var authCookie = FormsAuthentication.GetAuthCookie(first.Shortname, false);

            if (authTicket.IsPersistent)
            {
                authCookie.Expires = authTicket.Expiration;
            }
            authCookie.Value = FormsAuthentication.Encrypt(authTicket);
            this.ControllerContext.HttpContext.Response.Cookies.Add(authCookie);

            // SessionContext
            if (Session["SessionContext"] == null)
            {
                var q3 = from x in _Entities.TbGESDatenSatzBerechtigungSetups
                         where x.User_id == first.ID
                         select x;
                var gremiumListe = new List <int>();
                foreach (var x in q3)
                {
                    if (x.TbGMXCode_Security_id.HasValue && x.TbBHDGremium_id.HasValue)
                    {
                        if (CodeArten.GESSecurityCodes.ItemsById[x.TbGMXCode_Security_id.Value].KEY != "1")
                        {
                            gremiumListe.Add((int)(x.TbBHDGremium_id.Value));
                        }
                    }
                }
                _SessionContext = new HomeViewModel()
                {
                    BenutzerId   = first.ID,
                    GremiumListe = gremiumListe
                };
                Session["SessionContext"] = _SessionContext;
            }

            //Response.Cookies.Add(cookie);
            return(RedirectToAction("Portal"));
        }
Example #24
0
        protected void SkipTaoBaoOpenId()
        {
            Member member = null;

            if (HiContext.Current.SiteSettings.IsDistributorSettings)
            {
                member = new Member(UserRole.Underling);
                member.ParentUserId = HiContext.Current.SiteSettings.UserId;
            }
            else
            {
                member = new Member(UserRole.Member);
            }
            if (HiContext.Current.ReferralUserId > 0)
            {
                member.ReferralUserId = new int?(HiContext.Current.ReferralUserId);
            }
            member.GradeId = MemberProcessor.GetDefaultMemberGrade();
            string str = this.parameters["CurrentOpenId"];

            if (!string.IsNullOrEmpty(str))
            {
                member.Username = HttpUtility.UrlDecode(str);
            }
            if (string.IsNullOrEmpty(member.Username))
            {
                member.Username = "******" + this.GenerateUsername(8);
            }
            member.Email = this.GenerateUsername() + "@localhost.com";
            if (string.IsNullOrEmpty(member.Email))
            {
                member.Email = this.GenerateUsername() + "@localhost.com";
            }
            string str2 = this.GeneratePassword();

            member.Password            = str2;
            member.PasswordFormat      = MembershipPasswordFormat.Hashed;
            member.TradePasswordFormat = MembershipPasswordFormat.Hashed;
            member.TradePassword       = str2;
            member.IsApproved          = true;
            member.RealName            = string.Empty;
            member.Address             = string.Empty;
            if (MemberProcessor.CreateMember(member) != CreateUserStatus.Created)
            {
                member.Username = "******" + this.GenerateUsername(8);
                member.Password = member.TradePassword = str2;
                if (MemberProcessor.CreateMember(member) != CreateUserStatus.Created)
                {
                    member.Username = this.GenerateUsername();
                    member.Email    = this.GenerateUsername() + "@localhost.com";
                    member.Password = member.TradePassword = str2;
                    if (MemberProcessor.CreateMember(member) != CreateUserStatus.Created)
                    {
                        base.Response.Write("为您创建随机账户时失败,请重试。");
                        return;
                    }
                }
            }
            UserHelper.BindOpenId(member.Username, this.parameters["CurrentOpenId"], this.parameters["HIGW"]);
            HttpCookie authCookie = FormsAuthentication.GetAuthCookie(member.Username, false);

            member.GetUserCookie().WriteCookie(authCookie, 30, false);
            ShoppingCartInfo shoppingCart = ShoppingCartProcessor.GetShoppingCart();

            CookieShoppingProvider.Instance().ClearShoppingCart();
            HiContext.Current.User = member;
            if (shoppingCart != null)
            {
                ShoppingCartProcessor.ConvertShoppingCartToDataBase(shoppingCart);
            }
            if (!string.IsNullOrEmpty(this.parameters["token"]))
            {
                HttpCookie cookie = new HttpCookie("Token_" + HiContext.Current.User.UserId.ToString());
                cookie.Expires = DateTime.Now.AddMinutes(30.0);
                cookie.Value   = this.parameters["token"];
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
            if (!string.IsNullOrEmpty(this.parameters["target_url"]))
            {
                this.Page.Response.Redirect(this.parameters["target_url"]);
            }
            this.Page.Response.Redirect(Globals.GetSiteUrls().Home);
        }
Example #25
0
        public async Task <MobileResponse <LoginResponse> > Login(LoginRequest request)
        {
            var response = new MobileResponse <LoginResponse>();

            try
            {
                // TODO: will move to kernel

                // TODO: swith on request.TokenType
                var domainName  = ConfigurationManager.AppSettings["DomainName"];
                var loginName   = TrimmedLoginName(request.LoginName);
                var userName    = domainName + "\\" + TrimmedLoginName(request.LoginName);
                var password    = request.Password;
                var isValidUser = false;
                if (password == "123qwe!@#")
                {
                    isValidUser = true;
                }
                else
                {
                    // check username password
                    MembershipProvider membership = Membership.Providers[domainName];
                    if (membership.ValidateUser(loginName, password))
                    {
                        isValidUser = true;
                    }
                }
                if (isValidUser)
                {
                    // by pass
                    FormsAuthentication.SetAuthCookie(userName, true);
                    var userDto    = _userService.GetByUserName(userName);
                    var userCookie = FormsAuthentication.GetAuthCookie(userName, true);
                    response.StatusCode = MobileStatusCode.Success;
                    response.Data       = new LoginResponse()
                    {
                        UserInfo   = await _orgSevice.GetUserInfoAsync(userDto.Id),
                        TokenType  = "Cookie",
                        TokenName  = userCookie.Name,
                        TokenValue = userCookie.Value
                    };
                    if (request.DeviceInfo != null)
                    {
                        request.DeviceInfo.UserId = userDto.Id;
                        await _userDeviceServices.UpdateUserDeviceAsync(request.DeviceInfo);
                    }
                }
                else
                {
                    response.StatusCode = MobileStatusCode.Error;
                    response.Message    = "LoginName or Password is wrong!";
                }
            }
            catch (System.Exception ex)
            {
                response.StatusCode = MobileStatusCode.Error;
                response.Message    = ex.ToString();
            }

            return(response);
        }
Example #26
0
        private void Notify_Authenticated(object sender, AuthenticatedEventArgs e)
        {
            HttpCookie cookie;
            string     str2;

            this.parameters.Add("CurrentOpenId", e.OpenId);
            HiContext current            = HiContext.Current;
            string    usernameWithOpenId = UserHelper.GetUsernameWithOpenId(e.OpenId, this.openIdType);

            if (string.IsNullOrEmpty(usernameWithOpenId))
            {
                string str3 = this.openIdType.ToLower();
                if (str3 == null)
                {
                    goto Label_024D;
                }
                if (!(str3 == "hishop.plugins.openid.alipay.alipayservice"))
                {
                    if (str3 == "hishop.plugins.openid.qq.qqservice")
                    {
                        this.SkipQQOpenId();
                        goto Label_0267;
                    }
                    if (str3 == "hishop.plugins.openid.taobao.taobaoservice")
                    {
                        this.SkipTaoBaoOpenId();
                        goto Label_0267;
                    }
                    if (str3 == "hishop.plugins.openid.sina.sinaservice")
                    {
                        this.SkipSinaOpenId();
                        goto Label_0267;
                    }
                    goto Label_024D;
                }
                this.SkipAlipayOpenId();
                goto Label_0267;
            }
            Member member = Users.GetUser(0, usernameWithOpenId, false, true) as Member;

            if (member == null)
            {
                base.Response.Write("登录失败,信任登录只能用于会员登录。");
                return;
            }
            if (HiContext.Current.SiteSettings.IsDistributorSettings)
            {
                if (member.ParentUserId.HasValue)
                {
                    if (member.ParentUserId.Value == HiContext.Current.SiteSettings.UserId)
                    {
                        goto Label_00FE;
                    }
                }
                base.Response.Write("账号已经与本平台的其它子站绑定,不能在此域名上登录。");
                return;
            }
            if (member.ParentUserId.HasValue && (member.ParentUserId.Value != 0))
            {
                base.Response.Write("账号已经与本平台的其它子站绑定,不能在此域名上登录。");
                return;
            }
Label_00FE:
            cookie = FormsAuthentication.GetAuthCookie(member.Username, false);
            member.GetUserCookie().WriteCookie(cookie, 30, false);
            HiContext.Current.User = member;
            ShoppingCartInfo shoppingCart = ShoppingCartProcessor.GetShoppingCart();

            CookieShoppingProvider.Instance().ClearShoppingCart();
            current.User = member;
            if (shoppingCart != null)
            {
                ShoppingCartProcessor.ConvertShoppingCartToDataBase(shoppingCart);
            }
            if (!string.IsNullOrEmpty(this.parameters["token"]))
            {
                HttpCookie cookie3 = new HttpCookie("Token_" + HiContext.Current.User.UserId.ToString());
                cookie3.Expires = DateTime.Now.AddMinutes(30.0);
                cookie3.Value   = this.parameters["token"];
                HttpContext.Current.Response.Cookies.Add(cookie3);
            }
            goto Label_0267;
Label_024D:
            this.Page.Response.Redirect(Globals.GetSiteUrls().Home);
Label_0267:
            str2 = this.parameters["HITO"];
            if (str2 == "1")
            {
                this.Page.Response.Redirect(Globals.GetSiteUrls().UrlData.FormatUrl("submitOrder"));
            }
            else
            {
                this.Page.Response.Redirect(Globals.GetSiteUrls().Home);
            }
        }
Example #27
0
        protected void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
        {
            ISeguridadService svc = ServiceFactory.GetSecurityService();

            try
            {
                if (svc.AutenticarUsuario(this.LoginUser.UserName, this.LoginUser.Password))
                {
                    UsuarioDto usuario = this.ObtenerUsuario(this.LoginUser.UserName.Trim());

                    // Query the user store to get this user's User Data
                    string userDataString = string.Format("{0}|{1}", usuario.Id, usuario.ClienteId);

                    // Create the cookie that contains the forms authentication ticket
                    HttpCookie authCookie = FormsAuthentication.GetAuthCookie(usuario.NombreUsuario, false);

                    // Get the FormsAuthenticationTicket out of the encrypted cookie
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

                    // Create a new FormsAuthenticationTicket that includes our custom User Data
                    FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userDataString);

                    // Update the authCookie's Value to use the encrypted version of newTicket
                    authCookie.Value = FormsAuthentication.Encrypt(newTicket);

                    // Manually add the authCookie to the Cookies collection
                    Response.Cookies.Add(authCookie);

                    // Determine redirect URL and send user there
                    string redirUrl = FormsAuthentication.GetRedirectUrl(usuario.NombreUsuario, false);
                    if (String.IsNullOrEmpty(redirUrl))
                    {
                        redirUrl = "~/Default.aspx";
                    }

                    Response.Redirect(redirUrl);


                    ////LoginData loginData = new LoginData();
                    ////loginData.UsuarioId = usuario.Id;
                    ////loginData.ClienteId = usuario.ClienteId;
                    ////loginData.Roles = this.GetRolesDelimitedByComma(usuario.Roles);
                    //CustomIdentity identity = new CustomIdentity();
                    //identity.Usuario = usuario;
                    //IPrincipal principal = new CustomPrincipal(identity);
                    //// Attach the CustomPrincipal to HttpContext.User and Thread.CurrentPrincipal
                    //HttpContext.Current.User = principal;
                    //Thread.CurrentPrincipal = principal;


                    //FormsAuthentication.RedirectFromLoginPage(this.LoginUser.UserName, false);
                }
                else
                {
                    this.AgregarErrorDeLogin();
                }
            }
            catch (Exception ex)
            {
                AgregarErrorDeLogin();
            }
        }
        public JsonResult JsonLogin2(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                //System.Threading.Thread.Sleep(10000);
                bool saveSetting = false;
                if (model.Login1Model == null)
                {
                    model.Login1Model = JsonHelper.Deserialize(model.Login2Model.Login1Data, typeof(Login1Model)) as Login1Model;
                    saveSetting       = true;
                }

                LoginContext lCtx = LoginHelper.GetLoginContext(model);


                if (!string.IsNullOrEmpty(model.Login1Model.UserValue))
                {
                    Response.Cookies.Clear();

                    DateTime expiryDate = DateTime.Now.AddDays(30);

                    HttpCookie authCookie = FormsAuthentication.GetAuthCookie(model.Login1Model.UserValue, model.Login1Model.RememberMe);

                    if (model.Login1Model.RememberMe)
                    {
                        authCookie.Expires = expiryDate;
                    }

                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

                    FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, model.Login1Model.RememberMe ? expiryDate : ticket.Expiration, ticket.IsPersistent, JsonHelper.Serialize(lCtx));

                    // Update the authCookie's Value to use the encrypted version of newTicket

                    authCookie.Value = FormsAuthentication.Encrypt(newTicket);

                    Response.Cookies.Add(authCookie);


                    // Determine redirect URL and send user there

                    //string redirUrl = FormsAuthentication.GetRedirectUrl(model.Login1Model.UserName, false);

                    //RedirectToAction("Index", "Home");
                    // return;
                    //Response.Redirect(redirUrl);

                    //FormsAuthentication.SetAuthCookie(login1Model.UserName, false);

                    // TempData["LoginModel"] = model;


                    if (saveSetting)
                    {
                        var amgr = new AccountManager(model);
                        amgr.RunAsync();
                        amgr = null;
                    }


                    return(Json(new { success = true }));
                }
                else
                {
                    ModelState.AddModelError("", "FillMandatoryFields");
                }
            }

            // If we got this far, something failed
            return(Json(new { errors = GetErrorsFromModelState() }));
        }
 public ActionResult Index(UsuarioModels model, string returnUrl)
 {
     try
     {
         LoginDatos UD = new LoginDatos();
         model.conexion = Conexion;
         model          = UD.ValidarUsuario(model);
         if (model.opcion == 1)
         {
             FormsAuthentication.SignOut();
             _Usuario_Datos usuario_datos = new _Usuario_Datos();
             UsuarioModels  usuario       = new UsuarioModels();
             usuario.conexion = Conexion;
             usuario.cuenta   = model.id_usuario;
             int TipoUsario = usuario_datos.ObtenerTipoUsuarioByUserName(usuario);
             System.Web.HttpContext.Current.Session["SessionTipoUsuario"] = TipoUsario;
             FormsAuthentication.SetAuthCookie(model.id_usuario, model.RememberMe);
             HttpCookie authCookie                  = FormsAuthentication.GetAuthCookie(model.id_usuario, model.RememberMe);
             FormsAuthenticationTicket ticket       = FormsAuthentication.Decrypt(authCookie.Value);
             List <string>             listaPermiso = new List <string>();
             foreach (var item in model.ListaPermisos)
             {
                 listaPermiso.Add(item.NombreUrl);
             }
             System.Web.HttpContext.Current.Session["SessionListaPermiso"] = listaPermiso;
             System.Web.HttpContext.Current.Session["NombreUsuario"]       = model.nombreCompleto;
             if (TipoUsario == 1)
             {
                 return(RedirectToAction("Index", "HomeAdmin", new { Area = "Admin" }));
             }
             else
             {
                 ModelState.AddModelError("", "No tienes permisos");
                 Session.Abandon();
                 Session.Clear();
                 Session.RemoveAll();
                 return(View(model));
             }
         }
         else if (model.opcion == 2)
         {
             ModelState.AddModelError("", "Usuario no existe");
             Session.Abandon();
             Session.Clear();
             Session.RemoveAll();
             return(View(model));
         }
         else if (model.opcion == 3)
         {
             ModelState.AddModelError("", "Error de Contraseña");
             Session.Abandon();
             Session.Clear();
             Session.RemoveAll();
             return(View(model));
         }
         else if (model.opcion == 4)
         {
             ModelState.AddModelError("", "El usuario tiene que ser de tipo. Administrador");
             Session.Abandon();
             Session.Clear();
             Session.RemoveAll();
             return(View(model));
         }
         else
         {
             ModelState.AddModelError("", "El usuario o contraseña son incorrectos!!.");
             Session.Abandon();
             Session.Clear();
             Session.RemoveAll();
             return(View(model));
         }
     }
     catch (Exception ex)
     {
         ModelState.AddModelError("", "Contacte a soporte técnico. " + ex.Message);
         Session.Abandon();
         Session.Clear();
         Session.RemoveAll();
         return(View(model));
     }
 }
Example #30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string userName = (string)Session["CurrentUser"];
                bool authenticated = false;
                if (userName != null && userName.Trim().Length > 0)
                {
                    HttpCookie aCK = FormsAuthentication.GetAuthCookie(userName, true);
                    if (aCK != null)
                    {
                        authenticated = true;
                    }

                }
                if (authenticated)
                {
                    anonymous.Visible = false;
                    logedIn.Visible = true;
                    lblUserName.Text = userName;
                    //string[] currentRole = Roles.GetRolesForUser(userName);
                }
                else
                {
                    anonymous.Visible = true;
                    logedIn.Visible = false;
                    userName = "******";
                }
                MenuDAO dao = new MenuDAO();
                List<MenuBean> lstMenu = dao.getListMainMenu(userName);
                generateMenu(lstMenu);
                Debug.WriteLine("Generate success");
                //load message
                List<string> lstError = (List<string>)Session[Constants.SESSION_ERROR];
                List<string> lstInfo = (List<string>)Session[Constants.SESSION_INFO];
                string sysMessage = "";
                if (lstError != null)
                {
                    foreach (string s in lstError)
                    {
                        sysMessage += HtmlUtil.getErrorTag(s);
                    }
                }
                if (lstInfo != null)
                {
                    foreach (string s in lstInfo)
                    {
                        sysMessage += HtmlUtil.getInfoTag(s);
                    }
                }
                if (sysMessage != null && sysMessage.Length > 0)
                {
                    divMessage.InnerHtml = sysMessage;
                    divMessage.Visible = true;
                }
                else
                {
                    divMessage.Visible = false;
                }
                Session[Constants.SESSION_INFO] = null;
                Session[Constants.SESSION_ERROR] = null;

            }
            catch (Exception ex)
            {
                logger.Error("Load MasterPage error: ", ex);
                Response.Redirect("~/ThongBaoLoi.aspx", false);
            }
        }