Automatically Logging In User After Custom Membership Creation (not using Wizard) - asp.net

I'm using the following code to create a user account on my vb.net website. The code is in a button click. It works fine as far creating the membership but when the user is redirected to the next page they are not logged in. Apparently "newUser.IsApproved = True" is not working. Any thoughts on what I'm doing wrong. I want the user to be automatically logged in after the membership is created.
Dim createStatus As MembershipCreateStatus
Try
Dim newUser As System.Web.Security.MembershipUser = Membership.CreateUser(txtinput_Email.Value, txtinput_Password.Value, txtinput_Email.Value)
newUser.IsApproved = True
Catch ex As Exception
LabelCreateAccountResults.Text = ex.Message
' MessageBox.Show("There's an error: " & vbCrLf & ex.ToString)
Response.Write("<script language='javascript'>alert('" & ex.Message & "')</script>")
Exit Sub
End Try
Select Case createStatus
Case MembershipCreateStatus.Success
LabelCreateAccountResults.Text = "The user account was successfully created!"
Response.Redirect("yo-delivery.aspx")
Case MembershipCreateStatus.DuplicateUserName
LabelCreateAccountResults.Text = "That username already exists."
Case MembershipCreateStatus.DuplicateEmail
LabelCreateAccountResults.Text = "A user with that Email address already exists."
Case MembershipCreateStatus.InvalidEmail
LabelCreateAccountResults.Text = "PLease enter a VALID email address."
Case MembershipCreateStatus.InvalidPassword
LabelCreateAccountResults.Text = "The password entered is invalid. Please enter a passoword with at least 4 characters."
Case Else
LabelCreateAccountResults.Text = "Unknown Error: Account NOT created."
End Select

OK perhaps look into something along these lines
Dim username__1 As String = Username.Text
Dim password__2 As String = Password.Text
If Membership.ValidateUser(username__1, password__2) Then
Dim ticket As New FormsAuthenticationTicket(1, username__1, DateTime.Now, DateTime.Now.AddMinutes(20), False, String.Empty, _
FormsAuthentication.FormsCookiePath)
Response.Cookies.Add(New HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)) With { _
Key .Expires = ticket.Expiration, _
Key .Path = FormsAuthentication.FormsCookiePath _
})
If Not String.IsNullOrEmpty(Request.QueryString("returnurl")) Then
Response.Redirect(Request.QueryString("returnurl"))
End If
Response.Redirect("~/Home")
End If

Related

The code for my aspx signup page does not work

Hello the following code for my signup page does not work. when I execute it, it refreshes and stays in the same page. But it is supposed to redirect to a page called message.aspx. The register command works as follows the person trying to register writes in comboboxs their information and then once they finished, they click the button begin which will save all their information and then use it to personalize the message.aspx page and the person will receive an email.
here is the code:
Private Sub cmdRegister_Click(sender As Object, e As System.EventArgs) Handles cmdRegister.Click
Dim status As MembershipCreateStatus
Dim organization As New Org
Dim employee As New Employee
Dim description As New Description(25)
Dim userMembership As MembershipUser
Dim stringBuilder As New StringBuilder
Try
Membership.CreateUser( _
txtUserName.Text, _
txtPassword.Text, _
txtEmail.Text, _
"question", _
"answer", _
True, _
status)
If status.ToString = "Success" Then
organization.GSTRate = 1
organization.QSTRate = 1
organization.AccountStatus = 2
organization.Name = txtOrg.Text
organization.Active = 1
organization.OrgTypeID = cboType.SelectedValue
organization.Create()
organization = Nothing
organization = New Org(txtOrg.Text)
employee.Username = txtUserName.Text
employee.OrgID = organization.ID
employee.FirstName = txtFName.Text
employee.LastName = txtLName.Text
employee.Title = txtTitle.Text
employee.Username = txtUserName.Text
employee.IsAdmin = True
employee.IsSupervisor = True
employee.IsAccountant = False
employee.IsAdvalorem = True
employee.Email = txtEmail.Text
employee.Phone = ""
employee.Create()
Roles.AddUserToRole(employee.Username, "Admin")
userMembership = Membership.GetUser(txtUserName.Text)
stringBuilder.Append(description.EnglishDescription)
stringBuilder.Replace("(name)", employee.FirstName & " " & employee.LastName)
stringBuilder.Replace("(OrgName)", organization.Name)
stringBuilder.Replace("(username)", employee.Username)
stringBuilder.Replace("you must activate your account", "you must <a href='https://www.advataxes.ca/login.aspx?action=activate&id=" + userMembership.ProviderUserKey.ToString + "&username=" + userMembership.UserName + "'>activate your account</a>")
SendEmail(userMembership.Email, "Advataxes: Account created ", stringBuilder.ToString, Session("language"))
Session("NewUserEmail") = userMembership.Email
Response.Redirect("message.aspx?id=364")
Else
lblInvalidUserName.Visible = True
If status.ToString = "DuplicateUserName" Then lblInvalidUserName.Text = "Username already exists"
End If
Catch ex As MembershipCreateUserException
MsgBox(GetErrorMessage(ex.StatusCode))
Catch ex As HttpException
MsgBox(ex.Message)
Finally
userMembership = Nothing
organization = Nothing
employee = Nothing
description = Nothing
End Try
End Sub
Looking at your code, I suspect the code execution is not successfully reaching the Response.Redirect("message.aspx?id=364") line and due to an exception the flow jumps to catch block/
Two possibilities I can think of:
Exception is thrown inside SendEmail method if smtp is not configured
Membership.CreateUser is failing due to incorrect database connectionstring
I suggest you put a breakpoint inside the cmdRegister_Click method and step through the code.

Error when leaving input blank in ASP

I am developing a script to allow users to write to Active Directory. The problem is that, when I leave a field blank, it results in an error. When, however, I put a value in, even a space, it seems happy. I have the following code:
<%#LANGUAGE="VBScript">
%>
<%
if isEmpty(request.form("subval")) then
response.write("You did not submit the form, please <a href='ldap.asp'>go back</a>")
else
'If the subval field is empty, we know the form has been submitted OK
dim firstname, lastname, email, telephonenumber, mobile, description
ADUser = "LDAP://OU=Staff,OU=Users,DC=example,DC=internal"
' Make AD connection and run query
subval = request.querystring("account_name")
'This value held the CN earlier, it is now overwriten here
Set objCon = Server.CreateObject("ADODB.Connection")
objCon.provider ="ADsDSOObject"
objCon.Properties("User ID") = "EXAMPLE\Exampe"
objCon.Properties("Password") = "TestPassword"
objCon.Properties("Encrypt Password") = TRUE
objCon.open "Active Directory Provider"
Set objCom = CreateObject("ADODB.Command")
Set objCom.ActiveConnection = objCon
objCom.CommandText ="select sAMAccountName, distinguishedName FROM '"+ ADUser +"' where sAMAccountname='"& subval &"'"
Set objRS = objCom.Execute
distinguishedName = objRS.Fields("distinguishedName")
objRS.Close
objCon.Close
Set objRS = Nothing
Set objCom = Nothing
'We select the distinguishedName from AD
firstname = request.form("firstname")
lastname = request.form("lastname")
email = request.form("email")
telephonenumber = request.form("telephonenumber")
mobile = request.form("mobile")
description = request.form("description")
Const ADS_PROPERTY_UPDATE = 2
Set objUser = GetObject _ ("LDAP://" & distinguishedName)
if (IsNull(firstname)) Then
firstname = " "
end if
if (IsNull(lastname)) Then
lastname = " "
end if
if (IsNull(email)) Then
email = " "
end if
if (IsNull(telephonenumber)) Then
telephonenumber = " "
end if
if (IsNull(mobile)) Then
mobile = " "
end if
if (IsNull(description)) Then
description = " "
end if
objUser.Put "givenName", firstname
objUser.Put "mail", email
objUser.Put "sn", lastname
objUser.Put "mobile", mobile
objUser.Put "description", description
objUser.Put "telephoneNumber", telephonenumber
objUser.SetInfo
Response.Write("User data for "& subval &" has been modified")
end if
%>
The error I get whenever I leave a field blank is why I am trying to inject spaces into the variables since that seems to work in my form.
The error I get is on the SetInfo line
error '8007200b'
/updateldap.asp, line 68
I'm not sure what I can try since I've done all the stuff I can think of
8007200b = LDAP_INVALID_SYNTAX (The attribute syntax specified to the directory service is invalid)
I would say that you have worked out what the issue is. LDAP attributes cannot be NULL. You probably don't even need to have spaces, an empty string might work as well.
e.g.
if (IsNull(firstname)) Then
firstname = ""
end if

Send Password if user forgets

I'm working on a project with asp and i have a section of where a user forgets his or her password she enters her email and if it's valid it sends the password. Now the problem is, its able to check if the email is in the database alright and sends the mail, but can't send the password along.
<%
'Check if the form has been processed
If Request.Form("process")="true" Then
'Check the recordset for a valid record
If Not rs_user.Eof Then
'Valid record, so proceed with the email
Call sSendReminder (rs_user("email"), rs_user("password"))
Response.Write "Your password has been sent to your inbox. If you don't find it in your mail box, check your junk mail folder"
dim sName, sEmail, sMessage
dim oCdoMail, oCdoConf, sConfURL
sEmail = Request.Form("email")
Set oCdoMail = Server.CreateObject("CDO.Message")
Set oCdoConf = Server.CreateObject("CDO.Configuration")
sConfURL = "http://schemas.microsoft.com/cdo/configuration/"
with oCdoConf
.Fields.Item(sConfURL & "sendusing") = 2
.Fields.Item(sConfURL & "smtpserver") = "smptserveraddress.com"
.Fields.Item(sConfURL & "smtpserverport") = 25
.Fields.Update
end with
with oCdoMail
.From = "noreply#sample.com"
.To = sEmail
.Subject = "Password Recovery from samplesite"
.TextBody = "Your password is: " & password
.HTMLBody = "Your password is: " & password
.Configuration = oCdoConf
.Send
end with
Set oCdoConf = Nothing
Set oCdoMail = Nothing
Else
'Not a valid record
Response.Write "Sorry, no email was found."
End If
End If
Sub sSendReminder(email, password)
End Sub
%>
Is the above code the exact code you are running?
If so, you need to move the
Sub sSendReminder(email, password)
above
dim sName, sEmail, sMessage
You also need to move those "end if" statements outside the sub.
Your code runs (I think) because it is technically correct, but it doesn't run like you think it should because your sub is actually blank.
Correct code would look like this:
<%
'Check if the form has been processed
If Request.Form("process")="true" Then
'Check the recordset for a valid record
If Not rs_user.Eof Then
'Valid record, so proceed with the email
Call sSendReminder (rs_user("email"), rs_user("password"))
Response.Write "Your password has been sent to your inbox. If you don't find it in your mail box, check your junk mail folder"
Else
'Not a valid record
Response.Write "Sorry, no email was found."
End If
End If
Sub sSendReminder(email, password)
dim sName, sEmail, sMessage
dim oCdoMail, oCdoConf, sConfURL
sEmail = Request.Form("email")
Set oCdoMail = Server.CreateObject("CDO.Message")
Set oCdoConf = Server.CreateObject("CDO.Configuration")
sConfURL = "http://schemas.microsoft.com/cdo/configuration/"
with oCdoConf
.Fields.Item(sConfURL & "sendusing") = 2
.Fields.Item(sConfURL & "smtpserver") = "smptserveraddress.com"
.Fields.Item(sConfURL & "smtpserverport") = 25
.Fields.Update
end with
with oCdoMail
.From = "noreply#sample.com"
.To = sEmail
.Subject = "Password Recovery from samplesite"
.TextBody = "Your password is: " & password
.HTMLBody = "Your password is: " & password
.Configuration = oCdoConf
.Send
end with
Set oCdoConf = Nothing
Set oCdoMail = Nothing
End Sub %>

how to display the username after login instead of login and register form

i have created a login page using ASP classic.
The problem is that after the login it redirect to the index page with the same login and register button instead of display the username or email id?
Thanks in advance...
Here is the code(VBScript).
<%
email = ""
password = ""
ErrorMessage = ""
if request.form <> "" then
email = Request.Form("email")
password = Request.Form("password")
if email = "" or password = "" then
ErrorMessage = "You must specify a username and password."
else
set conn = Server.CreateObject("ADODB.Connection")
conn.Provider = "Microsoft.Jet.OLEDB.4.0"
conn.Open("F:\main\main\App_Data\Users.mdb")
set rs = Server.CreateObject("ADODB.recordset")
rs.Open "Select * FROM Login WHERE Email = '" & email & "'", conn
response.write("email")
if rs.EOF = false then
if rs.fields("Password") = password then
Response.Redirect("indexs.asp")
end if
end if
ErrorMessage = "Login failed"
end if
end if
if ErrorMessage <> "" then
response.write("<p>" & ErrorMessage & "</p>")
response.write("<p>Please correct the errors and try again.</p>")
end if
%>
Set a session variable before you redirect to index.asp eg
Session("username") = rs("username")
You can then use the session variable in a conditional statement on your index page eg
If session("username") = "" Then
'your login form goes here
else
response.write "Welcome "+ session("username")
End If

how to allow admin and customer to login in at same place but direct to other page after click button?

i have 2 textbox for name and password and a button
there 2 table, one admin and one customer
after i enter the customer name and password , it verify whether empty or incorrect password , if correct it will go to the customer page
however if i enter admin name and password and after verify it should go to the admin page
i am only able to allow use one table for the login ? so how should i change the code below?
Protected Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
If String.IsNullOrEmpty(txtName.Text) Or String.IsNullOrEmpty(txtPassword.Text) Then
Failure.Text = "Invalid User Name and Password. Try Again."
Exit Sub
End If
Dim connectionString = ConfigurationManager.ConnectionStrings("MYdatabase").ConnectionString
Dim myConn As New SqlConnection(connectionString)
Dim cmd = "Select * From Customer where name = #name"
Dim my As New SqlCommand(cmd, myConn)
my.Parameters.AddWithValue("#name", txtName.Text)
Dim objReader As SqlDataReader
myConn.Open()
objReader = myCmd.ExecuteReader()
FailureText.Text = " "
If objReader.Read() Then
Dim pass As String = objReader.GetString(2)
Dim cusId As Integer = objReader.GetValue(0)
If pass = txtPassword.Text Then
Failure.Text = "Login Successful"
Session("name") = txtName.Text
Session("Password") = txtPassword.Text
Session("customerID") = cusId
my.Dispose()
myConn.Dispose()
Response.Redirect("CustomerHome.aspx")
Else
FailureText.Text = "Invalid Password"
End If
Else
FailureText.Text = "Login Name does not exist"
End If
End Sub
You can repeat the same process that you use to validate if the user is a customer, for validating if it's an administrator.
Where you put: FailureText.Text = "Login Name does not exist" you can repeat the code from above and first validate if the supplied username and password map to an administrator. If so, set the session for an Admin and redirect to the admin page. If not, show the failure text.
To make sure your code stays readable, I would split the validate function into multiple functions that are called from the main function(refactoring). So you would get functions like: IsValidCustomer and IsValidAdministrator that do there checking.

Resources