-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
86 lines (70 loc) · 2.16 KB
/
main.go
File metadata and controls
86 lines (70 loc) · 2.16 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"fmt"
"net/http"
"base-auth/dbservice"
"base-auth/registerservice"
"log"
)
func rootHandler(w http.ResponseWriter, r *http.Request){
fmt.Fprint(w, "root handler")
}
func htmxActionHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello from HTMX!")
}
func serveHtmx (w http.ResponseWriter, r *http.Request){
http.ServeFile(w, r, "./static/index.html")
}
func handlePrivateRoute (w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w, "private route!")
}
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
middlewareHandler(w, r, next)
})
}
func middlewareHandler(w http.ResponseWriter, r *http.Request, next http.Handler){
cookie, err := r.Cookie("auth-token")
if err != nil || cookie.Value != "secret-token" {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
}
func LoginHandler(w http.ResponseWriter, r *http.Request) {
username := r.FormValue("username")
password := r.FormValue("password")
valid, err := dbservice.CheckCredentials(username, password)
log.Println(valid, "valid")
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
if valid {
http.SetCookie(w, &http.Cookie{
Name: "auth-token",
Value: "secret-token",
Path: "/",
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteStrictMode,
})
fmt.Fprint(w, "Login sucessful, access to /private granted")
} else {
fmt.Fprint(w, "please provide valid credentials!")
http.Error(w, "invalid credetials", http.StatusUnauthorized)
}
}
func main(){
fs := http.FileServer(http.Dir("./static"))
http.Handle("/", fs)
http.HandleFunc("/htmx-action", htmxActionHandler)
http.HandleFunc("/login", LoginHandler)
http.HandleFunc("/register", registerservice.HandleRegister)
privateRoute := http.HandlerFunc(handlePrivateRoute)
http.Handle("/private", AuthMiddleware(privateRoute))
fmt.Println("Starting server on port :8080")
if err := http.ListenAndServe(":8080", nil); err!= nil {
fmt.Println("Error starting server:", err)
}
}