public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { SecUtility.CheckParameter(ref roleName, true, true, true, 256, "roleName"); try { using (var session = new MongoSession(_connectionString)) { var role = (from r in session.Roles where r.RoleName == roleName select r).SingleOrDefault(); var users = session.Users .Where(u => u.Roles != null) .Where(u => u.Roles.Any(r => r.RoleName == roleName)); if (users.Any() && throwOnPopulatedRole) { throw new ProviderException(StringResources.GetString(StringResources.Role_is_not_empty)); } session.DeleteById <MembershipRole>(role.RoleId); return(true); } } catch { throw; } }
public override string[] GetUsersInRole(string roleName) { SecUtility.CheckParameter(ref roleName, true, true, true, 256, "roleName"); try { using (var session = new MongoSession(_connectionString)) { var role = (from r in session.Roles where r.RoleName == roleName select r).SingleOrDefault(); if (role == null) { throw new ProviderException(StringResources.GetString(StringResources.Provider_role_not_found, roleName)); } var users = from u in session.Users where u.Roles.Any(r => r.RoleName == roleName) select u; if (users == null || !users.Any()) { return(new string[0]); } return(users.Select(u => u.UserName).ToArray()); } } catch { throw; } }
public override void CreateRole(string roleName) { SecUtility.CheckParameter(ref roleName, true, true, true, 256, "roleName"); try { using (var session = new MongoSession(_connectionString)) { var roles = from r in session.Roles where r.RoleName == roleName select r; if (roles.Any()) { throw new ProviderException(StringResources.GetString(StringResources.Provider_role_already_exists, roleName)); } var role = new MembershipRole { RoleName = roleName, LoweredRoleName = roleName.ToLowerInvariant() }; session.Add(role); } } catch { throw; } }
// Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method public override bool ResetPasswordWithToken(string token, string newPassword) { VerifyInitialized(); if (string.IsNullOrEmpty(newPassword)) { throw new ArgumentException("Argument_Cannot_Be_Null_Or_Empty", "newPassword"); } using (var session = new MongoSession(_connectionString)) { var user = session.Users.FirstOrDefault(x => x.PasswordVerificationToken == token && x.PasswordVerificationTokenExpirationDate > DateTime.UtcNow); if (user != null) { bool success = SetPassword(session, user, newPassword); if (success) { // Clear the Token on success user.PasswordVerificationToken = null; user.PasswordVerificationTokenExpirationDate = null; try { session.Update(user); } catch (Exception) { throw new ProviderException("Database operation failed."); } } return(success); } else { return(false); } } }
public static void InitializeRoles(Type r, string connectionString) { var session = new MongoSession(connectionString); List <MembershipRole> roles = new List <MembershipRole>(); List <MembershipPermission> permissions = session.Permissions.ToList(); List <string> dbRoles = session.Roles.Select(x => x.RoleName).ToList(); foreach (FieldInfo field in r.GetFields(BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public)) { string value = field.GetRawConstantValue().ToString(); if (!dbRoles.Contains(value)) { MembershipRole role = new MembershipRole { RoleName = value }; if (value == DefaultRoles.Admin) { foreach (var p in permissions) { role.Permissions.Add(p.Name); } } session.Save(role); } } }
/// <summary> /// Sets the confirmed flag for the username if it is correct. /// </summary> /// <returns>True if the account could be successfully confirmed. False if the username was not found or the confirmation token is invalid.</returns> /// <remarks>Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method</remarks> public override bool ConfirmAccount(string userName, string accountConfirmationToken) { VerifyInitialized(); using (var session = new MongoSession(_connectionString)) { // We need to compare the token using a case insensitive comparison however it seems tricky to do this uniformly across databases when representing the token as a string. // Therefore verify the case on the client //session.ConfirmAccount(userTableName, userNameColumn, userIdColumn); var row = session.Users.FirstOrDefault(x => x.ConfirmationToken == accountConfirmationToken && x.UserName == userName); if (row == null) { return(false); } string expectedToken = row.ConfirmationToken; if (String.Equals(accountConfirmationToken, expectedToken, StringComparison.Ordinal)) { try { row.IsConfirmed = true; session.Update(row); } catch (Exception) { return(false); } } return(false); } }
// Ensures the user exists in the accounts table private MembershipAccount VerifyUserNameHasConfirmedAccount(MongoSession session, string userName, bool throwException) { var user = session.Users.FirstOrDefault(x => x.UserName == userName); if (user == null) { if (throwException) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "No user found was found that has the name \"{0}\".", userName)); } else { return(null); } } if (!user.IsConfirmed) { if (throwException) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "No account exists for \"{0}\".", userName)); } else { return(null); } } return(user); }
public override string[] GetRolesForUser(string username) { SecUtility.CheckParameter(ref username, true, false, true, 256, "username"); if (username.Length < 1) { return(new string[0]); } try { using (var session = new MongoSession(_connectionString)) { var user = (from u in session.Users where u.UserName == username select u).SingleOrDefault(); if (user == null) { return(new string[0]); } if (user.Roles == null) { return(new string[0]); } return(user.Roles.Select(r => r.RoleName).ToArray()); } } catch { throw; } }
// Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method public override string GeneratePasswordResetToken(string userName, int tokenExpirationInMinutesFromNow) { VerifyInitialized(); if (string.IsNullOrEmpty(userName)) { throw new ArgumentException("Argument_Cannot_Be_Null_Or_Empty", "userName"); } using (var session = new MongoSession(_connectionString)) { var user = VerifyUserNameHasConfirmedAccount(session, userName, throwException: true); if (user == null) { throw new InvalidOperationException(String.Format("No user found was found that has the name \"{0}\".", userName)); } if (user.PasswordVerificationToken == null || (user.PasswordVerificationToken != null && user.PasswordVerificationTokenExpirationDate > DateTime.UtcNow)) { user.PasswordVerificationToken = GenerateToken(); } try { user.PasswordVerificationTokenExpirationDate = DateTime.UtcNow.AddMinutes(tokenExpirationInMinutesFromNow); session.Save(user); } catch (Exception) { throw new ProviderException("Database operation failed."); } return(user.PasswordVerificationToken); } }
/// <summary> /// Sets the confirmed flag for the username if it is correct. /// </summary> /// <returns>True if the account could be successfully confirmed. False if the username was not found or the confirmation token is invalid.</returns> /// <remarks>Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method. /// There is a tiny possibility where this method fails to work correctly. Two or more users could be assigned the same token but specified using different cases. /// A workaround for this would be to use the overload that accepts both the user name and confirmation token. /// </remarks> public override bool ConfirmAccount(string accountConfirmationToken) { VerifyInitialized(); using (var session = new MongoSession(_connectionString)) { // We need to compare the token using a case insensitive comparison however it seems tricky to do this uniformly across databases when representing the token as a string. // Therefore verify the case on the client var rows = session.Users .Where(x => x.ConfirmationToken == accountConfirmationToken) .ToList() .Where(r => ((string)r.ConfirmationToken).Equals(accountConfirmationToken, StringComparison.Ordinal)) .ToList(); Debug.Assert(rows.Count < 2, "By virtue of the fact that the ConfirmationToken is random and unique, we can never have two tokens that are identical."); if (!rows.Any()) { return(false); } var row = rows.First(); row.IsConfirmed = true; try { session.Update(row); return(true); } catch (Exception) { return(false); } } }
// Not an override ==> Simple Membership MUST be enabled to use this method public int GetUserId(string userName) { VerifyInitialized(); using (var session = new MongoSession(_connectionString)) { return(GetUserId(session, userName)); } }
// Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method public override string CreateUserAndAccount(string userName, string password, bool requireConfirmation, IDictionary <string, object> values) { VerifyInitialized(); using (var session = new MongoSession(_connectionString)) { CreateUserRow(session, userName, values); return(CreateAccount(userName, password, requireConfirmation)); } }
/// <summary> /// Determines whether there exists a local account (as opposed to OAuth account) with the specified userId. /// </summary> /// <param name="userId">The user id to check for local account.</param> /// <returns> /// <c>true</c> if there is a local account with the specified user id]; otherwise, <c>false</c>. /// </returns> public override bool HasLocalAccount(int userId) { VerifyInitialized(); using (var session = new MongoSession(_connectionString)) { var user = session.Users.FirstOrDefault(x => x.UserId == userId); return(!string.IsNullOrEmpty(user.Password)); } }
/// <summary> /// Deletes the OAuth token from the backing store from the database. /// </summary> /// <param name="token">The token to be deleted.</param> public override void DeleteOAuthToken(string token) { VerifyInitialized(); using (var session = new MongoSession(_connectionString)) { // Note that token is case-sensitive session.DeleteById <OAuthToken>(token); } }
private static int GetPasswordFailuresSinceLastSuccess(MongoSession session, int userId) { var failure = session.Users.FirstOrDefault(x => x.UserId == userId); if (failure != null) { return(failure.PasswordFailuresSinceLastSuccess); } return(-1); }
internal static int GetUserId(MongoSession session, string userName) { var result = session.Users.FirstOrDefault(x => x.UserName == userName); if (result == null) { return(-1); } return(result.UserId); }
private string GetHashedPassword(MongoSession session, int userId) { var user = session.Users.FirstOrDefault(x => x.UserId == userId); // REVIEW: Should get exactly one match, should we throw if we get > 1? if (user == null) { return(null); } return(user.Password); }
public override string GetOAuthTokenSecret(string token) { VerifyInitialized(); using (var session = new MongoSession(_connectionString)) { // Note that token is case-sensitive var oauthToken = session.OAuthTokens.FirstOrDefault(x => x.Token == token); return(oauthToken.Secret); } }
internal static Guid GetUserId(MongoSession session, string userName) { var result = session.GetUserId("Users", "UserName", userName); if (result == null) { return(Guid.Empty); } return(result); }
// Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method public override int GetUserIdFromPasswordResetToken(string token) { VerifyInitialized(); using (var session = new MongoSession(_connectionString)) { var result = session.Users.FirstOrDefault(x => x.PasswordVerificationToken == token); if (result != null) { return((int)result.UserId); } return(-1); } }
// Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method public override int GetPasswordFailuresSinceLastSuccess(string userName) { using (var session = new MongoSession(_connectionString)) { int userId = GetUserId(session, userName); if (userId == -1) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "No user found was found that has the name \"{0}\".", userName)); } return(GetPasswordFailuresSinceLastSuccess(session, userId)); } }
private MembershipAccount GetUser(string userName) { VerifyInitialized(); using (var session = new MongoSession(_connectionString)) { var user = session.Users.FirstOrDefault(x => x.UserName == userName); if (user == null) { throw new MembershipCreateUserException(MembershipCreateStatus.InvalidUserName); } return(user); } }
// Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method public override bool IsConfirmed(string userName) { VerifyInitialized(); if (string.IsNullOrEmpty(userName)) { throw new ArgumentException("Argument_Cannot_Be_Null_Or_Empty", "userName"); } using (var session = new MongoSession(_connectionString)) { var user = VerifyUserNameHasConfirmedAccount(session, userName, throwException: false); return(user != null); } }
/// <summary> /// Replaces the request token with access token and secret. /// </summary> /// <param name="requestToken">The request token.</param> /// <param name="accessToken">The access token.</param> /// <param name="accessTokenSecret">The access token secret.</param> public override void ReplaceOAuthRequestTokenWithAccessToken(string requestToken, string accessToken, string accessTokenSecret) { VerifyInitialized(); using (var session = new MongoSession(_connectionString)) { // insert new record session.DeleteById <OAuthToken>(requestToken); // Although there are two different types of tokens, request token and access token, // we treat them the same in database records. StoreOAuthRequestToken(accessToken, accessTokenSecret); } }
public override string GetUserNameFromId(int userId) { VerifyInitialized(); using (var session = new MongoSession(_connectionString)) { var user = session.Users.FirstOrDefault(x => x.UserId == userId); if (user == null) { return(null); } return(user.UserName); } }
public override int GetUserIdFromOAuth(string provider, string providerUserId) { VerifyInitialized(); using (var session = new MongoSession(_connectionString)) { var user = session.Users.FirstOrDefault(y => y.OAuthData.Any(x => x.ProviderUserId == providerUserId && x.Provider == provider)); if (user != null) { return((int)user.UserId); } return(-1); } }
public override void CreateOrUpdateOAuthAccount(string provider, string providerUserId, string userName) { VerifyInitialized(); if (string.IsNullOrEmpty(userName)) { throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError); } var user = GetUser(userName); var oldUserId = GetUserIdFromOAuth(provider, providerUserId); using (var session = new MongoSession(_connectionString)) { if (oldUserId == -1) { // account doesn't exist. create a new one. user.OAuthData.Add(new OAuthAccountDataEmbedded(provider, providerUserId)); try { session.Save(user); } catch (Exception) { throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError); } } else { // account already exist. update it var oldUser = session.Users.Where(y => y.OAuthData.Any(x => x.ProviderUserId == providerUserId && x.Provider == provider)).FirstOrDefault(); var data = oldUser.OAuthData.FirstOrDefault(x => x.ProviderUserId == providerUserId && x.Provider == provider); oldUser.OAuthData.Remove(data); user.OAuthData.Add(data); try { session.Save(oldUser); session.Save(user); } catch (Exception) { throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError); } } } }
public override void StoreOAuthRequestToken(string requestToken, string requestTokenSecret) { VerifyInitialized(); OAuthToken existingSecret; using (var session = new MongoSession(_connectionString)) { existingSecret = session.OAuthTokens.FirstOrDefault(x => x.Token == requestToken); } if (existingSecret != null) { if (existingSecret.Secret == requestTokenSecret) { // the record already exists return; } using (var session = new MongoSession(_connectionString)) { // the token exists with old secret, update it to new secret existingSecret.Secret = requestTokenSecret; session.Save(existingSecret); } } else { using (var session = new MongoSession(_connectionString)) { // insert new record OAuthToken newOAuthToken = new OAuthToken { Secret = requestTokenSecret, Token = requestToken }; try { session.Save(newOAuthToken); } catch (Exception) { throw new ProviderException("Failed to store OAuth token to database."); } } } }
// Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method public override DateTime GetLastPasswordFailureDate(string userName) { using (var session = new MongoSession(_connectionString)) { var user = session.Users.FirstOrDefault(x => x.UserName == userName); if (user == null) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "No user found was found that has the name \"{0}\".", userName)); } if (user.LastPasswordFailureDate.HasValue) { return(user.LastPasswordFailureDate.Value); } return(DateTime.MinValue); } }
private void CreateUserRow(MongoSession session, string userName, IDictionary <string, object> values) { // Make sure user doesn't exist int userId = GetUserId(session, userName); if (userId != -1) { throw new MembershipCreateUserException(MembershipCreateStatus.DuplicateUserName); } bool result = session.CreateUserRow(userName, values); if (!result) { throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError); } }