Add CSRF checks to likes.

jocadbz
Joca 2026-03-06 14:53:23 -03:00
parent ca5ad07f26
commit f3749b3812
Signed by: jocadbz
GPG Key ID: B1836DCE2F50BDF7
3 changed files with 10 additions and 2 deletions

View File

@ -23,6 +23,10 @@ func LikeHandler(app *App) http.HandlerFunc {
http.Error(w, "Unauthorized", http.StatusUnauthorized) http.Error(w, "Unauthorized", http.StatusUnauthorized)
return return
} }
if !app.validateCSRFToken(r, session) {
http.Error(w, "Invalid CSRF token", http.StatusForbidden)
return
}
postIDStr := r.FormValue("post_id") postIDStr := r.FormValue("post_id")
postID, err := strconv.Atoi(postIDStr) postID, err := strconv.Atoi(postIDStr)

View File

@ -5,6 +5,7 @@ function initLikeButtons() {
var postId = btn.getAttribute('data-post-id'); var postId = btn.getAttribute('data-post-id');
var type = btn.getAttribute('data-type'); var type = btn.getAttribute('data-type');
var basePath = btn.getAttribute('data-base-path'); var basePath = btn.getAttribute('data-base-path');
var csrfToken = document.body ? document.body.getAttribute('data-csrf-token') : '';
btn.disabled = true; btn.disabled = true;
@ -14,7 +15,10 @@ function initLikeButtons() {
fetch(basePath + '/like/', { fetch(basePath + '/like/', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRF-Token': csrfToken
},
body: body.toString() body: body.toString()
}) })
.then(function(res) { return res.json(); }) .then(function(res) { return res.json(); })

View File

@ -7,7 +7,7 @@
<script src="{{.StaticPath}}/likes.js" defer></script> <script src="{{.StaticPath}}/likes.js" defer></script>
<script src="{{.StaticPath}}/app.js" defer></script> <script src="{{.StaticPath}}/app.js" defer></script>
</head> </head>
<body> <body data-csrf-token="{{.CSRFToken}}">
{{template "navbar" .}} {{template "navbar" .}}
<main> <main>
<div class="breadcrumb"> <div class="breadcrumb">