From d65e28c0d785e79eaa7fae875952c24fc1b12b95 Mon Sep 17 00:00:00 2001 From: Mark Albrand Date: Thu, 16 Nov 2023 23:17:29 -0600 Subject: [PATCH 1/8] =?UTF-8?q?Documentaci=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/middlewares/middlewares.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/backend/middlewares/middlewares.go b/backend/middlewares/middlewares.go index 810a1222..29857f6f 100644 --- a/backend/middlewares/middlewares.go +++ b/backend/middlewares/middlewares.go @@ -7,12 +7,13 @@ import ( "net/http" ) +// JwtAuthentication Middleware usado para verificar si el token es válido func JwtAuthentication() gin.HandlerFunc { return func(c *gin.Context) { err := utils.TokenValid(c) if err != nil { c.JSON(http.StatusUnauthorized, responses.StandardResponse{ - Status: 401, + Status: http.StatusUnauthorized, Message: "Unauthorized, token is invalid: " + err.Error(), Data: nil, }) From 2a65e4b3fd4d78bebf524aa518be9918fb7d26af Mon Sep 17 00:00:00 2001 From: Mark Albrand Date: Thu, 16 Nov 2023 23:19:12 -0600 Subject: [PATCH 2/8] Modelos --- backend/models/carrera.go | 1 + backend/models/estudiante.go | 2 -- backend/models/message.go | 2 +- backend/models/user.go | 3 +++ 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/backend/models/carrera.go b/backend/models/carrera.go index dd6d3cd8..2f2a4417 100644 --- a/backend/models/carrera.go +++ b/backend/models/carrera.go @@ -10,6 +10,7 @@ func (Carrera) TableName() string { return "carrera" } +// CarreraGet es la estructura de la tabla carrera en la base de datos type CarreraGet struct { Id_Carrera int `json:"id_carrera"` Nombre string `json:"nombre"` diff --git a/backend/models/estudiante.go b/backend/models/estudiante.go index 6797fe23..c4eed8d6 100644 --- a/backend/models/estudiante.go +++ b/backend/models/estudiante.go @@ -4,8 +4,6 @@ import ( "time" ) -// Mensaje es la estructura de la tabla estudiante en la base de datos - type Estudiante struct { IdEstudiante string `json:"id_estudiante"` Dpi string `json:"dpi"` diff --git a/backend/models/message.go b/backend/models/message.go index 805f1fe0..4baeb416 100644 --- a/backend/models/message.go +++ b/backend/models/message.go @@ -14,7 +14,7 @@ type Mensaje struct { Tiempo time.Time `json:"tiempo"` } -// mensajeGet es la estructura de la tabla mensaje en la base de datos +// MensajeGet es la estructura de la tabla mensaje en la base de datos type MensajeGet struct { ID_mensaje int `json:"id_mensaje"` IdEmisor string `json:"id_emisor"` diff --git a/backend/models/user.go b/backend/models/user.go index 9ace2092..9213da17 100644 --- a/backend/models/user.go +++ b/backend/models/user.go @@ -20,6 +20,7 @@ func (Usuario) TableName() string { return "usuario" } +// SaveUser guarda un usuario en la base de datos func (u *Usuario) SaveUser() (*Usuario, error) { err := configs.DB.Create(&u).Error @@ -30,6 +31,7 @@ func (u *Usuario) SaveUser() (*Usuario, error) { return u, nil } +// BeforeSave se llama antes de guardar un usuario en la base de datos, se encripta la contraseña func (u *Usuario) BeforeSave() error { hashedPassword, err := bcrypt.GenerateFromPassword([]byte(u.Contra), bcrypt.DefaultCost) @@ -43,6 +45,7 @@ func (u *Usuario) BeforeSave() error { return nil } +// GetUserByUsername busca un usuario por su nombre de usuario func GetUserByUsername(username string) (Usuario, error) { var user Usuario From 84403df0133219bbfb04d5c27487b6372817783e Mon Sep 17 00:00:00 2001 From: Mark Albrand Date: Thu, 16 Nov 2023 23:21:01 -0600 Subject: [PATCH 3/8] Respuestas --- backend/responses/responses.go | 1 + 1 file changed, 1 insertion(+) diff --git a/backend/responses/responses.go b/backend/responses/responses.go index 36876e7d..faf4c7d3 100644 --- a/backend/responses/responses.go +++ b/backend/responses/responses.go @@ -1,5 +1,6 @@ package responses +// StandardResponse es la estructura de una respuesta estándar type StandardResponse struct { Status int `json:"status"` Message string `json:"message"` From a0f4f599971ede68e4ebc855b6888b56c0fe72c7 Mon Sep 17 00:00:00 2001 From: Mark Albrand Date: Thu, 16 Nov 2023 23:22:41 -0600 Subject: [PATCH 4/8] Utils --- backend/utils/file.go | 2 ++ backend/utils/token.go | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/backend/utils/file.go b/backend/utils/file.go index 45a89759..3f755dd2 100644 --- a/backend/utils/file.go +++ b/backend/utils/file.go @@ -9,6 +9,7 @@ import ( "path/filepath" ) +// Contains verifica si un string está en un slice de strings func Contains(slice []string, item string) bool { for _, s := range slice { if s == item { @@ -19,6 +20,7 @@ func Contains(slice []string, item string) bool { return false } +// UploadFileToServer sube un archivo al File Server func UploadFileToServer(url string, bearer string, fileHeader *multipart.FileHeader, dst string) error { // Abrir el archivo f, err := fileHeader.Open() diff --git a/backend/utils/token.go b/backend/utils/token.go index 3351f7a1..86991490 100644 --- a/backend/utils/token.go +++ b/backend/utils/token.go @@ -10,6 +10,7 @@ import ( "time" ) +// GenerateToken genera un token JWT func GenerateToken(username string, userType string) (string, error) { tokenLifespan, err := strconv.Atoi(os.Getenv("TOKEN_HOUR_LIFESPAN")) @@ -27,6 +28,7 @@ func GenerateToken(username string, userType string) (string, error) { return token.SignedString([]byte(os.Getenv("API_SECRET"))) } +// TokenValid verifica si un token es válido func TokenValid(c *gin.Context) error { tokenString := ExtractTokenFromRequest(c) _, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { @@ -41,6 +43,7 @@ func TokenValid(c *gin.Context) error { return nil } +// ExtractTokenFromRequest extrae el token de una request func ExtractTokenFromRequest(c *gin.Context) string { token := c.Query("token") if token != "" { @@ -53,6 +56,7 @@ func ExtractTokenFromRequest(c *gin.Context) string { return "" } +// TokenExtractUsername extrae el username de un token func TokenExtractUsername(c *gin.Context) (string, error) { tokenString := ExtractTokenFromRequest(c) @@ -74,6 +78,7 @@ func TokenExtractUsername(c *gin.Context) (string, error) { return "", nil } +// TokenExtractRole extrae el rol de un token func TokenExtractRole(c *gin.Context) (string, error) { tokenString := ExtractTokenFromRequest(c) From e65de14d26bc6611521018f2910598c11ee981b9 Mon Sep 17 00:00:00 2001 From: Mark Albrand Date: Thu, 16 Nov 2023 23:23:24 -0600 Subject: [PATCH 5/8] =?UTF-8?q?Correcci=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/utils/token.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/utils/token.go b/backend/utils/token.go index 86991490..d7000832 100644 --- a/backend/utils/token.go +++ b/backend/utils/token.go @@ -62,7 +62,7 @@ func TokenExtractUsername(c *gin.Context) (string, error) { tokenString := ExtractTokenFromRequest(c) token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { - return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } return []byte(os.Getenv("API_SECRET")), nil }) @@ -84,7 +84,7 @@ func TokenExtractRole(c *gin.Context) (string, error) { tokenString := ExtractTokenFromRequest(c) token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { - return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } return []byte(os.Getenv("API_SECRET")), nil }) From c731d5d9d80bc6e279b471ff7e41987ad388a202 Mon Sep 17 00:00:00 2001 From: Mark Albrand Date: Thu, 16 Nov 2023 23:25:18 -0600 Subject: [PATCH 6/8] Enviroment --- backend/configs/envs.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/backend/configs/envs.go b/backend/configs/envs.go index 440a8704..ff1ebc29 100644 --- a/backend/configs/envs.go +++ b/backend/configs/envs.go @@ -8,6 +8,7 @@ import ( "os" ) +// EnvPG carga las variables de entorno, primero desde el sistema operativo, y si no están, desde un archivo .env func EnvPG() map[string]string { envs := make(map[string]string) @@ -32,6 +33,7 @@ func EnvPG() map[string]string { return envs } +// loadSystemEnv carga las variables de entorno desde el sistema operativo, en vez de un archivo .env func loadSystemEnv() (map[string]string, error) { envs := make(map[string]string) From 2f67f20947f3e82ca5e1a57b31771cc384b5ed55 Mon Sep 17 00:00:00 2001 From: Mark Albrand Date: Thu, 16 Nov 2023 23:25:59 -0600 Subject: [PATCH 7/8] Configuraciones --- backend/configs/setup.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/backend/configs/setup.go b/backend/configs/setup.go index 175ed767..0f5826e9 100644 --- a/backend/configs/setup.go +++ b/backend/configs/setup.go @@ -16,6 +16,7 @@ const ( Admin = "admin" ) +// SetupDB configura la conexión a la base de datos func SetupDB() { envs := EnvPG() @@ -28,6 +29,7 @@ func SetupDB() { DB = db } +// CreateDirIfNotExist crea un directorio si no existe func CreateDirIfNotExist(path string) (bool, error) { if _, err := os.Stat(path); os.IsNotExist(err) { fmt.Println("Directory " + path + " does not exist. Creating...") From e66cdfe36ff71bc23be8e9316920383cc8fdaa46 Mon Sep 17 00:00:00 2001 From: Mark Albrand Date: Thu, 16 Nov 2023 23:27:11 -0600 Subject: [PATCH 8/8] =?UTF-8?q?Documentaci=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/main.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/backend/main.go b/backend/main.go index 85822975..70d4c03e 100644 --- a/backend/main.go +++ b/backend/main.go @@ -7,11 +7,12 @@ import ( ) func main() { - // create directory for uploads + // create directory for profile pictures if _, err := configs.CreateDirIfNotExist("./uploads"); err != nil { panic(err) } + // create directory for pdf files if _, err := configs.CreateDirIfNotExist("./uploads/pdf"); err != nil { panic(err) } @@ -23,9 +24,13 @@ func main() { routes.Routes(router) configs.SetupDB() - router.Run(":8080") + err := router.Run(":8080") + if err != nil { + return + } } +// CORS permite el acceso a la API desde cualquier origen func CORS() gin.HandlerFunc { // Reference: https://github.com/gin-contrib/cors/issues/29 return func(c *gin.Context) {