/// <summary> /// Makes attempt to finish failed autopilot operations. /// </summary> public void CheckErrorBuffer() { using (var unitOfWork = UnitOfWork.Create()) { var errors = unitOfWork.AutopilotErrorRepository.GetAll(); string info; if (errors.Count() == 0) { log.Info("Method: " + MethodBase.GetCurrentMethod().DeclaringType + " .No autopilot errors were found."); return; } foreach (var error in errors) { switch (error.OperationType) { case "Edit": string autopilot_contact_id = error.AutopilotContactId; CustomerModel model = ConvertJSONtoObject <CustomerModel>(error.RequestData); string userId = error.UserId; var result = UpdateContactDetails(autopilot_contact_id, model, userId).Result; break; case "Login": userId = error.UserId; autopilot_contact_id = error.AutopilotContactId; info = UpdateAutopilotContactLogin(autopilot_contact_id, userId).Result; break; case "Registration": userId = error.UserId; RegisterGeneralModel registermodel = ConvertJSONtoObject <RegisterGeneralModel>(error.RequestData); info = CreateAutopilotContact(registermodel, userId).Result; break; case "PolicyLoad": userId = error.UserId; autopilot_contact_id = error.AutopilotContactId; result = UpdateContactPolicyLoad(autopilot_contact_id, userId).Result; break; case "TriggerJourney": userId = error.UserId; string journeyName = error.RequestData; autopilot_contact_id = error.AutopilotContactId; result = TriggerUserToJourney(journeyName, autopilot_contact_id, userId).Result; break; default: break; } unitOfWork.AutopilotErrorRepository.Delete(error); } unitOfWork.Save(); } }
public void Execute(IJobExecutionContext context) { provider.CheckErrorBuffer(); JobDataMap datamap = context.JobDetail.JobDataMap; string operation = datamap.GetString("OperationType"); string info; try { switch (operation) { case "Edit": string autopilot_contact_id = datamap.GetString("autopilotContactId"); CustomerModel model = (CustomerModel)datamap["model"]; string userId = datamap.GetString("userId"); var result = provider.UpdateContactDetails(autopilot_contact_id, model, userId).Result; break; case "Login": autopilot_contact_id = datamap.GetString("autopilotContactId"); userId = datamap.GetString("userId"); info = provider.UpdateAutopilotContactLogin(autopilot_contact_id, userId).Result; break; case "Registration": userId = datamap.GetString("userId"); RegisterGeneralModel registermodel = (RegisterGeneralModel)datamap["registermodel"]; info = provider.CreateAutopilotContact(registermodel, userId).Result; break; case "PolicyLoad": userId = datamap.GetString("policyauthorId"); autopilot_contact_id = datamap.GetString("autopilotContactId"); result = provider.UpdateContactPolicyLoad(autopilot_contact_id, userId).Result; break; case "TriggerJourney": string journeyName = datamap.GetString("journeyName"); userId = datamap.GetString("userId"); autopilot_contact_id = datamap.GetString("autopilotContactId"); result = provider.TriggerUserToJourney(journeyName, autopilot_contact_id, userId).Result; break; default: break; } } catch (Exception ex) { log.Fatal(ex.Message, ex); } }
public async Task <IHttpActionResult> RegisterExternal(RegisterExternalModel model) { var verifiedAccessToken = new ParsedExternalAccessToken(); if (ModelState.IsValid) { var helper = OauthHelper.Create(); if (!string.IsNullOrEmpty(model.Provider) && !string.IsNullOrEmpty(model.ExternalAccessToken)) { verifiedAccessToken = await helper.VerifyExternalAccessToken(model.Provider, model.ExternalAccessToken); if (verifiedAccessToken == null) { return(this.JsonError(HttpStatusCode.BadRequest, 10, "Invalid Provider or External Access Token", ModelState)); } } var loginInfo = await SignInManager.AuthenticationManager.GetExternalLoginInfoAsync(); ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(loginInfo.ExternalIdentity as ClaimsIdentity); var registerGeneral = new RegisterGeneralModel() { UserName = model.UserName, Email = model.Email, //FirstName = externalLogin.UserName.Split(' ')[0], //First Name //LastName = externalLogin.UserName.Split(' ').LastOrDefault(), //Last Name ExternalAccessToken = model.ExternalAccessToken, Provider = model.Provider }; var regResult = await RegisterInternal(registerGeneral); if (regResult.HasError) { return(JsonError(regResult.HttpStatusCode, regResult.ServerErrorCode, regResult.ErrorMessage, regResult.ModelState)); } else { var result = new { userId = regResult.UserId }; return(Json(result)); } } else { return(JsonError(HttpStatusCode.BadRequest, 10, "Warning", ModelState)); } }
public async Task <IHttpActionResult> Register([FromBody] RegisterModel model) { if (model.Password != null) { //Validate password var validateResult = await ApplicationUserManager.GetPasswordValidator().ValidateAsync(model.Password); if (!validateResult.Succeeded) { foreach (var error in validateResult.Errors) { ModelState.AddModelError("password", error); } } } if (ModelState.IsValid) { var registerGeneral = new RegisterGeneralModel() { Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, ContactPhone = model.ContactPhone, Password = model.Password, }; var regResult = await RegisterInternal(registerGeneral); if (regResult.HasError) { return(JsonError(regResult.HttpStatusCode, regResult.ServerErrorCode, regResult.ErrorMessage, regResult.ModelState)); } else { var result = new { userId = regResult.UserId }; return(Json(result)); } } else { return(JsonError(HttpStatusCode.BadRequest, 10, "Warning", ModelState)); } }
/// <summary> /// Register User Internal /// </summary> /// <param name="model"></param> /// <returns></returns> internal async Task <RegisterUserResult> RegisterInternal(RegisterGeneralModel model) { var userResult = new RegisterUserResult(); using (IUnitOfWork unitOfWork = UnitOfWork.Create()) { var checkUserEmail = unitOfWork.UserRepository.GetAll().FirstOrDefault(a => a.Email == model.Email || a.UserName == model.Email); if (checkUserEmail != null) { userResult.AddError(HttpStatusCode.BadRequest, 10, "This email is already taken ***"); return(userResult); } unitOfWork.BeginTransaction(); //Create user record var user = new ApplicationUser { Id = Guid.NewGuid().ToString(), FirstName = model.FirstName ?? string.Empty, LastName = model.LastName ?? string.Empty, UserName = model.Email, Email = model.Email, //AvatarFileId = model.AvatarFileId, HasTempPassword = true, CreatedById = DbConstants.AdminUserId, CreatedDate = DateTime.Now }; if (!string.IsNullOrEmpty(model.UserName)) { var names = model.UserName.Split(' '); user.FirstName = names[0]; user.LastName = names.Length > 1 ? names[1] : ""; } if (!string.IsNullOrEmpty(model.Password)) { user.PasswordHash = new PasswordHasher().HashPassword(model.Password); } user.AutopilotTrack = true; user.SecurityStamp = Guid.NewGuid().ToString(); #region Need To redo { ISchedulerFactory factory = new StdSchedulerFactory(); IScheduler scheduler = factory.GetScheduler(); JobDataMap dataMap = new JobDataMap(); dataMap["registermodel"] = model; dataMap["userId"] = user.Id; dataMap["OperationType"] = "Registration"; var job = JobBuilder.Create <UpdateContactJob>() .WithIdentity("UpdateContactJob").UsingJobData(dataMap) .Build(); var jobKey = new JobKey("UpdateContactJob"); ITrigger trigger = TriggerBuilder.Create() .WithIdentity("trigger1") .StartAt(DateTime.Now) .ForJob(jobKey) .Build(); if (!scheduler.CheckExists(jobKey)) { scheduler.ScheduleJob(job, trigger); } scheduler.Start(); } #endregion unitOfWork.UserRepository.Insert(user); await unitOfWork.SaveAsync(); ApplicationUserRole userRole = new ApplicationUserRole(); userRole.RoleId = DataLayer.DbConstants.CustomerUserRole; userRole.UserId = user.Id; unitOfWork.UserRoleRepository.Insert(userRole); await unitOfWork.SaveAsync(); Address address = new Address(); address.CreatedById = user.Id; address.CreatedDate = DateTime.Now; unitOfWork.AddressRepository.Insert(address); await unitOfWork.SaveAsync(); CustomerDetails customer = new CustomerDetails(); customer.Id = Guid.NewGuid(); customer.CreatedById = user.Id; customer.CreatedDate = DateTime.Now; customer.UserId = user.Id; customer.ContactPhone = model.ContactPhone; customer.AddressId = address.Id; customer.ModifiedReason = "created"; unitOfWork.CustomerDetailsRepository.Insert(customer); await unitOfWork.SaveAsync(); if (!string.IsNullOrEmpty(model.Provider) && !string.IsNullOrEmpty(model.ExternalAccessToken)) { var loginInfo = await this.SignInManager.AuthenticationManager.GetExternalLoginInfoAsync(); ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(loginInfo.ExternalIdentity as ClaimsIdentity); ApplicationUserLogin userLogin = new ApplicationUserLogin(); userLogin.UserId = user.Id; userLogin.ProviderKey = loginInfo.Login.ProviderKey; userLogin.LoginProvider = loginInfo.Login.LoginProvider; unitOfWork.UserLoginRepository.Insert(userLogin); await unitOfWork.SaveAsync(); } unitOfWork.CommitTransaction(); if (model.Provider == null) { //Senf verification Email { string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = string.Format("{0}/#/confirm-email?userId={1}&code={2}", Url.Link("Default", new { controller = "account" }), user.Id, Uri.EscapeDataString(code)); await EmailNitificationHelper.Create().SendConfirmationEmail(user, UserManager, callbackUrl); } } userResult.UserId = user.Id; return(userResult); } }
public async Task <ActionResult> ExternalLoginCallback(string returnUrl = null) { var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return(RedirectToAction("Login")); } string redirectUri = null; using (IUnitOfWork unitOfWork = UnitOfWork.Create()) { var userId = unitOfWork.UserLoginRepository.GetAll().Where(a => a.ProviderKey == loginInfo.Login.ProviderKey && a.LoginProvider == loginInfo.Login.LoginProvider).Select(a => a.UserId).FirstOrDefault(); var user = unitOfWork.UserRepository.GetAll().FirstOrDefault(a => a.Id == userId); if (user != null) { if (user.LockedByAdmin) { var message = "Your account has been locked by admin."; redirectUri = string.Format("{0}/account/#/login?error={1}", Request.Url.GetLeftPart(UriPartial.Authority), message); return(Redirect(redirectUri)); } } // Sign in the user with this external login provider if the user already has a login var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false); switch (result) { case SignInStatus.Success: var customer = unitOfWork.CustomerDetailsRepository.GetAll().FirstOrDefault(a => a.UserId == userId); if (user.AutopilotTrack && !string.IsNullOrEmpty(user.AutopilotContactId)) { StartUpdatingAutopilot(customer.User.AutopilotContactId, customer.UserId); } redirectUri = string.Format("{0}/Dashboard/", Request.Url.GetLeftPart(UriPartial.Authority)); if (customer != null && customer.Status == Domain.DbModels.CustomerStatus.Pending) { redirectUri = string.Format("{0}/Dashboard/#/user/profile", Request.Url.GetLeftPart(UriPartial.Authority)); } return(Redirect(redirectUri)); case SignInStatus.Failure: default: ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(loginInfo.ExternalIdentity as ClaimsIdentity); var un = externalLogin.UserName.Split(' '); string firstName = un[0]; string lastName = un.Length > 1 ? un[1] : ""; if (externalLogin.LoginProvider == "Facebook") { var client = new FacebookClient(externalLogin.ExternalAccessToken); dynamic me = client.Get("me?fields=first_name,last_name,email,birthday"); firstName = me.first_name; lastName = me.last_name; externalLogin.Email = me.email; var d = me.birthday; } //Doubting approach if (string.IsNullOrWhiteSpace(externalLogin.Email)) { externalLogin.Email = string.Format("{0}_{1}@tempadvisr.email", externalLogin.ProviderKey, externalLogin.LoginProvider[0]); } if (string.IsNullOrWhiteSpace(externalLogin.Email)) { redirectUri = string.Format("{0}/account/#/register?external_access_token={1}&provider={2}&haslocalaccount={3}&external_user_name={4}&email={5}&firstName={6}&lastName={7}", Request.Url.GetLeftPart(UriPartial.Authority), externalLogin.ExternalAccessToken, externalLogin.LoginProvider, false, externalLogin.UserName, externalLogin.Email, externalLogin.UserName.Split(' ')[0], //First Name externalLogin.UserName.Split(' ').LastOrDefault()); //Last Name return(Redirect(redirectUri)); } else { //Register new user UserController userController = new UserController(this.UserManager, this.SignInManager); RegisterGeneralModel model = new RegisterGeneralModel(); model.Email = externalLogin.Email; model.FirstName = firstName; model.LastName = lastName; model.Provider = externalLogin.LoginProvider; model.ExternalAccessToken = externalLogin.ExternalAccessToken; var userRegisterResult = await userController.RegisterInternal(model); if (userRegisterResult.HasError) { redirectUri = string.Format("{0}/account/#/login?error={1}", Request.Url.GetLeftPart(UriPartial.Authority), userRegisterResult.ErrorMessage); return(Redirect(redirectUri)); } else { return(RedirectToAction("ExternalLoginCallback", "Account")); } } } } }
/// <summary> /// Starts on registration or external registration(G+,FB). Creates autopilot contact and associates it with created user. /// </summary> /// <param name="model">model of registration</param> /// <param name="userId">id of created user</param> /// <returns></returns> public async Task <string> CreateAutopilotContact(RegisterGeneralModel model, string userId) { var autopilotContact = new Contact(); autopilotContact.FirstName = model.FirstName; autopilotContact.LastName = model.LastName; autopilotContact.Email = model.Email; autopilotContact.LeadSource = "AdvisrApp"; autopilotContact.ListToAdd = ConfigurationManager.AppSettings["RegistrationList"]; autopilotContact.Custom = new Custom(); autopilotContact.Custom.PolicyLoadInProgress = false; autopilotContact.Custom.LastAppLogin = DateTime.Now; autopilotContact.Custom.PolicyCount = 0; autopilotContact.Custom.AppLoginCount = 0; autopilotContact.Custom.FirstPolicyLoad = false; autopilotAPIClient = AutopilotAPIClient.Create(); string autopilotcontact_id = ""; var addContactResult = await autopilotAPIClient.AddOrUpdateContact(new AutopilotContactToAdd() { Contact = autopilotContact }); using (var unitOfWork = UnitOfWork.Create()) { if (!addContactResult.HasError) { var user = unitOfWork.UserRepository.GetAll().FirstOrDefault(u => u.Id == userId); if (user != null) { autopilotcontact_id = addContactResult.Result.ContactId; user.AutopilotContactId = autopilotcontact_id; var getContactResult = await autopilotAPIClient.GetContact(autopilotcontact_id); if (!getContactResult.HasError) { user.AutopilotData = JsonConvert.SerializeObject(getContactResult); } unitOfWork.UserRepository.Edit(user); await unitOfWork.SaveAsync(); log.Info("Method: " + MethodBase.GetCurrentMethod().DeclaringType + " .Contact " + autopilotcontact_id + " has been created."); return(autopilotcontact_id); } } else { var autopilotError = new AutopilotErrorBuffer(); autopilotError.AutopilotContactId = ""; autopilotError.OperationType = "Registration"; autopilotError.RequestData = JsonConvert.SerializeObject(model); autopilotError.UserId = userId; unitOfWork.AutopilotErrorRepository.Insert(autopilotError); await unitOfWork.SaveAsync(); log.Error("Method: " + MethodBase.GetCurrentMethod().DeclaringType + " .Contact's " + autopilotcontact_id + " creation has been failed."); autopilotcontact_id = ""; } } return(string.Empty); }