/// <summary> /// Deletes the specified directory and, if indicated, /// any subdirectories and files in the directory. /// </summary> /// <param name="path">The path.</param> /// <param name="user">The user.</param> /// <param name="recursive">if set to <c>true</c> [recursive].</param> /// <param name="debug">if set to <c>true</c> [debug].</param> /// <returns></returns> public static FileOperationResult DeleteDirectory(string path, DomainUser user, bool recursive = false, bool debug = false) { FileOperationResult result; // ReSharper disable once UnusedVariable using ( var impersonation = new Impersonation(user.Domain, user.Name, user.Pwd, ImpersonationLevel.Delegation)) { if (Directory.Exists(path)) { try { Directory.Delete(path, recursive); result = new FileOperationResult(path, FileOperation.Delete, true); } catch (Exception ex) { Log.Error(ex); result = new FileOperationResult(path, FileOperation.Delete, ex); } } else { result = new FileOperationResult(path, FileOperation.Delete, false, "Directory not Found"); } } return result; }
/// <summary> /// Determines whether the specified file exists. /// </summary> /// <returns> /// true if the caller has the required permissions and FullName contains the name of an existing file; /// otherwise, false. /// This method also returns false if FullName is null, an invalid path, /// or a zero-length string. /// If the caller does not have sufficient permissions to read the specified file, /// no exception is thrown and the method returns false regardless of the existence of FullName. /// </returns> public static bool Exists(this FileInfo fileInfo, DomainUser user) { // ReSharper disable once UnusedVariable using ( var impersonation = new Impersonation(user.Domain, user.Name, user.Pwd, ImpersonationLevel.Delegation)) { return File.Exists(fileInfo.FullName); } }
public virtual bool Check(string name, string password) { DomainUser user = new DomainUser(name); if (user.Domain == null || user.UserName == null) { return(false); } using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, user.Domain)) { return(pc.ValidateCredentials(user.UserName, password)); } }
private static void AddBlogPosts(ApplicationDbContext db, DomainUser creator) { if (!db.BlogPosts.Any()) { var faker = new Faker(); var categories = new string[] { "Branding", "Design", "Development", "Strategy" }; var blogPosts = new List <BlogPost>(); for (int i = 0; i < 5; i++) { blogPosts.Add(new BlogPost(creator) { Title = faker.Lorem.Sentence(faker.Random.Number(3, 7)), Category = faker.PickRandom(categories), ImagePath = faker.Image.PicsumUrl(faker.Random.Number(500, 900), faker.Random.Number(500, 900)), Content = faker.Lorem.Paragraphs(faker.Random.Number(5, 20), "<br /><br />") }); Thread.Sleep(100); } blogPosts.Add(new BlogPost(creator) { Title = "User Interface Designing Elements", Category = "Design", ImagePath = "~/images/blog-2.jpeg", Content = faker.Lorem.Paragraphs(faker.Random.Number(5, 20), "<br /><br />") }); Thread.Sleep(100); blogPosts.Add(new BlogPost(creator) { Title = "Startup ideas needs to be funded", Category = "Development", ImagePath = "~/images/blog-1.jpeg", Content = faker.Lorem.Paragraphs(faker.Random.Number(5, 20), "<br /><br />") }); try { blogPosts.ForEach(blogPost => { db.BlogPosts.Add(blogPost); db.SaveChanges(); }); } catch (Exception ex) { throw new DataInitializeException("Unable to add 'BlogPosts'.", ex); } } }
public ActionResult AddOU(DomainUser user) { string filePath = Server.MapPath("~/ADConfig.xml"); AdOperate ado = new AdOperate(filePath); DirectoryEntry entry = ado.GetEntry(); string filter = "(&(objectclass=organizationalUnit)(ou=行政部))"; DirectoryEntry ouEntry = ado.GetOUEntry(entry, filter); //DirectoryEntry userEntry = ado.GetUserEntry(entry,"yilidan"); //JavaScriptSerializer js = new JavaScriptSerializer(); return(Json(new AjaxResult { Status = "error", Msg = "想不通", Data = entry.Path + ":::" + ouEntry.Path + ":::" + user.Name })); }
public async Task Remove_users_from_group_sends_messages() { // Arrange DomainGroup existingGroup = _fakers.DomainGroup.Generate(); DomainUser existingUserWithSameGroup1 = _fakers.DomainUser.Generate(); existingUserWithSameGroup1.Group = existingGroup; DomainUser existingUserWithSameGroup2 = _fakers.DomainUser.Generate(); existingUserWithSameGroup2.Group = existingGroup; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Users.AddRange(existingUserWithSameGroup1, existingUserWithSameGroup2); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "domainUsers", id = existingUserWithSameGroup2.StringId } } }; string route = $"/domainGroups/{existingGroup.StringId}/relationships/users"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync <string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); var messageBroker = _testContext.Factory.Services.GetRequiredService <MessageBroker>(); messageBroker.SentMessages.Should().HaveCount(1); var content = messageBroker.SentMessages[0].GetContentAs <UserRemovedFromGroupContent>(); content.UserId.Should().Be(existingUserWithSameGroup2.Id); content.GroupId.Should().Be(existingGroup.Id); }
public bool LoadPosition() { log.WriteLogEntry("Begin LoadPosition..."); bool result = false; if (CurrentUser.GetType() == typeof(DomainUser)) { DomainUser user = (DomainUser)CurrentUser; log.WriteLogEntry("Loading position number " + user.PositionNumber); string cmdString = string.Format(@"select * from {0}.dbo.position where position_number = @positionNumber", dbName); using (SqlConnection conn = new SqlConnection(dataConnectionString)) { try { conn.Open(); using (SqlCommand cmd = new SqlCommand(cmdString, conn)) { cmd.Parameters.AddWithValue("@positionNumber", user.PositionNumber); using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.SingleResult)) { if (rdr.Read()) { user.Position.PositionNumber = (int)rdr["position_number"]; user.Position.PostiionTitle = rdr["position_title"].ToString(); user.Position.PositionDescription = rdr["position_description"].ToString(); log.WriteLogEntry(string.Format("Position loaded {0} {1} {2}", user.Position.PositionNumber, user.Position.PostiionTitle, user.Position.PositionDescription)); result = true; } } } } catch (SqlException ex) { log.WriteLogEntry("SQL error " + ex.Message); } catch (Exception ex) { log.WriteLogEntry("General program error " + ex.Message); } } } else { log.WriteLogEntry("FAILED not a domain user!"); } log.WriteLogEntry("End LoadPosition."); return(result); }
// GET api/accounts/emails public async Task <HttpResponseMessage> Get() { DomainUser user = await _userService.GetAsync(UserId); var emails = new List <ProfileEmail>(); if (!string.IsNullOrEmpty(user.Email)) { emails.Add(new ProfileEmail { Email = user.Email }); } return(Request.CreateResponse(HttpStatusCode.OK, emails)); }
/// <summary> /// moves the files. /// </summary> /// <param name="sourceFiles">The files.</param> /// <param name="destination">the copy target path</param> /// <param name="overwrite">determines if the files at target should be overwriten.</param> /// <param name="user">The user.</param> /// <param name="debug">if set to <c>true</c> [debug].</param> /// <returns></returns> public static List <FileOperationResult> MoveFiles( IEnumerable <FileInfo> sourceFiles, string destination, bool overwrite, DomainUser user, bool debug = false) { var results = new List <FileOperationResult>(); // ReSharper disable once UnusedVariable using ( var impersonation = new Impersonation(user.Domain, user.Name, user.Pwd, ImpersonationLevel.Delegation)) { results.AddRange(sourceFiles.Select(file => MoveFile(file, destination, overwrite, debug))); } return(results); }
/// <summary> /// Copies the files. /// </summary> /// <param name="sourceFiles">The files.</param> /// <param name="destination">the copy target path</param> /// <param name="overwrite">determines if the files at target should be overwriten.</param> /// <param name="user">The user.</param> /// <param name="debug">if set to <c>true</c> [debug].</param> /// <returns></returns> public static List<FileOperationResult> CopyFiles( IEnumerable<FileInfo> sourceFiles, string destination, bool overwrite, DomainUser user, bool debug = false) { var results = new List<FileOperationResult>(); // ReSharper disable once UnusedVariable using ( var impersonation = new Impersonation(user.Domain, user.Name, user.Pwd, ImpersonationLevel.Delegation)) { results.AddRange(sourceFiles.Select(file => CopyFile(file, destination, overwrite, debug))); } return results; }
bool AddUser(DomainUser newUser, RoleDB role) { /* CREATE LOGIN "PNG\GazeevAP" FROM WINDOWS; CREATE USER "PNG\GazeevAP"; EXEC sp_addrolemember 'db_datareader', "PNG\GazeevAP" */ string fullUserName = GetFullUserName(newUser); using (SqlConnection conn = new SqlConnection(_connectionString)) { conn.Open(); SqlCommand comm = new SqlCommand(); comm.Connection = conn; comm.CommandText = "CREATE LOGIN \"" + fullUserName + "\" FROM WINDOWS;"; try { comm.ExecuteNonQuery(); } catch (Exception exc) { MessageBox.Show(exc.Message, "Create login", MessageBoxButtons.OK, MessageBoxIcon.Warning); } comm.CommandText = "CREATE USER \"" + fullUserName + "\";"; try { comm.ExecuteNonQuery(); } catch (Exception exc) { MessageBox.Show(exc.Message, "Create user", MessageBoxButtons.OK, MessageBoxIcon.Warning); } comm.CommandText = "EXEC sp_addrolemember \"" + role.Role + "\", \"" + fullUserName + "\";"; try { comm.ExecuteNonQuery(); } catch (Exception exc) { MessageBox.Show(exc.Message, "Add user to the role", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } } return true; }
private async Task <DomainUser> CompleteRegistrationAsync(TokenData tokenData) { DomainUser user = null; // Create new profile try { user = await _userService.AddAsync(CreateDomainUser(tokenData)); } catch (Exception e) { Trace.TraceError("Authentication failed for '{0}:{1}': {2}", tokenData.IdentityProvider, tokenData.UserIdentifier, e); throw; } // Send registration e-mail try { await _emailNotificationService.SendRegistrationEmailAsync(user); } catch (Exception e) { Trace.TraceError("Failed to send registration email to address {0} for user {1}: {2}", user.Email, user.Id, e); } // Send notification into social network ISocialNetworkNotifier notifier = _notificationFactory.GetNotifier(tokenData.IdentityProvider); if (notifier != null) { try { await notifier.SendWelcomeMessageAsync(user, tokenData); } catch (BadGatewayException) { } catch (Exception e) { Trace.TraceError("Failed to send welcome message to user '{0}': {1}", user.Id, e); } } //For statistics HttpContext.Items.Add("isRegister", true); return(user); }
// // GET: /api/clients /// <summary> /// Gets client profile information. /// </summary> /// <returns>Client profile information.</returns> public async Task <HttpResponseMessage> Get() { // Get profile DomainUser user = await _userService.GetAsync(UserId); // Get company DomainCompany company = await _companyService.FindByUserAsync(UserId); Client client = _mapper.Map <Tuple <DomainUser, DomainCompany>, Client>(new Tuple <DomainUser, DomainCompany>(user, company)); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, client); response.SetLastModifiedDate(user.Modified); return(response); }
private IEnumerable <DomainUser> GetTestUserCollection() { var users = new DomainUser[] { new DomainUser(new UserIdentity("user1", "*****@*****.**"), new UserProfile("FirstName #1", "LastName #1", "Job #1", "Path #1")), new DomainUser(new UserIdentity("user2", "*****@*****.**"), new UserProfile("FirstName #2", "LastName #2", "Job #2", "Path #2")), new DomainUser(new UserIdentity("user3", "*****@*****.**"), new UserProfile("FirstName #3", "LastName #3", "Job #3", "Path #3")) }; foreach (var user in users) { user.Profile.AddSocialLinks(GetTestSocialLinks()); user.Profile.ChangeDisplayStatus(true); } return(users); }
public object[] SearchFile(DateTime start, DateTime end, string user, string drive, string file) { StringBuilder filter = new StringBuilder(); filter.AppendFormat(" '{0:yyyy-MM-dd}'<=date(StartTime) AND date(StartTime)<='{1:yyyy-MM-dd}' ", start, end); if (!string.IsNullOrEmpty(user) && ValidUser(user)) { var domainUser = DomainUser.Create(user); if (domainUser != null) { filter.AppendFormat(" AND Domain='{0}' AND UserName='******'", domainUser.Domain, domainUser.UserName); } } if (!string.IsNullOrEmpty(drive) && ValidDrive(drive)) { filter.AppendFormat(" AND UrlHost='{0}' ", drive); } else { filter.AppendFormat(" AND UrlHost LIKE '_:'"); } if (!string.IsNullOrEmpty(file) && ValidKey(file)) { filter.AppendFormat(" AND WindowUrl LIKE 'file:///%{0}%' ", file); } var segments = Database.Execute(db => db.SelectObjects <SnapshotGroup>("SearchUrl", filter.ToString(), "SessionDate", "SessionId", "Domain", "UserName", "StartTime", "EndTime", "UrlHost", "WindowUrl", "SnapshotCount")); List <object> objs = new List <object>(); foreach (var sg in segments) { objs.Add(new { SID = sg.SID, Date = sg.SessionDate, User = sg.User, Host = sg.UrlHost, Time = sg.TimeRange, Url = sg.WindowUrl, Count = sg.SnapshotCount, }); } return(objs.ToArray()); }
public async Task SendNewRecoveryMail(DomainUser user, string validationPath) { string guid = Guid.NewGuid().ToString(); DateTime expires = DateTime.UtcNow.Add(_expirationTime); var recoveryLink = new RecoveryLink { ExpirationDate = expires, Id = guid }; PasswordRecoveryEntity entity = _passwordRecoveryFactory.CreateDefault(user.Id, guid, user.Email, expires); PasswordRecoveryEntity recoveryEntity = await _passwordRecoverRepository.AddAsync(entity); string linkRoot = _settings.PortalUri + validationPath; string linkText = _recoveryLinkService.CreateRecoveryLinkText(recoveryLink, linkRoot); Email emailToSend = ComposeRecoveryMail(recoveryEntity, user.Name, linkText); await _mailerRepository.SendMail(emailToSend); }
public async Task <bool> SendVerificationEmailAsync(string token, DomainUser user) { var encodedToken = WebUtility.UrlEncode(token); var encodedEmail = WebUtility.UrlEncode(user.Email); var endpoint = $"{_serverSettings.BaseUrl}/api/account/verify_email?token={encodedToken}&email={encodedEmail}"; var messageText = $"<p><a href='{endpoint}' target='_blank'>Click here</a> to confirm your email.</p>" + $"<p>Please ignore this if you did not request it.</p>"; var emailMessage = new EmailMessage { Subject = "Email Confirmation", Content = messageText, Reciever = user.Email }; return(await _emailClientService.SendEmailAsync(emailMessage)); }
public async Task Replace_group_for_user_writes_to_outbox() { // Arrange DomainUser existingUser = _fakers.DomainUser.Generate(); existingUser.Group = _fakers.DomainGroup.Generate(); DomainGroup existingGroup = _fakers.DomainGroup.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync <OutgoingMessage>(); dbContext.AddRange(existingUser, existingGroup); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "domainGroups", id = existingGroup.StringId } }; string route = $"/domainUsers/{existingUser.StringId}/relationships/group"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync <string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { List <OutgoingMessage> messages = await dbContext.OutboxMessages.OrderBy(message => message.Id).ToListAsync(); messages.Should().HaveCount(1); var content = messages[0].GetContentAs <UserMovedToGroupContent>(); content.UserId.Should().Be(existingUser.Id); content.BeforeGroupId.Should().Be(existingUser.Group.Id); content.AfterGroupId.Should().Be(existingGroup.Id); }); }
private static JObject CreateAuditMatrixParameters(DomainUser user) { return(JObject.FromObject(new { resourceType = "App", resourceRef = new { }, subjectRef = new { resourceFilter = $"userid eq '{user.UserId}' and userdirectory eq '{user.UserDirectory}'" }, actions = 46, environmentAttributes = "", subjectProperties = new string[] { "id", "name", "userId", "userDirectory" }, auditLimit = 1000, outputObjectsPrivileges = 2 })); }
private static void AddBrands(ApplicationDbContext db, DomainUser creator) { if (!db.Brands.Any()) { var brands = new List <Brand> { new Brand(creator) { ImagePath = "~/images/client-1.png", Name = "Deorham Networks" }, new Brand(creator) { ImagePath = "~/images/client-2.png", Name = "Ratings" }, new Brand(creator) { ImagePath = "~/images/client-3.png", Name = "Malik Media" }, new Brand(creator) { ImagePath = "~/images/client-4.png", Name = "Bcause" }, new Brand(creator) { ImagePath = "~/images/client-5.png", Name = "Wompify" } }; try { brands.ForEach(brand => { db.Brands.Add(brand); db.SaveChanges(); }); } catch (Exception ex) { throw new DataInitializeException("Unable to add 'Brands'.", ex); } } }
private static Uri QlikConnectionCheck(string configJson, string serverUrl) { try { logger.Debug($"Use Url: {serverUrl}"); if (String.IsNullOrEmpty(serverUrl)) { logger.Info("No special url set up in the configuration file."); return(null); } dynamic configObject = JObject.Parse(configJson); var serverUri = new Uri($"{serverUrl}"); if (!serverUrl.EndsWith("/ser")) { var uriBuilder = new UriBuilder(serverUrl) { Path = "ser" }; serverUri = uriBuilder.Uri; } configObject.connection.serverUri = serverUri; ConnectorConfig connectorConfig = JsonConvert.DeserializeObject <ConnectorConfig>(configObject.ToString()); ServerCertificateValidation.Connection = connectorConfig.Connection; var qlikUser = new DomainUser("INTERNAL\\ser_scheduler"); var taskManager = new SessionHelper(); var session = taskManager.GetSession(connectorConfig.Connection, new QlikRequest() { QlikUser = qlikUser }); if (session?.Cookie != null) { logger.Info("The connection to Qlik Sense was successful."); return(serverUri); } logger.Warn($"Connection check to qlik with url '{serverUrl}' was not successfully..."); return(null); } catch (Exception ex) { logger.Error(ex, "The connection check to qlik has an error"); return(null); } }
/// <summary> /// Gets the files at target. /// </summary> /// <param name="path">The path.</param> /// <param name="user">the Domain User</param> /// <param name="recursive"></param> /// <param name="debug">if set to <c>true</c> [debug].</param> /// <returns></returns> public static List <FileInfo> GetFiles(string path, DomainUser user, bool recursive, bool debug = false) { if (string.IsNullOrEmpty(user.Domain) || string.IsNullOrEmpty(user.Name) || string.IsNullOrEmpty(user.Pwd)) { return(GetFiles(path, recursive)); } // ReSharper disable once UnusedVariable using ( var impersonation = new Impersonation(user.Domain, user.Name, user.Pwd, ImpersonationLevel.Delegation)) { return(GetFiles(path, recursive)); } }
private IList <BlogPost> GetTestBlogPostCollection() { var creator = new DomainUser(new UserIdentity()); var blogPosts = new List <BlogPost>(); for (int i = 1; i < 5; i++) { blogPosts.Add(new BlogPost(int.Parse($"10{i}"), creator) { Title = $"Title #{i}", ImagePath = $"Path #{i}", Category = $"Category #{i}", Content = $"Content #{i}" }); Thread.Sleep(100); } return(blogPosts); }
public async Task AccessTokenAsync_Bad_BadRequest() { var testUser = new DomainUser(new UserIdentity("Test UserName", "Test Email")); _mockUserService.Setup(x => x.GetUserAsync("Test UserName")).ReturnsAsync(testUser); var actionResult = await _target.AccessTokenAsync(GetTestUserCredentials()); Assert.IsType <BadRequestObjectResult>(actionResult.Result); Assert.Null(actionResult.Value); var result = actionResult.Result as BadRequestObjectResult; Assert.IsType <OperationDetails>(result.Value); var details = result.Value as OperationDetails; Assert.True(details.IsError); Assert.Equal("Invalid password.", details.Message); }
public async Task SendWelcomeMessageAsync(DomainUser user, TokenData data) { string facebookMessage = _settings.FacebookRegistrationMessage; if (String.IsNullOrEmpty(facebookMessage)) { return; } if (data == null || string.IsNullOrEmpty(data.Token)) { throw new ArgumentNullException("data"); } JObject message = JObject.Parse(facebookMessage); var fb = new FacebookClient(data.Token); var post = new { caption = (string)message["caption"], message = (string)message["message"], name = (string)message["name"], description = (string)message["description"], picture = (string)message["picture"], link = (string)message["link"] }; try { await fb.PostTaskAsync("me/feed", post); } catch (FacebookOAuthException e) { //Permission error if (e.ErrorCode != 200) { throw new BadRequestException(e); } } catch (WebExceptionWrapper e) { throw new BadGatewayException(e); } }
public async Task Replace_group_for_user_sends_messages() { // Arrange DomainUser existingUser = _fakers.DomainUser.Generate(); existingUser.Group = _fakers.DomainGroup.Generate(); DomainGroup existingGroup = _fakers.DomainGroup.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddRange(existingUser, existingGroup); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "domainGroups", id = existingGroup.StringId } }; string route = $"/domainUsers/{existingUser.StringId}/relationships/group"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync <string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); var messageBroker = _testContext.Factory.Services.GetRequiredService <MessageBroker>(); messageBroker.SentMessages.Should().HaveCount(1); var content = messageBroker.SentMessages[0].GetContentAs <UserMovedToGroupContent>(); content.UserId.Should().Be(existingUser.Id); content.BeforeGroupId.Should().Be(existingUser.Group.Id); content.AfterGroupId.Should().Be(existingGroup.Id); }
public object[] SearchText(DateTime start, DateTime end, string user, string prog, string text) { StringBuilder filter = new StringBuilder(); filter.AppendFormat(" '{0:yyyy-MM-dd}'<=date(StartTime) AND date(StartTime)<='{1:yyyy-MM-dd}' ", start, end); filter.Append(" AND length(trim(InputText)) > 0 "); if (!string.IsNullOrEmpty(user) && ValidUser(user)) { var domainUser = DomainUser.Create(user); if (domainUser != null) { filter.AppendFormat(" AND Domain='{0}' AND UserName='******'", domainUser.Domain, domainUser.UserName); } } if (!string.IsNullOrEmpty(prog) && ValidProgram(prog)) { filter.AppendFormat(" AND ProcessName='{0}' ", prog); } if (!string.IsNullOrEmpty(text) && ValidKey(text)) { filter.AppendFormat(" AND InputText LIKE '%{0}%' ", text); } var segments = Database.Execute(db => db.SelectObjects <SnapshotGroup>("SearchText", filter.ToString(), "SessionDate", "SessionId", "Domain", "UserName", "ProcessName", "WindowTitle", "StartTime", "EndTime", "InputText", "SnapshotCount")); List <object> objs = new List <object>(); foreach (var sg in segments) { objs.Add(new { Date = sg.SessionDate, User = sg.User, Prog = sg.ProcessName, Title = sg.WindowTitle, Text = sg.Text, SID = sg.SessionId, Time = sg.TimeRange, Count = sg.SnapshotCount, }); } return(objs.ToArray()); }
public bool InsertDomainUserSession(DomainUser user) { log.WriteLogEntry("Begin InsertDomainLoginUser..."); bool result = false; string dbServer = WebConfigurationManager.AppSettings.Get("LoginServer"); string dbName = WebConfigurationManager.AppSettings.Get("LoginDB"); UserSession session = new UserSession(user.UserID) { CompanyNumber = user.CompanyNumber, DeptNumber = user.DepartmentNumber, PositionNumber = user.PositionNumber, DomainNumber = user.CompanyNumber, RoleNumber = user.SecurityRoles.FirstOrDefault().RoleNumber, AccessLevel = user.SecurityAccess.FirstOrDefault().AccessNumber, UserName = user.UserName, UserEmail = user.UserEmail, FirstName = user.FirstName, LastName = user.LastName, EmployeeID = user.EmployeeID, DeptName = user.Department.DeptName, DeptHeadName = user.Department.DeptHeadName, DeptHeadEmail = user.Department.DeptHeadEmail, DomainUserName = user.DomainUserName, DomainUpn = user.DomainUpn, SessionKey = user.Token.SessionKey, Authenicated = user.Authenicated, StartTime = DateTime.Now }; log.WriteLogEntry("Starting UserDataHandler..."); UserDataHandler userData = new UserDataHandler(dbServer, dbName); if (userData.InsertUserSession(session)) { result = true; } else { log.WriteLogEntry("Failed inserting domain login user!"); } log.WriteLogEntry("End InsertDomainLoginUser."); return(result); }
private string GetADUser(string gourp, string name) { string json = string.Empty; Yawei.Domain.Domain domain = new Yawei.Domain.Domain(); if (name.Trim() != "") { SearchResultCollection searchResultCollection = Yawei.Domain.Domain.ExecuteSearchResult(domain.GetDirectoryEntry(domain.DistinguishedName), "(&(objectCategory=person)(objectClass=user)(CN=*" + name + "*))", SearchScope.Subtree); json += "{"; json += "\"total\":" + searchResultCollection.Count.ToString() + ",\"rows\":["; for (int i = 0; i < searchResultCollection.Count; i++) { DomainUser user = domain.GetUser(searchResultCollection[i].GetDirectoryEntry().Guid.ToString()); json += "{\"UserGuid\":\"" + user.Guid.ToString() + "\",\"UserDN\":\"" + user.DN + "\",\"UserCN\":\"" + user.CN + "\",\"UserLoginName\":\"" + user.LoginName + "\",\"UserType\":\"AD\"}"; if (i + 1 < searchResultCollection.Count) { json += ","; } } json += "]}"; } else { using (DomainOU domainOU = domain.GetOU(gourp)) { SearchResultCollection searchResultCollection = Yawei.Domain.Domain.ExecuteSearchResult(domainOU, "(&(objectCategory=person)(objectClass=user))", SearchScope.OneLevel);;//Yawei.Domain.Domain.ExecuteSearchResult(domainOU, "(&(objectCategory=person)(objectClass=user))", SearchScope.OneLevel); json += "{"; json += "\"total\":" + searchResultCollection.Count.ToString() + ",\"rows\":["; for (int i = 0; i < searchResultCollection.Count; i++) { DomainUser user = domain.GetUser(searchResultCollection[i].GetDirectoryEntry().Guid.ToString()); json += "{\"UserGuid\":\"" + user.Guid.ToString() + "\",\"UserDN\":\"" + user.DN + "\",\"UserCN\":\"" + user.CN + "\",\"UserLoginName\":\"" + user.LoginName + "\",\"UserType\":\"AD\"}"; if (i + 1 < searchResultCollection.Count) { json += ","; } } json += "]}"; } } return(json); }
public async Task <HttpResponseMessage> Post(ProfileEmailModel model) { DomainUser user = await _userService.GetAsync(UserId); // Checks whether user already has same e-mail if (string.Equals(user.Email, model.Email, StringComparison.OrdinalIgnoreCase)) { return(Request.CreateResponse(HttpStatusCode.OK)); } // Change email await _userService.ChangeEmailAsync(user.Id, model.Email); // Update claims user.Email = model.Email; _authenticationService.UpdateIdentityClaims(user); return(Request.CreateResponse(HttpStatusCode.Created, model)); }
private async Task <DomainUser> GetUserByToken(TokenData tokenData) { DomainUser user = null; try { user = await _userService.FindByIdentityAsync(tokenData.IdentityProvider, tokenData.UserIdentifier); } catch (NotFoundException) { } catch (Exception e) { Trace.TraceError("Failed to validate ip user '{0}:{1}': {2}", tokenData.IdentityProvider, tokenData.UserIdentifier, e); throw; } return(user); }
/// <summary> /// Асинхронно удаляет пользователя доменной модели. /// </summary> /// <param name="user">Удаляемый пользователь доменной модели.</param> /// <exception cref="ArgumentNullException"/> /// <exception cref="DataAccessException"/> public async Task DeleteAsync(DomainUser user) { EnsureUserNotNull(user); try { // DbContext настроен на каскадное удаление сущностей UserIdentity->DomainUser->UserProfile->SocialLink. var result = await _userManager.DeleteAsync(user.Identity as UserIdentity); if (!result.Succeeded) { throw new DataAccessException($"An error occurred while deleting identity for user '{user.Identity.UserName}'. " + $"Inspect '{nameof(DataAccessException.Errors)}' property for details.", GetIdentityErrors(result)); } } catch (Exception ex) when(!(ex is DataAccessException)) { throw new DataAccessException(GetExceptionMessage("delete entity"), ex); } }
public bool NotifyGeneralManager(User user) { log.WriteLogEntry("Begin NotifyGeneralManager..."); bool result = false; if (user.GetType() == typeof(DomainUser)) { DomainUser domainUser = (DomainUser)user; log.WriteLogEntry(string.Format("Current User {0} {1} {2} {3} {4}", user.UserID, domainUser.DomainUpn, domainUser.EmployeeID, domainUser.Department, domainUser.Department.DeptHeadEmail)); ExchangeHandler emailHandle = new ExchangeHandler { EmailSubject = "Notify General Manager", RecipientEmailAddress = domainUser.Company.GeneralManagerEmail, EmailBody = "<html><body><p>A department head has approved a request to travel</p><p>go <a href=\"https://bermuda.verawaterandpower.com/?route=travel\"> here to approve</a></p></body></html>" }; try { if (emailHandle.ConnectExchangeService()) { log.WriteLogEntry("Connection to Exchange service successful."); if (emailHandle.SendMail()) { result = true; } else { log.WriteLogEntry("Failed send email!"); } } else { log.WriteLogEntry("Failed connect to Exchange service!"); } } catch (Exception ex) { log.WriteLogEntry("Program error " + ex.Message); } } log.WriteLogEntry("End NotifyGeneralManager."); return(result); }
private static void AddTestimonials(ApplicationDbContext db, DomainUser creator) { if (!db.Testimonials.Any()) { var faker = new Faker(); var testimonials = new List <Testimonial> { new Testimonial(creator) { Author = "John Doe", Company = "Google Inc.", Text = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe fugit perferendis ratione " + "ducimus, modi recusandae eos aperiam blanditiis asperiores autem nulla sint laborum tenetur, " + "amet iste nisi nam adipisci aliquid?" }, new Testimonial(creator) { Author = faker.Person.FullName, Company = faker.Company.CompanyName(), Text = faker.Lorem.Sentences(5, " ") }, new Testimonial(creator) { Author = faker.Person.FullName, Company = faker.Company.CompanyName(), Text = faker.Lorem.Sentences(7, " ") } }; try { testimonials.ForEach(testimonial => { db.Testimonials.Add(testimonial); db.SaveChanges(); }); } catch (Exception ex) { throw new DataInitializeException("Unable to add 'Testimonials'.", ex); } } }
/// <summary> /// Gets the files at target. /// </summary> /// <param name="path">The path.</param> /// <param name="user">the Domain User</param> /// <param name="recursive"></param> /// <param name="debug">if set to <c>true</c> [debug].</param> /// <returns></returns> public static List<FileInfo> GetFiles(string path, DomainUser user, bool recursive, bool debug = false) { if (string.IsNullOrEmpty(user.Domain) || string.IsNullOrEmpty(user.Name) || string.IsNullOrEmpty(user.Pwd)) { return GetFiles(path, recursive, debug); } // ReSharper disable once UnusedVariable using ( var impersonation = new Impersonation(user.Domain, user.Name, user.Pwd, ImpersonationLevel.Delegation)) { return GetFiles(path, recursive, debug); } }
/// <summary> /// Deletes the files. /// </summary> /// <param name="files">The files.</param> /// <param name="user">The user.</param> /// <param name="debug">if set to <c>true</c> [debug].</param> /// <returns></returns> public static List<FileOperationResult> DeleteFiles( IEnumerable<FileInfo> files, DomainUser user, bool debug = false) { return files.Select(file => DeleteFile(file, user, debug)).ToList(); }
/// <summary> /// Deletes the file. /// </summary> /// <param name="file">The file.</param> /// <param name="user">The user.</param> /// <param name="debug">if set to <c>true</c> [debug].</param> /// <returns></returns> public static FileOperationResult DeleteFile(FileInfo file, DomainUser user, bool debug = false) { FileOperationResult result; // ReSharper disable once UnusedVariable using ( var impersonation = new Impersonation(user.Domain, user.Name, user.Pwd, ImpersonationLevel.Delegation)) { try { File.Delete(file.FullName); result = new FileOperationResult(file.FullName, FileOperation.Delete, true); } catch (Exception ex) { Log.Error(ex); result = new FileOperationResult(file.FullName, FileOperation.Delete, ex); } } return result; }
private void btAddUser_Click(object sender, EventArgs e) { DataGridViewRow userCh = dtgAllUsers.CurrentRow; if (userCh == null) { throw new ApplicationException("You must choose user"); } DomainUser user = new DomainUser(userCh.Cells["Domain"].Value.ToString(), userCh.Cells["Account"].Value.ToString(), userCh.Cells["Name"].Value.ToString()); DataGridViewRow roleCh = dtgRoles.CurrentRow; if (roleCh == null) { throw new ApplicationException("You must choose role"); } RoleDB role = new RoleDB(roleCh.Cells["Role"].Value.ToString(), roleCh.Cells["Description"].Value.ToString()); if (!AddUser(user, role)) { throw new ApplicationException("Can not add user to DB"); } MessageBox.Show("User was successfully added", "Add user", MessageBoxButtons.OK, MessageBoxIcon.Information); }
public DomainUserPhotos(DomainUser user, DomainPhotos photos) { User = user; Photos = photos; }
string GetFullUserName(DomainUser user) { return user.Domain + "\\" + user.Account; }