portfolio/api/handlers/authHandler.go

85 lines
1.7 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-09-12 15:34:45 +02:00
"portfolio/api/types"
2024-05-16 17:36:44 +02:00
"portfolio/database/query"
2024-05-19 23:57:13 +02:00
"time"
2024-05-15 15:27:18 +02:00
)
func Login(w http.ResponseWriter, r *http.Request) {
2024-09-12 15:34:45 +02:00
var u *types.LoginUser
2024-05-15 15:27:18 +02:00
2025-05-09 21:31:48 +02:00
if r.Header.Get("HX-Request") == "true" {
u = handleHtmxLogin(r)
2024-05-15 15:27:18 +02:00
} else {
2025-05-09 21:31:48 +02:00
u = handleHttpLogin(w, r, u)
}
if u == nil {
return
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
}
2025-05-09 21:31:48 +02:00
if !bcrypt.CheckPasswordHash(u.Password, User.Password) {
UnauthorizedHandler(w)
return
}
2024-05-15 15:27:18 +02:00
2025-05-09 21:31:48 +02:00
jwtToken := jwt.CreateUserJWT(User.Name, User.ID, string(User.Role))
2024-05-15 15:27:18 +02:00
2025-05-09 21:31:48 +02:00
cookie := &http.Cookie{
Name: "jwt",
Value: jwtToken,
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteLaxMode,
Expires: time.Now().Add(24 * time.Hour),
}
2024-05-19 23:56:53 +02:00
2025-05-09 21:31:48 +02:00
http.SetCookie(w, cookie)
2024-05-19 17:49:20 +02:00
2025-05-09 21:31:48 +02:00
w.WriteHeader(http.StatusOK)
_, err = w.Write([]byte("login success"))
}
2024-05-19 17:49:20 +02:00
2025-05-09 21:31:48 +02:00
func handleHtmxLogin(r *http.Request) *types.LoginUser {
return &types.LoginUser{
Email: r.PostFormValue("email"),
Password: r.PostFormValue("password"),
}
}
2025-02-24 00:18:04 +01:00
2025-05-09 21:31:48 +02:00
func handleHttpLogin(w http.ResponseWriter, r *http.Request, u *types.LoginUser) *types.LoginUser {
if err := json.NewDecoder(r.Body).Decode(&u); err != nil {
InternalServerErrorHandler(w, err)
return nil
2024-05-15 15:27:18 +02:00
}
2025-05-09 21:31:48 +02:00
return u
2024-05-15 15:27:18 +02:00
}
func CanEdit(w http.ResponseWriter, r *http.Request) {
_, audience, err := jwt.VerifyUser(r)
if err != nil {
w.WriteHeader(http.StatusOK)
w.Write([]byte(""))
}
2025-05-09 21:31:48 +02:00
if audience == "owner" || audience == "admin" {
w.WriteHeader(http.StatusOK)
w.Write([]byte("<button class=\"button is-link\">Edit</button>"))
} else {
w.WriteHeader(http.StatusOK)
w.Write([]byte(""))
}
}