My code is querying a server which, if the user and password are correct, returns the “+” character. Otherwise it doesn’t. Bad practice, but I am just using this idea to learn C# and ASP.NET which I am a beginner at (I’ve wrote the program in JSP previously).
My problem :
- Currently, I seem to have some error which causes my methods to
always return true. This should not be the case. It should only be
true when the usersname/pass are authenticated. - I want it to display the login form only if the user is not logged in
and a session has not been started – what is the best way to adapt my
code to do this?
My code so far :
@{
// Initialize general page variables
string username = "";
string password = "";
bool rememberMe = false;
// Validation
bool isValid = true;
// If this is a POST request, validate and process data
if (IsPost) {
username = Request.Form["username"];
password = Request.Form["password"];
rememberMe = Request.Form["remember"].AsBool();
// Attempt to login to the external authentication server
if(isValid){
using (TcpClient client = new TcpClient("hosty.host.com", 110)) {
using (NetworkStream stream = client.GetStream()) {
using (StreamReader reader = new StreamReader(stream)) {
using (StreamWriter writer = new StreamWriter(stream)) {
writer.WriteLine("USER " + username );
writer.WriteLine("PASS " + password );
string response = reader.ReadLine();
isValid = response[ 0 ] == '+';
Response.Write(response);
writer.WriteLine("quit\n");
}
}
}
}
}
if (isValid) {
<text>IT WORKED---></text>
//USER LOGGED IN/ SESSION STARTED
} else {
<text>IT DIDNT WORK :( </text>
//USER NOT LOGGED IN, SESSION NOT STARTED
}
}
}
<h2>Login Here</h2>
<form action="" method="post">
<fieldset>
<legend>Login Form</legend>
<label for="username">Username:
<input type="text" name="username" id="username" value="" />
</label>
<label for="password">Password:
<input type="password" name="password" id="password" value="" />
</label>
<label for="remember">
<input class="checkbox" type="checkbox" name="remember" id="remember" checked="checked" />
Remember me</label>
<p>
<input type="submit" name="login" id="login" value="Login" />
<input type="reset" name="reset" id="reset" value="Reset" />
</p>
</fieldset>
</form>
</div>
</fieldset>
</form>
You start with
isValid=truebut if your program can not even be able to connect to the server theisValidis remain true.So maybe your users not even validate at all, you start with isValid and end with the same even if the validation is not done.
The code as it is, I will start it with false, and remove one line.
Also be ware that Page.
IsValidis an existing parameter on web form.