public async ValueTask <IActionResult> ChangePasswordV1([FromBody] PasswordChangeV1 model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = uow.Users.Get(x => x.Id == GetIdentityGUID()).SingleOrDefault(); if (user == null) { ModelState.AddModelError(MessageType.UserNotFound.ToString(), $"User:{model.EntityId}"); return(NotFound(ModelState)); } else if (!user.IsHumanBeing || user.Id != model.EntityId) { ModelState.AddModelError(MessageType.UserInvalid.ToString(), $"User:{user.Id}"); return(BadRequest(ModelState)); } else if (!PBKDF2.Validate(user.PasswordHashPBKDF2, model.CurrentPassword) || model.NewPassword != model.NewPasswordConfirm) { ModelState.AddModelError(MessageType.UserInvalid.ToString(), $"Bad password for user:{user.Id}"); return(BadRequest(ModelState)); } var expire = uow.Settings.Get(x => x.IssuerId == null && x.AudienceId == null && x.UserId == null && x.ConfigKey == SettingsConstants.GlobalTotpExpire).Single(); string token = HttpUtility.UrlEncode(new PasswordTokenFactory(uow.InstanceType.ToString()) .Generate(model.NewPassword, TimeSpan.FromSeconds(uint.Parse(expire.ConfigValue)), user.Id.ToString(), user.SecurityStamp)); if (uow.InstanceType != InstanceContext.DeployedOrLocal && uow.InstanceType != InstanceContext.End2EndTest) { return(Ok(token)); } var url = UrlFactory.GenerateConfirmPasswordV1(conf, user.Id.ToString(), token); var alert = ControllerContext.HttpContext.RequestServices.GetRequiredService <IAlertService>(); await alert.Enqueue_EmailV1( new EmailV1() { FromEmail = user.EmailAddress, FromDisplay = $"{user.FirstName} {user.LastName}", ToEmail = user.EmailAddress, ToDisplay = $"{user.FirstName} {user.LastName}", Subject = MessageConstants.ConfirmPasswordSubject, Body = Email.ConfirmPassword(map.Map <UserV1>(user), url) }); return(NoContent()); }
public async Task <bool> ValidatePasswordAsync(string username, string password) { username = username.ToLower(); var result = await Client.Cypher .Match("(user:User)") .Where((User user) => user.Username == username) .Return((user) => user.As <User>().Password) .ResultsAsync; if (result.Count() == 0) { return(false); } return(PBKDF2.Validate(password, result.SingleOrDefault())); }
public async Task <string> ChangePassword(string id, [FromForm] string oldPassword, [FromForm] string newPassword) { var quiz = await new Database().QuizCollection .FindAsync <Quiz>(x => x.Id == new ObjectId(id)).Result .SingleAsync(); if (PBKDF2.Validate(oldPassword, quiz.Password)) { await new Database().QuizCollection.UpdateOneAsync( Builders <Quiz> .Filter.Eq("_id", new ObjectId(id)), Builders <Quiz> .Update.Set("password", newPassword)); return("0"); } else { return("Incorrect password."); } }
public async Task <string> Update(string id, [FromForm] string name, [FromForm] string json, [FromForm] string password) { var quiz = await new Database().QuizCollection .FindAsync <Quiz>(x => x.Id == new ObjectId(id)).Result .SingleAsync(); if (PBKDF2.Validate(password, quiz.Password)) { var update = Builders <Quiz> .Update.Set("name", name) .Set("json", json); await new Database().QuizCollection.UpdateOneAsync( Builders <Quiz> .Filter.Eq("_id", new ObjectId(id)), update); return(id); } else { return("[Error] Invalid Password"); } }
public override int Run(string[] remainingArguments) { try { if (_hashType == HashTypes.PBKDF2) { Console.Write("Enter plain text value: "); var clearText = StandardInput.GetHiddenInput(); var hashText = PBKDF2.Create(clearText); if (!PBKDF2.Validate(hashText, clearText)) { Console.WriteLine("Failed to generate hash. Please try again."); } else { Console.WriteLine(); Console.WriteLine(" Hash value: " + hashText); } } if (_hashType == HashTypes.SHA256) { Console.Write("Enter plain text value: "); var clearText = StandardInput.GetHiddenInput(); var hashText = SHA256.Create(clearText); Console.WriteLine(); Console.WriteLine(" Hash value: " + hashText); } return(StandardOutput.FondFarewell()); } catch (Exception ex) { return(StandardOutput.AngryFarewell(ex)); } }
public IActionResult ResourceOwnerV2_Grant([FromForm] ResourceOwnerV2 input) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } Guid issuerID; tbl_Issuer issuer; //check if identifier is guid. resolve to guid if not. if (Guid.TryParse(input.issuer, out issuerID)) { issuer = uow.Issuers.Get(x => x.Id == issuerID).SingleOrDefault(); } else { issuer = uow.Issuers.Get(x => x.Name == input.issuer).SingleOrDefault(); } if (issuer == null) { ModelState.AddModelError(MessageType.IssuerNotFound.ToString(), $"Issuer:{input.issuer}"); return(NotFound(ModelState)); } else if (!issuer.IsEnabled) { ModelState.AddModelError(MessageType.IssuerInvalid.ToString(), $"Issuer:{issuer.Id}"); return(BadRequest(ModelState)); } Guid userID; tbl_User user; //check if identifier is guid. resolve to guid if not. if (Guid.TryParse(input.user, out userID)) { user = uow.Users.Get(x => x.Id == userID).SingleOrDefault(); } else { user = uow.Users.Get(x => x.UserName == input.user).SingleOrDefault(); } if (user == null) { ModelState.AddModelError(MessageType.UserNotFound.ToString(), $"User:{input.user}"); return(NotFound(ModelState)); } //check that user is confirmed... //check that user is not locked... else if (uow.Users.IsLockedOut(user) || !user.EmailConfirmed || !user.PasswordConfirmed) { ModelState.AddModelError(MessageType.UserInvalid.ToString(), $"User:{user.Id}"); return(BadRequest(ModelState)); } var audienceList = uow.Audiences.Get(QueryExpressionFactory.GetQueryExpression <tbl_Audience>() .Where(x => x.tbl_Roles.Any(y => y.tbl_UserRoles.Any(z => z.UserId == user.Id))).ToLambda()); var audiences = new List <tbl_Audience>(); //check if client is single, multiple or undefined... if (string.IsNullOrEmpty(input.client)) { audiences = uow.Audiences.Get(x => audienceList.Contains(x) && x.IsLockedOut == false).ToList(); } else { foreach (string entry in input.client.Split(",")) { Guid audienceID; tbl_Audience audience; //check if identifier is guid. resolve to guid if not. if (Guid.TryParse(entry.Trim(), out audienceID)) { audience = uow.Audiences.Get(x => x.Id == audienceID).SingleOrDefault(); } else { audience = uow.Audiences.Get(x => x.Name == entry.Trim()).SingleOrDefault(); } if (audience == null) { ModelState.AddModelError(MessageType.AudienceNotFound.ToString(), $"Audience:{entry}"); return(NotFound(ModelState)); } else if (audience.IsLockedOut || !audienceList.Contains(audience)) { ModelState.AddModelError(MessageType.AudienceInvalid.ToString(), $"Audience:{audience.Id}"); return(BadRequest(ModelState)); } audiences.Add(audience); } } if (audiences.Count == 0) { ModelState.AddModelError(MessageType.AudienceNotFound.ToString(), $"Audience:None"); return(BadRequest(ModelState)); } var logins = uow.Logins.Get(QueryExpressionFactory.GetQueryExpression <tbl_Login>() .Where(x => x.tbl_UserLogins.Any(y => y.UserId == user.Id)).ToLambda()); switch (uow.InstanceType) { case InstanceContext.DeployedOrLocal: case InstanceContext.End2EndTest: { //check if login provider is local... if (logins.Where(x => x.Name.Equals(DefaultConstants.LoginName, StringComparison.OrdinalIgnoreCase)).Any()) { //check that password is valid... if (!PBKDF2.Validate(user.PasswordHashPBKDF2, input.password)) { uow.AuthActivity.Create( map.Map <tbl_AuthActivity>(new AuthActivityV1() { UserId = user.Id, LoginType = GrantFlowType.ResourceOwnerPasswordV2.ToString(), LoginOutcome = GrantFlowResultType.Failure.ToString(), })); uow.Commit(); ModelState.AddModelError(MessageType.UserInvalid.ToString(), $"User:{user.Id}"); return(BadRequest(ModelState)); } } else { ModelState.AddModelError(MessageType.LoginNotFound.ToString(), $"No login for user:{user.Id}"); return(NotFound(ModelState)); } } break; case InstanceContext.SystemTest: case InstanceContext.IntegrationTest: { //check if login provider is local or test... if (logins.Where(x => x.Name.Equals(DefaultConstants.LoginName, StringComparison.OrdinalIgnoreCase)).Any() || logins.Where(x => x.Name.StartsWith(TestDefaultConstants.LoginName, StringComparison.OrdinalIgnoreCase)).Any()) { //check that password is valid... if (!PBKDF2.Validate(user.PasswordHashPBKDF2, input.password)) { uow.AuthActivity.Create( map.Map <tbl_AuthActivity>(new AuthActivityV1() { UserId = user.Id, LoginType = GrantFlowType.ResourceOwnerPasswordV2.ToString(), LoginOutcome = GrantFlowResultType.Failure.ToString(), })); uow.Commit(); ModelState.AddModelError(MessageType.UserInvalid.ToString(), $"User:{user.Id}"); return(BadRequest(ModelState)); } } else { ModelState.AddModelError(MessageType.LoginNotFound.ToString(), $"No login for user:{user.Id}"); return(NotFound(ModelState)); } } break; default: throw new NotImplementedException(); } var rop_claims = uow.Users.GenerateAccessClaims(issuer, user); var rop = auth.ResourceOwnerPassword(issuer.Name, issuer.IssuerKey, conf["IdentityTenant:Salt"], audiences.Select(x => x.Name).ToList(), rop_claims); uow.AuthActivity.Create( map.Map <tbl_AuthActivity>(new AuthActivityV1() { UserId = user.Id, LoginType = GrantFlowType.ResourceOwnerPasswordV2.ToString(), LoginOutcome = GrantFlowResultType.Success.ToString(), })); var rt_claims = uow.Users.GenerateRefreshClaims(issuer, user); var rt = auth.ResourceOwnerPassword(issuer.Name, issuer.IssuerKey, conf["IdentityTenant:Salt"], audiences.Select(x => x.Name).ToList(), rt_claims); uow.Refreshes.Create( map.Map <tbl_Refresh>(new RefreshV1() { IssuerId = issuer.Id, UserId = user.Id, RefreshType = ConsumerType.User.ToString(), RefreshValue = rt.RawData, IssuedUtc = rt.ValidFrom, ValidFromUtc = rt.ValidFrom, ValidToUtc = rt.ValidTo, })); uow.AuthActivity.Create( map.Map <tbl_AuthActivity>(new AuthActivityV1() { UserId = user.Id, LoginType = GrantFlowType.RefreshTokenV2.ToString(), LoginOutcome = GrantFlowResultType.Success.ToString(), })); uow.Commit(); var result = new UserJwtV2() { token_type = "bearer", access_token = rop.RawData, refresh_token = rt.RawData, user = user.UserName, client = audiences.Select(x => x.Name).ToList(), issuer = issuer.Name + ":" + conf["IdentityTenant:Salt"], expires_in = (int)(new DateTimeOffset(rop.ValidTo).Subtract(DateTime.UtcNow)).TotalSeconds, }; return(Ok(result)); }
public IActionResult ResourceOwnerV1_Grant([FromForm] ResourceOwnerV1 input) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } //check if issuer compatibility mode enabled. var legacyIssuer = uow.Settings.Get(x => x.IssuerId == null && x.AudienceId == null && x.UserId == null && x.ConfigKey == SettingsConstants.GlobalLegacyIssuer).Single(); if (!bool.Parse(legacyIssuer.ConfigValue) && string.IsNullOrEmpty(input.issuer_id)) { ModelState.AddModelError(MessageType.IssuerInvalid.ToString(), $"Issuer:None"); return(BadRequest(ModelState)); } Guid issuerID; tbl_Issuer issuer; if (bool.Parse(legacyIssuer.ConfigValue) && string.IsNullOrEmpty(input.issuer_id)) { //really gross but needed for backward compatibility. can be lame if more than one issuer. if (uow.InstanceType == InstanceContext.DeployedOrLocal || uow.InstanceType == InstanceContext.End2EndTest) { issuer = uow.Issuers.Get(x => x.Name == conf.GetSection("IdentityTenant:AllowedIssuers").GetChildren() .Select(i => i.Value).First()).SingleOrDefault(); } else { issuer = uow.Issuers.Get(x => x.Name == TestDefaultConstants.IssuerName).SingleOrDefault(); } } else { //check if identifier is guid. resolve to guid if not. if (Guid.TryParse(input.issuer_id, out issuerID)) { issuer = uow.Issuers.Get(x => x.Id == issuerID).SingleOrDefault(); } else { issuer = uow.Issuers.Get(x => x.Name == input.issuer_id).SingleOrDefault(); } } if (issuer == null) { ModelState.AddModelError(MessageType.IssuerNotFound.ToString(), $"Issuer:{input.issuer_id}"); return(NotFound(ModelState)); } else if (!issuer.IsEnabled) { ModelState.AddModelError(MessageType.IssuerInvalid.ToString(), $"Issuer:{issuer.Id}"); return(BadRequest(ModelState)); } Guid audienceID; tbl_Audience audience; //check if identifier is guid. resolve to guid if not. if (Guid.TryParse(input.client_id, out audienceID)) { audience = uow.Audiences.Get(x => x.Id == audienceID).SingleOrDefault(); } else { audience = uow.Audiences.Get(x => x.Name == input.client_id).SingleOrDefault(); } if (audience == null) { ModelState.AddModelError(MessageType.AudienceNotFound.ToString(), $"Audience:{input.client_id}"); return(NotFound(ModelState)); } else if (audience.IsLockedOut) { ModelState.AddModelError(MessageType.AudienceInvalid.ToString(), $"Audience:{audience.Id}"); return(BadRequest(ModelState)); } Guid userID; tbl_User user; //check if identifier is guid. resolve to guid if not. if (Guid.TryParse(input.username, out userID)) { user = uow.Users.Get(x => x.Id == userID).SingleOrDefault(); } else { user = uow.Users.Get(x => x.UserName == input.username).SingleOrDefault(); } if (user == null) { ModelState.AddModelError(MessageType.UserNotFound.ToString(), $"User:{input.username}"); return(NotFound(ModelState)); } //check that user is confirmed... //check that user is not locked... else if (uow.Users.IsLockedOut(user) || !user.EmailConfirmed || !user.PasswordConfirmed) { ModelState.AddModelError(MessageType.UserInvalid.ToString(), $"User:{user.Id}"); return(BadRequest(ModelState)); } var logins = uow.Logins.Get(QueryExpressionFactory.GetQueryExpression <tbl_Login>() .Where(x => x.tbl_UserLogins.Any(y => y.UserId == user.Id)).ToLambda()); switch (uow.InstanceType) { case InstanceContext.DeployedOrLocal: case InstanceContext.End2EndTest: { //check if login provider is local... if (logins.Where(x => x.Name.Equals(DefaultConstants.LoginName, StringComparison.OrdinalIgnoreCase)).Any()) { //check that password is valid... if (!PBKDF2.Validate(user.PasswordHashPBKDF2, input.password)) { uow.AuthActivity.Create( map.Map <tbl_AuthActivity>(new AuthActivityV1() { UserId = user.Id, LoginType = GrantFlowType.ResourceOwnerPasswordV1.ToString(), LoginOutcome = GrantFlowResultType.Failure.ToString(), })); uow.Commit(); ModelState.AddModelError(MessageType.UserInvalid.ToString(), $"User:{user.Id}"); return(BadRequest(ModelState)); } } else { ModelState.AddModelError(MessageType.LoginNotFound.ToString(), $"No login for user:{user.Id}"); return(NotFound(ModelState)); } } break; case InstanceContext.SystemTest: case InstanceContext.IntegrationTest: { //check if login provider is local or test... if (logins.Where(x => x.Name.Equals(DefaultConstants.LoginName, StringComparison.OrdinalIgnoreCase)).Any() || logins.Where(x => x.Name.StartsWith(TestDefaultConstants.LoginName, StringComparison.OrdinalIgnoreCase)).Any()) { //check that password is valid... if (!PBKDF2.Validate(user.PasswordHashPBKDF2, input.password)) { uow.AuthActivity.Create( map.Map <tbl_AuthActivity>(new AuthActivityV1() { UserId = user.Id, LoginType = GrantFlowType.ResourceOwnerPasswordV1.ToString(), LoginOutcome = GrantFlowResultType.Failure.ToString(), })); uow.Commit(); ModelState.AddModelError(MessageType.UserInvalid.ToString(), $"User:{user.Id}"); return(BadRequest(ModelState)); } } else { ModelState.AddModelError(MessageType.LoginNotFound.ToString(), $"No login for user:{user.Id}"); return(NotFound(ModelState)); } } break; default: throw new NotImplementedException(); } if (bool.Parse(legacyIssuer.ConfigValue) && string.IsNullOrEmpty(input.issuer_id)) { var rop_claims = uow.Users.GenerateAccessClaims(user); var rop = auth.ResourceOwnerPassword(issuer.Name, issuer.IssuerKey, null, new List <string> { audience.Name }, rop_claims); uow.AuthActivity.Create( map.Map <tbl_AuthActivity>(new AuthActivityV1() { UserId = user.Id, LoginType = GrantFlowType.ResourceOwnerPasswordV1_Legacy.ToString(), LoginOutcome = GrantFlowResultType.Success.ToString(), })); uow.Commit(); var result = new UserJwtV1Legacy() { token_type = "bearer", access_token = rop.RawData, expires_in = (int)(new DateTimeOffset(rop.ValidTo).Subtract(DateTime.UtcNow)).TotalSeconds, }; return(Ok(result)); } else { var rop_claims = uow.Users.GenerateAccessClaims(issuer, user); var rop = auth.ResourceOwnerPassword(issuer.Name, issuer.IssuerKey, conf["IdentityTenant:Salt"], new List <string>() { audience.Name }, rop_claims); uow.AuthActivity.Create( map.Map <tbl_AuthActivity>(new AuthActivityV1() { UserId = user.Id, LoginType = GrantFlowType.ResourceOwnerPasswordV1.ToString(), LoginOutcome = GrantFlowResultType.Success.ToString(), })); var rt_claims = uow.Users.GenerateRefreshClaims(issuer, user); var rt = auth.ResourceOwnerPassword(issuer.Name, issuer.IssuerKey, conf["IdentityTenant:Salt"], new List <string>() { audience.Name }, rt_claims); uow.Refreshes.Create( map.Map <tbl_Refresh>(new RefreshV1() { IssuerId = issuer.Id, UserId = user.Id, RefreshType = ConsumerType.User.ToString(), RefreshValue = rt.RawData, IssuedUtc = rt.ValidFrom, ValidFromUtc = rt.ValidFrom, ValidToUtc = rt.ValidTo, })); uow.AuthActivity.Create( map.Map <tbl_AuthActivity>(new AuthActivityV1() { UserId = user.Id, LoginType = GrantFlowType.RefreshTokenV1.ToString(), LoginOutcome = GrantFlowResultType.Success.ToString(), })); uow.Commit(); var result = new UserJwtV1() { token_type = "bearer", access_token = rop.RawData, refresh_token = rt.RawData, user_id = user.UserName, client_id = audience.Name, issuer_id = issuer.Name + ":" + conf["IdentityTenant:Salt"], expires_in = (int)(new DateTimeOffset(rop.ValidTo).Subtract(DateTime.UtcNow)).TotalSeconds, }; return(Ok(result)); } }
public IActionResult ClientCredentialV2_Grant([FromForm] ClientCredentialV2 input) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } Guid issuerID; tbl_Issuer issuer; //check if identifier is guid. resolve to guid if not. if (Guid.TryParse(input.issuer, out issuerID)) { issuer = uow.Issuers.Get(x => x.Id == issuerID).SingleOrDefault(); } else { issuer = uow.Issuers.Get(x => x.Name == input.issuer).SingleOrDefault(); } if (issuer == null) { ModelState.AddModelError(MessageType.IssuerNotFound.ToString(), $"Issuer:{input.issuer}"); return(NotFound(ModelState)); } else if (!issuer.IsEnabled) { ModelState.AddModelError(MessageType.IssuerInvalid.ToString(), $"Issuer:{issuer.Id}"); return(BadRequest(ModelState)); } Guid audienceID; tbl_Audience audience; //check if identifier is guid. resolve to guid if not. if (Guid.TryParse(input.client, out audienceID)) { audience = uow.Audiences.Get(x => x.Id == audienceID).SingleOrDefault(); } else { audience = uow.Audiences.Get(x => x.Name == input.client).SingleOrDefault(); } if (audience == null) { ModelState.AddModelError(MessageType.AudienceNotFound.ToString(), $"Audience:{input.client}"); return(NotFound(ModelState)); } else if (audience.IsLockedOut || !PBKDF2.Validate(audience.PasswordHashPBKDF2, input.client_secret)) { uow.AuthActivity.Create( map.Map <tbl_AuthActivity>(new AuthActivityV1() { AudienceId = audience.Id, LoginType = GrantFlowType.ClientCredentialV2.ToString(), LoginOutcome = GrantFlowResultType.Failure.ToString(), })); uow.Commit(); ModelState.AddModelError(MessageType.AudienceInvalid.ToString(), $"Audience:{audience.Id}"); return(BadRequest(ModelState)); } var cc_claims = uow.Audiences.GenerateAccessClaims(issuer, audience); var cc = auth.ClientCredential(issuer.Name, issuer.IssuerKey, conf["IdentityTenant:Salt"], audience.Name, cc_claims); uow.AuthActivity.Create( map.Map <tbl_AuthActivity>(new AuthActivityV1() { AudienceId = audience.Id, LoginType = GrantFlowType.ClientCredentialV2.ToString(), LoginOutcome = GrantFlowResultType.Success.ToString(), })); var rt_claims = uow.Audiences.GenerateRefreshClaims(issuer, audience); var rt = auth.ClientCredential(issuer.Name, issuer.IssuerKey, conf["IdentityTenant:Salt"], audience.Name, rt_claims); uow.Refreshes.Create( map.Map <tbl_Refresh>(new RefreshV1() { IssuerId = issuer.Id, AudienceId = audience.Id, RefreshType = ConsumerType.Client.ToString(), RefreshValue = rt.RawData, ValidFromUtc = rt.ValidFrom, ValidToUtc = rt.ValidTo, })); uow.AuthActivity.Create( map.Map <tbl_AuthActivity>(new AuthActivityV1() { AudienceId = audience.Id, LoginType = GrantFlowType.RefreshTokenV2.ToString(), LoginOutcome = GrantFlowResultType.Success.ToString(), })); uow.Commit(); var result = new ClientJwtV2() { token_type = "bearer", access_token = cc.RawData, refresh_token = rt.RawData, client = audience.Name, issuer = issuer.Name + ":" + conf["IdentityTenant:Salt"], expires_in = (int)(new DateTimeOffset(cc.ValidTo).Subtract(DateTime.UtcNow)).TotalSeconds, }; return(Ok(result)); }