Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
mauryparra committed Dec 6, 2017
2 parents 7957657 + 52cdeaf commit 4862533
Show file tree
Hide file tree
Showing 9 changed files with 197 additions and 38 deletions.
134 changes: 128 additions & 6 deletions SireCu/Clases/Usuario.vb
Original file line number Diff line number Diff line change
@@ -1,17 +1,139 @@
Module Usuario

Public Function verificarUsuario(ByVal user As String, ByVal pass As String)
Public Class SampleIPrincipal
Implements System.Security.Principal.IPrincipal

Dim sql As String = "SELECT * FROM Usuarios WHERE usuario = '" & user & "'"
Private identityValue As SampleIIdentity

Public ReadOnly Property Identity() As System.Security.Principal.IIdentity Implements System.Security.Principal.IPrincipal.Identity
Get
Return identityValue
End Get
End Property

Public Function IsInRole(ByVal role As String) As Boolean Implements System.Security.Principal.IPrincipal.IsInRole
Return role = identityValue.Role.ToString
End Function

Public Sub New(ByVal name As String, ByVal password As String)
identityValue = New SampleIIdentity(name, password)
End Sub

End Class

Public Class SampleIIdentity
Implements System.Security.Principal.IIdentity

Private nameValue As String
Private authenticatedValue As Boolean
Private roleValue As ApplicationServices.BuiltInRole

Public ReadOnly Property AuthenticationType As String Implements System.Security.Principal.IIdentity.AuthenticationType
Get
Return "SqlCEDatabase"
End Get
End Property

Public ReadOnly Property IsAuthenticated As Boolean Implements System.Security.Principal.IIdentity.IsAuthenticated
Get
Return authenticatedValue
End Get
End Property

Public ReadOnly Property Name As String Implements System.Security.Principal.IIdentity.Name
Get
Return nameValue
End Get
End Property

Public ReadOnly Property Role() As ApplicationServices.BuiltInRole
Get
Return roleValue
End Get
End Property

Public Sub New(ByVal name As String, ByVal password As String)
' Contraseña es Case Sensitive, el Usuario no lo es
If IsValidNameAndPassword(name, password) Then
nameValue = name
authenticatedValue = True
Else
nameValue = ""
authenticatedValue = False
End If

End Sub

Private Function IsValidNameAndPassword(ByVal username As String, ByVal password As String) As Boolean

' Look up the stored hashed password and salt for the username.
Dim storedHashedPW As String = GetHashedPassword(username)
Dim salt As String = GetSalt(username)

'Create the salted hash.
Dim rawSalted As String = salt & Trim(password)
Dim saltedPwBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(rawSalted)
Dim sha512 As New System.Security.Cryptography.SHA512CryptoServiceProvider
Dim hashedPwBytes() As Byte = sha512.ComputeHash(saltedPwBytes)
Dim hashedPw As String = Convert.ToBase64String(hashedPwBytes)

' Compare the hashed password with the stored password.
Return hashedPw = storedHashedPW

End Function


End Class

Friend Function GetHashedPassword(ByVal username As String) As String
' Code that gets the user's hashed password

Dim sql As String = "SELECT contraseña FROM Usuarios WHERE usuario = '" & username & "'"
Dim dt As DataTable = consultarReader(sql)

If dt.Rows.Count = 0 Then
Return False
ElseIf dt.Rows(0).Item("contraseña") = pass Then
Return True
Else Return False
Return ""
Else
Return dt.Rows(0).Item("contraseña")
End If
End Function

Friend Function GetSalt(ByVal username As String) As String
' Code that gets the user's salt

Dim sql As String = "SELECT salt FROM Usuarios WHERE usuario = '" & username & "'"
Dim dt As DataTable = consultarReader(sql)

If dt.Rows.Count = 0 Then
Return ""
Else
Return dt.Rows(0).Item("salt")
End If
End Function

Public Function CreateRandomSalt() As String
'the following is the string that will hold the salt charachters
Dim mix As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+=][}{<>"
Dim salt As String = ""
Dim rnd As New Random
Dim sb As New System.Text.StringBuilder
For i As Integer = 1 To 100 'Length of the salt
Dim x As Integer = rnd.Next(0, mix.Length - 1)
salt &= (mix.Substring(x, 1))
Next
Return salt
End Function

Public Function CreateHashedPassword(ByVal contraseña As String, ByVal salt As String) As String

'Create the hashed password.
Dim rawSalted As String = salt & Trim(contraseña)
Dim saltedPwBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(rawSalted)
Dim sha512 As New System.Security.Cryptography.SHA512CryptoServiceProvider
Dim hashedPwBytes() As Byte = sha512.ComputeHash(saltedPwBytes)
Dim hashedPw As String = Convert.ToBase64String(hashedPwBytes)

Return hashedPw
End Function

Public Function tipoDeUsuario(ByVal user As String)
Expand Down
Binary file modified SireCu/DBSireCu.sdf
Binary file not shown.
18 changes: 9 additions & 9 deletions SireCu/My Project/Application.Designer.vb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions SireCu/My Project/Application.myapp
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<?xml version="1.0" encoding="utf-16"?>
<?xml version="1.0" encoding="utf-8"?>
<MyApplicationData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MySubMain>true</MySubMain>
<MainForm>Principal</MainForm>
<SingleInstance>false</SingleInstance>
<ShutdownMode>0</ShutdownMode>
<EnableVisualStyles>true</EnableVisualStyles>
<AuthenticationMode>0</AuthenticationMode>
<AuthenticationMode>1</AuthenticationMode>
<SaveMySettingsOnExit>true</SaveMySettingsOnExit>
</MyApplicationData>
4 changes: 2 additions & 2 deletions SireCu/Paneles/ABMEgresos.vb
Original file line number Diff line number Diff line change
Expand Up @@ -681,7 +681,7 @@ Public Class ABMEgresos
Private Sub cbSeccional_Validating(sender As Object, e As CancelEventArgs) Handles cbSeccional.Validating
If (sender.Text = "") Or (exist("Seccionales", "nombre", sender.Text) = False) Then
Principal.ErrorProvider.SetError(sender, "Debe ingresar una Seccional correcta." & vbCrLf &
"Puede agregar una nueva en la seccion Administrar")
"Puede configurarlo desde el Menú Editar")
If Not ControlesConErroresAgregar.Contains(sender) Then
ControlesConErroresAgregar.Add(sender)
End If
Expand Down Expand Up @@ -823,7 +823,7 @@ Public Class ABMEgresos
Private Sub ComboBoxSeccional_Validating(sender As Object, e As CancelEventArgs) Handles ComboBoxSeccional.Validating
If (sender.Text = "") Or (exist("Seccionales", "nombre", sender.Text) = False) Then
Principal.ErrorProvider.SetError(sender, "Debe ingresar una Seccional correcta." & vbCrLf &
"Puede agregar una nueva en la seccion Administrar")
"Puede configurarlo desde el Menú Editar")
If Not ControlesConErroresModificar.Contains(sender) Then
ControlesConErroresModificar.Add(sender)
End If
Expand Down
47 changes: 35 additions & 12 deletions SireCu/Paneles/ABMUsuarios.vb
Original file line number Diff line number Diff line change
Expand Up @@ -63,28 +63,40 @@ Public Class ABMUsuarios
End If
Else
Principal.ErrorProvider.SetError(cb_Rol, "")
ControlesConErrores.Remove(cb_Rol)
If ControlesConErrores.Contains(cb_Rol) Then
ControlesConErrores.Remove(cb_Rol)
End If
End If

If ControlesConErrores.Count > 0 Then
MsgBox("Por favor revise los campos ingresados", MsgBoxStyle.Exclamation, "Error")
Exit Sub
End If

'Si existe el usuario, preguntamos por modificarlo
Dim modificar As Boolean = 0
If (exist("Usuarios", "usuario", tb_Usuario.Text) = True) Then
modificar = 1
End If

Select Case btn_Guardar.Text
Case "Actualizar"
If (MsgBox("Quiere Modificar al usuario " & tb_Usuario.Text & "?",

If (exist("Usuarios", "usuario", tb_Usuario.Text) = True) Then
If LCase(tb_Usuario.Text) <> LCase(DGVAdmin.CurrentRow.Cells(1).Value) Then
MsgBox("El nombre de usuario ingresado ya se encuentra utilizado." &
vbCrLf & "Por favor, intentelo con otro nuevamente.", MsgBoxStyle.Exclamation, "Usuario Inválido")
Exit Sub
End If
End If

If (MsgBox("Quiere Modificar al usuario " & DGVAdmin.CurrentRow.Cells(1).Value & "?",
MsgBoxStyle.OkCancel, "Modificar?") = MsgBoxResult.Ok) Then

Dim contraseña As String = ""
If tb_Contraseña.Text = Usuario.GetHashedPassword(DGVAdmin.CurrentRow.Cells(1).Value) Then
contraseña = tb_Contraseña.Text
Else
contraseña = Usuario.CreateHashedPassword(tb_Contraseña.Text, Usuario.GetSalt(DGVAdmin.CurrentRow.Cells(1).Value))
End If

Principal.query = "UPDATE [Usuarios] SET " &
"usuario = '" & tb_Usuario.Text &
"' ,contraseña = '" & tb_Contraseña.Text &
"' ,contraseña = '" & contraseña &
"' ,rol = '" & cb_Rol.Text &
"' WHERE id= '" & DGVAdmin.CurrentRow.Cells(0).Value & "'"
consultarNQ(Principal.query, Principal.command)
Expand All @@ -94,12 +106,22 @@ Public Class ABMUsuarios
Exit Sub
End If
Case "Guardar"

If (exist("Usuarios", "usuario", tb_Usuario.Text) = True) Then
MsgBox("El nombre de usuario ingresado ya se encuentra utilizado." &
vbCrLf & "Por favor, intentelo con otro nuevamente.", MsgBoxStyle.Exclamation, "Usuario Inválido")
Exit Sub
End If

If (MsgBox("Guardar nuevo usuario?", MsgBoxStyle.OkCancel, "Guardar?") = MsgBoxResult.Ok) Then

Principal.query = "INSERT INTO [Usuarios] (usuario,contraseña, rol)
Dim salt As String = Usuario.CreateRandomSalt()
Dim contraseña As String = Usuario.CreateHashedPassword(tb_Contraseña.Text, salt)

Principal.query = "INSERT INTO [Usuarios] (usuario, contraseña, rol, salt)
VALUES ('" &
tb_Usuario.Text & "', '" & tb_Contraseña.Text &
"', '" & cb_Rol.Text & "')"
tb_Usuario.Text & "', '" & contraseña &
"', '" & cb_Rol.Text & "', '" & salt & "')"
consultarNQ(Principal.query, Principal.command)

MsgBox("Guardado Correctamente!", MsgBoxStyle.Information, "Guardado")
Expand Down Expand Up @@ -214,6 +236,7 @@ Public Class ABMUsuarios
DGVAdmin.Columns.Item("usuario").HeaderText = "Usuario"
DGVAdmin.Columns.Item("contraseña").HeaderText = "Contraseña"
DGVAdmin.Columns.Item("rol").HeaderText = "Rol"
DGVAdmin.Columns.Item("salt").Visible = False

End Sub

Expand Down
17 changes: 11 additions & 6 deletions SireCu/Paneles/Login.vb
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,25 @@ Public Class Login

Private Sub btn_Login_Click(sender As Object, e As EventArgs) Handles btn_Login.Click

'Validaciones
If verificarUsuario(tb_Usuario.Text, tb_Contraseña.Text) Then
Dim samplePrincipal As New Usuario.SampleIPrincipal(Me.tb_Usuario.Text, Me.tb_Contraseña.Text)
Me.tb_Contraseña.Text = ""
If (Not samplePrincipal.Identity.IsAuthenticated) Then
' The user is still not validated.
Principal.ErrorProvider.SetError(tb_Contraseña, "Usuario y/o Contraseña Inválido/s")
Else
' Update the current principal.
My.User.CurrentPrincipal = samplePrincipal

Principal.bttn_Login.Text = "Desloguear"
Principal.stat_Label.Text = "Logueado como: " & tb_Usuario.Text
Principal.userLogueado = tb_Usuario.Text
Principal.stat_Label.Text = "Logueado como: " & My.User.Name
Principal.userLogueado = My.User.Name

ActualizarSaldo()
permisosUsuarios(tb_Usuario.Text)

' Limpiamos todas las pantallas
Principal.SplitContainerPrincipal.Panel2.Controls.Clear()
Principal.AdminPantallas("Home")
Else
Principal.ErrorProvider.SetError(tb_Contraseña, "Usuario y/o Contraseña Inválido/s")
End If

End Sub
Expand Down
8 changes: 7 additions & 1 deletion SireCu/Paneles/VerReporte.vb
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ Public Class VerReporte

End If

Else
Else
MsgBox("No se pudo establecer la conexción con el servidor." & vbCrLf &
"Por favor, intentelo mas tarde.", MsgBoxStyle.Exclamation, "No se estableció conexión")
Exit Sub
Expand Down Expand Up @@ -122,6 +122,12 @@ Public Class VerReporte
End If

End Sub
Private Sub VerReporte_Load(sender As Object, e As EventArgs) Handles Me.Load
Select Case tipoDeUsuario(Principal.userLogueado)
Case "Usuario"
btn_Subir.Enabled = False
End Select
End Sub

#End Region

Expand Down
3 changes: 3 additions & 0 deletions SireCu/Principal.vb
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,9 @@ Public Class Principal
End Sub
Private Sub desloguear()

' Se borra la identidad auntenticada en la aplicación
My.User.CurrentPrincipal = Nothing

' Limpiamos todas las pantallas
SplitContainerPrincipal.Panel2.Controls.Clear()

Expand Down

0 comments on commit 4862533

Please sign in to comment.