Imports System.Data.SqlClient
Imports System.Data
Imports System.Security.Cryptography
Partial Class login_FLEX
    Inherits System.Web.UI.Page
    Private Customer_ID As String = String.Empty
    Private UserNaMe As String = String.Empty
    Private passw As String = String.Empty
    Private USERID As String = String.Empty
    Private salt As Byte()
    Private intzahl As Integer
    Private intzahliterats As Integer
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        VERAG_VARIABLES.initerrorcount()
        If Page.IsPostBack = True Then
            Page.MaintainScrollPositionOnPostBack = True
            intzahl = VERAG_VARIABLES.RandomInteger(Math.Pow(2, 7), Math.Pow(2, 10))
            intzahliterats = VERAG_VARIABLES.getiterationnumber
            salt = VERAG_VARIABLES.GenerateSalt(intzahl)
        Else
            Page.MaintainScrollPositionOnPostBack = False
        End If

    End Sub
    Protected Async Sub ValidateUser(sender As Object, e As EventArgs)
        ' cDBFunctions.GetNewOpenConnection()
        Dim ConnectionString = ""
        If HttpContext.Current.Request.ServerVariables("SERVER_NAME") = "localhost" Then
            VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
            '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
            VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
            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 tb As TextBox = Login1.FindControl("txt_CustomerID")
        Dim tb_M As TextBox = Login2.FindControl("txt_CustomerID_M")
        Dim tb2 As TextBox = Login1.FindControl("Username")
        Dim tb2_M As TextBox = Login2.FindControl("Username")
        Dim tb3 As TextBox = Login1.FindControl("Password")
        Dim tb3_M As TextBox = Login2.FindControl("Password")

        Dim reqfieldvaluserID As RequiredFieldValidator = Login1.FindControl("CustomerIDrequired")
        Dim reqfieldvaluserID_M As RequiredFieldValidator = Login2.FindControl("CustomerID_M_required")
        Dim reqfieldvaluserName As RequiredFieldValidator = Login1.FindControl("UserNamerequired")
        Dim reqfieldvaluserName_M As RequiredFieldValidator = Login2.FindControl("UserName_M_required")
        Dim reqfieldvalpassw As RequiredFieldValidator = Login1.FindControl("Passwordrequired")
        Dim reqfieldvalpassw_M As RequiredFieldValidator = Login2.FindControl("Passwordrequired_M")

        Dim regexuserID As RegularExpressionValidator = Login1.FindControl("valid_getNumberInput")
        Dim regexuserID_M As RegularExpressionValidator = Login2.FindControl("valid_getNumber_M_Input")
        Dim regexusername As RegularExpressionValidator = Login1.FindControl("check_UserName_regex")
        Dim regexusername_M As RegularExpressionValidator = Login2.FindControl("check_UserName_M_regex")
        Dim cb As CheckBox = Login1.FindControl("RememberMe")
        Dim cb_M As CheckBox = Login2.FindControl("RememberMe_M")


        If String.IsNullOrEmpty(tb.Text) = False AndAlso String.IsNullOrEmpty(tb_M.Text) = True Then
            reqfieldvaluserID.Enabled = True
            reqfieldvaluserID_M.Enabled = False
            reqfieldvaluserID.Validate()
            If reqfieldvaluserID.IsValid = True Then
                regexuserID.Validate()
                If regexuserID.IsValid Then
                    Customer_ID = tb.Text
                Else
                    VERAG_VARIABLES.seterrorcount(1)
                    regexuserID.ErrorMessage = VERAG_VARIABLES.geterrornumb + ": Customer-ID has to be a number."
                End If
            End If
        End If
        If String.IsNullOrEmpty(tb_M.Text) = False AndAlso String.IsNullOrEmpty(tb.Text) = True Then
            reqfieldvaluserID.Enabled = False
            reqfieldvaluserID_M.Enabled = True
            If reqfieldvaluserID_M.IsValid = True Then
                regexusername_M.Validate()
                If regexusername_M.IsValid Then
                    Customer_ID = tb_M.Text
                Else
                    VERAG_VARIABLES.seterrorcount(2)
                    regexusername_M.ErrorMessage = VERAG_VARIABLES.geterrornumb + "Customer-ID does not have any special characters in it."
                End If
            End If
        End If
        If String.IsNullOrEmpty(tb2.Text) = False AndAlso String.IsNullOrEmpty(tb2_M.Text) = True Then
            reqfieldvaluserName.Enabled = True
            reqfieldvaluserName_M.Enabled = False
            regexusername.Validate()
            If reqfieldvaluserName.IsValid = True Then
                If regexusername.IsValid Then
                    UserNaMe = tb2.Text
                Else
                    VERAG_VARIABLES.seterrorcount(2)
                    regexusername_M.ErrorMessage = VERAG_VARIABLES.geterrornumb + "Username does not have any special characters in it."
                End If
            Else

                reqfieldvaluserName.ErrorMessage = String.Empty
            End If
        End If
        If String.IsNullOrEmpty(tb2_M.Text) = False AndAlso String.IsNullOrEmpty(tb2.Text) = True Then
            reqfieldvaluserName.Enabled = False
            reqfieldvaluserName_M.Enabled = True
            reqfieldvaluserName_M.Validate()
            If reqfieldvaluserName_M.IsValid = True Then
                regexusername_M.Validate()
                If regexusername.IsValid Then
                    UserNaMe = tb2_M.Text
                Else
                    VERAG_VARIABLES.seterrorcount(3)
                    regexusername.ErrorMessage = VERAG_VARIABLES.geterrornumb + "Password has to match the criterias of tge info button."
                End If
            End If
        End If
        If String.IsNullOrEmpty(tb3.Text) = False AndAlso String.IsNullOrEmpty(tb3_M.Text) = True Then
            reqfieldvalpassw.Enabled = True
            reqfieldvalpassw_M.Enabled = False
            reqfieldvalpassw.Validate()
            If reqfieldvalpassw.IsValid = True Then
                passw = tb3.Text
            End If
        End If
        If String.IsNullOrEmpty(tb3_M.Text) = False AndAlso String.IsNullOrEmpty(tb3.Text) = True Then
            reqfieldvalpassw.Enabled = False
            reqfieldvalpassw_M.Enabled = True
            reqfieldvalpassw_M.Validate()
            If reqfieldvalpassw_M.IsValid = True Then
                passw = tb3_M.Text
            Else
                VERAG_VARIABLES.seterrorcount(4)
                reqfieldvalpassw_M.ErrorMessage = String.Empty
            End If
        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 KundenNr,Username,Password FROM [VERAG_HOMEPAGE].[dbo].[Users] WHERE Username=@Username AND Password=@Password AND KundenNr=@KundenNr")
                ' cmd.CommandType = CommandType.StoredProcedure
                cmd.Parameters.AddWithValue("@Username", UserNaMe)
                cmd.Parameters.AddWithValue("@KundenNr", Customer_ID)
                cmd.Parameters.AddWithValue("@Password", passw)
                cmd.Connection = con
                con.Open()
                ' userId = Convert.ToInt32(cmd.ExecuteScalar())
                Dim dr As SqlDataReader = cmd.ExecuteReader()
                If dr.HasRows Then
                    dr.Read()
                    'MsgBox(dr.Item(0).ToString())
                    Select Case dr.Item(0)
                        Case 0
                            VERAG_VARIABLES.seterrorcount(5)
                            Login1.FailureText = VERAG_VARIABLES.geterrornumb + "Username and/or Password do not match."
                            Exit Select
                        Case -2
                            VERAG_VARIABLES.seterrorcount(6)
                            Login1.FailureText = VERAG_VARIABLES.geterrornumb + "Account is not activated."
                            Exit Select
                        Case Else
                            If tb.Text = dr("KundenNr").ToString Then
                                Customer_ID = dr("KundenNr").ToString
                            Else
                                VERAG_VARIABLES.seterrorcount(7)
                                Login1.FailureText = VERAG_VARIABLES.geterrornumb + "ID cannot be found in the database!"
                            End If
                            If tb2.Text = dr("Username") Then
                                UserNaMe = dr("Username").ToString
                            Else
                                VERAG_VARIABLES.seterrorcount(8)
                                Login1.FailureText = VERAG_VARIABLES.geterrornumb + "Username is not in the database!"
                            End If
                            If tb3.Text = dr("Password") Then
                                Dim hashpw As Byte() = Await VERAG_VARIABLES.HashPassword(passw, salt, intzahliterats, intzahl)
                                If Await VERAG_VARIABLES.Verifyhash(dr("Password").ToString, salt, hashpw, intzahliterats, intzahl) = True Then
                                    passw = dr("Password").ToString
                                Else
                                    passw = String.Empty
                                End If
                            Else
                                VERAG_VARIABLES.seterrorcount(9)
                                Login1.FailureText = VERAG_VARIABLES.geterrornumb + "Password is not in the database!"
                            End If

                            'MsgBox("Erfolgreich validiert.")
                            Session.Add("test", UserNaMe)
                            Session.Add("CustomerID", Customer_ID)
                            Session.Add("PW", passw)
                            Exit Select
                    End Select
                End If
                dr.Close()
                con.Close()
            End Using
        End Using

        If String.IsNullOrEmpty(tb2_M.Text) = False AndAlso String.IsNullOrEmpty(tb2.Text) = True Then
            FormsAuthentication.SetAuthCookie(Login1.UserName, cb_M.Checked)
        ElseIf String.IsNullOrEmpty(tb2.Text) = False AndAlso String.IsNullOrEmpty(tb2_M.Text) = True Then
            FormsAuthentication.SetAuthCookie(Login2.UserName, cb.Checked)
        End If
        'If (String.IsNullOrEmpty(passw) = False And String.IsNullOrEmpty(UserNaMe) = False And String.IsNullOrEmpty(Customer_ID) = False) Then
        'Dim str = gensaltToken(UserNaMe, passw, Customer_ID, Session.IsNewSession)
        'MsgBox(str)
        'End If

        FormsAuthentication.RedirectFromLoginPage(UserNaMe, True)


    End Sub

    Protected Sub LoginButton_Click(sender As Object, e As EventArgs)
        Validate("Login")
        Session.Add("test", UserNaMe)
        Session.Add("CustomerID", Customer_ID)
        Session.Add("PW", passw)
    End Sub
    Protected Sub LoginButton_M_Click(sender As Object, e As EventArgs)
        Validate("Login_M")
        Session.Add("test", UserNaMe)
        Session.Add("CustomerID", Customer_ID)
        Session.Add("PW", passw)
    End Sub
    Async Function gensaltToken(username As String, password As String, CustomerID As String, salt As Byte(), intzahliterats As Integer, intzahl As Integer, isnewSession As Boolean) As Threading.Tasks.Task(Of String)
        If isnewSession = False Then
            Dim time() As Byte = BitConverter.GetBytes(DateTime.UtcNow.ToBinary())
            Dim Key() As Byte = Guid.NewGuid().ToByteArray()
            Dim token As Byte()

            token = Await VERAG_VARIABLES.HashPassword(Convert.ToBase64String(time.Concat(Key).ToArray()), salt, intzahliterats, intzahl)
            Return VERAG_PROG_ALLGEMEIN.cCryptography3.Encrypt(Convert.ToBase64String(token))

            '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)
            token = Await VERAG_VARIABLES.HashPassword(Convert.ToBase64String(time.Concat(Key).ToArray()), salt, intzahliterats, intzahl)
            Return VERAG_PROG_ALLGEMEIN.cCryptography3.Encrypt(Convert.ToBase64String(token))

            '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 = Await VERAG_VARIABLES.HashPassword(Convert.ToBase64String(time.Concat(Key).ToArray()), salt, intzahliterats, intzahl)
                Return VERAG_PROG_ALLGEMEIN.cCryptography3.Encrypt(Convert.ToBase64String(token))
                'End If
            End If

        End If
    End Function

    Protected Sub CreateTestusers_Click(sender As Object, e As EventArgs)
        Dim str As String = String.Empty
        Dim textbox As TextBox = Page.FindControl("txt_numbuserstes")
        str = textbox.Text

        TestPerformance.createnUsers(Integer.Parse(str))
    End Sub
End Class