bigest part of the api done

This commit is contained in:
2022-01-30 05:39:57 +01:00
commit 7585a53baa
38 changed files with 11551 additions and 0 deletions

View File

@@ -0,0 +1,57 @@
package authentication
import (
"database/sql"
"net/http"
"github.com/gin-gonic/gin"
"spahl.ddns.net/jasper/wok-able-backend/auth"
"spahl.ddns.net/jasper/wok-able-backend/models"
)
func Register(c *gin.Context) {
var user models.User
if err := c.BindJSON(&user); err != nil || user.Email == "" || user.Username == "" {
c.Status(http.StatusBadRequest)
return
}
if err := models.DB.Create(&user).Save(&user).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
token, err := auth.GenerateJWT(user.ID, user.Username, user.Email)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.SetCookie("token", token, 2*60*60, "", "", false, true)
c.Status(http.StatusCreated)
}
func Login(c *gin.Context) {
var authentication models.Auth
if err := c.BindJSON(&authentication); err != nil {
c.Status(http.StatusBadRequest)
return
}
var user models.User
models.DB.Where("username = @name OR email = @name", sql.Named("name", authentication.Username)).First(&user)
if user.Email == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Username or Password is incorrect"})
return
}
if err := auth.CheckPassword(authentication.Password, user.Salt, user.PasswordHash); err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Username or Password is incorrect"})
return
}
token, _ := auth.GenerateJWT(user.ID, user.Username, user.Email)
c.SetCookie("token", token, 2*60*60, "", "", false, true)
c.Status(http.StatusOK)
}
func Logout(c *gin.Context) {
c.SetCookie("token", "", -1, "", "", false, true)
c.Redirect(http.StatusTemporaryRedirect, "/")
}

View File

@@ -0,0 +1,9 @@
package authentication
import "github.com/gin-gonic/gin"
func Setup(r *gin.RouterGroup) {
r.GET("/logout", Logout)
r.POST("/login", Login)
r.POST("/register", Register)
}