portfolio/api/handlers/authHandler.go

65 lines
1.2 KiB
Go
Raw Normal View History

2024-05-16 17:59:21 +02:00
package handlers
2024-05-15 15:27:18 +02:00
import (
"context"
"encoding/json"
"net/http"
2024-05-19 17:49:20 +02:00
"portfolio/api/service/bcrypt"
"portfolio/api/service/jwt"
2024-05-16 17:36:44 +02:00
"portfolio/database/ent"
"portfolio/database/query"
2024-05-15 15:27:18 +02:00
)
func Login(w http.ResponseWriter, r *http.Request) {
var u *ent.User
isHtmx := r.Header.Get("HX-Request")
if isHtmx == "true" {
u = &ent.User{
2024-05-19 23:56:53 +02:00
Email: r.PostFormValue("email"),
2024-05-15 15:27:18 +02:00
Password: r.PostFormValue("password"),
}
} else {
err := json.NewDecoder(r.Body).Decode(&u)
if err != nil {
2024-05-19 17:49:20 +02:00
InternalServerErrorHandler(w, err)
2024-05-15 15:27:18 +02:00
}
}
2024-05-19 17:49:20 +02:00
User, err := query.GetLogin(context.Background(), u)
2024-05-15 15:27:18 +02:00
if err != nil {
2024-05-19 17:49:20 +02:00
UnprocessableEntityHandler(w, err)
2024-05-15 15:27:18 +02:00
return
}
if bcrypt.CheckPasswordHash(u.Password, User.Password) {
2024-05-19 23:56:53 +02:00
jwtToken := jwt.CreateUserJWT(User.Name, User.ID, string(User.Role))
2024-05-15 15:27:18 +02:00
2024-05-19 17:49:20 +02:00
if jwtToken != "" {
2024-05-15 15:27:18 +02:00
2024-05-19 23:56:53 +02:00
cookie := &http.Cookie{Name: "jwt",
Value: jwtToken,
//HttpOnly: true,
//Secure: true,
//SameSite: http.SameSiteNoneMode,
//Expires: time.Now().Add(24 * time.Hour),
}
2024-05-19 17:49:20 +02:00
http.SetCookie(w, cookie)
w.WriteHeader(http.StatusOK)
_, err = w.Write([]byte("login success"))
return
} else {
InternalServerErrorHandler(w, err)
return
}
} else {
UnauthorizedHandler(w)
2024-05-15 15:27:18 +02:00
return
}
}