public Ping() { var connectionString = ConfigurationManager.AppSettings["UsersDalConnectionString"]; var storageAccountConnectionString = ConfigurationManager.AppSettings["StorageAccountConnectionString"]; this.usersDal = new UsersDal(connectionString, null, false, new PriorityEmailJobsQueue <PriorityEmailCargo>(storageAccountConnectionString)); }
private static void CreateUser(UserInfo userInfo, IUsersDal usersDal, Action <Guid> writer, SubscriptionType subscriptionType = SubscriptionType.Promotional) { try { // In manual creation context the user email isn't confirmed bool isEmailConfirmed = false; User user = usersDal.CreateOrGetUserByEmail(userInfo.UserEmail, isEmailConfirmed, userInfo.Source); if (!string.IsNullOrEmpty(userInfo.UserLocation)) { usersDal.CreateOrUpdateEmailSubscription(new EmailSubscription { IsActive = true, LocationId = userInfo.UserLocation, UserId = user.Id, SubscriptionType = subscriptionType }); } if (userInfo.UserPreferences.Any()) { usersDal.UpdateUserInfo(user.Id, new Users.Dal.DataModel.UserInfo { Preferences = new UserPreferences { Categories = userInfo.UserPreferences } }); } writer(user.Id); Log.Info("User Created. Email={0}, Id={1}, Location={2}, User Email Source {3}, Preferences Count={4}", userInfo.UserEmail, user.Id, userInfo.UserLocation, userInfo.Source, userInfo.UserPreferences.Count); } catch (Exception exception) { if (exception.InnerException.Message == "Cant update a suppressed user") { Trace.WriteLine(string.Format("Cannot create user {0} - Suppressed user", userInfo.UserEmail)); } } }
/// <summary> /// Initializes a new instance of the <see cref="EmailSubscriptionHostFactory" /> class. /// </summary> public EmailSubscriptionHostFactory() { try { string storageAccountConnectionString = this.GetMandatorySetting("StorageAccountConnectionString"); // User Dal string usersConnectionString = this.GetMandatorySetting("UsersDalConnectionString"); this.usersDal = new UsersDal(usersConnectionString, null, false, new PriorityEmailJobsQueue <PriorityEmailCargo>(storageAccountConnectionString)); // HCP commands queue int queueMaxRetries = int.Parse(this.GetMandatorySetting("QueueMaxRetriesNumber")); TimeSpan queueRetriesDeltaBackoff = TimeSpan.Parse(this.GetMandatorySetting("QueueRetriesDeltaBackoff")); this.hcpCommandsQueue = new HcpCommandsAzureQueue(storageAccountConnectionString, queueMaxRetries, queueRetriesDeltaBackoff); // Other settings this.mdmApplicationId = int.Parse(this.GetMandatorySetting("MdMApplicationId")); this.publicationDescription = this.GetMandatorySetting("PublicationDescription"); this.publicationId = this.GetMandatorySetting("PublicationId"); this.publicationName = this.GetMandatorySetting("PublicationName"); this.publicationOptinLink = this.GetMandatorySetting("PublicationOptinLink"); } catch (Exception e) { Log.Error(e, "Couldn't initialize email subscriptions host factory"); throw; } }
/// <summary> /// Pings the Users database. /// </summary> /// <returns> /// * True if the Users database could be pinged. /// * Else returns false. /// </returns> private static bool PingUsers() { // Ping Users by attempting to retrieve a User known not to exist. IUsersDal usersDal = PartnerFactory.UsersDal(CommerceServiceConfig.Instance); return(usersDal.GetUserByUserId(Guid.Empty) == null); }
/// <summary> /// Registers external services for commerce like MVC constructs, security providers and Analytics /// </summary> internal static void RegisterExternalServices() { // Register log. LogInitializer.CreateLogInstance(CommerceServiceConfig.Instance.LogVerbosity, CommerceServiceConfig.Instance.ForceEventLog, General.CommerceLogSource, CommerceServiceConfig.Instance); // Register MVC constructs. WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Register security providers. IUsersDal usersDal = PartnerFactory.UsersDal(CommerceServiceConfig.Instance); if (CommerceServiceConfig.Instance.EnableDebugSecurityProvider == true) { Security.Add("user_debug", new UserDebugSecurityProvider(usersDal)); } Security.Add("usertoken", new UserTokenSecurityProvider()); // Register Analytics Service Analytics.Initialize(CommerceServiceConfig.Instance); }
/// <summary> /// Initializes a new instance of the <see cref="SubscriptionLookupService"/> class. /// </summary> /// <param name="usersDal"> /// The users dal. /// </param> /// <param name="serviceSettings">the lookup service settings</param> public SubscriptionLookupService(IUsersDal usersDal, LookupServiceSettings serviceSettings) { Log.Info("Instantiating the Subscription Lookup Service"); if (serviceSettings == null) { throw new ArgumentNullException("serviceSettings"); } if (string.IsNullOrEmpty(serviceSettings.PublicationDescription) || string.IsNullOrEmpty(serviceSettings.PublicationId) || string.IsNullOrEmpty(serviceSettings.PublicationName) || string.IsNullOrEmpty(serviceSettings.PublicationOptinLink)) { throw new ArgumentException("one or more of the parameter properties have invalid value", "serviceSettings"); } this.usersDal = usersDal; this.serviceSettings = serviceSettings; _emailSubscribers = new List <string>(); Log.Info("Creating the Background worker to refresh the in memory email subscribers list every {0} minute(s) from db", RefreshIntervalInMinutes); Worker worker = new Worker(new RefreshWorkItem(this), 1000 * 60 * RefreshIntervalInMinutes); worker.StartWorker(); }
public FServer(ILogger log, FConfig config, IUsersDal usersDal = null) { var tcpAcceptor = TcpAcceptor.New(config, log, this); var users = usersDal ?? UsersDal.New(log, config); _log = log; _config = config; _tcpAcceptor = tcpAcceptor; _users = users; }
/// <summary> /// Initializes a new instance of the <see cref="ConfirmController"/> class. /// </summary> /// <param name="usersDal"> /// The users dal. /// </param> /// <param name="entityConfirmationSettings"> /// The entity confirmation settings. /// </param> /// <exception cref="ArgumentNullException"> entityConfirmationSettings is null /// </exception> public ConfirmController(IUsersDal usersDal, EntityConfirmationSettings entityConfirmationSettings) { if (entityConfirmationSettings == null) { throw new ArgumentNullException("entityConfirmationSettings"); } this._bingOffersBaseUri = entityConfirmationSettings.BingOffersBaseUri; this._usersDal = usersDal; }
/// <summary> /// Initializes a new instance of the <see cref="LookupServiceInstanceProvider"/> class. /// </summary> /// <param name="usersDal"> /// The users dal. /// </param> /// <param name="lookupServiceSettings"> /// The lookup service settings. /// </param> public LookupServiceInstanceProvider(IUsersDal usersDal, LookupServiceSettings lookupServiceSettings) { if (usersDal == null) { throw new ArgumentNullException("usersDal"); } if (lookupServiceSettings == null) { throw new ArgumentNullException("lookupServiceSettings"); } this.usersDal = usersDal; this.lookupServiceSettings = lookupServiceSettings; }
/// <summary> /// Registers external services for commerce like MVC constructs, security providers and Analytics /// </summary> internal static void RegisterExternalServices() { // Use only for debugging // TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = true; TelemetryConfiguration.Active.InstrumentationKey = CloudConfigurationManager.GetSetting("APPINSIGHTS_INSTRUMENTATIONKEY"); // Register log. LogInitializer.CreateLogInstance(CommerceServiceConfig.Instance.LogVerbosity, CommerceServiceConfig.Instance.ForceEventLog, General.CommerceLogSource, CommerceServiceConfig.Instance); Log.Info("Started Commerce MBI service."); // Register MVC constructs. WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); // Bing FrontDoor and user debug security providers. IUsersDal usersDal = PartnerFactory.UsersDal(CommerceServiceConfig.Instance); if (CommerceServiceConfig.Instance.EnableDebugSecurityProvider == true) { Security.Add("user_debug", new UserDebugSecurityProvider(usersDal)); } Security.Add("lomo", new LomoSecurityProvider(usersDal)); // Register the mutual SSL security provider. Security.Add(MutualSslSecurityProvider.Name, new MutualSslSecurityProvider()); // Register the Simple Web Token security provider. string environment = string.Concat("commerce-", CommerceServiceConfig.Instance.Environment); string resourceTemplate = string.Concat(string.Format("https://{0}.TODO_INSERT_YOUR_DOMAIN_HERE/api/commerce/service/", environment), "{0}"); Security.Add(SimpleWebTokenSecurityProvider.Name, new SimpleWebTokenSecurityProvider(environment, resourceTemplate, CommerceServiceConfig.Instance.SimpleWebTokenKey)); // Amex payment authorization SWT security provider Security.Add("Bearer", new SimpleWebTokenSecurityProvider(environment, string.Concat(string.Format("https://{0}.TODO_INSERT_YOUR_DOMAIN_HERE/api/commerce/amex/", environment), "{0}"), CommerceServiceConfig.Instance.SimpleWebTokenKey)); // Register Analytics Service Analytics.Initialize(CommerceServiceConfig.Instance); }
/// <summary> /// Initializes a new instance of the <see cref="LookupServiceHost"/> class. /// </summary> /// <param name="usersDal"> /// The users dal. /// </param> /// <param name="lookupServiceSettings"> /// The lookup service settings. /// </param> /// <param name="serviceType"> /// The service type. /// </param> /// <param name="baseAddresses"> /// The base addresses. /// </param> public LookupServiceHost(IUsersDal usersDal, LookupServiceSettings lookupServiceSettings, Type serviceType, params Uri[] baseAddresses) : base(serviceType, baseAddresses) { if (usersDal == null) { throw new ArgumentNullException("usersDal"); } if (lookupServiceSettings == null) { throw new ArgumentNullException("lookupServiceSettings"); } foreach (ContractDescription cd in this.ImplementedContracts.Values) { cd.Behaviors.Add(new LookupServiceInstanceProvider(usersDal, lookupServiceSettings)); } this.Description.Behaviors.Find <ServiceBehaviorAttribute>().InstanceContextMode = InstanceContextMode.Single; }
/// <summary> /// Populate Authentication Status and email verification/confirmation link for a given user. /// - If the email is unconfirmed, auth status: UnConfirmedEmail /// - If email is confirmed, but MsId not populated, auth status : UnLinkedEmail /// - Otherwise we leave it as default: Null /// </summary> /// <param name="user"> /// User object from Dal /// </param> /// <param name="dal"> /// Instance of Users Dal /// </param> /// <param name="environmentType"> /// Environment Type /// </param> public void PopulateAuthStatusAndEmailLink(User user, IUsersDal dal, EnvironmentType environmentType) { if (user != null) { if (user.IsEmailConfirmed) { if (string.IsNullOrWhiteSpace(user.MsId)) { UnauthenticatedUserStatus = UnlinkedEmail; AccountLinkingUri = LinkingOrVerificationUrl(EntityType.AccountLink, user, dal, environmentType); } else { UnauthenticatedUserStatus = null; } } else { UnauthenticatedUserStatus = UnconfirmedEmail; EmailVerificationUri = LinkingOrVerificationUrl(EntityType.UnAuthenticatedEmailAddress, user, dal, environmentType); } } }
public IsUserExistService(IUsersDal dal) { _dal = dal; }
public AuthManager(IUsersDal mongoUserDal, IUsersDalNeo4j neo4jUserDal) { this._mongoUserDal = mongoUserDal; this._neo4jUserDal = neo4jUserDal; }
/// <summary> /// Initializes a new instance of the <see cref="ConfirmApiController"/> class. /// </summary> /// <param name="userDal"> /// The user dal. /// </param> /// <param name="confirmationJobsQueue">the confirmation jobs confirmationJobsQueue</param> public ConfirmApiController(IUsersDal userDal, IPriorityEmailJobsQueue <PriorityEmailCargo> confirmationJobsQueue) { this.userDal = userDal; this.confirmationJobsQueue = confirmationJobsQueue; }
/// <summary> /// Initializes a new instance of the <see cref="SubscriptionsController"/> class. /// </summary> /// <param name="usersDal"> /// The users dal. /// </param> public SubscriptionsController(IUsersDal usersDal) { this.usersDal = usersDal; }
public UserManager(IUsersDal users, ILogsService log, ITokenHelper tokenHelper) { _users = users; _log = log; _tokenHelper = tokenHelper; }
public LoginService(IUsersDal dal) { _dal = dal; }
private static void CreateUsers(string filePath, string outputFilePath, string emailSource, IUsersDal usersDal) { string[] lines = File.ReadAllLines(filePath); List <UserInfo> usersInfo = new List <UserInfo>(); foreach (string line in lines) { string[] lineParts = line.Split(','); UserInfo userInfo = new UserInfo { UserEmail = lineParts[0] }; if (lineParts.Length >= 2) { userInfo.UserLocation = string.Format("us:postal:{0}", lineParts[1].Trim()); } List <Guid> categories = new List <Guid>(); for (int i = 2; i < lineParts.Length; i++) { string cat = lineParts[i]; if (!string.IsNullOrEmpty(cat)) { Guid catGuid = GetCategoryGuid(cat.Trim().ToLowerInvariant()); categories.Add(catGuid); } } userInfo.UserPreferences = categories; userInfo.Source = emailSource; usersInfo.Add(userInfo); } using (TextWriter tx = new StreamWriter(outputFilePath)) { foreach (UserInfo userInfo in usersInfo) { CreateUser(userInfo, usersDal, userId => tx.WriteLine("{0}\t{1}\t{2}", userInfo.UserEmail, userInfo.UserLocation, userId)); } } }
/// <summary> /// Initializes a new instance of the <see cref="LomoSecurityProvider"/> class. /// </summary> /// <param name="usersDal"> /// The users dal. /// </param> /// <param name="saveUserName"> store user name, when true </param> /// <param name="bypassTokenValidation"> hook for test environment, when true </param> public LomoSecurityProvider(IUsersDal usersDal, bool saveUserName = false, bool bypassTokenValidation = false) { this.usersDal = usersDal; this.saveUserName = saveUserName; }
/// <summary> /// Initializes a new instance of the <see cref="UserDebugSecurityProvider"/> class. /// </summary> /// <param name="usersDal"> /// The users dal. /// </param> public UserDebugSecurityProvider(IUsersDal usersDal) { this.usersDal = usersDal; }
public LoginController(IUsersDal dal, ILogger <LoginController> logger) { this._dal = dal; this._logger = logger; }
/// <summary> /// Places the User object representing the person making this request to the context. /// </summary> /// <returns> /// The ResultCode corresponding to the result of the operation. /// </returns> /// <remarks> /// If flagged to do so, a user account will be created and associated with the specified e-mail address, if the e-mail /// address has not already been used. /// </remarks> private ResultCode PlaceUserInContext() { ResultCode result = ResultCode.Success; bool createUnauthenticatedAccount = false; if (Context[Key.CreateUnauthenticatedAccount] != null) { createUnauthenticatedAccount = (bool)Context[Key.CreateUnauthenticatedAccount]; } if (createUnauthenticatedAccount == true) { string emailAddress = Context[Key.EmailAddress] as string; if (String.IsNullOrWhiteSpace(emailAddress) == false) { try { // Ensure the e-mail address may be valid. MailAddress mailAddress = new MailAddress(emailAddress); // Attempt to add a user to User Services via Users Dal and obtain its authentication vector. IUsersDal usersDal = PartnerFactory.UsersDal(Context.Config); Users.Dal.DataModel.User fullUser = usersDal.CreateUnauthenticatedUser(mailAddress.Address, (string)Context[Key.ReferrerId], (string)Context[Key.UserLocation]); UnauthenticatedAddCardResponse response = (UnauthenticatedAddCardResponse)Context[Key.Response]; if (String.IsNullOrWhiteSpace(fullUser.MsId) == true) { response.AuthenticationVector = AuthenticationVector.Email.ToString(); } else if (fullUser.MsId.StartsWith("FB-", StringComparison.OrdinalIgnoreCase) == true) { response.AuthenticationVector = AuthenticationVector.Facebook.ToString(); } else { response.AuthenticationVector = AuthenticationVector.MicrosoftAccount.ToString(); } Guid userId = fullUser.Id; Context[Key.GlobalUserId] = userId; // If the user returned by User Services has not already been registered in the Commerce system, register a new Commerce user. User user = SharedUserLogic.RetrieveUser(); if (user == null) { user = new User(userId, Guid.NewGuid()); Context[Key.User] = user; result = SharedUserLogic.AddUser(); if (result == ResultCode.Created) { Analytics.AddRegisterUserEvent(user.GlobalId, user.AnalyticsEventId, Guid.Empty, Context[Key.ReferrerId] as string); result = ResultCode.Success; } } else { Context[Key.User] = user; } // If the user was added or retrieved successfully, proceed. if (result == ResultCode.Success) { // If the user has not already signed up officially with Bing Offers, proceed. if (response.AuthenticationVector == AuthenticationVector.Email.ToString()) { // If the user has not already added a card, proceed. SharedCardLogic sharedCardLogic = new SharedCardLogic(Context, CommerceOperationsFactory.CardOperations(Context)); if (sharedCardLogic.RetrieveUserCards().Count() == 0) { response.ActivationToken = fullUser.ActivationToken; } else { result = ResultCode.UnauthenticatedUserAlreadyExists; } } else { result = ResultCode.UserAlreadyExists; } } } catch (FormatException) { result = ResultCode.InvalidParameter; } } else { result = ResultCode.ParameterCannotBeNull; } } else { Context[Key.User] = SharedUserLogic.RetrieveUser(); } return(result); }
/// <summary> /// Concludes execution of the Add card call after previous work has been completed. /// </summary> /// <param name="resultCode"> /// The ResultCode to set within the call response. /// </param> /// <exception cref="ArgumentNullException"> /// Parameter context cannot be null. /// </exception> public void Conclude(ResultCode resultCode) { try { Context.Log.Verbose("ResultCode when Conclude process begins: {0}.", resultCode); // If process succeeded, update internal data storage. AddCardResponse response = (AddCardResponse)Context[Key.Response]; if (resultCode == ResultCode.Created) { // Add the card. resultCode = AddCard(); if (resultCode == ResultCode.Created || resultCode == ResultCode.Success) { response.NewCardId = General.GuidFromInteger(((Card)Context[Key.Card]).Id); // If a new card was added, kick off confirmation process for unauthenticated users and add needed information to analytics. // TODO: AddCard() above returns ResultCode.Success. So the code below will not execute. Is it ok? if (resultCode == ResultCode.Created) { // Kick off confirmation process for unauthenticated users. bool createUnauthenticatedAccount = false; if (Context[Key.CreateUnauthenticatedAccount] != null) { createUnauthenticatedAccount = (bool)Context[Key.CreateUnauthenticatedAccount]; } if (createUnauthenticatedAccount == true) { IUsersDal usersDal = PartnerFactory.UsersDal(Context.Config); Task.Run(() => usersDal.CompleteUnauthenticatedUserSetUp((Guid)Context[Key.GlobalUserId])); } // Add analytics info. Context.Log.Verbose("Adding new card to analytics."); User user = (User)Context[Key.User]; Analytics.AddAddCardEvent(user.GlobalId, user.AnalyticsEventId, Guid.Empty, Context[Key.ReferrerId] as string); } // Queue deal claiming if set to do so. bool queueDealClaiming = false; if (Context[Key.QueueJob] != null) { queueDealClaiming = (bool)Context[Key.QueueJob]; } // Linking is only for First Data, but by the time execution reaches this part of the code, the card may need to be linked to CLO offers or // Burn offers, or both, but definitely at least one of them. Therefore, a job has to be scheduled to cover the relevant combination of CLO // and Burn offers. That Earn offers are not registered with First Data doesn't change this-- the filtering will have to occur as part of the job. if (queueDealClaiming == true) { QueueClaimingDeals(response); resultCode = ResultCode.JobQueued; } } } response.ResultSummary.SetResultCode(resultCode); RestResponder.BuildAsynchronousResponse(Context); } catch (Exception ex) { RestResponder.BuildAsynchronousResponse(Context, ex); } }
public UsersService(IUsersDal usersDal) { _IUsersDal = usersDal; }
/// <summary> /// Initializes a new instance of the <see cref="HomeController"/> class. /// </summary> /// <param name="usersDal"> /// The users dal. /// </param> public HomeController(IUsersDal usersDal) { this._usersDal = usersDal; }
public UsersManager(IUsersDal usersDal) { _usersDal = usersDal; }
public LogoutService(IUsersDal dal) { _dal = dal; }
public UserManager(IUsersDal mongoUserDal, IUsersDalNeo4j neo4jUserDal, IUserDalCassandra cassandraUserDal) { this._mongoUserDal = mongoUserDal; this._neo4jUserDal = neo4jUserDal; this._cassandraUserDal = cassandraUserDal; }
public GetAllUsersService(IUsersDal dal) { _dal = dal; }