diff --git a/SireCu/Clases/Usuario.vb b/SireCu/Clases/Usuario.vb index 7c60d07..6fc1cd2 100644 --- a/SireCu/Clases/Usuario.vb +++ b/SireCu/Clases/Usuario.vb @@ -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) diff --git a/SireCu/DBSireCu.sdf b/SireCu/DBSireCu.sdf index 3eddd89..ac60451 100644 Binary files a/SireCu/DBSireCu.sdf and b/SireCu/DBSireCu.sdf differ diff --git a/SireCu/My Project/Application.Designer.vb b/SireCu/My Project/Application.Designer.vb index 51b924b..004906c 100644 --- a/SireCu/My Project/Application.Designer.vb +++ b/SireCu/My Project/Application.Designer.vb @@ -1,10 +1,10 @@ '------------------------------------------------------------------------------ ' -' This code was generated by a tool. -' Runtime Version:4.0.30319.42000 +' Este código fue generado por una herramienta. +' Versión de runtime:4.0.30319.42000 ' -' Changes to this file may cause incorrect behavior and will be lost if -' the code is regenerated. +' Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si +' se vuelve a generar el código. ' '------------------------------------------------------------------------------ @@ -14,16 +14,16 @@ Option Explicit On Namespace My - 'NOTE: This file is auto-generated; do not modify it directly. To make changes, - ' or if you encounter build errors in this file, go to the Project Designer - ' (go to Project Properties or double-click the My Project node in - ' Solution Explorer), and make changes on the Application tab. + 'NOTA: este archivo se genera de forma automática; no lo modifique directamente. Para realizar cambios, + ' o si detecta errores de compilación en este archivo, vaya al Diseñador de proyectos + ' (vaya a Propiedades del proyecto o haga doble clic en el nodo My Project en el + ' Explorador de soluciones) y realice cambios en la pestaña Aplicación. ' Partial Friend Class MyApplication _ Public Sub New() - MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows) + MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.ApplicationDefined) Me.IsSingleInstance = false Me.EnableVisualStyles = true Me.SaveMySettingsOnExit = true diff --git a/SireCu/My Project/Application.myapp b/SireCu/My Project/Application.myapp index 1572e1e..7fecdff 100644 --- a/SireCu/My Project/Application.myapp +++ b/SireCu/My Project/Application.myapp @@ -1,10 +1,10 @@ - + true Principal false 0 true - 0 + 1 true \ No newline at end of file diff --git a/SireCu/Paneles/ABMEgresos.vb b/SireCu/Paneles/ABMEgresos.vb index 96ef2d4..ef79fef 100644 --- a/SireCu/Paneles/ABMEgresos.vb +++ b/SireCu/Paneles/ABMEgresos.vb @@ -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 @@ -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 diff --git a/SireCu/Paneles/ABMUsuarios.vb b/SireCu/Paneles/ABMUsuarios.vb index 25de988..d1e5d84 100644 --- a/SireCu/Paneles/ABMUsuarios.vb +++ b/SireCu/Paneles/ABMUsuarios.vb @@ -63,7 +63,9 @@ 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 @@ -71,20 +73,30 @@ Public Class ABMUsuarios 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) @@ -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") @@ -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 diff --git a/SireCu/Paneles/Login.vb b/SireCu/Paneles/Login.vb index d738df9..c0ef5fa 100644 --- a/SireCu/Paneles/Login.vb +++ b/SireCu/Paneles/Login.vb @@ -8,11 +8,18 @@ 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) @@ -20,8 +27,6 @@ Public Class Login ' 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 diff --git a/SireCu/Paneles/VerReporte.vb b/SireCu/Paneles/VerReporte.vb index b899172..fdc9160 100644 --- a/SireCu/Paneles/VerReporte.vb +++ b/SireCu/Paneles/VerReporte.vb @@ -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 @@ -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 diff --git a/SireCu/Principal.vb b/SireCu/Principal.vb index 1ddb261..e77f6a0 100644 --- a/SireCu/Principal.vb +++ b/SireCu/Principal.vb @@ -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()