Imports System.Net
Imports System.Net.Mail
Imports System.Drawing
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Data

Partial Class login_ForgotPW
    Inherits System.Web.UI.Page

    Protected Sub btn_Back_Click(sender As Object, e As EventArgs)
        Response.Redirect("login/login_FLEX.aspx")
    End Sub

    Protected Sub btn_Send_Click(sender As Object, e As EventArgs)
        Dim username As String = String.Empty
        Dim password As String = String.Empty
        Dim email As String = String.Empty
        Dim tokenname As String = String.Empty
        valreqtxtEmail.Validate()
        check_UserName_regex.Validate()
        If valreqtxtEmail.IsValid = True Then
            email = txtEmail.Text
        ElseIf valreqtxtEmail.IsValid = False Then
            valreqtxtEmail.ErrorMessage = "Annotation: The given Domain is not the company domain."
            regexval_txt_Email.Validate()
            valreqtxtEmail.IsValid = True
        End If
        If check_UserName_regex.IsValid = True Then
            username = txt_Username.Text
        Else
            check_UserName_regex.ErrorMessage = "No valid Username found!"
        End If
        If String.IsNullOrEmpty(email) = False AndAlso String.IsNullOrEmpty(tokenname) = True AndAlso String.IsNullOrEmpty(password) = True AndAlso String.IsNullOrEmpty(username) = False Then
            'cDBFunctions.GetNewOpenConnection()
            Dim ConnectionString = String.Empty
            If HttpContext.Current.Request.ServerVariables("SERVER_NAME") = "localhost" Then
                'ConnectionString = "Server=DEVELOPER\DEVSQL;Database=VERAG_HOMEPAGE;Uid=sa;Pwd=BmWr501956"
                ConnectionString = "Server=DEVELOPER\DEVSQL;Database=VERAG_HOMEPAGE;Uid=AppUser;Pwd=yp/THDd?xM+pZ$;"
            Else
                ConnectionString = "Server=DEVELOPER.verag.ost.dmn\DEVSQL;Database=VERAG_HOMEPAGE;Uid=AppUser;Pwd=yp/THDd?xM+pZ$;"
                'ConnectionString = "Server=db593295684.db.1and1.com;Database=db593295684;Uid=dbo593295684;Pwd=atilla#2;"
            End If
            ' Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
            Using con As New SqlConnection(ConnectionString)
                ' Using cmd As New SqlCommand("Validate_User")
                Using cmd As New SqlCommand("SELECT Username,Password FROM [VERAG_HOMEPAGE].[dbo].[Users] WHERE Username=@Username")
                    ' cmd.CommandType = CommandType.StoredProcedure
                    cmd.Parameters.AddWithValue("@Username", username)
                    cmd.Connection = con
                    con.Open()
                    'userId = Convert.ToInt32(cmd.ExecuteScalar())
                    Dim dr As SqlDataReader = cmd.ExecuteReader()
                    If dr.Read() Then
                        username = dr("Username").ToString()
                        password = dr("Password").ToString()
                        Try
                            regexval_txt_Email.Validate()
                        Catch ex As Exception
                            Dim Msg, Style, Title As String
                            Msg = "E-Mail validation failed!" & vbCrLf + "Please try again!"
                            Style = vbRetry + vbExclamation + vbDefaultButton1
                            Title = "Authentication error!"
                            'MsgBox(Msg, Style, Title)
                            'If MsgBox(Msg, Style, Title).Yes Then
                            'txtEmail.Text = String.Empty
                            'txtEmail.Focus()
                            'ElseIf MsgBox(Msg, Style, Title).No Then
                            'End If
                        End Try
                    End If
                End Using
                con.Close()
            End Using

            tokenname = genToken(username, password, email)
            Session.Add("TokenforEmail", tokenname)
            If SendEmail(username, password, email, tokenname) = True Then
                'password = RandomString(New Random, 10)
                If (getDateoftoken(tokenname) = True) Then
                    'Dim msgboxstyle = vbDefaultButton1 + vbOK
                    'MsgBox(tokenname, msgboxstyle)
                    lblMessage.ForeColor = Color.Green
                    lblMessage.Text = "Token generated successfully."
                    'MsgBox("Token generated successfully.")
                Else
                    lblMessage.ForeColor = Color.Red
                    lblMessage.Text = "Token is not valid anymore. Please generate a new one by sending a new e-mail!"
                    'MsgBox("Token is not valid anymore. Please generate a new one by sending a new e-mail!")

                    tokenname = genToken(username, password, email)
                End If
                'SendEmail(username, password, email)
                'MsgBox("Mail would be sent successfully!")
                lblMessage.ForeColor = Color.Green
                lblMessage.Text = "The password has been sent sucessfully on the given valid e-mail address."
            ElseIf SendEmail(username, password, email, tokenname) = False Then
                'MsgBox("Mail would not be sent successfully!")
                lblMessage.ForeColor = Color.Red
                If String.IsNullOrWhiteSpace(username) = True Then
                    lblMessage.Text = "The Username was not found in our database."
                ElseIf String.IsNullOrWhiteSpace(email) = True Then
                    lblMessage.Text = "The given e-mail does not exist in our database."
                ElseIf String.IsNullOrWhiteSpace(password) = True Then
                    lblMessage.Text = "The searched password was not found in our database."
                End If

            End If
        Else
            'MsgBox("The form has not been filled completeley.", MsgBoxStyle.Critical, "Error08")
            lblMessage.ForeColor = Color.Red
            lblMessage.Text = "The form has not been filled completeley."
        End If
    End Sub

    'Function RandomString(r As Random, max As Integer) As String
    'Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!§$%&/?="
    'Dim sb As New StringBuilder
    'Dim cnt As Integer = r.Next(4, max)
    'For i As Integer = 1 To cnt
    'Dim idx As Integer = r.Next(0, s.Length)
    '       sb.Append(s.Substring(idx, 1))
    'Next
    'Return sb.ToString()
    'End Function

    Function SendEmail(username As String, password As String, email As String, tokenname As String) As Boolean
        Dim getdomianenvironment As String = String.Empty
        Dim pagename As String = String.Empty
        Dim ServPort As String = String.Empty

        Dim mailto As String = String.Empty
        Dim Betreff As String = String.Empty
        Dim htmlbody As String = String.Empty
        If HttpContext.Current.Request.ServerVariables("SERVER_NAME") = "localhost" Then
            getdomianenvironment = HttpContext.Current.Request.ServerVariables("SERVER_NAME")
            ServPort = ":" + Request.ServerVariables("SERVER_PORT")
            'pagename = Request.ServerVariables("SCRIPT_NAME")
            mailto = email
            Betreff = "Passwort reset"
            htmlbody = String.Format("Dear, {0},<br /><br /> Please follow the Link to reset your password:<br /><br />" + Environment.NewLine + "<a runat=" + "server" + " href=http://" + getdomianenvironment + ServPort + "/login/ChangePW.aspx?Par1=" + VERAG_PROG_ALLGEMEIN.cCryptography.Encrypt(tokenname) + ">Link</a>" + Environment.NewLine + "<br />Kind regards, <br />VERAG | EDV Support<br />support@verag.ag,", username, password)
        ElseIf String.IsNullOrWhiteSpace(HttpContext.Current.Request.ServerVariables("SERVER_NAME")) = False Then
            getdomianenvironment = HttpContext.Current.Request.ServerVariables("SERVER_NAME")
            ServPort = String.Empty
            'pagename = Request.ServerVariables("SCRIPT_NAME")
            mailto = email
            Betreff = "Passwort reset"
            htmlbody = String.Format("Dear, {0},<br /><br /> Please follow the Link to reset your password:<br /><br />" + Environment.NewLine + "<a runat=" + "server" + " href=http://" + getdomianenvironment + "/login/ChangePW.aspx?Par1=" + VERAG_PROG_ALLGEMEIN.cCryptography.Encrypt(tokenname) + ">Link</a>" + Environment.NewLine + "<br />Kind regards, <br />VERAG | EDV Support<br />support@verag.ag,", username, password)
        ElseIf String.IsNullOrWhiteSpace(HttpContext.Current.Request.ServerVariables("SERVER_NAME")) = True Then
            MsgBox("Error09:" + Environment.NewLine + " The Domain could not be vaildated. Check Link please or contact the Administrator of the program.")
        End If
        'Dim pg As String = Request.ServerVariables("URL")
        'MsgBox("/" + ServPort + Request.ServerVariables("URL"))

        Try
            Dim tokennametemp = genToken(username, password, email)
            'Dim Strtemp = Session.Keys.Item("urltochangepw")
            If getDateoftoken(tokennametemp) = True Then
                '  Dim attachment As Attachment = New Attachment(File.OpenRead(excel), "Kundenliste.xlsx")
                '  Msg.Attachments.Add(attachment)
                If String.IsNullOrEmpty(mailto) = False AndAlso String.IsNullOrEmpty(Betreff) = False AndAlso String.IsNullOrEmpty(htmlbody) = False Then
                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(mailto, Betreff, htmlbody)
                Else
                    'MsgBox("Error07: Die Paramter wurden nicht alle gesetzt. Bitte Felder überprüfen.", vbAbort, "Error07")
                    lblMessage.ForeColor = Color.OrangeRed
                    lblMessage.Text = "Error07: Die Paramter wurden nicht alle gesetzt. Bitte Felder überprüfen!"
                End If
                MsgBox("SENT")
                Return True
            Else
                lblMessage.ForeColor = Color.Red
                lblMessage.Text = "Error02: Mail not delivered!"
                'MsgBox("Error02: Mail not delivered!" & vbCrLf & "New Token has been generated.")
                tokennametemp = genToken(username, password, email)
                VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(mailto, Betreff, htmlbody, tokenname)
                Return False
            End If
        Catch ex As Exception
            'MsgBox(Err.Number & ex.Message & ex.StackTrace.ToString) 'Falls ein Fehler auftritt wird eine MsgBox angezeigt
        End Try
        Return False
    End Function

    Function genToken(username As String, password As String, email As String) As String
        Dim time() As Byte = BitConverter.GetBytes(DateTime.UtcNow.ToBinary())
        Dim Key() As Byte = Guid.NewGuid().ToByteArray()
        Dim token As String
        Try
            token = Convert.ToBase64String(time.Concat(Key).ToArray())
            Return token
        Catch Ex As Exception
            Dim Msg, Style, Title As String
            Msg = "Token Generation failed" & vbCrLf & "A new E-mail has been sent to the intern e-mail given."
            Style = vbRetry + vbExclamation + vbDefaultButton1
            Title = "Error05: Token-Generierung"
            'MsgBox(Msg, Style, Title)

            'If MsgBox(Msg, Style, Title).Retry Then
            'genToken(username, password, email)
            If SendEmail(username, password, email, token) = False Then
                'MsgBox("Email could not been sent because of an internal encryption error.", vbOK + vbInformation + vbDefaultButton1, "Token-Generation Error")
            Else
                'MsgBox("Email has been sent successful." & vbCr & "Please check your E-Mails!", vbOK + vbInformation + vbDefaultButton1, "Token-Generation successful!")
            End If
            'Else
            'MsgBox("Token-Generation has not been successful." & vbCrLf & "Please try again in five seconds!")
            Dim jetzt As DateTime = DateTime.UtcNow
            Dim wenn As DateTime = DateTime.UtcNow.AddSeconds(-5)

            If jetzt < wenn Then
                'Return "NotYet"
                'Else
                token = genToken(username, password, email)
                Return token
                'End If
            End If
        End Try
    End Function

    Function getDateoftoken(tokenname As String) As Boolean
        Dim data() As Byte = Convert.FromBase64String(tokenname)
        Dim wenn As DateTime = DateTime.FromBinary(BitConverter.ToInt64(data, 0))
        If wenn < DateTime.UtcNow.AddMinutes(-30) Then
            tokenname = String.Empty

            'MsgBox("Token has not been found or is too old!" + Environment.NewLine + "Please send a new E-mail!")
            Return False
        ElseIf tokenname = "NotYet" Then
            Return False
        ElseIf tokenname = "Error04" Then
            Return False
        Else
            Return True
        End If
    End Function
End Class