-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathmain.go
More file actions
81 lines (60 loc) · 1.73 KB
/
main.go
File metadata and controls
81 lines (60 loc) · 1.73 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
package main
import (
"encoding/json"
"fmt"
"log"
"log/slog"
"net/http"
"os"
"github.com/rs/cors"
"github.com/dreamsofcode-io/authly/api/auth"
"github.com/dreamsofcode-io/authly/api/middleware"
)
type AuthResponse struct {
Status string `json:"status"`
Message string `json:"message"`
User *auth.User `json:"user,omitempty"`
}
type ErrorResponse struct {
Error string `json:"error"`
}
type contextKey string
const UserContextKey contextKey = "user"
var logger *slog.Logger
func verifyAuthHandler(w http.ResponseWriter, r *http.Request) {
// Get user from request
user, err := auth.UserFromRequest(r)
if err != nil {
slog.Error("failed to get user", slog.Any("error", err))
// Return 401 Unauthorized with appropriate error message
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
errorMessage := "Authentication failed"
errorResponse := ErrorResponse{
Error: errorMessage,
}
json.NewEncoder(w).Encode(errorResponse)
return
}
response := AuthResponse{
Status: "success",
Message: "Token is valid",
User: &user,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
func main() {
logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
router := http.NewServeMux()
router.HandleFunc("/health", healthHandler)
router.Handle("/api/auth/verify", http.HandlerFunc(verifyAuthHandler))
router.Handle("/api/me", http.HandlerFunc(verifyAuthHandler))
// Enable CORS
handler := cors.AllowAll().Handler(middleware.Logging(logger, router))
port := ":8080"
fmt.Println("Server starting on port", port)
if err := http.ListenAndServe(port, handler); err != nil {
log.Fatal("Server failed to start:", err)
}
}