Skip to content

The only tool you need to know what is happening and how to fix it.

progress

ddux6833332786dc
diff --git a/backend/app/controllers/password_reset.controller.go b/backend/app/controllers/password_reset.controller.go
new file mode 100644
index 00000000..6ea4c5d4
--- /dev/null
+++ b/backend/app/controllers/password_reset.controller.go
@@ -0,0 +1,137 @@
+package controllers
+
+import (
+ "backend/app/middleware"
+ "backend/app/models"
+ "backend/app/pgdb"
+ "backend/app/repositories"
+ "backend/app/services"
+ "database/sql"
+ "net/http"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+ traceway "go.tracewayapp.com"
+)
+
+type passwordResetController struct{}
+
+const resetTokenExpiry = 1 * time.Hour
+const resetRateLimitPeriod = 1 * time.Hour
+
+func (c *passwordResetController) ForgotPassword(ctx *gin.Context) {
+ tx := middleware.GetTx(ctx)
+
+ var request models.ForgotPasswordRequest
+ if err := ctx.ShouldBindJSON(&request); err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ return
+ }
+
+ user, err := repositories.UserRepository.FindByEmail(tx, request.Email)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to find user: %w", err))
+ return
+ }
+
+ if user == nil {
+ ctx.JSON(http.StatusOK, gin.H{"message": "If an account exists with this email, a password reset link will be sent to it."})
+ return
+ }
+
+ if user.PasswordResetRequestedAt != nil && time.Since(*user.PasswordResetRequestedAt) < resetRateLimitPeriod {
+ ctx.JSON(http.StatusOK, gin.H{"message": "If an account exists with this email, a password reset link will be sent to it."})
+ return
+ }
+
+ token := uuid.New().String()
+ expiresAt := time.Now().Add(resetTokenExpiry)
+
+ err = repositories.UserRepository.SetPasswordResetToken(tx, user.Id, token, expiresAt)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to set reset token: %w", err))
+ return
+ }
+
+ go services.EmailService.SendPasswordReset(user.Email, token)
+
+ ctx.JSON(http.StatusOK, gin.H{"message": "If an account exists with this email, a password reset link will be sent to it."})
+}
+
+func (c *passwordResetController) ValidateToken(ctx *gin.Context) {
+ token := ctx.Param("token")
+
+ user, err := pgdb.ExecuteTransaction(func(tx *sql.Tx) (*models.User, error) {
+ return repositories.UserRepository.FindByPasswordResetToken(tx, token)
+ })
+
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to validate token: %w", err))
+ return
+ }
+
+ if user == nil {
+ ctx.JSON(http.StatusOK, &models.PasswordResetTokenInfo{Valid: false})
+ return
+ }
+
+ if user.PasswordResetExpiresAt == nil || time.Now().After(*user.PasswordResetExpiresAt) {
+ ctx.JSON(http.StatusOK, &models.PasswordResetTokenInfo{Valid: false})
+ return
+ }
+
+ ctx.JSON(http.StatusOK, &models.PasswordResetTokenInfo{
+ Valid: true,
+ Email: user.Email,
+ })
+}
+
+func (c *passwordResetController) ResetPassword(ctx *gin.Context) {
+ tx := middleware.GetTx(ctx)
+ token := ctx.Param("token")
+
+ var request models.ResetPasswordRequest
+ if err := ctx.ShouldBindJSON(&request); err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ return
+ }
+
+ user, err := repositories.UserRepository.FindByPasswordResetToken(tx, token)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to find user: %w", err))
+ return
+ }
+
+ if user == nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid or expired reset token"})
+ return
+ }
+
+ if user.PasswordResetExpiresAt == nil || time.Now().After(*user.PasswordResetExpiresAt) {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid or expired reset token"})
+ return
+ }
+
+ hashedPassword, err := services.HashPassword(request.Password)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to hash password: %w", err))
+ return
+ }
+
+ err = repositories.UserRepository.UpdatePassword(tx, user.Id, hashedPassword)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to update password: %w", err))
+ return
+ }
+
+ err = repositories.UserRepository.ClearPasswordResetToken(tx, user.Id)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to clear reset token: %w", err))
+ return
+ }
+
+ ctx.JSON(http.StatusOK, gin.H{"message": "Password has been reset successfully"})
+}
+
+var PasswordResetController = passwordResetController{}
diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.go
index 0d13f286..fa2d9160 100644
--- a/backend/app/controllers/routes.go
+++ b/backend/app/controllers/routes.go
@@ -70,6 +70,11 @@ func RegisterControllers(router *gin.RouterGroup) {
router.GET("/has-organizations", middleware.Transactional, AuthController.HasOrganizations)
}
+ // Password reset
+ router.POST("/forgot-password", middleware.Transactional, PasswordResetController.ForgotPassword)
+ router.GET("/password-reset/:token", PasswordResetController.ValidateToken)
+ router.POST("/password-reset/:token", middleware.Transactional, PasswordResetController.ResetPassword)
+
// Organization settings (admin/owner access)
router.GET("/organizations/:organizationId/settings", middleware.UseAppAuth, middleware.RequireAdminAccess, OrganizationController.GetSettings)
router.PUT("/organizations/:organizationId/settings", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, OrganizationController.UpdateSettings)
diff --git a/backend/app/migrations/pg/0012_add_password_reset_fields_to_users.up.sql b/backend/app/migrations/pg/0012_add_password_reset_fields_to_users.up.sql
new file mode 100644
index 00000000..16d3d49d
--- /dev/null
+++ b/backend/app/migrations/pg/0012_add_password_reset_fields_to_users.up.sql
@@ -0,0 +1,4 @@
+ALTER TABLE users
+ADD COLUMN password_reset_token TEXT,
+ADD COLUMN password_reset_expires_at TIMESTAMPTZ,
+ADD COLUMN password_reset_requested_at TIMESTAMPTZ
diff --git a/backend/app/models/auth.model.go b/backend/app/models/auth.model.go
index c88a17df..08cbb4ca 100644
--- a/backend/app/models/auth.model.go
+++ b/backend/app/models/auth.model.go
@@ -35,3 +35,16 @@ type RegisterResponse struct {
Projects []*ProjectWithBackendUrl `json:"projects"`
Organizations []*UserOrganizationResponse `json:"organizations"`
}
+
+type ForgotPasswordRequest struct {
+ Email string `json:"email" binding:"required,email"`
+}
+
+type ResetPasswordRequest struct {
+ Password string `json:"password" binding:"required,min=8"`
+}
+
+type PasswordResetTokenInfo struct {
+ Valid bool `json:"valid"`
+ Email string `json:"email,omitempty"`
+}
diff --git a/backend/app/models/user.model.go b/backend/app/models/user.model.go
index e7666c4e..cd27783f 100644
--- a/backend/app/models/user.model.go
+++ b/backend/app/models/user.model.go
@@ -5,11 +5,14 @@ import (
)
type User struct {
- Id int `json:"id"`
- Email string `json:"email"`
- Name string `json:"name"`
- Password string `json:"-"` // Never serialize
- CreatedAt time.Time `json:"createdAt"`
+ Id int `json:"id"`
+ Email string `json:"email"`
+ Name string `json:"name"`
+ Password string `json:"-"`
+ CreatedAt time.Time `json:"createdAt"`
+ PasswordResetToken *string `json:"-"`
+ PasswordResetExpiresAt *time.Time `json:"-"`
+ PasswordResetRequestedAt *time.Time `json:"-"`
}
type UserResponse struct {
diff --git a/backend/app/repositories/user.repository.go b/backend/app/repositories/user.repository.go
index dbc6b65b..3a00b826 100644
--- a/backend/app/repositories/user.repository.go
+++ b/backend/app/repositories/user.repository.go
@@ -3,6 +3,7 @@ package repositories
import (
"backend/app/models"
"database/sql"
+ "time"
"github.com/tracewayapp/go-lightning/lit"
)
@@ -49,4 +50,43 @@ func (r *userRepository) EmailExists(tx *sql.Tx, email string) (bool, error) {
return user != nil, nil
}
+func (r *userRepository) SetPasswordResetToken(tx *sql.Tx, userId int, token string, expiresAt time.Time) error {
+ now := time.Now()
+ return lit.Update[models.User](
+ tx,
+ &models.User{
+ PasswordResetToken: &token,
+ PasswordResetExpiresAt: &expiresAt,
+ PasswordResetRequestedAt: &now,
+ },
+ "WHERE id = $1",
+ userId,
+ )
+}
+
+func (r *userRepository) ClearPasswordResetToken(tx *sql.Tx, userId int) error {
+ _, err := tx.Exec(
+ "UPDATE users SET password_reset_token = NULL, password_reset_expires_at = NULL, password_reset_requested_at = NULL WHERE id = $1",
+ userId,
+ )
+ return err
+}
+
+func (r *userRepository) FindByPasswordResetToken(tx *sql.Tx, token string) (*models.User, error) {
+ return lit.SelectSingle[models.User](
+ tx,
+ "SELECT id, email, name, password, created_at, password_reset_token, password_reset_expires_at, password_reset_requested_at FROM users WHERE password_reset_token = $1",
+ token,
+ )
+}
+
+func (r *userRepository) UpdatePassword(tx *sql.Tx, userId int, hashedPassword string) error {
+ return lit.Update[models.User](
+ tx,
+ &models.User{Password: hashedPassword},
+ "WHERE id = $1",
+ userId,
+ )
+}
+
var UserRepository = userRepository{}
diff --git a/backend/app/services/email.service.go b/backend/app/services/email.service.go
index db7f05f3..faec687b 100644
--- a/backend/app/services/email.service.go
+++ b/backend/app/services/email.service.go
@@ -92,3 +92,43 @@ The Traceway Team
func (e *emailService) IsEnabled() bool {
return e.enabled
}
+
+func (e *emailService) SendPasswordReset(toEmail string, token string) error {
+ resetUrl := fmt.Sprintf("%s/reset-password?token=%s", e.baseUrl, token)
+
+ subject := "Reset your Traceway password"
+ body := fmt.Sprintf(`Hello,
+
+You requested to reset your password for your Traceway account.
+
+Click the link below to reset your password:
+%s
+
+This link will expire in 1 hour.
+
+If you did not request this password reset, you can safely ignore this email.
+
+Best regards,
+The Traceway Team
+`, resetUrl)
+
+ if !e.enabled {
+ log.Printf("[EMAIL LOG] To: %s\nSubject: %s\nBody:\n%s", toEmail, subject, body)
+ return nil
+ }
+
+ msg := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s",
+ e.from, toEmail, subject, body)
+
+ auth := smtp.PlainAuth("", e.username, e.password, e.host)
+ addr := fmt.Sprintf("%s:%d", e.host, e.port)
+
+ err := smtp.SendMail(addr, auth, e.from, []string{toEmail}, []byte(msg))
+ if err != nil {
+ log.Printf("Failed to send password reset email to %s: %v", toEmail, err)
+ return err
+ }
+
+ log.Printf("Password reset email sent to %s", toEmail)
+ return nil
+}
diff --git a/backend/backend b/backend/backend
index 1a05a389..c9e1bb21 100755
Binary files a/backend/backend and b/backend/backend differ
diff --git a/frontend/src/routes/forgot-password/+page.svelte b/frontend/src/routes/forgot-password/+page.svelte
new file mode 100644
index 00000000..3ceca50f
--- /dev/null
+++ b/frontend/src/routes/forgot-password/+page.svelte
@@ -0,0 +1,98 @@
+<script lang="ts">
+ import { Button } from "$lib/components/ui/button";
+ import { Input } from "$lib/components/ui/input";
+ import { Label } from "$lib/components/ui/label";
+ import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "$lib/components/ui/card";
+ import { Alert, AlertDescription, AlertTitle } from "$lib/components/ui/alert";
+ import { CircleAlert, CircleCheck } from "@lucide/svelte";
+ import { themeState } from '$lib/state/theme.svelte';
+
+ let email = $state('');
+ let error = $state('');
+ let loading = $state(false);
+ let success = $state(false);
+
+ async function handleSubmit() {
+ loading = true;
+ error = '';
+
+ try {
+ const response = await fetch('/api/forgot-password', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({ email })
+ });
+
+ if (!response.ok) {
+ const data = await response.json();
+ throw new Error(data.error || 'Failed to process request');
+ }
+
+ success = true;
+ } catch (e) {
+ error = e instanceof Error ? e.message : 'An unexpected error occurred';
+ } finally {
+ loading = false;
+ }
+ }
+</script>
+
+<div class="flex h-screen w-full items-center justify-center px-4">
+ <Card class="w-[350px]">
+ <CardHeader>
+ <CardTitle class="text-2xl">
+ <div class="flex flex-row items-center justify-center gap-2">
+ {#if themeState.isDark}
+ <img src="/traceway-logo-white.svg" alt="Traceway Logo" class="h-8 w-auto" />
+ {:else}
+ <img src="/traceway-logo.png" alt="Traceway Logo" class="h-8 w-auto" />
+ {/if}
+ </div>
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ {#if success}
+ <Alert class="mb-4 bg-green-50 border-green-200">
+ <CircleCheck class="h-4 w-4 text-green-700" />
+ <AlertTitle class="text-green-800">Check your email</AlertTitle>
+ <AlertDescription class="text-green-700">
+ If an account exists with this email, a password reset link will be sent to it.
+ </AlertDescription>
+ </Alert>
+ {:else}
+ {#if error}
+ <Alert variant="destructive" class="mb-4 bg-red-50 border-red-200">
+ <CircleAlert class="h-4 w-4 text-red-700" />
+ <AlertTitle class="text-red-800">Error</AlertTitle>
+ <AlertDescription class="text-red-700">
+ {error}
+ </AlertDescription>
+ </Alert>
+ {/if}
+ <p class="text-sm text-muted-foreground mb-4">
+ Enter your email address and we'll send you a link to reset your password.
+ </p>
+ <form onsubmit={(e) => { e.preventDefault(); handleSubmit(); }} class="grid w-full items-center gap-4">
+ <div class="flex flex-col space-y-1.5">
+ <Label for="email">Email</Label>
+ <Input id="email" type="email" bind:value={email} placeholder="[email protected]" required />
+ </div>
+ <Button type="submit" disabled={loading} class="w-full">
+ {#if loading}
+ Sending...
+ {:else}
+ Send Reset Link
+ {/if}
+ </Button>
+ </form>
+ {/if}
+ </CardContent>
+ <CardFooter class="flex flex-col justify-center">
+ <p class="text-sm text-muted-foreground">
+ <a href="/login" class="text-primary hover:underline">Back to Login</a>
+ </p>
+ </CardFooter>
+ </Card>
+</div>
diff --git a/frontend/src/routes/login/+page.svelte b/frontend/src/routes/login/+page.svelte
index 7f4c310e..2ebd3468 100644
--- a/frontend/src/routes/login/+page.svelte
+++ b/frontend/src/routes/login/+page.svelte
@@ -109,6 +109,7 @@
<div class="flex flex-col space-y-1.5">
<Label for="password">Password</Label>
<Input id="password" type="password" bind:value={password} placeholder="Password" required />
+ <a href="/forgot-password" class="text-sm text-primary hover:underline self-end">Forgot password?</a>
</div>
<Button type="submit" disabled={loading} class="w-full">
{#if loading}
diff --git a/frontend/src/routes/reset-password/+page.svelte b/frontend/src/routes/reset-password/+page.svelte
new file mode 100644
index 00000000..4ed3f579
--- /dev/null
+++ b/frontend/src/routes/reset-password/+page.svelte
@@ -0,0 +1,167 @@
+<script lang="ts">
+ import { goto } from '$app/navigation';
+ import { page } from '$app/state';
+ import { Button } from "$lib/components/ui/button";
+ import { Input } from "$lib/components/ui/input";
+ import { Label } from "$lib/components/ui/label";
+ import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "$lib/components/ui/card";
+ import { Alert, AlertDescription, AlertTitle } from "$lib/components/ui/alert";
+ import { CircleAlert, CircleCheck, Loader2 } from "@lucide/svelte";
+ import { themeState } from '$lib/state/theme.svelte';
+
+ let password = $state('');
+ let confirmPassword = $state('');
+ let error = $state('');
+ let loading = $state(false);
+ let success = $state(false);
+ let validating = $state(true);
+ let tokenValid = $state(false);
+ let email = $state('');
+
+ const token = $derived(page.url.searchParams.get('token'));
+
+ $effect(() => {
+ if (token) {
+ validateToken(token);
+ } else {
+ validating = false;
+ tokenValid = false;
+ }
+ });
+
+ async function validateToken(token: string) {
+ try {
+ const response = await fetch(`/api/password-reset/${token}`);
+ const data = await response.json();
+
+ if (data.valid) {
+ tokenValid = true;
+ email = data.email;
+ } else {
+ tokenValid = false;
+ }
+ } catch {
+ tokenValid = false;
+ } finally {
+ validating = false;
+ }
+ }
+
+ async function handleSubmit() {
+ if (password !== confirmPassword) {
+ error = 'Passwords do not match';
+ return;
+ }
+
+ if (password.length < 8) {
+ error = 'Password must be at least 8 characters';
+ return;
+ }
+
+ loading = true;
+ error = '';
+
+ try {
+ const response = await fetch(`/api/password-reset/${token}`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({ password })
+ });
+
+ if (!response.ok) {
+ const data = await response.json();
+ throw new Error(data.error || 'Failed to reset password');
+ }
+
+ success = true;
+ setTimeout(() => {
+ goto('/login');
+ }, 2000);
+ } catch (e) {
+ error = e instanceof Error ? e.message : 'An unexpected error occurred';
+ } finally {
+ loading = false;
+ }
+ }
+</script>
+
+<div class="flex h-screen w-full items-center justify-center px-4">
+ <Card class="w-[350px]">
+ <CardHeader>
+ <CardTitle class="text-2xl">
+ <div class="flex flex-row items-center justify-center gap-2">
+ {#if themeState.isDark}
+ <img src="/traceway-logo-white.svg" alt="Traceway Logo" class="h-8 w-auto" />
+ {:else}
+ <img src="/traceway-logo.png" alt="Traceway Logo" class="h-8 w-auto" />
+ {/if}
+ </div>
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ {#if validating}
+ <div class="flex flex-col items-center justify-center py-8">
+ <Loader2 class="h-8 w-8 animate-spin text-muted-foreground" />
+ <p class="mt-4 text-sm text-muted-foreground">Validating reset link...</p>
+ </div>
+ {:else if !tokenValid}
+ <Alert variant="destructive" class="bg-red-50 border-red-200">
+ <CircleAlert class="h-4 w-4 text-red-700" />
+ <AlertTitle class="text-red-800">Invalid Link</AlertTitle>
+ <AlertDescription class="text-red-700">
+ This password reset link is invalid or has expired. Please request a new one.
+ </AlertDescription>
+ </Alert>
+ {:else if success}
+ <Alert class="bg-green-50 border-green-200">
+ <CircleCheck class="h-4 w-4 text-green-700" />
+ <AlertTitle class="text-green-800">Password Reset</AlertTitle>
+ <AlertDescription class="text-green-700">
+ Your password has been reset successfully. Redirecting to login...
+ </AlertDescription>
+ </Alert>
+ {:else}
+ {#if error}
+ <Alert variant="destructive" class="mb-4 bg-red-50 border-red-200">
+ <CircleAlert class="h-4 w-4 text-red-700" />
+ <AlertTitle class="text-red-800">Error</AlertTitle>
+ <AlertDescription class="text-red-700">
+ {error}
+ </AlertDescription>
+ </Alert>
+ {/if}
+ <p class="text-sm text-muted-foreground mb-4">
+ Enter a new password for your account.
+ </p>
+ <form onsubmit={(e) => { e.preventDefault(); handleSubmit(); }} class="grid w-full items-center gap-4">
+ <div class="flex flex-col space-y-1.5">
+ <Label for="email">Email</Label>
+ <Input id="email" type="email" value={email} disabled class="bg-muted" />
+ </div>
+ <div class="flex flex-col space-y-1.5">
+ <Label for="password">New Password</Label>
+ <Input id="password" type="password" bind:value={password} placeholder="New password" required minlength={8} />
+ </div>
+ <div class="flex flex-col space-y-1.5">
+ <Label for="confirmPassword">Confirm Password</Label>
+ <Input id="confirmPassword" type="password" bind:value={confirmPassword} placeholder="Confirm password" required minlength={8} />
+ </div>
+ <Button type="submit" disabled={loading} class="w-full">
+ {#if loading}
+ Resetting...
+ {:else}
+ Reset Password
+ {/if}
+ </Button>
+ </form>
+ {/if}
+ </CardContent>
+ <CardFooter class="flex flex-col justify-center">
+ <p class="text-sm text-muted-foreground">
+ <a href="/login" class="text-primary hover:underline">Back to Login</a>
+ </p>
+ </CardFooter>
+ </Card>
+</div>