-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathdelete_account_handler.go
More file actions
43 lines (35 loc) · 1.13 KB
/
Copy pathdelete_account_handler.go
File metadata and controls
43 lines (35 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package main
import (
"crypto/subtle"
"fmt"
"net/http"
)
type DeleteAccountHandler HandlerWithDBConnection
func (hd *DeleteAccountHandler) ServeHTTP(resp http.ResponseWriter, request *http.Request) {
db := hd.db
session, err := sessionFromRequest(request, db)
if err == ErrInvalidSession {
fmt.Println(err)
clearSessionCookie(resp)
}
signedIn := err == nil
if !signedIn {
fmt.Println("deleting account: not signed in")
http.Error(resp, "Unauthorized", http.StatusUnauthorized)
return
}
if subtle.ConstantTimeCompare([]byte(request.PostFormValue("csrf_token")), []byte(session.csrfToken)) != 1 {
fmt.Println("invalid csrf token")
http.Error(resp, "Invalid CSRF token", http.StatusBadRequest)
return
}
// TODO: use idiomatic go transactions
_, err = db.Exec("begin transaction; delete from users where user_id = ?; delete from sessions where user_id = ?; commit;", session.userId, session.userId)
if err != nil {
fmt.Println("deleting user:", err)
http.Error(resp, "Internal server error", http.StatusInternalServerError)
return
}
clearSessionCookie(resp)
http.Redirect(resp, request, "/", http.StatusSeeOther)
}