This commit is contained in:
Christoph Haas 2026-03-21 22:41:23 +01:00
commit f4be03ceba
1826 changed files with 830924 additions and 0 deletions

View file

@ -0,0 +1,160 @@
package handlers
import (
"encoding/json"
"net/http"
"strconv"
"strings"
"github.com/imc-vibe/backend/internal/db"
)
type AliasHandler struct {
db *db.DB
}
func NewAliasHandler(database *db.DB) *AliasHandler {
return &AliasHandler{db: database}
}
type CreateAliasRequest struct {
Source string `json:"source"`
Destination string `json:"destination"`
}
func (h *AliasHandler) List(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
domainName := extractDomainNameFromPath(r.URL.Path)
if domainName == "" {
Error(w, http.StatusBadRequest, "domain name required")
return
}
authCtx := GetAuthContext(r)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
return
}
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
if !canAccess {
Error(w, http.StatusForbidden, "access denied")
return
}
domain, err := h.db.GetDomainByName(domainName)
if err != nil {
Error(w, http.StatusNotFound, "domain not found")
return
}
aliases, err := h.db.GetAliasesByDomain(domain.ID)
if err != nil {
Error(w, http.StatusInternalServerError, "database error")
return
}
Success(w, aliases)
}
func (h *AliasHandler) Create(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
domainName := extractDomainNameFromPath(r.URL.Path)
if domainName == "" {
Error(w, http.StatusBadRequest, "domain name required")
return
}
authCtx := GetAuthContext(r)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
return
}
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
if !canAccess {
Error(w, http.StatusForbidden, "access denied")
return
}
domain, err := h.db.GetDomainByName(domainName)
if err != nil {
Error(w, http.StatusNotFound, "domain not found")
return
}
var req CreateAliasRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
Error(w, http.StatusBadRequest, "invalid request body")
return
}
if req.Source == "" || req.Destination == "" {
Error(w, http.StatusBadRequest, "source and destination required")
return
}
alias, err := h.db.CreateAliasInDomain(req.Source, req.Destination, domain.ID)
if err != nil {
Error(w, http.StatusInternalServerError, "failed to create alias")
return
}
Created(w, alias)
}
func (h *AliasHandler) Delete(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
pathParts := strings.Split(r.URL.Path, "/")
var domainName, idStr string
for i, part := range pathParts {
if part == "domains" && i+1 < len(pathParts) {
domainName = pathParts[i+1]
}
if part == "aliases" && i+1 < len(pathParts) {
idStr = pathParts[i+1]
}
}
if domainName == "" || idStr == "" {
Error(w, http.StatusBadRequest, "invalid path")
return
}
authCtx := GetAuthContext(r)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
return
}
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
if !canAccess {
Error(w, http.StatusForbidden, "access denied")
return
}
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
Error(w, http.StatusBadRequest, "invalid alias id")
return
}
if err := h.db.DeleteAlias(uint(id)); err != nil {
Error(w, http.StatusInternalServerError, "failed to delete alias")
return
}
NoContent(w)
}

View file

@ -0,0 +1,269 @@
package handlers
import (
"encoding/json"
"net/http"
"strings"
"time"
"github.com/imc-vibe/backend/internal/auth"
"github.com/imc-vibe/backend/internal/db"
)
const MaxLoginAttempts = 5
type AuthHandler struct {
db *db.DB
jwtManager *auth.JWTManager
}
func NewAuthHandler(database *db.DB, jwtManager *auth.JWTManager) *AuthHandler {
return &AuthHandler{
db: database,
jwtManager: jwtManager,
}
}
type LoginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
type ChangePasswordRequest struct {
OldPassword string `json:"oldPassword"`
NewPassword string `json:"newPassword"`
}
type ForgotPasswordRequest struct {
Identifier string `json:"identifier"`
}
type UserResponse struct {
ID uint `json:"id"`
Username string `json:"username"`
Role string `json:"role"`
Domains []string `json:"domains"`
}
func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
var req LoginRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
Error(w, http.StatusBadRequest, "invalid request body")
return
}
if req.Username == "" || req.Password == "" {
Error(w, http.StatusBadRequest, "username and password required")
return
}
ip := getClientIP(r)
if isLockedOut(ip, req.Username, h.db) {
Error(w, http.StatusTooManyRequests, "too many failed attempts, try again later")
return
}
user, err := h.db.GetImcUserByUsername(req.Username)
if err != nil || user == nil || !auth.CheckPassword(req.Password, user.PasswordHash) {
recordFailedAttempt(req.Username, ip, h.db)
Error(w, http.StatusUnauthorized, "invalid credentials")
return
}
clearFailedAttempts(req.Username, ip, h.db)
domains, _ := h.db.GetUserAccessibleDomains(user.ID, user.Role == "admin")
domainNames := make([]string, len(domains))
for i, d := range domains {
domainNames[i] = d.Name
}
token, err := h.jwtManager.GenerateToken(user.ID, user.Username, user.Role, 24*time.Hour)
if err != nil {
Error(w, http.StatusInternalServerError, "failed to generate token")
return
}
Success(w, map[string]interface{}{
"token": token,
"user": UserResponse{
ID: user.ID,
Username: user.Username,
Role: user.Role,
Domains: domainNames,
},
})
}
func (h *AuthHandler) Me(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
authCtx := GetAuthContext(r)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "not authenticated")
return
}
user, err := h.db.GetImcUserByID(authCtx.UserID)
if err != nil || user == nil {
Error(w, http.StatusNotFound, "user not found")
return
}
domains, _ := h.db.GetUserAccessibleDomains(user.ID, user.Role == "admin")
domainNames := make([]string, len(domains))
for i, d := range domains {
domainNames[i] = d.Name
}
Success(w, UserResponse{
ID: user.ID,
Username: user.Username,
Role: user.Role,
Domains: domainNames,
})
}
func (h *AuthHandler) ForgotPassword(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
var req ForgotPasswordRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
Error(w, http.StatusBadRequest, "invalid request")
return
}
req.Identifier = strings.TrimSpace(strings.ToLower(req.Identifier))
if req.Identifier == "" {
Error(w, http.StatusBadRequest, "identifier required")
return
}
_, err := h.db.GetImcUserByUsername(req.Identifier)
if err == nil {
Success(w, map[string]string{
"message": "If the account exists, a password reset link will be sent",
})
return
}
Success(w, map[string]string{
"message": "If the account exists, a password reset link will be sent",
})
}
func (h *AuthHandler) ChangePassword(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
authCtx := GetAuthContext(r)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
return
}
var req ChangePasswordRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
Error(w, http.StatusBadRequest, "invalid request")
return
}
if req.OldPassword == "" || req.NewPassword == "" {
Error(w, http.StatusBadRequest, "old and new password required")
return
}
if len(req.NewPassword) < 8 {
Error(w, http.StatusBadRequest, "password must be at least 8 characters")
return
}
user, err := h.db.GetImcUserByID(authCtx.UserID)
if err != nil || user == nil {
Error(w, http.StatusNotFound, "user not found")
return
}
if !auth.CheckPassword(req.OldPassword, user.PasswordHash) {
Error(w, http.StatusUnauthorized, "current password is incorrect")
return
}
newHash, err := auth.HashPassword(req.NewPassword)
if err != nil {
Error(w, http.StatusInternalServerError, "failed to hash password")
return
}
err = h.db.UpdateImcUserPassword(user.ID, newHash)
if err != nil {
Error(w, http.StatusInternalServerError, "failed to update password")
return
}
Success(w, map[string]string{"message": "password updated successfully"})
}
func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) {
Success(w, map[string]string{"message": "logged out"})
}
func isLockedOut(ip, identifier string, database *db.DB) bool {
var count int64
cutoff := time.Now().Add(-15 * time.Minute)
database.Model(&db.ImcLoginAttempt{}).
Where("ip_address = ? AND attempted_at > ? AND successful = false", ip, cutoff).
Count(&count)
if count >= MaxLoginAttempts {
return true
}
database.Model(&db.ImcLoginAttempt{}).
Where("email = ? AND attempted_at > ? AND successful = false", identifier, cutoff).
Count(&count)
return count >= MaxLoginAttempts
}
func recordFailedAttempt(identifier, ip string, database *db.DB) {
database.Create(&db.ImcLoginAttempt{
Email: identifier,
IPAddress: ip,
Successful: false,
})
}
func clearFailedAttempts(identifier, ip string, database *db.DB) {
database.Model(&db.ImcLoginAttempt{}).
Where("email = ? OR ip_address = ?", identifier, ip).
Update("successful", true)
}
func getClientIP(r *http.Request) string {
forwarded := r.Header.Get("X-Forwarded-For")
if forwarded != "" {
return strings.Split(forwarded, ",")[0]
}
if idx := strings.LastIndex(r.RemoteAddr, ":"); idx != -1 {
return r.RemoteAddr[:idx]
}
return r.RemoteAddr
}

View file

@ -0,0 +1,316 @@
package handlers
import (
"encoding/json"
"net/http"
"strings"
"github.com/imc-vibe/backend/internal/db"
)
type DomainHandler struct {
db *db.DB
}
func NewDomainHandler(database *db.DB) *DomainHandler {
return &DomainHandler{db: database}
}
type CreateDomainRequest struct {
Name string `json:"name"`
}
type DomainPermissions struct {
DomainID uint `json:"domainId"`
DomainName string `json:"domainName"`
UserID uint `json:"userId"`
CanManage bool `json:"canManage"`
}
func (h *DomainHandler) List(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
authCtx := GetAuthContext(r)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
return
}
isAdmin := authCtx.IsAdmin()
domains, err := h.db.GetUserAccessibleDomains(authCtx.UserID, isAdmin)
if err != nil {
Error(w, http.StatusInternalServerError, "database error")
return
}
domainStats := make([]db.DomainStats, len(domains))
for i, d := range domains {
var userCount, aliasCount int64
h.db.Model(&db.User{}).Where("domain_id = ?", d.ID).Count(&userCount)
h.db.Model(&db.Alias{}).Where("domain_id = ?", d.ID).Count(&aliasCount)
domainStats[i] = db.DomainStats{
ID: d.ID,
Name: d.Name,
UserCount: userCount,
AliasCount: aliasCount,
}
}
Success(w, domainStats)
}
func (h *DomainHandler) Get(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
domainName := extractDomainName(r.URL.Path)
if domainName == "" {
Error(w, http.StatusBadRequest, "domain name required")
return
}
domain, err := h.db.GetDomainByName(domainName)
if err != nil {
Error(w, http.StatusNotFound, "domain not found")
return
}
authCtx := GetAuthContext(r)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
return
}
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
if !canAccess {
Error(w, http.StatusForbidden, "access denied")
return
}
Success(w, domain)
}
func (h *DomainHandler) Create(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
authCtx := GetAuthContext(r)
if authCtx == nil || !authCtx.IsAdmin() {
Error(w, http.StatusForbidden, "admin access required")
return
}
var req CreateDomainRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
Error(w, http.StatusBadRequest, "invalid request body")
return
}
if req.Name == "" {
Error(w, http.StatusBadRequest, "domain name required")
return
}
existing, err := h.db.GetDomainByName(req.Name)
if err == nil && existing != nil {
Error(w, http.StatusConflict, "domain already exists")
return
}
domain, err := h.db.CreateDomain(req.Name)
if err != nil {
Error(w, http.StatusInternalServerError, "failed to create domain")
return
}
Created(w, domain)
}
func (h *DomainHandler) Delete(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
authCtx := GetAuthContext(r)
if authCtx == nil || !authCtx.IsAdmin() {
Error(w, http.StatusForbidden, "admin access required")
return
}
domainName := extractDomainName(r.URL.Path)
if domainName == "" {
Error(w, http.StatusBadRequest, "domain name required")
return
}
domain, err := h.db.GetDomainByName(domainName)
if err != nil {
Error(w, http.StatusNotFound, "domain not found")
return
}
if err := h.db.DeleteDomain(domain.ID); err != nil {
Error(w, http.StatusInternalServerError, "failed to delete domain")
return
}
NoContent(w)
}
func (h *DomainHandler) GetPermissions(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
authCtx := GetAuthContext(r)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
return
}
if !authCtx.IsAdmin() {
Error(w, http.StatusForbidden, "admin access required")
return
}
domainName := extractDomainName(r.URL.Path)
if domainName == "" {
Error(w, http.StatusBadRequest, "domain name required")
return
}
domain, err := h.db.GetDomainByName(domainName)
if err != nil {
Error(w, http.StatusNotFound, "domain not found")
return
}
users, err := h.db.GetUsersForDomain(domain.ID)
if err != nil {
Error(w, http.StatusInternalServerError, "database error")
return
}
permissions := make([]DomainPermissions, len(users))
for i, u := range users {
permissions[i] = DomainPermissions{
DomainID: domain.ID,
DomainName: domain.Name,
UserID: u.ID,
CanManage: true,
}
}
Success(w, permissions)
}
func (h *DomainHandler) AddPermission(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
authCtx := GetAuthContext(r)
if authCtx == nil || !authCtx.IsAdmin() {
Error(w, http.StatusForbidden, "admin access required")
return
}
domainName := extractDomainName(r.URL.Path)
if domainName == "" {
Error(w, http.StatusBadRequest, "domain name required")
return
}
domain, err := h.db.GetDomainByName(domainName)
if err != nil {
Error(w, http.StatusNotFound, "domain not found")
return
}
var req struct {
UserID uint `json:"userId"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
Error(w, http.StatusBadRequest, "invalid request")
return
}
if err := h.db.AddUserToDomain(req.UserID, domain.ID); err != nil {
Error(w, http.StatusInternalServerError, "failed to add user to domain")
return
}
Success(w, map[string]string{"message": "user added to domain"})
}
func (h *DomainHandler) RemovePermission(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
authCtx := GetAuthContext(r)
if authCtx == nil || !authCtx.IsAdmin() {
Error(w, http.StatusForbidden, "admin access required")
return
}
domainName := extractDomainName(r.URL.Path)
if domainName == "" {
Error(w, http.StatusBadRequest, "domain name required")
return
}
domain, err := h.db.GetDomainByName(domainName)
if err != nil {
Error(w, http.StatusNotFound, "domain not found")
return
}
userID := extractIDFromPath(r.URL.Path)
if err := h.db.RemoveUserFromDomain(userID, domain.ID); err != nil {
Error(w, http.StatusInternalServerError, "failed to remove user from domain")
return
}
NoContent(w)
}
func extractDomainName(path string) string {
parts := strings.Split(strings.TrimPrefix(path, "/api/"), "/")
if len(parts) >= 2 && parts[1] != "" {
return parts[1]
}
return ""
}
func extractIDFromPath(path string) uint {
parts := strings.Split(path, "/")
for i := len(parts) - 1; i >= 0; i-- {
if idStr := parts[i]; idStr != "" {
var id uint
for _, c := range idStr {
if c >= '0' && c <= '9' {
id = id*10 + uint(c-'0')
} else {
break
}
}
if id > 0 {
return id
}
}
}
return 0
}

View file

@ -0,0 +1,38 @@
package handlers
import (
"net/http"
"strconv"
"github.com/imc-vibe/backend/internal/mail"
)
type LogsHandler struct{}
func NewLogsHandler() *LogsHandler {
return &LogsHandler{}
}
func (h *LogsHandler) List(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
hours := 1
if h := r.URL.Query().Get("hours"); h != "" {
if n, err := strconv.Atoi(h); err == nil && n > 0 {
hours = n
}
}
filter := r.URL.Query().Get("filter")
entries, err := mail.GetLogs(hours, filter)
if err != nil {
Error(w, http.StatusInternalServerError, "failed to get logs")
return
}
Success(w, entries)
}

View file

@ -0,0 +1,72 @@
package handlers
import (
"context"
"net/http"
"strings"
"github.com/imc-vibe/backend/internal/auth"
)
type contextKey string
const AuthContextKey contextKey = "auth"
func AuthMiddleware(jwtManager *auth.JWTManager, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
http.Error(w, `{"error":"authorization header required"}`, http.StatusUnauthorized)
return
}
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
http.Error(w, `{"error":"invalid authorization header format"}`, http.StatusUnauthorized)
return
}
claims, err := jwtManager.ValidateToken(parts[1])
if err != nil {
http.Error(w, `{"error":"invalid token"}`, http.StatusUnauthorized)
return
}
authCtx := &auth.Context{
UserID: claims.UserID,
Username: claims.Username,
Role: auth.Role(claims.Role),
}
ctx := context.WithValue(r.Context(), AuthContextKey, authCtx)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func GetAuthContext(r *http.Request) *auth.Context {
if ctx := r.Context().Value(AuthContextKey); ctx != nil {
if authCtx, ok := ctx.(*auth.Context); ok {
return authCtx
}
}
return nil
}
func RequireAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authCtx := GetAuthContext(r)
if authCtx == nil || !authCtx.IsAdmin() {
http.Error(w, `{"error":"admin access required"}`, http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
func extractID(path string) string {
parts := strings.Split(path, "/")
if len(parts) > 0 {
return parts[len(parts)-1]
}
return ""
}

View file

@ -0,0 +1,58 @@
package handlers
import (
"net/http"
"github.com/imc-vibe/backend/internal/mail"
)
type QueueHandler struct{}
func NewQueueHandler() *QueueHandler {
return &QueueHandler{}
}
func (h *QueueHandler) List(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
entries, err := mail.GetQueue()
if err != nil {
Error(w, http.StatusInternalServerError, "failed to get queue")
return
}
Success(w, entries)
}
func (h *QueueHandler) Requeue(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
id := extractID(r.URL.Path)
if err := mail.RequeueMail(id); err != nil {
Error(w, http.StatusInternalServerError, "failed to requeue mail")
return
}
Success(w, map[string]string{"message": "mail requeued"})
}
func (h *QueueHandler) Delete(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
id := extractID(r.URL.Path)
if err := mail.DeleteFromQueue(id); err != nil {
Error(w, http.StatusInternalServerError, "failed to delete from queue")
return
}
NoContent(w)
}

View file

@ -0,0 +1,41 @@
package handlers
import (
"encoding/json"
"net/http"
)
type Response struct {
Data interface{} `json:"data"`
Error string `json:"error,omitempty"`
Meta *Meta `json:"meta,omitempty"`
}
type Meta struct {
Total int `json:"total,omitempty"`
Page int `json:"page,omitempty"`
}
func JSON(w http.ResponseWriter, status int, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(Response{Data: data})
}
func Error(w http.ResponseWriter, status int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(Response{Error: message})
}
func Success(w http.ResponseWriter, data interface{}) {
JSON(w, http.StatusOK, data)
}
func Created(w http.ResponseWriter, data interface{}) {
JSON(w, http.StatusCreated, data)
}
func NoContent(w http.ResponseWriter) {
w.WriteHeader(http.StatusNoContent)
}

View file

@ -0,0 +1,53 @@
package handlers
import (
"net/http"
"github.com/imc-vibe/backend/internal/db"
)
type StatsHandler struct {
db *db.DB
}
func NewStatsHandler(database *db.DB) *StatsHandler {
return &StatsHandler{db: database}
}
type Stats struct {
TotalDomains int `json:"totalDomains"`
TotalUsers int `json:"totalUsers"`
TotalAliases int `json:"totalAliases"`
QueueSize int `json:"queueSize"`
}
func (h *StatsHandler) Get(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
domains, err := h.db.GetAllDomains()
if err != nil {
domains = []db.DomainStats{}
}
users, err := h.db.GetAllUsers()
if err != nil {
users = []db.User{}
}
aliases, err := h.db.GetAllAliases()
if err != nil {
aliases = []db.AliasWithDomain{}
}
stats := Stats{
TotalDomains: len(domains),
TotalUsers: len(users),
TotalAliases: len(aliases),
QueueSize: 0,
}
Success(w, stats)
}

View file

@ -0,0 +1,351 @@
package handlers
import (
"encoding/json"
"net/http"
"strconv"
"strings"
"github.com/imc-vibe/backend/internal/auth"
"github.com/imc-vibe/backend/internal/db"
)
type UserHandler struct {
db *db.DB
}
func NewUserHandler(database *db.DB) *UserHandler {
return &UserHandler{db: database}
}
type CreateUserRequest struct {
Email string `json:"email"`
Password string `json:"password"`
Quota int64 `json:"quota"`
}
type UpdateUserRequest struct {
Password string `json:"password,omitempty"`
Quota int64 `json:"quota,omitempty"`
}
func (h *UserHandler) List(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
domainName := extractDomainNameFromPath(r.URL.Path)
if domainName == "" {
Error(w, http.StatusBadRequest, "domain name required")
return
}
authCtx := GetAuthContext(r)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
return
}
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
if !canAccess {
Error(w, http.StatusForbidden, "access denied")
return
}
domain, err := h.db.GetDomainByName(domainName)
if err != nil {
Error(w, http.StatusNotFound, "domain not found")
return
}
users, err := h.db.GetUsersByDomain(domain.ID)
if err != nil {
Error(w, http.StatusInternalServerError, "database error")
return
}
Success(w, users)
}
func (h *UserHandler) Get(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/domains/"), "/")
if len(parts) < 4 {
Error(w, http.StatusBadRequest, "invalid path")
return
}
domainName := parts[0]
authCtx := GetAuthContext(r)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
return
}
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
if !canAccess {
Error(w, http.StatusForbidden, "access denied")
return
}
idStr := parts[3]
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
Error(w, http.StatusBadRequest, "invalid user id")
return
}
user, err := h.db.GetUserByID(uint(id))
if err != nil {
Error(w, http.StatusNotFound, "user not found")
return
}
Success(w, user)
}
func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
domainName := extractDomainNameFromPath(r.URL.Path)
if domainName == "" {
Error(w, http.StatusBadRequest, "domain name required")
return
}
authCtx := GetAuthContext(r)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
return
}
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
if !canAccess {
Error(w, http.StatusForbidden, "access denied")
return
}
domain, err := h.db.GetDomainByName(domainName)
if err != nil {
Error(w, http.StatusNotFound, "domain not found")
return
}
var req CreateUserRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
Error(w, http.StatusBadRequest, "invalid request body")
return
}
if req.Email == "" || req.Password == "" {
Error(w, http.StatusBadRequest, "email and password required")
return
}
existing, _ := h.db.GetUserByEmail(req.Email)
if existing != nil {
Error(w, http.StatusConflict, "user already exists")
return
}
passwordHash := "{BLF-CRYPT}" + req.Password
user, err := h.db.CreateUserInDomain(req.Email, passwordHash, req.Quota, domain.ID)
if err != nil {
Error(w, http.StatusInternalServerError, "failed to create user")
return
}
Created(w, user)
}
func (h *UserHandler) Update(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPut {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/domains/"), "/")
if len(parts) < 4 {
Error(w, http.StatusBadRequest, "invalid path")
return
}
domainName := parts[0]
authCtx := GetAuthContext(r)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
return
}
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
if !canAccess {
Error(w, http.StatusForbidden, "access denied")
return
}
idStr := parts[3]
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
Error(w, http.StatusBadRequest, "invalid user id")
return
}
user, err := h.db.GetUserByID(uint(id))
if err != nil {
Error(w, http.StatusNotFound, "user not found")
return
}
var req UpdateUserRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
Error(w, http.StatusBadRequest, "invalid request body")
return
}
if req.Password != "" {
passwordHash := "{BLF-CRYPT}" + req.Password
if err := h.db.UpdateUserPassword(user.ID, passwordHash); err != nil {
Error(w, http.StatusInternalServerError, "failed to update password")
return
}
}
if req.Quota >= 0 {
if err := h.db.UpdateUserQuota(user.ID, req.Quota); err != nil {
Error(w, http.StatusInternalServerError, "failed to update quota")
return
}
}
Success(w, map[string]string{"message": "user updated"})
}
func (h *UserHandler) Delete(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/domains/"), "/")
if len(parts) < 4 {
Error(w, http.StatusBadRequest, "invalid path")
return
}
domainName := parts[0]
authCtx := GetAuthContext(r)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
return
}
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
if !canAccess {
Error(w, http.StatusForbidden, "access denied")
return
}
idStr := parts[3]
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
Error(w, http.StatusBadRequest, "invalid user id")
return
}
if err := h.db.DeleteUser(uint(id)); err != nil {
Error(w, http.StatusInternalServerError, "failed to delete user")
return
}
NoContent(w)
}
func (h *UserHandler) ListAll(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
authCtx := GetAuthContext(r)
if authCtx == nil || !authCtx.IsAdmin() {
Error(w, http.StatusForbidden, "admin access required")
return
}
users, err := h.db.GetAllUsers()
if err != nil {
Error(w, http.StatusInternalServerError, "database error")
return
}
Success(w, users)
}
func extractDomainNameFromPath(path string) string {
parts := strings.Split(strings.TrimPrefix(path, "/api/"), "/")
if len(parts) >= 2 && parts[0] == "domains" && parts[1] != "" {
if idx := strings.Index(parts[1], "/"); idx > 0 {
return parts[1][:idx]
}
return parts[1]
}
return ""
}
func requireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if GetAuthContext(r) == nil {
http.Error(w, `{"error":"authentication required"}`, http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func requireAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authCtx := GetAuthContext(r)
if authCtx == nil || !authCtx.IsAdmin() {
http.Error(w, `{"error":"admin access required"}`, http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
func checkDomainAccess(database *db.DB) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authCtx := GetAuthContext(r)
if authCtx == nil {
http.Error(w, `{"error":"authentication required"}`, http.StatusUnauthorized)
return
}
domainName := extractDomainNameFromPath(r.URL.Path)
if domainName == "" {
next.ServeHTTP(w, r)
return
}
canAccess, _ := database.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
if !canAccess {
http.Error(w, `{"error":"access denied"}`, http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
}
var _ = auth.RoleAdmin

View file

@ -0,0 +1,247 @@
package api
import (
"context"
"net/http"
"strings"
"github.com/imc-vibe/backend/internal/api/handlers"
"github.com/imc-vibe/backend/internal/auth"
"github.com/imc-vibe/backend/internal/config"
"github.com/imc-vibe/backend/internal/db"
)
type Router struct {
authHandler *handlers.AuthHandler
domainHandler *handlers.DomainHandler
userHandler *handlers.UserHandler
aliasHandler *handlers.AliasHandler
statsHandler *handlers.StatsHandler
queueHandler *handlers.QueueHandler
logsHandler *handlers.LogsHandler
jwtManager *auth.JWTManager
db *db.DB
}
func New(database *db.DB, cfg *config.Config) *Router {
jwtManager := auth.NewJWTManager(cfg.JWTSecret, "imc-vibe")
return &Router{
authHandler: handlers.NewAuthHandler(database, jwtManager),
domainHandler: handlers.NewDomainHandler(database),
userHandler: handlers.NewUserHandler(database),
aliasHandler: handlers.NewAliasHandler(database),
statsHandler: handlers.NewStatsHandler(database),
queueHandler: handlers.NewQueueHandler(),
logsHandler: handlers.NewLogsHandler(),
jwtManager: jwtManager,
db: database,
}
}
func (r *Router) Handler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
path := req.URL.Path
// Only handle /api/* routes
if !strings.HasPrefix(path, "/api/") {
http.NotFound(w, req)
return
}
// Public routes - no auth required
switch path {
case "/api/auth/login":
r.authHandler.Login(w, req)
return
case "/api/auth/forgot":
r.authHandler.ForgotPassword(w, req)
return
case "/api/auth/logout":
r.authHandler.Logout(w, req)
return
}
// Protected routes - auth required
req = r.validateAuth(req)
if req == nil {
http.Error(w, `{"error":"not authenticated"}`, http.StatusUnauthorized)
return
}
switch {
case path == "/api/auth/me":
r.authHandler.Me(w, req)
case path == "/api/auth/change-password":
r.authHandler.ChangePassword(w, req)
case path == "/api/stats":
r.statsHandler.Get(w, req)
case strings.HasPrefix(path, "/api/domains/"):
if strings.Contains(strings.TrimPrefix(path, "/api/domains/"), "/users") {
r.handleDomainUsers(w, req)
} else if strings.Contains(strings.TrimPrefix(path, "/api/domains/"), "/aliases") {
r.handleDomainAliases(w, req)
} else {
r.handleDomains(w, req)
}
case strings.HasPrefix(path, "/api/domains"):
r.handleDomains(w, req)
case strings.HasPrefix(path, "/api/queue"):
r.handleQueue(w, req)
case path == "/api/logs":
r.logsHandler.List(w, req)
default:
http.NotFound(w, req)
}
})
}
func (r *Router) validateAuth(req *http.Request) *http.Request {
authHeader := req.Header.Get("Authorization")
if authHeader == "" {
return nil
}
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
return nil
}
claims, err := r.jwtManager.ValidateToken(parts[1])
if err != nil {
return nil
}
authCtx := &auth.Context{
UserID: claims.UserID,
Username: claims.Username,
Role: auth.Role(claims.Role),
}
ctx := context.WithValue(req.Context(), handlers.AuthContextKey, authCtx)
return req.WithContext(ctx)
}
func (r *Router) handleDomains(w http.ResponseWriter, req *http.Request) {
switch req.Method {
case http.MethodGet:
if len(req.URL.Path) > len("/api/domains/") {
r.domainHandler.Get(w, req)
} else {
r.domainHandler.List(w, req)
}
case http.MethodPost:
r.domainHandler.Create(w, req)
case http.MethodDelete:
r.domainHandler.Delete(w, req)
default:
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
}
}
func (r *Router) handleDomainUsers(w http.ResponseWriter, req *http.Request) {
path := req.URL.Path
parts := strings.Split(strings.TrimPrefix(path, "/api/domains/"), "/")
if len(parts) < 2 || parts[1] != "users" {
http.NotFound(w, req)
return
}
domainName := parts[0]
var idStr string
if len(parts) >= 3 {
idStr = parts[2]
}
switch req.Method {
case http.MethodGet:
if idStr != "" {
req.URL.Path = "/api/domains/" + domainName + "/users/" + idStr
r.userHandler.Get(w, req)
} else {
req.URL.Path = "/api/domains/" + domainName + "/users"
r.userHandler.List(w, req)
}
case http.MethodPost:
req.URL.Path = "/api/domains/" + domainName + "/users"
r.userHandler.Create(w, req)
case http.MethodPut:
if idStr != "" {
req.URL.Path = "/api/domains/" + domainName + "/users/" + idStr
r.userHandler.Update(w, req)
} else {
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
}
case http.MethodDelete:
if idStr != "" {
req.URL.Path = "/api/domains/" + domainName + "/users/" + idStr
r.userHandler.Delete(w, req)
} else {
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
}
default:
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
}
}
func (r *Router) handleDomainAliases(w http.ResponseWriter, req *http.Request) {
path := req.URL.Path
parts := strings.Split(strings.TrimPrefix(path, "/api/domains/"), "/")
if len(parts) < 2 || parts[1] != "aliases" {
http.NotFound(w, req)
return
}
domainName := parts[0]
var idStr string
if len(parts) >= 3 {
idStr = parts[2]
}
switch req.Method {
case http.MethodGet:
req.URL.Path = "/api/domains/" + domainName + "/aliases"
r.aliasHandler.List(w, req)
case http.MethodPost:
req.URL.Path = "/api/domains/" + domainName + "/aliases"
r.aliasHandler.Create(w, req)
case http.MethodDelete:
if idStr != "" {
req.URL.Path = "/api/domains/" + domainName + "/aliases/" + idStr
r.aliasHandler.Delete(w, req)
} else {
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
}
default:
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
}
}
func (r *Router) handleQueue(w http.ResponseWriter, req *http.Request) {
path := req.URL.Path
id := ""
if len(path) > len("/api/queue/") {
id = path[len("/api/queue/"):]
}
switch req.Method {
case http.MethodGet:
r.queueHandler.List(w, req)
case http.MethodPost:
if id != "" {
req.URL.Path = "/api/queue/" + id
r.queueHandler.Requeue(w, req)
} else {
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
}
case http.MethodDelete:
if id != "" {
req.URL.Path = "/api/queue/" + id
r.queueHandler.Delete(w, req)
} else {
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
}
default:
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
}
}