Go-JWT-Tests/controllers/usersController.go

128 lines
2.5 KiB
Go
Raw Permalink Normal View History

package controllers
import (
"net/http"
"os"
"time"
"gitea.voser.cloud/janic/Go-JWT-Tests/initializers"
"gitea.voser.cloud/janic/Go-JWT-Tests/models"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
)
func Signup(c *gin.Context) {
// Get the email/pass
var body struct {
Email string
Password string
}
if c.Bind(&body) != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Failed to read body",
})
return
}
// Hash Password
hash, err := bcrypt.GenerateFromPassword([]byte(body.Password), 10)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Failed to hash password",
})
return
}
// Create the user
user := models.User{Email: body.Email, Password: string(hash)}
result := initializers.DB.Create(&user)
if result.Error != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Failed to create user",
})
return
}
// respond
c.JSON(http.StatusOK, gin.H{})
}
func Login(c *gin.Context) {
// Get the email and pass of body
var body struct {
Email string
Password string
}
if c.Bind(&body) != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Failed to read body",
})
return
}
// Lookup requested user
var user models.User
initializers.DB.First(&user, "email = ?", body.Email)
if user.ID == 0 {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Invalid Email or Password",
})
return
}
// Compare sent in pass with saved user pass hash
err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(body.Password))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Invalid Email or Password",
})
return
}
// Generate a jwt token
// Create a new token object, specifying signing method and the claims
// you would like it to contain.
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": user.ID,
"nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),
"exp": time.Now().Add(time.Hour * 24 * 30).Unix(),
})
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString([]byte(os.Getenv("SECRET")))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Failed to create Token",
})
return
}
// Return token
c.SetSameSite(http.SameSiteLaxMode)
c.SetCookie("Authorization", tokenString, 3600*24*30, "", "", false, true)
c.JSON(http.StatusOK, gin.H{})
}
func Validate(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "I'm Logged in",
})
}