diff --git a/source/controllers/auth.go b/source/controllers/auth.go index a72531d..83fe074 100644 --- a/source/controllers/auth.go +++ b/source/controllers/auth.go @@ -1,65 +1,68 @@ /** * Created by fbonhomm * Email: flo-github@outlook.fr - * Licence: MIT + * License: MIT */ package controllers import ( - "net/http" + "net/http" - "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin" - "github.com/fbonhomm/api-go/source/libs" - "github.com/fbonhomm/api-go/source/models" - "github.com/fbonhomm/api-go/source/services" + "github.com/fbonhomm/api-go/source/libs" + "github.com/fbonhomm/api-go/source/models" + "github.com/fbonhomm/api-go/source/services" ) // AuthLogin func AuthLogin(c *gin.Context) { - var accessToken string - var refreshToken string - var err error - var user = models.User{ - Email: c.PostForm("email"), - } + var accessToken string + var refreshToken string + var err error + var user = models.User{ + Email: c.PostForm("email"), + } - if err = services.Db.First(&user).Error; err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - } else if err = user.Compare(c.PostForm("password")); err != nil { - c.JSON(http.StatusInternalServerError, gin.H{ "error": err.Error() }) - } else if accessToken, err = libs.GenerateAccessToken(user); err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - } else if refreshToken, err = libs.GenerateRefreshToken(user); err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - } else { - c.JSON(http.StatusOK, gin.H{ - "access_token": accessToken, - "refresh_token": refreshToken, - }) - } + if err = services.Db.First(&user).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } else if err = user.Compare(c.PostForm("password")); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } else if accessToken, err = libs.GenerateAccessToken(&user); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } else if refreshToken, err = libs.GenerateRefreshToken(&user); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } else { + c.JSON(http.StatusOK, gin.H{ + "access_token": accessToken, + "refresh_token": refreshToken, + }) + } } // AuthRefresh func AuthRefresh(c *gin.Context) { - var accessToken string - var refreshToken string - var err error - var user = models.User{} + var accessToken string + var refreshToken string + var token map[string]string + var err error + var user = models.User{} - token, _ := GetToken(c) + if token, err = GetToken(c); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } - if err = services.Db.First(&user, token["id"]).Error; err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - } else if accessToken, err = libs.GenerateAccessToken(user); err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - } else if refreshToken, err = libs.GenerateRefreshToken(user); err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - } else { - c.JSON(http.StatusOK, gin.H{ - "access_token": accessToken, - "refresh_token": refreshToken, - }) - } + if err = services.Db.First(&user, token["id"]).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } else if accessToken, err = libs.GenerateAccessToken(&user); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } else if refreshToken, err = libs.GenerateRefreshToken(&user); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } else { + c.JSON(http.StatusOK, gin.H{ + "access_token": accessToken, + "refresh_token": refreshToken, + }) + } } diff --git a/source/controllers/user.go b/source/controllers/user.go index 4a5c66d..f823378 100644 --- a/source/controllers/user.go +++ b/source/controllers/user.go @@ -1,52 +1,53 @@ /** * Created by fbonhomm * Email: flo-github@outlook.fr - * Licence: MIT + * License: MIT */ package controllers import ( - "github.com/gin-gonic/gin" - "net/http" + "net/http" - "github.com/fbonhomm/api-go/source/models" - "github.com/fbonhomm/api-go/source/services" + "github.com/gin-gonic/gin" + + "github.com/fbonhomm/api-go/source/models" + "github.com/fbonhomm/api-go/source/services" ) // UserCreate func UserCreate(c *gin.Context) { - user := models.User{ - Name: c.PostForm("name"), - Email: c.PostForm("email"), - Password: c.PostForm("password"), - } + user := models.User{ + Name: c.PostForm("name"), + Email: c.PostForm("email"), + Password: c.PostForm("password"), + } - if err := services.Db.Create(&user).Error; err != nil { - c.JSON(http.StatusConflict, gin.H{ "error": err.Error() }) - } else { - c.JSON(http.StatusCreated, gin.H{ "item": user }) - } + if err := services.Db.Create(&user).Error; err != nil { + c.JSON(http.StatusConflict, gin.H{"error": err.Error()}) + } else { + c.JSON(http.StatusCreated, gin.H{"item": user}) + } } -// UserGetId -func UserGetId(c *gin.Context) { - user := models.User{} +// UserGetID +func UserGetID(c *gin.Context) { + user := models.User{} - if err := services.Db.First(&user, c.Param("id")).Error; err != nil { - c.JSON(http.StatusInternalServerError, gin.H{ "error": err.Error() }) - } else { - c.JSON(http.StatusOK, gin.H{ "item": user }) - } + if err := services.Db.First(&user, c.Param("id")).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } else { + c.JSON(http.StatusOK, gin.H{"item": user}) + } } -// UserDeleteId -func UserDeleteId(c *gin.Context) { - user := models.User{} +// UserDeleteID +func UserDeleteID(c *gin.Context) { + user := models.User{} - if err := services.Db.First(&user, c.Param("id")).Delete(&user).Error; err != nil { - c.JSON(http.StatusInternalServerError, gin.H{ "error": err.Error() }) - } else { - c.JSON(http.StatusOK, gin.H{ "item": user }) - } + if err := services.Db.First(&user, c.Param("id")).Delete(&user).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } else { + c.JSON(http.StatusOK, gin.H{"item": user}) + } } diff --git a/source/controllers/utils.go b/source/controllers/utils.go index 9051493..7b34a91 100644 --- a/source/controllers/utils.go +++ b/source/controllers/utils.go @@ -1,25 +1,24 @@ /** * Created by fbonhomm * Email: flo-github@outlook.fr - * Licence: MIT + * License: MIT */ package controllers import ( - "errors" - "github.com/gin-gonic/gin" + "errors" + + "github.com/gin-gonic/gin" ) // GetToken -func GetToken(c *gin.Context) (info map[string]string, err error) { - token, ok := c.Get("Token") +func GetToken(c *gin.Context) (map[string]string, error) { + token, ok := c.Get("Token") - if ok == false { - err = errors.New("token is not found") - } else { - info = token.(map[string]string) - } + if !ok { + return nil, errors.New("token is not found") + } - return info, err + return token.(map[string]string), nil } diff --git a/source/libs/generate-access-token.go b/source/libs/generate-access-token.go index a5758a6..462e388 100644 --- a/source/libs/generate-access-token.go +++ b/source/libs/generate-access-token.go @@ -1,31 +1,38 @@ /** * Created by fbonhomm * Email: flo-github@outlook.fr - * Licence: MIT + * License: MIT */ package libs import ( - "time" + "errors" + "time" - "github.com/dgrijalva/jwt-go" + "github.com/dgrijalva/jwt-go" - "github.com/fbonhomm/api-go/source/models" - "github.com/fbonhomm/api-go/source/services" + "github.com/fbonhomm/api-go/source/models" + "github.com/fbonhomm/api-go/source/services" ) // GenerateAccessToken -func GenerateAccessToken(user models.User) (accessToken string, err error) { - token := jwt.New(jwt.SigningMethodES256) +func GenerateAccessToken(user *models.User) (accessToken string, err error) { + var ok bool + var token *jwt.Token + var claims jwt.MapClaims - claims := token.Claims.(jwt.MapClaims) - claims["id"] = user.ID - claims["name"] = user.Name - claims["email"] = user.Email - claims["exp"] = time.Now().Add(time.Minute * 15).Unix() + token = jwt.New(jwt.SigningMethodES256) - accessToken, err = token.SignedString(services.PrivateKeyAccess) + if claims, ok = token.Claims.(jwt.MapClaims); !ok { + return accessToken, errors.New("access token is not valid") + } + claims["id"] = user.ID + claims["name"] = user.Name + claims["email"] = user.Email + claims["exp"] = time.Now().Add(time.Minute * 15).Unix() - return accessToken, err + accessToken, err = token.SignedString(services.PrivateKeyAccess) + + return accessToken, err } diff --git a/source/libs/generate-refresh-token.go b/source/libs/generate-refresh-token.go index ac37df9..54a80db 100644 --- a/source/libs/generate-refresh-token.go +++ b/source/libs/generate-refresh-token.go @@ -1,27 +1,36 @@ /** * Created by fbonhomm * Email: flo-github@outlook.fr - * Licence: MIT + * License: MIT */ package libs import ( - "github.com/dgrijalva/jwt-go" - "github.com/fbonhomm/api-go/source/models" - "github.com/fbonhomm/api-go/source/services" - "time" + "errors" + "time" + + "github.com/dgrijalva/jwt-go" + + "github.com/fbonhomm/api-go/source/models" + "github.com/fbonhomm/api-go/source/services" ) // GenerateRefreshToken -func GenerateRefreshToken(user models.User) (refreshToken string, err error) { - token := jwt.New(jwt.SigningMethodES384) +func GenerateRefreshToken(user *models.User) (refreshToken string, err error) { + var ok bool + var token *jwt.Token + var claims jwt.MapClaims - claims := token.Claims.(jwt.MapClaims) - claims["id"] = user.ID - claims["exp"] = time.Now().Add(time.Hour * 24).Unix() + token = jwt.New(jwt.SigningMethodES384) - refreshToken, err = token.SignedString(services.PrivateKeyRefresh) + if claims, ok = token.Claims.(jwt.MapClaims); !ok { + return refreshToken, errors.New("refresh token is not valid") + } + claims["id"] = user.ID + claims["exp"] = time.Now().Add(time.Hour * 24).Unix() - return refreshToken, err + refreshToken, err = token.SignedString(services.PrivateKeyRefresh) + + return refreshToken, err } diff --git a/source/libs/get-token.go b/source/libs/get-token.go index ef34b37..65d46e2 100644 --- a/source/libs/get-token.go +++ b/source/libs/get-token.go @@ -1,25 +1,26 @@ /** * Created by fbonhomm * Email: flo-github@outlook.fr - * Licence: MIT + * License: MIT */ package libs import ( - "errors" - "github.com/gin-gonic/gin" - "strings" + "errors" + "strings" + + "github.com/gin-gonic/gin" ) // GetToken func GetToken(c *gin.Context) (string, error) { - var reqToken = c.Request.Header.Get("Authorization") - var splitToken = strings.Split(reqToken, "Bearer") + var reqToken = c.Request.Header.Get("Authorization") + var splitToken = strings.Split(reqToken, "Bearer") - if len(splitToken) != 2 { - return "", errors.New("Token not provided.") - } + if len(splitToken) != 2 { + return "", errors.New("token not provided") + } - return strings.TrimSpace(splitToken[1]), nil + return strings.TrimSpace(splitToken[1]), nil } diff --git a/source/middlewares/jwt.go b/source/middlewares/jwt.go index ba62e27..2a3c896 100644 --- a/source/middlewares/jwt.go +++ b/source/middlewares/jwt.go @@ -1,77 +1,79 @@ /** * Created by fbonhomm * Email: flo-github@outlook.fr - * Licence: MIT + * License: MIT */ package middlewares import ( - "fmt" - "github.com/dgrijalva/jwt-go" - "github.com/fbonhomm/api-go/source/libs" - "github.com/fbonhomm/api-go/source/services" - "github.com/gin-gonic/gin" - "net/http" + "fmt" + "net/http" + + "github.com/dgrijalva/jwt-go" + "github.com/gin-gonic/gin" + + "github.com/fbonhomm/api-go/source/libs" + "github.com/fbonhomm/api-go/source/services" ) func Auth(c *gin.Context) { - tokenString, err := libs.GetToken(c) + tokenString, err := libs.GetToken(c) - if err != nil { - c.JSON(http.StatusUnauthorized, gin.H{ "error": err }) - c.Abort() - return - } + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": err}) + c.Abort() + return + } - token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { - if _, ok := token.Method.(*jwt.SigningMethodECDSA); !ok { - return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) - } + token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { + if _, ok := token.Method.(*jwt.SigningMethodECDSA); !ok { + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) + } - return services.PublicKeyAccess, nil - }) + return services.PublicKeyAccess, nil + }) - if err != nil { - c.JSON(http.StatusUnauthorized, gin.H{ "error": "Token not conform." }) - c.Abort() - return - } + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Token not conform."}) + c.Abort() + return + } - if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { - c.Set("Token", claims) - } else { - c.JSON(http.StatusUnauthorized, gin.H{ "error": "Token not conform." }) - c.Abort() - } + if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { + c.Set("Token", claims) + } else { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Token not conform."}) + c.Abort() + } } func AuthRefresh(c *gin.Context) { - tokenString := c.PostForm("refresh_token") + tokenString := c.PostForm("refresh_token") - token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { - if _, ok := token.Method.(*jwt.SigningMethodECDSA); !ok { - return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) - } + token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { + if _, ok := token.Method.(*jwt.SigningMethodECDSA); !ok { + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) + } - return services.PublicKeyRefresh, nil - }) + return services.PublicKeyRefresh, nil + }) - if err != nil { - c.JSON(http.StatusUnauthorized, gin.H{ "error": "Token not conform." }) - c.Abort() - return - } + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Token not conform."}) + c.Abort() + return + } - if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { - var decode = make(map[string]string, 10) + if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { + var decode = make(map[string]string, 10) - for key, value := range claims { - decode[key] = fmt.Sprintf("%v", value) - } - c.Set("Token", decode) - } else { - c.JSON(http.StatusUnauthorized, gin.H{ "error": "Token not conform." }) - c.Abort() - } + for key, value := range claims { + decode[key] = fmt.Sprintf("%v", value) + } + c.Set("Token", decode) + } else { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Token not conform."}) + c.Abort() + } } diff --git a/source/models/user.go b/source/models/user.go index 1554342..7d597a5 100644 --- a/source/models/user.go +++ b/source/models/user.go @@ -1,41 +1,36 @@ /** * Created by fbonhomm * Email: flo-github@outlook.fr - * Licence: MIT + * License: MIT */ package models import ( - "github.com/jinzhu/gorm" - "golang.org/x/crypto/bcrypt" + "github.com/jinzhu/gorm" + "golang.org/x/crypto/bcrypt" ) -// ID uint `gorm:"primary_key"` -// CreatedAt time.Time -// UpdatedAt time.Time -// DeletedAt *time.Time `sql:"index"` - type User struct { - gorm.Model - Name string `gorm:"type:varchar(50);not null" json:"name"` - Email string `gorm:"type:varchar(100);unique_index;not null" json:"email"` - Password string `gorm:"type:text;not null" json:"-"` + gorm.Model + Name string `gorm:"type:varchar(50);not null" json:"name"` + Email string `gorm:"type:varchar(100);unique_index;not null" json:"email"` + Password string `gorm:"type:text;not null" json:"-"` } func (u *User) BeforeSave() (err error) { - var hash []byte + var hash []byte - if u.Password != "" { - hash, err = bcrypt.GenerateFromPassword([]byte(u.Password), 12) + if u.Password != "" { + hash, err = bcrypt.GenerateFromPassword([]byte(u.Password), 12) - if err == nil { - u.Password = string(hash) - } - } - return err + if err == nil { + u.Password = string(hash) + } + } + return err } func (u *User) Compare(attempt string) (err error) { - return bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(attempt)) + return bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(attempt)) } diff --git a/source/routers/auth.go b/source/routers/auth.go index 5a895f2..36cf10f 100644 --- a/source/routers/auth.go +++ b/source/routers/auth.go @@ -1,22 +1,23 @@ /** * Created by fbonhomm * Email: flo-github@outlook.fr - * Licence: MIT + * License: MIT */ package routers import ( - "github.com/fbonhomm/api-go/source/controllers" - "github.com/fbonhomm/api-go/source/middlewares" - "github.com/fbonhomm/api-go/source/validators" - "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin" + + "github.com/fbonhomm/api-go/source/controllers" + "github.com/fbonhomm/api-go/source/middlewares" + "github.com/fbonhomm/api-go/source/validators" ) // main func Auth(router *gin.Engine) { - route := router.Group("/auth") + route := router.Group("/auth") - route.POST("", validators.ValidateAuthLogin, controllers.AuthLogin) - route.POST("/refresh", middlewares.AuthRefresh, validators.ValidateAuthRefresh, controllers.AuthRefresh) + route.POST("", validators.ValidateAuthLogin, controllers.AuthLogin) + route.POST("/refresh", middlewares.AuthRefresh, validators.ValidateAuthRefresh, controllers.AuthRefresh) } diff --git a/source/routers/index.go b/source/routers/index.go index cba1c3d..ca5527f 100644 --- a/source/routers/index.go +++ b/source/routers/index.go @@ -1,36 +1,35 @@ /** * Created by fbonhomm * Email: flo-github@outlook.fr - * Licence: MIT + * License: MIT */ package routers import ( - "os" - "time" + "os" + "time" - "github.com/gin-contrib/cors" - "github.com/gin-gonic/gin" + "github.com/gin-contrib/cors" + "github.com/gin-gonic/gin" ) // RouterInitialize // Initialize all api route func RouterInitialize() *gin.Engine { - routerEngine := gin.Default() + routerEngine := gin.Default() - routerEngine.Use(cors.New(cors.Config{ - AllowOrigins: []string{os.Getenv("HOST") + ":" + os.Getenv("PORT")}, - AllowMethods: []string{"OPTIONS", "GET", "POST", "PUT", "DELETE"}, - AllowHeaders: []string{"Origin", "Content-Type", "Content-Length", "Accept-Encoding", "Authorization"}, - ExposeHeaders: []string{"Content-Length"}, - AllowCredentials: true, - MaxAge: 12 * time.Hour, - })) + routerEngine.Use(cors.New(cors.Config{ + AllowOrigins: []string{os.Getenv("HOST") + ":" + os.Getenv("PORT")}, + AllowMethods: []string{"OPTIONS", "GET", "POST", "PUT", "DELETE"}, + AllowHeaders: []string{"Origin", "Content-Type", "Content-Length", "Accept-Encoding", "Authorization"}, + ExposeHeaders: []string{"Content-Length"}, + AllowCredentials: true, + MaxAge: 12 * time.Hour, + })) - User(routerEngine) - Auth(routerEngine) + User(routerEngine) + Auth(routerEngine) - return routerEngine + return routerEngine } - diff --git a/source/routers/user.go b/source/routers/user.go index efa22f9..81ed8f4 100644 --- a/source/routers/user.go +++ b/source/routers/user.go @@ -1,23 +1,24 @@ /** * Created by fbonhomm * Email: flo-github@outlook.fr - * Licence: MIT + * License: MIT */ package routers import ( - "github.com/fbonhomm/api-go/source/controllers" - "github.com/fbonhomm/api-go/source/middlewares" - "github.com/fbonhomm/api-go/source/validators" - "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin" + + "github.com/fbonhomm/api-go/source/controllers" + "github.com/fbonhomm/api-go/source/middlewares" + "github.com/fbonhomm/api-go/source/validators" ) // main func User(router *gin.Engine) { - route := router.Group("/users") + route := router.Group("/users") - route.POST("", middlewares.Auth, validators.ValidateUserCreate, controllers.UserCreate) - route.GET("/:id", middlewares.Auth, validators.ValidateUserGetId, controllers.UserGetId) - route.DELETE("/:id", middlewares.Auth, validators.ValidateUserDeleteId, controllers.UserDeleteId) + route.POST("", middlewares.Auth, validators.ValidateUserCreate, controllers.UserCreate) + route.GET("/:id", middlewares.Auth, validators.ValidateUserGetID, controllers.UserGetID) + route.DELETE("/:id", middlewares.Auth, validators.ValidateUserDeleteID, controllers.UserDeleteID) } diff --git a/source/services/database.go b/source/services/database.go index f84e159..25609f5 100644 --- a/source/services/database.go +++ b/source/services/database.go @@ -1,35 +1,38 @@ /** * Created by fbonhomm * Email: flo-github@outlook.fr - * Licence: MIT + * License: MIT */ package services import ( - "fmt" - "github.com/fbonhomm/api-go/source/models" - "github.com/jinzhu/gorm" - _ "github.com/jinzhu/gorm/dialects/postgres" - "log" - "os" + "fmt" + "log" + "os" + + "github.com/jinzhu/gorm" + // initialize dialects + _ "github.com/jinzhu/gorm/dialects/postgres" + + "github.com/fbonhomm/api-go/source/models" ) var Db *gorm.DB var Err error func Database() { - Db, Err = gorm.Open( - "postgres", - fmt.Sprintf( - "host=%s port=%s dbname=%s user=%s password=%s sslmode=disable", - os.Getenv("DB_HOST"), os.Getenv("DB_PORT"), os.Getenv("DB_NAME"), - os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD")), - ) + Db, Err = gorm.Open( + "postgres", + fmt.Sprintf( + "host=%s port=%s dbname=%s user=%s password=%s sslmode=disable", + os.Getenv("DB_HOST"), os.Getenv("DB_PORT"), os.Getenv("DB_NAME"), + os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD")), + ) - if Err != nil { - log.Panic("Error connect database: ", Err) - } + if Err != nil { + log.Panic("Error connect database: ", Err) + } - Db.AutoMigrate(&models.User{}) + Db.AutoMigrate(&models.User{}) } diff --git a/source/services/jwt.go b/source/services/jwt.go index 8a7c067..66b726f 100644 --- a/source/services/jwt.go +++ b/source/services/jwt.go @@ -1,39 +1,56 @@ /** * Created by fbonhomm * Email: flo-github@outlook.fr - * Licence: MIT + * License: MIT */ package services import ( - "crypto/ecdsa" - "io/ioutil" - "os" + "log" + "os" - "github.com/dgrijalva/jwt-go" + "crypto/ecdsa" + "io/ioutil" + + "github.com/dgrijalva/jwt-go" ) - var PublicKeyAccess *ecdsa.PublicKey var PrivateKeyAccess *ecdsa.PrivateKey var PublicKeyRefresh *ecdsa.PublicKey var PrivateKeyRefresh *ecdsa.PrivateKey -var err error func Jwt() { - var tmp []byte - var root = os.Getenv("ROOT") + "/source/services" + var tmp []byte + var err error + var root = os.Getenv("ROOT") + "/source/services" - tmp, err = ioutil.ReadFile(root + "/jwt/access.public.pem") - PublicKeyAccess, _ = jwt.ParseECPublicKeyFromPEM(tmp) + if tmp, err = ioutil.ReadFile(root + "/jwt/access.public.pem"); err != nil { + log.Fatal(err) + } + if PublicKeyAccess, err = jwt.ParseECPublicKeyFromPEM(tmp); err != nil { + log.Fatal(err) + } - tmp, _ = ioutil.ReadFile(root + "/jwt/access.private.pem") - PrivateKeyAccess, _ = jwt.ParseECPrivateKeyFromPEM(tmp) + if tmp, err = ioutil.ReadFile(root + "/jwt/access.private.pem"); err != nil { + log.Fatal(err) + } + if PrivateKeyAccess, err = jwt.ParseECPrivateKeyFromPEM(tmp); err != nil { + log.Fatal(err) + } - tmp, _ = ioutil.ReadFile(root + "/jwt/refresh.public.pem") - PublicKeyRefresh, _ = jwt.ParseECPublicKeyFromPEM(tmp) + if tmp, err = ioutil.ReadFile(root + "/jwt/refresh.public.pem"); err != nil { + log.Fatal(err) + } + if PublicKeyRefresh, err = jwt.ParseECPublicKeyFromPEM(tmp); err != nil { + log.Fatal(err) + } - tmp, _ = ioutil.ReadFile(root + "/jwt/refresh.private.pem") - PrivateKeyRefresh, _ = jwt.ParseECPrivateKeyFromPEM(tmp) + if tmp, err = ioutil.ReadFile(root + "/jwt/refresh.private.pem"); err != nil { + log.Fatal(err) + } + if PrivateKeyRefresh, err = jwt.ParseECPrivateKeyFromPEM(tmp); err != nil { + log.Fatal(err) + } } diff --git a/source/validators/auth.go b/source/validators/auth.go index 0126a7d..15e4891 100644 --- a/source/validators/auth.go +++ b/source/validators/auth.go @@ -1,42 +1,41 @@ /** * Created by fbonhomm * Email: flo-github@outlook.fr - * Licence: MIT + * License: MIT */ package validators import ( - "github.com/gin-gonic/gin" - "github.com/gin-gonic/gin/binding" + "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin/binding" ) type authLogin struct { - Email string `form:"email" binding:"required,email"` - Password string `form:"password" binding:"required,min=8,max=50"` + Email string `form:"email" binding:"required,email"` + Password string `form:"password" binding:"required,min=8,max=50"` } type authRefresh struct { - RefreshToken string `form:"refresh_token" binding:"required,min=100,max=1000"` + RefreshToken string `form:"refresh_token" binding:"required,min=100,max=1000"` } - // ValidateAuthLogin func ValidateAuthLogin(c *gin.Context) { - var v authLogin + var v authLogin - if err := c.ShouldBindWith(&v, binding.FormPost); err != nil { - errorHandling(c, err.Error()) - return - } + if err := c.ShouldBindWith(&v, binding.FormPost); err != nil { + errorHandling(c, err.Error()) + return + } } // ValidateAuthRefresh func ValidateAuthRefresh(c *gin.Context) { - var v authRefresh + var v authRefresh - if err := c.ShouldBindWith(&v, binding.FormPost); err != nil { - errorHandling(c, err.Error()) - return - } + if err := c.ShouldBindWith(&v, binding.FormPost); err != nil { + errorHandling(c, err.Error()) + return + } } diff --git a/source/validators/user.go b/source/validators/user.go index 137d9cb..8ab64a6 100644 --- a/source/validators/user.go +++ b/source/validators/user.go @@ -1,56 +1,55 @@ /** * Created by fbonhomm * Email: flo-github@outlook.fr - * Licence: MIT + * License: MIT */ package validators import ( - "github.com/gin-gonic/gin" - "github.com/gin-gonic/gin/binding" + "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin/binding" ) // https://godoc.org/gopkg.in/go-playground/validator.v8 type userCreate struct { - Name string `form:"name" binding:"required,min=2,max=50"` - Email string `form:"email" binding:"required,email"` - Password string `form:"password" binding:"required,min=8,max=50"` + Name string `form:"name" binding:"required,min=2,max=50"` + Email string `form:"email" binding:"required,email"` + Password string `form:"password" binding:"required,min=8,max=50"` } -type userGetId struct { - Id uint `uri:"id" binding:"required,min=0,max=9999"` +type userGetID struct { + ID uint `uri:"id" binding:"required,min=0,max=9999"` } -type userDeleteId struct { - Id uint `uri:"id" binding:"required,min=0,max=9999"` +type userDeleteID struct { + ID uint `uri:"id" binding:"required,min=0,max=9999"` } - // ValidateUserCreate func ValidateUserCreate(c *gin.Context) { - var v userCreate + var v userCreate - if err := c.ShouldBindWith(&v, binding.FormPost); err != nil { - errorHandling(c, err.Error()) - } + if err := c.ShouldBindWith(&v, binding.FormPost); err != nil { + errorHandling(c, err.Error()) + } } -// ValidateUserGetId -func ValidateUserGetId(c *gin.Context) { - var v userGetId +// ValidateUserGetID +func ValidateUserGetID(c *gin.Context) { + var v userGetID - if err := c.ShouldBindUri(&v); err != nil { - errorHandling(c, err.Error()) - } + if err := c.ShouldBindUri(&v); err != nil { + errorHandling(c, err.Error()) + } } -// ValidateUserDeleteId -func ValidateUserDeleteId(c *gin.Context) { - var v userDeleteId +// ValidateUserDeleteID +func ValidateUserDeleteID(c *gin.Context) { + var v userDeleteID - if err := c.ShouldBindUri(&v); err != nil { - errorHandling(c, err.Error()) - } + if err := c.ShouldBindUri(&v); err != nil { + errorHandling(c, err.Error()) + } } diff --git a/source/validators/utils.go b/source/validators/utils.go index 4fb5169..c430ecc 100644 --- a/source/validators/utils.go +++ b/source/validators/utils.go @@ -1,18 +1,18 @@ /** * Created by fbonhomm * Email: flo-github@outlook.fr - * Licence: MIT + * License: MIT */ package validators import ( - "net/http" + "net/http" - "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin" ) func errorHandling(c *gin.Context, msg string) { - c.JSON(http.StatusBadRequest, gin.H{ "error": msg }) - c.Abort() + c.JSON(http.StatusBadRequest, gin.H{"error": msg}) + c.Abort() }