Compare commits
1
Commits
0d5cc4d21f
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2b6644e0a4 |
+21
-5
@@ -5,26 +5,42 @@ import TemperatureHistory from "@/components/temperature-history"
|
||||
import TemperaturePlot from "@/components/temperature-plot"
|
||||
import RegisterForm from './components/register-form'
|
||||
import { AuthProvider } from './contexts/auth-context'
|
||||
import { useAuth } from './hooks/use-auth'
|
||||
import UserMenu from './components/user-menu'
|
||||
import LoginForm from './components/login-form'
|
||||
|
||||
|
||||
function AppContent() {
|
||||
const { isAuthenticated, isLoading } = useAuth()
|
||||
|
||||
if (isLoading) return <div className="p-6">Loading...</div>
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<ThemeProvider defaultTheme="dark" storageKey="vite-ui-theme">
|
||||
<AuthProvider>
|
||||
<main className="min-h-screen bg-background p-6 w-full">
|
||||
<div>
|
||||
{isAuthenticated ? <UserMenu /> :
|
||||
<div className="flex">
|
||||
<LoginForm />
|
||||
<RegisterForm />
|
||||
</div>
|
||||
}
|
||||
<div className="w-full mx-auto space-y-2">
|
||||
<TemperaturePlot />
|
||||
<div className="grid grid-cols-4 gap-6">
|
||||
<LatestTemperature />
|
||||
<TemperatureHistory />
|
||||
{isAuthenticated && <TemperatureHistory />}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
|
||||
}
|
||||
|
||||
function App() {
|
||||
|
||||
return (
|
||||
<ThemeProvider defaultTheme="dark" storageKey="vite-ui-theme">
|
||||
<AuthProvider>
|
||||
<AppContent />
|
||||
</AuthProvider>
|
||||
</ThemeProvider>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { useState } from "react"
|
||||
import { useAuth } from "@/hooks/use-auth"
|
||||
import { Button } from "./ui/button"
|
||||
|
||||
export default function LoginForm() {
|
||||
const { login, isLoading } = useAuth()
|
||||
const [email, setEmail] = useState("")
|
||||
const [password, setPassword] = useState("")
|
||||
const [formError, setFormError] = useState<string | null>("")
|
||||
|
||||
async function handleSubmit(e: React.SubmitEvent) {
|
||||
e.preventDefault()
|
||||
setFormError(null)
|
||||
try {
|
||||
await login(email, password)
|
||||
}
|
||||
catch (err) {
|
||||
setFormError(err instanceof Error ? err.message : "Login failed")
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="p-4 m-6 flex flex-col gap-3 border rounded-lg bg-card w-80">
|
||||
|
||||
<h2 className="text-lg font-sembibold">Login</h2>
|
||||
{formError && <p className="text-red-500 text-sm">{formError}</p>}
|
||||
<input
|
||||
type="email"
|
||||
placeholder="Email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
className="p-2 border rounded bg-background"
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
placeholder="Password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
className="p-2 border rounded bg-background"
|
||||
/>
|
||||
<Button type="submit" className="w-full">
|
||||
{isLoading ? "Logging in..." : "Login"}
|
||||
</Button>
|
||||
|
||||
</form>
|
||||
)
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ export default function RegisterForm() {
|
||||
const [success, setSuccess] = useState(false)
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||
async function handleSubmit(e: React.SubmitEvent) {
|
||||
e.preventDefault()
|
||||
setError(null)
|
||||
setSuccess(false)
|
||||
@@ -52,7 +52,7 @@ export default function RegisterForm() {
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="p-4 m-6 flex flex-col border rounded-lg bg-card">
|
||||
<form onSubmit={handleSubmit} className="p-4 m-6 flex flex-col gap-3 border rounded-lg bg-card w-80">
|
||||
<h2>Register</h2>
|
||||
{error && <p>{error}</p>}
|
||||
{success && <p>Account created</p>}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { Button } from "./ui/button";
|
||||
|
||||
export default function UserMenu() {
|
||||
const { user, logout } = useAuth()
|
||||
|
||||
return (
|
||||
<div className="p-4 m-6 flex items-center gap-4 border rounded-lg bg-card">
|
||||
<span className="text-sm">{user?.email}</span>
|
||||
<Button onClick={logout} varient="outline" size="sm">
|
||||
Logout
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -35,11 +35,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const res = await fetch("/api/me", {
|
||||
credentials: "include",
|
||||
})
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
// api response will be null if user is not authenticated
|
||||
setUser(data.user)
|
||||
}
|
||||
}
|
||||
catch {
|
||||
setUser(null)
|
||||
}
|
||||
|
||||
@@ -2,9 +2,8 @@ module go-weather
|
||||
|
||||
go 1.25.6
|
||||
|
||||
require github.com/lib/pq v1.11.1
|
||||
|
||||
require (
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
|
||||
golang.org/x/crypto v0.48.0 // indirect
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/lib/pq v1.11.1
|
||||
golang.org/x/crypto v0.48.0
|
||||
)
|
||||
|
||||
+11
-6
@@ -5,6 +5,7 @@ import (
|
||||
"go-weather/middleware"
|
||||
"go-weather/models"
|
||||
"go-weather/services"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
@@ -20,17 +21,20 @@ func NewUserHandler(us *services.UserService, as *services.AuthService) *UserHan
|
||||
|
||||
func (h *UserHandler) Me(w http.ResponseWriter, r *http.Request) {
|
||||
claims := middleware.GetClaims(r)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
if claims == nil {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
json.NewEncoder(w).Encode(map[string]any{"user": nil})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.userService.GetUserByID(claims.UserID)
|
||||
if err != nil {
|
||||
http.Error(w, "user not found", http.StatusNotFound)
|
||||
json.NewEncoder(w).Encode(map[string]any{"user": nil})
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{"user": user})
|
||||
json.NewEncoder(w).Encode(map[string]any{"user": user})
|
||||
}
|
||||
|
||||
func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -51,8 +55,8 @@ func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if len(req.Password) < 8 {
|
||||
http.Error(w, "password must be at least 8 characters", http.StatusBadRequest)
|
||||
if len(req.Password) < 4 {
|
||||
http.Error(w, "password must be at least 4 characters", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -105,6 +109,7 @@ func (h *UserHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
token, err := h.authService.GenerateToken(user.ID, user.Email)
|
||||
if err != nil {
|
||||
slog.Error("failed to generate token", "user_id", user.ID, "error", err)
|
||||
http.Error(w, "failed to generate token", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"go-weather/middleware"
|
||||
"go-weather/services"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
@@ -49,6 +50,11 @@ func startPoller(db *sql.DB, ws *services.WeatherService, defaultCity string, in
|
||||
}
|
||||
func main() {
|
||||
config := config.Load()
|
||||
// Setup logger
|
||||
var handler slog.Handler
|
||||
handler = slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug})
|
||||
slog.SetDefault(slog.New(handler))
|
||||
|
||||
// Connect to DB
|
||||
connStr := fmt.Sprintf(
|
||||
"host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
|
||||
@@ -82,9 +88,7 @@ func main() {
|
||||
http.HandlerFunc(weatherHandler.FetchWeather)),
|
||||
)
|
||||
|
||||
http.Handle("/weather/me", middleware.AuthMiddleware(authService)(
|
||||
http.HandlerFunc(userHandler.Me)),
|
||||
)
|
||||
http.Handle("/me", http.HandlerFunc(userHandler.Me))
|
||||
|
||||
http.HandleFunc("/weather/history", weatherHandler.GetHistory)
|
||||
http.HandleFunc("/health", handlers.Health)
|
||||
|
||||
+1
-1
@@ -31,7 +31,7 @@ func (s *AuthService) GenerateToken(userID int, email string) (string, error) {
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString(s.secretKey)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user