In my asp.net Web app. I have a change password form that is not working properly. I set the LoginEvent cancel to false when it has changed. It changes ok, but the control thinks that it fails. Is there something else I need to do?
control.Objects.User user = GlobalClass.GlobalVariables.User;
string currentRealPassword = control.Data.Users.GetUserPassword(user);
if (user != null && ChangeUserPassword.CurrentPassword.Trim() == currentRealPassword)
{
e.Cancel = !control.Data.Users.UpdateUserPassword(user, ChangeUserPassword.NewPassword);
}`enter code here`
Hm...the code doesn't helps:P
What "UpdateUserPassword" Returns? suppose bool.
One hint... C# is OOP:P
Are you comming from php?
Related
I am developing a login application which save username and password using Shared Preferences in Xamarin Android (C#). Firstly, I get the username and password value from web service and then I check the value. If in my local db (sqlite) doesn't have the value so, I update the data with the newest one from web service. After that, I store the user ID by using my custom sqlite function to get the user ID with username and password.
So far, I can parse the Json Object from my web service and assign them into variables. But, I found something strange that, my parsed json object item can't be saved in my shared preferences. I've been 3 days searching and researching from internet but, I didn't find anything. I almost give up, guys. Would you like to help me? I would appreciate the helps.
Here what I did to my app.
I made utilities folder which save my essentials class. I made LoginSession class which save property of user now.
in my main activity
private void MyBtnLogin(object aSender, System.EventArgs e)
{
try
{
System.Net.Http.HttpClient client= new System.Net.Http.HttpClient();
System.Threading.Tasks.Task.Run(async () =>
{
string response = await _httpClient.GetStringAsync($"http://yourjson.com/{fix_email_value}");
JObject parsedObject = JObject.Parse(response);
int userID = parsedObject .Value<int>("ID");
string userEmail = _parsedResponseObject.Value<string>("Email");
string userPassword = _parsedResponseObject.Value<string>("Password");
List<User> lists= User.GetUserList(userID);
User updatedvalue= (from a in lists where a.Email == userEmail && a.Password == userPassword select a).FirstOrDefault();
if (updatedvalue== null)
{
updatedvalue= new User();
updatedvalue.ID = userID;
updatedvalue.Email = userEmail;
updatedvalue.Password = userPassword;
updatedvalue.StoreOrChange();
RunOnUiThread(() =>
{
SharedPref.UserIDNow= userID;
LoginSession.UserNow= User.GetID(userID);
});
} }
});
StartActivity(typeof(NextPage));
Finish();
}
and I retrieve the value in the next activity using SharedPref.UserIDNow to retrieve the user ID. I put the SharedPref.UserIDNow inside my static function to get current User ID
What am i missing? Everytime when I launch and login, after login the app closed like log out! and the value returns -22. Btw, -22 is a default value of my shared preference. I think it must be the ID of the User. Please help me :(
I test with your code , it works with no problem .
Some suggestions to troubleshoot .
Debug your code (add breakpoint) to check if SharedPref.UserIDNow= userID; has been executed , and also remove RunOnUiThread method ,you don't need to wrap code into it unless UI elements gets changed .
Use default SharedPreferences ,change preference as
private static ISharedPreferences preference = PreferenceManager.GetDefaultSharedPreferences(Application.Context);
Use Commit instead of Apply method on ISharedPreferencesEditor,Apply is asynchronous method which means if you read value too early ,you would get default value at that time .
I'm attempting to check if a given user has access to a specific Custom Table.
Based on the example listed on the kentico documentation to check permissions for a custom table, I have setup a similar call, using my custom table class name and userinfo, but the call to "UserInfoProvider.IsAuthorizedPerClass" always return false:
private bool CheckCustomTableReadPermission(UserInfo user = null)
{
// Gets the user object
//UserInfo user = UserInfoProvider.GetUserInfo("CMSEditor");
//UserInfo user = UserInfoProvider.GetUserInfo("someothervalidusername");
//UserInfo user = CurrentUser;
//normally outside of this function
UserInfo CurrentUser = MembershipContext.AuthenticatedUser;
string CustomTableClassName = "Namespc.TblName";
if (user == null)
{
user = CurrentUser;
}
if (user != null)
{
// Checks whether the user has the Read permission for the CMS.MenuItem page type
if (UserInfoProvider.IsAuthorizedPerClass(CustomTableClassName, "Read", SiteContext.CurrentSiteName, user))
{
// Perform an action according to the result
return true;
}
}
return false;
}
Can anyone also mention what the valid permission name strings are, other than "Read"? (e.g.: "Modify"? "Delete"? "Insert"?)
Does UserInfoProvider.IsAuthorizedPerClass resolve all memberships of the given user, or does it only check if the user is explicitly added to the Custom Table?
Any suggestions? We're using Kentico v8.2.25
Thanks!
Victor
What about doing it the same way as it's done in
CMS\CMSModules\CustomTables\Tools\CustomTable_Data_EditItem.aspx.cs
which is:
DataClassInfo dci = DataClassInfoProvider.GetDataClassInfo(customTableId);
dci.CheckPermissions(PermissionsEnum.Read, SiteContext.CurrentSiteName, MembershipContext.AuthenticatedUser)
And the possible permissions are located in CMS.DataEngine.PermissionsEnum. (Read, Modify, Create, Delete, Destroy)
EDIT:
I'm, dumb. You're assigning a default value to the user param, not an auto-assigned value. I would still check to make sure you're getting the user info you're expecting, because that seems to be the most likely cause for the problem.
You seem to be running into a problem here:
private bool CheckCustomTableReadPermission(UserInfo user = null)
Since you're auto-assigning your user parameter to null when your method is called, the following statement will always be true:
if (user == null)
{
user = CurrentUser;
}
And you will never reach your other statement:
if (user != null)
{
// Checks whether the user has the Read permission for the CMS.MenuItem page type
if (UserInfoProvider.IsAuthorizedPerClass(CustomTableClassName, "Read", SiteContext.CurrentSiteName, user))
{
// Perform an action according to the result
return true;
}
}
So your method will always return false.
The IsAuthorizedPerClass() function checks only the user's permissions for the class that you provide to check against and only the specific permission you provide for it to check (e.g. "Read"). So yes, it's only going to see if the user has the Read permission for your custom table.
I'm not 100% certain what all the permissions are, although it appears to be stored in an enum. I'll get back to you on that one in a bit. Hope this helps :)
The IsAuthorizedPerClass() method will return true only if the user's role has been granted permission explicitly within the role's Permissions for that class. All other times, it will return false even if the user is in fact able to Read/Modify/etc. the custom table.
To get the correct permission strings, you can use CMS.DataEngine.PermissionsEnum.<type>.ToString()
To check whether a user has permissions to Read a specific custom table, you will need to make the following 3 checks in order:
UserInfoProvider.IsAuthorizedPerUIElement("CMS.CustomTables","CustomTables",SiteContext.CurrentSiteName,user)
UserInfoProvider.IsAuthorizedPerResource("CMS.CustomTables", PermissionsEnum.Read.ToString(), SiteContext.CurrentSiteName, user)
UserInfoProvider.IsAuthorizedPerClass(CustomTableClassName, PermissionsEnum.Read.ToString(), SiteContext.CurrentSiteName, user)
I'm developing a website in ASP.Net 4. One of the requirements is to log search queries that people use to find our website. So, assuming that a URL parameter named "q" is present in Referrer, I've written the following code in my MasterPage's Page_Load:
if (!CookieHelper.HasCookie("mywebsite")) CookieHelper.CreateSearchCookie();
And my CookieHelper class is like this:
public class CookieHelper
{
public static void CreateSearchCookie()
{
if (HttpContext.Current.Request.UrlReferrer != null)
{
if (HttpContext.Current.Request.UrlReferrer.Query != null)
{
string q = HttpUtility.ParseQueryString(HttpContext.Current.Request.UrlReferrer.Query).Get("q");
if (!string.IsNullOrEmpty(q))
{
HttpCookie adcookie = new HttpCookie("mywebsite");
adcookie.Value = q;
adcookie.Expires = DateTime.Now.AddYears(1);
HttpContext.Current.Response.Cookies.Add(adcookie);
}
}
}
}
public static bool HasCookie(string cookiename)
{
return (HttpContext.Current.Request.Cookies[cookiename] != null);
}
}
It seems ok at the first glance. I created a page to mimic a link from Google and worked like a charm. But it doesn't work on the host server. The reason is that when you search blah blah you see something like www.google.com/?q=blah+blah in your browser address bar. You expect clicking on your link in the results, will redirect to your site and you can grab the "q" parameter. But ,unfortunately, it is not true! Google, first redirects you to an address like:
http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CCgQFjAA&url=http%3A%2F%2Fwww.mywebsite.com%2F&ei=cks5Uof4G-aX0QXKhIGoCA&usg=AFQjCNEdmmYFpeRRRBiT_MGH5a1x9wUUlg&bvm=bv.52288139,d.d2k&cad=rja
and this will redirect to your website. As you can see the "q" parameter is empty this time! And my code gets an empty string and actually doesn't create the cookie (or whatever).
I need to know if there is a way to solve this problem and get the real "q" value. The real search term user typed to find my website. Does anybody know how to solve this?
Google stopped passing the search keyword:
http://www.searchenginepeople.com/blog/what-googles-keyword-data-grab-means-and-five-ways-around-it.html
Edit Some have expressed their dislike for my particular solution presented in this problem, but please don't waste my time suggesting completely alternative methods. I have no control over the requirements of what I am working on. If you disagree with it and don't have an answer, just move along. Thanks.
For starters, this is a practice project and will not be used by the general public. I need to secure some pages in my website using session properties for username. This occurs (the username saved into session) when a correct username and password combo is entered. My boss reviewed my implementation and said that "storing the username value into the HttpSessionState directly is wrong, you should set the username property of the session, and store the session object into the HttpSessionState". Now I think I understand what parts of my code he is referring to, but changing this breaks the security (anyone can use a direct link to a page once a single user has logged in).
Make sure to read the comments in code, I added them to describe the lines in question.
What worked in terms of security, but username is stored directly into HttpSessionState:
//login.ascx.cs
private void Login_Click(object sender, EventArgs e)
{
if (sender == null || e == null)
{
throw new ArgumentNullException("Null Exception: Login_Click");
}
User user = new User();
user.Login(_username.Text, _password.Text);
if (user.IsValid() && user.GetIsUser() != false)
{
user.Save();
//the line below is what I used to make the secure pages work properly.
//but based on what my boss says, I think this is what should be changed.
Session["Username"] = _username.Text;
//What i tried instead was to set 'MySession.Current.Username = _username.Text;'
//which allowed successful login, but the pages became insecure once again.
Response.Redirect("Secure/Default.aspx");
}
else
{
DisplayErrors(user._validationErrors);
}
_errors.Text = errorMessage;
}
and MySession.cs
public string Username
{
get
{
if (HttpContext.Current.Session["Username"] == null)
{
return string.Empty;
}
else
{
return HttpContext.Current.Session["Username"].ToString();
}
}
set
{
//when the line below is uncommented, the secure pages are vulnerable
//but if I comment it out, they work properly.
//HttpContext.Current.Session["Username"] = value;
}
}
So how can I Set the username property of the session, and store the session object into the HttpSessionState while still maintaining a secure site?
EDIT: #Win, within Secure/Default.aspx.cs
private void Page_load(object sender, System.EventArgs e)
{
...
if((string)Session["Username"] != _labelusername.Text)
{
Response.Redirect(redirectLogin); //to login page
}
else {} //success
}
You should look into FormsAuthentication. There are many examples online like this one:
http://bradkingsley.com/securing-asp-net-pages-forms-authentication-c-and-net-4/
I want to check if a user is logged in and if they are, deny them access to the registration and login pages. When a user logs in I'm setting these session variables:
HttpContext.Current.Session["LoggedIn"] = true;
HttpContext.Current.Session["FullName"] = (string)Reader["FirstName"] + " " + (string)Reader["LastName"];
Response.Redirect("Default.aspx");
And I'm checking them at the top of the register and login pages like so:
if ((bool)HttpContext.Current.Session["LoggedIn"])
{
Response.Redirect("Default.aspx");
}
However, when I try to go to the page while not logged in this exception gets thrown:
Object reference not set to an instance of an object.
I'm assuming it's ebcause the LoggedIn key doesn't exist because I only create it after a successful login.
So, how can I check if the LoggedIn key exists and if it doesn't, redirect the user to Default.aspx?
Thanks!
I think you can do a simple null check on this like....
if (HttpContext.Current.Session["LoggedIn"] != null)
{
// once inside this loop
// you can now read the value from Session["LoggedIn"]
Response.Redirect("Default.aspx");
}
you need to make shure that the object is not null before unboxing it
if(HttpContext.Current.Session["LoggedIn"]!=null)
{
if ((bool)HttpContext.Current.Session["LoggedIn"])
{
Response.Redirect("Default.aspx");
}
}
Why to avoid the default webforms authentication model altogether? Simply use web.config to define a restricted area, set all the settings correctly and you won't have to perform checks like this for every page.
But, if you want to reinvent the wheel....
You check for something that probably doesn't exist yet. You must modify your if-statement like this:
bool isLoggedIn = (HttpContext.Current.Session["LoggedIn"] == null ? false : (bool)HttpContenxt.Current.Session["LoggedIn"];
if (isLoggedIn)
{
Response.Redirect("Default.aspx");
}