I have an SQLite database. I work with it using EclipseLink and JPA. In addition I have an entity class User:
import com.vaadin.server.VaadinService;
import java.io.Serializable;
import javax.persistence.*;
#Entity
public class User implements Serializable {
#Id #GeneratedValue
long id; // Unique identifier of the user in the DB
String username; // Unique name used for login
String password; // Password used for login
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public Long getId() {
return id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
In a registration form I create a user and then call an EntityManager to persist() the changes:
public int createUser(String username, String password, String password_confirmation) {
int regStatus = 0;
if(checkValidUsername(username)) {
if(checkValidPassword(password, password_confirmation)) {
EntityManager em = factory.createEntityManager();
try {
em.getTransaction().begin();
User user = new User(username, password);
em.persist(user);
em.getTransaction().commit();
}
catch(Exception e) {
System.out.println(e.getMessage());
regStatus = 3;
}
finally {
em.close();
}
}
else regStatus = 2; // Password mismatch
}
else regStatus = 1; // User with selected username already present in DB
return regStatus;
}
It works without any problems. I get each and every newly registered user in my USER table. However when I try to change the password it doesn't work. Here are the methods that are related to this procedure:
// Inside the controller for my settings view - here the user can change various things related to his/her profile
public void setCurrentUser() {
currentUser = UserController.findUserByName((String)VaadinSession.getCurrent().getAttribute("username")); // findUserByName() is a static method
}
// Inside the User controller I have multiple methods for common user-related queries; here I use the username that I have retrieved from the VaadinSession's attribute "username" to execute a query and get the User entity (I make sure that a user's name is unique so getting a single result here is not a problem)
public static User findUserByName(String username) {
if(username == null) return null;
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
User user = null;
try{
Query q = em.createQuery("SELECT u FROM User u WHERE u.username = :username");
q.setParameter("username", username);
user = (User)q.getSingleResult();
}
catch(Exception e){
System.err.println(e.getMessage());
}
finally {
em.close();
}
return user;
}
// Inside the controller fpr my settings view (where I change the password)
public int changePassword(String currentPassword, String newPassword, String newPasswordConfirmation) {
if(newPassword.isEmpty()) return 1;
if(!newPassword.equals(newPasswordConfirmation)) return 2; // Incorrect confirmation
if(!currentPassword.equals(currentUser.getPassword())) return 3; // Given current password doesn't match the one stored in the database for this user
int resStatus = 0;
EntityManager em = factory.createEntityManager();
try {
em.getTransaction().begin();
currentUser.setPassword(newPassword);
em.getTransaction().commit(); // NO ERRORS at all...
}
catch(Exception e) {
System.out.println(e.getMessage());
resStatus = 4; // Exception
}
finally {
em.close();
}
return resStatus;
}
I have also tried using EntityManager.find(...), which should return the same row from the USER table (and it does) but the result is again the same - transaction begins, finishes, entity manager closes but the table USER for the supposedly changed user is the same.
Any ideas? I have used the same routine in another project but for setting other things. The database there was PostreSQL and I haven't encountered such issues. Here with the SQLite database I get no errors but the commit fails somehow.
I just develop with hibernate etc. but it will be the same, because both implements JPA.
If you start a transaction JPA will remember all entities you load in this transaction and if you change something you will see the changes in db (after commit).
But in your transaction JPA don't recognize your entity and so the changes will not persists. Try to load the entity in the transaction. Like...
em.getTransaction().begin();
em.find(User.class, currentUser.getId()); //Reload the User from db, so it is attached to the session
currentUser.setPassword(newPassword);
em.getTransaction().commit();
More Information about the methods:
https://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#refresh(java.lang.Object)
https://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#merge(T)
http://www.objectdb.com/java/jpa/persistence/managed
Related
I am fairly new to coding with asp.net so there might be an obvious answere to my question but I haven't found one yet.
So currently I am developing a site for project management and I want the users to get notified when an event happens, eg. they were added to a new project, a project has been updated etc.
For that I have expanded the IdentityUser Model with a new property List
public class CojectUser : IdentityUser
{
public List<Notification> Notifications { get; set; }
}
public class Notification
{
public int NotificationID { get; set; }
public string Message { get; set; }
public bool Seen { get; set; }
}
When an event happens I add them to the user's notification list and update the user via the userManager.
public class EventBroker<T> : IEventBroker<T>
{
private readonly UserManager<CojectUser> userManager;
public EventBroker(UserManager<CojectUser> userMgr, IUserValidator<CojectUser> userValid)
{
userManager = userMgr;
}
public async Task NotifyAsync(Message<T> message, List<UserRole> recipients)
{
foreach (var user in recipients)
{
var cojectUser = await userManager.FindByNameAsync(user.Name);
if (cojectUser != null)
{
if (cojectUser.Notifications == null)
{
cojectUser.Notifications = new List<Notification>();
}
cojectUser.Notifications.Add(new Notification
{
Message = message.Information,
Seen = false
});
IdentityResult result = await userManager.UpdateAsync(cojectUser);
if (!result.Succeeded)
{
throw new UserUpdateFailException();
}
}
}
}
}
}
I am able to save the custom data to the database, but I am unable to load it again from database.
When I want to display the user's notifications userManager retrieves an user object with null as notification list. Even though the data is stored in database.
public async Task<IActionResult> Index()
{
CojectUser user = await userManager.GetUserAsync(User);
if(user.Notifications == null)
{
user.Notifications = new List<Notification>();
}
return View(user);
}
Data in database:
Can anybody tell me what I am doing wrong?
UserManager don't eager load properties by default.
You should use DatabaseContext directly.
var user = _context.Users.Include(c => c.Notifications).Where(u => u.Id == user.Id).ToList();
I am developing a chat application using signalr in asp.net which is mainly used for customer service now i am facing problem when one operator accepted the client request for private chat this client user should not be displayed for other operators except the operator who accepted, i am struggling to solve this issue
the code i have written in hub class is
i have declared ConnectedUsers as
static List<UserDetail> ConnectedUsers = new List<UserDetail>();
and added users using
ConnectedUsers.Add(new UserDetail { ConnectionId = id, UserName = userName });
and tried to remove private chat users using
public void Remove(string UserId, string User)
{
UserDetail item = new UserDetail();
item.ConnectionId = UserId;
item.UserName = User;
if (item != null)
{
ConnectedUsers.Remove(item);
}
}
i am calling this code from html page as follows
chatHub.server.remove(userId, userName);
but this approach is not removing or hiding the user from userlist
I would edit edit the UserDetail class and add a property IsAvailable:
public class UserDetail {
//Guid or string? edit accordingly
public string ConnectionId { get; set;}
public string UserName { get; set; }
public bool IsAvailable { get; set; }
}
Per default, each user needs his "IsAvailable" to be true, when he connects.
When they accept a private chat, send a notification to the server that sets IsAvailable to false, for that particular ConnectionId:
//you don't really need the user name, id is sufficient
public void Remove(string UserId, string User) {
var user = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == UserId);
if(user != null) {
user.IsAvailable = false;
}
}
That also means, you cannot just return the list of connected users back. But you have to filter it first. So when you push that list to your connected clients, add a where clause ConnectedUsers.Where(x => x.IsAvailable).
That should hide all non-available users on your conncted clients.
I trying to write a kind of pseudo singleton implementation. I want it to work similar to how HttpContext does work, where I can get an instance to the context doing something as simple as:
var ctx = HttpContext.Current;
So my implementation goes something like this:
public class AppUser
{
public string Username { get; set; }
public string[] Roles { get; set; }
public AppUser()
{
var appuser = HttpContext.Session["AppUser"] as AppUser;
if(appuser == null)
throw new Exception("User session has expired");
Username = appuser.Username;
Roles = appuser.Roles;
}
}
public class WebAppContext
{
const string ContextKey = "WebAppContext";
WebAppContext() { } //empty constructor
public static WebAppContext Current
{
get
{
var ctx = HttpContext.Current.Items[ContextKey] as WebAppContext;
if(ctx == null)
{
try
{
ctx = new WebAppContext() { User = new AppUser() };
}
catch
{
//Redirect for login
}
HttpContext.Current.Items.Add(ContextKey, ctx);
}
return ctx;
}
}
public AppUser User { get; set; }
}
And I try to consume this object as follows:
var appuser = WebAppContext.Current.User;
Now does the above line guarantee I get the user associated with the correct request context; not some other user which is associated with another concurrent http request being processed?
Apart from the fact that I can't understand why would you need to barely copy the user information from the Session container to the Items container, the answer to your question should be - yes, if the Session data is correct then the same data will be available from your static property.
I wrote a blog entry on that once
http://netpl.blogspot.com/2010/12/container-based-pseudosingletons-in.html
I've looked through the current literature but I'm struggling to workout exactly how to make the new IdentityStore system work with your own database.
My database's User table is called tblMember an example class below.
public partial class tblMember
{
public int id { get; set; }
public string membership_id { get; set; }
public string password { get; set; }
....other fields
}
currently users login with the membership_id which is unique and then I use the id throughout the system which is the primary key. I cannot use a username scenario for login as its not unique enough on this system.
With the examples I've seen it looks like the system is designed to me quite malleable, but i cannot currently workout how to get the local login to use my tblmember table to authenticate using membership_id and then I will have access the that users tblMember record from any of the controllers via the User property.
http://blogs.msdn.com/b/webdev/archive/2013/07/03/understanding-owin-forms-authentication-in-mvc-5.aspx
Assuming you are using EF, you should be able to do something like this:
public partial class tblMember : IUserSecret
{
public int id { get; set; }
public string membership_id { get; set; }
public string password { get; set; }
....other fields
/// <summary>
/// Username
/// </summary>
string UserName { get { return membership_id; set { membership_id = value; }
/// <summary>
/// Opaque string to validate the user, i.e. password
/// </summary>
string Secret { get { return password; } set { password = value; } }
}
Basically the local password store is called the IUserSecretStore in the new system. You should be able to plug in your entity type into the AccountController constructor like so assuming you implemented everything correctly:
public AccountController()
{
var db = new IdentityDbContext<User, UserClaim, tblMember, UserLogin, Role, UserRole>();
StoreManager = new IdentityStoreManager(new IdentityStoreContext(db));
}
Note the User property will contain the user's claims, and the NameIdentifier claim will map to the IUser.Id property in the Identity system. That is not directly tied to the IUserSecret which is just a username/secret store. The system models a local password as a local login with providerKey = username, and loginProvider = "Local"
Edit: Adding an example of a Custom User as well
public class CustomUser : User {
public string CustomProperty { get; set; }
}
public class CustomUserContext : IdentityStoreContext {
public CustomUserContext(DbContext db) : base(db) {
Users = new UserStore<CustomUser>(db);
}
}
[TestMethod]
public async Task IdentityStoreManagerWithCustomUserTest() {
var db = new IdentityDbContext<CustomUser, UserClaim, UserSecret, UserLogin, Role, UserRole>();
var manager = new IdentityStoreManager(new CustomUserContext(db));
var user = new CustomUser() { UserName = "Custom", CustomProperty = "Foo" };
string pwd = "password";
UnitTestHelper.IsSuccess(await manager.CreateLocalUserAsync(user, pwd));
Assert.IsTrue(await manager.ValidateLocalLoginAsync(user.UserName, pwd));
CustomUser fetch = await manager.Context.Users.FindAsync(user.Id) as CustomUser;
Assert.IsNotNull(fetch);
Assert.AreEqual("Custom", fetch.UserName);
Assert.AreEqual("Foo", fetch.CustomProperty);
}
EDIT #2: There's also a bug in the implementation of IdentityAuthenticationmanager.GetUserClaims that is casting to User instead of IUser, so custom users that are not extending from User will not work.
Here's the code that you can use to override:
internal const string IdentityProviderClaimType = "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider";
internal const string DefaultIdentityProviderClaimValue = "ASP.NET Identity";
/// <summary>
/// Return the claims for a user, which will contain the UserIdClaimType, UserNameClaimType, a claim representing each Role
/// and any claims specified in the UserClaims
/// </summary>
public override async Task<IList<Claim>> GetUserIdentityClaims(string userId, IEnumerable<Claim> claims) {
List<Claim> newClaims = new List<Claim>();
User user = await StoreManager.Context.Users.Find(userId) as IUser;
if (user != null) {
bool foundIdentityProviderClaim = false;
if (claims != null) {
// Strip out any existing name/nameid claims that may have already been set by external identities
foreach (var c in claims) {
if (!foundIdentityProviderClaim && c.Type == IdentityProviderClaimType) {
foundIdentityProviderClaim = true;
}
if (c.Type != ClaimTypes.Name &&
c.Type != ClaimTypes.NameIdentifier) {
newClaims.Add(c);
}
}
}
newClaims.Add(new Claim(UserIdClaimType, userId, ClaimValueTypes.String, ClaimsIssuer));
newClaims.Add(new Claim(UserNameClaimType, user.UserName, ClaimValueTypes.String, ClaimsIssuer));
if (!foundIdentityProviderClaim) {
newClaims.Add(new Claim(IdentityProviderClaimType, DefaultIdentityProviderClaimValue, ClaimValueTypes.String, ClaimsIssuer));
}
var roles = await StoreManager.Context.Roles.GetRolesForUser(userId);
foreach (string role in roles) {
newClaims.Add(new Claim(RoleClaimType, role, ClaimValueTypes.String, ClaimsIssuer));
}
IEnumerable<IUserClaim> userClaims = await StoreManager.Context.UserClaims.GetUserClaims(userId);
foreach (IUserClaim uc in userClaims) {
newClaims.Add(new Claim(uc.ClaimType, uc.ClaimValue, ClaimValueTypes.String, ClaimsIssuer));
}
}
return newClaims;
}
I have an ASP.NET application I'm developing. In it is a CR report. When I first wrote the report, I had it hard coded to point to my development server (using MSSQL with Windows integrated login). So, when I moved my app to the production server, it of course failed.
I have been searching for an answer on how to connect it to DB listed in the Web.config, but haven't had any luck.
I saw one suggestion that I create a dataset in my project and tie in to that, but now it seems I can't use a parameter to filter the records.
I did see one other suggestion on how you can change the DB source on the fly, but that was designed for those who want to change the DB in mid session, rather than dependent on the machine, and seemed overkill.
Does anyone have a nice simple solution? I have been working on this problem for way too long and feel that I'm about to shoot my computer (that will teach it a lesson). :-(
public static class ReportDocumentExtensions
{
public static void SetConnectionInfo(this ReportDocument report, ReportContextArgs context)
{
SetConnectionInfo(report, context.UserId, context.Password, context.ServerName, context.DatabaseName);
}
public static void SetConnectionInfo(this ReportDocument report, string userId, string password, string serverName, string databaseName)
{
foreach (Table oTable in report.Database.Tables)
{
TableLogOnInfo oInfo = oTable.LogOnInfo;
ConnectionInfo oConnection = oTable.LogOnInfo.ConnectionInfo;
oConnection.UserID = userId;
oConnection.Password = password;
oConnection.ServerName = serverName;
oConnection.DatabaseName = databaseName;
oTable.ApplyLogOnInfo(oInfo);
}
}
}
public class ReportContextArgs
{
private string _userId;
private string _password;
private string _serverName;
private string _databaseName;
public string ServerName
{
get { return _serverName; }
set { _serverName = value; }
}
public string UserId
{
get { return _userId; }
set { _userId = value; }
}
public string Password
{
get { return _password; }
set { _password = value; }
}
public string DatabaseName
{
get { return _databaseName; }
set { _databaseName = value; }
}
}