/// <summary> /// Initializes the services of MS-WEBSS with the specified transport type, soap version and user authentication provided by the test case. /// </summary> /// <param name="transportType">The type of the connection</param> /// <param name="soapVersion">The soap version of the protocol message</param> /// <param name="userAuthentication">a user authenticated</param> /// <param name="serverRelativeUrl"> a Server related URL</param> public void InitializeService(TransportProtocol transportType, SoapProtocolVersion soapVersion, UserAuthentication userAuthentication, string serverRelativeUrl) { this.service = Proxy.CreateProxy<WebsSoap>(this.Site); this.service.SoapVersion = soapVersion; // select transport protocol switch (transportType) { case TransportProtocol.HTTP: this.service.Url = serverRelativeUrl; break; default: this.service.Url = serverRelativeUrl; // when request URL include HTTPS prefix, avoid closing base connection. // local client will accept all certificate after execute this function. Common.AcceptServerCertificate(); break; } this.service.Credentials = AdapterHelper.ConfigureCredential(userAuthentication); // Configure the service timeout. int soapTimeOut = Common.GetConfigurationPropertyValue<int>("ServiceTimeOut", this.Site); // 60000 means the configure SOAP Timeout is in minute. this.service.Timeout = soapTimeOut * 60000; }
public ActionResult LogOn(UserAuthentication value) { if (value == null) { throw new ArgumentNullException("value"); } value.Validate(); if (value.IsValid) { var user = this.UserService.GetBy(new UserEmailAddressSpecification(value.EmailAddress)); this.AuthenticationService.LogOn(user); ApplicationSession.Destroy(this.Session); var url = value.Redirect; if (base.Url.IsLocalUrl(url)) { return base.Redirect(url); } return base.RedirectToRoute(CommonRoutes.Index); } value.CopyToModel(ModelState); return base.View(Views.LogOn, value); }
public void Test_UserAuthentication_Validate() { var value = new UserAuthentication(); value.Validate(); Assert.AreEqual(2, value.Errors.Count, "Errors"); }
public ActionResult LogOn() { var value = new UserAuthentication { Redirect = Request["returnUrl"] }; return base.View(Views.LogOn, value); }
public Form2(Form1 form1, UserAuthentication userAuthentication, DeviceOptions deviceOptions) : base() { InitializeComponent(); Form1 = form1; UserAuthentication = userAuthentication; DeviceOptions = deviceOptions; btnCancel.Click += btnCancel_Click; btnPrevious.Click += btnPrevious_Click; btnPrevious.Enabled = true; btnNext.Click += btnNext_Click; txtPath.Text = Static.Constants.ApplicationDirectoryPath; SetText(label1, "The installer will install " + Static.ExecutingAssemblyAttributes.AssemblyProduct + " to the following folder.\nTo install in this folder, click \"Next\"." + " To install to a different folder, click \"Browse\"."); }
//---------------------------------------------------------------// //----------------------------------------------------------------------------------------------------------------------------------------------// private void Start() { if (instance == null) { instance = this; DontDestroyOnLoad(this.gameObject); } else { Destroy(this.gameObject); } FirebaseApp.DefaultInstance.SetEditorDatabaseUrl(databaseURL); auth = Firebase.Auth.FirebaseAuth.DefaultInstance; auth.StateChanged += AuthStateChanged; AuthStateChanged(this, null); LoadUser(); }
public void addActiveAuthToken(String token, String username) { connection.CreateTable <UserAuthentication>(); var activeConfig = getActiveConfiguration(); UserAuthentication auth = new UserAuthentication { Username = username, AuthToken = token, applicableConfigurationId = activeConfig.Id }; connection.Insert(auth); activeConfig.ActiveAuthId = auth.Id; connection.Update(activeConfig); }
public void AuthenticationAsync_invalidLogin() { DataShell resultHashPassword = new DataShell(); mockDbOperations .Setup(m => m.GetUserHashPasswordAsync(user.Login)) .Returns(Task.FromResult(resultHashPassword)); var service = new UserAuthentication(mockDbOperations.Object, supportingMethods); var result = service.AuthenticationAsync(user).Result; Assert.Null(result.datas); Assert.NotNull(result.error); Assert.Null(result.data); Assert.Null(result.stringData); Assert.Equal("User not found", result.error); }
public async Task WithExpiredAuth_ShouldFail() { // Arrange var auth = new UserAuthentication(userActive, TimeSpan.FromSeconds(-1)); var authCreator = ServiceProvider.GetService <ICreateAuthenticationRepository>(); await authCreator.Create(auth); var content = "some content"; var req = new CreateCommentRequest(auth.Id, threadVisisble.Id, content); var createCommentUseCase = ServiceProvider.GetService <CreateCommentUseCase>(); // Act var result = await createCommentUseCase.Handle(req); // Assert Assert.Single(result.ValidationErrors); Assert.Contains(CreateCommentError.AuthenticationIsInvalid, result.ValidationErrors); }
public async Task <ActionResult> Register([FromBody] UserAuthentication userModel) { if (!await _unitOfWork.UserRepository.DoesUserEmailExist(userModel.Email)) { if (!await _unitOfWork.UserRepository.DoesUserNameExist(userModel.UserName)) { User user = await _unitOfWork.UserRepository.CreateNewUser(userModel.UserName, userModel.Email, userModel.Password, Url, Request.Scheme); if (user == null) { return(StatusCode(500)); } return(StatusCode(200)); } return(StatusCode(422)); } return(StatusCode(409)); }
public UserAuthentication GetAuthenticationByName(string userName) { UserAuthentication userAuth = new UserAuthentication(); try { DynamicParameters param = new DynamicParameters(); param.Add("@UserName", userName); return(userAuth = dbConnection.Query <UserAuthentication>(userAuthByName, param, commandType: CommandType.StoredProcedure).SingleOrDefault()); } catch (Exception ex) { throw; } finally { } }
public UserAuthenticationResult LoginUser(UserAuthentication userAuthentication, string path) { var response = new UserAuthenticationResult(); XmlDocument doc = new XmlDocument(); doc.Load(path); doc.GetElementsByTagName("UserName").Item(0).InnerText = userAuthentication.UserName; doc.GetElementsByTagName("Password").Item(0).InnerText = userAuthentication.Password; //payload of xml document(Conversion to xml document) var stringPayload = new XmlConverter.XmlConverter().ToXml(doc); //econding of xml document to UTF-8 var encodedString = new UTF8Encoding().GetString(stringPayload); //replaces xml document footers var httpContent = new StringContent(encodedString, Encoding.UTF8, "text/xml"); using (var httpClient = new HttpClient()) { // Do the actual request and await the response var httpResponse = httpClient.PostAsync("http://41.216.173.228/RoboService/UserServicing.asmx?op=RegisterUser", httpContent); // If the response contains content we want to read it! if (httpResponse.Result.Content != null) { if (httpResponse.Result.IsSuccessStatusCode) { //convert back to xml string var stringData = httpResponse.Result.Content.ReadAsStringAsync().Result; XmlDocument resultDoc = new XmlDocument(); resultDoc.LoadXml(stringData); response.responsecode = resultDoc.GetElementsByTagName("responsecode").Item(0).InnerText; response.responsemessage = resultDoc.GetElementsByTagName("responsemessage").Item(0).InnerText; response.comment = resultDoc.GetElementsByTagName("comment").Item(0).InnerText; } } } return(response); }
public bool UpdateUser(UserDetails userDetails) { bool result = true; using (var context = new AdminAppEntities()) { UserDetail details = context.UserDetails.Where(x => x.UserID == userDetails.UserId).FirstOrDefault(); UserDetail updatedetails = new UserDetail { CompanyID = userDetails.CompanyID, RoleId = userDetails.RoleId, FirstName = userDetails.FirstName, LastName = userDetails.LastName, PrimaryEmailID = userDetails.PrimaryEmailID, PhoneNumber = userDetails.PhoneNumber, EmployeeCode = userDetails.EmployeeCode, Address = userDetails.Address, Address1 = userDetails.Address1, City = userDetails.City, State = userDetails.State, Country = userDetails.Country, Pincode = userDetails.Pincode, Active = true, UserID = userDetails.UserId }; context.Entry(details).CurrentValues.SetValues(updatedetails); context.SaveChanges(); UserAuthentication userAuth = context.UserAuthentications.Where(x => x.UserID == userDetails.UserId).FirstOrDefault(); context.UserAuthentications.Remove(userAuth); context.SaveChanges(); UserAuthentication userAuthNew = new UserAuthentication { UserID = userDetails.UserId, UserName = userDetails.UserName, Password = userDetails.Password }; context.UserAuthentications.Add(userAuthNew); context.SaveChanges(); return(result); } }
public void QuickMethodTest() { UserAuthentication.Login(TestData.UserData.Username, TestData.UserData.Password); Topic topic = TopicBank.AddTopic("sdfdsf"); Q_Zone.Models.Question.Question q1 = QuestionBank.AddQuestion(topic); Q_Zone.Models.Question.Question q2 = QuestionBank.AddQuestion(topic); Q_Zone.Models.Question.Question q3 = QuestionBank.AddQuestion(topic); Q_Zone.Models.Question.Question q4 = QuestionBank.AddQuestion(topic); Q_Zone.Models.Question.Question q5 = QuestionBank.AddQuestion(topic); Q_Zone.Models.Question.Question q6 = QuestionBank.AddQuestion(topic); Quiz quiz = QuizBank.AddQuiz(topic); quiz.QuizName = "dfgfdgdf"; quiz.AddQuestion(q1); quiz.AddQuestion(q2); quiz.AddQuestion(q3); quiz.AddQuestion(q4); quiz.AddQuestion(q5); quiz.AddQuestion(q6); quiz.DateTime = DateTime.UtcNow.AddMilliseconds(5); quiz.IsPublic = true; AnswerSheet answerSheet = new AnswerSheet(quiz); bool testBool = answerSheet.GiveAnswer(q1, "Correct answer"); answerSheet.GiveAnswer(q2, "Answer option 1"); answerSheet.GiveAnswer(q3, "Correct answer"); answerSheet.GiveAnswer(q4, "Correct answer"); answerSheet.Submit(); string testString = answerSheet.ShowGivenAnswer(q2); Result r1 = new Result(quiz); Result r2 = new Result(1, quiz); testBool = (r1 == r2); List <Quiz> quizList = RankList.ViewParticipatedQuizzes(maximumDuration: 5000); List <Result> rankList = RankList.ViewRankList(quiz); quizList = RankList.ViewStartedQuizzes(searchName: "d"); }
public string GetTimeZonesByName(string name) { ITimeZoneService service = null; try { // Create search criteria. TimeZoneSearchCriteria criteria = new TimeZoneSearchCriteria(); criteria.Name = name; // Create the service. service = AppService.Create <ITimeZoneService>(); // TODO: Need to change. UserAuthentication authentication = new UserAuthentication(); service.AppManager = authentication.AppManager; // Call service method. List <Tks.Entities.TimeZone> timeZones = service.Search(criteria); var resultList = from item in timeZones where item.IsActive = true select new { Id = item.Id, Name = item.Name, ShortName = item.ShortName }; // Serialize. JavaScriptSerializer serializer = new JavaScriptSerializer(); string timeZonesJson = serializer.Serialize(resultList); // Return the value. return(timeZonesJson); } catch { throw; } finally { // Dispose. if (service != null) { service.Dispose(); } } }
public void EditIncorrectOptionTest() { // prerequisite method call bool returnValue = UserAuthentication.Login(UserData.Username, UserData.Password); // prerequisite check Assert.IsTrue(returnValue, "\"Login\" method returns false"); User user = UserAuthentication.LoggedInUser; Assert.IsNotNull(user, "\"LoggedInUser\" is null"); // initialization Topic returnTopic = TopicBank.AddTopic(QuestionData.TopicName); Assert.IsNotNull(returnTopic, "\"AddTopic\" method returns null"); Q_Zone.Models.Question.Question question = new Q_Zone.Models.Question.Question(returnTopic); // test method call and initial check for (int i = 0; i < 4; i++) { returnValue = question.EditIncorrectOption(i, QuestionData.AnswerOptions[i]); Assert.IsTrue(returnValue, "\"EditIncorrectOption\" method returns false"); } // extended check List <string> list = question.ViewAllAnswerOptions(); foreach (string answerOption in list) { returnValue = list.Contains(answerOption); Assert.IsTrue(returnValue, "Question's incorrect answer option not changed"); } // security check UserAuthentication.Logout(); returnValue = question.EditIncorrectOption(2, "changed answer option"); Assert.IsFalse(returnValue, "Question's incorrect answer option changed even after logout"); list = question.ViewAllAnswerOptions(); foreach (string answerOption in list) { returnValue = list.Contains(answerOption); Assert.IsTrue(returnValue, "Question's incorrect answer option not changed"); } }
public UserAuthentication HashPassword(string password) { if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException(nameof(password)); } byte[] salt = new byte[_saltLength]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(salt); } var subKey = KeyDerivation.Pbkdf2(password, salt, _prf, _iterCount, _requestedLength); var headerByteLength = 1; // Format marker only if (_includeHeaderInfo) { headerByteLength = 13; } var outputBytes = new byte[headerByteLength + salt.Length + subKey.Length]; outputBytes[0] = _formatMarker; if (_includeHeaderInfo) { WriteNetworkByteOrder(outputBytes, 1, (uint)_prf); WriteNetworkByteOrder(outputBytes, 5, (uint)_iterCount); WriteNetworkByteOrder(outputBytes, 9, (uint)_saltLength); } Buffer.BlockCopy(salt, 0, outputBytes, headerByteLength, salt.Length); Buffer.BlockCopy(subKey, 0, outputBytes, headerByteLength + _saltLength, subKey.Length); UserAuthentication userAuthentication = new UserAuthentication(Convert.ToBase64String(salt), Convert.ToBase64String(outputBytes)) { UserId = 0 }; return(userAuthentication); // return Convert.ToBase64String(outputBytes); }
public void ViewQuestionsTest() { // prerequisite method call bool returnValue = UserAuthentication.Login(UserData.Username, UserData.Password); // prerequisite check Assert.IsTrue(returnValue, "\"Login\" method returns false"); User user = UserAuthentication.LoggedInUser; Assert.IsNotNull(user, "\"LoggedInUser\" is null"); // initialization Topic returnTopic = TopicBank.AddTopic(QuestionData.TopicName); Assert.IsNotNull(returnTopic, "\"AddTopic\" method returns null"); Q_Zone.Models.Question.Question question = QuestionBank.AddQuestion(returnTopic); question.QuestionString = QuestionData.QuestionString; foreach (string questionString in QuestionData.QuestionStrings) { question = QuestionBank.AddQuestion(returnTopic); question.QuestionString = questionString; } // test method call List <Q_Zone.Models.Question.Question> list = returnTopic.ViewQuestions(); // initial check Assert.AreEqual(5, list.Count, "\"ViewQuestions\" method does not return all questions"); // initial database check List <string> questionStringList = TestHelper.GetQuestionStringListFromQuestionList(list); Assert.IsTrue(questionStringList.Contains(QuestionData.QuestionString), "Question not shown in the list"); foreach (string questionString in QuestionData.QuestionStrings) { Assert.IsTrue(questionStringList.Contains(questionString), "Question not shown in the list"); } // security check UserAuthentication.Logout(); list = QuestionBank.ViewQuestions(); Assert.IsNull(list, "Questions shown even after logout"); }
public override int SaveChanges() { ObjectContext context = ((IObjectContextAdapter)this).ObjectContext; foreach (ObjectStateEntry entry in (context.ObjectStateManager .GetObjectStateEntries(EntityState.Added | EntityState.Modified))) { if (!entry.IsRelationship) { CurrentValueRecord entryValues = entry.CurrentValues; if (entryValues.GetOrdinal("ModifiedBy") > 0) { HttpContext currentContext = HttpContext.Current; string userId = "nazrul"; DateTime now = DateTime.Now; if (currContext.User.Identity.IsAuthenticated) { if (currentContext.Session["userId"] != null) { userId = (string)currentContext.Session["userId"]; } else { userId = UserAuthentication.GetUserId(currentContext.User.Identity.UserCode); } } entryValues.SetString(entryValues.GetOrdinal("ModifiedBy"), userId); entryValues.SetDateTime(entryValues.GetOrdinal("ModifiedDate"), now); if (entry.State == EntityState.Added) { entryValues.SetString(entryValues.GetOrdinal("CreatedBy"), userId); entryValues.SetDateTime(entryValues.GetOrdinal("CreatedDate"), now); } } } } return(base.SaveChanges()); }
public UserAuthentication GetUserAuthentication(UserAuthentication userCred) { UserAuthentication userAuth = new UserAuthentication(); try { DynamicParameters param = new DynamicParameters(); param.Add("@UserName", userCred.UserName); param.Add("@Password", userCred.Password); return(userAuth = dbConnection.Query <UserAuthentication>(valUser, param, commandType: CommandType.StoredProcedure).SingleOrDefault()); } catch (Exception ex) { throw; } finally { } }
void AuthenticateWithBrowser() { var userAuthProvider = new UserAuthentication(_connection); _authProvider = userAuthProvider; userAuthProvider.TokenChanged += userAuthProvider_TokenChanged; OAuthToken authToken = userAuthProvider.GetToken(); string savedToken = authToken.ToJson(); // This can be restored into a UserAuthentication object later to reuse: OAuthToken restoredToken = OAuthToken.FromJson(savedToken); UserAuthentication restoredAuthProvider = new UserAuthentication(_connection, restoredToken); // Now the user will not be prompted when we call GetToken OAuthToken cachedToken = restoredAuthProvider.GetToken(); }
public async Task <ActionResult> Login(UserAuthentication model, string retUrl) { SigninStatus result = await SigninManager.SigninUserAsync(model.username, model.userpwd, model.custid); switch (result) { case SigninStatus.Success: IsAuthenticated = true; return(DoAuthentication(model.custid, model.username, retUrl)); break; case SigninStatus.Undefine: ViewBag.Error = "UserName or Password is not valid... Please Check"; break; } model.userpwd = string.Empty; return(View(model)); }
public async Task OnPostAsync_GivenCommandFailure_ExpectRedirectToPageResultToSamePageAndPrgStateSet() { var mediator = new Mock <IMediator>(); mediator.Setup(x => x.Send(It.IsAny <AuthenticateUserCommand>(), It.IsAny <CancellationToken>())) .ReturnsAsync(() => Result.Fail <AuthenticateUserCommandResult, ErrorData>(new ErrorData(ErrorCodes.SavingChanges))); var authenticationService = new Mock <IAuthenticationService>(); var page = new UserAuthentication(mediator.Object, authenticationService.Object) { PageModel = new UserAuthentication.Model() }; var result = await page.OnPostAsync(); Assert.IsType <RedirectToPageResult>(result); Assert.Equal(PrgState.Failed, page.PrgState); }
// GET: Shop public ActionResult Index(FormCollection categoriesFC) { List <Product> allProducts = new List <Product>(); if (categoriesFC.Count == 0) { allProducts = db.Products.ToList(); } else { foreach (string key in categoriesFC.AllKeys) { foreach (var item in db.Products) { if (item.Category_Name == key) { allProducts.Add(item); } } } } ViewBag.CurrentUrl = new List <string>(); foreach (Product item in allProducts) { if (item.ProductPictureURL != null) { ViewBag.CurrentUrl.Add(item.ProductPictureURL.Substring(1, item.ProductPictureURL.Length - 1)); } } string currentUser = UserAuthentication.WhoAmI(User, Session); List <Product> allProductRightOrder = allProducts.OrderBy(p => p.ProductName).ThenBy(m => m.Manufacturer).ToList(); List <BasketEntry> CurrentUserBasketEntries = db.BasketEntries.Where(x => x.UserID == currentUser).ToList(); TempData["ProductNameAndCount"] = CurrentUserBasketEntries; ViewBag.CategoriesChecked = categoriesFC.AllKeys.ToList(); ViewBag.ProdCategories = db.CategoryNames.Select(x => x.Category_Name).ToList(); return(View(allProductRightOrder)); }
public IActionResult Index(LoginForm logForm) { if (ModelState.IsValid) { if (UserAuthentication.Login(logForm.Email, logForm.Password)) { //HttpContext.Session.SetString("user", logInfo.Login); HttpContext.Session.SetString("Email", logForm.Email); return(RedirectToAction("Index", "Home")); //return RedirectToAction("Index", new RouteValueDictionary( new { controller = Home, action = "Index", auth = ea })); } else { ModelState.AddModelError("Email", logForm.Email); ModelState.AddModelError("Password", logForm.Password); } } return(View()); }
public async Task <IActionResult> AddPersons(string personId) { string[] employeeId = Splitstr(personId, "+/+"); Person person = PersonRepository.FindById(Guid.Parse(employeeId[0])); UserAuthentication userAuthentication = await _userManager.FindByIdAsync(employeeId[1]); userAuthentication.personId = person.Id; var userRoles = await _userManager.GetRolesAsync(userAuthentication); // получаем все роли var AddRoles = userRoles; AddRoles.Add("employee"); await _userManager.AddToRoleAsync(userAuthentication, "employee"); return(RedirectToAction("UserList")); }
private void GenerateToken(UserAuthentication user) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(this.jwtTokenSettings.Key); var expirationDate = DateTime.UtcNow.AddDays(this.jwtTokenSettings.ExpirationDays); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Username) }), Expires = expirationDate, SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); user.Token = tokenHandler.WriteToken(token); user.TokenExpiration = expirationDate; }
public EmployeeMonitoringSystem(User user) { _handler = EmployeeHandler.Init(); _userAuthentication = new UserAuthentication(); _user = user; InitializeComponent(); if (_user.IsAdmin()) { addUserToolStripMenuItem.Enabled = true; addUserToolStripMenuItem.Visible = true; } else { addUserToolStripMenuItem.Enabled = false; addUserToolStripMenuItem.Visible = false; } LoadDatabase(); }
private void UpdateHPPAuthenticationDateUpdated(UserAuthentication hppAuth) { try { IIdeaDatabaseDataContext writableContext = DependencyInjector.Get <IIdeaDatabaseDataContext, IdeaDatabaseReadWrite>(); DatabaseWrapper.databaseOperation(new ResponseBase(), writableContext, (context) => { UserAuthentication writableHPPAuth = context.UserAuthentications.Where(x => x.UserId == hppAuth.UserId && x.TokenMD5 == hppAuth.TokenMD5 && x.CallerId == hppAuth.CallerId).FirstOrDefault(); writableHPPAuth.ModifiedDate = DateTime.UtcNow; context.SubmitChanges(); } ); } catch (Exception ex) { logger.Error($"Exception {ex.Message} while updating dateUpdated in UserAuthentication for UserID : {hppAuth.UserId} and CallerId : {hppAuth.CallerId}"); } }
/// <summary> /// Initialize the services of WEBSS with the specified transport type, soap version and user authentication provided by the test case. /// </summary> /// <param name="userAuthentication">a user authenticated</param> public void InitializeService(UserAuthentication userAuthentication) { SoapVersion soapVersion = Common.GetConfigurationPropertyValue<SoapVersion>("SoapVersion", this.Site); switch (soapVersion) { case SoapVersion.SOAP11: { this.InitializeService(AdapterHelper.GetTransportType(), SoapProtocolVersion.Soap11, userAuthentication, Common.GetConfigurationPropertyValue("TargetServiceUrl", this.Site)); break; } default: { this.InitializeService(AdapterHelper.GetTransportType(), SoapProtocolVersion.Soap12, userAuthentication, Common.GetConfigurationPropertyValue("TargetServiceUrl", this.Site)); break; } } }
/// <summary> /// Initialize the services of WEBSS with the specified transport type, soap version and user authentication provided by the test case. /// </summary> /// <param name="userAuthentication">a user authenticated</param> public void InitializeService(UserAuthentication userAuthentication) { SoapVersion soapVersion = Common.GetConfigurationPropertyValue <SoapVersion>("SoapVersion", this.Site); switch (soapVersion) { case SoapVersion.SOAP11: { this.InitializeService(AdapterHelper.GetTransportType(), SoapProtocolVersion.Soap11, userAuthentication, Common.GetConfigurationPropertyValue("TargetServiceUrl", this.Site)); break; } default: { this.InitializeService(AdapterHelper.GetTransportType(), SoapProtocolVersion.Soap12, userAuthentication, Common.GetConfigurationPropertyValue("TargetServiceUrl", this.Site)); break; } } }
public void GetRefreshTokenTest_InvalidCredentials() { TokenDetails accessToken = new TokenDetails() { AccessToken = "dasfdasfdasfadsfasdfdasfdasfds" }; UserAuthentication appAuth = null; queryUtilsMock.Setup(q => q.GetHPPToken(It.IsAny <IIdeaDatabaseDataContext>(), It.IsAny <String>(), It.IsAny <String>())).Returns(appAuth); Assert.IsNull(new UserUtils().GetRefreshToken("", accessToken)); queryUtilsMock.Verify(q => q.GetHPPToken(It.IsAny <IIdeaDatabaseDataContext>(), It.IsAny <String>(), It.IsAny <String>()), Times.Once); queryUtilsMock.Verify(q => q.GetUser(It.IsAny <IIdeaDatabaseDataContext>(), It.IsAny <int>()), Times.Never); }
private void btnShowProducts_Click(object sender, EventArgs e) { Awin.ApiPortTypeClient client = new Awin.ApiPortTypeClient(); UserAuthentication userAuthentication = new UserAuthentication(); userAuthentication.sApiKey = "b9e01904105aac94b7ded008abcef422"; getProduct product = new getProduct(); product.iProductId = new long[1]; product.iProductId [0] = 3389364729; lblProducts.Text = "Products (id, name):\n"; Product[] result = client.getProduct(userAuthentication, product); lblProducts.Text += result[0].sName + "\n"; }
OnPostAsync_GivenSuccessfulExecutionAndMfaIsEmail_ExpectPartialAuthenticationAndRedirectEmailMfaPage() { var mediator = new Mock <IMediator>(); mediator.Setup(x => x.Send(It.IsAny <AuthenticateUserCommand>(), It.IsAny <CancellationToken>())) .ReturnsAsync(() => Result.Ok <AuthenticateUserCommandResult, ErrorData>(new AuthenticateUserCommandResult(TestVariables.UserId, BaseAuthenticationProcessCommandResult.AuthenticationState.AwaitingMfaEmailCode, MfaProvider.Email))); var authenticationService = new Mock <IAuthenticationService>(); var page = new UserAuthentication(mediator.Object, authenticationService.Object) { PageModel = new UserAuthentication.Model(), ReturnUrl = "some-url", }; var result = Assert.IsType <RedirectToPageResult>(await page.OnPostAsync()); Assert.Equal(PageLocations.AuthEmailMfa, result.PageName); }
public bool LogIn(UserAuthentication userAuth) { Connection.Open(); string query = "SELECT * FROM UserAuthentication WHERE UserId= @userId AND Password = @password"; Command = new SqlCommand(query, Connection); Command.Parameters.Add("@userId", userAuth.UserId); Command.Parameters.Add("@password", userAuth.Password); Reader = Command.ExecuteReader(); bool isExists = Reader.HasRows; Reader.Close(); Connection.Close(); return(isExists); }
public static Boolean SendResetPasswordEmail(Data.Model.User user, out String message) { try { //string siteUrl = Upsilab.Business.Utility.UrlHelper.GetSiteUrl(); string siteUrl = string.Empty; String from = ConfigurationManager.ResetPasswordEmailFrom; if (user.IsEndUser()) { siteUrl = string.Format("{0}/Client", Upsilab.Business.Utility.UrlHelper.GetHost()); Data.Model.CustomerProspect customer = CustomerProspectBL.GetCustomerProspectByIdUser(user.idUser); from = customer.User1.UserEmail; } else if (user.IsSuperAdmin()) { siteUrl = string.Format("{0}/Admin", Upsilab.Business.Utility.UrlHelper.GetHost()); } else { siteUrl = string.Format("{0}/User", Upsilab.Business.Utility.UrlHelper.GetHost()); } string token = HttpServerUtility.UrlTokenEncode(new System.Text.ASCIIEncoding().GetBytes((UserBL.CreateSecureToken(user)))); string urlResetPwd = string.Format("{0}/User/ResetPassword?token={1}", siteUrl, token); var template = EmailManager.GetEmailTemplateContentByName(EmailManager.ResetPassword); string subject = LanguageContentBL.Translate("mailResetPassword");//Réinitialisation de votre mot de passe sur www.upsideo.fr string emailMessage = string.Format(template, urlResetPwd); UserAuthentication userAuth = new UserAuthentication() { UserAuthToken = token, IsValid = true, DateCreated = DateTime.Now, idUser = user.idUser }; UserAuthentificationBL.CreateUserAuthentication(userAuth); EmailManager.SendEmail(from, user.UserEmail, String.Empty, subject, emailMessage); //Log mail EmailLogBL.TypeDestinataire typeDestinaire = EmailLogBL.TypeDestinataire.Admin; if (user.IsEndUser()) typeDestinaire = EmailLogBL.TypeDestinataire.Client; else if (user.IsAdmin()) typeDestinaire = EmailLogBL.TypeDestinataire.Admin; else if (user.IsAdviser()) typeDestinaire = EmailLogBL.TypeDestinataire.Adviser; EmailLogBL.Log(null, from, user.idUser, user.UserEmail, typeDestinaire, System.Reflection.MethodBase.GetCurrentMethod().Name); message = LanguageContentBL.Translate("messageResetPassword");//L'email de réinitialisation de mot de passe a été envoyé avec succès ! return true; } catch (Exception ex) { message = ex.Message; return false; } }
public static void InvalidateToken(UserAuthentication userAuth) { userAuth.IsValid = false; UserAuthentificationBL.UpdateUserAuthentication(userAuth); }
/// <summary> /// Send email to admin to confirm his command and activate his access to the application /// </summary> /// <param name="subscription"></param> public static void SendAccessActivationEmail(Subscription subscription) { try { //Define password Data.Model.User userAdmin = subscription.FirmInstitution.User; string urlAccessUser = string.Format("{0}/User", Upsilab.Business.Utility.UrlHelper.GetHost()); string token = System.Web.HttpServerUtility.UrlTokenEncode(new System.Text.ASCIIEncoding().GetBytes((Upsilab.Business.User.UserBL.CreateSecureToken(userAdmin)))); //Token for access user UserAuthentication userAuth = new UserAuthentication() { UserAuthToken = token, IsValid = true, DateCreated = DateTime.Now, idUser = userAdmin.idUser }; Upsilab.Business.User.UserAuthentificationBL.CreateUserAuthentication(userAuth); string urlDefinePwd = string.Format("{0}/User/DefinePassword?token={1}", urlAccessUser, token); // License or Credit string labelLicenseOrCredit = string.Empty; int? numberLicenseOrCredit = null; GetNumberLabelCommand(subscription, out numberLicenseOrCredit, out labelLicenseOrCredit); //From string from = ConfigurationManager.EmailFrom; //To : send to admin string to = null; string cc = null; to = subscription.FirmInstitution.User.UserEmail; string subject = LanguageContentBL.Translate("email_access_activation_subject"); var template = EmailManager.GetEmailTemplateContentByName(EmailManager.Subscription_AccessActivation); string message = string.Format(template, numberLicenseOrCredit, labelLicenseOrCredit, subscription.Application, urlDefinePwd, ConfigurationManager.ExtranetUserUrl); EmailManager.SendEmail(from, to, cc, subject, message, true); //log EmailLogBL.Log(null, from, subscription.FirmInstitution.idFirmInstitution, to, EmailLogBL.TypeDestinataire.Admin, System.Reflection.MethodBase.GetCurrentMethod().Name, null, cc); } catch (Exception ex) { Log.Log.AppendException(ex); } }
private void Authenticate(ref HttpSessionStateBase session, string token) { iisTraceListener.WriteLine("Authenticate"); iisTraceListener.Flush(); User user = new User(); UserAuthentication userAuthentication = new UserAuthentication(); if (userAuthentication.IsAuthenticated(ref user, token)) { session.Contents.Add("USER", user); } else { session.Contents.Remove("USER"); } }
public void Test_AuthController_LogOn_Post_Error() { var value = new UserAuthentication(); var viewResult = this.AuthController.LogOn(value) as ViewResult; Assert.IsNotNull(viewResult, "ViewResult"); Assert.AreEqual(Views.LogOn, viewResult.ViewName, "ViewName"); var model = viewResult.Model as UserAuthentication; Assert.IsNotNull(model, "UserAuthentication"); Assert.AreEqual(2, model.Errors.Count, "Errors"); }
public void Test_AuthController_LogOn_Post() { var value = new UserAuthentication { EmailAddress = "*****@*****.**", Password = "******", Redirect = "test", IsPersistent = true }; var redirectResult = this.AuthController.LogOn(value) as RedirectResult; Assert.IsNotNull(redirectResult, "RedirectResult"); }
/// <summary> /// Send email to CGP to approve or to signe the convention /// </summary> /// <param name="signatureTransaction"></param> /// <param name="isConvention">true if convention, false if avenant</param> /// <returns></returns> public static bool SendConventionMailToCGP(Upsilab.Data.Model.SignatureTransaction signatureTransaction, bool isConvention) { bool isOk = true; try { var userCGPClient = SignatoryBL.GetSignatory(signatureTransaction.idSignatureTransaction, SignatoryBL.Roles.CGP).User; var userSDG = UserBL.GetUserById(signatureTransaction.idUserCreated); var firmSDG = Configuration.FirmInstitutionBL.GetFirmInstitutionParentByIdFirm(signatureTransaction.idFirmInstitution.Value); var from = userSDG.UserEmail; var to = userCGPClient.UserEmail; var subject = string.Empty; var body = string.Empty; var emailTemplate = string.Empty; var urlAccessCGP = string.Format("{0}/signature-client", Upsilab.Business.Utility.UrlHelper.GetHost()); //Invite CGP to approve or sign var token = System.Web.HttpServerUtility.UrlTokenEncode(new System.Text.ASCIIEncoding().GetBytes((Upsilab.Business.User.UserBL.CreateSecureToken(userCGPClient)))); //Token for access client var userAuth = new UserAuthentication() { UserAuthToken = token, IsValid = true, DateCreated = DateTime.Now, idUser = userCGPClient.idUser }; UserAuthentificationBL.CreateUserAuthentication(userAuth); var urlDefinePwd = string.Format("{0}/User/DefinePassword?token={1}", urlAccessCGP, token); var urlResetPwd = string.Format("{0}/User/ResetPassword?token={1}", urlAccessCGP, token); var urlLogin = string.Format("{0}/User/Login", urlAccessCGP); //Approval or signature ? bool isApproval = (signatureTransaction.Status == DocumentBL.Status.WaitingForClientApproval.ToString()) ? true : false; if (isApproval) //Approval { if (isConvention) //Convention { subject = LanguageContentBL.Translate("convention_approval_email_subject"); //Convention de partenariat emailTemplate = EmailManager.GetEmailTemplateContentByName(EmailManager.Convention_InviteCGPToApprove); } else //Avenant { subject = LanguageContentBL.Translate("avenant_approval_email_subject"); //Avenant relatif à la convention de partenariat emailTemplate = EmailManager.GetEmailTemplateContentByName(EmailManager.Avenant_InviteCGPToApprove); } } else //Signature { if (isConvention) //Convention { subject = LanguageContentBL.Translate("convention_signature_email_subject"); //Convention de partenariat emailTemplate = EmailManager.GetEmailTemplateContentByName(EmailManager.Convention_InviteCGPToSign); } else //Avenant { subject = LanguageContentBL.Translate("avenant_signature_email_subject"); //Avenant sur la convention de partenariat emailTemplate = EmailManager.GetEmailTemplateContentByName(EmailManager.Avenant_InviteCGPToSign); } } body = String.Format(emailTemplate, LanguageContentBL.Translate(userCGPClient.Civility), userCGPClient.UserName, firmSDG.FirmInstitutionName, urlDefinePwd, urlLogin, urlResetPwd); Upsilab.Business.Utility.EmailManager.SendEmail(from, to, null, subject, body, true); //Log mail EmailLogBL.Log(userSDG.idUser, from, userCGPClient.idUser, to, EmailLogBL.TypeDestinataire.Adviser, System.Reflection.MethodBase.GetCurrentMethod().Name); } catch (Exception ex) { isOk = false; Log.Log.AppendException(ex); } return isOk; }
private static bool SendAlertEmailToUpdate_LAB(List<Data.Model.CustomerProspect> customerProspects, bool isAutomatic) { if (customerProspects == null || customerProspects.Count == 0) return false; bool isSent = true; try { bool bProdServer = (Upsilab.Business.Utility.ConfigurationManager.ServerType == Upsilab.Business.Utility.ConfigurationManager.EnumServerType.PROD.ToString()) ? true : false; //var userClient = customerProspect[0].User; var userAdvisor = customerProspects[0].User1; if (!string.IsNullOrEmpty(userAdvisor.UserEmail)) { var host = System.Configuration.ConfigurationManager.AppSettings["WebHostAddress"]; string siteUrl = string.Format("{0}/User", host); string token = HttpServerUtility.UrlTokenEncode(new System.Text.ASCIIEncoding().GetBytes((UserBL.CreateSecureToken(userAdvisor)))); string urlResetPwd = string.Format("{0}/User/ResetPassword?token={1}", siteUrl, token); var template = string.Empty; String emailMessage = string.Empty; String subject = string.Empty; String from = ConfigurationManager.EmailFrom; String to = ConfigurationManager.EmailTo; template = EmailManager.GetEmailTemplateContentByName(EmailManager.LAB_AlertAdviserToUpdateManyClient, isAutomatic, userAdvisor); subject = "Alerte de mise à jour de données LAB"; var param = string.Empty; var i = 0; foreach (var customer in customerProspects) { param += (i == 0) ? string.Format("{0} {1}", customer.FirstName, customer.Name) : string.Format("<br/>{0} {1}", customer.FirstName, customer.Name); i++; } emailMessage = String.Format(template , param , siteUrl , urlResetPwd); to = userAdvisor.UserEmail; //Toujours envoyer au conseiller pour ces 3 documents if (!bProdServer) //preprod { subject = "TEST - " + subject; to = ConfigurationManager.EmailTo; } EmailManager.SendEmail(from, to, String.Empty, subject, emailMessage, true); //Log mail EmailLogBL.Log(null, from, userAdvisor.idUser, userAdvisor.UserEmail, EmailLogBL.TypeDestinataire.Adviser, System.Reflection.MethodBase.GetCurrentMethod().Name); UserAuthentication userAuth = new UserAuthentication() { UserAuthToken = token, IsValid = true, DateCreated = DateTime.Now, idUser = userAdvisor.idUser }; UserAuthentificationBL.CreateUserAuthentication(userAuth); } } catch (Exception ex) { isSent = false; Log.Log.AppendException(ex); } return isSent; }
public ActionResult MotDePasseOublie(User objUser) { var LanguageData = PageLanguageHelper.GetLanguageContent("Public", "UserCtrl/MdpOublie"); try { if (objUser != null) { Upsilab.Data.Model.User objUserRecupere = UserBL.GetUserByEmail(objUser.UserEmail); // Tester si l'utilisateur existe et qu'il est active if (objUserRecupere != null && objUserRecupere.IsActive) { // la chaine à crypter string sTokenConcatene = string.Concat(objUserRecupere.UserEmail, System.Diagnostics.Stopwatch.GetTimestamp(), System.Configuration.ConfigurationManager.AppSettings["ClePriveToken"].ToString()); // cryptage du byte[] data = new System.Text.ASCIIEncoding().GetBytes(sTokenConcatene); string sToken = Convert.ToBase64String(new SHA1CryptoServiceProvider().ComputeHash(data)); // L'url de récupération de mdp string sUrl = System.Configuration.ConfigurationManager.AppSettings["UrlInitialiserMDP"].ToString() + sToken; #region "Envoi du mail" // Envoi du mail string sFrom = System.Configuration.ConfigurationManager.AppSettings["EmailFrom"].ToString(); string sTo = objUser.UserEmail; string sSujet = LanguageData.GetContent("umo_sujet_mail"); string sMessage = LanguageData.GetContent("umo_contenu_mail") + "<a href='" + sUrl + "'>" + sUrl + "</a>"; EmailManager.SendEmail(sFrom, sTo, null, sSujet, sMessage); //Log mail EmailLogBL.Log(null, sFrom, objUser.idUser, sTo, EmailLogBL.TypeDestinataire.Client, System.Reflection.MethodBase.GetCurrentMethod().Name); #endregion #region "Enregistrement dans la base de données" using (var db = new UpsilabEntities()) { UserAuthentication objUserAuth = new UserAuthentication() { UserAuthToken = sToken, IsValid = true, DateCreated = DateTime.Now, idUser = objUserRecupere.idUser }; db.UserAuthentication.AddObject(objUserAuth); db.SaveChanges(); } #endregion ViewBag.Info = LanguageData.GetContent("umo_mail_envoye"); } } else { ViewBag.Info = LanguageData.GetContent("umo_user_inconnu"); } } catch(Exception ex) { ViewBag.Info = LanguageData.GetContent("umo_catch_erreur") + ex.Message; } return View(); }
/// <summary> /// /// </summary> /// <param name="customerProspect"></param> public static bool SendAlertEmailToUpdateReport(Data.Model.CustomerProspect customerProspect, bool forceCustomerAsRecipient, bool isAutomatic) { bool isSent = true; try { bool bProdServer = (Upsilab.Business.Utility.ConfigurationManager.ServerType == Upsilab.Business.Utility.ConfigurationManager.EnumServerType.PROD.ToString()) ? true : false; var userClient = customerProspect.User; var userAdvisor = customerProspect.User1; var host = (isAutomatic) ? System.Configuration.ConfigurationManager.AppSettings["WebHostAddress"] : Upsilab.Business.Utility.UrlHelper.GetHost(); String from = ConfigurationManager.EmailFrom; String to = ConfigurationManager.EmailTo; if (customerProspect.IsAlertRecipientClient || forceCustomerAsRecipient) //Send email to customer { string token = System.Web.HttpServerUtility.UrlTokenEncode(new System.Text.ASCIIEncoding().GetBytes((Upsilab.Business.User.UserBL.CreateSecureToken(userClient)))); //Token for access client string urlAccessClient = string.Format("{0}/Client", host); string urlDefinePwd = string.Format("{0}/User/DefinePassword?token={1}", urlAccessClient, token); string urlResetPwd = string.Format("{0}/User/ResetPassword?token={1}", urlAccessClient, token); var template = EmailManager.GetEmailTemplateContentByName(EmailManager.Report_AlertCustomerToUpdate, isAutomatic, userClient); //TODO String subject = (isAutomatic) ? "Votre conseiller financier vous invite à mettre à jour vos données" : LanguageContentBL.Translate("mailReportInvitSubject"); String emailMessage = String.Format(template , userAdvisor.UserFirstName , userAdvisor.UserName , urlAccessClient , urlResetPwd , urlDefinePwd); to = userClient.UserEmail; from = userAdvisor.UserEmail; if (!bProdServer) //prepord { subject = "TEST - " + subject; to = ConfigurationManager.EmailTo; } //9866 : create / copy report //Update status var sendMail = ReportBL.SendReportToBeUpdatedByCustomer(customerProspect); if (sendMail) { EmailManager.SendEmail(from, to, String.Empty, subject, emailMessage, true); UserAuthentication userAuth = new UserAuthentication() { UserAuthToken = token, IsValid = true, DateCreated = DateTime.Now, idUser = userClient.idUser }; UserAuthentificationBL.CreateUserAuthentication(userAuth); //Log mail EmailLogBL.Log(null, from, customerProspect.IdUser, userClient.UserEmail, EmailLogBL.TypeDestinataire.Client, System.Reflection.MethodBase.GetCurrentMethod().Name); } } else //Send email to adviser { if (!string.IsNullOrEmpty(userAdvisor.UserEmail)) { string token = System.Web.HttpServerUtility.UrlTokenEncode(new System.Text.ASCIIEncoding().GetBytes((Upsilab.Business.User.UserBL.CreateSecureToken(userAdvisor)))); //Token for access advisor string urlAccessAdviser = string.Format("{0}/User", host); string urlResetPwd = string.Format("{0}/User/ResetPassword?token={1}", urlAccessAdviser, token); var template = EmailManager.GetEmailTemplateContentByName(EmailManager.Report_AlertAdviserToUpdate, isAutomatic, userAdvisor); //TODO String subject = (isAutomatic) ? "Alerte de mise à jour de recueil d'informations client" : LanguageContentBL.Translate("mailReportAlertAdviserSubject"); String emailMessage = String.Format(template , customerProspect.FirstName , customerProspect.Name , urlAccessAdviser , urlResetPwd); to = userAdvisor.UserEmail; from = userClient.UserEmail; if (!bProdServer) //preprod { subject = "TEST - " + subject; to = ConfigurationManager.EmailTo; } EmailManager.SendEmail(from, to, String.Empty, subject, emailMessage, true); UserAuthentication userAuth = new UserAuthentication() { UserAuthToken = token, IsValid = true, DateCreated = DateTime.Now, idUser = userAdvisor.idUser }; UserAuthentificationBL.CreateUserAuthentication(userAuth); //Log mail EmailLogBL.Log(null, from, customerProspect.idUserCreated, userAdvisor.UserEmail, EmailLogBL.TypeDestinataire.Adviser, System.Reflection.MethodBase.GetCurrentMethod().Name); } } } catch (Exception ex) { isSent = false; Log.Log.AppendException(ex); } return isSent; }
public static Boolean SendDefinePasswordEmail(Data.Model.CustomerProspect customer, out String message) { try { //string siteUrl = string.Format("{0}/Client", Upsilab.Business.Utility.UrlHelper.GetHost()); string siteUrl = Upsilab.Business.Utility.UrlHelper.GetSiteUrl(); var template = EmailManager.GetEmailTemplateContentByName(EmailManager.DefinePasswordCustomer); string token = HttpServerUtility.UrlTokenEncode(new System.Text.ASCIIEncoding().GetBytes((UserBL.CreateSecureToken(customer.User)))); string urlDefinePwd = string.Format("{0}/User/DefinePassword?token={1}", siteUrl, token); //Adviser / FirmInstitution Data.Model.User userAdviser = customer.User1; Data.Model.FirmInstitution firm = FirmInstitutionBL.GetFirmInstitutionByUser(userAdviser); //string from = ConfigurationManager.DefinePasswordEmailFrom; string from = userAdviser.UserEmail; string subject = LanguageContentBL.Translate("mailDefinePasswordAdviser"); string emailMessage = String.Format(template, userAdviser.UserFirstName, userAdviser.UserName, firm.FirmInstitutionName, urlDefinePwd); EmailManager.SendEmail(from, customer.User.UserEmail, String.Empty, subject, emailMessage); //Log mail EmailLogBL.Log(null, from, customer.User.idUser, customer.User.UserEmail, EmailLogBL.TypeDestinataire.Client, System.Reflection.MethodBase.GetCurrentMethod().Name); UserAuthentication userAuth = new UserAuthentication() { UserAuthToken = token, IsValid = true, DateCreated = DateTime.Now, idUser = customer.User.idUser }; UserAuthentificationBL.CreateUserAuthentication(userAuth); message = LanguageContentBL.Translate("messageSetPassword"); return true; } catch (Exception ex) { message = ex.Message; return false; } }
public static void SendDERMailToClient(Upsilab.Data.Model.DER der, bool inviteClientToSign) { try { Upsilab.Data.Model.User userClient = der.CustomerProspect.User; Upsilab.Data.Model.User userAdviser = (der.User != null) ? der.User : der.CustomerProspect.User1; //NB : User1 => UserCreated string from = userAdviser.UserEmail; string to = userClient.UserEmail; string subject = string.Empty; string body = string.Empty; string direction = "DER"; string idCustomer = der.CustomerProspect.idCustomer.ToString(); string urlAccessClient = string.Format("{0}/Client", Upsilab.Business.Utility.UrlHelper.GetHost(), direction); string derLabel = LanguageContentBL.Translate("der_title"); //Invite client to sign if (inviteClientToSign) { string token = System.Web.HttpServerUtility.UrlTokenEncode(new System.Text.ASCIIEncoding().GetBytes((Upsilab.Business.User.UserBL.CreateSecureToken(userClient)))); //Token for access client UserAuthentication userAuth = new UserAuthentication() { UserAuthToken = token, IsValid = true, DateCreated = DateTime.Now, idUser = userClient.idUser }; UserAuthentificationBL.CreateUserAuthentication(userAuth); string urlDefinePwd = string.Format("{0}/User/DefinePassword?token={1}", urlAccessClient, token); string urlResetPwd = string.Format("{0}/User/ResetPassword?token={1}", urlAccessClient, token); string urlHome = string.Format("{0}/Home/Index/{1}/?d={2}", urlAccessClient, idCustomer, direction); subject = derLabel; string emailTemplateKey = EmailManager.DER_InviteCustomerToSignAfterAdviserSign; var emailTemplate = EmailManager.GetEmailTemplateContentByName(emailTemplateKey); body = String.Format(emailTemplate, userAdviser.UserFirstName, userAdviser.UserName, urlHome, urlResetPwd, urlDefinePwd); } else // Inform client that adviser has signed the Report { //DO NOTHING } Upsilab.Business.Utility.EmailManager.SendEmail(from, to, null, subject, body, true); //Log mail EmailLogBL.Log(userAdviser.idUser, from, userClient.idUser, to, EmailLogBL.TypeDestinataire.Client, System.Reflection.MethodBase.GetCurrentMethod().Name); } catch { } }
public static void SendMissionDocumentMailToClient(Upsilab.Data.Model.MissionDocument missionDoc, bool inviteClientToSign) { try { Upsilab.Data.Model.User userClient = missionDoc.CustomerProspect.User; Upsilab.Data.Model.User userAdviser = (missionDoc.User != null) ? missionDoc.User : missionDoc.CustomerProspect.User1; //NB : User1 => UserCreated string from = userAdviser.UserEmail; string to = userClient.UserEmail; string subject = string.Empty; string body = string.Empty; string direction = missionDoc.IsLetter ? "LM" : "RM"; string idCustomer = missionDoc.CustomerProspect.idCustomer.ToString(); string urlAccessClient = string.Format("{0}/Client", Upsilab.Business.Utility.UrlHelper.GetHost(), direction); string missionDocLabel = (missionDoc.IsLetter) ? LanguageContentBL.Translate("Subscription_MissionLetter") : LanguageContentBL.Translate("cf_menu_gauche_compte_rendu"); //Invite client to sign if (inviteClientToSign) { string token = System.Web.HttpServerUtility.UrlTokenEncode(new System.Text.ASCIIEncoding().GetBytes((Upsilab.Business.User.UserBL.CreateSecureToken(userClient)))); //Token for access client UserAuthentication userAuth = new UserAuthentication() { UserAuthToken = token, IsValid = true, DateCreated = DateTime.Now, idUser = userClient.idUser }; UserAuthentificationBL.CreateUserAuthentication(userAuth); string urlDefinePwd = string.Format("{0}/User/DefinePassword?token={1}", urlAccessClient, token); string urlResetPwd = string.Format("{0}/User/ResetPassword?token={1}", urlAccessClient, token); string urlHome = string.Format("{0}/Home/Index/{1}/?d={2}", urlAccessClient, idCustomer, direction); subject = missionDocLabel; string MISSION_DOC_LABEL = missionDocLabel.ToLower(); string PRONOM_MISSION_DOC_LABEL = string.Format("{0} {1}", (missionDoc.IsLetter) ? LanguageContentBL.Translate("ma") : LanguageContentBL.Translate("mon"), MISSION_DOC_LABEL); // string emailTemplateKey = (missionDoc.IsLetter) ? EmailManager.MissionLetter_InviteCustomerToSignAfterAdviserSign : EmailManager.MissionReport_InviteCustomerToSignAfterAdviserSign; var emailTemplate = EmailManager.GetEmailTemplateContentByName(emailTemplateKey); body = String.Format(emailTemplate, userAdviser.UserFirstName, userAdviser.UserName, urlHome, urlResetPwd, urlDefinePwd); } else // Inform client that adviser has signed the Report { //DO NOTHING } Upsilab.Business.Utility.EmailManager.SendEmail(from, to, null, subject, body, true); //Log mail EmailLogBL.Log(userAdviser.idUser, from, userClient.idUser, to, EmailLogBL.TypeDestinataire.Client, System.Reflection.MethodBase.GetCurrentMethod().Name); } catch { } }
private void Start () { user = new UserAuthentication (serverSettings); user.Failed += ShowFailedError; type.UpdateValue += ChangedRole; }
public static void SendReportMailToClient(Upsilab.Data.Model.Report report, bool inviteClientToSign, bool canUpdateInfo = false) { try { Upsilab.Data.Model.User userClient = report.CustomerProspect.User; Upsilab.Data.Model.User userAdviser = (report.User != null) ? report.User : report.CustomerProspect.User1; //NB : User1 => UserCreated string from = userAdviser.UserEmail; string to = userClient.UserEmail; string subject = string.Empty; string body = string.Empty; string direction = "RI"; string idCustomer = report.CustomerProspect.idCustomer.ToString(); string urlAccessClient = string.Format("{0}/Client", Upsilab.Business.Utility.UrlHelper.GetHost()); //Invite client to sign if (inviteClientToSign) { string token = System.Web.HttpServerUtility.UrlTokenEncode(new System.Text.ASCIIEncoding().GetBytes((Upsilab.Business.User.UserBL.CreateSecureToken(userClient)))); //Token for access client UserAuthentication userAuth = new UserAuthentication() { UserAuthToken = token, IsValid = true, DateCreated = DateTime.Now, idUser = userClient.idUser }; UserAuthentificationBL.CreateUserAuthentication(userAuth); string urlDefinePwd = string.Format("{0}/User/DefinePassword?token={1}", urlAccessClient, token); string urlResetPwd = string.Format("{0}/User/ResetPassword?token={1}", urlAccessClient, token); string urlHome = string.Format("{0}/Home/Index/{1}?d={2}", urlAccessClient, idCustomer, direction); subject = LanguageContentBL.Translate("mailReportInviteCustomerToFillAndSign");//Mise à jour et signature des informations relatives à votre situation et votre patrimoine if (canUpdateInfo) // case when Adviser sends to customer an unfilled report { var emailTemplate = EmailManager.GetEmailTemplateContentByName(EmailManager.Report_InviteCustomerToFillAndSign); body = String.Format(emailTemplate, userAdviser.UserFirstName, userAdviser.UserName, urlHome, urlResetPwd, urlDefinePwd); } else { var emailTemplate = EmailManager.GetEmailTemplateContentByName(EmailManager.Report_InviteCustomerToSignAfterAdviserSignature); body = String.Format(emailTemplate, userAdviser.UserFirstName, userAdviser.UserName, urlHome, urlResetPwd, urlDefinePwd); } } else // Inform client that adviser has signed the Report { subject = string.Format(LanguageContentBL.Translate("mailReportInformCustomerAdviserHasSigned"), userAdviser.UserFirstName, userAdviser.UserName);//Confirmation de la signature sur le recueil d'informations par votre conseiller var emailTemplate = EmailManager.GetEmailTemplateContentByName(EmailManager.Report_InformCustomerAdviserHasSigned); body = String.Format(emailTemplate, userAdviser.UserFirstName, userAdviser.UserName, report.DateAdviserSignature.Value.ToString("dd/MM/yyyy"), report.DateCustomerSignature.Value.ToString("dd/MM/yyyy"), urlAccessClient); } Upsilab.Business.Utility.EmailManager.SendEmail(from, to, null, subject, body, true); //Log mail EmailLogBL.Log(userAdviser.idUser, from, userClient.idUser, to, EmailLogBL.TypeDestinataire.Client, System.Reflection.MethodBase.GetCurrentMethod().Name); } catch(Exception ex) { Log.Log.AppendException(ex); } }
public static bool SendAlertEmailToUpdate_LAB_CNI_Passport(Data.Model.CustomerProspect customerProspect, string typeRelance, bool isAutomatic = false) { bool isSent = true; try { bool bProdServer = (Upsilab.Business.Utility.ConfigurationManager.ServerType == Upsilab.Business.Utility.ConfigurationManager.EnumServerType.PROD.ToString()) ? true : false; var userClient = customerProspect.User; var userAdvisor = customerProspect.User1; if (!string.IsNullOrEmpty(userAdvisor.UserEmail)) { var host = System.Configuration.ConfigurationManager.AppSettings["WebHostAddress"]; string siteUrl = string.Format("{0}/User", host); string token = HttpServerUtility.UrlTokenEncode(new System.Text.ASCIIEncoding().GetBytes((UserBL.CreateSecureToken(userAdvisor)))); string urlResetPwd = string.Format("{0}/User/ResetPassword?token={1}", siteUrl, token); var template = string.Empty; String emailMessage = string.Empty; String subject = string.Empty; String from = ConfigurationManager.EmailFrom; String to = ConfigurationManager.EmailTo; switch (typeRelance) { case TypeRelanceLAB: { template = EmailManager.GetEmailTemplateContentByName(EmailManager.LAB_AlertAdviserToUpdate, isAutomatic, userAdvisor); subject = "Alerte de mise à jour de données LAB"; break; } case TypeRelanceCNI: { template = EmailManager.GetEmailTemplateContentByName(EmailManager.CNI_AlertAdviserToUpdate, isAutomatic, userAdvisor); subject = "Alerte de mise à jour de données CNI"; break; } case TypeRelancePASSEPORT: { template = EmailManager.GetEmailTemplateContentByName(EmailManager.PASSEPORT_AlertAdviserToUpdate, isAutomatic, userAdvisor); subject = "Alerte de mise à jour de données PASSEPORT"; break; } } emailMessage = String.Format(template , userClient.UserFirstName , userClient.UserName , siteUrl , urlResetPwd); //String subject = LanguageContentBL.Translate("mailLABAlertSubject"); //Ceci utilise cache et ne fonctionne pas sous console to = userAdvisor.UserEmail; //Toujours envoyer au conseiller pour ces 3 documents from = userClient.UserEmail; //Nécessaire pour la determination du nom de l'établissemnt if (!bProdServer) //preprod { subject = "TEST - " + subject; to = ConfigurationManager.EmailTo; } EmailManager.SendEmail(from, to, String.Empty, subject, emailMessage, true); //Log mail EmailLogBL.Log(null, from, customerProspect.idUserCreated, userAdvisor.UserEmail, EmailLogBL.TypeDestinataire.Adviser, System.Reflection.MethodBase.GetCurrentMethod().Name); UserAuthentication userAuth = new UserAuthentication() { UserAuthToken = token, IsValid = true, DateCreated = DateTime.Now, idUser = userAdvisor.idUser }; UserAuthentificationBL.CreateUserAuthentication(userAuth); } } catch (Exception ex) { isSent = false; Log.Log.AppendException(ex); } return isSent; }
public static void SendAgreementMailToClient(Upsilab.Data.Model.CustomerProspect customer, bool inviteClientToSign) { try { Upsilab.Data.Model.User userClient = customer.User; Upsilab.Data.Model.User userAdviser = (customer.ConfidentialityAgreement != null && customer.ConfidentialityAgreement.User != null) ? customer.ConfidentialityAgreement.User : customer.User1; string from = userAdviser.UserEmail; string to = userClient.UserEmail; string subject = string.Empty; string body = string.Empty; string direction = "EC"; string idCustomer = customer.idCustomer.ToString(); string urlAccessClient = string.Format("{0}/Client", Upsilab.Business.Utility.UrlHelper.GetHost()); //Invite client to sign if (inviteClientToSign) { string token = System.Web.HttpServerUtility.UrlTokenEncode(new System.Text.ASCIIEncoding().GetBytes((Upsilab.Business.User.UserBL.CreateSecureToken(userClient)))); //Token for access client UserAuthentication userAuth = new UserAuthentication() { UserAuthToken = token, IsValid = true, DateCreated = DateTime.Now, idUser = userClient.idUser }; UserAuthentificationBL.CreateUserAuthentication(userAuth); string urlDefinePwd = string.Format("{0}/User/DefinePassword?token={1}&d={2}", urlAccessClient, token, direction); string urlResetPwd = string.Format("{0}/User/ResetPassword?token={1}&d={2}", urlAccessClient, token, direction); string urlHome = string.Format("{0}/Home/Index/{1}/?d={2}", urlAccessClient, idCustomer, direction); subject = LanguageContentBL.Translate("mailAgreementInviteCustomerToSign");//Signature de l'engagement de confidentialité var emailTemplate = EmailManager.GetEmailTemplateContentByName(EmailManager.Agreement_InviteCustomerToSign); body = String.Format(emailTemplate, userAdviser.UserFirstName, userAdviser.UserName, urlHome, urlResetPwd, urlDefinePwd); } else // Inform client that adviser has signed the Report { subject = string.Format(LanguageContentBL.Translate("mailAgreementInformCustomerAdviserHasSigned"), userAdviser.UserFirstName, userAdviser.UserName);//Confirmation de la signature de l'engagement de confidentialité par votre conseiller {0} {1} var emailTemplate = EmailManager.GetEmailTemplateContentByName(EmailManager.Agreement_InformCustomerAdviserHasSigned); body = String.Format(emailTemplate, userAdviser.UserFirstName, userAdviser.UserName, customer.ConfidentialityAgreement.DateAdviserSignature.Value.ToString("dd/MM/yyyy"), customer.ConfidentialityAgreement.DateCustomerSignature.Value.ToString("dd/MM/yyyy"), urlAccessClient); } Upsilab.Business.Utility.EmailManager.SendEmail(from, to, null, subject, body, true); //Log mail EmailLogBL.Log(userAdviser.idUser, from, userClient.idUser, to, EmailLogBL.TypeDestinataire.Client, System.Reflection.MethodBase.GetCurrentMethod().Name); } catch (Exception ex) { Log.Log.AppendException(ex); if (inviteClientToSign) { throw new Exception(ex.Message); } else { // PS : On log seulement l'erreur car ici c'est juste un envoi mail, le processus de signature a été deja effectué } } // laisser l'erreur atteindre le codebehind de l'IHM }
/// <summary> /// Send reminder email to CGP /// </summary> /// <param name="userAdviser">The current user</param> /// <param name="listClients">List of client</param> /// <param name="statusIndex">Index of the client status (3,4,7 or 8)</param> /// <returns></returns> public static string SendReminderMailToCgp(Upsilab.Data.Model.User userAdviser, List<ClientViewModel> listClients, int statusIndex) { //statusIndex = 3 <=> Conformité KYC plus à jour //statusIndex = 4 <=> Conformité non renseigné //statusIndex = 7 <=> LAB n'est plus à jour //statusIndex = 8 <=> Auncune étude LAB réalisée string isOk = "OK"; try { //ID List de tous les CGP var idcgplist = listClients.Select(x => x.IdUserCgp).Distinct(); foreach (var idcgp in idcgplist) { Upsilab.Data.Model.User userClient = UserBL.GetUserById(idcgp); var from = userAdviser.UserEmail; var to = userClient.UserEmail; var subject = "Informations Clients à mettre à jour"; var body = string.Empty; var emailTemplate = string.Empty; var urlAccessCGP = string.Format("{0}/user", Upsilab.Business.Utility.UrlHelper.GetHost()); //Invite CGP to approve or sign var token = System.Web.HttpServerUtility.UrlTokenEncode(new System.Text.ASCIIEncoding().GetBytes((Upsilab.Business.User.UserBL.CreateSecureToken(userClient)))); //Token for access client var userAuth = new UserAuthentication() { UserAuthToken = token, IsValid = true, DateCreated = DateTime.Now, idUser = userClient.idUser }; UserAuthentificationBL.CreateUserAuthentication(userAuth); var urlDefinePwd = string.Format("{0}/User/DefinePassword?token={1}", urlAccessCGP, token); var urlResetPwd = string.Format("{0}/User/ResetPassword?token={1}", urlAccessCGP, token); //var urlLogin = string.Format("{0}/User/Login", urlAccessCGP); //ENVOI MAIL----------------------------------------------------- //List de tous les clients du CGP en ligne (du parcours) var listClientsForCgp = listClients.Where(c => c.IdUserCgp == idcgp).Select(x => x); string clientsAvecRecLab = string.Empty; string clientsSansRecLab = string.Empty; foreach (ClientViewModel c in listClientsForCgp) { if (c.avoirRecLab) { clientsAvecRecLab = clientsAvecRecLab + c.Client.UserName + " " + c.Client.UserFirstName + "<br/>"; } else { clientsSansRecLab = clientsSansRecLab + c.Client.UserName + " " + c.Client.UserFirstName + "<br/>"; } } if (!string.IsNullOrEmpty(clientsAvecRecLab)) { if (statusIndex <= 4) { //Recueil à mettre à jour pour les clients ayant Recueil/LAB : emailTemplate = EmailManager.GetEmailTemplateContentByName(EmailManager.RecueilToUpdate_ClientWhithRecLab); } else { //LAB à mettre à jour pour les clients ayant Recueil/LAB : emailTemplate = EmailManager.GetEmailTemplateContentByName(EmailManager.LabToUpdate_ClientWhithRecLab); } body = String.Format(emailTemplate, userClient.UserName, clientsAvecRecLab, urlDefinePwd, urlResetPwd, "mailto:[email protected]"); Upsilab.Business.Utility.EmailManager.SendEmail(from, to, null, subject, body, true); //Log mail EmailLogBL.Log(userAdviser.idUser, from, userClient.idUser, to, EmailLogBL.TypeDestinataire.Adviser, System.Reflection.MethodBase.GetCurrentMethod().Name); } if (!string.IsNullOrEmpty(clientsSansRecLab)) { if (statusIndex <= 4) { //Recueil à mettre à jour pour les clients n’ayant pas Recueil/LAB : emailTemplate = EmailManager.GetEmailTemplateContentByName(EmailManager.RecueilToUpdate_ClientWhithoutRecLab); } else { //LAB à mettre à jour pour les clients n’ayant pas Recueil/LAB : emailTemplate = EmailManager.GetEmailTemplateContentByName(EmailManager.LabToUpdate_ClientWhithoutRecLab); } body = string.Format(emailTemplate, userClient.UserName, clientsSansRecLab, urlDefinePwd, urlResetPwd, "mailto:[email protected]"); Upsilab.Business.Utility.EmailManager.SendEmail(from, to, null, subject, body, true); //Log mail EmailLogBL.Log(userAdviser.idUser, from, userClient.idUser, to, EmailLogBL.TypeDestinataire.Adviser, System.Reflection.MethodBase.GetCurrentMethod().Name); } } //------------------------------------------------------------ } catch (Exception ex) { isOk = "KO"; Log.Log.AppendException(ex); } return isOk; }