i am using jpa with hibernate envers of micro service.
i tried
public class MyRevisionEntityListener implements RevisionListener {
#Override
public void newRevision(Object revisionEntity) {
// If you use spring security, you could use SpringSecurityContextHolder.
final UserContext userContext = UserContextHolder.getUserContext();
MyRevisionEntity mre = MyRevisionEntity.class.cast( revisionEntity );
mre.setUserName( userContext.getUserName() );
}
}
it saves username better.but i want to save user name as"by system" when updates the record by another micro service and when user updates should save the user name as above.how to customize above code as my requirement
It would seem the most logical based on your supplied code might be to simply add a boolean flag to your UserContext thread local variable and simply check that inside the listener.
By default this flag would be false but for your special microservice or business use case, you could alter that state temporarily, run your process, and clear that state after you've finished, very much like a web filter chain works in web applications.
Related
I'm developing two different applications, I will name them A and B.
A is an internet platform, where you can logon only if you have a valid user account.
B is an intranet platform, where users can authenticate via Active Directory. An administrator using application B should be able to create new user accounts for application A.
After the creation of a new user account, I want to be able to realize different functions, for example to send an e-mail to the registered mail address, so the new user can change the default password.
All the functionalities that I want to implement, can be done by the UserManager (see section "Use another app to add users" in the following link: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-3.1&tabs=visual-studio#disable-register-page).
Based on this I implemented the following code:
public class ControllerClass : Controller
{
private readonly HelperClass _helper;
private readonly UserManager<IdentityUser> _userManager;
public ControllerClass (UserManager<IdentityUser> userManager)
{
_userManager = userManager;
_helper= new HelperClass (userManager);
}
}
public class HelperClass
{
private readonly DbContext _db;
private readonly UserManager<IdentityUser> _userManager;
public HelperClass (UserManager<IdentityUser> userManager)
{
_db = new DbContext ();
_userManager = userManager;
}
private async Task<string> EnsureUser(string userName, string userPassword)
{
var user = await _userManager.FindByNameAsync(userName);
if (user == null)
{
user = new IdentityUser()
{
UserName = userName
};
await _userManager.CreateAsync(user, userPassword);
}
return user.Id;
}
internal async void CreateUser(UserVM uvm, int id)
{
var userId = await EnsureUser(uvm.userName, uvm.userPassword);
// TODO ...
}
}
Unfortunately I didn't manage to include the UserManager into my application B. I got the following error message: "An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[IdentityUser]' while attempting to activate 'ControllerClass '."
Do you have an idea, how I can add the UserManager to manage the users for another application?
Well, the specific error you're getting is simply because UserManager<TUser> is not registered in the service collection. In order to inject anything, you must first register it. In your actual user-facing app, that's being done by services.AddIdentity(). However, that does a lot more than just register UserManager<TUser>, so you shouldn't just run off and add the same command to your second app.
You could add a registration for it specifically:
services.AddScoped<UserManager<ApplicationUser>>();
However, it actually has a ton of dependencies, each of which would also need to be registered. If you look at the constructor, there's seven services not registered out of the box, many of which have their own dependency trees. Long and short, it's a pain. There's also the matter of separation of concerns, here. This would require adding in the whole data layer from the other app.
Your best bet is to simply expose an API on the Identity app (and lock it down, of course). That way, all the logic of working with users stays with the rest of that logic. The administration app, then, can call out to the API to add, update, delete, etc. users without having to have knowledge of how that's actually done.
Answering after 2 years. For future reader, You can use
services.AddIdentityCore<IdentityUser>();
which adds necessary services that are for user-management add/delete etc. without adding Login service.
to add EntityFramework you can create context and use like this
services.AddDbContext<ApplicationAuthDbContext>(options =>
{
// Configure the context to use postgresql.
options.UseNpgsql(config.GetConnectionString("AuthDbContext"))
.UseSnakeCaseNamingConvention();
});
services.AddIdentityCore<IdentityUser>()
.AddEntityFrameworkStores<ApplicationAuthDbContext>();
For more information
https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.identityservicecollectionextensions.addidentitycore?view=aspnetcore-6.0
The JAVA EE #DeclareRoles annotation is a way to declare the list of possible roles of the users to match with the annotation #RolesAllowed.
But what if our roles are stored in database and if the list of the potential roles is long ?
I currently use roles to specify an atomic access to functionnalities on my website, so I have a long list of roles as some users can access functionnality-1 but not the 2, and some can on the 2 but not on the 1, etc...
I want to avoid editing the #DeclareRoles annotation every time I am creating a new role for a new functionnality, so the question is :
Is there any way to programmatically setup the #DeclareRoles annotation or to specify that it should load from a database ?
Since the introduction of the JavaEE 8 security API you have the ability to write your own identity store. This allows you to fetch users and user data from a custom location and a custom service. You asked about using a database - so here is an example using a database facade together with a custom identity store;
#ApplicationScoped
public class MyIdentityStore implements IdentityStore {
#EJB private UserFacade userFacade;
#Override
public int priority() {
return 50;
}
#Override
public Set<ValidationType> validationTypes() {
return EnumSet.of(ValidationType.PROVIDE_GROUPS, ValidationType.VALIDATE);
}
#Override
public Set<String> getCallerGroups(CredentialValidationResult validationResult) {
final String userName = validationResult.getCallerPrincipal().getName();
final User user= usersFacade.find(userName);
return user.getRoles();
}
public CredentialValidationResult validate(UsernamePasswordCredential credential) {
/* Handle validation/login of the user here */
}
}
To explain the above slightly more - the getCallerGroups() will return the roles that the user is part of - something you can then use throughout the JavaEE security API and lockdown methods such as #RolesAllowed. The validate() method handles the validation of the user when a check is requested by the container. Finally, the validationTypes() method simply specifies what this Identity store should be used for - in this case we have specified both the fetching of roles and handling of validation.
So since EE8 introduced this - it has become really flexible and easy to take advantage of the security features in the platform.
Here are some really great references on the subject;
https://www.ibm.com/developerworks/library/j-javaee8-security-api-1
https://www.ibm.com/developerworks/library/j-javaee8-security-api-2
https://www.ibm.com/developerworks/library/j-javaee8-security-api-3
https://www.baeldung.com/java-ee-8-security
Is there any way in Kentico to have a user submit a form and then email the response but not actually save the answer to the related table?
As mentioned the emails from Kentico rely on the record being written to the DB before they trigger. Furthermore (unless I'm just unlucky) the only values you have access to are those stored in the table. I had thought that maybe you could mark the offending fields as Field without database representation, but sadly, the fields you may want will all be null - so best not to go down that route.
I took a slightly different approach to #trevor-j-fayas in that I used the BizFormItemEvents.Insert.Before event so that there is no trace of any log. It's a short hop from there to make use of an email template to make things look good. So my code looked as follows:
using CMS;
using CMS.DataEngine;
using CMS.EmailEngine;
using System;
[assembly: RegisterModule(typeof(FormGlobalEvents))]
public class FormGlobalEvents : Module
{
public FormGlobalEvents() : base("FormGlobalEvents")
{
}
protected override void OnInit()
{
CMS.OnlineForms.BizFormItemEvents.Insert.Before += Insert_Before;
}
private void Insert_Before(object sender, CMS.OnlineForms.BizFormItemEventArgs e)
{
var email = new EmailMessage();
email.From = e.Item.GetStringValue("ContactEmail", "null#foo.com");
email.Recipients = "no-reply#foo.com";
email.Subject = "Test from event handler (before save)";
email.PlainTextBody = "test" + DateTime.Now.ToLongTimeString();
EmailSender.SendEmail(email);
e.Cancel();
}
}
To me, it seems cleaner to not insert the record in the first place than delete it, but obviously that autoresponder etc. will only kick in automatically if you do save the record, so the choice is yours and ultimately depends on your preference.
Well, there's a couple different options, but the easiest is to simply delete the record after it's inserted. Use the Global Event Hooks to capture the BizFormItemEvent insert after, if it's your form, then delete it. Below is for Kentico 10:
using CMS;
using CMS.DataEngine;
using CMS.Forums;
using CMS.Helpers;
using CMS.IO;
using System.Net;
using System.Web;
// Registers the custom module into the system
[assembly: RegisterModule(typeof(CustomLoaderModule))]
public class CustomLoaderModule : Module
{
// Module class constructor, the system registers the module under the name "CustomForums"
public CustomLoaderModule()
: base("CustomLoaderModule")
{
}
// Contains initialization code that is executed when the application starts
protected override void OnInit()
{
base.OnInit();
CMS.OnlineForms.BizFormItemEvents.Insert.After += BizFormItem_Insert_After;
}
private void BizFormItem_Insert_After(object sender, CMS.OnlineForms.BizFormItemEventArgs e)
{
switch(e.Item.BizFormInfo.FormName)
{
case "YourFormNameHere":
e.Item.Delete();
break;
}
}
}
The other option would be to clone and modify the Online Form Web part to take the information, manually call the email and cancel the insert, but that's a lot of work when this is quicker.
Yes and no. The record is stored before the email notifications and autoresponders are sent out. Your best bet for this is to create a custom global event handler for the form submission(s) using the BizFormItemEvents.Insert.Before. This will call the event before the actual record is stored in the database. You can then cancel out of the event (which will not store the record) and send your email manually.
Handling global events
BizFormItemEvents Events
I am writing a CLI app with Mybatis. In my app, when i go to different menus, it prompts for the user and password for the particular database that menu goes against.
I want to use Guice and Mybatis to handle all this but i have a slight problem. I want to use the XML config file to handle the mybatis config per database, but the user and pass from each connection has to come from the UI. So basically, i want to load mybatis xml file for a particular connection, then insert the credentials for the particular connection the user typed in, then bind those to the guice injector for that set of menus.
I can do it in java with a property object pretty easy, but i can't figure out how to do it with loading the XML first, then augmenting it with certain settings before loading.
Has anyone tried this?
If you are using mybatis guice this can be done by providing your dataSourceProvider for MyBatisModule like this:
Class<? extends Provider<DataSource>> dataSourceProviderType = YourDataSourceProvider.class;
Injector injector = Guice.createInjector(
new MyBatisModule() {
#Override
protected void initialize() {
bindDataSourceProviderType(dataSourceProviderType);
// other initialization ...
}
},
// other modules
);
YourDataSourceProvider should be able to create DataSource using credentials gotten from UI.
In this case you still can use xml mappers for mybatis.
I'm a C# developer but I read nearly every tutorial about cqrs out there, doesn't matter if the language was Java, because I want to learn the structure and base of cqrs.
But now I think, the fact that I read so much tutorials is the problem because there are differences in the tutorials and now I'm confused and don't know which technique I have to use.
Two main questions are running wild in my head and maybe some of you can bring some clarity in there.
On the command side, where should I place the logic to call my ORM for example?
Some tutorials do that in the command handler (what is more logic to me) and some do it in the event handlers which will be fired by the command handler which in that case do only validation logic.
For the event store and to undo thinks, which data do I have to save into the db, some tutorials save the aggregate and some save the event model.
I hope that someone can explain me what pattern to use and why, maybe both in different scenarios, I don't know.
An practical example would be great. (Only pseudo code)
Maybe a User registration, RegisterTheUser command:
Things to do:
Check if the username is already in use
Add user to db
Send confirmation mail (In command or in the UserIsRegistered event?)
Fire event ConfirmationMailSended or only UserIsRegistered event?
Kind regards
EDIT:
Here is my current implementation (Simple)
public class RegisterTheUser : ICommand
{
public String Login { get; set; }
public String Password { get; set; }
}
public class RegisterTheUserHandler : IHandleCommand<RegisterTheUser, AccountAggregate>
{
public void Handle(AccountAggregate agg, RegisterTheUser command)
{
if (agg.IsLoginAlreadyInUse(command.Login))
throw new LoginIsAlreadyInUse();
agg.AddUserAccount(command);
CommandBus.Execute<SendMail>(x => { });
EventBus.Raise<UserIsRegistred>(x => { x.Id = agg.UserAccount.Id; });
}
}
public class UserIsRegistred : IEvent
{
public Guid Id { get; set; }
}
public class AccountAggregate : AggregateBase
{
public AccountAggregate(IUnitOfWork uow)
{
UnitOfWork = uow;
}
private IUnitOfWork UnitOfWork { get; set; }
public UserAccount UserAccount { get; set; }
public void AddUserAccount(RegisterTheUser command)
{
UserAccount = new UserAccount
{
Id = Guid.NewGuid(),
IsAdmin = false,
Login = command.Login,
Password = Crypto.Sha512Encrypt(command.Password)
};
UnitOfWork.UserAccountRepository.Add(UserAccount);
UnitOfWork.Commit();
}
public Boolean IsLoginAlreadyInUse(String login)
{
var result = UnitOfWork.UserAccountRepository.SingleOrDefault(x => x.Login == login);
return (result != null);
}
}
So a number of questions, but I'll take a stab at answering.
On the command side, where should I place the logic to call my ORM for
example?
Having this logic either in the command handler or in your event handler, to me, really depends on the type of system you're building. If you have a fairly simple system, you can probably have your persistence logic in your event handlers, which receive events raised by your domain. The thinking here is that your commands handled by the command handler will already have the information needed and your command handler ends up being not much more than a router. If you need more complexity in your command handler, such as dealing with sagas, long running transactions, or some additional layer of validation, then your command handler will use your persistence layer here to pull out data (and perhaps write data) and then route the command to the proper domain or issue more commands or raise events. So I believe it really depends on the level of complexity you're dealing with.
I tend to favor simplicity over complexity when starting out, and would probably look at having that logic in the event handler to begin with. Move to the command handler if your system is more complex.
For the event store and to undo thinks, which data do I have to save
into the db, some tutorials save the aggregate and some save the event
model
I'm not exactly sure what you're asking here, but if you're asking what should be stored in your event store, then I think a simple solution is the aggregate id, the aggregate type, the event with data (serialized) and the event type. Off the top of my head, that's probably the bare bones of what you'd need: based on the aggregate id you're working with, get all the events for that aggregate (in order raised) and then replay them to rebuild the aggregate. I don't think you need to save the aggregate unless there's some compelling reason to (which is always possible).
As for your request for a practical example and the steps you laid out, that's probably a question in and of itself, but my thoughts on that are:
Check if the user name is already in use
Depending on your application, you may want to do this from the read side in your controller (or whichever layer is raising commands) before you issue a command. Validate at that point, but you'd probably want to validate again before persisting it. You could do that in your event handler where it would probably catch an exception because you're violating a unique index in your database.
Add user to DB
Again, my thought is keep it simple and handle it in your event handler, since your domain is raising a UserIsRegistered event.
Send confirmation email
Your domain could raise the UserIsRegistered event and a second event handler (EmailHandler) would also subscribe to that event and send out the email.
ConfirmationMailSent event could be raised by the event handler, added to the event queue and handled accordingly. I guess I'm not sure what you want to happen here.
But, hopefully this helps a bit.