예제 #1
0
        public bool AddSessionHostCredentials(EnterpriseHostSessionCredentials credentials)
        {
            var success = false;

            using (var db = new MyrtilleEnterpriseDBContext())
            {
                var session = db.Session.FirstOrDefault(m => m.SessionID == credentials.SessionID);
                if (session != null && db.Host.Any(m => m.ID == credentials.HostID))
                {
                    var sessionHost = db.SessionHostCredentials.FirstOrDefault(m =>
                                                                               m.SessionID == session.ID &&
                                                                               m.HostID == credentials.HostID);

                    if (sessionHost != null)
                    {
                        db.SessionHostCredentials.Remove(sessionHost);
                    }

                    sessionHost = new SessionHostCredential
                    {
                        SessionID = session.ID,
                        HostID    = credentials.HostID,
                        Domain    = credentials.Domain,
                        Username  = credentials.Username,
                        Password  = CryptoHelper.AES_Encrypt(CryptoHelper.RDP_Encrypt(credentials.Password), credentials.SessionKey)
                    };

                    db.SessionHostCredentials.Add(sessionHost);
                    db.SaveChanges();
                    success = true;
                }
            }

            return(success);
        }
예제 #2
0
        public string CreateUserSession(string sessionID, long hostID, string username, string password, string domain)
        {
            using (var db = new MyrtilleEnterpriseDBContext())
            {
                if (!db.Session.Any(m => m.SessionID == sessionID && m.IsAdmin && m.Expire > DateTime.Now))
                {
                    return(null);
                }

                if (!db.Host.Any(m => m.ID == hostID))
                {
                    return(null);
                }

                string newSessionID = Guid.NewGuid().ToString();
                string sessionKey   = Guid.NewGuid().ToString("n");

                var session = new Session
                {
                    Domain    = domain,
                    Username  = username,
                    Password  = CryptoHelper.AES_Encrypt(CryptoHelper.RDP_Encrypt(password), sessionKey),
                    SessionID = newSessionID,
                    IsAdmin   = false,
                    Expire    = DateTime.Now.AddHours(1),
                    OneTime   = true
                };

                db.Session.Add(session);
                db.SaveChanges();

                return(string.Format("?SI={0}&SD={1}&SK={2}", newSessionID, hostID, sessionKey));
            }
        }
예제 #3
0
        public static void CreateUser(User user)
        {
            HttpCookie cookie = new HttpCookie(Params.UserCookieName);

            cookie.Value   = CryptoHelper.AES_Encrypt(user.ToJson(), Params.SecretKey);
            cookie.Expires = DateTime.Now.AddYears(1);
            // 写登录Cookie
            HttpContext.Current.Response.Cookies.Remove(cookie.Name);
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
예제 #4
0
        /// <summary>
        /// 用户修改密码
        /// </summary>
        /// <param name="loginName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public WebResult <bool> ChangePassword(string oldPassword, string newPassword, string cfmPassword)
        {
            try
            {
                if (oldPassword.IsNullOrEmpty() || newPassword.IsNullOrEmpty() || cfmPassword.IsNullOrEmpty())
                {
                    return(Result(false, ErrorCode.sys_param_format_error));
                }
                if (!cfmPassword.Equals(newPassword))
                {
                    return(Result(false, ErrorCode.user_password_notequal));
                }
                using (var db = new DbRepository())
                {
                    oldPassword = CryptoHelper.MD5_Encrypt(oldPassword);

                    var user = db.User.Where(x => x.ID.Equals(this.Client.LoginUser.ID)).FirstOrDefault();
                    if (user == null)
                    {
                        return(Result(false, ErrorCode.user_not_exit));
                    }
                    if (!user.Password.Equals(oldPassword))
                    {
                        return(Result(false, ErrorCode.user_password_nottrue));
                    }
                    newPassword   = CryptoHelper.MD5_Encrypt(newPassword);
                    user.Password = newPassword;
                    Client.Session[Params.UserCookieName] = CryptoHelper.AES_Encrypt(user.ToJson(), Params.SecretKey);
                    if (db.SaveChanges() > 0)
                    {
                        var list  = Cache_Get_UserList();
                        var index = list.FindIndex(x => x.ID.Equals(user.ID));
                        if (index > -1)
                        {
                            list[index] = user;
                        }
                        else
                        {
                            list.Add(user);
                        }
                        return(Result(true));
                    }
                    else
                    {
                        return(Result(false, ErrorCode.sys_fail));
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteException(ex);
                return(Result(false, ErrorCode.sys_fail));
            }
        }
예제 #5
0
        public void TestRunner(string text, string password, byte[] salt)
        {
            var encrypted = CryptoHelper.AES_Encrypt(text, password, salt);

            System.Console.WriteLine(encrypted);

            var decrypted = CryptoHelper.AES_Decrypt(encrypted, password, salt);

            System.Console.WriteLine(decrypted);
            Assert.AreEqual(text, decrypted, "Decrypted text did not match original text.");
        }
예제 #6
0
 //更新用户的cookie
 public static void CreatePeople(Person person)
 {
     try
     {
         HttpCookie cookie = new HttpCookie(Params.PeopleCookieName);
         cookie.Value   = CryptoHelper.AES_Encrypt(person.ToJson(), Params.SecretKey);
         cookie.Expires = DateTime.Now.AddMinutes(120);
         // 写登录Cookie
         HttpContext.Current.Response.Cookies.Remove(cookie.Name);
         HttpContext.Current.Response.Cookies.Add(cookie);
     }
     catch { }
 }
예제 #7
0
 //更新用户的cookie
 public static void CreateWxUser(WXUser user)
 {
     try
     {
         HttpCookie cookie = new HttpCookie(Params.UserCookieName);
         using (DbRepository entities = new DbRepository())
         {
             cookie.Value   = CryptoHelper.AES_Encrypt(user.ToJson(), Params.SecretKey);
             cookie.Expires = DateTime.Now.AddMinutes(120);
         }
         // 写登录Cookie
         HttpContext.Current.Response.Cookies.Remove(cookie.Name);
         HttpContext.Current.Response.Cookies.Add(cookie);
     }
     catch { }
 }
예제 #8
0
        public EnterpriseSession Authenticate(string username, string password, string adminGroup, string domain, string netbiosDomain)
        {
            try
            {
                using (var context = new PrincipalContext(ContextType.Domain, domain, username, password))
                {
                    UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);

                    DirectoryEntry entry = (DirectoryEntry)user.GetUnderlyingObject();

                    if (user.IsAccountLockedOut())
                    {
                        return(new EnterpriseSession
                        {
                            AuthenticationErrorCode = EnterpriseAuthenticationErrorCode.USER_ACCOUNT_LOCKED
                        });
                    }

                    if (user.Enabled != null && !(bool)user.Enabled)
                    {
                        return(new EnterpriseSession
                        {
                            AuthenticationErrorCode = EnterpriseAuthenticationErrorCode.ACCOUNT_DISABLED
                        });
                    }

                    if (user.AccountExpirationDate != null && (DateTime)user.AccountExpirationDate <= DateTime.Now)
                    {
                        return(new EnterpriseSession
                        {
                            AuthenticationErrorCode = EnterpriseAuthenticationErrorCode.ACCOUNT_EXPIRED
                        });
                    }

                    if (!user.PasswordNeverExpires) //&& !user.UserCannotChangePassword)
                    {
                        var expDate = (DateTime)entry.InvokeGet("PasswordExpirationDate");
                        // if the expiration date is not set, its default value is 1970/01/01
                        if (expDate <= DateTime.Now && expDate > new DateTime(1970, 1, 1))
                        {
                            return(new EnterpriseSession
                            {
                                AuthenticationErrorCode = EnterpriseAuthenticationErrorCode.PASSWORD_EXPIRED
                            });
                        }
                    }


                    var directoryGroups = new List <string>();

                    try
                    {
                        directoryGroups.AddRange(user.GetGroups().Select(m => m.Name).ToList <string>());
                    }
                    catch (Exception e)
                    {
                        //There is an issue accessing user primary ad group remotely,
                        //Exception: Information about the domain could not be retrieved (1355).
                        //in that case use another method which will exclude the primary domain
                        // might need to find another way to do this!
                        directoryGroups.AddRange(GetDirectoryGroups(entry));
                    }

                    //Add user to directory group to allow restriction to host to specific username
                    directoryGroups.Add(username);

                    bool isAdmin = directoryGroups.Any(m => m.Equals(adminGroup, StringComparison.InvariantCultureIgnoreCase));

                    string sessionID  = Guid.NewGuid().ToString();
                    string sessionKey = Guid.NewGuid().ToString("n");
                    using (var db = new MyrtilleEnterpriseDBContext())
                    {
                        var session = db.Session.FirstOrDefault(m => m.Username == username);
                        if (session != null)
                        {
                            db.Session.Remove(session);
                            db.SaveChanges();
                        }

                        session = new Session
                        {
                            Domain    = netbiosDomain,
                            Username  = username,
                            Password  = CryptoHelper.AES_Encrypt(CryptoHelper.RDP_Encrypt(password), sessionKey),
                            SessionID = sessionID,
                            IsAdmin   = isAdmin
                        };

                        db.Session.Add(session);
                        db.SaveChanges();

                        var groups = directoryGroups.Select(x => new SessionGroup
                        {
                            SessionID      = session.ID,
                            DirectoryGroup = x
                        });

                        db.SessionGroup.AddRange(groups);
                        db.SaveChanges();
                        return(new EnterpriseSession
                        {
                            Domain = netbiosDomain,
                            UserName = username,
                            SessionID = sessionID,
                            SessionKey = sessionKey,
                            IsAdmin = isAdmin,
                            SingleUseConnection = false
                        });
                    }
                }
            }
            catch (DirectoryServicesCOMException e)
            {
                var formattedError = (DirectoryExceptionHelper)e;

                return(new EnterpriseSession
                {
                    AuthenticationErrorCode = formattedError.ErrorCode
                });
            }
            catch (PrincipalOperationException e)
            {
                return(null);
            }
            catch (Exception e)
            {
                return(new EnterpriseSession
                {
                    AuthenticationErrorCode = EnterpriseAuthenticationErrorCode.UNKNOWN_ERROR
                });
            }
        }
예제 #9
0
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="loginName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public WebResult <bool> Login(string loginName, string password)
        {
            try
            {
                if (loginName.IsNullOrEmpty() || password.IsNullOrEmpty())
                {
                    return(Result(false, ErrorCode.sys_param_format_error));
                }
                using (var db = new DbRepository())
                {
                    string md5Password = CryptoHelper.MD5_Encrypt(password);
                    var    user        = Cache_Get_UserList().AsQueryable().AsNoTracking().Where(x => x.Password.Equals(md5Password) && x.Account.Equals(loginName)).FirstOrDefault();
                    if (user == null)
                    {
                        return(Result(false, ErrorCode.user_login_error));
                    }
                    else if ((user.Flag & (long)GlobalFlag.Unabled) != 0)
                    {
                        return(Result(false, ErrorCode.user_disabled));
                    }
                    else if ((user.Flag & (long)GlobalFlag.Removed) != 0)
                    {
                        return(Result(false, ErrorCode.user_not_exit));
                    }
                    else if ((user.Flag & (long)GlobalFlag.Qiut) != 0)
                    {
                        return(Result(false, ErrorCode.user_quit));
                    }

                    else
                    {
                        if (user.OperateFlag.HasValue)
                        {
                            user.OperateList = Get_UserOperateList(user.OperateFlag.Value);
                        }
                        if (user.RoleID.IsNotNullOrEmpty())
                        {
                            if (user.RoleID.Trim() == "1")
                            {
                                user.IsNotShowMoney = false;
                            }
                            else
                            {
                                var role = db.Role.Find(user.RoleID);
                                if (role == null)
                                {
                                    return(Result(false, ErrorCode.sys_param_format_error));
                                }
                                user.IsNotShowMoney = role.IsNotShowMoney == YesOrNoCode.Yes;
                            }
                        }
                        Client.Session[Params.UserCookieName] = CryptoHelper.AES_Encrypt(user.ToJson(), Params.SecretKey);
                        return(Result(true));
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteException(ex);
                return(Result(false, ErrorCode.sys_fail));
            }
        }
예제 #10
0
        public bool ChangeUserPassword(string username, string oldPassword, string newPassword, string domain)
        {
            var success = false;

            var config             = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var localAdminUser     = ((AppSettingsSection)config.GetSection("localAdmin")).Settings["LocalAdminUser"].Value;
            var localAdminPassword = ((AppSettingsSection)config.GetSection("localAdmin")).Settings["localAdminPassword"].Value;

            if (username.Equals(localAdminUser))
            {
                if (!localAdminPassword.Equals("admin"))
                {
                    localAdminPassword = CryptoHelper.AES_Decrypt(localAdminPassword, localAdminUser);
                }
                if (oldPassword.Equals(localAdminPassword))
                {
                    ((AppSettingsSection)config.GetSection("localAdmin")).Settings["localAdminPassword"].Value = CryptoHelper.AES_Encrypt(newPassword, localAdminUser);
                    config.Save(ConfigurationSaveMode.Modified);
                    ConfigurationManager.RefreshSection("localAdmin");
                    success = true;
                }
            }

            return(success);
        }
예제 #11
0
        public EnterpriseSession Authenticate(string username, string password, string adminGroup, string domain, string netbiosDomain)
        {
            EnterpriseSession enterpriseSession = null;

            try
            {
                var config             = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var localAdminUser     = ((AppSettingsSection)config.GetSection("localAdmin")).Settings["LocalAdminUser"].Value;
                var localAdminPassword = ((AppSettingsSection)config.GetSection("localAdmin")).Settings["localAdminPassword"].Value;
                if (!username.Equals(localAdminUser))
                {
                    enterpriseSession = new EnterpriseSession
                    {
                        AuthenticationErrorCode = EnterpriseAuthenticationErrorCode.USER_NOT_FOUND
                    };
                }
                else
                {
                    if (!localAdminPassword.Equals("admin"))
                    {
                        localAdminPassword = CryptoHelper.AES_Decrypt(localAdminPassword, localAdminUser);
                    }
                    if (!password.Equals(localAdminPassword))
                    {
                        enterpriseSession = new EnterpriseSession
                        {
                            AuthenticationErrorCode = EnterpriseAuthenticationErrorCode.INVALID_LOGIN_CREDENTIALS
                        };
                    }
                    else
                    {
                        if (password.Equals("admin"))
                        {
                            enterpriseSession = new EnterpriseSession
                            {
                                AuthenticationErrorCode = EnterpriseAuthenticationErrorCode.PASSWORD_EXPIRED
                            };
                        }
                        else
                        {
                            using (var db = new MyrtilleEnterpriseDBContext())
                            {
                                var session = db.Session.FirstOrDefault(m => m.Username == username);
                                if (session != null)
                                {
                                    db.Session.Remove(session);
                                    db.SaveChanges();
                                }

                                string sessionID  = Guid.NewGuid().ToString();
                                string sessionKey = Guid.NewGuid().ToString("n");

                                session = new Session
                                {
                                    Domain    = netbiosDomain,
                                    Username  = username,
                                    Password  = CryptoHelper.AES_Encrypt(CryptoHelper.RDP_Encrypt(password), sessionKey),
                                    SessionID = sessionID,
                                    IsAdmin   = true
                                };

                                db.Session.Add(session);
                                db.SaveChanges();

                                enterpriseSession = new EnterpriseSession
                                {
                                    Domain              = netbiosDomain,
                                    UserName            = username,
                                    SessionID           = sessionID,
                                    SessionKey          = sessionKey,
                                    IsAdmin             = true,
                                    SingleUseConnection = false
                                };
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                enterpriseSession = new EnterpriseSession
                {
                    AuthenticationErrorCode = EnterpriseAuthenticationErrorCode.UNKNOWN_ERROR
                };
            }

            return(enterpriseSession);
        }