portfolio/api/handlers/authHandler.go

59 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{
Name: r.PostFormValue("name"),
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 17:49:20 +02:00
jwtToken := jwt.CreateUserJWT(u.Name, u.ID, string(u.Role))
2024-05-15 15:27:18 +02:00
2024-05-19 17:49:20 +02:00
if jwtToken != "" {
w.Header().Set("HX-Location", "/")
2024-05-15 15:27:18 +02:00
2024-05-19 17:49:20 +02:00
cookie := &http.Cookie{Name: "jwt", Value: jwtToken, HttpOnly: true, Secure: true, SameSite: http.SameSiteStrictMode}
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
}
}