other user's profile not populating - c#

I've got a weird issue going on. I'm calling the profile for another user (not the currently authenticated user) and trying to access a value.
var profile = System.Web.Profile.ProfileBase.Create(username, true);
if (profile.PropertyValues["x"] != null)
ddlList.SelectedValue = profile.PropertyValues["x"].PropertyValue.ToString();
The value 'x' does exist for the user, but it's returning null. If I step through the code, and actually view the profile values before the if statement, then it works as expected. So I have to explicitly step through the code and view the value for the app to actually acknowledge it.

Related

Can't get Unity Firebase userID

I'm trying to save the user data to the firebase realtime database directly after the user has been created. But the problem is not the saving, but the UserID. I save also save the user ID that i get from CurrentUser. and then i check in the realtime database and saw that the ID that stored was from a last user who recently created. And i check it in the editor by getting the current user Email and it showed the last user Email not the current user who are creating at the moment. Can someone help me to get the current user ID and not the last user id.
You guys can see the image from the links.
What ID should be
The last user ID showing up instead You guys can see that the ID don't event match. I did try redo the project and looking at the videos that from firebase it self. I really have no ide what to do, i am stuck for 3 days now.
public void SaveNewUserInCode(string userId, string Name, string Email) {
var currentUser = FirebaseAuth.DefaultInstance.CurrentUser;
string userNameId;
if (currentUser != null)
{
userNameId = currentUser.Email;
user = new User(userId, Name, Email);
string Json = JsonUtility.ToJson(user);
reference.Child("Users").Child(currentUser.UserId).SetRawJsonValueAsync(Json);
Data.text = userNameId;
}
}
It would be helpful to see the code that invokes SaveNewUserInCode.
I see a few potential dangers with the code you've posted:
The first is that any call (other than Auth.SignOut) is asynchronous. If you're caching userId immediately after Auth.SignInWithEmailAndPasswordAsync, you'll likely have the previous user still in Auth.CurrentUser (until the related task completes). See my related post on all the ways to wait for a task in Unity if you think this is the issue.
The second, especially if Email is sometimes null, you may be automatically calling Auth.SignInAnonymouslyAsync every time your app starts (perhaps old logic, I usually start my prototypes with anonymous users and later on add real accounts when it's time to do some user testing). This will always overwrite your current user even if you were previously signed in anonymously. You should always check Auth.CurrentUser before calling any of the Auth.SignIn methods, but definitely make sure that you don't have a stray Auth.SignInAnonymouslyAsync laying around.
If the issue is threading, I believe the following logic will fix your problem:
var auth = FirebaseAuth.DefaultInstance;
auth.SignInWithEmailAndPasswordAsync(email, password).ContinueWithOnMainThread(task => {
// omitted : any error handling. Check task's state
var user = task.Result;
SaveNewUserInCode(user.UserId, user.DisplayName /* or however you get Name */, user.Email);
});

Why is my List.GetUserEffectivePermissions() method not working?

I'm developing a process in C# with the SharePoint 2013 Client Side Object Model. I need to retrieve the SharePoint List Permissions of a given user, that will be different than the user that is executing the code.
using SP = Microsoft.SharePoint.Client;
SP.ClientContext SpContext = new SP.ClientContext("SITEURL");
SP.Web SiteWeb = SpContext.Web;
SP.List Lst = SpContext.Web.Lists.GetByTitle("LIST");
var ClientUserEffPerms = Lst.GetUserEffectivePermissions(#"<domain>\<username>");
SpContext.Load(SiteWeb, S => S.EffectiveBasePermissions);
SpContext.Load(Lst, L => L.EffectiveBasePermissions);
SpContext.ExecuteQuery();
After this code executes, the ClientUserEffPerms.Value (BasePermissions) object does not represent the permissions of the given user correctly. The object isn't null, but it represents the user as having no permissions. The user has at minimum view and edit permissions and I can confirm this by viewing/editing List Items using the web browser as this user.
The code executing user has permission to enumerate permissions at both the Web and List level. I've confirmed this with the code below, both booleans resolve to true.
bool SvcUserHasSiteEnumPermsPerm = SiteWeb.EffectiveBasePermissions.Has(SP.PermissionKind.EnumeratePermissions);
bool SvcUserHasListEnumPermsPerm = Lst.EffectiveBasePermissions.Has(SP.PermissionKind.EnumeratePermissions);
Can anyone help me determine what is wrong with my GetUserEffectivePermissions() method?
When you call GetUserEffectivePermissions you need to pass in the full claims token version of the login name, which looks something like this:
i:0#.w|domain\user
You can get this by loading the LoginName property on a user object:
clientContext.Load(clientContext.Web.CurrentUser, i => i.LoginName);
clientContext.ExecuteQuery();
Of course, that's for the current user, so you'll need to acquire the user you actually want first.

Registering a new user overwrites current user session - why?

I've come across an issue when registering new users with my app. The behaviour looks to be by design, but I don't understand why.
My problem is as follows (and I know it's a bit of an edge case):
User browses to my site's login page in two separate tabs in the same browser.
In the first tab, the user logs in and is correctly redirected to my home page.
In the second tab, the user follows my signup logic (which doesn't require any kind of page refresh, it's all done with client side code that culminates in a jQuery AJAX POST to the built in ServiceStack RegistrationService's /register endpoint)
Instead of creating a new user, the second user's details overwrite that of the logged in user's UserAuth record, and the first user can no longer log in.
Looking at the code in ServiceStack.ServiceInterface.Auth.RegistrationService, this behaviour appears to be 100% intentional:
var session = this.GetSession();
var newUserAuth = ToUserAuth(request);
var existingUser = UserAuthRepo.GetUserAuth(session, null);
var registerNewUser = existingUser == null;
var user = registerNewUser
? this.UserAuthRepo.CreateUserAuth(newUserAuth, request.Password)
: this.UserAuthRepo.UpdateUserAuth(existingUser, newUserAuth, request.Password);
Once the first user is logged in, the session cookie for that user gets sent with the registration request, causing the existingUser variable in the code above to be populated with the UserAuth for that user, which is then updated with the registering user details.
Can anyone explain why the code's been written in this way? And is there any way around it without replacing the RegistrationService with my own implementation?
This is the feature that lets you to auto-merge different Auth Providers into the same account in ServiceStack.

C# MVC4 windows username and cookie issues

First, I'm sad to say I'm not sure whether this code should be in the _Layout.cshtml or somewhere in the controller. It needs to run on all pages, so I've put it in the _Layout.cshtml page.
This is for an intranet web app. What I'm attempting to do is this: if a cookie (holding the user's userid) is not found, get the windows username, run it through a class that will go into the database and get the corresponding user's username, and - if we get a user id back - make a cookie containing it. Doesn't sound too hard, but one line in particular, and various incarnations of it, is refusing to be supportive. Here's the code as a whole.
if(!Context.Response.Cookies.AllKeys.Contains("userid")){
var winuser = System.Web.HttpContext.Current.User.Identity.Name;
var winuserid = myprojectname.Models.MyIntranetDataContext.getUserId(winuser).UserID();
if (winuserid == null) {
Response.Redirect("/someotherpage");
} else {
HttpCookie cookieuser = new HttpCookie("userid");
DateTime now = DateTime.Now;
cookieuser.Value = winuserid;
cookieuser.Expires = now.AddMonths(1);
Response.Cookies.Add(cookieuser);
}
}
Line 2 - var winuser... - appears to be the problem. In this current incarnation, I'm getting a build error: An object reference is required for the non-static field, method, or property 'myprojectname.Models.MyIntranetDataContext.getUserId(string)'
It doesn't like it when I add a .ToString to it either.
I've tried making winuser this as well:
Page.User.Identity.Name;
That gave no build errors. When I attempt to Start Debugging, she blows up with this beauty of an error: 'Cannot perform runtime binding on a null reference'
Once I get the windows username, all will be well.
Really, this isn't about cookies, or even mvc to much of an extent (except maybe guidance on where to put this code - the _Layout.cshtml?). Really it's about getting the windows username, which I seem unable to do. Thanks in advance for any assistance you are able to provide.
Note, the above names aren't actual - just for example only.
If they are on the domain, couldn't you use something like the following to retrieve that information?
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal;
WindowsIdentity identity = (WindowsIdentity)principal.Identity;
String userName= principal.Identity.Name;

Adding users to roles fails

I have been working on a website for some time now.
I am using the membership, role and profile providers which are working correctly.
I have a standard createuserwizard control where a user can register. When a user registers, I want to add him to a certain role like this:
Roles.AddUserToRole(Profile.UserName, "Member");
I do this through the userCreated event trigger.
There's also a adminpage where an admin should be able to change the role of a user, I did that like this:
DropdownList ddl = ((DropDownList)sender);
String usr = ddl.enter code here
if (Roles.IsUserInRole(usr, "Member")) {
Roles.RemoveUserFromRole(usr, "Member");
}
if (Roles.IsUserInRole(usr, "Visitor")) {
...
switch (ddl.selectedIndex)
case 0:
Roles.AddUserToRole(usr, "Admin");
case 1:
...
This doesn't work either. If I go to the database itself, the user wasn't added to the aspnet_UserInRoles.
Extra details:
When I create a user, he can see the adminpages, which is not intended. Security trimming is working correctly, when I add the user manually to the aspnet_UsersInRoles table I can't reach the memberpages anymore as intended.
The newly created user isn't added to any role, although he can see all pages he shouldn't be able to see. This is freaking me out!
Alright, I fixed the issue that it wouldn't assign the role after registering.
You'd think that userCreated is called after the user has been logged in, but it isn't.
Profile.UserName results in an empty string!
I'm still having problems with the adminpage though... I get the username value from the tooltip of the dropdownlist. By hovering over the ddl I can visually verify that the username is indeed in the tooltip attribute.
Assuming that the same problem exists here -> the usr (username) string is empty. Why can't I get the value?

Categories