public bool AccountConfirmation(string username)
 {
     CriticalResultsEntityManager manager = new CriticalResultsEntityManager();
     UserEntity ue = manager.GetUser(username);
     if (!ue.UserTransports.IsLoaded)
     {
         ue.UserTransports.Load();
     }
     foreach (UserTransportEntity ute in ue.UserTransports)
     {
         if (!ute.TransportReference.IsLoaded)
         {
             ute.TransportReference.Load();
         }
         if (ute.Transport.Name == EMAIL_TRANSPORT && !String.IsNullOrEmpty(ute.Address))
         {
             SystemMailer = new SystemEmailer();
             SettingEntity[] settings = new CriticalResultsEntityManager().GetSettings("System");
             string message = "";
             foreach (SettingEntity setting in settings)
             {
                 if (setting.EntryKey == "AccountConfirmationMessage")
                 {
                     message = setting.Value;
                 }
             }
             message = String.Format(message, ue.UserName);
             BackgroundWorker bgw = new BackgroundWorker();
             bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
             bgw.RunWorkerAsync(message + "|" + ute.Address);
         }
     }
     return true;
 }
        public static bool Authenticate(string authKey, string authValue, string userName, string userIP, TraceSource _Trace, out string outUserName, out string tokenString, out string message)
        {
            outUserName="";
            tokenString = "";
            CriticalResults.CriticalResultsEntityManager manager = new CriticalResultsEntityManager();
            bool hasPassword = false;
            string queryString = string.Format("it.Type='AuthExt' AND it.Key='{0}' AND it.Value='{1}'", authKey, authValue);
            // if userName is specified then we go from ANCR and authValue is password, overwise authValue is username of already authenticated user
            if (userName != null)
            {
                hasPassword = true;
                UserEntity user = manager.GetUser(userName);
                if (user == null)
                {
                    message = "Invalid username or password.";
                    return false;
                }
                queryString = string.Format("it.Type='AuthExt' AND it.Key='{0}' AND it.Value='{1}' AND it.User.Id={2}", authKey, authValue, user.Id);
            }

            CriticalResults.UserEntryEntity[] entries = manager.QueryUserEntryEntities(queryString, null, null);
            if (entries.Count() == 1)
            {
                UserEntity user=entries.First().User;
                if (!hasPassword)
                {
                    _Trace.TraceEvent(TraceEventType.Information, 0, "Lookup for username \"{0}\" mapped to \"{1}\".", authValue, user.UserName);
                }
                if (user.Enabled == true)
                {
                    outUserName = user.UserName;
                    CriticalResults.TokenEntity[] currentTokens = manager.GetTokensForUser(user.UserName);
                    foreach (CriticalResults.TokenEntity t in currentTokens)
                    {
                        if (t.Ipv4 == userIP)
                        {
                            t.UpdatedTime = DateTime.Now;
                            manager.SaveChanges();
                            tokenString = t.Token.ToString();
                            message = "";
                            return true;
                        }
                    }
                    CriticalResults.TokenEntity token = manager.CreateToken(user, userIP);
                    tokenString = token.Token.ToString();
                    message = "";
                    return true;
                }
                else
                {
                    _Trace.TraceEvent(TraceEventType.Warning, 0, "Found user \"{0}\" mapped to \"{1}\".  ANCR Account disabled.", authValue, user.UserName);
                    message = "Your account is disabled. Please contact your System Administrator.";
                    return false;
                }
            }
            else
            {
                if (entries.Count() > 1)
                {
                    _Trace.TraceEvent(TraceEventType.Warning, 0, "Found multiple users \"{0}\" (Count: {1})", authValue, entries.Count());
                    message = "Multiple ANCR users found for your username, until this is resolved you may not login with your credentials.  Please contact your System Administrator.";
                }
                else
                {
                    if (hasPassword)
                    {
                        _Trace.TraceEvent(TraceEventType.Warning, 0, "Invalid username or password \"{0}\"", userName);
                        message = "Invalid username or password.";
                    }
                    else
                    {
                        _Trace.TraceEvent(TraceEventType.Warning, 0, "No ANCR account found for  \"{0}\"", authValue);
                        message = "No ANCR user is found for your credentials. Please contact your System Administrator.";
                    }
                }
                return false;
            }
        }
 /// <summary>
 /// Adds all available transports to a user with address to be filled out later.
 /// Created: 2009-07-28, John Morgan
 /// Modified: 2009-08-13, John Morgan
 /// Altered to only add transports that do not exist
 /// </summary>
 /// <param name="userName"></param>
 /// <returns>UserEntity</returns>
 private UserEntity AddTransportsToUser(string userName)
 {
     CriticalResultsEntityManager manager = new CriticalResultsEntityManager();
     TransportEntity[] transports = manager.GetAllTransports();
     UserEntity user = manager.GetUser(userName);
     foreach (TransportEntity transport in transports)
     {
         bool transportFound = false;
         foreach (UserTransportEntity t in user.UserTransports)
         {
             if (t.Transport.Name == transport.Name)
                 transportFound = true;
         }
         if(!transportFound)
             manager.CreateUserTransport(userName, transport.Name, "");
     }
     return manager.GetUser(userName);
 }
        public User CreateANCRUser(User user)
        {
            CriticalResultsEntityManager manager = new CriticalResultsEntityManager();
            UserEntity userEntity = manager.CreateUserEntity(user.ToEntity());

            AuditEvent("CreateUser:Success", user.UserName);

            LevelEntity[] levels = manager.GetLevels();
            List<string> levelNames = new List<string>();
            foreach (LevelEntity level in levels)
            {
                levelNames.Add(level.Name);
            }

            TransportEntity[] transports = manager.GetAllTransports();
            foreach (TransportEntity transport in transports)
            {
                bool addTransport = true;
                foreach (UserTransportEntity userTransport in userEntity.UserTransports)
                {
                    if (userTransport.Transport.Name == transport.Name)
                    {
                        addTransport = false;
                    }
                }
                if (addTransport)
                {
                    if (user.Transports != null)
                    {
                        bool transportFound = false;
                        for (int i = 0; i < user.Transports.Length; i++)
                        {
                            if (user.Transports[i].Transport.Name == transport.Name)
                            {
                                if (user.Transports[i].Address == null)
                                {
                                    user.Transports[i].Address = "";
                                }
                                manager.CreateUserTransport(userEntity.UserName, transport.Name, user.Transports[i].Address);
                                manager.UpdateLevelsToUserTransport(user.UserName, transport.Name, user.Transports[i].Address, levelNames.ToArray());
                                transportFound = true;

                            }
                        }
                        if (!transportFound)
                        {
                            manager.CreateUserTransport(userEntity.UserName, transport.Name, "");
                            manager.UpdateLevelsToUserTransport(user.UserName, transport.Name, "", levelNames.ToArray());
                        }
                    }
                    else
                    {
                        manager.CreateUserTransport(userEntity.UserName, transport.Name, "");
                        manager.UpdateLevelsToUserTransport(user.UserName, transport.Name, "", levelNames.ToArray());
                    }
                }
            }

            userEntity = manager.GetUser(user.UserName);

            //bool passwordFound = false;
            //foreach (UserEntryEntity uee in e.UserEntries)
            //{
            //    if (uee.Type == "AuthExt" && uee.Key == "ANCR")
            //        passwordFound = true;
            //}
            //if(!passwordFound)
            //    GeneratePassword(user.UserName);

            User u = new User(userEntity);
            u.ResolveRoles();
            u.ResolveTransports();
            u.ResolveEntries();
            return u;
        }
 public bool SetPassword(string userName, string currentPassword, string newPassword)
 {
     string currentPasswordHash = BitConverter.ToString(HashAlgorithm.Create("SHA256").ComputeHash(Encoding.ASCII.GetBytes(currentPassword))).ToLower().Replace("-", "");
     string newPasswordHash = BitConverter.ToString(HashAlgorithm.Create("SHA256").ComputeHash(Encoding.ASCII.GetBytes(newPassword))).ToLower().Replace("-", "");
     CriticalResultsEntityManager manager = new CriticalResultsEntityManager();
     UserEntity ue = manager.GetUser(userName);
     UserEntryEntity passwordEntity = null;
     foreach (UserEntryEntity uee in ue.UserEntries)
     {
         if (uee.Type == "AuthExt" && uee.Key == "ANCR")
         {
             passwordEntity = uee;
         }
     }
     if (passwordEntity == null)
         return false;
     else
     {
         if (passwordEntity.Value == currentPasswordHash)
         {
             return manager.UpdateUserEntryEntity(userName, "AuthExt", "ANCR", newPasswordHash, true);
         }
         return false;
     }
 }
        public bool CreateEntity()
        {
            CriticalResultsEntityManager manager = new CriticalResultsEntityManager();

            ResultEntity result = new ResultEntity();
            result.Message = _Message;
            if (_CreationTime == null)
                result.CreationTime = DateTime.Now;
            else
                result.CreationTime = _CreationTime.Value;
            result.Uuid = Guid.NewGuid();

            result.Sender = manager.GetUser(_Sender.UserName);
            result.Receiver = manager.GetUser(_Receiver.UserName);
            result.Level = manager.GetLevel(_Level.Name);

            result.EscalationTime = result.CreationTime + result.Level.EscalationTimespan;
            result.DueTime = result.CreationTime + result.Level.DueTimespan;

            if (result.SenderProxy != null)
            {
                result.SenderProxy = manager.GetUser(_SenderProxy.UserName);
            }

            _Entity = manager.CreateResultEntity(result);

            foreach (ResultContext context in _Context)
            {
                ContextTypeEntity contextTypeEntity = manager.GetContextType(context.ContextType.Name);
                ResultContextEntity resultEntity = manager.CreateResultContextEntity(_Entity, contextTypeEntity, context.JsonValue, context.XmlValue, context.PatientKey, context.ExamKey);
                _Entity.ResultContexts.Add(resultEntity);
            }

            ApplyEntity();

            return true;
        }