package controllers import ( "fmt" "html" "net/http" "strings" "ccsecrets/models" "ccsecrets/utils/token" "github.com/gin-gonic/gin" "golang.org/x/crypto/bcrypt" ) type RegisterInput struct { Username string `json:"username" binding:"required"` Password string `json:"password" binding:"required"` } type LoginInput struct { Username string `json:"username" binding:"required"` Password string `json:"password" binding:"required"` } func Register(c *gin.Context) { var input RegisterInput if err := c.ShouldBindJSON(&input); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } u := models.User{} u.RoleId = 1 u.UserName = input.Username u.Password = input.Password //turn password into hash hashedPassword, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"Error hashing password": err.Error()}) return } else { fmt.Printf("Register generated hashed password value '%s' from '%s'\n", string(hashedPassword), input.Password) } u.Password = string(hashedPassword) //remove spaces in username u.UserName = html.EscapeString(strings.TrimSpace(u.UserName)) _, err = u.SaveUser() if err != nil { c.JSON(http.StatusBadRequest, gin.H{"Error saving user": err.Error()}) return } c.JSON(http.StatusOK, gin.H{"message": "registration success"}) } func Login(c *gin.Context) { var input LoginInput if err := c.ShouldBindJSON(&input); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } u := models.User{} u.UserName = input.Username u.Password = input.Password fmt.Printf("Login checking username '%s' and password '%s'\n", u.UserName, u.Password) token, err := models.LoginCheck(u.UserName, u.Password) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "username or password is incorrect."}) return } c.JSON(http.StatusOK, gin.H{"token": token}) } func CurrentUser(c *gin.Context) { user_id, err := token.ExtractTokenID(c) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } u, err := models.GetUserByID(user_id) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } c.JSON(http.StatusOK, gin.H{"message": "success", "data": u}) }