/// <summary> /// Inserts a new user entity to database. User entity will /// be marked as unregistered by assigning RegistrationToken /// </summary> /// <param name="newUser">New user to be inserted</param> public User RegisterNewUser(PostUser newUser) { using (var transaction = new TransactionScope()) { newUser.RegistrationToken = HashingUtil.GenerateToken(); var userInRespository = usersDao.SelectByEmail(newUser.Email); if (userInRespository != null) { if (userInRespository.RegistrationToken == null) { throw new UniqueFieldException($"User with email {newUser.Email} is already registered", nameof(PostUser.Email)); } // If user exists but has not yet finished registration, renew their registration token userInRespository.RegistrationToken = newUser.RegistrationToken; usersDao.UpdateUser(userInRespository); } else { userInRespository = usersDao.InsertAndReturnNewUser(newUser); } userIntegrations.CreateInvitation(newUser); transaction.Complete(); return(userInRespository); } }
public static object ConvertToParam(ParamType paramType, object obj) { if (obj == null) { return(null); } object param; switch (paramType) { case ParamType.Md5: param = HashingUtil.Md5(obj.ToString(), false); break; case ParamType.Object: param = obj.ToString(); break; case ParamType.Json: param = JsonConvert.SerializeObject(obj, ApiConstants.JsonSerializerSettings); break; default: { param = obj.GetType().IsPrimitive ? obj : obj.ToString(); break; } } return(param); }
private async Task SeedGlobalAdministrator( ICredentialRoleStore credentialRoleStore, ICredentialStore credentialStore) { bool isExistingAnyAdminCredentials = await credentialStore.IsExistingByCredentialRoleCode(SentinelCredentialRoleCodes.GlobalAdmin); if (!isExistingAnyAdminCredentials) { string adminCredentialId = SentinelCredentialIds.Admin; CredentialRole adminRole = await credentialRoleStore.Get(SentinelCredentialRoleCodes.GlobalAdmin); Credential admin = new Credential(); admin.BirthDate = new DateTime(2000, 1, 1); admin.CreationDate = DateTime.UtcNow; admin.DisplayName = adminCredentialId; admin.CredentialId = adminCredentialId; admin.Email = adminCredentialId + "@admin.com"; admin.PasswordSalt = HashingUtil.GenerateSalt(); admin.PasswordHash = HashingUtil.GenerateHash(adminCredentialId, admin.PasswordSalt); admin.Roles = new List <CredentialRole> { adminRole }; await credentialStore.Create(admin); } }
public void HashAndVerifyPassowrd_ShouldVerify(string password) { // var hash = HashingUtil.HashPasswordWithSalt(password); var verifyIsTrue = HashingUtil.VerifyPassword(password, hash); Assert.IsTrue(verifyIsTrue); }
public Session SignIn(string email, string password, Guid tenantID) { var request = new SignInRequest() { Email = email, Password = HashingUtil.CalculateMD5Hash(password), TenantID = tenantID }; return(SignIn(request)); }
public CredentialBuilder(string credentialId) { _credential = new Credential(); _credential.BirthDate = new DateTime(1990, 6, 1); _credential.CreationDate = DateTime.UtcNow; _credential.CredentialId = credentialId; _credential.DisplayName = credentialId; _credential.Email = credentialId + "@mail.com"; _credential.PasswordSalt = HashingUtil.GenerateSalt(); _credential.PasswordHash = HashingUtil.GenerateHash("12345678", _credential.PasswordSalt); }
public ChangePasswordResponse ChangePassword(ChangePasswordRequest request) { request.NewPassword = HashingUtil.CalculateMD5Hash(request.NewPassword); request.OldPassword = HashingUtil.CalculateMD5Hash(request.OldPassword); var httpRequest = new JSONRestRequest("api/v3/accounts/change-password", Method.POST); httpRequest.AddBody(request); var response = Execute <ChangePasswordResponse>(httpRequest, HttpStatusCode.OK); return(response.Data); }
public ValidationInfo ValidateRegToken(string registrationToken) { var errorMessages = new LinkedList <ErrorMessage>(); if (HashingUtil.IsTokenExpired(registrationToken, hoursToExpire: 336)) { errorMessages.AddLast(Errors.ExpiredRegistrationToken()); } return(new ValidationInfo(errorMessages)); }
public Session SignIn(string email, string password) { var request = new SignInRequest() { Email = email, Password = HashingUtil.CalculateMD5Hash(password), UseDefaultTenant = true }; return(SignIn(request)); }
private bool IsUserTrusted(User user) { if (!this.configurationManager.Configuration.TrustedUsers.ContainsKey(user.Username)) { return(false); } string keyHash = HashingUtil.GetSha256Hash(user.PublicKey); return(this.configurationManager.Configuration.TrustedUsers[user.Username] == keyHash); }
public void ResetPassword(ResetPasswordRequest request) { if (request.NewPassword.Length >= 4) { request.NewPassword = HashingUtil.CalculateMD5Hash(request.NewPassword); var httpRequest = new JSONRestRequest("api/v3/accounts/reset-password", Method.POST); httpRequest.AddBody(request); Execute(httpRequest, HttpStatusCode.OK); } else { throw new SDKServiceException("Password must be at least 4 characters long!", new ServiceErrror()); } }
public List <Credential> GetTestCredentials() { var testRoles = GetTestRoles(); var credentials = new List <Credential>(); string newId = ""; Credential cred1 = new Credential(); cred1.CredentialId = "agnael"; cred1.DisplayName = "Agnael"; cred1.CreationDate = new DateTime(2015, 5, 4); cred1.Email = "*****@*****.**"; cred1.PasswordSalt = "ABCDEFGHIJKLMNOP"; cred1.PasswordHash = HashingUtil.GenerateHash("12345678", cred1.PasswordSalt); cred1.BirthDate = new DateTime(1994, 10, 26); // TODO: CAMBIE EL SISTEMA DE ROLES PARA QUE HAYA POR CREDENCIAL Y POR USUARIO DE CADA API, ASIQUE TODO ESTO YA NO TIENE SENTIDO Y HAY QUE CAMBIARLo //cred1.Roles = new List<Role> //{ // testRoles[0], // testRoles[1], // testRoles[2], // testRoles[3] //}; Credential cred2 = new Credential(); cred2.CredentialId = "simbad"; cred2.DisplayName = "Simbad"; cred2.CreationDate = new DateTime(2015, 5, 4); cred2.Email = "*****@*****.**"; cred2.PasswordSalt = "ABCDEFGHIJKLMNOP"; cred2.PasswordHash = HashingUtil.GenerateHash("12345678", cred1.PasswordSalt); cred2.BirthDate = new DateTime(1998, 6, 2); //cred2.Roles = new List<Role> //{ // testRoles[1], // testRoles[3] //}; credentials.Add(cred1); credentials.Add(cred2); return(credentials); }
public static SignatureBody GetSign(List <KeyValuePair <string, object> > paramList, BaseStringPreprocessingDelegate baseStringPreprocessing = null) { if (paramList == null) { return(SignatureBody.Nil); } var baseString = GetBaseString(paramList, false, baseStringPreprocessing); // 获得签名 var body = new SignatureBody { Signature = HashingUtil.Md5(baseString), BaseString = baseString }; return(body); }
public static RegistrationEntity CreateRegistrationEntity(string password = "******") { var tenantProvider = ProviderFactory.Instance.CreateTenantServiceProvider(); var registrationRequest = new RegistrationRequest(); registrationRequest.Account = new Account(); var tenant = new Tenant(); tenant.DisplayName = "fakeTenant"; tenant.ID = Guid.NewGuid(); tenant.Code = GenerateRandomString(); tenant.Address = new Address(); tenant.Person = new Person(); tenant.Organization = new Organization(); var account = registrationRequest.Account; account.AccountType = EAccountType.Master; account.Email = GenerateRandomString() + "@test.com"; account.PasswordHash = HashingUtil.CalculateMD5Hash(password); account.Verified = true; account.ID = Guid.NewGuid(); account.TenantID = tenant.ID; account.Address = new Address(); account.Person = new Person(); tenantProvider.CreateTenantAndAccount(new RegistrationRequest() { Account = account, Tenant = tenant }); var entity = new RegistrationEntity() { Account = account, Tenant = tenant, AccountPassword = password }; return(entity); }
private bool TrustUser(User user) { if (user == null) { return(false); } if (this.configurationManager.Configuration.TrustedUsers.ContainsKey(user.Username)) { return(false); } string keyHash = HashingUtil.GetSha256Hash(user.PublicKey); this.configurationManager.Configuration.TrustedUsers.Add(user.Username, keyHash); this.configurationManager.SaveChanges(); return(true); }
public ValidationInfo ValidateFinishReg(User userForUpdate, RegCredentials regCredentials) { var errorMessages = new List <ErrorMessage>(); if (userForUpdate.RegistrationToken == null) { errorMessages.Add(Errors.UserAlreadyRegistered()); } if (userForUpdate.RegistrationToken != regCredentials.RegistrationToken) { errorMessages.Add(Errors.InvalidRegistrationToken()); } if (userForUpdate.RegistrationToken != null && HashingUtil.IsTokenExpired(userForUpdate.RegistrationToken, hoursToExpire: 336)) { errorMessages.Add(Errors.ExpiredRegistrationToken()); } return(new ValidationInfo(errorMessages)); }
public void ChangePassword(int userId, string oldPassword, string newPassword) { using (var transaction = new TransactionScope()) { var user = usersDao.SelectByID(userId); if (user == null) { throw new EntityNotFoundException($"User with ID {userId} was not found", typeof(User)); } if (!HashingUtil.VerifyPassword(oldPassword, user.Password)) { throw new ValidationFailedException(new ValidationInfo(new ErrorMessage[] { Errors.InvalidPassword() })); } user.Password = HashingUtil.HashPasswordWithSalt(newPassword); usersDao.UpdateUser(user); transaction.Complete(); } }
/// <summary> /// Finalizes registration for user with provided email. /// Will perform validations and test if user is not already registered, /// if provided token is not expired and if user exists at all /// </summary> /// <param name="regCredentials">Credentials used to finish registration, also used for validation</param> /// <returns>Updated user entity after successfulregistration</returns> /// <exception cref="ValidationFailedException">When user registration fails described validations</exception> /// <exception cref="EntityNotFoundException">When user with provided email was not found</exception> public User FinishRegistration(RegCredentials regCredentials) { using (var transaction = new TransactionScope()) { var userToUpdate = usersDao.SelectByRegToken(regCredentials.RegistrationToken); if (userToUpdate == null) { throw new EntityNotFoundException($"User with token {regCredentials.RegistrationToken} was not found", typeof(User)); } var validationInfo = userValidator.ValidateFinishReg(userToUpdate, regCredentials); if (!validationInfo.IsValid) { throw new ValidationFailedException(validationInfo); } usersDao.UpdatePasswordClearToken(HashingUtil.HashPasswordWithSalt(regCredentials.PlainPassword), userToUpdate.UserId); transaction.Complete(); userToUpdate.RegistrationToken = null; return(userToUpdate); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var identity = new ClaimsIdentity(context.Options.AuthenticationType); var userSelector = new UsersDao(); //var userData = (User) userSelector.SelectOneRow(context.UserName, context.Password); var userData = (User)userSelector.SelectByEmail(context.UserName); if (userData != null && userData.Password != null && HashingUtil.VerifyPassword(context.Password, userData.Password)) { //identity.AddClaim(new Claim(ClaimTypes. identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userData.UserId.ToString())); identity.AddClaim(new Claim(ClaimTypes.Name, userData.Email)); context.Validated(identity); } else { context.SetError("invalid_grant", "Provided username and password is incorrect"); context.Rejected(); } }
public static void ClassInit(TestContext context) { var tenantProvider = ProviderFactory.Instance.CreateTenantServiceProvider(); var registrationRequest = new RegistrationRequest(); registrationRequest.Account = new Account(); var tenant = new Tenant(); tenant.DisplayName = "fakeTenant"; tenant.ID = Guid.NewGuid(); tenant.Code = GenerateRandomString(); tenant.Address = new Address(); tenant.Person = new Person(); tenant.Organization = new Organization(); var account = registrationRequest.Account; account.AccountType = EAccountType.Master; account.Email = GenerateRandomString() + "@test.com"; account.PasswordHash = HashingUtil.CalculateMD5Hash(_password); account.Verified = true; account.ID = Guid.NewGuid(); account.TenantID = tenant.ID; account.Address = new Address(); account.Person = new Person(); tenantProvider.CreateTenantAndAccount(new RegistrationRequest() { Account = account, Tenant = tenant }); _account = account; _tenant = tenant; }
public async Task <IActionResult> Create(CredentialCreateForm form) { var validationResult = new CredentialCreateFormValidator( CredentialStore, DisplayNameRule) .Validate(form); validationResult.AddToModelState(this.ModelState, null); if (!validationResult.IsValid) { return(ValidationError()); } Credential credential = new Credential(); credential.BirthDate = form.Birthdate; credential.CreationDate = DateTime.UtcNow; credential.DisplayName = form.Username; credential.CredentialId = form.Username.ToLower(); credential.Email = form.Email; credential.PasswordSalt = HashingUtil.GenerateSalt(); credential.PasswordHash = HashingUtil.GenerateHash(form.Password, credential.PasswordSalt); CredentialRole defaultRole = await CredentialRoleStore.Get(SentinelCredentialRoleCodes.RegularUser); credential.Roles.Add(defaultRole); await this.CredentialStore.Create(credential); string url = Url.Action(nameof(GetByCredentialId), new { credential.CredentialId }); var view = await this.GetByCredentialId(credential.CredentialId); return(Created(url, view)); }
public CredentialBuilder WithPassword(string unhashedPassword) { _credential.PasswordSalt = HashingUtil.GenerateSalt(); _credential.PasswordHash = HashingUtil.GenerateHash(unhashedPassword, _credential.PasswordSalt); return(this); }
public Collaborator(MailAddress mailAddress) { UserKey = HashingUtil.CalculateMD5Hash(mailAddress.Address.ToLower()); DisplayName = mailAddress.DisplayName ?? mailAddress.User; }
//public Hash(ChainNodeView nodeView) //{ // LocalHash(nodeView); // //DescendentHash = HashingUtil.StringToMd5Hash( ) //} private void LocalHash(ChainNodeView nodeView) { TypeHash = HashingUtil.StringToMd5Hash(nodeView.ChainNode.GetType().ToString()); PositionHash = HashingUtil.StringToMd5Hash(nodeView.ViewModel.Position.ToString()); }
public async Task <IActionResult> Login([FromBody] SessionCreateForm form) { // El form está comlpeto? -------------------- if (form == null) { return(new BadRequestResult()); } if (string.IsNullOrEmpty(form.UsernameOrEmail)) { ModelState.AddModelError(nameof(form.UsernameOrEmail), "Required"); } if (string.IsNullOrEmpty(form.Password)) { ModelState.AddModelError(nameof(form.Password), "Required"); } if (!ModelState.IsValid) { return(ValidationError()); } // La IP tiene permiso de intentar login? -------------------- var attemptRateResult = await LoginAttemptLimitingService.Check(RequestInfoService.RemoteIp, LoginAttemptStore); if (!attemptRateResult.IsApproved) { ModelState.AddModelError("", attemptRateResult.ErrorMessage); return(ValidationError()); } LoginAttempt attempt = new LoginAttempt(this.RequestInfoService.RemoteIp, DateTime.UtcNow); // La credencial existe? -------------------- string failedLoginMsg = "Invalid email and password combination."; Credential credential = null; bool isEmail = form.UsernameOrEmail.IsEmail(); if (isEmail) { credential = await CredentialStore.GetByEmail(form.UsernameOrEmail); } else { credential = await CredentialStore.Get(form.UsernameOrEmail); } if (credential == null) { ModelState.AddModelError("", failedLoginMsg); await LoginAttemptStore.Create(attempt); return(ValidationError()); } // La contraseña es correcta? string newCalculatedHash = HashingUtil.GenerateHash(form.Password, credential.PasswordSalt); if (newCalculatedHash != credential.PasswordHash) { ModelState.AddModelError("", failedLoginMsg); await LoginAttemptStore.Create(attempt); return(ValidationError()); } // El usuario está penalizado? CredentialPenalty activePenalty = await CredentialPenaltyStore.Get(credential.CredentialId, DateTime.UtcNow); if (activePenalty != null) { string validationMsg = null; if (activePenalty.EndDate.HasValue) { validationMsg = string.Format("User temporarily banned, until [{0}]. Reason: '{1}'", activePenalty.EndDate.Value.ToString(), activePenalty.Reason); } else { validationMsg = string.Format("User permanently banned. Reason: '{0}'", activePenalty.Reason); } ModelState.AddModelError("", validationMsg); await LoginAttemptStore.Create(attempt); return(ValidationError()); } var agent = RequestInfoService.UserAgent; // La credencial ya tiene una sesión activa? Session session = await this.SessionStore.Get( credential.CredentialId, agent.DeviceClass, agent.DeviceName, agent.AgentName, agent.AgentVersion); if (session != null) { session.LastActiveDate = DateTime.UtcNow; if (session.AllowSelfRenewal) { session.ExpirationDate = session.LastActiveDate.AddDays(1); } await SessionStore.Update(session); } else { // Crea la sesión session = new Session(); session.CredentialId = credential.CredentialId; session.LoginDate = DateTime.UtcNow; session.ExpirationDate = DateTime.UtcNow.AddDays(1); session.LastActiveDate = session.LoginDate; session.AllowSelfRenewal = form.IsRememberLogin; session.Device = new UserDevice(agent.DeviceClass, agent.DeviceName); session.Agent = new UserAgent(agent.AgentName, agent.AgentVersion); await SessionStore.Create(session); } // Autentifica // check if we are in the context of an authorization request var context = await _interaction.GetAuthorizationContextAsync(form.ReturnUrl); await _events.RaiseAsync(new UserLoginSuccessEvent(credential.DisplayName, credential.CredentialId, credential.DisplayName, clientId : context?.ClientId)); // only set explicit expiration here if user chooses "remember me". // otherwise we rely upon expiration configured in cookie middleware. AuthenticationProperties props = null; if (form.IsRememberLogin) { props = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromHours(8)) }; } ; // issue authentication cookie with subject ID and username var isuser = new IdentityServerUser(credential.CredentialId) { DisplayName = credential.DisplayName }; await HttpContext.SignInAsync(isuser, props); // Devuelve el recurso Session return(Element <Session>(session)); }