protected List <Recipient> LoadRecipients(NotificationType notificationType, Customer customer, bool dsrDSMOnly = false) { if (customer == null) { return(new List <Recipient>()); } UserProfileReturn users = GetUsers(customer, dsrDSMOnly); if (users.UserProfiles.Count == 0) { return(new List <Recipient>()); } List <UserMessagingPreference> userDefaultMessagingPreferences, customerMessagingPreferences, ump; GatherUserMessagingPreferences(notificationType, customer, users, out userDefaultMessagingPreferences, out customerMessagingPreferences, out ump); string prefs = string.Empty; foreach (var u in ump) { prefs += u.Channel + u.UserId.ToString("B") + u.NotificationType + "; "; } _log.WriteInformationLog (String.Format( "notification prefs: {0}, profiles count: {1}, profiles: {2}, userDefaultMessagingPreferences: {3}, customerMessagingPreferences: {4}", prefs, users.UserProfiles.Count, JsonConvert.SerializeObject(users.UserProfiles.Select(p => new { UserId = p.UserId, EmailAddress = p.EmailAddress }).ToList()), userDefaultMessagingPreferences, customerMessagingPreferences)); List <Recipient> recipients = new List <Recipient>(); GetRecipientsFromUsers(customer, users, userDefaultMessagingPreferences, customerMessagingPreferences, recipients); Dictionary <string, Recipient> dict = new Dictionary <string, Recipient>(); foreach (Recipient rec in recipients) { string dupkey = rec.UserId + "_" + rec.CustomerNumber + "_" + rec.Channel + "_" + rec.ProviderEndpoint; if (dict.Keys.Contains(dupkey, StringComparer.CurrentCultureIgnoreCase) == false) { dict.Add(dupkey, rec); } } return(dict.Values.ToList()); }
public ProductReturn GetProductsWithPrice(string customerNumber, ProductLine[] products, DateTime effDate, bool getAllFields) { if (header == null) { header = LoadHeader(unknownHeaders[0]); } ProductReturn retVal = new ProductReturn(); IUserProfileLogic profileLogic = _scope.GetService(typeof(IUserProfileLogic)) as IUserProfileLogic; UserProfileReturn profileLogicReturn = profileLogic.GetUserProfile(header.UserName, false); if (profileLogicReturn.UserProfiles.Count > 0) { UserProfile profile = profileLogicReturn.UserProfiles[0]; PagedResults <Customer> customers = profileLogic.CustomerSearch(profile, customerNumber, new Core.Models.Paging.PagingModel(), string.Empty, CustomerSearchType.Customer); if (customers.TotalResults > 0) { retVal.Products.AddRange(GetItemPricing(customers.Results[0].CustomerBranch, customerNumber, products, effDate)); } } return(retVal); }
private UserProfileReturn GetUsers(Customer customer, bool dsrDSMOnly) { UserProfileReturn users = new UserProfileReturn(); if (dsrDSMOnly) { //Only load DSRs and DSMs for the customer //Load DSRs var dsr = _dsrLogic.GetDsr(customer.CustomerBranch, customer.DsrNumber); if (dsr != null && dsr.DsrNumber != "000" && !string.IsNullOrEmpty(dsr.EmailAddress)) { users = (userProfileLogic.GetUserProfile(dsr.EmailAddress, createBekProfile: false)); } //Load DSM List <UserProfile> customerUsers = userProfileLogic.GetInternalUsersWithAccessToCustomer(customer.CustomerNumber, customer.CustomerBranch); if (customerUsers == null || customerUsers.Count == 0) { // no internal users found with access to the customer log.WriteWarningLog(string.Format("Could not find any internal users with access to {0}-{1}", customer.CustomerBranch, customer.CustomerNumber)); } else { UserProfile dsm = customerUsers.Where(x => x.IsDSM && !string.IsNullOrEmpty(x.DSMNumber) && x.DSMNumber == customer.DsmNumber) .FirstOrDefault(); if (dsm != null) { users.UserProfiles.Add(dsm); } } } else { users = userProfileLogic.GetUsers(new UserFilterModel() { CustomerId = customer.CustomerId }); users.UserProfiles.AddRange(userProfileLogic.GetInternalUsersWithAccessToCustomer(customer.CustomerNumber, customer.CustomerBranch)); //Retreive any internal users that have access to this customer } // make sure that we return good data in the users list if (users == null || users.UserProfiles == null) { users = new UserProfileReturn(); } else { users.UserProfiles.RemoveAll(u => u == null || u.UserId == null); } return(users); }
private UserProfileReturn GetAllUsers(Customer customer) { UserProfileReturn users = _userProfileLogic.GetUsers(new UserFilterModel() { CustomerId = customer.CustomerId }); users.UserProfiles.AddRange(_userProfileLogic.GetInternalUsersWithAccessToCustomer(customer.CustomerNumber, customer.CustomerBranch)); //Retreive any internal users that have access to this customer return(users); }
private UserProfileReturn GetDSRs(Customer customer, UserProfileReturn users) { var dsr = _dsrLogic.GetDsr(customer.CustomerBranch, customer.DsrNumber); if (dsr != null && dsr.DsrNumber != "000" && !string.IsNullOrEmpty(dsr.EmailAddress)) { users = (_userProfileLogic.GetUserProfile(dsr.EmailAddress, createBekProfile: false)); } return(users); }
/// <summary> /// handles the authentication of the user and creates the authentication token /// </summary> /// <returns>nothing</returns> /// <remarks> /// jwames - 8/12/2014 - original code /// </remarks> public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); if (!ValidateApiKey(context)) { return; } string errMsg = null; // determine if we are authenticating an internal or external user if (ProfileHelper.IsInternalAddress(context.UserName)) { IUserDomainRepository ADRepo = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IUserDomainRepository)) as IUserDomainRepository; bool success = await Task.Run <bool>(() => ADRepo.AuthenticateUser(context.UserName, context.Password, out errMsg)); if (!success) { context.SetError("invalid_grant", errMsg); return; } } else { ICustomerDomainRepository ADRepo = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(ICustomerDomainRepository)) as ICustomerDomainRepository; AuthenticationModel authentication = await Task.Run <AuthenticationModel>(() => ADRepo.AuthenticateUser(context.UserName, context.Password)); if (!authentication.Status.Equals(AuthenticationStatus.Successful) && !authentication.Status.Equals(AuthenticationStatus.PasswordExpired)) { context.SetError("invalid_grant", authentication.Message); return; } } IUserProfileLogic _profileLogic = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IUserProfileLogic)) as IUserProfileLogic; UserProfileReturn userReturn = await Task.Run <UserProfileReturn>(() => _profileLogic.GetUserProfile(context.UserName)); if (userReturn.UserProfiles.Count == 0) { context.SetError("invalid_grant", "User profile does not exist in Commerce Server"); } else { _profileLogic.SetUserProfileLastLogin(userReturn.UserProfiles[0].UserId); var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); identity.AddClaim(new Claim("name", context.UserName)); identity.AddClaim(new Claim("role", userReturn.UserProfiles[0].RoleName)); context.Validated(identity); } }
private UserProfileReturn GetOnlyDSRsDSMs(Customer customer, UserProfileReturn users) { //Only load DSRs and DSMs for the customer //Load DSRs users = GetDSRs(customer, users); //Load DSM List <UserProfile> customerUsers = GetDSMs(customer); GatherDSRsDSMs(customer, users, customerUsers); return(users); }
/// <summary> /// Initialize for BaseIntegrationsController /// </summary> /// <param name="controllerContext"></param> protected override void Initialize(System.Web.Http.Controllers.HttpControllerContext controllerContext) { try { base.Initialize(controllerContext); var headers = controllerContext.Request.Headers; if (headers.Contains("username")) { var email = headers.GetValues("username").First(); UserProfileReturn users = _profileLogic.GetUserProfile(email); SsoUser = users.UserProfiles[0]; if (headers.Contains("userSelectedContext")) { this.SelectedUserContext = JsonConvert.DeserializeObject <UserSelectedContext> (headers.GetValues("userSelectedContext").FirstOrDefault().ToString()); } } } catch (Exception ex) { string sEvent = "BEK Exception - BaseIntegrationsController:Initialize - " + ex.Message + ": " + ex.StackTrace; try { IEventLogRepository eventLogRepository = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IEventLogRepository)) as IEventLogRepository; eventLogRepository.WriteErrorLog("Unhandled API Exception", ex); } catch (Exception) { string sSource = "BEK_Shop"; string sLog = "Application"; if (!EventLog.SourceExists(sSource)) { EventLog.CreateEventSource(sSource, sLog); } EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning, 234); } throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("An unhandled exception has occured") }); } }
/// <summary> /// main method for handling requests send to this handler /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { // get data string xml = new StreamReader(context.Request.InputStream).ReadToEnd(); XDocument doc = XDocument.Load(new StringReader(xml)); XNamespace xns = XNamespace.Get("http://schemas.xmlsoap.org/soap/envelope/"); AuthHeader header = GetSoapHeader(doc.Descendants(xns + "Header").First().FirstNode); PricingRequest body = GetSoapBody(doc.Descendants(xns + "Body").First().FirstNode); // process pricing ProductReturn returnedPrices = new ProductReturn(); IUserProfileLogic profileLogic = _scope.GetService(typeof(IUserProfileLogic)) as IUserProfileLogic; UserProfileReturn profileLogicReturn = profileLogic.GetUserProfile(header.UserName, false); if (profileLogicReturn.UserProfiles.Count > 0) { UserProfile profile = profileLogicReturn.UserProfiles[0]; PagedResults <Customer> customers = profileLogic.CustomerSearch(profile, body.customerNumber, new Core.Models.Paging.PagingModel(), string.Empty, CustomerSearchType.Customer); if (customers.TotalResults > 0) { returnedPrices.Products.AddRange(GetItemPricing(customers.Results[0].CustomerBranch, body.customerNumber, body.products, ConvertEffectiveDate(body.effDate))); } } // return results SoapEnvelope soap = new SoapEnvelope(); soap.Body.Response.Results = GetProductString(returnedPrices); XmlSerializer serializer = new XmlSerializer(soap.GetType()); XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(); namespaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance"); namespaces.Add("xsd", "http://www.w3.org/2001/XMLSchema"); namespaces.Add("soap", "http://schemas.xmlsoap.org/soap/envelope/"); serializer.Serialize(context.Response.OutputStream, soap, namespaces); context.Response.ContentType = "text/xml"; }
private UserProfileReturn GetUsers(Customer customer, bool dsrDSMOnly) { UserProfileReturn users = new UserProfileReturn(); users = GetSpecifiedUsers(customer, dsrDSMOnly, users); // make sure that we return good data in the users list if (users == null || users.UserProfiles == null) { users = new UserProfileReturn(); } else { users.UserProfiles.RemoveAll(u => u == null || u.UserId == null); } return(users); }
private void GetRecipientsFromUsers(Customer customer, UserProfileReturn users, List <UserMessagingPreference> userDefaultMessagingPreferences, List <UserMessagingPreference> customerMessagingPreferences, List <Recipient> recipients) { foreach (UserProfile userProfile in users.UserProfiles) { if (userDefaultMessagingPreferences != null) { // first, check for customer specific prefs List <UserMessagingPreference> prefsToUse = customerMessagingPreferences.Where( p => p.UserId == userProfile.UserId).ToList(); // check for customer specific prefs first if (prefsToUse == null || prefsToUse.Count() == 0) // then check for defaults { prefsToUse = userDefaultMessagingPreferences.Where(p => p.UserId == userProfile.UserId).ToList(); } AddSpecificRecipients(customer, recipients, userProfile, prefsToUse); } } }
private void GatherDSRsDSMs(Customer customer, UserProfileReturn users, List <UserProfile> customerUsers) { if (customerUsers == null || customerUsers.Count == 0) { // no internal users found with access to the customer _log.WriteWarningLog(string.Format("Could not find any internal users with access to {0}-{1}", customer.CustomerBranch, customer.CustomerNumber)); } else { UserProfile dsm = customerUsers.Where(x => x.IsDSM && !string.IsNullOrEmpty(x.DSMNumber) && x.DSMNumber == customer.DsmNumber) .FirstOrDefault(); if (dsm != null) { users.UserProfiles.Add(dsm); } } }
private void GatherUserMessagingPreferences(NotificationType notificationType, Customer customer, UserProfileReturn users, out List <UserMessagingPreference> userDefaultMessagingPreferences, out List <UserMessagingPreference> customerMessagingPreferences, out List <UserMessagingPreference> ump) { GetUserMessagingPreferences (notificationType, customer, users, out userDefaultMessagingPreferences, out customerMessagingPreferences, out ump); ump.AddRange(userDefaultMessagingPreferences); ump.AddRange(customerMessagingPreferences); }
private UserProfileReturn GetSpecifiedUsers(Customer customer, bool dsrDSMOnly, UserProfileReturn users) { if (dsrDSMOnly) { users = GetOnlyDSRsDSMs(customer, users); } else { users = GetAllUsers(customer); } return(users); }
protected List <Recipient> LoadRecipients(NotificationType notificationType, Customer customer, bool dsrDSMOnly = false) { if (customer == null) { return(new List <Recipient>()); } UserProfileReturn users = GetUsers(customer, dsrDSMOnly); if (users.UserProfiles.Count == 0) { return(new List <Recipient>()); } List <UserMessagingPreference> userDefaultMessagingPreferences = // list of each user's default prefs userMessagingPreferenceRepository.ReadByUserIdsAndNotificationType(users.UserProfiles.Select(u => u.UserId), notificationType, true).ToList(); List <UserMessagingPreference> customerMessagingPreferences = // list of customer's user specific pref userMessagingPreferenceRepository.ReadByCustomerAndNotificationType(customer.CustomerNumber, customer.CustomerBranch, notificationType).ToList(); List <UserMessagingPreference> ump = new List <UserMessagingPreference>(); ump.AddRange(userDefaultMessagingPreferences); ump.AddRange(customerMessagingPreferences); string prefs = string.Empty; foreach (var u in ump) { prefs += u.Channel + u.UserId.ToString("B") + u.NotificationType + "; "; } log.WriteInformationLog (String.Format( "notification prefs: {0}, profiles count: {1}, profiles: {2}, userDefaultMessagingPreferences: {3}, customerMessagingPreferences: {4}", prefs, users.UserProfiles.Count, JsonConvert.SerializeObject(users.UserProfiles.Select(p => new { UserId = p.UserId, EmailAddress = p.EmailAddress }).ToList()), userDefaultMessagingPreferences, customerMessagingPreferences)); List <Recipient> recipients = new List <Recipient>(); foreach (UserProfile userProfile in users.UserProfiles) { if (userDefaultMessagingPreferences != null) { // first, check for customer specific prefs List <UserMessagingPreference> prefsToUse = customerMessagingPreferences.Where( p => p.UserId == userProfile.UserId).ToList(); // check for customer specific prefs first if (prefsToUse == null || prefsToUse.Count() == 0) // then check for defaults { prefsToUse = userDefaultMessagingPreferences.Where(p => p.UserId == userProfile.UserId).ToList(); } foreach (var pref in prefsToUse) { if (pref.Channel == Channel.Email) { recipients.Add(new Recipient() { ProviderEndpoint = userProfile.EmailAddress, Channel = Channel.Email, UserId = userProfile.UserId, UserEmail = userProfile.EmailAddress, CustomerNumber = customer.CustomerNumber }); } else if (pref.Channel == Channel.MobilePush) { // lookup any and all mobile devices foreach (var device in userPushNotificationDeviceRepository.ReadUserDevices(userProfile.UserId)) { if (device.Enabled != false) { recipients.Add(new Recipient() { ProviderEndpoint = device.ProviderEndpointId, DeviceOS = device.DeviceOS, Channel = Channel.MobilePush, UserId = userProfile.UserId, UserEmail = userProfile.EmailAddress, DeviceId = device.DeviceId, CustomerNumber = customer.CustomerNumber }); } } } else if (pref.Channel == Channel.Web) { recipients.Add(new Recipient() { UserId = userProfile.UserId, CustomerNumber = customer.CustomerNumber, Channel = Channel.Web, UserEmail = userProfile.EmailAddress }); } } } } Dictionary <string, Recipient> dict = new Dictionary <string, Recipient>(); foreach (Recipient rec in recipients) { string dupkey = rec.UserId + "_" + rec.CustomerNumber + "_" + rec.Channel + "_" + rec.ProviderEndpoint; if (dict.Keys.Contains(dupkey, StringComparer.CurrentCultureIgnoreCase) == false) { dict.Add(dupkey, rec); } } return(dict.Values.ToList()); }
/// <summary> /// Initialize for BaseController /// </summary> /// <param name="controllerContext"></param> protected override void Initialize(System.Web.Http.Controllers.HttpControllerContext controllerContext) { try { base.Initialize(controllerContext); if (controllerContext.RequestContext.Principal.Identity.IsAuthenticated && string.Compare(controllerContext.RequestContext.Principal.Identity.AuthenticationType, "bearer", true) == 0) { UserProfileReturn retVal = _profileLogic.GetUserProfile(((ClaimsIdentity)this.ControllerContext.RequestContext.Principal.Identity).FindFirst("name").Value); _profileLogic.SetUserProfileLastAccess(retVal.UserProfiles[0].UserId); _user = retVal.UserProfiles[0]; _user.IsAuthenticated = true; NewRelic.Api.Agent.NewRelic.AddCustomParameter("AuthenticatedUserName", _user.UserName); NewRelic.Api.Agent.NewRelic.AddCustomParameter("AuthenticatedUserRoleName", _user.RoleName); NewRelic.Api.Agent.NewRelic.AddCustomParameter("HTTP Verb", System.Web.HttpContext.Current.Request.HttpMethod.ToUpper()); GenericPrincipal genPrincipal = new GenericPrincipal(_user, new string[] { retVal.UserProfiles[0].RoleName }); controllerContext.RequestContext.Principal = genPrincipal; if (Request.Headers.Contains("userSelectedContext")) { this.SelectedUserContext = JsonConvert.DeserializeObject <UserSelectedContext>(Request.Headers.GetValues("userSelectedContext").FirstOrDefault().ToString()); if (!(_user.IsInternalUser || controllerContext.RequestContext.Principal.IsInRole(KeithLink.Svc.Core.Constants.ROLE_NAME_KBITADMIN)))//For now, don't verify internal users { //TODO: Need to update check now that customers are no longer included with the user profile //Verify that the authenticated user has access to this customer/branch bool isGuest = controllerContext.RequestContext.Principal.IsInRole(KeithLink.Svc.Core.Constants.ROLE_EXTERNAL_GUEST); bool isCustomerSelected = (!string.IsNullOrEmpty(this.SelectedUserContext.CustomerId)); var customer = _profileLogic.GetCustomerForUser(this.SelectedUserContext.CustomerId, this.SelectedUserContext.BranchId, _user.UserId); bool userHasAccessToCustomer = customer != null; if ((isGuest && isCustomerSelected) || (!isGuest && !userHasAccessToCustomer)) { throw new Exception(string.Format("Authenticated user does not have access to passed CustomerId/Branch ({0}/{1}). Requested URI {2}", this.SelectedUserContext.CustomerId, this.SelectedUserContext.BranchId, this.Request.RequestUri)); } } NewRelic.Api.Agent.NewRelic.AddCustomParameter("userSelectedContext", Request.Headers.GetValues("userSelectedContext").FirstOrDefault().ToString()); } if (Request.Content != null) { System.Threading.Tasks.Task <string> content = Request.Content.ReadAsStringAsync(); NewRelic.Api.Agent.NewRelic.AddCustomParameter("Request.Content", content.Result); } } else { _user = null; } } catch (Exception ex) { string sEvent = "BEK Exception - BaseController:Initialize - " + ex.Message + ": " + ex.StackTrace; try { IEventLogRepository eventLogRepository = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IEventLogRepository)) as IEventLogRepository; eventLogRepository.WriteErrorLog("Unhandled API Exception", ex); } catch (Exception) { string sSource = "BEK_Shop"; string sLog = "Application"; if (!EventLog.SourceExists(sSource)) { EventLog.CreateEventSource(sSource, sLog); } EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning, 234); } throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("An unhandled exception has occured") }); } }
private void GetUserMessagingPreferences(NotificationType notificationType, Customer customer, UserProfileReturn users, out List <UserMessagingPreference> userDefaultMessagingPreferences, out List <UserMessagingPreference> customerMessagingPreferences, out List <UserMessagingPreference> ump) { userDefaultMessagingPreferences = _userMessagingPreferenceRepository.ReadByUserIdsAndNotificationType(users.UserProfiles.Select(u => u.UserId), notificationType, true).ToList(); customerMessagingPreferences = _userMessagingPreferenceRepository.ReadByCustomerAndNotificationType(customer.CustomerNumber, customer.CustomerBranch, notificationType).ToList(); ump = new List <UserMessagingPreference>(); }