portfolio/api/handlers/authHandler.go

52 lines
938 B
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"
"fmt"
"net/http"
2024-05-16 17:36:44 +02:00
"portfolio/database/ent"
"portfolio/database/ent/user"
"portfolio/database/query"
"portfolio/service/bcrypt"
2024-05-15 15:27:18 +02:00
)
func Login(w http.ResponseWriter, r *http.Request) {
fmt.Println("test")
var u *ent.User
isHtmx := r.Header.Get("HX-Request")
if isHtmx == "true" {
u = &ent.User{
Name: r.PostFormValue("name"),
Password: r.PostFormValue("password"),
Role: user.Role(r.PostFormValue("role")),
}
} else {
err := json.NewDecoder(r.Body).Decode(&u)
if err != nil {
InternalServerErrorHandler(w)
}
}
User, err := query.GetLogin(context.Background(), u.Name)
if err != nil {
return
}
if bcrypt.CheckPasswordHash(u.Password, User.Password) {
w.Header().Set("HX-Location", "/")
return
} else {
}
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(User)
if err != nil {
return
}
}