Esempio n. 1
0
        private static bool VerifyHostUser(Dictionary <string, string> accountInfo, out string errorMsg)
        {
            var result = true;

            errorMsg = string.Empty;

            UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
            var             userRequestIpAddressController = UserRequestIPAddressController.Instance;
            var             ipAddress = userRequestIpAddressController.GetUserRequestIPAddress(new HttpRequestWrapper(HttpContext.Current.Request));
            UserInfo        hostUser  = UserController.ValidateUser(-1, accountInfo["username"], accountInfo["password"], "DNN", string.Empty, string.Empty, ipAddress, ref loginStatus);

            if (loginStatus == UserLoginStatus.LOGIN_FAILURE || !hostUser.IsSuperUser)
            {
                result   = false;
                errorMsg = LocalizeStringStatic("InvalidCredentials");
            }
            else
            {
                IsAuthenticated = true;
            }

            if (result && (!accountInfo.ContainsKey("acceptTerms") || accountInfo["acceptTerms"] != "Y"))
            {
                result   = false;
                errorMsg = LocalizeStringStatic("AcceptTerms.Required");
            }

            return(result);
        }
Esempio n. 2
0
        private void btm_Login_Click(object sender, EventArgs e)
        {
            string login    = tb_Login.Text;
            string password = tb_Password.Text;

            if (string.IsNullOrWhiteSpace(login) ||
                string.IsNullOrWhiteSpace(password))
            {
                lb_ErrorLogin.Visible = true;
            }
            else
            {
                UserLoginStatus userLoginStatus = _authenticationController.Login(UserAuthenticationMapper.Map(login, password));
                if (userLoginStatus.ErrorId == OperationStatusEnum.Success)
                {
                    _authenticationController.GetUser(userLoginStatus.UserId.Value);
                    LoginStatus = true;
                    Close();
                }
                else
                {
                    LoginStatus           = false;
                    lb_ErrorLogin.Visible = true;
                }
            }
        }
Esempio n. 3
0
 protected int Login_Input()
 {
     UserLoginStatus loginStatus = new UserLoginStatus();
     UserInfo objUserInfo = UserController.ValidateUser(PortalId, tbUsername.Text, tbPassword.Text, "", PortalSettings.PortalName, Request.UserHostAddress, ref loginStatus);
     if (loginStatus == UserLoginStatus.LOGIN_SUCCESS || loginStatus == UserLoginStatus.LOGIN_SUPERUSER)
     {
         UserController.UserLogin(PortalId, objUserInfo, PortalSettings.PortalName, Request.UserHostAddress, false);
         if (cbRemember.Checked)
         {
             // Set settings
             int random = new Random().Next();
             ModuleController obModule = new ModuleController();
             obModule.UpdateModuleSetting(ModuleId, tbUsername.Text, random.ToString());
             // Set cookie
             HttpCookie obCookie = new HttpCookie(cookie_name());
             obCookie.Value = string.Format("{0}_{1}", random, tbUsername.Text);
             obCookie.Expires = DateTime.Today.AddMonths(3);
             Response.Cookies.Add(obCookie);
             obCookie = new HttpCookie("EOFFICE");
             obCookie.Value = Request.ApplicationPath;
             obCookie.Expires = DateTime.Today.AddYears(1);
             obCookie.HttpOnly = false;
             Response.Cookies.Add(obCookie);
         }
         return 1;
     }
     else
     {
         lbError.Text = "Tên đăng nhập hoặc Mật khẩu không chính xác";
         return 0;
     }
 }
 /// <summary>
 /// cmdAssociate_Click runs when the associate button is clicked
 /// </summary>
 /// <remarks>
 /// </remarks>
 /// <history>
 ///     [cnurse]	07/12/2007	Created
 /// </history>
 protected void cmdAssociate_Click(object sender, EventArgs e)
 {
     if ((UseCaptcha && ctlCaptcha.IsValid) || (!UseCaptcha))
     {
         UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
         UserInfo        objUser     = UserController.ValidateUser(PortalId,
                                                                   txtUsername.Text,
                                                                   txtPassword.Text,
                                                                   "DNN",
                                                                   "",
                                                                   PortalSettings.PortalName,
                                                                   AuthenticationLoginBase.GetIPAddress(),
                                                                   ref loginStatus);
         if (loginStatus == UserLoginStatus.LOGIN_SUCCESS)
         {
             //Assocate alternate Login with User and proceed with Login
             AuthenticationController.AddUserAuthentication(objUser.UserID, AuthenticationType, UserToken);
             if (objUser != null)
             {
                 UpdateProfile(objUser, true);
             }
             ValidateUser(objUser, true);
         }
         else
         {
             AddModuleMessage("AssociationFailed", ModuleMessage.ModuleMessageType.RedError, true);
         }
     }
 }
Esempio n. 5
0
        // REMOVED AS WE'RE NOT USING THIS
        // bool IMetaWeblog.SetPostCategories(string postid, string username, string password, MTCategory[] cat)
        // {

        // for (int i = 0; i < cat.Length; i++)
        // {
        // MTCategory mcat;
        // mcat = cat[i];
        // Item iv = Item.GetItem(Convert.ToInt32(postid), _portalId, ItemType.Article.GetId(), false);
        // Tag t = Tag.GetTag(mcat.categoryName, _portalId);

        // //if this item tag relationship already existed for another versionID don't increment the count;
        // if (!ItemTag.CheckItemTag(iv.ItemId, Convert.ToInt32(t.TagId)))
        // {
        // t.TotalItems++;
        // t.Save();
        // }

        // //it.ItemVersionId = i.ItemVersionId;
        // //ad the itemtag relationship
        // ItemTag.AddItemTag(iv.ItemVersionId, Convert.ToInt32(t.TagId));
        // }

        // throw new XmlRpcFaultException(0, Localization.GetString("FailedAuthentication.Text", LocalResourceFile));
        // }

        ///<summary>
        /// Authenticate user
        /// </summary>
        /// <param name="username">UserName</param>
        /// <param name="password">Password</param>
        private DotNetNuke.Entities.Users.UserInfo Authenticate(string username, string password)
        {
            // Check user credentials using form authentication

            // Check the portal alias to verify where the request is coming from and set portalid
            UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;

            DotNetNuke.Entities.Users.UserInfo objUser = UserController.ValidateUser(PortalId, username, password, string.Empty, string.Empty, string.Empty, ref loginStatus);

            if (loginStatus == UserLoginStatus.LOGIN_FAILURE || loginStatus == UserLoginStatus.LOGIN_USERLOCKEDOUT ||
                loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED)
            {
                throw new InvalidCredentialException(Localization.GetString("FailedAuthentication.Text", this.LocalResourceFile));
            }

            // Check for the author/admin roles in Publish
            var hostController = HostController.Instance;

            if (!objUser.IsInRole(hostController.GetString(Utility.PublishAuthorRole + PortalId)) &&
                !objUser.IsInRole(hostController.GetString(Utility.PublishAdminRole + PortalId)))
            {
                throw new InvalidCredentialException(Localization.GetString("FailedAuthentication.Text", this.LocalResourceFile));
            }

            return(objUser);
        }
Esempio n. 6
0
        /// <summary>
        /// 新建
        /// </summary>
        public void AddUserLoginStatus(UserLoginStatus userloginstatus)
        {
            //int id = GetId("userauths");
            //userauths.AuthsId = id;

            ExecuteInsert("InsertUserLoginStatus", userloginstatus);
        }
Esempio n. 7
0
        public void AuthenticateUser(UserData user, PortalSettings settings, string IPAddress, Action <NameValueCollection> addCustomProperties, Action <UserAuthenticatedEventArgs> onAuthenticated)
        {
            UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;

            string userName = Service + "-" + user.Id;

            UserInfo objUserInfo = UserController.ValidateUser(settings.PortalId, userName, "",
                                                               Service, "",
                                                               settings.PortalName, IPAddress,
                                                               ref loginStatus);


            //Raise UserAuthenticated Event
            UserAuthenticatedEventArgs eventArgs = new UserAuthenticatedEventArgs(objUserInfo, userName, loginStatus, Service);

            eventArgs.AutoRegister = true;

            NameValueCollection profileProperties = new NameValueCollection();

            profileProperties.Add("FirstName", user.FirstName);
            profileProperties.Add("LastName", user.LastName);
            profileProperties.Add("Email", user.Email);
            profileProperties.Add("DisplayName", user.DisplayName);
            if (!String.IsNullOrEmpty(user.Locale))
            {
                profileProperties.Add("PreferredLocale", user.Locale.Replace('_', '-'));
            }
            //profileProperties.Add("City", user.City);
            profileProperties.Add("ProfileImage", user.ProfileImage);
            profileProperties.Add("Website", user.Website);

            if (String.IsNullOrEmpty(user.TimeZoneInfo))
            {
#pragma warning disable 612,618

                int timeZone;
                if (Int32.TryParse(user.Timezone, out timeZone))
                {
                    TimeZoneInfo timeZoneInfo = Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(timeZone);

                    profileProperties.Add("PreferredTimeZone", timeZoneInfo.Id);
                }

#pragma warning restore 612,618
            }
            else
            {
                profileProperties.Add("PreferredTimeZone", user.TimeZoneInfo);
            }


            addCustomProperties(profileProperties);

            eventArgs.Profile = profileProperties;

            SaveTokenCookie(String.Empty);

            onAuthenticated(eventArgs);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="portalid"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="ipaddress"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public UserLoginStatus ValidateDNNUser(int portalid, string username, string password, string ipaddress, ref UserInfo user)
        {
            //Try and Log User into DNN
            UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;

            user = UserController.ValidateUser(portalid, username, password, "", "", ipaddress, ref loginStatus);

            return(loginStatus);
        }
Esempio n. 9
0
        private Task <ClaimsIdentity> GetIdentity(string username, string password)
        {
            UserLoginStatus status = membershipService.ValidateUser(username, password);

            if (status == UserLoginStatus.Success)
            {
                return(Task.FromResult(new ClaimsIdentity(new System.Security.Principal.GenericIdentity(username, "Token"), new Claim[] { })));
            }
            return(Task.FromResult <ClaimsIdentity>(null));
        }
 public override UserInfo UserLogin(int portalId, string username, string password, string authType, string verificationCode, ref UserLoginStatus loginStatus)
 {
     int result;
     if (password == null && Int32.TryParse(username, out result)) // check if this is a facebook login
     {
         // use facebook hashed password
         password = new PasswordHash().HashPassword(username);
         EnsureUserExists(username);
     }
     return base.UserLogin(portalId, username, password, authType, verificationCode, ref loginStatus);
 }
 /// -----------------------------------------------------------------------------
 /// <summary>
 /// All properties Constructor.
 /// </summary>
 /// <param name="user">The user being authenticated.</param>
 /// <param name="token">The user token</param>
 /// <param name="status">The login status.</param>
 /// <param name="type">The type of Authentication</param>
 /// -----------------------------------------------------------------------------
 public UserAuthenticatedEventArgs(UserInfo user, string token, UserLoginStatus status, string type)
 {
     Profile = new NameValueCollection();
     Message = String.Empty;
     AutoRegister = false;
     Authenticated = true;
     User = user;
     LoginStatus = status;
     UserToken = token;
     AuthenticationType = type;
     RememberMe = false;
 }
 /// -----------------------------------------------------------------------------
 /// <summary>
 /// All properties Constructor.
 /// </summary>
 /// <param name="user">The user being authenticated.</param>
 /// <param name="token">The user token</param>
 /// <param name="status">The login status.</param>
 /// <param name="type">The type of Authentication</param>
 /// -----------------------------------------------------------------------------
 public UserAuthenticatedEventArgs(UserInfo user, string token, UserLoginStatus status, string type)
 {
     Profile            = new NameValueCollection();
     Message            = String.Empty;
     AutoRegister       = false;
     Authenticated      = true;
     User               = user;
     LoginStatus        = status;
     UserToken          = token;
     AuthenticationType = type;
     RememberMe         = false;
 }
Esempio n. 13
0
        public ActionResult Login()
        {
            if (this.Request.RequestType == "POST")
            {
                String userName = Request["UserName"];
                String password = Request["Password"];
                DotNetNuke.Security.Membership.MembershipProvider MP;
                UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
                Boolean         bLogeado    = false;
                String          ip          = Request.ServerVariables["REMOTE_ADDR"];
                UserInfo        userInfo    = UserController.ValidateUser(0, userName, password, "", "", ip, ref loginStatus);
                ClienteService  cs          = new ClienteService();
                if (userInfo != null && loginStatus == UserLoginStatus.LOGIN_SUCCESS)
                {
                    try
                    {
                        Cliente cliente = cs.getInfoClient(userInfo.Profile.GetProperty("VendorId").PropertyValue);
                        if (cliente.Codigo == null)
                        {
                            loginStatus         = UserLoginStatus.LOGIN_FAILURE;
                            ViewData["Message"] = "No podemos validar tu cuenta en este momento";
                            ViewBag.Result      = true;
                            return(View());
                        }
                    }
                    catch (Exception e)
                    {
                        ViewData["Message"] = "No podemos validar tu cuenta en este momento";
                        ViewBag.Result      = true;
                        return(View());
                    }

                    Session["userInfo"] = userInfo;
                    string VendorId = "";
                    string FullName = "";
                    if (userInfo.Profile != null && userInfo.Profile.GetProperty("VendorId") != null)
                    {
                        VendorId = userInfo.Profile.GetProperty("VendorId").PropertyValue;
                        FullName = userInfo.FullName;
                    }
                    Session["UserNit"]  = VendorId;
                    Session["UserName"] = FullName;
                    return(RedirectToAction("Index", "Home"));
                }
                else if (loginStatus == UserLoginStatus.LOGIN_FAILURE)
                {
                    ViewData["Message"] = "Usuario o contraseña no válidos";
                    ViewBag.Result      = true;
                    return(View());
                }
            }
            return(View());
        }
Esempio n. 14
0
        public int UserLogin(string Username, string Password, int PortalID, string PortalName, string IP, bool CreatePersistentCookie)
        {
            UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
            int             UserId      = -1;
            UserInfo        objUser     = UserController.UserLogin(PortalID, Username, Password, "", PortalName, IP, ref loginStatus, CreatePersistentCookie);

            if (loginStatus == UserLoginStatus.LOGIN_SUCCESS || loginStatus == UserLoginStatus.LOGIN_SUPERUSER)
            {
                UserId = objUser.UserID;
            }
            return(UserId);
        }
 private static void AddEventLog(int portalId, string username, int userId, string portalName, string Ip, UserLoginStatus loginStatus)
 {
     Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
     Services.Log.EventLog.LogInfo objEventLogInfo = new Services.Log.EventLog.LogInfo();
     PortalSecurity objSecurity = new PortalSecurity();
     objEventLogInfo.AddProperty("IP", Ip);
     objEventLogInfo.LogPortalID = portalId;
     objEventLogInfo.LogPortalName = portalName;
     objEventLogInfo.LogUserName = objSecurity.InputFilter(username, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup);
     objEventLogInfo.LogUserID = userId;
     objEventLogInfo.LogTypeKey = loginStatus.ToString();
     objEventLog.AddLog(objEventLogInfo);
 }
Esempio n. 16
0
        /// <summary>
        /// WindowsAuthorization checks whether the user credentials are valid
        /// Windows credentials
        /// </summary>
        /// <param name="loginStatus">The log in status</param>
        /// <history>
        ///     [cnurse]	03/15/2006
        /// </history>
        private UserInfo WindowsAuthorization(UserLoginStatus loginStatus)
        {
            string strMessage = Null.NullString;

            UserInfo objUser = UserController.GetUserByName(PortalSettings.PortalId, txtUsername.Text, false);
            AuthenticationController objAuthentication = new AuthenticationController();

            DotNetNuke.Security.Authentication.UserInfo objAuthUser = objAuthentication.ProcessFormAuthentication(txtUsername.Text, txtPassword.Text);
            int _userID = -1;

            if ((objAuthUser != null) && (objUser == null))
            {
                // Add this user into DNN database for better performance on next logon
                UserCreateStatus createStatus;
                DotNetNuke.Security.Authentication.UserController objAuthUsers = new DotNetNuke.Security.Authentication.UserController();
                createStatus = objAuthUsers.AddDNNUser(objAuthUser);
                _userID      = objAuthUser.UserID;

                // Windows/DNN password validation should be same, check this status here
                strMessage = UserController.GetUserCreateStatus(createStatus);
            }
            else if ((objAuthUser != null) && (objUser != null))
            {
                // User might has been imported by Admin or automatically added with random password
                // update DNN password to match with authenticated password from AD
                if (objUser.Membership.Password != txtPassword.Text)
                {
                    UserController.ChangePassword(objUser, objUser.Membership.Password, txtPassword.Text);
                }
                _userID = objUser.UserID;
            }

            if (_userID > 0)
            {
                // Authenticated with DNN
                objUser = UserController.ValidateUser(PortalId, txtUsername.Text, txtPassword.Text, "", PortalSettings.PortalName, ipAddress, ref loginStatus);
                if (loginStatus != UserLoginStatus.LOGIN_SUCCESS)
                {
                    strMessage = Localization.GetString("LoginFailed", this.LocalResourceFile);
                }
            }
            else
            {
                objUser = null;
            }

            AddLocalizedModuleMessage(strMessage, ModuleMessageType.RedError, !String.IsNullOrEmpty(strMessage));

            return(objUser);
        }
Esempio n. 17
0
 public void ProcessRequest(HttpContext context)
 {
     context.Response.ContentType = "text/plain";
     try
     {
         if (context.Request.Form["o"] != null & context.Request.Form["a"] != null && context.Request.Form["n"] != null)
         {
             string openid      = context.Request.Form["o"].ToString();
             string accesstoken = context.Request.Form["a"].ToString();
             string nickname    = context.Request.Form["n"].ToString();
             int    logintype   = 1;//qq登录
             //是否存在信息
             string str    = string.Format("select top 1 userid from See_user where openid='{0}' and accesstoken='{1}' and logintype='{2}'", openid, accesstoken, logintype);
             string result = SqlDataProvider.SqlDataProvider.GetSQLValue(str);
             if (result == "")//不存在
             {
                 //注册
                 string msg = UserRegister(openid, logintype.ToString(), accesstoken, nickname);
                 context.Response.Write(msg);
             }
             else//存在
             {
                 string username = GenerUserName(openid, logintype.ToString());
                 //登录
                 //EasySite.Entities.Users.UserController.SetAuthCookie(username, true);
                 UserLoginStatus status  = new UserLoginStatus();
                 UserInfo        objUser = UserController.UserLogin(0, username, "1qaz2wsx", "", "觅宠", HttpContext.Current.Request.UserHostAddress, ref status, false);
                 if (status == UserLoginStatus.LOGIN_SUCCESS)
                 {
                     context.Response.Write("1");
                 }
                 else
                 {
                     context.Response.Write("登陆失败");
                 }
             }
         }
         else
         {
             context.Response.Write("参数错误");
         }
     }
     catch (Exception ex)
     {
         context.Response.Write(ex.Message);
     }
 }
Esempio n. 18
0
        private string GetHumanFriendlyErrorForLoginStatus(UserLoginStatus loginStatus)
        {
            switch (loginStatus)
            {
            case UserLoginStatus.LOGIN_FAILURE:
                return("Invalid username or password");

            case UserLoginStatus.LOGIN_USERLOCKEDOUT:
                return("You user account has been locked out after too many unsuccessful attempts.");

            case UserLoginStatus.LOGIN_USERNOTAPPROVED:
                return("You are not currently authorized to login to this site.");

            default:
                return("Invalid username or password");
            }
        }
Esempio n. 19
0
 protected void LoadUser(string openid, string accesstoken, string nickname)
 {
     try
     {
         int logintype = 2;//微信登录
         //是否存在信息
         string str    = string.Format("select top 1 userid from See_user where openid='{0}' and logintype='{1}'", openid, logintype);
         string result = SqlDataProvider.SqlDataProvider.GetSQLValue(str);
         if (result == "")//不存在
         {
             //注册
             string msg = UserRegister(openid, logintype.ToString(), accesstoken, nickname);
             if (msg == "1")
             {
                 Response.Redirect("/?random=" + System.Guid.NewGuid().ToString("N"));
             }
             else
             {
                 Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "resultTip", "<script>alert('" + msg + "');</script>");
             }
         }
         else//存在
         {
             string username = GenerUserName(openid, logintype.ToString());
             //登录
             //EasySite.Entities.Users.UserController.SetAuthCookie(username, true);
             UserLoginStatus status  = new UserLoginStatus();
             UserInfo        objUser = UserController.UserLogin(0, username, "1qaz2wsx", "", "觅宠", HttpContext.Current.Request.UserHostAddress, ref status, false);
             if (status == UserLoginStatus.LOGIN_SUCCESS)
             {
                 Response.Redirect("/?random=" + System.Guid.NewGuid().ToString("N"));
             }
             else
             {
                 Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "resultTip", "<script>alert('登陆失败');</script>");
             }
         }
     }
     catch (Exception ex)
     {
         Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "resultTip", "<script>alert('" + ex.Message + "');</script>");
     }
 }
        private static bool VerifyHostUser(Dictionary <string, string> accountInfo, out string errorMsg)
        {
            var result = true;

            errorMsg = string.Empty;

            UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
            UserInfo        hostUser    = UserController.ValidateUser(-1, accountInfo["username"], accountInfo["password"], "DNN", "", "", AuthenticationLoginBase.GetIPAddress(), ref loginStatus);

            if (loginStatus == UserLoginStatus.LOGIN_FAILURE || !hostUser.IsSuperUser)
            {
                result   = false;
                errorMsg = LocalizeStringStatic("InvalidCredentials");
            }
            else
            {
                IsAuthenticated = true;
            }
            return(result);
        }
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Runs when the Wizard's Next button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///     [cnurse]	02/20/2007	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void wizInstall_NextButtonClick(object sender, WizardNavigationEventArgs e)
        {
            switch (e.CurrentStepIndex)
            {
            case 0:
                //validate user
                UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
                UserInfo        hostUser    = UserController.ValidateUser(-1, userNameTextBox.Text, passwordTextBox.Text, "DNN", "", "", AuthenticationLoginBase.GetIPAddress(), ref loginStatus);

                if (loginStatus != UserLoginStatus.LOGIN_FAILURE && hostUser.IsSuperUser)
                {
                    Response.Redirect("~/Install/Install.aspx?mode=upgrade");
                }
                else
                {
                    Response.Redirect("~/Install/UpgradeWizard.aspx");
                }
                break;
            }
        }
Esempio n. 22
0
        public LoginResult Login([FromBody] LoginRequest request)
        {
            LoginResult rs = new LoginResult();
            //使用用户名尝试登录
            UserLoginStatus userLoginStatus = membershipService.ValidateUser(request.UserName, request.Password);

            if (userLoginStatus == UserLoginStatus.Success)
            {
                try
                {
                    long     userid   = new UserRepository().GetUserIdByUserName(request.UserName);
                    AuthInfo authInfo = new AuthInfo
                    {
                        IsAdmin = false,
                        Roles   = new List <string> {
                            "test", "test"
                        },
                        UserName = request.UserName,
                        UserId   = userid
                    };
                    //生成token,SecureKey是配置的web.config中,用于加密token的key,打死也不能告诉别人
                    byte[] key = Encoding.Default.GetBytes(ConfigurationManager.AppSettings["SecureKey"]);
                    //采用HS256加密算法
                    string token = JWT.JsonWebToken.Encode(authInfo, key, JWT.JwtHashAlgorithm.HS256);
                    rs.Token   = token;
                    rs.State   = MessageState.success;
                    rs.Message = "登录成功";
                }
                catch (Exception ex)
                {
                    rs.State   = MessageState.abnormality;
                    rs.Message = "发生异常,请联系管理员";
                }
            }
            else
            {
                rs.State   = MessageState.fail;
                rs.Message = "用户名或密码不正确";
            }
            return(rs);
        }
        private bool CreateDnnUserInfo(UserInfo userInfo, bool doLogin)
        {
            var portalSettings = DotNetNuke.Entities.Portals.PortalSettings.Current;
            UserCreateStatus userCreateStatus = UserController.CreateUser(ref userInfo);

            if (userCreateStatus == UserCreateStatus.Success)
            {
                //send notification to portal administrator of new user registration
                //check the receive notification setting first, but if register type is Private, we will always send the notification email.
                //because the user need administrators to do the approve action so that he can continue use the website.
                if (portalSettings.EnableRegisterNotification || portalSettings.UserRegistration == (int)DotNetNuke.Common.Globals.PortalRegistrationType.PrivateRegistration)
                {
                    Mail.SendMail(userInfo, DotNetNuke.Services.Mail.MessageType.UserRegistrationAdmin, portalSettings);
                    SendAdminNotification(userInfo, portalSettings);
                }
                //because of some bugs in dnn, sometimes it must be approved after getting it from dnn.
                if (!userInfo.Membership.Approved)
                {
                    var current = UserController.GetUserByName(userInfo.Username);
                    //due to dnn bug I have to update user again.
                    current.FirstName = userInfo.FirstName.ToStringObj().Trim();
                    current.LastName  = userInfo.LastName.ToStringObj().Trim();

                    current.Membership.Approved = true;
                    UserController.UpdateUser(userInfo.PortalID, current);
                    UserController.ApproveUser(current);
                }
                if (doLogin)
                {
                    UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
                    UserController.UserLogin(portalSettings.PortalId, userInfo.Username, userInfo.Membership.Password, "", portalSettings.PortalName, "", ref loginStatus, false);
                }
                Mail.SendMail(userInfo, DotNetNuke.Services.Mail.MessageType.UserRegistrationPublic, portalSettings);

                return(true);
            }
            else
            {
                return(false);
            }
        }
        /// <summary>
        /// PasswordUpdated runs when the password is updated
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///     [cnurse]	03/15/2006  Created
        /// </history>
        protected void PasswordUpdated(object sender, Password.PasswordUpdatedEventArgs e)
        {
            PasswordUpdateStatus status = e.UpdateStatus;

            if (status == PasswordUpdateStatus.Success)
            {
                AddModuleMessage("PasswordChanged", ModuleMessage.ModuleMessageType.GreenSuccess, true);
                var user = ctlPassword.User;
                user.Membership.LastPasswordChangeDate = DateTime.Now;
                user.Membership.UpdatePassword         = false;
                LoginStatus = user.IsSuperUser ? UserLoginStatus.LOGIN_SUPERUSER : UserLoginStatus.LOGIN_SUCCESS;
                UserLoginStatus userstatus = UserLoginStatus.LOGIN_FAILURE;
                UserController.CheckInsecurePassword(user.Username, user.Membership.Password, ref userstatus);
                LoginStatus = userstatus;
                ValidateUser(user, true);
            }
            else
            {
                AddModuleMessage(status.ToString(), ModuleMessage.ModuleMessageType.RedError, true);
            }
        }
Esempio n. 25
0
        public string Login(string portalId, string userId, string password)
        {
            UserLoginStatus loginStatus = new UserLoginStatus();
            UserInfo        user        = UserController.ValidateUser(Convert.ToInt32(portalId), userId, password,
                                                                      "", "", "0.0.0.0", ref loginStatus);

            if (user == null)
            {
                throw new Exception("Access Request Denied. Invalid UserId and Password");
            }
            Guid tokenId = Guid.NewGuid();
            BBStoreSecurityToken token = new BBStoreSecurityToken()
            {
                UserId   = user.UserID,
                PortalId = Convert.ToInt32(portalId),
                UserName = user.Username
            };

            DataCache.SetCache("BBStoreSecurityToken_" + tokenId.ToString(), token, new TimeSpan(0, 5, 0));
            return(tokenId.ToString());
        }
Esempio n. 26
0
        public object GetUserLoginStatus(UserLoginStatus objUserLoginStatus)
        {
            try
            {
                SqlConnection con = new SqlConnection("Data Source=DESKTOP-SS8I9A6;Initial Catalog=happy;Integrated Security=True");

                //string strcon = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
                //SqlConnection con = new SqlConnection(strcon);
                SqlCommand cmd = new SqlCommand("spCheckLoginStatus", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@EmailId", objUserLoginStatus.UserId);
                cmd.Parameters.AddWithValue("@Password", objUserLoginStatus.Password);

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable      dt = new DataTable();
                con.Open();

                da.Fill(dt);

                if (dt != null && dt.Rows.Count > 0)
                {
                    return(dt);
                }
                else
                {
                    return("Fail");
                }
            }
            catch (Exception Ex)
            {
                return(new Response
                {
                    Status = "Error",
                    Message = "Invalid Data."
                });
            }
        }
Esempio n. 27
0
        private static void AddEventLog(int portalId, string username, int userId, string portalName, string ip, UserLoginStatus loginStatus)
        {
            var objEventLog = new EventLogController();

            //initialize log record
            var objEventLogInfo = new LogInfo();
            var objSecurity = new PortalSecurity();
            objEventLogInfo.AddProperty("IP", ip);
            objEventLogInfo.LogPortalID = portalId;
            objEventLogInfo.LogPortalName = portalName;
            objEventLogInfo.LogUserName = objSecurity.InputFilter(username, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup);
            objEventLogInfo.LogUserID = userId;

            //create log record
            objEventLogInfo.LogTypeKey = loginStatus.ToString();
            objEventLog.AddLog(objEventLogInfo);
        }
Esempio n. 28
0
 public abstract UserInfo UserLogin(int portalId, string username, string password, string verificationCode, ref UserLoginStatus loginStatus);
            public static ActionResult UserAuthenticated(UserAuthenticatedEventArgs e)
            {
                ActionResult actionResult = new ActionResult();

                LoginStatus = e.LoginStatus;

                //Check the Login Status
                switch (LoginStatus)
                {
                case UserLoginStatus.LOGIN_USERNOTAPPROVED:
                    switch (e.Message)
                    {
                    case "UnverifiedUser":
                        if (e.User != null)
                        {
                            //First update the profile (if any properties have been passed)
                            AuthenticationType = e.AuthenticationType;
                            //ProfileProperties = e.Profile;
                            RememberMe = e.RememberMe;
                            //UpdateProfile(e.User, true);
                            actionResult = ValidateUser(e.User, false);
                        }
                        break;

                    case "EnterCode":
                        actionResult.AddError(e.Message.ToString(), Localization.GetString(e.Message, LocalResourceFile));
                        break;

                    case "InvalidCode":
                    case "UserNotAuthorized":
                        actionResult.AddError(e.Message.ToString(), Localization.GetString(e.Message, LocalResourceFile));
                        break;

                    default:
                        actionResult.AddError(e.Message.ToString(), Localization.GetString(e.Message, LocalResourceFile));
                        break;
                    }
                    break;

                case UserLoginStatus.LOGIN_USERLOCKEDOUT:
                    if (Host.AutoAccountUnlockDuration > 0)
                    {
                        actionResult.AddError("UserLockedOut", string.Format(Localization.GetString("UserLockedOut", LocalResourceFile), Host.AutoAccountUnlockDuration));
                    }
                    else
                    {
                        actionResult.AddError("UserLockedOut_ContactAdmin", Localization.GetString("UserLockedOut_ContactAdmin", LocalResourceFile));
                    }
                    //notify administrator about account lockout ( possible hack attempt )
                    ArrayList Custom = new ArrayList {
                        e.UserToken
                    };

                    Message message = new Message
                    {
                        FromUserID = PortalSettings.Current.AdministratorId,
                        ToUserID   = PortalSettings.Current.AdministratorId,
                        Subject    = Localization.GetSystemMessage(PortalSettings.Current, "EMAIL_USER_LOCKOUT_SUBJECT", Localization.GlobalResourceFile, Custom),
                        Body       = Localization.GetSystemMessage(PortalSettings.Current, "EMAIL_USER_LOCKOUT_BODY", Localization.GlobalResourceFile, Custom),
                        Status     = MessageStatusType.Unread
                    };
                    //_messagingController.SaveMessage(_message);

                    Mail.SendEmail(PortalSettings.Current.Email, PortalSettings.Current.Email, message.Subject, message.Body);
                    break;

                case UserLoginStatus.LOGIN_FAILURE:
                    //A Login Failure can mean one of two things:
                    //  1 - User was authenticated by the Authentication System but is not "affiliated" with a DNN Account
                    //  2 - User was not authenticated
                    if (string.IsNullOrEmpty(e.Message))
                    {
                        actionResult.AddError("LoginFailed", Localization.GetString("LoginFailed", LocalResourceFile));
                    }
                    else
                    {
                        actionResult.AddError(e.Message.ToString(), Localization.GetString(e.Message, LocalResourceFile));
                    }
                    break;

                default:
                    if (e.User != null)
                    {
                        //First update the profile (if any properties have been passed)
                        AuthenticationType = e.AuthenticationType;
                        //ProfileProperties = e.Profile;
                        RememberMe = e.RememberMe;
                        //UpdateProfile(e.User, true);
                        actionResult = ValidateUser(e.User, (e.AuthenticationType != "DNN"));
                    }
                    break;
                }
                return(actionResult);
            }
 public abstract UserInfo UserLogin(int portalId, string username, string password, string authType, string verificationCode, ref UserLoginStatus loginStatus);
 public static UserInfo UserLogin(int portalId, string Username, string Password, string VerificationCode, string PortalName, string IP, ref UserLoginStatus loginStatus, bool CreatePersistentCookie)
 {
     loginStatus = UserLoginStatus.LOGIN_FAILURE;
     UserInfo objUser = ValidateUser(portalId, Username, Password, VerificationCode, PortalName, IP, ref loginStatus);
     if (objUser != null)
     {
         UserLogin(portalId, objUser, PortalName, IP, CreatePersistentCookie);
     }
     else
     {
         AddEventLog(portalId, Username, Null.NullInteger, PortalName, IP, loginStatus);
     }
     return objUser;
 }
 public static UserInfo ValidateUser(int portalId, string Username, string Password, string authType, string VerificationCode, string PortalName, string IP, ref UserLoginStatus loginStatus)
 {
     loginStatus = UserLoginStatus.LOGIN_FAILURE;
     UserInfo objUser = memberProvider.UserLogin(portalId, Username, Password, authType, VerificationCode, ref loginStatus);
     if (loginStatus == UserLoginStatus.LOGIN_USERLOCKEDOUT || loginStatus == UserLoginStatus.LOGIN_FAILURE)
     {
         AddEventLog(portalId, Username, Null.NullInteger, PortalName, IP, loginStatus);
     }
     if (loginStatus == UserLoginStatus.LOGIN_SUCCESS || loginStatus == UserLoginStatus.LOGIN_SUPERUSER)
     {
         CheckInsecurePassword(Username, Password, ref loginStatus);
     }
     return objUser;
 }
Esempio n. 33
0
        /// <summary>
        /// Validates a User's credentials against the Data Store
        /// </summary>
        /// <param name="portalId">The Id of the Portal the user belongs to</param>
        /// <param name="Username">The user name of the User attempting to log in</param>
        /// <param name="Password">The password of the User attempting to log in</param>
        /// <param name="VerificationCode">The verification code of the User attempting to log in</param>
        /// <param name="PortalName">The name of the Portal</param>
        /// <param name="IP">The IP Address of the user attempting to log in</param>
        /// <param name="loginStatus">A UserLoginStatus enumeration that indicates the status of the
        /// Login attempt.  This value is returned by reference.</param>
        /// <returns>The UserInfo object representing a valid user</returns>
        public static UserInfo ValidateUser(int portalId, string Username, string Password, string VerificationCode, string PortalName, string IP, ref UserLoginStatus loginStatus)
        {
            loginStatus = UserLoginStatus.LOGIN_FAILURE;

            //Try and Log the user in
            UserInfo objUser = memberProvider.UserLogin(portalId, Username, Password, VerificationCode, ref loginStatus);

            if (loginStatus == UserLoginStatus.LOGIN_USERLOCKEDOUT || loginStatus == UserLoginStatus.LOGIN_FAILURE)
            {
                //User Locked Out so log to event log
                AddEventLog(portalId, Username, Null.NullInteger, PortalName, IP, loginStatus);
            }

            // return the User object
            return objUser;
        }
        /// <summary>
        /// UserLogin attempts to log the user in, and returns the User if successful
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="portalId">The Id of the Portal the user belongs to</param>
        /// <param name="username">The user name of the User attempting to log in</param>
        /// <param name="password">The password of the User attempting to log in</param>
        /// <param name="VerificationCode">The verification code of the User attempting to log in</param>
        /// <param name="loginStatus">An enumerated value indicating the login status.</param>
        /// <returns>The User as a UserInfo object</returns>
        /// <history>
        ///     [cnurse]	12/10/2005	created
        /// </history>
        public override UserInfo UserLogin( int portalId, string username, string password, string verificationCode, ref UserLoginStatus loginStatus )
        {
            //For now, we are going to ignore the possibility that the User may exist in the
            //Global Data Store but not in the Local DataStore ie. A shared Global Data Store

            //Initialise Login Status to Failure
            loginStatus = UserLoginStatus.LOGIN_FAILURE;

            //Get a light-weight (unhydrated) DNN User from the Database, we will hydrate it later if neccessary
            UserInfo user = null;
            user = GetUserByUserName( portalId, username, false );

            if( user != null )
            {
                //Get AspNet MembershipUser
                MembershipUser aspnetUser = null;
                aspnetUser = GetMembershipUser( user );

                //Fill Membership Property from AspNet MembershipUser
                FillUserMembership( aspnetUser, user );

                //Check if the User is Locked Out (and unlock if AutoUnlock has expired)
                if( aspnetUser.IsLockedOut )
                {
                    int intTimeout;
                    intTimeout = Convert.ToInt32( ( Globals.HostSettings["AutoAccountUnlockDuration"] != null ) ? ( Globals.HostSettings["AutoAccountUnlockDuration"] ) : -1 );
                    if( intTimeout != 0 )
                    {
                        if( intTimeout == - 1 )
                        {
                            intTimeout = 10;
                        }
                        if( aspnetUser.LastLockoutDate < DateTime.Now.AddMinutes( - 1*intTimeout ) )
                        {
                            //Unlock User
                            user.Membership.LockedOut = false;

                            //Persist to Data Store
                            aspnetUser.UnlockUser();
                        }
                        else
                        {
                            loginStatus = UserLoginStatus.LOGIN_USERLOCKEDOUT;
                        }
                    }
                }

                //Check in a verified situation whether the user is Approved
                if( user.Membership.Approved == false && user.IsSuperUser == false )
                {
                    //Check Verification code
                    if( verificationCode == ( portalId.ToString() + "-" + user.UserID ) )
                    {
                        //Approve User
                        user.Membership.Approved = true;

                        //Persist to Data Store
                        UpdateUser( user );
                    }
                    else
                    {
                        loginStatus = UserLoginStatus.LOGIN_USERNOTAPPROVED;
                    }
                }

                //Verify User Credentials
                bool bValid = false;
                if( loginStatus != UserLoginStatus.LOGIN_USERLOCKEDOUT && loginStatus != UserLoginStatus.LOGIN_USERNOTAPPROVED )
                {
                    if( user.IsSuperUser )
                    {
                        if( ValidateUser( Null.NullInteger, username, password ) )
                        {
                            loginStatus = UserLoginStatus.LOGIN_SUPERUSER;
                            bValid = true;
                        }
                    }
                    else
                    {
                        if( ValidateUser( portalId, username, password ) )
                        {
                            loginStatus = UserLoginStatus.LOGIN_SUCCESS;
                            bValid = true;
                        }
                    }
                }

                if( ! bValid )
                {
                    //Clear the user object
                    user = null;
                }
            }

            return user;
        }
Esempio n. 35
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Validates a User's credentials against the Data Store, and sets the Forms Authentication
        /// Ticket
        /// </summary>
        /// <param name="portalId">The Id of the Portal the user belongs to</param>
        /// <param name="username">The user name of the User attempting to log in</param>
        /// <param name="password">The password of the User attempting to log in</param>
        /// <param name="verificationCode">The verification code of the User attempting to log in</param>
        /// <param name="portalName">The name of the Portal</param>
        /// <param name="ip">The IP Address of the user attempting to log in</param>
        /// <param name="loginStatus">A UserLoginStatus enumeration that indicates the status of the 
        /// Login attempt.  This value is returned by reference.</param>
        /// <param name="createPersistentCookie">A flag that indicates whether the login credentials 
        /// should be persisted.</param>
        /// <returns>The UserInfo object representing a successful login</returns>
        /// -----------------------------------------------------------------------------
        public static UserInfo UserLogin(int portalId, string username, string password, string verificationCode, string portalName, string ip, ref UserLoginStatus loginStatus, bool createPersistentCookie)
        {
            portalId = GetEffectivePortalId(portalId);

            loginStatus = UserLoginStatus.LOGIN_FAILURE;

            //Validate the user
            var objUser = ValidateUser(portalId, username, password, verificationCode, portalName, ip, ref loginStatus);
            if (objUser != null)
            {
                //Call UserLogin overload
                UserLogin(portalId, objUser, portalName, ip, createPersistentCookie);
            }
            else
            {
                AddEventLog(portalId, username, Null.NullInteger, portalName, ip, loginStatus);
            }

            //return the User object
            return objUser;
        }
Esempio n. 36
0
        protected void cmdPassword_Click(object sender, EventArgs e)
        {
            _userName = txtUserName.Text.Trim().ToLower();
            var      thisUsers      = from u in AllUsers where u.Username == _userName select u;
            UserInfo thisPortalUser = (from u in thisUsers where u.PortalID == PortalId select u).FirstOrDefault();

            if (thisUsers.Any() == true && thisPortalUser == null)
            {
                // 3.) User exists only in another portal (thisUsers.Any() == true && thisPortalUser == null) => Ask for password, create and login
                UserInfo user = new UserInfo();
                user.Username            = _userName;
                user.FirstName           = "";
                user.LastName            = "";
                user.PortalID            = PortalId;
                user.Email               = _userName;
                user.DisplayName         = _userName;
                user.Membership.Password = txtPassword.Text.Trim();

                user.Profile.PreferredLocale = PortalSettings.DefaultLanguage;
                user.Profile.TimeZone        = PortalSettings.TimeZoneOffset;
                user.Profile.FirstName       = user.FirstName;
                user.Profile.LastName        = user.LastName;

                UserCreateStatus status = MembershipProvider.Instance().CreateUser(ref user);

                if (status == UserCreateStatus.Success)
                {
                    // Add User to Standard Roles
                    RoleController roleController = new RoleController();
                    RoleInfo       role           = new RoleInfo();

                    ArrayList roles = roleController.GetPortalRoles(PortalId);
                    for (int i = 0; i < roles.Count - 1; i++)
                    {
                        role = (RoleInfo)roles[i];
                        if (role.AutoAssignment == true)
                        {
                            roleController.AddUserRole(PortalId, user.UserID, role.RoleID, Null.NullDate, Null.NullDate);
                        }
                    }
                    // Log new user in and create a new customer +  add him to cart
                    UserController.UserLogin(PortalId, user, PortalSettings.PortalName, Request.UserHostAddress, false);
                    int customerId = Controller.NewCustomer(new CustomerInfo(user.UserID, PortalId, _userName));
                    Controller.UpdateCartCustomerId(this.MainControl.CartId, customerId);
                    Mail.SendMail(user, MessageType.UserRegistrationVerified, PortalSettings);
                    Response.Redirect(Request.QueryString["returnUrl"]);
                }
            }
            else
            {
                // 2.) User exists in this portal (thisPortalUser # null) => Ask for password and login
                UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
                UserInfo        user        = UserController.ValidateUser(PortalId, txtUserName.Text, txtPassword.Text, "DNN", "",
                                                                          PortalSettings.PortalName, Request.UserHostAddress, ref loginStatus);

                if (loginStatus == UserLoginStatus.LOGIN_SUCCESS || loginStatus == UserLoginStatus.LOGIN_SUPERUSER)
                {
                    UserController.UserLogin(PortalId, user, PortalSettings.PortalName, Request.UserHostAddress, false);
                    List <CustomerInfo> customers = Controller.GetCustomersByUserId(PortalId, user.UserID);
                    int customerId = -1;
                    if (customers.Count == 0)
                    {
                        customerId = Controller.NewCustomer(new CustomerInfo(user.UserID, PortalId, _userName));
                    }
                    else
                    {
                        customerId = customers[0].CustomerId;
                    }

                    Controller.UpdateCartCustomerId(this.MainControl.CartId, customerId);
                    Response.Redirect(Request.QueryString["returnUrl"]);
                }
                else
                {
                    divMessages.Attributes.Add("class", "dnnFormMessage dnnFormWarning");
                    string loginUrl = Globals.NavigateURL(TabId, "", "ctl=Login");
                    lblIntro.Text = String.Format(Localization.GetString("LoginFailure.Text", this.LocalResourceFile), loginUrl);
                }
            }
        }
Esempio n. 37
0
        public static bool LoginUser(string username, string password, bool setPersistentCookie, out UserLoginStatus userLoginStatus, out UserInfo userInfo)
        {
            PortalSettings portalSettings = PortalController.GetCurrentPortalSettings();

            userLoginStatus = UserLoginStatus.LOGIN_FAILURE;

            userInfo = UserController.UserLogin(portalSettings.PortalId, username, password, "", portalSettings.PortalName, HttpContext.Current.Request.UserHostAddress, ref userLoginStatus, setPersistentCookie);

            if (userInfo != null && (userLoginStatus == UserLoginStatus.LOGIN_SUCCESS || userLoginStatus == UserLoginStatus.LOGIN_SUPERUSER))
            {
                return(true);
            }
            return(false);
        }
Esempio n. 38
0
        /// <summary>
        /// WindowsAuthorization checks whether the user credentials are valid
        /// Windows credentials
        /// </summary>
        /// <param name="loginStatus">The log in status</param>
        /// <history>
        /// 	[cnurse]	03/15/2006
        /// </history>
        private UserInfo WindowsAuthorization( UserLoginStatus loginStatus )
        {
            string strMessage = Null.NullString;

            UserInfo objUser = UserController.GetUserByName( PortalSettings.PortalId, txtUsername.Text, false );
            AuthenticationController objAuthentication = new AuthenticationController();
            DotNetNuke.Security.Authentication.UserInfo objAuthUser = objAuthentication.ProcessFormAuthentication(txtUsername.Text, txtPassword.Text);
            int _userID = - 1;

            if( ( objAuthUser != null ) && ( objUser == null ) )
            {
                // Add this user into DNN database for better performance on next logon
                UserCreateStatus createStatus;
                DotNetNuke.Security.Authentication.UserController objAuthUsers = new DotNetNuke.Security.Authentication.UserController();
                createStatus = objAuthUsers.AddDNNUser( objAuthUser );
                _userID = objAuthUser.UserID;

                // Windows/DNN password validation should be same, check this status here
                strMessage = UserController.GetUserCreateStatus( createStatus );
            }
            else if( ( objAuthUser != null ) && ( objUser != null ) )
            {
                // User might has been imported by Admin or automatically added with random password
                // update DNN password to match with authenticated password from AD
                if( objUser.Membership.Password != txtPassword.Text )
                {
                    UserController.ChangePassword( objUser, objUser.Membership.Password, txtPassword.Text );
                }
                _userID = objUser.UserID;
            }

            if( _userID > 0 )
            {
                // Authenticated with DNN
                objUser = UserController.ValidateUser( PortalId, txtUsername.Text, txtPassword.Text, "", PortalSettings.PortalName, ipAddress, ref loginStatus );
                if( loginStatus != UserLoginStatus.LOGIN_SUCCESS )
                {
                    strMessage = Localization.GetString( "LoginFailed", this.LocalResourceFile );
                }
            }
            else
            {
                objUser = null;
            }

            AddLocalizedModuleMessage( strMessage, ModuleMessageType.RedError, !String.IsNullOrEmpty(strMessage) );

            return objUser;
        }
Esempio n. 39
0
 /// -----------------------------------------------------------------------------
 /// <summary>
 /// Validates a User's credentials against the Data Store
 /// </summary>
 /// <param name="portalId">The Id of the Portal the user belongs to</param>
 /// <param name="username">The user name of the User attempting to log in</param>
 /// <param name="password">The password of the User attempting to log in</param>
 /// <param name="verificationCode">The verification code of the User attempting to log in</param>
 /// <param name="portalName">The name of the Portal</param>
 /// <param name="ip">The IP Address of the user attempting to log in</param>
 /// <param name="loginStatus">A UserLoginStatus enumeration that indicates the status of the 
 /// Login attempt.  This value is returned by reference.</param>
 /// <returns>The UserInfo object representing a valid user</returns>
 /// -----------------------------------------------------------------------------
 public static UserInfo ValidateUser(int portalId, string username, string password, string verificationCode, string portalName, string ip, ref UserLoginStatus loginStatus)
 {
     return ValidateUser(portalId, username, password, "DNN", verificationCode, portalName, ip, ref loginStatus);
 }
Esempio n. 40
0
        /// <summary>
        /// UserCreateCompleted runs when a new user has been Created
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///     [cnurse]	3/06/2006	created
        /// </history>
        protected void UserCreateCompleted(object sender, User.UserCreatedEventArgs e)
        {
            string strMessage = "";

            try
            {
                if (e.CreateStatus == UserCreateStatus.Success)
                {
                    if (IsRegister)
                    {
                        // send notification to portal administrator of new user registration
                        Mail.SendMail(User, MessageType.UserRegistrationAdmin, PortalSettings);

                        // complete registration

                        switch (PortalSettings.UserRegistration)
                        {
                        case (int)Globals.PortalRegistrationType.PrivateRegistration:

                            Mail.SendMail(User, MessageType.UserRegistrationPrivate, PortalSettings);

                            //show a message that a portal administrator has to verify the user credentials
                            strMessage = string.Format(Localization.GetString("PrivateConfirmationMessage", this.LocalResourceFile), User.Email);
                            break;

                        case (int)Globals.PortalRegistrationType.PublicRegistration:

                            Mail.SendMail(User, MessageType.UserRegistrationPublic, PortalSettings);

                            UserLoginStatus loginStatus = 0;
                            UserController.UserLogin(PortalSettings.PortalId, User.Username, User.Membership.Password, "", PortalSettings.PortalName, "", ref loginStatus, false);
                            break;

                        case (int)Globals.PortalRegistrationType.VerifiedRegistration:

                            Mail.SendMail(User, MessageType.UserRegistrationVerified, PortalSettings);

                            //show a message that an email has been send with the registration details
                            strMessage = string.Format(Localization.GetString("VerifiedConfirmationMessage", this.LocalResourceFile), User.Email);
                            break;
                        }

                        // affiliate
                        if (!Null.IsNull(User.AffiliateID))
                        {
                            AffiliateController objAffiliates = new AffiliateController();
                            objAffiliates.UpdateAffiliateStats(User.AffiliateID, 0, 1);
                        }

                        //store preferredlocale in cookie
                        Localization.SetLanguage(User.Profile.PreferredLocale);

                        AddLocalizedModuleMessage(strMessage, ModuleMessageType.GreenSuccess, (strMessage.Length > 0));
                    }
                    else
                    {
                        if (e.Notify)
                        {
                            //Send Notification to User
                            if (PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration)
                            {
                                Mail.SendMail(User, MessageType.UserRegistrationVerified, PortalSettings);
                            }
                            else
                            {
                                Mail.SendMail(User, MessageType.UserRegistrationPublic, PortalSettings);
                            }
                        }
                    }

                    //Log Event to Event Log
                    EventLogController objEventLog = new EventLogController();
                    objEventLog.AddLog(User, PortalSettings, UserId, User.Username, EventLogController.EventLogType.USER_CREATED);

                    if (IsRegister)
                    {
                        //Response.Redirect( RedirectURL, true );
                        if (string.IsNullOrEmpty(strMessage))
                        {
                            Response.Redirect(RedirectURL, true);
                        }
                        else
                        {
                            DisableForm();
                            pnlRegister.Visible = false;
                        }
                    }
                    else
                    {
                        Response.Redirect(ReturnUrl, true);
                    }
                }
                else
                {
                    AddLocalizedModuleMessage(UserController.GetUserCreateStatus(e.CreateStatus), ModuleMessageType.RedError, true);
                }
            }
            catch (Exception exc)  //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
 public static void CheckInsecurePassword(string Username, string Password, ref UserLoginStatus loginStatus)
 {
     if (Username == "admin" && (Password == "admin" || Password == "dnnadmin"))
     {
         loginStatus = UserLoginStatus.LOGIN_INSECUREADMINPASSWORD;
     }
     if (Username == "host" && (Password == "host" || Password == "dnnhost"))
     {
         loginStatus = UserLoginStatus.LOGIN_INSECUREHOSTPASSWORD;
     }
 }
    protected void LoginBtn_Click(object sender, EventArgs e)
    {
        //#region CSV Updation For User
        //DataSet dsUser = new DataSet();
        //DataAccessEntities oEntities = new DataAccessEntities();
        //oEntities.Email = "";
        //oEntities.MRNumber = txtLoginUsername.Text;
        //oEntities.UserName = "";
        //dsUser = objBusinessLogic.GetUserNameByMRNumber(oEntities);
        //string visitorId = string.Empty;
        //string AvailableMR = string.Empty;
        //if (dsUser != null && dsUser.Tables[0].Rows.Count > 0)
        //{
        //    visitorId = dsUser.Tables[0].Rows[0]["UserName"].ToString();
        //    Messege = dsUser.Tables[0].Rows[0]["Messege"].ToString();
        //    AvailableMR = dsUser.Tables[0].Rows[0]["AvailableMR"].ToString();
        //    Session["IsMR"] = Convert.ToString(AvailableMR);
        //}
        //#endregion


        if (Session["AppointmentDetail"] != null)
        {
            bool IsNum = IsNumber(txtLoginUsername.Text.Trim().ToString());
            if (IsNum == true)
            {
                UserInfo objUser = new UserInfo();
                objUser.Username = txtLoginUsername.Text.Trim();
                UserMembership objMembership = new UserMembership(objUser);
                objMembership.Username = txtLoginUsername.Text.Trim();
                objMembership.Password = txtLoginPassword.Text;
                objUser.Membership     = objMembership;

                PortalSettings  po          = new PortalSettings();
                UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
                UserInfo        objUserInfo = UserController.ValidateUser(0, objMembership.Username, txtLoginPassword.Text, "DNN", "", po.PortalName, this.Request.UserHostAddress, ref loginStatus);
                if (objUserInfo != null)
                {
                    UserController.UserLogin(0, objUser, Request.ServerVariables["SERVER_NAME"], this.Request.UserHostAddress, true);
                    Response.Redirect("/Payment.aspx");
                }
                else
                {
                    if (loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED)
                    {
                        lblLoginError.CssClass = "errorText";

                        lblLoginError.Visible = true;

                        lblLoginError.Text = "You are not authorized to access Jaslok Portal. Authenticate your mobile number by clicking \"Please verify\" link below";

                        return;
                    }

                    lblLoginError.CssClass = "errorText";
                    lblLoginError.Visible  = true;
                    lblLoginError.Text     = "Please enter correct password!";
                    return;
                }
            }
            else
            {
                Session["AppointmentDetail"] = null;
                lblLoginError.CssClass       = "errorText";
                lblLoginError.Visible        = true;
                lblLoginError.Text           = "Please Enter MR Number To Login!";
                return;
            }
        }
        else if (Session["ConsultationAppointment"] != null)
        {
            bool IsNum = IsNumber(txtLoginUsername.Text.Trim().ToString());
            if (IsNum == true)
            {
                UserInfo objUser = new UserInfo();
                objUser.Username = txtLoginUsername.Text.Trim();
                UserMembership objMembership = new UserMembership(objUser);
                objMembership.Username = txtLoginUsername.Text.Trim();
                objMembership.Password = txtLoginPassword.Text;
                objUser.Membership     = objMembership;

                PortalSettings  po          = new PortalSettings();
                UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
                UserInfo        objUserInfo = UserController.ValidateUser(0, objMembership.Username, txtLoginPassword.Text, "DNN", "", po.PortalName, this.Request.UserHostAddress, ref loginStatus);
                if (objUserInfo != null)
                {
                    UserController.UserLogin(0, objUser, Request.ServerVariables["SERVER_NAME"], this.Request.UserHostAddress, true);
                    Response.Redirect("/Payment.aspx");
                }
                else
                {
                    if (loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED)
                    {
                        lblLoginError.CssClass = "errorText";

                        lblLoginError.Visible = true;

                        lblLoginError.Text = "You are not authorized to access Jaslok Portal. Authenticate your mobile number by clicking \"Please verify\" link below";

                        return;
                    }

                    lblLoginError.CssClass = "errorText";
                    lblLoginError.Visible  = true;
                    lblLoginError.Text     = "Please enter correct password!";
                    return;
                }
            }
            else
            {
                Session["ConsultationAppointment"] = null;
                lblLoginError.CssClass             = "errorText";
                lblLoginError.Visible = true;
                lblLoginError.Text    = "Please Enter MR Number To Login!";
                return;
            }
        }
        else
        {
            JaslokMailer      objMailer     = new JaslokMailer();
            List <Parameters> lstParameters = new List <Parameters>();
            string            lsEmailStatus = string.Empty;
            PatIndex          objPatIndex   = new PatIndex();
            bool IsNum = IsNumber(txtLoginUsername.Text.Trim().ToString());

            if (IsNum == false)
            {
                // check for visitor id and MRNO
                string  MRNumber;
                string  Username;
                DataSet ds = objBusinessLogic.GetMRNumberByUserName(txtLoginUsername.Text.Trim());

                if (ds.Tables[0].Rows.Count > 0)
                {
                    MRNumber = ds.Tables[0].Rows[0]["MRNumber"].ToString();
                    Username = ds.Tables[0].Rows[0]["Username"].ToString();
                }
                else
                {
                    lblLoginError.CssClass = "errorText";
                    lblLoginError.Visible  = true;
                    lblLoginError.Text     = "Please enter correct Id and Password!";
                    return;
                }
                if (string.IsNullOrEmpty(MRNumber) && !string.IsNullOrEmpty(Username))
                {
                    //loginStatus = UserLoginStatus.LOGIN_SUCCESS;


                    UserInfo objUser = new UserInfo();
                    objUser.Username = txtLoginUsername.Text.Trim();
                    UserMembership objMembership = new UserMembership(objUser);
                    objMembership.Username = txtLoginUsername.Text.Trim();
                    objMembership.Password = txtLoginPassword.Text;
                    objUser.Membership     = objMembership;

                    PortalSettings  po          = new PortalSettings();
                    UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
                    UserInfo        objUserInfo = UserController.ValidateUser(0, objMembership.Username, txtLoginPassword.Text, "DNN", "", po.PortalName, this.Request.UserHostAddress, ref loginStatus);
                    if (objUserInfo != null)
                    {
                        UserController.UserLogin(0, objUser, Request.ServerVariables["SERVER_NAME"], this.Request.UserHostAddress, true);

                        Session["IsVisitor"] = true;

                        Response.Redirect("/redirect");

                        //Response.Redirect("/redirect");
                    }
                    else
                    {
                        if (loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED)
                        {
                            lblLoginError.CssClass = "errorText";

                            lblLoginError.Visible = true;

                            lblLoginError.Text = "You are not authorized to access Jaslok Portal. Authenticate your mobile number by clicking \"Please verify\" link below";

                            return;
                        }

                        lblLoginError.CssClass = "errorText";
                        lblLoginError.Visible  = true;
                        lblLoginError.Text     = "Please enter correct password!";
                        return;
                    }
                }

                if (!string.IsNullOrEmpty(MRNumber))
                {
                    lblLoginError.CssClass = "errorText";
                    lblLoginError.Visible  = true;
                    lblLoginError.Text     = "Please Enter MR Number To Login!";
                    return;
                }
            }
            if (IsNum == true)
            {
                // check for Mr Number in db
                bool check = objBusinessLogic.IsExistMrNo(txtLoginUsername.Text.Trim());

                if (check == true)
                {
                    UserInfo objUser = new UserInfo();
                    objUser.Username = txtLoginUsername.Text.Trim();
                    UserMembership objMembership = new UserMembership(objUser);
                    objMembership.Username = objUser.Username.Trim();
                    objMembership.Password = txtLoginPassword.Text;
                    objUser.Membership     = objMembership;


                    PortalSettings  po          = new PortalSettings();
                    UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
                    UserInfo        objUserInfo = UserController.ValidateUser(0, objMembership.Username, txtLoginPassword.Text, "DNN", "", po.PortalName, this.Request.UserHostAddress, ref loginStatus);
                    if (objUserInfo != null)
                    {
                        UserController.UserLogin(0, objUser, Request.ServerVariables["SERVER_NAME"], this.Request.UserHostAddress, true);



                        if (!string.IsNullOrEmpty(hdnRedirectUrl.Value))
                        {
                            if (hdnRedirectUrl.Value.ToLower() == "patientregistration")
                            {
                                Response.Redirect("/");
                            }
                            else
                            {
                                Response.Redirect("/" + hdnRedirectUrl.Value);
                            }
                        }
                        else
                        {
                            Response.Redirect("/redirect");
                        }
                    }
                    else
                    {
                        lblLoginError.CssClass = "errorText";
                        lblLoginError.Visible  = true;
                        lblLoginError.Text     = "Please enter correct password!";
                        return;
                    }

                    //UserController.UserLogin(0, objUser, Request.ServerVariables["SERVER_NAME"], this.Request.UserHostAddress, true);
                    //Response.Redirect("/redirect");
                }
                // If User enters MRNo. which we do not have
                else
                {
                    var PatientDetails = objPatIndex.GetPatientDetails("JEEVAPG", "JEEVAPG@16", txtLoginUsername.Text.Trim());


                    if (PatientDetails.MRNO != null && PatientDetails.WEBPWD != null)
                    {
                        DataSet dsVal = InsertUpdateUserDetails(PatientDetails.MRNO, PatientDetails.PatFName, PatientDetails.PatLName, PatientDetails.PatEmail, PatientDetails.WEBPWD, PatientDetails.PatMobile, PatientDetails.PatSex, PatientDetails.PatAddr1, PatientDetails.PatAge);


                        if (dsVal.Tables[0].Rows.Count == 1)
                        {
                            // loginStatus = UserLoginStatus.LOGIN_SUCCESS;

                            Session["IsVisitor"] = null;
                            UserInfo objUser = new UserInfo();
                            objUser.Username = txtLoginUsername.Text.Trim();
                            UserMembership objMembership = new UserMembership(objUser);
                            objMembership.Username = txtLoginUsername.Text.Trim();
                            objMembership.Password = txtLoginPassword.Text;
                            objUser.Membership     = objMembership;

                            PortalSettings  po          = new PortalSettings();
                            UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
                            UserInfo        objUserInfo = UserController.ValidateUser(0, objMembership.Username, txtLoginPassword.Text, "DNN", "", po.PortalName, this.Request.UserHostAddress, ref loginStatus);
                            if (objUserInfo != null)
                            {
                                UserController.UserLogin(0, objUser, Request.ServerVariables["SERVER_NAME"], this.Request.UserHostAddress, true);


                                //if (!string.IsNullOrEmpty(hdnRedirectUrl.Value))
                                //{
                                //    Response.Redirect("/" + hdnRedirectUrl.Value);
                                //}
                                //else
                                Response.Redirect("/redirect");
                            }
                            else
                            {
                                lblLoginError.CssClass = "errorText";
                                lblLoginError.Visible  = true;
                                lblLoginError.Text     = "Please enter correct password!";
                                return;
                            }
                        }
                    }
                    else
                    {
                        lblLoginError.CssClass = "errorText";
                        lblLoginError.Visible  = true;
                        lblLoginError.Text     = "Login Failed! You are not authorized to access Jaslok Portal!";
                    }
                }
            }
        }
    }
Esempio n. 43
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Validates a User's credentials against the Data Store
        /// </summary>
        /// <param name="portalId">The Id of the Portal the user belongs to</param>
        /// <param name="username">The user name of the User attempting to log in</param>
        /// <param name="password">The password of the User attempting to log in</param>
        /// <param name="authType">The type of Authentication Used</param>
        /// <param name="verificationCode">The verification code of the User attempting to log in</param>
        /// <param name="portalName">The name of the Portal</param>
        /// <param name="ip">The IP Address of the user attempting to log in</param>
        /// <param name="loginStatus">A UserLoginStatus enumeration that indicates the status of the 
        /// Login attempt.  This value is returned by reference.</param>
        /// <returns>The UserInfo object representing a valid user</returns>
        /// -----------------------------------------------------------------------------
        public static UserInfo ValidateUser(int portalId, string username, string password, string authType, string verificationCode, string portalName, string ip, ref UserLoginStatus loginStatus)
        {
            loginStatus = UserLoginStatus.LOGIN_FAILURE;

            //Try and Log the user in
            var user = MembershipProvider.Instance().UserLogin(GetEffectivePortalId(portalId), username, password, authType, verificationCode, ref loginStatus);
			if (loginStatus == UserLoginStatus.LOGIN_USERLOCKEDOUT || loginStatus == UserLoginStatus.LOGIN_FAILURE || loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED)
            {
                //User Locked Out so log to event log
                AddEventLog(portalId, username, Null.NullInteger, portalName, ip, loginStatus);
            }

            //Check Default Accounts
            if (loginStatus == UserLoginStatus.LOGIN_SUCCESS || loginStatus == UserLoginStatus.LOGIN_SUPERUSER)
            {
                CheckInsecurePassword(username, password, ref loginStatus);
            }

            //Reset portalId
            FixMemberPortalId(user, portalId);

            //return the User object
            return user;
        }
Esempio n. 44
0
    protected void LoginBtn_Click(object sender, EventArgs e)
    {
        try
        {
            SqlConnection conn = new SqlConnection(connectionString);
            SqlDataAdapter adap = new SqlDataAdapter("Select * from Users where IsFirstLogin=0 and username= '******'", conn);
            dt.Clear();
            adap.Fill(dt);
            if (dt.Rows.Count > 0)
            {

                foreach (DataRow dr in dt.Rows)
                {
                    UserInfo objUser = new UserInfo();
                    objUser.Username = Login1.UserName;
                    UserMembership objMembership = new UserMembership(objUser);
                    objMembership.Username = Login1.UserName;
                    objMembership.Password = "******";
                    objUser.Membership = objMembership;
                    UserCreateStatus result = UserController.CreateUser(ref objUser);
                    UserController.UserLogin(0, objUser, Request.ServerVariables["SERVER_NAME"], this.Request.UserHostAddress, true);
                    Response.Redirect("/profile", false);
                }
            }
            else
            {
                PortalSecurity secure = new PortalSecurity();
                if (Login1.Password != "" && Login1.UserName != "")
                {
                    UserInfo objUser = new UserInfo();
                    objUser.Username = Login1.UserName;

                    UserLoginStatus loginStatus = new UserLoginStatus();
                    UserInfo objAuthendicationPortalUserInfo = UserController.ValidateUser(0, Login1.UserName, Login1.Password, "", "", GetIPAddress(), ref loginStatus);

                    if (!(objAuthendicationPortalUserInfo == null))
                    {
                        UserController.UserLogin(0, objUser, Request.ServerVariables["SERVER_NAME"], this.Request.UserHostAddress, true);
						Response.Redirect("/customredirects.aspx", false);
                    }
                    else
                    {
                        ErrorNotification = true;
                    }
                    
                }
                else
                {
                    ErrorNotification = true;
                }
            }
        }

        catch (Exception ex)
        {


            UserInfo info = UserController.GetCurrentUserInfo();
            ErrorLog objLog = new ErrorLog();
            objLog.ErrorDescription = ex.ToString();
            objLog.ErrorDate = DateTime.Now;
            objLog.ErrorFunctionName = System.Reflection.MethodBase.GetCurrentMethod().Name;
            objLog.ErrorControlName = (GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").Remove(0, GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").LastIndexOf("_") + 1));
            objLog.ErrorLoggedInUser = info.Username;
            objLog.AddErrorToLog(objLog);

        }
    }
    protected void LoginBtn_Click(object sender, EventArgs e)
    {
        bool _isPermanentUser = objBusinessLogic.IsExistMrNo(txtLoginUsername.Text);

        if (Session["AppointmentDetail"] != null)
        {
            if (_isPermanentUser)
            {
                UserInfo objUser = new UserInfo();
                objUser.Username = txtLoginUsername.Text.Trim();
                UserMembership objMembership = new UserMembership(objUser);
                objMembership.Username = txtLoginUsername.Text.Trim();
                objMembership.Password = txtLoginPassword.Text;
                objUser.Membership     = objMembership;

                PortalSettings  po          = new PortalSettings();
                UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
                UserInfo        objUserInfo = UserController.ValidateUser(0, objMembership.Username, txtLoginPassword.Text, "DNN", "", po.PortalName, this.Request.UserHostAddress, ref loginStatus);
                if (objUserInfo != null)
                {
                    UserController.UserLogin(0, objUser, Request.ServerVariables["SERVER_NAME"], this.Request.UserHostAddress, true);
                    Response.Redirect("/Payment.aspx");
                }
                else
                {
                    if (loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED)
                    {
                        lblLoginError.CssClass = "errorText";
                        lblLoginError.Visible  = true;
                        lblLoginError.Text     = "You are not authorized to access Jaslok Portal. Authenticate your mobile number by clicking \"Please verify\" link below";

                        return;
                    }

                    lblLoginError.CssClass = "errorText";
                    lblLoginError.Visible  = true;
                    lblLoginError.Text     = "Please enter correct password!";
                    return;
                }
            }
            else
            {
                Session["AppointmentDetail"] = null;
                lblLoginError.CssClass       = "errorText";
                lblLoginError.Visible        = true;
                lblLoginError.Text           = "Please Enter MR Number To Login!";
                return;
            }
        }
        else if (Session["ConsultationAppointment"] != null)
        {
            if (_isPermanentUser)
            {
                UserInfo objUser = new UserInfo();
                objUser.Username = txtLoginUsername.Text.Trim();
                UserMembership objMembership = new UserMembership(objUser);
                objMembership.Username = txtLoginUsername.Text.Trim();
                objMembership.Password = txtLoginPassword.Text;
                objUser.Membership     = objMembership;

                PortalSettings  po          = new PortalSettings();
                UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
                UserInfo        objUserInfo = UserController.ValidateUser(0, objMembership.Username, txtLoginPassword.Text, "DNN", "", po.PortalName, this.Request.UserHostAddress, ref loginStatus);
                if (objUserInfo != null)
                {
                    UserController.UserLogin(0, objUser, Request.ServerVariables["SERVER_NAME"], this.Request.UserHostAddress, true);
                    Response.Redirect("/Payment.aspx");
                }
                else
                {
                    if (loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED)
                    {
                        lblLoginError.CssClass = "errorText";
                        lblLoginError.Visible  = true;
                        lblLoginError.Text     = "You are not authorized to access Jaslok Portal. Authenticate your mobile number by clicking \"Please verify\" link below";

                        return;
                    }

                    lblLoginError.CssClass = "errorText";
                    lblLoginError.Visible  = true;
                    lblLoginError.Text     = "Please enter correct password!";
                    return;
                }
            }
            else
            {
                Session["ConsultationAppointment"] = null;
                lblLoginError.CssClass             = "errorText";
                lblLoginError.Visible = true;
                lblLoginError.Text    = "Please Enter MR Number To Login!";
                return;
            }
        }
        #region Fresh Login
        else
        {
            JaslokMailer      objMailer     = new JaslokMailer();
            List <Parameters> lstParameters = new List <Parameters>();
            string            lsEmailStatus = string.Empty;

            if (!_isPermanentUser)
            {
                #region Check MrNumber in JEEVA
                var PatientDetails = (dynamic)null;
                if (host.StartsWith("www."))
                {
                    PatientDetails = objPatIndex.GetPatientDetails("JEEVAPG", "JEEVAPG@16", txtLoginUsername.Text.Trim());
                }
                else
                {
                    PatientDetails = objlocalPatIndex.GetPatientDetails("JEEVAPG", "JEEVAPG@16", txtLoginUsername.Text.Trim());
                }
                if (PatientDetails.MRNO != null && PatientDetails.WEBPWD != null)
                {
                    DataSet dsVal = InsertUpdateUserDetails(PatientDetails.MRNO, PatientDetails.PatFName, PatientDetails.PatLName, PatientDetails.PatEmail, PatientDetails.WEBPWD, PatientDetails.PatMobile, PatientDetails.PatSex, PatientDetails.PatAddr1, PatientDetails.PatAge);
                    if (dsVal.Tables[0].Rows.Count == 1)
                    {
                        Session["IsVisitor"] = null;
                        UserInfo objUser = new UserInfo();
                        objUser.Username = txtLoginUsername.Text.Trim();
                        UserMembership objMembership = new UserMembership(objUser);
                        objMembership.Username = txtLoginUsername.Text.Trim();
                        objMembership.Password = txtLoginPassword.Text;
                        objUser.Membership     = objMembership;

                        PortalSettings  po          = new PortalSettings();
                        UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
                        UserInfo        objUserInfo = UserController.ValidateUser(0, objMembership.Username, txtLoginPassword.Text, "DNN", "", po.PortalName, this.Request.UserHostAddress, ref loginStatus);
                        if (objUserInfo != null)
                        {
                            UserController.UserLogin(0, objUser, Request.ServerVariables["SERVER_NAME"], this.Request.UserHostAddress, true);
                            Response.Redirect("/redirect");
                        }
                        else
                        {
                            lblLoginError.CssClass = "errorText";
                            lblLoginError.Visible  = true;
                            lblLoginError.Text     = "Please enter correct password!";
                            return;
                        }
                    }
                }
                else
                {
                    // check for visitor id and MRNO
                    string  MRNumber;
                    string  Username;
                    DataSet ds = objBusinessLogic.GetMRNumberByUserName(txtLoginUsername.Text.Trim());
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        MRNumber = ds.Tables[0].Rows[0]["MRNumber"].ToString();
                        Username = ds.Tables[0].Rows[0]["Username"].ToString();
                    }
                    else
                    {
                        lblLoginError.CssClass = "errorText";
                        lblLoginError.Visible  = true;
                        lblLoginError.Text     = "Please enter correct Id and Password!";
                        return;
                    }
                    if (string.IsNullOrEmpty(MRNumber) && !string.IsNullOrEmpty(Username))
                    {
                        UserInfo objUser = new UserInfo();
                        objUser.Username = txtLoginUsername.Text.Trim();
                        UserMembership objMembership = new UserMembership(objUser);
                        objMembership.Username = txtLoginUsername.Text.Trim();
                        objMembership.Password = txtLoginPassword.Text;
                        objUser.Membership     = objMembership;

                        PortalSettings  po          = new PortalSettings();
                        UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
                        UserInfo        objUserInfo = UserController.ValidateUser(0, objMembership.Username, txtLoginPassword.Text, "DNN", "", po.PortalName, this.Request.UserHostAddress, ref loginStatus);
                        if (objUserInfo != null)
                        {
                            UserController.UserLogin(0, objUser, Request.ServerVariables["SERVER_NAME"], this.Request.UserHostAddress, true);
                            Session["IsVisitor"] = true;
                            Response.Redirect("/redirect");
                        }
                        else
                        {
                            if (loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED)
                            {
                                lblLoginError.CssClass = "errorText";
                                lblLoginError.Visible  = true;
                                lblLoginError.Text     = "You are not authorized to access Jaslok Portal. Authenticate your mobile number by clicking \"Please verify\" link below";
                                return;
                            }
                            lblLoginError.CssClass = "errorText";
                            lblLoginError.Visible  = true;
                            lblLoginError.Text     = "Please enter correct password!";
                            return;
                        }
                    }
                    if (!string.IsNullOrEmpty(MRNumber))
                    {
                        lblLoginError.CssClass = "errorText";
                        lblLoginError.Visible  = true;
                        lblLoginError.Text     = "Please Enter MR Number To Login!";
                        return;
                    }
                    lblLoginError.CssClass = "errorText";
                    lblLoginError.Visible  = true;
                    lblLoginError.Text     = "Login Failed! You are not authorized to access Jaslok Portal!";
                }
                #endregion
            }
            else
            {
                UserInfo objUser = new UserInfo();
                objUser.Username = txtLoginUsername.Text.Trim();
                UserMembership objMembership = new UserMembership(objUser);
                objMembership.Username = objUser.Username.Trim();
                objMembership.Password = txtLoginPassword.Text;
                objUser.Membership     = objMembership;


                PortalSettings  po          = new PortalSettings();
                UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
                UserInfo        objUserInfo = UserController.ValidateUser(0, objMembership.Username, txtLoginPassword.Text, "DNN", "", po.PortalName, this.Request.UserHostAddress, ref loginStatus);
                if (objUserInfo != null)
                {
                    UserController.UserLogin(0, objUser, Request.ServerVariables["SERVER_NAME"], this.Request.UserHostAddress, true);
                    if (!string.IsNullOrEmpty(hdnRedirectUrl.Value))
                    {
                        if (hdnRedirectUrl.Value.ToLower() == "patientregistration")
                        {
                            Response.Redirect("/");
                        }
                        else
                        {
                            Response.Redirect("/" + hdnRedirectUrl.Value);
                        }
                    }
                    else
                    {
                        Response.Redirect("/redirect");
                    }
                }
                else
                {
                    lblLoginError.CssClass = "errorText";
                    lblLoginError.Visible  = true;
                    lblLoginError.Text     = "Please enter correct password!";
                    return;
                }
            }
        }
        #endregion

        /*            if (IsNum == true)
         *          {
         *              // check for Mr Number in db
         *              bool check = objBusinessLogic.IsExistMrNo(txtLoginUsername.Text.Trim());
         *
         *              if (check == true)
         *              {
         *                  UserInfo objUser = new UserInfo();
         *                  objUser.Username = txtLoginUsername.Text.Trim();
         *                  UserMembership objMembership = new UserMembership(objUser);
         *                  objMembership.Username = objUser.Username.Trim();
         *                  objMembership.Password = txtLoginPassword.Text;
         *                  objUser.Membership = objMembership;
         *
         *
         *                  PortalSettings po = new PortalSettings();
         *                  UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
         *                  UserInfo objUserInfo = UserController.ValidateUser(0, objMembership.Username, txtLoginPassword.Text, "DNN", "", po.PortalName, this.Request.UserHostAddress, ref loginStatus);
         *                  if (objUserInfo != null)
         *                  {
         *
         *                      UserController.UserLogin(0, objUser, Request.ServerVariables["SERVER_NAME"], this.Request.UserHostAddress, true);
         *
         *
         *
         *                      if (!string.IsNullOrEmpty(hdnRedirectUrl.Value))
         *                      {
         *                          if (hdnRedirectUrl.Value.ToLower() == "patientregistration")
         *                          {
         *                              Response.Redirect("/");
         *                          }
         *                          else
         *                              Response.Redirect("/" + hdnRedirectUrl.Value);
         *                      }
         *                      else
         *                          Response.Redirect("/redirect");
         *
         *                  }
         *                  else if (loginStatus == UserLoginStatus.LOGIN_USERLOCKEDOUT)
         *                  {
         *
         *                      if (Host.AutoAccountUnlockDuration > 0)
         *                      {
         *                          lblLoginError.CssClass = "errorText";
         *                          lblLoginError.Visible = true;
         *                          lblLoginError.Text = "This account has been locked out after too many unsuccessful login attempts. Please wait 10 minutes before trying to login again. If you have forgotten your password, please try the Forgot Password option before contacting an Administrator.";
         *                      }
         *                  }
         *                  else
         *                  {
         *                      lblLoginError.CssClass = "errorText";
         *                      lblLoginError.Visible = true;
         *                      lblLoginError.Text = "Please enter correct password!";
         *                      return;
         *
         *                  }
         *
         *                  //UserController.UserLogin(0, objUser, Request.ServerVariables["SERVER_NAME"], this.Request.UserHostAddress, true);
         *                  //Response.Redirect("/redirect");
         *
         *
         *
         *              }
         *              // If User enters MRNo. which we do not have
         *              else
         *              {
         *                  var PatientDetails = (dynamic)null;
         *
         *                  if (host.StartsWith("www."))
         *                  {
         *                      PatientDetails = objPatIndex.GetPatientDetails("JEEVAPG", "JEEVAPG@16", txtLoginUsername.Text.Trim());
         *                  }
         *                  else
         *                  {
         *                      PatientDetails = objlocalPatIndex.GetPatientDetails("JEEVAPG", "JEEVAPG@16", txtLoginUsername.Text.Trim());
         *                  }
         *
         *                  if (PatientDetails.MRNO != null && PatientDetails.WEBPWD != null)
         *                  {
         *                      DataSet dsVal = InsertUpdateUserDetails(PatientDetails.MRNO, PatientDetails.PatFName, PatientDetails.PatLName, PatientDetails.PatEmail, PatientDetails.WEBPWD, PatientDetails.PatMobile, PatientDetails.PatSex, PatientDetails.PatAddr1, PatientDetails.PatAge);
         *
         *                      if (dsVal.Tables[0].Rows.Count == 1)
         *                      {
         *                          // loginStatus = UserLoginStatus.LOGIN_SUCCESS;
         *
         *                          Session["IsVisitor"] = null;
         *                          UserInfo objUser = new UserInfo();
         *                          objUser.Username = txtLoginUsername.Text.Trim();
         *                          UserMembership objMembership = new UserMembership(objUser);
         *                          objMembership.Username = txtLoginUsername.Text.Trim();
         *                          objMembership.Password = txtLoginPassword.Text;
         *                          objUser.Membership = objMembership;
         *
         *                          PortalSettings po = new PortalSettings();
         *                          UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
         *                          UserInfo objUserInfo = UserController.ValidateUser(0, objMembership.Username, txtLoginPassword.Text, "DNN", "", po.PortalName, this.Request.UserHostAddress, ref loginStatus);
         *                          if (objUserInfo != null)
         *                          {
         *
         *                              UserController.UserLogin(0, objUser, Request.ServerVariables["SERVER_NAME"], this.Request.UserHostAddress, true);
         *
         *
         *                              //if (!string.IsNullOrEmpty(hdnRedirectUrl.Value))
         *                              //{
         *                              //    Response.Redirect("/" + hdnRedirectUrl.Value);
         *                              //}
         *                              //else
         *                              Response.Redirect("/redirect");
         *
         *                          }
         *                          else
         *                          {
         *                              lblLoginError.CssClass = "errorText";
         *                              lblLoginError.Visible = true;
         *                              lblLoginError.Text = "Please enter correct password!";
         *                              return;
         *                          }
         *                      }
         *                  }
         *                  else
         *                  {
         *                      lblLoginError.CssClass = "errorText";
         *                      lblLoginError.Visible = true;
         *                      lblLoginError.Text = "Login Failed! You are not authorized to access Jaslok Portal!";
         *                  }
         *              }
         *          }*/
    }
 /// -----------------------------------------------------------------------------
 /// <summary>
 /// UserLogin attempts to log the user in, and returns the User if successful
 /// </summary>
 /// <remarks>
 /// </remarks>
 /// <param name="portalId">The Id of the Portal the user belongs to</param>
 /// <param name="username">The user name of the User attempting to log in</param>
 /// <param name="password">The password of the User attempting to log in</param>
 /// <param name="verificationCode">The verification code of the User attempting to log in</param>
 /// <param name="loginStatus">An enumerated value indicating the login status.</param>
 /// <returns>The User as a UserInfo object</returns>
 /// -----------------------------------------------------------------------------
 public override UserInfo UserLogin(int portalId, string username, string password, string verificationCode,
                                    ref UserLoginStatus loginStatus)
 {
     return UserLogin(portalId, username, password, "DNN", verificationCode, ref loginStatus);
 }
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// UserLogin attempts to log the user in, and returns the User if successful
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="portalId">The Id of the Portal the user belongs to</param>
        /// <param name="username">The user name of the User attempting to log in</param>
        /// <param name="password">The password of the User attempting to log in (may not be used by all Auth types)</param>
        /// <param name="authType">The type of Authentication Used</param>
        /// <param name="verificationCode">The verification code of the User attempting to log in</param>
        /// <param name="loginStatus">An enumerated value indicating the login status.</param>
        /// <returns>The User as a UserInfo object</returns>
        /// -----------------------------------------------------------------------------
        public override UserInfo UserLogin(int portalId, string username, string password, string authType,
                                           string verificationCode, ref UserLoginStatus loginStatus)
        {
            //For now, we are going to ignore the possibility that the User may exist in the 
            //Global Data Store but not in the Local DataStore ie. A shared Global Data Store

            //Initialise Login Status to Failure
            loginStatus = UserLoginStatus.LOGIN_FAILURE;

            DataCache.ClearUserCache(portalId, username);
            DataCache.ClearCache(GetCacheKey(username));

            //Get a light-weight (unhydrated) DNN User from the Database, we will hydrate it later if neccessary
            UserInfo user = (authType == "DNN")
                                ? GetUserByUserName(portalId, username)
                                : GetUserByAuthToken(portalId, username, authType);
            if (user != null && !user.IsDeleted)
            {
                //Get AspNet MembershipUser
                MembershipUser aspnetUser = GetMembershipUser(user);

                //Fill Membership Property from AspNet MembershipUser
                FillUserMembership(aspnetUser, user);

                //Check if the User is Locked Out (and unlock if AutoUnlock has expired)
                if (aspnetUser.IsLockedOut)
                {
                    if (AutoUnlockUser(aspnetUser))
                    {
                        //Unlock User
                        user.Membership.LockedOut = false;
                    }
                    else
                    {
                        loginStatus = UserLoginStatus.LOGIN_USERLOCKEDOUT;
                    }
                }

                //Check in a verified situation whether the user is Approved
                if (user.Membership.Approved == false && user.IsSuperUser == false)
                {
                    //Check Verification code
                    var ps = new PortalSecurity();
                    if (verificationCode == ps.EncryptString(portalId + "-" + user.UserID, Config.GetDecryptionkey()))
                    {
                        UserController.ApproveUser(user);
                    }
                    else
                    {
                        loginStatus = UserLoginStatus.LOGIN_USERNOTAPPROVED;
                    }
                }

                //Verify User Credentials
                bool bValid = false;
                loginStatus = ValidateLogin(username, authType, user, loginStatus, password, ref bValid, portalId);
                if (!bValid)
                {
                    //Clear the user object
                    user = null;
                }
            }
            else
            {
                //Clear the user object
                user = null;
            }
            return user;
        }
 public static UserInfo ValidateUser(int portalId, string Username, string Password, string VerificationCode, string PortalName, string IP, ref UserLoginStatus loginStatus)
 {
     return ValidateUser(portalId, Username, Password, "DNN", VerificationCode, PortalName, IP, ref loginStatus);
 }
 private static UserLoginStatus ValidateLogin(string username, string authType, UserInfo user,
                                              UserLoginStatus loginStatus, string password, ref bool bValid,
                                              int portalId)
 {
     if (loginStatus != UserLoginStatus.LOGIN_USERLOCKEDOUT &&
         (loginStatus != UserLoginStatus.LOGIN_USERNOTAPPROVED || user.IsInRole("Unverified Users")))
     {
         if (authType == "DNN")
         {
             if (user.IsSuperUser)
             {
                 if (ValidateUser(username, password))
                 {
                     loginStatus = UserLoginStatus.LOGIN_SUPERUSER;
                     bValid = true;
                 }
             }
             else
             {
                 if (ValidateUser(username, password))
                 {
                     loginStatus = UserLoginStatus.LOGIN_SUCCESS;
                     bValid = true;
                 }
             }
         }
         else
         {
             if (user.IsSuperUser)
             {
                 loginStatus = UserLoginStatus.LOGIN_SUPERUSER;
                 bValid = true;
             }
             else
             {
                 loginStatus = UserLoginStatus.LOGIN_SUCCESS;
                 bValid = true;
             }
         }
     }
     return loginStatus;
 }
Esempio n. 50
0
        protected override void OnLoad(EventArgs e)
        {
            if (Request.QueryString["noSAML"] != null)
            {
            }
            else
            {
                base.OnLoad(e);
                staticPortalSettings = PortalSettings;
                string redirectTo = "~/";
                try
                {
                    config = DNNAuthenticationSAMLAuthenticationConfig.GetConfig(PortalId);
                    if (Request.HttpMethod == "POST" && !Request.IsAuthenticated)
                    {
                        //specify the certificate that your SAML provider has given to you
                        string samlCertificate = config.TheirCert;

                        Saml.Response samlResponse = new Saml.Response(samlCertificate);
                        LogToEventLog("Request:", Request.Form["SAMLResponse"].ToString());
                        samlResponse.LoadXmlFromBase64(Request.Form["SAMLResponse"]); //SAML providers usually POST the data into this var
                                                                                      //String xmlExample = "";
                                                                                      //samlResponse.LoadXml(xmlExample);

                        LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("samlResponse is:  ", samlResponse.ToString()));

                        if (samlResponse.IsValid())
                        {
                            LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "saml valid");
                            LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("samlResponse is:  {0}", samlResponse.Xml.ToString()));
                            //WOOHOO!!! user is logged in
                            //YAY!

                            //Obtain optional items
                            string username = "", email = "", firstname = "", lastname = "", displayname = "";
                            var    rolesList         = new List <string>();
                            var    requiredRolesList = new List <string>();
                            try
                            {
                                username = samlResponse.GetNameID();

                                if (username == null)
                                {
                                    LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "USER IS NULL");
                                }
                                else
                                {
                                    if (username == "")
                                    {
                                        LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "USER IS EMPTY");
                                    }
                                }


                                LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("Username is: {0} ", username));

                                email = samlResponse.GetUserProperty(config.usrEmail);
                                if (email == null)
                                {
                                    email = samlResponse.GetUserProperty("email");
                                }
                                firstname = samlResponse.GetUserProperty(config.usrFirstName);
                                if (firstname == null)
                                {
                                    firstname = samlResponse.GetUserProperty("firstName");
                                }
                                lastname = samlResponse.GetUserProperty(config.usrLastName);
                                if (lastname == null)
                                {
                                    lastname = samlResponse.GetUserProperty("lastName");
                                }
                                displayname = samlResponse.GetUserProperty(config.usrDisplayName);
                                if (displayname == null)
                                {
                                    displayname = samlResponse.GetUserProperty("displayName");
                                }

                                var roles = samlResponse.GetUserProperty(config.RoleAttribute);
                                if (!string.IsNullOrWhiteSpace(roles))
                                {
                                    rolesList = roles.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                                }

                                var requiredRoles = samlResponse.GetUserProperty(config.RequiredRoles);
                                if (!string.IsNullOrWhiteSpace(requiredRoles))
                                {
                                    requiredRolesList = requiredRoles.Split(new[] { ',' },
                                                                            StringSplitOptions.RemoveEmptyEntries).ToList();
                                }
                            }
                            catch (Exception ex)
                            {
                                //insert error handling code
                                //no, really, please do
                                LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("Exception:......{0}", ex.InnerException.Message));
                            }


                            UserInfo userInfo = UserController.GetUserByName(PortalSettings.PortalId, username);


                            if (userInfo == null)
                            {
                                //user does not exists, it needs to be created.
                                userInfo = new UserInfo();
                                try
                                {
                                    if (username != null && email != null && firstname != null && lastname != null)
                                    {
                                        if (displayname == null)
                                        {
                                            userInfo.DisplayName = firstname + " " + lastname;
                                        }
                                        else
                                        {
                                            userInfo.DisplayName = displayname;
                                        }

                                        userInfo.FirstName           = firstname;
                                        userInfo.LastName            = lastname;
                                        userInfo.Username            = username;
                                        userInfo.Email               = email;
                                        userInfo.PortalID            = PortalSettings.PortalId;
                                        userInfo.IsSuperUser         = false;
                                        userInfo.Membership.Password = UserController.GeneratePassword();

                                        var usrCreateStatus = new UserCreateStatus();

                                        usrCreateStatus = UserController.CreateUser(ref userInfo);

                                        if (usrCreateStatus == UserCreateStatus.Success)
                                        {
                                            UserInfo usrInfo = UserController.GetUserByName(PortalSettings.PortalId, username);
                                            SetProfileProperties(samlResponse, usrInfo);

                                            //Add roles if needed, since a new user no need to remove roles or process that condition
                                            if (rolesList.Any())
                                            {
                                                AssignRolesFromList(usrInfo, rolesList);
                                            }
                                        }
                                        else
                                        {
                                            LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "Error creating new user..." + usrCreateStatus.ToString());
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "Error creating new user...exception:  " + ex.InnerException.Message);
                                }
                            }
                            else
                            {
                                //User already exists

                                //Wen unlock it if necessary
                                if (userInfo.Membership.LockedOut)
                                {
                                    UserController.UnLockUser(userInfo);
                                }
                                LogToEventLog("DNN.Authentication.SAML.OnLoad(post !auth)", String.Format("FoundUser userInfo.Username: {0}", userInfo.Username));


                                try
                                {
                                    //We update the user's info
                                    userInfo.DisplayName = displayname;
                                    userInfo.FirstName   = firstname;
                                    userInfo.LastName    = lastname;
                                    userInfo.Email       = email;

                                    UserController.UpdateUser(PortalSettings.PortalId, userInfo);

                                    //We update the user's properties
                                    SetProfileProperties(samlResponse, userInfo);

                                    //Ensure roles if neeeded
                                    if (rolesList.Any())
                                    {
                                        AssignRolesFromList(userInfo, rolesList);
                                    }

                                    //If we have a required role list, remove any of those items that were not in the SAML attribute
                                    if (requiredRolesList.Any())
                                    {
                                        var toRemove = requiredRolesList.Where(req => !rolesList.Contains(req))
                                                       .ToList();
                                        RemoveRolesFromList(userInfo, toRemove);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "Error updating existing user...exception:  " + ex.InnerException.Message);
                                }
                            }


                            UserValidStatus validStatus = UserController.ValidateUser(userInfo, PortalId, true);
                            UserLoginStatus loginStatus = validStatus == UserValidStatus.VALID ? UserLoginStatus.LOGIN_SUCCESS : UserLoginStatus.LOGIN_FAILURE;
                            if (loginStatus == UserLoginStatus.LOGIN_SUCCESS)
                            {
                                SetLoginDate(username);
                                //Raise UserAuthenticated Event
                                var eventArgs = new UserAuthenticatedEventArgs(userInfo, userInfo.Email, loginStatus, config.DNNAuthName) //"DNN" is default, "SAML" is this one.  How did it get named SAML????
                                {
                                    Authenticated = true,
                                    Message       = "User authorized",
                                    RememberMe    = false
                                };
                                OnUserAuthenticated(eventArgs);
                            }
                        }
                        else
                        {
                            LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "saml not valid");
                        }
                    }
                    else if (Request.IsAuthenticated)
                    {
                        //Do Nothing if the request is authenticated
                    }
                    else
                    {
                        XmlDocument request = GenerateSAMLRequest();
                        //X509Certificate2 cert = StaticHelper.GetCert(config.OurCertFriendlyName);
                        //request = StaticHelper.SignSAMLRequest(request, cert);
                        LogToEventLog("DNN.Authentication.SAML.OnLoad()", string.Format("request xml {0}", request.OuterXml));
                        String convertedRequestXML = StaticHelper.Base64CompressUrlEncode(request);
                        redirectTo = config.IdPURL + (config.IdPURL.Contains("?") ? "&" : "?") + "SAMLRequest=" + convertedRequestXML;
                        if (Request.QueryString.Count > 0)
                        {
                            redirectTo += "&RelayState=" + HttpUtility.UrlEncode(Request.Url.Query.Replace("?", "&"));
                        }

                        Response.Redirect(Page.ResolveUrl(redirectTo), false);
                    }
                }
                catch (System.Threading.ThreadAbortException tae)
                {
                    LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("Exception is {0}", tae.Message));
                    //Response.Redirect(Page.ResolveUrl(redirectTo), false);
                }
                catch (Exception ex)
                {
                    LogToEventLog("DNN.Authentication.SAML.OnLoad()", string.Format("Exception  {0}", ex.Message));
                    //redirectTo = "~/";
                }

                //Response.Redirect(Page.ResolveUrl(redirectTo), false);
            }
        }
 public UserLoginFailedException(UserLoginStatus status)
 {
     Status = status;
 }