I am building a simple website from the "Starter Site" template in WebMatrix. I have some questions about the Websecurity methods, especially with the ".CreateAccount" and ".login".
Some nice folk already helped me with ".CurrentUserName" and ".InitializeDatabaseConnection"
here.
This is basically it's continuation. Let me sum up what I did already: Changed the registration process, so the User can now add a Username to the site, changed ".InitializeDatabaseConnection", so the site greets the user when ".CurrentUserName" is called by
his / her Username, altered the Userprofile table.
The problem I have, is that with this solution the user can now only
log in with his / her username instead of his / her e-mail. I have found, that it is most likely because ".CreateAccount" is called like this:
So, somehow it says the other methods, such as ".login", that the UserName shall be used to do various things.
(If I change the "user" arguement in the ".CreateAccount" method back to Email it gives me this error: "The provider encountered an unknown error")
So, when I call the ".login" method like this:
WebSecurity.Login(email, password, rememberMe)
It only let's me login with the Username i specified in the registration ("email" is written as the first arg., because I haven't changed the default variable name)
Here is my full login code:
Layout = "~/_SiteLayout.cshtml";
Page.Title = "Bejelentkezés";
// Initialize general page variables
var email = "";
var password = "";
var rememberMe = false;
var returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl.IsEmpty()) {
// Some external login providers always require a return URL value
returnUrl = Href("~/");
}
// Setup validation
Validation.RequireField("email", "Nem adtál meg email címet!");
Validation.RequireField("password", "Nem adtál meg jelszót!");
Validation.Add("password",
Validator.StringLength(
maxLength: Int32.MaxValue,
minLength: 6,
errorMessage: "Legalább 6 karakter."));
// If this is a POST request, validate and process data
if (IsPost) {
AntiForgery.Validate();
// is this an external login request?
string provider = Request.Form["provider"];
if (!provider.IsEmpty()) {
OAuthWebSecurity.RequestAuthentication(provider, Href("~/Account/RegisterService", new { returnUrl }));
return;
} else if (Validation.IsValid()) {
email = Request.Form["email"];
password = Request.Form["password"];
rememberMe = Request.Form["rememberMe"].AsBool();
if (WebSecurity.UserExists(email) && WebSecurity.GetPasswordFailuresSinceLastSuccess(email) > 4 && WebSecurity.GetLastPasswordFailureDate(email).AddSeconds(60) > DateTime.UtcNow) {
Response.Redirect("~/Account/AccountLockedOut");
return;
}
// Attempt to log in using provided credentials
if (WebSecurity.Login(email, password, rememberMe)) {
Context.RedirectLocal(returnUrl);
return;
} else {
ModelState.AddFormError("Felhasználónév és/vagy jelszó érvénytelen");
}
}
}
}
So, my question:
How can I change that the user can still specify a username, with ".CurrentUserName" called it displays the username, but they can log in with their Email address?
Also, is there a method that I can simply call to write out the User's email address? Like :
Hello, @Websecurity.CurrentUserName, your E-mail address is: @Websecurity.CurrentUserEmail
Can I write my own Websecurity methods? (I know that ".CurrentUserEmail" doesn't exist, I made it up just for demonstration purposes)
If someone with a little-more-time-that-they-can-use could explain me how the "Websecurity" methods work, I'd be really grateful.
@{
var db = Database.Open("StarterSite");
var sqlquery = "SELECT UserName FROM UserProfile WHERE Email = @0";
}
@foreach(var names in db.Query(sqlquery,WebSecurity.CurrentUserName))
{
@names.UserName
}
Dear,
Sorry for late reply
Yes you can create a Partial View for GetUserName not the email
The above code will Query the UserName according to WebSecurity.CurrentUserName from the database
Now your users can Login with their Email and also get a Welcome message having their UserName and not the email. And the ForgotPassword code also works now.
Put the above code in a file called _UserName.cshtml in the root of the folder.
And then render _UserName.cshtml page in the _SiteLayout.cshtml using the RenderPage method like this
Thanks
With Regards
Abhishek Rajiv Luv
"Helpful then please Mark as Answer"
http://www.codeabstract.com/
http://pluralsight.com/training/users/abhishekluv
No, you have to use the asp.net web pages language
You were asking to use your own property for WebSecurity. I am sorry you cant. But you can use your own variables. Like you said you want to display the name of user but user logs in with his email here is solution for that
// After login the user will be having a userId of himself that server knows.
// Also you can change the userName of the user in _AppStart.
@{
var db = Database.Open("StarterSite");
var query = "SELECT * FROM UserProfile WHERE UserId =@0";
var result = db.Query(query, WebSecurity.CurrentUserId);
}
// In my database I had a col for users' names. SO make one. And let the user edit that.
// Than get the users' names.
@{
var name = "";
foreach (var row in result) {
name = row.Name; // or whatever your cols name is. Mine was Name so I used it.
}
}
// Than in the page use
<p>Hello! Mr. @name your email address is: @WebSecurity.CurrentUserName</p>
And remember you can never change the properties of object (WebSecurity is object and .Login, Logout, CurrentUserId is its property)
Please "Marks As Answer" if any answer helped you out!
~~! FIREWALL !~~
Marked as answer by trisztann on Jan 16, 2013 05:15 PM
(WebSecurity is object and .Login, Logout, CurrentUserId is its property)
Dear,
Only CurrentUserId and CurrentUserName are properties and rest others like Login() , Logout() , CreateAccount() are methods of the WebSecurity Class.
Thanks
With Regards
Abhishek Rajiv Luv
"Helpful then please Mark as Answer"
http://www.codeabstract.com/
http://pluralsight.com/training/users/abhishekluv
Sorry for late reply, thought the thread was dead.
Thank both of you, sorry, but I could only quote one answer, would have both if i could.
It works great, thanks for the help, also, I understand a bit more now how ASP.net works :) I actually came from PHP, I have to say it's much better, security wise and coding wise aswell. Also the community is much more helpful.
Thanks
With Regards
Abhishek Rajiv Luv
"Helpful then please Mark as Answer"
http://www.codeabstract.com/
http://pluralsight.com/training/users/abhishekluv
trisztann
Member
14 Points
20 Posts
Some newbie questions about Websecurity methods
Jan 13, 2013 08:27 PM|LINK
Hello,
I am building a simple website from the "Starter Site" template in WebMatrix. I have some questions about the Websecurity methods, especially with the ".CreateAccount" and ".login".
Some nice folk already helped me with ".CurrentUserName" and ".InitializeDatabaseConnection" here.
This is basically it's continuation. Let me sum up what I did already: Changed the registration process, so the User can now add a Username to the site, changed ".InitializeDatabaseConnection", so the site greets the user when ".CurrentUserName" is called by his / her Username, altered the Userprofile table.
The problem I have, is that with this solution the user can now only log in with his / her username instead of his / her e-mail. I have found, that it is most likely because ".CreateAccount" is called like this:
So, somehow it says the other methods, such as ".login", that the UserName shall be used to do various things.
(If I change the "user" arguement in the ".CreateAccount" method back to Email it gives me this error: "The provider encountered an unknown error")
So, when I call the ".login" method like this:
It only let's me login with the Username i specified in the registration ("email" is written as the first arg., because I haven't changed the default variable name)
Here is my full login code:
Layout = "~/_SiteLayout.cshtml"; Page.Title = "Bejelentkezés"; // Initialize general page variables var email = ""; var password = ""; var rememberMe = false; var returnUrl = Request.QueryString["ReturnUrl"]; if (returnUrl.IsEmpty()) { // Some external login providers always require a return URL value returnUrl = Href("~/"); } // Setup validation Validation.RequireField("email", "Nem adtál meg email címet!"); Validation.RequireField("password", "Nem adtál meg jelszót!"); Validation.Add("password", Validator.StringLength( maxLength: Int32.MaxValue, minLength: 6, errorMessage: "Legalább 6 karakter.")); // If this is a POST request, validate and process data if (IsPost) { AntiForgery.Validate(); // is this an external login request? string provider = Request.Form["provider"]; if (!provider.IsEmpty()) { OAuthWebSecurity.RequestAuthentication(provider, Href("~/Account/RegisterService", new { returnUrl })); return; } else if (Validation.IsValid()) { email = Request.Form["email"]; password = Request.Form["password"]; rememberMe = Request.Form["rememberMe"].AsBool(); if (WebSecurity.UserExists(email) && WebSecurity.GetPasswordFailuresSinceLastSuccess(email) > 4 && WebSecurity.GetLastPasswordFailureDate(email).AddSeconds(60) > DateTime.UtcNow) { Response.Redirect("~/Account/AccountLockedOut"); return; } // Attempt to log in using provided credentials if (WebSecurity.Login(email, password, rememberMe)) { Context.RedirectLocal(returnUrl); return; } else { ModelState.AddFormError("Felhasználónév és/vagy jelszó érvénytelen"); } } } }So, my question:
How can I change that the user can still specify a username, with ".CurrentUserName" called it displays the username, but they can log in with their Email address?
Also, is there a method that I can simply call to write out the User's email address? Like :
Can I write my own Websecurity methods? (I know that ".CurrentUserEmail" doesn't exist, I made it up just for demonstration purposes)
If someone with a little-more-time-that-they-can-use could explain me how the "Websecurity" methods work, I'd be really grateful.
Thanks for your patience and help,
Tristan
Abhishek Luv
Participant
1736 Points
468 Posts
Re: Some newbie questions about Websecurity methods
Jan 15, 2013 05:46 AM|LINK
@{ var db = Database.Open("StarterSite"); var sqlquery = "SELECT UserName FROM UserProfile WHERE Email = @0"; } @foreach(var names in db.Query(sqlquery,WebSecurity.CurrentUserName)) { @names.UserName }Dear,
Sorry for late reply
Yes you can create a Partial View for GetUserName not the email
The above code will Query the UserName according to WebSecurity.CurrentUserName from the database
Now your users can Login with their Email and also get a Welcome message having their UserName and not the email. And the ForgotPassword code also works now.
Put the above code in a file called _UserName.cshtml in the root of the folder.
And then render _UserName.cshtml page in the _SiteLayout.cshtml using the RenderPage method like this
<section id="login"> @if (WebSecurity.IsAuthenticated) { <text> Welcome, <a class="email" href="~/Account/Manage" title="Manage">@RenderPage("~/_UserName.cshtml")</a> <form id="logoutForm" action="~/Account/Logout" method="post"> @AntiForgery.GetHtml() <a href="javascript:document.getElementById('logoutForm').submit()">Log out</a> </form> </text> } else { <ul> <li><a href="~/Account/Register">Register</a></li> <li><a href="~/Account/Login">Log in</a></li> </ul> } </section>With Regards
Abhishek Rajiv Luv
"Helpful then please Mark as Answer"
http://www.codeabstract.com/
http://pluralsight.com/training/users/abhishekluv
Afzaal.Ahmad...
Contributor
2660 Points
1039 Posts
Re: Some newbie questions about Websecurity methods
Jan 15, 2013 09:01 AM|LINK
No, you have to use the asp.net web pages language
You were asking to use your own property for WebSecurity. I am sorry you cant. But you can use your own variables. Like you said you want to display the name of user but user logs in with his email here is solution for that
// After login the user will be having a userId of himself that server knows. // Also you can change the userName of the user in _AppStart. @{ var db = Database.Open("StarterSite"); var query = "SELECT * FROM UserProfile WHERE UserId =@0"; var result = db.Query(query, WebSecurity.CurrentUserId); } // In my database I had a col for users' names. SO make one. And let the user edit that. // Than get the users' names. @{ var name = ""; foreach (var row in result) { name = row.Name; // or whatever your cols name is. Mine was Name so I used it. } } // Than in the page use <p>Hello! Mr. @name your email address is: @WebSecurity.CurrentUserName</p>And remember you can never change the properties of object (WebSecurity is object and .Login, Logout, CurrentUserId is its property)
~~! FIREWALL !~~
Abhishek Luv
Participant
1736 Points
468 Posts
Re: Some newbie questions about Websecurity methods
Jan 15, 2013 09:23 AM|LINK
Dear,
Only CurrentUserId and CurrentUserName are properties and rest others like Login() , Logout() , CreateAccount() are methods of the WebSecurity Class.
With Regards
Abhishek Rajiv Luv
"Helpful then please Mark as Answer"
http://www.codeabstract.com/
http://pluralsight.com/training/users/abhishekluv
Afzaal.Ahmad...
Contributor
2660 Points
1039 Posts
Re: Some newbie questions about Websecurity methods
Jan 15, 2013 09:24 AM|LINK
Yes I know thats why I wrote CurrentUserId on the last number.
~~! FIREWALL !~~
trisztann
Member
14 Points
20 Posts
Re: Some newbie questions about Websecurity methods
Jan 16, 2013 05:19 PM|LINK
Hello,
Sorry for late reply, thought the thread was dead.
Thank both of you, sorry, but I could only quote one answer, would have both if i could.
It works great, thanks for the help, also, I understand a bit more now how ASP.net works :) I actually came from PHP, I have to say it's much better, security wise and coding wise aswell. Also the community is much more helpful.
Thanks again! Have a nice day!
Tristan
Afzaal.Ahmad...
Contributor
2660 Points
1039 Posts
Re: Some newbie questions about Websecurity methods
Jan 17, 2013 08:42 AM|LINK
You found PHP more better? Or this one?
~~! FIREWALL !~~
trisztann
Member
14 Points
20 Posts
Re: Some newbie questions about Websecurity methods
Feb 03, 2013 09:07 AM|LINK
This one ofc.
Abhishek Luv
Participant
1736 Points
468 Posts
Re: Some newbie questions about Websecurity methods
Feb 03, 2013 12:01 PM|LINK
@Tristan
Good to hear that.
With Regards
Abhishek Rajiv Luv
"Helpful then please Mark as Answer"
http://www.codeabstract.com/
http://pluralsight.com/training/users/abhishekluv