Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mark #255

Merged
merged 8 commits into from
Nov 17, 2023
Merged

Mark #255

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions backend/configs/envs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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)

Expand Down
2 changes: 2 additions & 0 deletions backend/configs/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const (
Admin = "admin"
)

// SetupDB configura la conexión a la base de datos
func SetupDB() {
envs := EnvPG()

Expand All @@ -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...")
Expand Down
9 changes: 7 additions & 2 deletions backend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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) {
Expand Down
3 changes: 2 additions & 1 deletion backend/middlewares/middlewares.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
})
Expand Down
1 change: 1 addition & 0 deletions backend/models/carrera.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down
2 changes: 0 additions & 2 deletions backend/models/estudiante.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down
2 changes: 1 addition & 1 deletion backend/models/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down
3 changes: 3 additions & 0 deletions backend/models/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)

Expand All @@ -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

Expand Down
1 change: 1 addition & 0 deletions backend/responses/responses.go
Original file line number Diff line number Diff line change
@@ -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"`
Expand Down
2 changes: 2 additions & 0 deletions backend/utils/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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()
Expand Down
9 changes: 7 additions & 2 deletions backend/utils/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"))

Expand All @@ -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) {
Expand All @@ -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 != "" {
Expand All @@ -53,12 +56,13 @@ func ExtractTokenFromRequest(c *gin.Context) string {
return ""
}

// TokenExtractUsername extrae el username de un token
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
})
Expand All @@ -74,12 +78,13 @@ 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)
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
})
Expand Down
Loading