diff --git a/Authentication/MongoAuth/DatabaseConfig.cs b/Authentication/MongoAuth/DatabaseConfig.cs index cc02fae..acdd091 100644 --- a/Authentication/MongoAuth/DatabaseConfig.cs +++ b/Authentication/MongoAuth/DatabaseConfig.cs @@ -10,9 +10,9 @@ internal static class DatabaseConfig static DatabaseConfig() { - Host = !string.IsNullOrEmpty(ConfigurationManager.AppSettings["data:MongoHost"]) ? - ConfigurationManager.AppSettings["data:MongoHost"] : - "localhost"; + Host = !string.IsNullOrEmpty(ConfigurationManager.AppSettings["data:MongoHost"]) + ? ConfigurationManager.AppSettings["data:MongoHost"] + : "localhost"; int _port; bool success = int.TryParse(ConfigurationManager.AppSettings["data:MongoPort"], out _port); @@ -22,9 +22,9 @@ static DatabaseConfig() } Port = _port; - Database = !string.IsNullOrEmpty(ConfigurationManager.AppSettings["data:MongoDB"]) ? - ConfigurationManager.AppSettings["data:MongoDB"] : - "MongoAuth"; + Database = !string.IsNullOrEmpty(ConfigurationManager.AppSettings["data:MongoDB"]) + ? ConfigurationManager.AppSettings["data:MongoDB"] + : "MongoAuth"; } } } \ No newline at end of file diff --git a/Authentication/MongoAuth/MongoMembershipProvider.cs b/Authentication/MongoAuth/MongoMembershipProvider.cs index efb8077..cfab4e3 100644 --- a/Authentication/MongoAuth/MongoMembershipProvider.cs +++ b/Authentication/MongoAuth/MongoMembershipProvider.cs @@ -1,7 +1,4 @@ -using MongoDB.Bson; -using MongoDB.Bson.Serialization.Attributes; -using MongoDB.Driver; -using System; +using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; @@ -9,12 +6,15 @@ using System.Text; using System.Threading.Tasks; using System.Web.Security; +using MongoDB.Bson; +using MongoDB.Bson.Serialization.Attributes; +using MongoDB.Driver; namespace MongoAuth { public class MongoMembershipProvider : MembershipProvider { - private const string _memberCollectionName = "members"; + private const string MEMBER_COLLECTION_NAME = "members"; private bool _enablePasswordReset = true; private int _maxInvalidPasswordAttempts = 5; @@ -57,18 +57,18 @@ public override void Initialize(string name, NameValueCollection config) base.Initialize(name, config); - _enablePasswordReset = tryReadBool(config["enablePasswordReset"], _enablePasswordReset); - _maxInvalidPasswordAttempts = tryReadInt(config["maxInvalidPasswordAttempts"], _maxInvalidPasswordAttempts); - _minRequiredNonAlphanumericCharacters = tryReadInt(config["minRequiredNonAlphanumericCharacters"], _minRequiredNonAlphanumericCharacters); - _minRequriedPasswordLength = tryReadInt(config["minRequriedPasswordLength"], _minRequriedPasswordLength); - _passwordAttemptWindow = tryReadInt(config["passwordAttemptWindow"], _passwordAttemptWindow); - _requiresUniqueEmail = tryReadBool(config["requiresUniqueEmail"], _requiresUniqueEmail); + _enablePasswordReset = TryReadBool(config["enablePasswordReset"], _enablePasswordReset); + _maxInvalidPasswordAttempts = TryReadInt(config["maxInvalidPasswordAttempts"], _maxInvalidPasswordAttempts); + _minRequiredNonAlphanumericCharacters = TryReadInt(config["minRequiredNonAlphanumericCharacters"], _minRequiredNonAlphanumericCharacters); + _minRequriedPasswordLength = TryReadInt(config["minRequriedPasswordLength"], _minRequriedPasswordLength); + _passwordAttemptWindow = TryReadInt(config["passwordAttemptWindow"], _passwordAttemptWindow); + _requiresUniqueEmail = TryReadBool(config["requiresUniqueEmail"], _requiresUniqueEmail); - _dbClient = new MongoClient(new MongoClientSettings() + _dbClient = new MongoClient(new MongoClientSettings { Server = new MongoServerAddress(DatabaseConfig.Host, DatabaseConfig.Port) }); - _memberCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection(_memberCollectionName); + _memberCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection(MEMBER_COLLECTION_NAME); } public override bool ChangePassword(string username, string oldPassword, string newPassword) @@ -77,11 +77,9 @@ public override bool ChangePassword(string username, string oldPassword, string if (isAuthenticated) { - var task = _memberCollection - .Find(m => m.UserName.ToLower() == username.ToLower()) - .SingleOrDefaultAsync(); + Task task = _memberCollection.Find(m => m.UserName.ToLower() == username.ToLower()).SingleOrDefaultAsync(); task.Wait(); - var mm = task.Result; + MongoMember mm = task.Result; if (mm == null) { @@ -89,13 +87,12 @@ public override bool ChangePassword(string username, string oldPassword, string } byte[] salt = new byte[24]; - byte[] hash = calculateHash(newPassword, ref salt); + byte[] hash = CalculateHash(newPassword, ref salt); mm.PassSalt = salt; mm.PassHash = hash; - var replaceTask = _memberCollection - .ReplaceOneAsync(m => m.Id == mm.Id, mm); + Task replaceTask = _memberCollection.ReplaceOneAsync(m => m.Id == mm.Id, mm); replaceTask.Wait(); return replaceTask.IsCompleted; @@ -104,10 +101,7 @@ public override bool ChangePassword(string username, string oldPassword, string return false; } - public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) - { - throw new NotImplementedException(); - } + public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) { throw new NotImplementedException(); } public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { @@ -119,12 +113,8 @@ public override MembershipUser CreateUser(string username, string password, stri MembershipUser mu = null; - var dupeUsers = _memberCollection - .Find(m => m.UserName.ToLower() == username.ToLower()) - .CountAsync(); - var dupeEmails = _memberCollection - .Find(m => m.EmailAddress.ToLower() == email.ToLower()) - .CountAsync(); + Task dupeUsers = _memberCollection.Find(m => m.UserName.ToLower() == username.ToLower()).CountAsync(); + Task dupeEmails = _memberCollection.Find(m => m.EmailAddress.ToLower() == email.ToLower()).CountAsync(); dupeUsers.Wait(); dupeEmails.Wait(); @@ -139,34 +129,30 @@ public override MembershipUser CreateUser(string username, string password, stri else { byte[] salt = new byte[24]; - byte[] hash = calculateHash(password, ref salt); + byte[] hash = CalculateHash(password, ref salt); - MongoMember mm = new MongoMember() + MongoMember mm = new MongoMember { Id = Guid.NewGuid(), UserName = username, PassHash = hash, PassSalt = salt, EmailAddress = email, - IsApproved = false, IsLockedOut = false, - CreationDate = DateTime.Now, LastLoginDate = DateTime.MinValue, LastActivityDate = DateTime.MinValue, LastLockoutDate = DateTime.MinValue }; - var insertTask = _memberCollection - .InsertOneAsync(mm); + Task insertTask = _memberCollection.InsertOneAsync(mm); insertTask.Wait(); if (insertTask.Status == TaskStatus.RanToCompletion) { - status = MembershipCreateStatus.Success; - mu = new MembershipUser(this.Name, mm.UserName, mm.Id, mm.EmailAddress, "", "", mm.IsApproved, mm.IsLockedOut, mm.CreationDate, mm.LastLoginDate, mm.LastActivityDate, DateTime.MinValue, mm.LastLockoutDate); + mu = new MembershipUser(Name, mm.UserName, mm.Id, mm.EmailAddress, "", "", mm.IsApproved, mm.IsLockedOut, mm.CreationDate, mm.LastLoginDate, mm.LastActivityDate, DateTime.MinValue, mm.LastLockoutDate); } else { @@ -179,110 +165,85 @@ public override MembershipUser CreateUser(string username, string password, stri public override bool DeleteUser(string username, bool deleteAllRelatedData) { - var task = _memberCollection - .DeleteOneAsync(m => m.UserName.ToLower() == username.ToLower()); + Task task = _memberCollection.DeleteOneAsync(m => m.UserName.ToLower() == username.ToLower()); task.Wait(); return task.Result.IsAcknowledged && task.Result.DeletedCount == 1; } - public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) - { - throw new NotImplementedException(); - } + public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } - public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) - { - throw new NotImplementedException(); - } + public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { MembershipUserCollection muc = new MembershipUserCollection(); - var users = _memberCollection - .Find(new BsonDocument()); + IFindFluent users = _memberCollection.Find(new BsonDocument()); - var totalRecordsTask = users - .CountAsync(); + Task totalRecordsTask = users.CountAsync(); totalRecordsTask.Wait(); totalRecords = Convert.ToInt32(totalRecordsTask.Result); - users = users - .Skip(pageIndex * pageSize) - .Limit(pageSize); - var pageItemsTask = users.ToListAsync(); + users = users.Skip(pageIndex * pageSize).Limit(pageSize); + Task> pageItemsTask = users.ToListAsync(); pageItemsTask.Wait(); - foreach (var mm in pageItemsTask.Result) + foreach (MongoMember mm in pageItemsTask.Result) { - muc.Add(new MembershipUser(this.Name, mm.UserName, mm.Id, mm.EmailAddress, "", "", mm.IsApproved, mm.IsLockedOut, mm.CreationDate, mm.LastLoginDate, mm.LastActivityDate, DateTime.MinValue, mm.LastLockoutDate)); + muc.Add(new MembershipUser(Name, mm.UserName, mm.Id, mm.EmailAddress, "", "", mm.IsApproved, mm.IsLockedOut, mm.CreationDate, mm.LastLoginDate, mm.LastActivityDate, DateTime.MinValue, mm.LastLockoutDate)); } return muc; } - public override int GetNumberOfUsersOnline() - { - throw new NotImplementedException(); - } + public override int GetNumberOfUsersOnline() { throw new NotImplementedException(); } - public override string GetPassword(string username, string answer) - { - throw new NotImplementedException(); - } + public override string GetPassword(string username, string answer) { throw new NotImplementedException(); } public override MembershipUser GetUser(string username, bool userIsOnline) { - var task = _memberCollection - .Find(f => f.UserName.ToLower() == username.ToLower()) - .FirstOrDefaultAsync(); + Task task = _memberCollection.Find(f => f.UserName.ToLower() == username.ToLower()).FirstOrDefaultAsync(); task.Wait(); - var mm = task.Result; + MongoMember mm = task.Result; - return mm == null ? null : new MembershipUser(this.Name, mm.UserName, mm.Id, mm.EmailAddress, "", "", mm.IsApproved, mm.IsLockedOut, mm.CreationDate, mm.LastLoginDate, mm.LastActivityDate, DateTime.MinValue, mm.LastLockoutDate); + return mm == null + ? null + : new MembershipUser(Name, mm.UserName, mm.Id, mm.EmailAddress, "", "", mm.IsApproved, mm.IsLockedOut, mm.CreationDate, mm.LastLoginDate, mm.LastActivityDate, DateTime.MinValue, mm.LastLockoutDate); } public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { - var task = _memberCollection - .Find(f => f.Id == (Guid)providerUserKey) - .FirstOrDefaultAsync(); + Task task = _memberCollection.Find(f => f.Id == (Guid)providerUserKey).FirstOrDefaultAsync(); task.Wait(); - var mm = task.Result; + MongoMember mm = task.Result; - return mm == null ? null : new MembershipUser(this.Name, mm.UserName, mm.Id, mm.EmailAddress, "", "", mm.IsApproved, mm.IsLockedOut, mm.CreationDate, mm.LastLoginDate, mm.LastActivityDate, DateTime.MinValue, mm.LastLockoutDate); + return mm == null + ? null + : new MembershipUser(Name, mm.UserName, mm.Id, mm.EmailAddress, "", "", mm.IsApproved, mm.IsLockedOut, mm.CreationDate, mm.LastLoginDate, mm.LastActivityDate, DateTime.MinValue, mm.LastLockoutDate); } public override string GetUserNameByEmail(string email) { - var task = _memberCollection - .Find(f => f.EmailAddress.ToLower() == email.ToLower()) - .FirstOrDefaultAsync(); + Task task = _memberCollection.Find(f => f.EmailAddress.ToLower() == email.ToLower()).FirstOrDefaultAsync(); task.Wait(); return task.Result.UserName; } - public override string ResetPassword(string username, string answer) - { - throw new NotImplementedException(); - } + public override string ResetPassword(string username, string answer) { throw new NotImplementedException(); } - public void ChangeApproval(Guid Id, bool newStatus) + public void ChangeApproval(Guid id, bool newStatus) { - var task = _memberCollection - .UpdateOneAsync( - Builders.Filter.Eq(u => u.Id, Id), - Builders.Update.Set(u => u.IsApproved, newStatus)); + Task task = _memberCollection.UpdateOneAsync(Builders.Filter.Eq(u => u.Id, id), Builders.Update.Set(u => u.IsApproved, newStatus)); task.Wait(); } - public void ChangeLockStatus(Guid Id, bool newStatus) + public void ChangeLockStatus(Guid id, bool newStatus) { - var updateDefinition = new List>(); + List> updateDefinition = new List>(); updateDefinition.Add(Builders.Update.Set(u => u.IsLockedOut, newStatus)); if (newStatus) @@ -295,50 +256,40 @@ public void ChangeLockStatus(Guid Id, bool newStatus) updateDefinition.Add(Builders.Update.Set(u => u.LastLockoutDate, DateTime.MinValue)); } - var task = _memberCollection - .UpdateOneAsync( - Builders.Filter.Eq(u => u.Id, Id), - Builders.Update.Combine(updateDefinition)); + Task task = _memberCollection.UpdateOneAsync(Builders.Filter.Eq(u => u.Id, id), Builders.Update.Combine(updateDefinition)); task.Wait(); } public override bool UnlockUser(string userName) { - var task = _memberCollection - .UpdateOneAsync( - Builders.Filter.Eq(m => m.UserName.ToLower(), userName.ToLower()), - Builders.Update.Set(m => m.IsLockedOut, false)); + Task task = _memberCollection.UpdateOneAsync(Builders.Filter.Eq(m => m.UserName.ToLower(), userName.ToLower()), Builders.Update.Set(m => m.IsLockedOut, false)); task.Wait(); return task.Result.IsAcknowledged && task.Result.ModifiedCount == 1; } - public override void UpdateUser(MembershipUser user) - { - throw new NotImplementedException(); - } + public override void UpdateUser(MembershipUser user) { throw new NotImplementedException(); } public override bool ValidateUser(string username, string password) { - var task = _memberCollection - .Find(f => f.UserName.ToLower() == username.ToLower()) - .FirstOrDefaultAsync(); + Task task = _memberCollection.Find(f => f.UserName.ToLower() == username.ToLower()).FirstOrDefaultAsync(); task.Wait(); - var mm = task.Result; + MongoMember mm = task.Result; - if (mm == null || !(mm.IsApproved && !mm.IsLockedOut)) + if (mm == null + || !(mm.IsApproved && !mm.IsLockedOut)) { return false; } byte[] salt = mm.PassSalt; - byte[] hash = calculateHash(password, ref salt); + byte[] hash = CalculateHash(password, ref salt); bool isFail = false; for (int i = 0; i > hash.Length; i++) { - isFail |= (hash[i] != mm.PassHash[i]); + isFail |= hash[i] != mm.PassHash[i]; } @@ -375,16 +326,13 @@ public override bool ValidateUser(string username, string password) mm.LockoutWindowAttempts = 0; } - var updTask = _memberCollection - .ReplaceOneAsync( - Builders.Filter.Eq(u => u.Id, mm.Id), - mm); + Task updTask = _memberCollection.ReplaceOneAsync(Builders.Filter.Eq(u => u.Id, mm.Id), mm); updTask.Wait(); return !isFail; } - private static byte[] calculateHash(string password, ref byte[] salt) + private static byte[] CalculateHash(string password, ref byte[] salt) { if (!salt.Any(v => v != 0)) { @@ -405,18 +353,22 @@ private static byte[] calculateHash(string password, ref byte[] salt) return hash; } - private static bool tryReadBool(string config, bool defaultValue) + private static bool TryReadBool(string config, bool defaultValue) { - bool temp = false; + bool temp; bool success = bool.TryParse(config, out temp); - return success ? temp : defaultValue; + return success + ? temp + : defaultValue; } - private static int tryReadInt(string config, int defaultValue) + private static int TryReadInt(string config, int defaultValue) { - int temp = 0; + int temp; bool success = int.TryParse(config, out temp); - return success ? temp : defaultValue; + return success + ? temp + : defaultValue; } } @@ -441,5 +393,4 @@ public class MongoMember public DateTime LockoutWindowStart { get; set; } public int LockoutWindowAttempts { get; set; } } - -} +} \ No newline at end of file diff --git a/Authentication/MongoAuth/MongoRoleProvider.cs b/Authentication/MongoAuth/MongoRoleProvider.cs index cbc8b2b..04ea0e5 100644 --- a/Authentication/MongoAuth/MongoRoleProvider.cs +++ b/Authentication/MongoAuth/MongoRoleProvider.cs @@ -1,254 +1,217 @@ -using MongoDB.Bson; +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Configuration.Provider; +using System.Linq; +using System.Threading.Tasks; +using System.Web.Security; +using MongoAuth.Properties; +using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Driver; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Web.Security; -using System.Collections.Specialized; -using System.Configuration.Provider; namespace MongoAuth { - public class MongoRoleProvider : RoleProvider - { - private const string _roleCollectionName = "roles"; - private const string _memberCollectionName = "members"; - private MongoClient _dbClient; - private IMongoCollection _roleCollection; - private IMongoCollection _memberCollection; + public class MongoRoleProvider : RoleProvider + { + private const string MEMBER_COLLECTION_NAME = "members"; + private const string ROLE_COLLECTION_NAME = "roles"; + private MongoClient _dbClient; + private IMongoCollection _roleCollection; + private IMongoCollection _memberCollection; - public override string ApplicationName - { - get { return ""; } - set { } - } + public override string ApplicationName + { + get { return ""; } + set { } + } - public override void Initialize(string name, NameValueCollection config) - { - base.Initialize(name, config); + public override void Initialize(string name, NameValueCollection config) + { + base.Initialize(name, config); - _dbClient = new MongoClient(new MongoClientSettings() + _dbClient = new MongoClient(new MongoClientSettings + { + Server = new MongoServerAddress(DatabaseConfig.Host, DatabaseConfig.Port) + }); + + _roleCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection(ROLE_COLLECTION_NAME); + _memberCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection(MEMBER_COLLECTION_NAME); + } + + public override void AddUsersToRoles(string[] usernames, string[] roleNames) + { + Task> roleTask = _roleCollection.Find(r => roleNames.Contains(r.RoleName)).ToListAsync(); + roleTask.Wait(); + List roles = roleTask.Result; + + Task> userTask = _memberCollection.Find(u => usernames.Contains(u.UserName)).ToListAsync(); + userTask.Wait(); + List users = userTask.Result; + + for (int i = 0; i < roles.Count; i++) + { + List newUsers = new List(); + + if (roles[i].Users != null) { - Server = new MongoServerAddress(DatabaseConfig.Host, DatabaseConfig.Port) - }); - - _roleCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection(_roleCollectionName); - _memberCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection(_memberCollectionName); - } - - public override void AddUsersToRoles(string[] usernames, string[] roleNames) - { - var roleTask = _roleCollection - .Find(r => roleNames.Contains(r.RoleName)) - .ToListAsync(); - roleTask.Wait(); - List roles = roleTask.Result; - - var userTask = _memberCollection - .Find(u => usernames.Contains(u.UserName)) - .ToListAsync(); - userTask.Wait(); - List users = userTask.Result; - - for (int i = 0; i < roles.Count; i++) - { - List newUsers = new List(); - - if (roles[i].Users != null) - { - newUsers.AddRange(roles[i].Users); - } - - var usersToAdd = from u in users - where !newUsers.Any(v => v == u.Id) - select u.Id; - - newUsers.AddRange(usersToAdd); - - roles[i].Users = newUsers.ToArray(); - - var update = _roleCollection - .ReplaceOneAsync(Builders.Filter.Eq(r => r.Id, roles[i].Id), roles[i]); - update.Wait(); - } - } - - public override void CreateRole(string roleName) - { - MongoRole r = new MongoRole() - { - Id = Guid.NewGuid(), - RoleName = roleName - }; - - var task = _roleCollection - .InsertOneAsync(r); - task.Wait(); - } - - public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) - { - var role = _roleCollection - .Find(r => r.RoleName == roleName) - .SingleOrDefaultAsync(); - role.Wait(); - - if (role.Result != null && role.Result.Users.Length > 0 && throwOnPopulatedRole) - { - throw new ProviderException(Properties.Resources.RoleNotEmpty); + newUsers.AddRange(roles[i].Users); } - var task = _roleCollection - .DeleteOneAsync(r => r.RoleName == roleName); - task.Wait(); + IEnumerable usersToAdd = from u in users + where newUsers.All(v => v != u.Id) + select u.Id; - return true; - } + newUsers.AddRange(usersToAdd); - public override string[] FindUsersInRole(string roleName, string usernameToMatch) - { - var role = _roleCollection - .Find(r => r.RoleName == roleName) - .SingleOrDefaultAsync(); - role.Wait(); + roles[i].Users = newUsers.ToArray(); - if (role == null) - { - return Array.Empty(); - } + Task update = _roleCollection.ReplaceOneAsync(Builders.Filter.Eq(r => r.Id, roles[i].Id), roles[i]); + update.Wait(); + } + } - var users = _memberCollection - .Find(u => role.Result.Users.Contains(u.Id) && u.UserName.ToLower().Contains(usernameToMatch.ToLower())) - .ToListAsync(); - users.Wait(); + public override void CreateRole(string roleName) + { + MongoRole r = new MongoRole + { + Id = Guid.NewGuid(), + RoleName = roleName + }; - return users.Result - .Select(r => r.UserName) - .ToArray(); - } + Task task = _roleCollection.InsertOneAsync(r); + task.Wait(); + } - public override string[] GetAllRoles() - { - var roles = _roleCollection - .Find(new BsonDocument()) - .ToListAsync(); - roles.Wait(); + public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) + { + Task role = _roleCollection.Find(r => r.RoleName == roleName).SingleOrDefaultAsync(); + role.Wait(); - return roles.Result - .Select(r => r.RoleName) - .ToArray(); - } + if (role.Result != null + && role.Result.Users.Length > 0 + && throwOnPopulatedRole) + { + throw new ProviderException(Resources.RoleNotEmpty); + } - public override string[] GetRolesForUser(string username) - { - var user = _memberCollection - .Find(u => u.UserName.ToLower() == username.ToLower()) - .SingleOrDefaultAsync(); - user.Wait(); + Task task = _roleCollection.DeleteOneAsync(r => r.RoleName == roleName); + task.Wait(); - if (user == null) - { - return Array.Empty(); - } + return true; + } - var role = _roleCollection - .Find(r => r.Users != null && r.Users.Contains(user.Result.Id)) - .ToListAsync(); - role.Wait(); + public override string[] FindUsersInRole(string roleName, string usernameToMatch) + { + Task role = _roleCollection.Find(r => r.RoleName == roleName).SingleOrDefaultAsync(); + role.Wait(); - return role.Result - .Select(r => r.RoleName) - .ToArray(); - } + if (role.Result == null) + { + return Array.Empty(); + } - public override string[] GetUsersInRole(string roleName) - { - var role = _roleCollection - .Find(r => r.RoleName == roleName) - .SingleOrDefaultAsync(); - role.Wait(); + Task> users = _memberCollection.Find(u => role.Result.Users.Contains(u.Id) && u.UserName.ToLower().Contains(usernameToMatch.ToLower())).ToListAsync(); + users.Wait(); - if (role == null) - { - return Array.Empty(); - } + return users.Result.Select(r => r.UserName).ToArray(); + } - var users = _memberCollection - .Find(u => role.Result.Users.Contains(u.Id)) - .ToListAsync(); - users.Wait(); + public override string[] GetAllRoles() + { + Task> roles = _roleCollection.Find(new BsonDocument()).ToListAsync(); + roles.Wait(); - return users.Result - .Select(u => u.UserName) - .ToArray(); - } + return roles.Result.Select(r => r.RoleName).ToArray(); + } - public override bool IsUserInRole(string username, string roleName) - { - var user = _memberCollection - .Find(u => u.UserName.ToLower() == username.ToLower()) - .SingleOrDefaultAsync(); - var role = _roleCollection - .Find(r => r.RoleName == roleName) - .SingleOrDefaultAsync(); - user.Wait(); - role.Wait(); + public override string[] GetRolesForUser(string username) + { + Task user = _memberCollection.Find(u => u.UserName.ToLower() == username.ToLower()).SingleOrDefaultAsync(); + user.Wait(); - if (user.Result == null || role.Result == null || role.Result.Users == null) - { - return false; - } + if (user.Result == null) + { + return Array.Empty(); + } - return role.Result.Users.Contains(user.Result.Id); - } + Task> role = _roleCollection.Find(r => r.Users != null && r.Users.Contains(user.Result.Id)).ToListAsync(); + role.Wait(); - public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) - { - var roleTask = _roleCollection - .Find(r => roleNames.Contains(r.RoleName)) - .ToListAsync(); - roleTask.Wait(); - List roles = roleTask.Result; + return role.Result.Select(r => r.RoleName).ToArray(); + } - var userTask = _memberCollection - .Find(u => usernames.Contains(u.UserName)) - .ToListAsync(); - userTask.Wait(); - List users = userTask.Result; + public override string[] GetUsersInRole(string roleName) + { + Task role = _roleCollection.Find(r => r.RoleName == roleName).SingleOrDefaultAsync(); + role.Wait(); - for (int i = 0; i < roles.Count; i++) - { - roles[i].Users = (from u in roles[i].Users - where !users.Any(v => v.Id == u) - select u).ToArray(); + if (role.Result == null) + { + return Array.Empty(); + } - var update = _roleCollection - .ReplaceOneAsync(Builders.Filter.Eq(r => r.Id, roles[i].Id), roles[i]); - update.Wait(); - } - } + Task> users = _memberCollection.Find(u => role.Result.Users.Contains(u.Id)).ToListAsync(); + users.Wait(); - public override bool RoleExists(string roleName) - { - var role = _roleCollection - .Find(r => r.RoleName == roleName) - .SingleOrDefaultAsync(); - role.Wait(); + return users.Result.Select(u => u.UserName).ToArray(); + } - return role.Result != null; - } - } + public override bool IsUserInRole(string username, string roleName) + { + Task user = _memberCollection.Find(u => u.UserName.ToLower() == username.ToLower()).SingleOrDefaultAsync(); + Task role = _roleCollection.Find(r => r.RoleName == roleName).SingleOrDefaultAsync(); + user.Wait(); + role.Wait(); - [DataObject] - public class MongoRole - { - [BsonId] - public Guid Id { get; set; } + if (user.Result == null + || role.Result?.Users == null) + { + return false; + } - public string RoleName { get; set; } + return role.Result.Users.Contains(user.Result.Id); + } - public Guid[] Users { get; set; } - } + public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) + { + Task> roleTask = _roleCollection.Find(r => roleNames.Contains(r.RoleName)).ToListAsync(); + roleTask.Wait(); + List roles = roleTask.Result; + + Task> userTask = _memberCollection.Find(u => usernames.Contains(u.UserName)).ToListAsync(); + userTask.Wait(); + List users = userTask.Result; + + foreach (MongoRole t in roles) + { + t.Users = (from u in t.Users + where users.All(v => v.Id != u) + select u).ToArray(); + + Task update = _roleCollection.ReplaceOneAsync(Builders.Filter.Eq(r => r.Id, t.Id), t); + update.Wait(); + } + } + + public override bool RoleExists(string roleName) + { + Task role = _roleCollection.Find(r => r.RoleName == roleName).SingleOrDefaultAsync(); + role.Wait(); + + return role.Result != null; + } + } + + [DataObject] + public class MongoRole + { + [BsonId] + public Guid Id { get; set; } + + public string RoleName { get; set; } + + public Guid[] Users { get; set; } + } } \ No newline at end of file diff --git a/BuildFeed/App_Start/FilterConfig.cs b/BuildFeed/App_Start/FilterConfig.cs index f668540..b4f34d4 100644 --- a/BuildFeed/App_Start/FilterConfig.cs +++ b/BuildFeed/App_Start/FilterConfig.cs @@ -4,9 +4,6 @@ namespace BuildFeed { public class FilterConfig { - public static void RegisterGlobalFilters(GlobalFilterCollection filters) - { - filters.Add(new HandleErrorAttribute()); - } + public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } } \ No newline at end of file diff --git a/BuildFeed/App_Start/MongoConfig.cs b/BuildFeed/App_Start/MongoConfig.cs index d3717af..511ee19 100644 --- a/BuildFeed/App_Start/MongoConfig.cs +++ b/BuildFeed/App_Start/MongoConfig.cs @@ -1,6 +1,5 @@ -using BuildFeed.Models; -using System.Configuration; -using System.Threading.Tasks; +using System.Configuration; +using BuildFeed.Models; namespace BuildFeed { @@ -12,9 +11,9 @@ internal static class MongoConfig static MongoConfig() { - Host = !string.IsNullOrEmpty(ConfigurationManager.AppSettings["data:MongoHost"]) ? - ConfigurationManager.AppSettings["data:MongoHost"] : - "localhost"; + Host = !string.IsNullOrEmpty(ConfigurationManager.AppSettings["data:MongoHost"]) + ? ConfigurationManager.AppSettings["data:MongoHost"] + : "localhost"; int _port; bool success = int.TryParse(ConfigurationManager.AppSettings["data:MongoPort"], out _port); @@ -24,9 +23,9 @@ static MongoConfig() } Port = _port; - Database = !string.IsNullOrEmpty(ConfigurationManager.AppSettings["data:MongoDB"]) ? - ConfigurationManager.AppSettings["data:MongoDB"] : - "MongoAuth"; + Database = !string.IsNullOrEmpty(ConfigurationManager.AppSettings["data:MongoDB"]) + ? ConfigurationManager.AppSettings["data:MongoDB"] + : "MongoAuth"; } public static void SetupIndexes() diff --git a/BuildFeed/App_Start/RouteConfig.cs b/BuildFeed/App_Start/RouteConfig.cs index 322305a..9325e88 100644 --- a/BuildFeed/App_Start/RouteConfig.cs +++ b/BuildFeed/App_Start/RouteConfig.cs @@ -11,12 +11,14 @@ public static void RegisterRoutes(RouteCollection routes) routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.AppendTrailingSlash = true; - routes.MapHttpRoute("API", "api/{action}/{id}", new - { - controller = "api", - action = "GetBuilds", - id = UrlParameter.Optional - }); + routes.MapHttpRoute("API", + "api/{action}/{id}", + new + { + controller = "api", + action = "GetBuilds", + id = UrlParameter.Optional + }); routes.MapMvcAttributeRoutes(); } } diff --git a/BuildFeed/Areas/admin/Controllers/metaController.cs b/BuildFeed/Areas/admin/Controllers/metaController.cs index d90a61b..b19968a 100644 --- a/BuildFeed/Areas/admin/Controllers/metaController.cs +++ b/BuildFeed/Areas/admin/Controllers/metaController.cs @@ -82,11 +82,12 @@ public async Task create(MetaItemModel meta) public async Task edit(MetaType type, string value) { - return View("create", await _mModel.SelectById(new MetaItemKey - { - Type = type, - Value = value - })); + return View("create", + await _mModel.SelectById(new MetaItemKey + { + Type = type, + Value = value + })); } [HttpPost] diff --git a/BuildFeed/Areas/admin/Controllers/usersController.cs b/BuildFeed/Areas/admin/Controllers/usersController.cs index adf6760..2a5ef2d 100644 --- a/BuildFeed/Areas/admin/Controllers/usersController.cs +++ b/BuildFeed/Areas/admin/Controllers/usersController.cs @@ -67,7 +67,8 @@ public ActionResult cleanup() foreach (MembershipUser user in users) { - if (!user.IsApproved && (user.CreationDate.AddDays(30) < DateTime.Now)) + if (!user.IsApproved + && (user.CreationDate.AddDays(30) < DateTime.Now)) { Membership.DeleteUser(user.UserName); } diff --git a/BuildFeed/Areas/admin/Views/_ViewStart.cshtml b/BuildFeed/Areas/admin/Views/_ViewStart.cshtml index 1906fb1..b43c42a 100644 --- a/BuildFeed/Areas/admin/Views/_ViewStart.cshtml +++ b/BuildFeed/Areas/admin/Views/_ViewStart.cshtml @@ -1,3 +1,3 @@ @{ - Layout = "~/Views/shared/_default.cshtml"; -} + Layout = "~/Views/shared/_default.cshtml"; +} \ No newline at end of file diff --git a/BuildFeed/Areas/admin/Views/base/index.cshtml b/BuildFeed/Areas/admin/Views/base/index.cshtml index cea9e2d..70037e2 100644 --- a/BuildFeed/Areas/admin/Views/base/index.cshtml +++ b/BuildFeed/Areas/admin/Views/base/index.cshtml @@ -19,4 +19,4 @@
  • @Html.ActionLink("Exception test", "exception")
  • @Html.ActionLink("Initial setup", "setup")
  • } - + \ No newline at end of file diff --git a/BuildFeed/Areas/admin/Views/meta/create.cshtml b/BuildFeed/Areas/admin/Views/meta/create.cshtml index ad71eac..0d77a5b 100644 --- a/BuildFeed/Areas/admin/Views/meta/create.cshtml +++ b/BuildFeed/Areas/admin/Views/meta/create.cshtml @@ -1,9 +1,9 @@ @model BuildFeed.Models.MetaItemModel @{ - ViewBag.Title = string.Format("Add metadata for {0} | BuildFeed", Model.Id.Value); + ViewBag.Title = $"Add metadata for {Model.Id.Value} | BuildFeed"; } -

    @string.Format("Add metadata for {0}", Model.Id.Value)

    +

    @($"Add metadata for {Model.Id.Value}")

    @using (Html.BeginForm()) @@ -15,9 +15,16 @@
    - @Html.LabelFor(model => model.MetaDescription, htmlAttributes: new { @class = "control-label" }) + @Html.LabelFor(model => model.MetaDescription, new + { + @class = "control-label" + })
    - @Html.TextAreaFor(model => model.MetaDescription, new { @class = "form-control", rows = "2" }) + @Html.TextAreaFor(model => model.MetaDescription, new + { + @class = "form-control", + rows = "2" + })
    0 characters @Html.ValidationMessageFor(model => model.MetaDescription) @@ -26,9 +33,15 @@
    - @Html.LabelFor(model => model.PageContent, new { @class = "control-label" }) + @Html.LabelFor(model => model.PageContent, new + { + @class = "control-label" + })
    - @Html.TextAreaFor(model => model.PageContent, new { @class = "form-control" }) + @Html.TextAreaFor(model => model.PageContent, new + { + @class = "form-control" + })
    @Html.ValidationMessageFor(model => model.PageContent)
    @@ -53,36 +66,44 @@