diff --git a/cmd/main.go b/cmd/main.go index 88dae0f..9055f09 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -1,6 +1,7 @@ package main import ( + "fmt" "os" "github.com/gin-gonic/gin" @@ -14,24 +15,33 @@ func initEnvVariables() { } } +func initJWT() { + errInit := internal.AuthMiddleware.MiddlewareInit() + if errInit != nil { + fmt.Printf(errInit.Error()) + } +} + func initGin() { r := gin.Default() r.SetTrustedProxies([]string{"localhost"}) + r.POST("/login", internal.AuthMiddleware.LoginHandler) r.GET("/ping", internal.Ping) - r.GET("/articles/", internal.AuthCheck, internal.GetAllArticles) - r.GET("/articles/:id", internal.AuthCheck, internal.GetArticle) - r.POST("/articles/:id", internal.AuthCheck, internal.AddArticle) - r.DELETE("/articles/:id", internal.AuthCheck, internal.DeleteArticle) + articlesRouter := r.Group("/articles/") + articlesRouter.Use(internal.AuthMiddleware.MiddlewareFunc()) - r.POST("/login", internal.LoginUser) - r.POST("/logout", internal.LogoutUser) + articlesRouter.GET("/", internal.GetAllArticles) + articlesRouter.GET("/:id", internal.GetArticle) + articlesRouter.POST("/:id", internal.AddArticle) + articlesRouter.DELETE("/:id", internal.DeleteArticle) r.Run(":" + os.Getenv("API_PORT")) } func main() { initEnvVariables() + initJWT() initGin() } diff --git a/internal/auth.go b/internal/auth.go index b004b72..eb8178a 100644 --- a/internal/auth.go +++ b/internal/auth.go @@ -1,10 +1,11 @@ package internal import ( - "crypto/sha256" "errors" - "fmt" + "os" + "time" + jwt "github.com/appleboy/gin-jwt/v2" "github.com/gin-gonic/gin" ) @@ -15,90 +16,19 @@ type User struct { var USERS_LOCATION = Location{Database: "gohcms", Collection: "users"} -func getUserHashedPassword(user User) string { - password := sha256.New() - password.Write([]byte(user.Password)) - return fmt.Sprintf("%x", password.Sum(nil)) -} - -func isUserLoggedIn(user User) bool { - for i := 0; i < len(SESSIONS); i++ { - hash1 := fmt.Sprint(SESSIONS[i].Token.Sum(nil)) - hash2 := fmt.Sprint(generateSessionToken(user).Sum(nil)) - if hash1 != hash2 { - continue - } - sessionExpired := isSessionExpired(SESSIONS[i]) - if sessionExpired { - removeSession(user) - } - return !sessionExpired - } - return false -} - -func isUserReal(user User) bool { - docUsers, _ := getDocuments(USERS_LOCATION, user) - return len(docUsers) == 1 -} - -func parseUserFromContext(c *gin.Context) (User, error) { - var user User - if c.BindJSON(&user) != nil { - return User{}, errors.New("could not correctly parse user crendentials") - } - user.Password = getUserHashedPassword(user) - return user, nil -} - -func LoginUser(c *gin.Context) { - user, err := parseUserFromContext(c) - if err != nil { - SendBadRequest(c, err.Error()) - return - } - if isUserLoggedIn(user) { - SendBadRequest(c, "User is already logged in!") - return - } - if !isUserReal(user) { - SendBadRequest(c, "Unknown email or wrong password.") - return - } - addSession(user) - SendOk(c, "User successfully logged in.") -} - -func LogoutUser(c *gin.Context) { - user, err := parseUserFromContext(c) - if err != nil { - SendBadRequest(c, err.Error()) - return - } - if !isUserLoggedIn(user) { - SendBadRequest(c, "User is not logged in!") - return - } - removeSession(user) - SendOk(c, "User successfully logged out.") -} - -func AuthCheck(c *gin.Context) { - var user User - username, password, isOk := c.Request.BasicAuth() - if !isOk { - SendBadRequest(c, "Incorrect or missing user credentials.") - c.Abort() - return - } - - user.Email = username - user.Password = password - user.Password = getUserHashedPassword(user) - - if !isUserLoggedIn(user) { - SendForbidden(c, "Authentification failed, credentials could be wrong, user may not be logged in, session may have expired.") - c.Abort() - return - } +var AuthMiddleware, _ = jwt.New(&jwt.GinJWTMiddleware{ + Realm: "GohCMS", + Key: []byte(os.Getenv("JWT_SECRET")), + Timeout: time.Hour, + MaxRefresh: time.Hour, + Authenticator: JWTAuthenticator, +}) + +func JWTAuthenticator(c *gin.Context) (interface{}, error) { + var user = User{} + c.BindJSON(&user) + if user.Email == "dddeschamps2022" && user.Password == "1234" { + return gin.H{"email": "dddeschamps2022"}, nil + } + return nil, errors.New("can't verify credentials.") }