Private
Public Access
fix+feat: añadido crear usuario y separado en componentes los modals
This commit is contained in:
1 parent
eff116fab0
commit
62ec25b768
14 files changed
+385
-129
No files matched your search
@@ -0,0 +1,71 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"repuestera_back/config"
|
||||||
|
"repuestera_back/dto"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
func CambiarContraseña(c *gin.Context) {
|
||||||
|
var req dto.CambiarContraseñaRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(req.NewPassword) < 8 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "La nueva contraseña debe tener mas de 8 caracteres"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
authUserID, _ := c.Get("userID")
|
||||||
|
authUserIDUint, _ := authUserID.(uint)
|
||||||
|
|
||||||
|
targetID := authUserIDUint
|
||||||
|
if req.UserID != 0 {
|
||||||
|
targetID = req.UserID
|
||||||
|
}
|
||||||
|
|
||||||
|
esAdmin := utils.UsuarioTienePermiso(c, 3)
|
||||||
|
|
||||||
|
if targetID != authUserIDUint && !esAdmin {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": "No tienes permiso para cambiar la contraseña de otro usuario"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var user models_seguridad.Usuario
|
||||||
|
if err := config.DB.First(&user, targetID).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "usuario no encontrado"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !esAdmin {
|
||||||
|
if req.OldPassword == "" {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Se requiere la contraseña actual"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.OldPassword)); err != nil {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "contraseña actual incorrecta"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al procesar la contraseña"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := config.DB.Model(&user).Update("password", string(hashedPassword)).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al actualizar la contraseña"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "Contraseña actualizada exitosamente"})
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
|
|
||||||
"repuestera_back/config"
|
"repuestera_back/config"
|
||||||
"repuestera_back/dto"
|
"repuestera_back/dto"
|
||||||
|
"repuestera_back/jwtutils"
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -14,8 +15,6 @@ import (
|
|||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
)
|
)
|
||||||
|
|
||||||
var JWTSecret = []byte("supersecretkey123456789")
|
|
||||||
|
|
||||||
func Login(c *gin.Context) {
|
func Login(c *gin.Context) {
|
||||||
var req dto.LoginRequest
|
var req dto.LoginRequest
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
@@ -65,5 +64,5 @@ func generarToken(user models_seguridad.Usuario, duration time.Duration) (string
|
|||||||
}
|
}
|
||||||
|
|
||||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||||
return token.SignedString(JWTSecret)
|
return token.SignedString(jwtutils.JWTSecret)
|
||||||
}
|
}
|
||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
|
|
||||||
"repuestera_back/config"
|
"repuestera_back/config"
|
||||||
"repuestera_back/dto"
|
"repuestera_back/dto"
|
||||||
|
"repuestera_back/jwtutils"
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -31,7 +32,7 @@ func Me(c *gin.Context) {
|
|||||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||||
return nil, jwt.ErrSignatureInvalid
|
return nil, jwt.ErrSignatureInvalid
|
||||||
}
|
}
|
||||||
return JWTSecret, nil
|
return jwtutils.JWTSecret, nil
|
||||||
})
|
})
|
||||||
|
|
||||||
if err != nil || !token.Valid {
|
if err != nil || !token.Valid {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
|
|
||||||
"repuestera_back/config"
|
"repuestera_back/config"
|
||||||
"repuestera_back/dto"
|
"repuestera_back/dto"
|
||||||
|
"repuestera_back/jwtutils"
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -24,7 +25,7 @@ func Refresh(c *gin.Context) {
|
|||||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||||
return nil, jwt.ErrSignatureInvalid
|
return nil, jwt.ErrSignatureInvalid
|
||||||
}
|
}
|
||||||
return JWTSecret, nil
|
return jwtutils.JWTSecret, nil
|
||||||
})
|
})
|
||||||
|
|
||||||
if err != nil || !token.Valid {
|
if err != nil || !token.Valid {
|
||||||
|
|||||||
@@ -33,3 +33,9 @@ type MeResponse struct {
|
|||||||
type RefreshRequest struct {
|
type RefreshRequest struct {
|
||||||
RefreshToken string `json:"refresh_token" binding:"required"`
|
RefreshToken string `json:"refresh_token" binding:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type CambiarContraseñaRequest struct {
|
||||||
|
UserID uint `json:"user_id"`
|
||||||
|
OldPassword string `json:"old_password"`
|
||||||
|
NewPassword string `json:"new_password" binding:"required"`
|
||||||
|
}
|
||||||
@@ -1,17 +1,17 @@
|
|||||||
package jwtutils
|
package jwtutils
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"repuestera_back/controllers/auth"
|
|
||||||
|
|
||||||
"github.com/golang-jwt/jwt/v5"
|
"github.com/golang-jwt/jwt/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var JWTSecret = []byte("supersecretkey123456789")
|
||||||
|
|
||||||
func ValidarJWT(tokenString string) (jwt.MapClaims, error) {
|
func ValidarJWT(tokenString string) (jwt.MapClaims, error) {
|
||||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||||
return nil, jwt.ErrSignatureInvalid
|
return nil, jwt.ErrSignatureInvalid
|
||||||
}
|
}
|
||||||
return auth.JWTSecret, nil
|
return JWTSecret, nil
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package routes
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"repuestera_back/controllers/auth"
|
"repuestera_back/controllers/auth"
|
||||||
|
"repuestera_back/middleware"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
@@ -13,5 +14,6 @@ func AuthRoute(r *gin.Engine) {
|
|||||||
authGroup.POST("/register", auth.Register)
|
authGroup.POST("/register", auth.Register)
|
||||||
authGroup.POST("/refresh", auth.Refresh)
|
authGroup.POST("/refresh", auth.Refresh)
|
||||||
authGroup.GET("/me", auth.Me)
|
authGroup.GET("/me", auth.Me)
|
||||||
|
authGroup.POST("/cambiar-contraseña", middleware.AuthMiddleware(), auth.CambiarContraseña)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -19,9 +19,9 @@ func UserRoute(r *gin.Engine) {
|
|||||||
userGroup.DELETE("/:id", usuarios.EliminarUsuario)
|
userGroup.DELETE("/:id", usuarios.EliminarUsuario)
|
||||||
|
|
||||||
}
|
}
|
||||||
//Esto necesita una validacion de que el usuario que pide realmente sea él
|
userSelfGroup := r.Group("/usuarios")
|
||||||
// userGroup.GET("/:userId/permisos", permission.ObtenerPermisosUsuario)
|
userSelfGroup.Use(middleware.AuthMiddleware())
|
||||||
//
|
{
|
||||||
|
userSelfGroup.POST("/grupos-permisos", permission.ObtenerGruposYPermisosPorEmail)
|
||||||
userGroup.POST("/grupos-permisos", permission.ObtenerGruposYPermisosPorEmail)
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { invalidate } from '$app/navigation';
|
||||||
|
import { API_URL } from '$lib/env';
|
||||||
|
import { getToken } from './token';
|
||||||
|
|
||||||
|
export async function cambiarContraseña(dto: {
|
||||||
|
user_id: number;
|
||||||
|
old_password: string;
|
||||||
|
new_password: string;
|
||||||
|
}) {
|
||||||
|
if (
|
||||||
|
!dto.old_password ||
|
||||||
|
!dto.new_password ||
|
||||||
|
dto.old_password.length < 8 ||
|
||||||
|
dto.new_password.length < 8
|
||||||
|
)
|
||||||
|
return 'Las contraseñas no alcanzan el minimo de 8 caracteres';
|
||||||
|
try {
|
||||||
|
const req = await fetch(`${API_URL}/auth/cambiar-contraseña`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Authorization: `Bearer ${getToken()}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify(dto)
|
||||||
|
});
|
||||||
|
|
||||||
|
let data = await req.json();
|
||||||
|
if (!req.ok) {
|
||||||
|
return data.error || 'Error';
|
||||||
|
}
|
||||||
|
invalidate('usuarios:load');
|
||||||
|
return 'Ok';
|
||||||
|
} catch {
|
||||||
|
return 'No se pudo conectar con el servidor';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,23 +1,21 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import Header from '$lib/components/Header.svelte';
|
import Header from '$lib/components/Header.svelte';
|
||||||
import { actualizarUsuario } from '$lib/hooks/actualizarUsuario.js';
|
|
||||||
import { crearUsuario } from '$lib/hooks/crearUsuario.js';
|
|
||||||
import { eliminarUsuario } from '$lib/hooks/eliminarUsuario.js';
|
|
||||||
import {
|
import {
|
||||||
Button,
|
Button,
|
||||||
Modal,
|
Modal,
|
||||||
PasswordInput,
|
|
||||||
Table,
|
Table,
|
||||||
TableBody,
|
TableBody,
|
||||||
TableCell,
|
TableCell,
|
||||||
TableContainer,
|
TableContainer,
|
||||||
TableHead,
|
TableHead,
|
||||||
TableHeader,
|
TableHeader,
|
||||||
TableRow,
|
TableRow
|
||||||
TextInput
|
|
||||||
} from 'carbon-components-svelte';
|
} from 'carbon-components-svelte';
|
||||||
import { Add, Pen, TrashCan } from 'carbon-icons-svelte';
|
import { Add, Keychain, Pen, TrashCan } from 'carbon-icons-svelte';
|
||||||
import { Keychain } from 'carbon-icons-svelte';
|
import CambiarContraseñaForm from './CambiarContraseñaForm.svelte';
|
||||||
|
import CrearUsuarioForm from './CrearUsuarioForm.svelte';
|
||||||
|
import EditarUsuarioForm from './EditarUsuarioForm.svelte';
|
||||||
|
import EliminarUsuarioForm from './EliminarUsuarioForm.svelte';
|
||||||
|
|
||||||
let { data } = $props();
|
let { data } = $props();
|
||||||
|
|
||||||
@@ -25,12 +23,11 @@
|
|||||||
let showEditarModal = $state(false);
|
let showEditarModal = $state(false);
|
||||||
let showEliminarModal = $state(false);
|
let showEliminarModal = $state(false);
|
||||||
let showCambiarContraseñaModal = $state(false);
|
let showCambiarContraseñaModal = $state(false);
|
||||||
let showError: string | Promise<string> = $state('');
|
let showError = $state('');
|
||||||
|
|
||||||
let usuarioCrear = $state({ name: '', email: '', password: '' });
|
let usuarioModificar = $state({ id: 0, name: '', email: '' });
|
||||||
let usuarioModificar = $state({ name: '', email: '' });
|
|
||||||
let usuarioEliminar = $state({ id: 0 });
|
let usuarioEliminar = $state({ id: 0 });
|
||||||
let usuarioCambiarContraseña = $state();
|
let usuarioCambiarContraseña = $state({ id: 0 });
|
||||||
|
|
||||||
function cerrarModal() {
|
function cerrarModal() {
|
||||||
showCrearModal = false;
|
showCrearModal = false;
|
||||||
@@ -38,9 +35,9 @@
|
|||||||
showEliminarModal = false;
|
showEliminarModal = false;
|
||||||
showCambiarContraseñaModal = false;
|
showCambiarContraseñaModal = false;
|
||||||
|
|
||||||
usuarioModificar = undefined;
|
usuarioModificar = { id: 0, name: '', email: '' };
|
||||||
usuarioEliminar = undefined;
|
usuarioEliminar = { id: 0 };
|
||||||
usuarioCambiarContraseña = undefined;
|
usuarioCambiarContraseña = { id: 0 };
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -78,9 +75,9 @@
|
|||||||
<TableCell>{u.id}</TableCell>
|
<TableCell>{u.id}</TableCell>
|
||||||
<TableCell>{u.email}</TableCell>
|
<TableCell>{u.email}</TableCell>
|
||||||
<TableCell>{u.name}</TableCell>
|
<TableCell>{u.name}</TableCell>
|
||||||
<TableCell>{u.deleted_at ? 'no' : 'si'}</TableCell>
|
<TableCell>{(u as any).deleted_at ? 'no' : 'si'}</TableCell>
|
||||||
<TableCell>{new Date(u.created_at).toLocaleString()}</TableCell>
|
<TableCell>{new Date((u as any).created_at).toLocaleString()}</TableCell>
|
||||||
<TableCell>{new Date(u.updated_at).toLocaleString()}</TableCell>
|
<TableCell>{new Date((u as any).updated_at).toLocaleString()}</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<Button
|
<Button
|
||||||
onclick={() => {
|
onclick={() => {
|
||||||
@@ -118,104 +115,22 @@
|
|||||||
</TableContainer>
|
</TableContainer>
|
||||||
{/await}
|
{/await}
|
||||||
</div>
|
</div>
|
||||||
{#await showError then msgerr}
|
|
||||||
<Modal
|
<CrearUsuarioForm bind:show={showCrearModal} onclose={cerrarModal} />
|
||||||
open={!!showError && msgerr != 'Ok'}
|
<EditarUsuarioForm bind:show={showEditarModal} usuario={usuarioModificar} onclose={cerrarModal} />
|
||||||
primaryButtonText="Cerrar"
|
<EliminarUsuarioForm
|
||||||
on:click:button--primary={() => (showError = '')}
|
bind:show={showEliminarModal}
|
||||||
>
|
usuario={usuarioEliminar}
|
||||||
{msgerr}
|
onclose={cerrarModal}
|
||||||
</Modal>
|
|
||||||
{/await}
|
|
||||||
<form
|
|
||||||
id="crearForm"
|
|
||||||
onsubmit={(e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
showError = crearUsuario(usuarioCrear);
|
|
||||||
showCrearModal = false;
|
|
||||||
usuarioCrear = { name: '', email: '', password: '' };
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Modal
|
|
||||||
formId="crearForm"
|
|
||||||
bind:open={showCrearModal}
|
|
||||||
modalHeading="Registrar Nuevo Usuario"
|
|
||||||
primaryButtonText="Crear"
|
|
||||||
secondaryButtonText="Cerrar"
|
|
||||||
on:click:button--secondary={cerrarModal}
|
|
||||||
>
|
|
||||||
<TextInput bind:value={usuarioCrear.name} labelText="Nombre" placeholder="Tu nombre" />
|
|
||||||
<TextInput
|
|
||||||
bind:value={usuarioCrear.email}
|
|
||||||
labelText="Email"
|
|
||||||
placeholder="tu@email.com"
|
|
||||||
type="email"
|
|
||||||
/>
|
/>
|
||||||
<PasswordInput
|
<CambiarContraseñaForm
|
||||||
bind:value={usuarioCrear.password}
|
bind:show={showCambiarContraseñaModal}
|
||||||
labelText="Contraseña"
|
usuario={usuarioCambiarContraseña}
|
||||||
placeholder="••••••••"
|
onclose={cerrarModal}
|
||||||
minlength={8}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{#if showError}
|
||||||
|
<Modal open primaryButtonText="Cerrar" on:click:button--primary={() => (showError = '')}>
|
||||||
|
{showError}
|
||||||
</Modal>
|
</Modal>
|
||||||
</form>
|
{/if}
|
||||||
<form
|
|
||||||
id="editarForm"
|
|
||||||
onsubmit={(e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
showError = actualizarUsuario(usuarioModificar);
|
|
||||||
showEditarModal = false;
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Modal
|
|
||||||
formId="editarForm"
|
|
||||||
bind:open={showEditarModal}
|
|
||||||
modalHeading="Editar Usuario"
|
|
||||||
primaryButtonText="Editar"
|
|
||||||
secondaryButtonText="Cerrar"
|
|
||||||
on:click:button--secondary={cerrarModal}
|
|
||||||
>
|
|
||||||
<TextInput name="nombre" type="text" labelText="Nombre: " bind:value={usuarioModificar.name} />
|
|
||||||
<TextInput name="email" type="text" labelText="Email" bind:value={usuarioModificar.email} />
|
|
||||||
</Modal>
|
|
||||||
</form>
|
|
||||||
<form
|
|
||||||
id="eliminarForm"
|
|
||||||
onsubmit={(e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
if (!usuarioEliminar && !usuarioEliminar.id) {
|
|
||||||
showError = 'No se pudo obtener la id del usuario? recarga la pagina.';
|
|
||||||
} else {
|
|
||||||
showError = eliminarUsuario(usuarioEliminar.id);
|
|
||||||
}
|
|
||||||
showEliminarModal = false;
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Modal
|
|
||||||
formId="eliminarForm"
|
|
||||||
bind:open={showEliminarModal}
|
|
||||||
modalHeading="Eliminar Usuario"
|
|
||||||
primaryButtonText="Eliminar"
|
|
||||||
secondaryButtonText="Cerrar"
|
|
||||||
on:click:button--secondary={cerrarModal}
|
|
||||||
>
|
|
||||||
Esta seguro que quiere borrar este usuario?
|
|
||||||
</Modal>
|
|
||||||
</form>
|
|
||||||
<form
|
|
||||||
id="cambiarForm"
|
|
||||||
onsubmit={(e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Modal
|
|
||||||
formId="cambiarForm"
|
|
||||||
bind:open={showCambiarContraseñaModal}
|
|
||||||
modalHeading="Cambiar Contraseña"
|
|
||||||
primaryButtonText="Aceptar"
|
|
||||||
secondaryButtonText="Cerrar"
|
|
||||||
on:click:button--secondary={cerrarModal}
|
|
||||||
>
|
|
||||||
<PasswordInput labelText="Nueva Contraseña: " />
|
|
||||||
</Modal>
|
|
||||||
</form>
|
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { Button, Modal, PasswordInput } from 'carbon-components-svelte';
|
||||||
|
import { cambiarContraseña } from '$lib/hooks/cambiarContraseña.js';
|
||||||
|
|
||||||
|
let {
|
||||||
|
show = $bindable(),
|
||||||
|
onclose,
|
||||||
|
usuario
|
||||||
|
}: { show?: boolean; onclose: () => void; usuario: { id: number } } = $props();
|
||||||
|
|
||||||
|
let password = $state('');
|
||||||
|
let error = $state('');
|
||||||
|
|
||||||
|
async function handleSubmit(e: Event) {
|
||||||
|
e.preventDefault();
|
||||||
|
error = '';
|
||||||
|
const result = await cambiarContraseña({
|
||||||
|
old_password: 'adminoverride',
|
||||||
|
new_password: password,
|
||||||
|
user_id: usuario.id
|
||||||
|
});
|
||||||
|
if (result !== 'Ok') {
|
||||||
|
error = result;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
password = '';
|
||||||
|
onclose();
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleClose() {
|
||||||
|
password = '';
|
||||||
|
error = '';
|
||||||
|
onclose();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<form id="cambiarForm" onsubmit={handleSubmit}>
|
||||||
|
<Modal
|
||||||
|
formId="cambiarForm"
|
||||||
|
bind:open={show}
|
||||||
|
modalHeading="Cambiar Contraseña"
|
||||||
|
primaryButtonText="Aceptar"
|
||||||
|
secondaryButtonText="Cerrar"
|
||||||
|
on:click:button--secondary={handleClose}
|
||||||
|
>
|
||||||
|
{#if error}
|
||||||
|
<div class="text-red-500">{error}</div>
|
||||||
|
{/if}
|
||||||
|
<PasswordInput labelText="Nueva Contraseña: " minlength={8} bind:value={password} />
|
||||||
|
</Modal>
|
||||||
|
</form>
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { crearUsuario } from '$lib/hooks/crearUsuario.js';
|
||||||
|
import { Button, Modal, PasswordInput, TextInput } from 'carbon-components-svelte';
|
||||||
|
|
||||||
|
let { show = $bindable(), onclose }: { show?: boolean; onclose: () => void } = $props();
|
||||||
|
|
||||||
|
let name = $state('');
|
||||||
|
let email = $state('');
|
||||||
|
let password = $state('');
|
||||||
|
let error = $state('');
|
||||||
|
|
||||||
|
async function handleSubmit(e: Event) {
|
||||||
|
e.preventDefault();
|
||||||
|
error = '';
|
||||||
|
const result = await crearUsuario({ name, email, password });
|
||||||
|
if (result !== 'Ok') {
|
||||||
|
error = result;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
reset();
|
||||||
|
onclose();
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleClose() {
|
||||||
|
reset();
|
||||||
|
onclose();
|
||||||
|
}
|
||||||
|
|
||||||
|
function reset() {
|
||||||
|
name = '';
|
||||||
|
email = '';
|
||||||
|
password = '';
|
||||||
|
error = '';
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<form id="crearForm" onsubmit={handleSubmit}>
|
||||||
|
<Modal
|
||||||
|
formId="crearForm"
|
||||||
|
bind:open={show}
|
||||||
|
modalHeading="Registrar Nuevo Usuario"
|
||||||
|
primaryButtonText="Crear"
|
||||||
|
secondaryButtonText="Cerrar"
|
||||||
|
on:click:button--secondary={handleClose}
|
||||||
|
>
|
||||||
|
{#if error}
|
||||||
|
<div class="error-msg">{error}</div>
|
||||||
|
{/if}
|
||||||
|
<TextInput bind:value={name} labelText="Nombre" placeholder="Tu nombre" />
|
||||||
|
<TextInput bind:value={email} labelText="Email" placeholder="tu@email.com" type="email" />
|
||||||
|
<PasswordInput bind:value={password} labelText="Contraseña" placeholder="••••••••" minlength={8} />
|
||||||
|
</Modal>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.error-msg {
|
||||||
|
color: #da1e28;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { actualizarUsuario } from '$lib/hooks/actualizarUsuario.js';
|
||||||
|
import { Button, Modal, TextInput } from 'carbon-components-svelte';
|
||||||
|
|
||||||
|
let {
|
||||||
|
show = $bindable(),
|
||||||
|
onclose,
|
||||||
|
usuario
|
||||||
|
}: {
|
||||||
|
show?: boolean;
|
||||||
|
onclose: () => void;
|
||||||
|
usuario: { id: number; name: string; email: string };
|
||||||
|
} = $props();
|
||||||
|
|
||||||
|
let error = $state('');
|
||||||
|
|
||||||
|
async function handleSubmit(e: Event) {
|
||||||
|
e.preventDefault();
|
||||||
|
error = '';
|
||||||
|
const result = await actualizarUsuario(usuario);
|
||||||
|
if (result !== 'Ok') {
|
||||||
|
error = result;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onclose();
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleClose() {
|
||||||
|
error = '';
|
||||||
|
onclose();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<form id="editarForm" onsubmit={handleSubmit}>
|
||||||
|
<Modal
|
||||||
|
formId="editarForm"
|
||||||
|
bind:open={show}
|
||||||
|
modalHeading="Editar Usuario"
|
||||||
|
primaryButtonText="Editar"
|
||||||
|
secondaryButtonText="Cerrar"
|
||||||
|
on:click:button--secondary={handleClose}
|
||||||
|
>
|
||||||
|
{#if error}
|
||||||
|
<div class="error-msg">{error}</div>
|
||||||
|
{/if}
|
||||||
|
<TextInput name="nombre" type="text" labelText="Nombre: " bind:value={usuario.name} />
|
||||||
|
<TextInput name="email" type="text" labelText="Email" bind:value={usuario.email} />
|
||||||
|
</Modal>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.error-msg {
|
||||||
|
color: #da1e28;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { eliminarUsuario } from '$lib/hooks/eliminarUsuario.js';
|
||||||
|
import { Button, Modal } from 'carbon-components-svelte';
|
||||||
|
|
||||||
|
let {
|
||||||
|
show = $bindable(),
|
||||||
|
onclose,
|
||||||
|
usuario
|
||||||
|
}: { show?: boolean; onclose: () => void; usuario: { id: number } } = $props();
|
||||||
|
|
||||||
|
let error = $state('');
|
||||||
|
|
||||||
|
async function handleSubmit(e: Event) {
|
||||||
|
e.preventDefault();
|
||||||
|
error = '';
|
||||||
|
if (!usuario.id) {
|
||||||
|
error = 'No se pudo obtener la id del usuario? recarga la pagina.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const result = await eliminarUsuario(usuario.id);
|
||||||
|
if (result !== 'Ok') {
|
||||||
|
error = result;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onclose();
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleClose() {
|
||||||
|
error = '';
|
||||||
|
onclose();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<form id="eliminarForm" onsubmit={handleSubmit}>
|
||||||
|
<Modal
|
||||||
|
formId="eliminarForm"
|
||||||
|
bind:open={show}
|
||||||
|
modalHeading="Eliminar Usuario"
|
||||||
|
primaryButtonText="Eliminar"
|
||||||
|
secondaryButtonText="Cerrar"
|
||||||
|
on:click:button--secondary={handleClose}
|
||||||
|
>
|
||||||
|
{#if error}
|
||||||
|
<div class="error-msg">{error}</div>
|
||||||
|
{/if}
|
||||||
|
Esta seguro que quiere borrar este usuario?
|
||||||
|
</Modal>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.error-msg {
|
||||||
|
color: #da1e28;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
Reference in new issue
Block a user