-->

Membuat Form Login Dengan Captcha di VB.Net

selamat sore sobat semuanya pembaca setia blog ane ini , hehe...., hari ini ane akan share tentang bagaimana caranya membuat aplikasi login di vb.net dengan menggunakan captcha ? udah pada tau kan captcha itu apa ?

Secara harfiah Captcha singkatan dari ”Completely Automated Public Turing test to tell Computers and Humans Apart” ( dikutip dari Wikipedia ), dibuat untuk membedakan antara mesin ( bot ) dan manusia. Istilah Captcha ini dicetuskan oleh Luis von Ahn, Manuel Blum, and Nicholas J. Hopper dari Carnegie MellonUniversity, dan John Langford dari IBM pada tahun 2000.
kenapa mesti dibedakan? karena banyak buanget “penjahat form” alias program SPAM COMMENT yang bisa aja menyerang website kita kapanpun dengan tanpa “sopan santun” menyisipkan comment pada guestbook/forum yang isinya bisa berupa promosi atau malah link2 kesitus porno(ih….atut…) . kebayang ga gimana jadinya tampilan web kita?

oke langsung aja gan , disini ane mnggunakan database mysql sebagai pengolahan databasenya . ane asumsikan agan udah bisa mengkoneksikan database mysql dengan vb.net. Jika ternyata belum , agan bisa baca artikel ini :koneksi vb.net dengan mysql.

Let's chek it on!

1. Pertama buka dulu visual studio agan , kemudian buat sebuah form dengan nama "frmLogin" . Silahkan terserah cara agan mendesainnya , yang jelas objek yang ada yaitu :
  • 3 buah textbox ( texbox untuk menampung username , password , dan captcha ).
  • 2 buah button ( button login dan button refresh captcha ).
  • 1 buah picture box untuk menampilkan kode captcha .
hasilnya seperti ini gan :


silahkan kreasikan sendiri imaginasinya agan untuk mendesainnya .

2. Jika sudah lanjut ke tahap berikutnya yaitu buatlah sebuah modul untuk koneksi database mysql dengan vb.net nya . Klik menu project pada bagian atas kemudian pilih add module , dan copas saja gan code berikut ini :

Imports MySql.Data.MySqlClient.MySqlConnection
Module modKoneksi
    Public conn As New MySql.Data.MySqlClient.MySqlConnection
    Public Sub koneksi(ByVal server As String, ByVal user As String, ByVal pass As String, _
                       ByVal db As String, ByVal port As String)
        Try
            If conn.State = ConnectionState.Closed Then
                conn.ConnectionString = "DATABASE=" & db _
                & ";SERVER = " & server _
                & ";user id=" & user & ";password=" & pass & ";port=" & port & ";charset=utf8"
                conn.Open()

            End If
        Catch ex As MySql.Data.MySqlClient.MySqlException
            MsgBox("Koneksi ke server gagal", MsgBoxStyle.Critical, "USB Monitoring")
        End Try
    End Sub

    Public Sub disconnect()
        Try
            conn.Open()
        Catch ex As MySql.Data.MySqlClient.MySqlException

        End Try
    End Sub
End Module

simpan code diatas dengan nama modKoneksi atau terserah agan aja dech mau pake nama apa.

3. Jika sudah , klik 2x pada form login , dan pada baris paling atas , importlah mysql data .  Berikut kodenya :
Imports MySql.Data.MySqlClient
jika pada waktu ketika imports pilihan mysql belum ada , maka caranya , klik menu project dan pilih add reference , kemudian cari MySQL data , jika sudah klik OK.


dan selajutnya buat deklarasi variable untuk objeknya , copas saja gan kode berikut ini :

 Dim DrawingFont As New Font("Arial", 20)
    Dim CaptchaImage As New Bitmap(140, 40)
    Dim CaptchaGraf As Graphics = Graphics.FromImage(CaptchaImage)
    Dim Alphabet As String = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
    Dim CaptchaString, TickRandom As String
    Dim ProcessNumber As Integer


jika sudah , kemudian buat sebuah fungsi untuk mengenerate kode captcha nya , seperti ini :
Private Sub GenerateCaptcha()
        ProcessNumber = My.Computer.Clock.LocalTime.Millisecond
        If ProcessNumber < 521 Then
            ProcessNumber = ProcessNumber \ 10
            CaptchaString = Alphabet.Substring(ProcessNumber, 1)
        Else
            CaptchaString = CStr(My.Computer.Clock.LocalTime.Second \ 6)
        End If
        ProcessNumber = My.Computer.Clock.LocalTime.Second
        If ProcessNumber < 30 Then
            ProcessNumber = Math.Abs(ProcessNumber - 8)
            CaptchaString += Alphabet.Substring(ProcessNumber, 1)
        Else
            CaptchaString += CStr(My.Computer.Clock.LocalTime.Minute \ 6)
        End If
        ProcessNumber = My.Computer.Clock.LocalTime.DayOfYear
        If ProcessNumber Mod 2 = 0 Then
            ProcessNumber = ProcessNumber \ 8
            CaptchaString += Alphabet.Substring(ProcessNumber, 1)
        Else
            CaptchaString += CStr(ProcessNumber \ 37)
        End If
        TickRandom = My.Computer.Clock.TickCount.ToString
        ProcessNumber = Val(TickRandom.Substring(TickRandom.Length - 1, 1))
        If ProcessNumber Mod 2 = 0 Then
            CaptchaString += CStr(ProcessNumber)
        Else
            ProcessNumber = Math.Abs(Int(Math.Cos(Val(TickRandom)) * 51))
            CaptchaString += Alphabet.Substring(ProcessNumber, 1)
        End If
        ProcessNumber = My.Computer.Clock.LocalTime.Hour
        If ProcessNumber Mod 2 = 0 Then
            ProcessNumber = Math.Abs(Int(Math.Sin(Val(My.Computer.Clock.LocalTime.Year)) * 51))
            CaptchaString += Alphabet.Substring(ProcessNumber, 1)
        Else
            CaptchaString += CStr(ProcessNumber \ 3)
        End If
        ProcessNumber = My.Computer.Clock.LocalTime.Millisecond
        If ProcessNumber > 521 Then
            ProcessNumber = Math.Abs((ProcessNumber \ 10) - 52)
            CaptchaString += Alphabet.Substring(ProcessNumber, 1)
        Else
            CaptchaString += CStr(My.Computer.Clock.LocalTime.Second \ 6)
        End If
        CaptchaGraf.Clear(Color.White)

        For hasher As Integer = 0 To 5
            CaptchaGraf.DrawString(CaptchaString.Substring(hasher, 1), DrawingFont, Brushes.Black, hasher * 20 + hasher + ProcessNumber \ 200, (hasher Mod 3) * (ProcessNumber \ 200))
        Next
        PictureBox2.Image = CaptchaImage
    End Sub

kemudian tambahkan baris kode dibawah ini pada form_load nya :
Private Sub frmLogin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        GenerateCaptcha()
        koneksi("localhost", "root", "WnbZNXD7Hrmr4cLC", "dbUSB", "")
    End Sub

kemudian tambahkan kode untuk memanggil fungsi generate captcha diatas tadi pada form refresh sehingga , jika diklik maka kode akan diacak lagi . kodenya seperti ni :
 GenerateCaptcha()

dan yang terakhir pada button loginnya copas kode berikut ini gan :
 Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        If txtUsername.Text = "" Then
            MsgBox("Username masih kosong", vbExclamation, "USB Monitoring")
            txtUsername.Focus()
            Exit Sub
        ElseIf txtPassword.Text = "" Then
            MsgBox("Password masih kosong", vbExclamation, "USB Monitoring")
            txtPassword.Focus()
            Exit Sub
        Else
            If txtCaptcha.Text = CaptchaString Then
                Dim myAdapter As New MySqlDataAdapter
                Dim sqlQuery = "SELECT * FROM user WHERE username='" + txtUsername.Text + "' AND password='" + txtPassword.Text + "'"
                Dim myCommand As New MySqlCommand
                myCommand.Connection = conn
                myCommand.CommandText = sqlQuery
                myAdapter.SelectCommand = myCommand
                Dim myData As MySqlDataReader
                myData = myCommand.ExecuteReader()

                If myData.HasRows = 0 Then
                    MsgBox("Username atau Password yang anda masukkan salah.! Kemungkinan juga username anda belum terdaftar. Hubungi development.!", vbExclamation, "USB Monitoring")
                    txtUsername.Text = ""
                    txtPassword.Text = ""
                    txtCaptcha.Text = ""
                    txtUsername.Focus()
                    Call GenerateCaptcha()
                Else
                    Me.Hide()
                    frmUtama.StatusStrip1.Items(0).Text = "Login As : " & txtUsername.Text
                    frmUtama.Show()

                End If


            Else
                MsgBox("Kode Captcha yang anda masukkan salah.!", vbExclamation, "USB Monitoring")
                txtUsername.Text = ""
                txtPassword.Text = ""
                txtCaptcha.Text = ""
                txtUsername.Focus()
                Exit Sub
            End If
        End If
    End Sub

Jadi kode lengkapnya kayak gini gan :
Imports MySql.Data.MySqlClient
Public Class frmLogin
    Dim DrawingFont As New Font("Arial", 20)
    Dim CaptchaImage As New Bitmap(140, 40)
    Dim CaptchaGraf As Graphics = Graphics.FromImage(CaptchaImage)
    Dim Alphabet As String = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
    Dim CaptchaString, TickRandom As String
    Dim ProcessNumber As Integer
    Private Sub GenerateCaptcha()
        ProcessNumber = My.Computer.Clock.LocalTime.Millisecond
        If ProcessNumber < 521 Then
            ProcessNumber = ProcessNumber \ 10
            CaptchaString = Alphabet.Substring(ProcessNumber, 1)
        Else
            CaptchaString = CStr(My.Computer.Clock.LocalTime.Second \ 6)
        End If
        ProcessNumber = My.Computer.Clock.LocalTime.Second
        If ProcessNumber < 30 Then
            ProcessNumber = Math.Abs(ProcessNumber - 8)
            CaptchaString += Alphabet.Substring(ProcessNumber, 1)
        Else
            CaptchaString += CStr(My.Computer.Clock.LocalTime.Minute \ 6)
        End If
        ProcessNumber = My.Computer.Clock.LocalTime.DayOfYear
        If ProcessNumber Mod 2 = 0 Then
            ProcessNumber = ProcessNumber \ 8
            CaptchaString += Alphabet.Substring(ProcessNumber, 1)
        Else
            CaptchaString += CStr(ProcessNumber \ 37)
        End If
        TickRandom = My.Computer.Clock.TickCount.ToString
        ProcessNumber = Val(TickRandom.Substring(TickRandom.Length - 1, 1))
        If ProcessNumber Mod 2 = 0 Then
            CaptchaString += CStr(ProcessNumber)
        Else
            ProcessNumber = Math.Abs(Int(Math.Cos(Val(TickRandom)) * 51))
            CaptchaString += Alphabet.Substring(ProcessNumber, 1)
        End If
        ProcessNumber = My.Computer.Clock.LocalTime.Hour
        If ProcessNumber Mod 2 = 0 Then
            ProcessNumber = Math.Abs(Int(Math.Sin(Val(My.Computer.Clock.LocalTime.Year)) * 51))
            CaptchaString += Alphabet.Substring(ProcessNumber, 1)
        Else
            CaptchaString += CStr(ProcessNumber \ 3)
        End If
        ProcessNumber = My.Computer.Clock.LocalTime.Millisecond
        If ProcessNumber > 521 Then
            ProcessNumber = Math.Abs((ProcessNumber \ 10) - 52)
            CaptchaString += Alphabet.Substring(ProcessNumber, 1)
        Else
            CaptchaString += CStr(My.Computer.Clock.LocalTime.Second \ 6)
        End If
        CaptchaGraf.Clear(Color.White)

        For hasher As Integer = 0 To 5
            CaptchaGraf.DrawString(CaptchaString.Substring(hasher, 1), DrawingFont, Brushes.Black, hasher * 20 + hasher + ProcessNumber \ 200, (hasher Mod 3) * (ProcessNumber \ 200))
        Next
        PictureBox2.Image = CaptchaImage
    End Sub
    Private Sub frmLogin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        GenerateCaptcha()
        koneksi("localhost", "root", "WnbZNXD7Hrmr4cLC", "dbUSB", "")
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        GenerateCaptcha()
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        If txtUsername.Text = "" Then
            MsgBox("Username masih kosong", vbExclamation, "USB Monitoring")
            txtUsername.Focus()
            Exit Sub
        ElseIf txtPassword.Text = "" Then
            MsgBox("Password masih kosong", vbExclamation, "USB Monitoring")
            txtPassword.Focus()
            Exit Sub
        Else
            If txtCaptcha.Text = CaptchaString Then
                Dim myAdapter As New MySqlDataAdapter
                Dim sqlQuery = "SELECT * FROM user WHERE username='" + txtUsername.Text + "' AND password='" + txtPassword.Text + "'"
                Dim myCommand As New MySqlCommand
                myCommand.Connection = conn
                myCommand.CommandText = sqlQuery
                myAdapter.SelectCommand = myCommand
                Dim myData As MySqlDataReader
                myData = myCommand.ExecuteReader()

                If myData.HasRows = 0 Then
                    MsgBox("Username atau Password yang anda masukkan salah.! Kemungkinan juga username anda belum terdaftar. Hubungi development.!", vbExclamation, "USB Monitoring")
                    txtUsername.Text = ""
                    txtPassword.Text = ""
                    txtCaptcha.Text = ""
                    txtUsername.Focus()
                    Call GenerateCaptcha()
                Else
                    Me.Hide()
                    frmUtama.StatusStrip1.Items(0).Text = "Login As : " & txtUsername.Text
                    frmUtama.Show()

                End If


            Else
                MsgBox("Kode Captcha yang anda masukkan salah.!", vbExclamation, "USB Monitoring")
                txtUsername.Text = ""
                txtPassword.Text = ""
                txtCaptcha.Text = ""
                txtUsername.Focus()
                Exit Sub
            End If
        End If
    End Sub
End Class

selesai dech gan , silahkan agan test hasilnya sendiri ,

see uuuu next time . . . .


1 komentar:

Click to comment