You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
1.6 KiB
Go
58 lines
1.6 KiB
Go
3 years ago
|
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, "/")
|
||
|
}
|