public void Api_UserSessionController_GetStatus() { Assert.IsNotNull(ConfigurationManager.AppSettings["AppKey"]); TreeMonDbContext context = new TreeMonDbContext(connectionKey); User u = TestHelper.GenerateTestUser(Guid.NewGuid().ToString("N")); string loginPassword = u.Password; string tmpHashPassword = PasswordHash.CreateHash(u.Password); u.Password = PasswordHash.ExtractHashPassword(tmpHashPassword); u.PasswordHashIterations = PasswordHash.ExtractIterations(tmpHashPassword); u.PasswordSalt = PasswordHash.ExtractSalt(tmpHashPassword); Assert.IsTrue(context.Insert <User>(u)); // set a user session then pass the authtoken SessionManager sessionManager = new SessionManager(connectionKey); string userJson = JsonConvert.SerializeObject(u); UserSession us = sessionManager.SaveSession("127.1.1.34", u.UUID, userJson, false); Task.Run(async() => { ServiceResult res = await TestHelper.SentHttpRequest("GET", "api/Sessions/Status/" + us.AuthToken, "", _ownerAuthToken); Assert.IsNotNull(res); Assert.AreEqual(res.Code, 200); }).GetAwaiter().GetResult(); }
public void PasswordHash_ExtractHashPassword() { string pwd = PasswordHash.CreateHash("password"); string hash = PasswordHash.ExtractHashPassword(pwd); Assert.AreNotEqual(pwd, hash); Assert.IsTrue(pwd.Contains(hash)); }
public void Api_UserSessionController_DeleteUserSession() { Assert.IsNotNull(ConfigurationManager.AppSettings["AppKey"]); TreeMonDbContext context = new TreeMonDbContext(connectionKey); User u = TestHelper.GenerateTestUser(Guid.NewGuid().ToString("N")); string loginPassword = u.Password; u.SiteAdmin = true; // api/StatusMessages/Type/adfda6fe97774f6ea4b3f58f700c32e8 string tmpHashPassword = PasswordHash.CreateHash(u.Password); u.Password = PasswordHash.ExtractHashPassword(tmpHashPassword); u.PasswordHashIterations = PasswordHash.ExtractIterations(tmpHashPassword); u.PasswordSalt = PasswordHash.ExtractSalt(tmpHashPassword); Assert.IsTrue(context.Insert <User>(u)); // set a user session then pass the authtoken SessionManager sessionManager = new SessionManager(connectionKey); string userJson = JsonConvert.SerializeObject(u); UserSession us = sessionManager.SaveSession("127.1.1.35", u.UUID, userJson, false); string sessionInfo = "{ 'SessionId' : '" + us.AuthToken + "' , 'UserUUID' : '" + u.UUID + "' }"; Task.Run(async() => { ServiceResult res = await TestHelper.SentHttpRequest("DELETE", "api/Sessions/Delete", sessionInfo, us.AuthToken); Assert.IsNotNull(res); Assert.AreEqual(res.Code, 200); UserSession dbUserSession = context.GetAll <UserSession>().FirstOrDefault(w => w.AuthToken == us.AuthToken); Assert.IsNull(dbUserSession); }).GetAwaiter().GetResult(); }
public ServiceResult ChangePassword(ChangePassword frm) { if (frm == null) { return(ServiceResponse.Error("Invalid data.")); } NetworkHelper network = new NetworkHelper(); string ipAddress = network.GetClientIpAddress(this.Request); string sessionToken = ""; User u = null; UserManager userManager = new UserManager(Globals.DBConnectionKey, Request.Headers?.Authorization?.Parameter); if (frm.ResetPassword) {//if a reset then the user isn't logged in, so get the user by alt means. //only use captcha on reset if (string.IsNullOrWhiteSpace(frm.ConfirmationCode)) { return(ServiceResponse.Error("Invalid confirmation code. You must use the link provided in the email in order to reset your password.")); } u = userManager.GetUsers(false).FirstOrDefault(dw => (dw.ProviderUserKey == frm.ConfirmationCode && dw.Email.EqualsIgnoreCase(frm.Email))); if (u == null) { return(ServiceResponse.Error("Invalid confirmation code.")); } } else { if (Request.Headers.Authorization == null) { return(ServiceResponse.Error("You must be logged in to change your password.")); } sessionToken = Request.Headers?.Authorization?.Parameter; u = GetUser(sessionToken);//since the user session doesn't contain the password, wi have to pull it. u = (User)userManager.GetBy(u.UUID, false); } if (u == null) { SessionManager.DeleteSession(sessionToken); return(ServiceResponse.Error("Session error. If your logged in try logging out and back in.")); } if (frm.NewPassword != frm.ConfirmPassword) { return(ServiceResponse.Error("Password don't match.")); } if (string.IsNullOrWhiteSpace(frm.NewPassword) || string.IsNullOrWhiteSpace(frm.ConfirmPassword)) { return(ServiceResponse.Error("Password can't be empty. ")); } if (PasswordHash.CheckStrength(frm.NewPassword) < PasswordHash.PasswordScore.Medium) { return(ServiceResponse.Error("Password is too weak. ")); } if (frm.ResetPassword) { if (u.ProviderName != UserFlags.ProviderName.ForgotPassword || u.ProviderUserKey != frm.ConfirmationCode || u.Email.EqualsIgnoreCase(frm.Email) == false) {// string msg = "Invalid informaition posted to server"; SystemLogger logger = new SystemLogger(Globals.DBConnectionKey); logger.InsertSecurity(msg, "AccountController", "ChangePassword"); return(ServiceResponse.Error("Invalid confirmation code.")); } } else //just a user updating their password. { // verify old password if (!PasswordHash.ValidatePassword(frm.OldPassword, u.PasswordHashIterations + ":" + u.PasswordSalt + ":" + u.Password)) { return(ServiceResponse.Error("Invalid password.")); } } ServiceResult sr = userManager.IsUserAuthorized(u, ipAddress); if (sr.Status == "ERROR") { return(sr); } string tmpHashPassword = PasswordHash.CreateHash(frm.NewPassword); u.Password = PasswordHash.ExtractHashPassword(tmpHashPassword); u.PasswordHashIterations = PasswordHash.ExtractIterations(tmpHashPassword); u.PasswordSalt = PasswordHash.ExtractSalt(tmpHashPassword); u.ProviderName = ""; u.ProviderUserKey = ""; u.LastPasswordChangedDate = DateTime.UtcNow; ServiceResult updateResult = userManager.Update(u, false); if (updateResult.Code != 200) { return(ServiceResponse.Error("Error updating password. Try again later.")); } return(ServiceResponse.OK("Password has been updated.")); }
public void Api_StatusMessageController_Get_StatusMessages_ByType() { TreeMonDbContext context = new TreeMonDbContext(connectionKey); User u = TestHelper.GenerateTestUser(Guid.NewGuid().ToString("N")); u.SiteAdmin = true; string loginPassword = u.Password; string tmpHashPassword = PasswordHash.CreateHash(u.Password); u.Password = PasswordHash.ExtractHashPassword(tmpHashPassword); u.AccountUUID = SystemFlag.Default.Account; u.PasswordHashIterations = PasswordHash.ExtractIterations(tmpHashPassword); u.PasswordSalt = PasswordHash.ExtractSalt(tmpHashPassword); u.DateCreated = DateTime.Now; Assert.IsTrue(context.Insert <User>(u)); // set a user session then pass the authtoken SessionManager sessionManager = new SessionManager(connectionKey); string userJson = JsonConvert.SerializeObject(u); UserSession us = sessionManager.SaveSession("127.1.1.34", u.UUID, userJson, false); string statusType = Guid.NewGuid().ToString("N"); StatusMessage mdl = new StatusMessage(); mdl.AccountUUID = SystemFlag.Default.Account; mdl.Status = Guid.NewGuid().ToString("N"); mdl.UUID = Guid.NewGuid().ToString("N"); mdl.DateCreated = DateTime.UtcNow; mdl.CreatedBy = u.UUID; mdl.StatusType = statusType; Assert.IsTrue(context.Insert <StatusMessage>(mdl)); StatusMessage mdl2 = new StatusMessage(); mdl2.AccountUUID = SystemFlag.Default.Account; mdl2.Status = Guid.NewGuid().ToString("N"); mdl2.UUID = Guid.NewGuid().ToString("N"); mdl2.CreatedBy = u.UUID; mdl2.DateCreated = DateTime.UtcNow; mdl2.StatusType = statusType; Assert.IsTrue(context.Insert <StatusMessage>(mdl2)); Task.Run(async() => { ServiceResult res = await TestHelper.SentHttpRequest("POST", "api/StatusMessages/Type/" + mdl.StatusType, "", us.AuthToken); Assert.IsNotNull(res); Assert.AreEqual(res.Code, 200); List <StatusMessage> StatusMessages = JsonConvert.DeserializeObject <List <StatusMessage> >(res.Result.ToString()); Assert.IsNotNull(StatusMessages); Assert.IsTrue(StatusMessages.Count >= 2); int foundStatusMessages = 0; foreach (StatusMessage p in StatusMessages) { if (p.Status == mdl.Status || p.Status == mdl2.Status) { foundStatusMessages++; } } Assert.AreEqual(foundStatusMessages, 2); }).GetAwaiter().GetResult(); }
public ServiceResult RegisterUser(UserRegister ur, bool Approved, string ipAddress) { if (string.IsNullOrEmpty(ur.Name)) { return(ServiceResponse.Error("Invalid username.")); } if (ur.Password != ur.ConfirmPassword) { return(ServiceResponse.Error("Passwords must match.")); } if (Validator.IsEmailInjectionAttempt(ur.Email)) { _logger.InsertSecurity(ur.Email, "UserManager", "RegisterUser.IsEmailInjectionAttempt"); return(ServiceResponse.Error("Dangerous email format.")); } if (!Validator.IsValidEmailFormat(ur.Email)) { return(ServiceResponse.Error("Invalid email format.")); } if (Validator.HasReservedLoginName(ur.Email)) { _logger.InsertSecurity(ur.Email, "UserManager", "RegisterUser.HasReservedLoginName"); return(ServiceResponse.Error("Invalid email name.")); } User dbUser = new User(); using (var context = new TreeMonDbContext(this._connectionKey)) { dbUser = context.GetAll <User>().FirstOrDefault(uw => (uw.Email?.EqualsIgnoreCase(ur.Email) ?? false) || (uw.Name?.EqualsIgnoreCase(ur.Name) ?? false)); } if (dbUser != null && dbUser.Approved == false) { return(ServiceResponse.Error("The email account you provided is already on registered, but has not been validated. <br />Please check your email account and follow the instructions on the message sent.<br/><br/>Thank you,<br/> ")); } else if (dbUser != null) { return(ServiceResponse.Error("Username or email already exists.")); } string tmpHashPassword = PasswordHash.CreateHash(ur.Password); bool approved = false; //if mobile the email validation isn't going to be sent for them to validate=> approve. So auto approve. if (ur.ClientType == "mobile.app") { approved = true; } User u = new User() { //AccountUUID Name = ur.Name, Password = PasswordHash.ExtractHashPassword(tmpHashPassword), PasswordAnswer = ur.SecurityAnswer, PasswordQuestion = ur.SecurityQuestion, Active = true, DateCreated = DateTime.UtcNow, Deleted = false, PasswordSalt = PasswordHash.ExtractSalt(tmpHashPassword), PasswordHashIterations = PasswordHash.ExtractIterations(tmpHashPassword), Email = ur.Email, SiteAdmin = false, Approved = approved, Anonymous = false, Banned = false, LockedOut = false, Private = true, // Since its a site admin we'll make it private appSettings.UserIsPrivate, FailedPasswordAnswerAttemptWindowStart = 0, FailedPasswordAttemptCount = 0, FailedPasswordAnswerAttemptCount = 0, ProviderUserKey = Cipher.RandomString(12), ProviderName = UserFlags.ProviderName.ValidateEmail }; return(Insert(u, ipAddress, true)); }