diff --git a/main.go b/main.go index 12196df..7033828 100644 --- a/main.go +++ b/main.go @@ -131,8 +131,8 @@ const sessionMaxAge = 30 * 24 * time.Hour func lookupBySession(service, sid string) (name, ak, sk, bucket string, err error) { var createdAt int64 err = scyllaSession.Query( - `SELECT name, access_key, secret_key, bucket, created_at FROM cosmos.users WHERE service = ? AND session_id = ? ALLOW FILTERING`, - service, sid).Scan(&name, &ak, &sk, &bucket, &createdAt) + `SELECT name, access_key, secret_key, bucket, created_at FROM cosmos.users WHERE session_id = ? ALLOW FILTERING`, + sid).Scan(&name, &ak, &sk, &bucket, &createdAt) if err != nil { return } @@ -204,12 +204,12 @@ func handleSignup(w http.ResponseWriter, r *http.Request, service string) { } var ex string - if scyllaSession.Query(`SELECT email FROM cosmos.users WHERE service = ? AND email = ?`, service, email).Scan(&ex) == nil { + if scyllaSession.Query(`SELECT email FROM cosmos.users WHERE email = ? ALLOW FILTERING`, email).Scan(&ex) == nil { http.Error(w, "Email already registered", http.StatusConflict) return } // Also check username uniqueness - if scyllaSession.Query(`SELECT email FROM cosmos.users WHERE service = ? AND username = ? ALLOW FILTERING`, service, username).Scan(&ex) == nil { + if scyllaSession.Query(`SELECT email FROM cosmos.users WHERE username = ? ALLOW FILTERING`, username).Scan(&ex) == nil { http.Error(w, "Username already taken", http.StatusConflict) return } @@ -251,61 +251,98 @@ func handleLogin(w http.ResponseWriter, r *http.Request, service string) { r.ParseForm() ident := strings.ToLower(strings.TrimSpace(r.FormValue("email"))) password := r.FormValue("password") - - var sessionID, passwordHash string - - // Check if ident is email or username - query := `SELECT session_id, password_hash FROM cosmos.users WHERE service = ? AND email = ?` - if !strings.Contains(ident, "@") { - query = `SELECT session_id, password_hash FROM cosmos.users WHERE service = ? AND username = ? ALLOW FILTERING` + + var sessionID, passwordHash, userEmail, userName string + var err error + + // Query single unified user database by email or username + if strings.Contains(ident, "@") { + err = scyllaSession.Query( + `SELECT session_id, password_hash, email, username FROM cosmos.users WHERE email = ? ALLOW FILTERING`, + ident, + ).Scan(&sessionID, &passwordHash, &userEmail, &userName) + } else { + err = scyllaSession.Query( + `SELECT session_id, password_hash, email, username FROM cosmos.users WHERE username = ? ALLOW FILTERING`, + ident, + ).Scan(&sessionID, &passwordHash, &userEmail, &userName) } - - if err := scyllaSession.Query(query, service, ident).Scan(&sessionID, &passwordHash); err != nil { + + if err != nil || sessionID == "" { + log.Printf("[LOGIN] User not found for '%s': %v", ident, err) http.Redirect(w, r, "/"+service+"/login?error=1", http.StatusFound) return } if bcrypt.CompareHashAndPassword([]byte(passwordHash), []byte(password)) != nil { + log.Printf("[LOGIN] Password mismatch for '%s'", ident) http.Redirect(w, r, "/"+service+"/login?error=1", http.StatusFound) return } - if service == "git" { - var giteaUser string - scyllaSession.Query(`SELECT username FROM cosmos.users WHERE service = ? AND email = ?`, service, ident).Scan(&giteaUser) - if giteaUser == "" { - scyllaSession.Query(`SELECT username FROM cosmos.users WHERE service = ? AND username = ? ALLOW FILTERING`, service, ident).Scan(&giteaUser) - } - if giteaUser == "" { - giteaUser = ident - } - cookies, err := loginGitea(giteaUser, password) - if err == nil { - for _, c := range cookies { - if c.Name == "i_like_gitea" && c.Value != "" { - http.SetCookie(w, &http.Cookie{ - Name: c.Name, - Value: c.Value, - Path: "/source", - MaxAge: 86400 * 7, - HttpOnly: true, - Secure: r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https", - SameSite: http.SameSiteLaxMode, - }) - } + // Set unified SSO session cookies across all Cosmos modules + isSecure := r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" + http.SetCookie(w, &http.Cookie{ + Name: "cosmos_sid", + Value: sessionID, + Path: "/", + MaxAge: 86400 * 30, + HttpOnly: true, + Secure: isSecure, + SameSite: http.SameSiteLaxMode, + }) + http.SetCookie(w, &http.Cookie{ + Name: "oort_session", + Value: sessionID, + Path: "/", + MaxAge: 86400 * 30, + HttpOnly: true, + Secure: isSecure, + SameSite: http.SameSiteLaxMode, + }) + http.SetCookie(w, &http.Cookie{ + Name: "orbit_session", + Value: sessionID, + Path: "/", + MaxAge: 86400 * 30, + HttpOnly: true, + Secure: isSecure, + SameSite: http.SameSiteLaxMode, + }) + + // Also log into Gitea to establish the i_like_gitea session + giteaUser := userName + if giteaUser == "" { + giteaUser = ident + } + if cookies, gErr := loginGitea(giteaUser, password); gErr == nil { + for _, c := range cookies { + if c.Name == "i_like_gitea" && c.Value != "" { + http.SetCookie(w, &http.Cookie{ + Name: c.Name, + Value: c.Value, + Path: "/source", + MaxAge: 86400 * 7, + HttpOnly: true, + Secure: isSecure, + SameSite: http.SameSiteLaxMode, + }) } - http.SetCookie(w, &http.Cookie{ - Name: "cosmos_sid", - Value: sessionID, - Path: "/", - MaxAge: 86400 * 30, - HttpOnly: true, - Secure: r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https", - SameSite: http.SameSiteLaxMode, - }) - http.Redirect(w, r, "/source/", http.StatusFound) - return } - log.Printf("[LOGIN] Gitea login attempt failed for %s: %v", giteaUser, err) + } else { + log.Printf("[LOGIN] Gitea login attempt for %s: %v", giteaUser, gErr) + } + + if service == "git" { + http.Redirect(w, r, "/source/", http.StatusFound) + return + } + if service == "oort" { + http.Redirect(w, r, "/oort/console?sid="+sessionID, http.StatusFound) + return + } + if service == "orbit" { + http.Redirect(w, r, "/orbit", http.StatusFound) + return } http.Redirect(w, r, "/"+service+"/dashboard?sid="+sessionID, http.StatusFound) @@ -351,11 +388,11 @@ func handleVerify(w http.ResponseWriter, r *http.Request, service string) { bucket := "unity-" + strings.ReplaceAll(uuid.New().String(), "-", "")[:8] // Store created_at for future session expiry checks createdAt := time.Now().Unix() - if err = scyllaSession.Query(`INSERT INTO cosmos.users (service, email, name, password_hash, access_key, secret_key, bucket, bucket_display_name, session_id, username, profile_image, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, 'mybucket', ?, ?, ?, ?)`, - service, email, name, passwordHash, accessKey, secretKey, bucket, sessionID, username, profileImage, createdAt).Exec(); err != nil { + if err = scyllaSession.Query(`INSERT INTO cosmos.users (service, email, name, password_hash, access_key, secret_key, bucket, bucket_display_name, session_id, username, profile_image, created_at) VALUES ('git', ?, ?, ?, ?, ?, ?, 'mybucket', ?, ?, ?, ?)`, + email, name, passwordHash, accessKey, secretKey, bucket, sessionID, username, profileImage, createdAt).Exec(); err != nil { // created_at column may not exist yet — fall back without it - if err2 := scyllaSession.Query(`INSERT INTO cosmos.users (service, email, name, password_hash, access_key, secret_key, bucket, bucket_display_name, session_id, username, profile_image) VALUES (?, ?, ?, ?, ?, ?, ?, 'mybucket', ?, ?, ?)`, - service, email, name, passwordHash, accessKey, secretKey, bucket, sessionID, username, profileImage).Exec(); err2 != nil { + if err2 := scyllaSession.Query(`INSERT INTO cosmos.users (service, email, name, password_hash, access_key, secret_key, bucket, bucket_display_name, session_id, username, profile_image) VALUES ('git', ?, ?, ?, ?, ?, ?, 'mybucket', ?, ?, ?)`, + email, name, passwordHash, accessKey, secretKey, bucket, sessionID, username, profileImage).Exec(); err2 != nil { log.Printf("[VERIFY] Insert failed: %v", err2) http.Error(w, "Failed to create account", 500) return @@ -367,13 +404,9 @@ func handleVerify(w http.ResponseWriter, r *http.Request, service string) { pendingPasswords.Delete(service + ":" + token) go func() { - switch service { - case "oort": - provisionMinIO(accessKey, secretKey, bucket) - case "git": - if rawPassword != "" { - provisionGitea(username, email, rawPassword) - } + provisionMinIO(accessKey, secretKey, bucket) + if rawPassword != "" { + provisionGitea(username, email, rawPassword) } }() if r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" { @@ -398,14 +431,24 @@ a{background:#fafafa;color:#000;padding:14px 28px;border-radius:8px;text-decorat func handleLogout(w http.ResponseWriter, r *http.Request, service string) { http.SetCookie(w, &http.Cookie{Name: "cosmos_sid", Value: "", Path: "/", MaxAge: -1}) - if service == "git" { - http.SetCookie(w, &http.Cookie{Name: "i_like_gitea", Value: "", Path: "/source", MaxAge: -1}) - } + http.SetCookie(w, &http.Cookie{Name: "oort_session", Value: "", Path: "/", MaxAge: -1}) + http.SetCookie(w, &http.Cookie{Name: "orbit_session", Value: "", Path: "/", MaxAge: -1}) + http.SetCookie(w, &http.Cookie{Name: "i_like_gitea", Value: "", Path: "/source", MaxAge: -1}) http.Redirect(w, r, "/" + service, http.StatusFound) } func handleDashboard(w http.ResponseWriter, r *http.Request, service string) { sid := r.URL.Query().Get("sid") + if sid == "" { + if c, err := r.Cookie("cosmos_sid"); err == nil { + sid = c.Value + } + } + if sid == "" { + if c, err := r.Cookie("oort_session"); err == nil { + sid = c.Value + } + } if sid == "" { http.Redirect(w, r, "/"+service+"/login", http.StatusFound) return @@ -416,6 +459,10 @@ func handleDashboard(w http.ResponseWriter, r *http.Request, service string) { http.Redirect(w, r, "/"+service+"/login", http.StatusFound) return } + if service == "oort" { + http.Redirect(w, r, "/oort/console?sid="+sid, http.StatusFound) + return + } w.Header().Set("Content-Type", "text/html; charset=utf-8") switch service { case "oort": diff --git a/oortconsole.go b/oortconsole.go index 9e818be..ad5479c 100644 --- a/oortconsole.go +++ b/oortconsole.go @@ -41,10 +41,22 @@ func authS3Console(r *http.Request) (ak, sk, bucket string, ok bool) { sid = cookie.Value } } + if sid == "" { + cookie, err := r.Cookie("oort_session") + if err == nil { + sid = cookie.Value + } + } + if sid == "" { + cookie, err := r.Cookie("orbit_session") + if err == nil { + sid = cookie.Value + } + } if sid == "" { return "", "", "", false } - _, ak, sk, bucket, err := lookupBySession("oort", sid) + _, ak, sk, bucket, err := lookupBySession("", sid) if err != nil || ak == "" { return "", "", "", false } @@ -684,7 +696,7 @@ func handleS3RenameBucket(w http.ResponseWriter, r *http.Request) { if req.OldName == defBucket { // Rename default bucket - scyllaSession.Query(`UPDATE cosmos.users SET bucket_display_name = ? WHERE service = 'oort' AND email = ?`, displayName, ak).Exec() + scyllaSession.Query(`UPDATE cosmos.users SET bucket_display_name = ? WHERE service = 'git' AND email = ?`, displayName, ak).Exec() } else { // Verify ownership in DB var owner string @@ -724,7 +736,7 @@ func handleS3Profile(w http.ResponseWriter, r *http.Request) { return } var name, username, profileImage string - scyllaSession.Query(`SELECT name, username, profile_image FROM cosmos.users WHERE service = 'oort' AND email = ?`, ak).Scan(&name, &username, &profileImage) + scyllaSession.Query(`SELECT name, username, profile_image FROM cosmos.users WHERE service = 'git' AND email = ?`, ak).Scan(&name, &username, &profileImage) jsonOK(w, map[string]any{ "access_key": ak, @@ -824,11 +836,16 @@ func handleS3Password(w http.ResponseWriter, r *http.Request) { // Change in ScyllaDB ONLY. MinIO API token (secret_key) remains unchanged. hash, _ := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost) - err := scyllaSession.Query(`UPDATE cosmos.users SET password_hash = ? WHERE service = 'oort' AND email = ?`, + err := scyllaSession.Query(`UPDATE cosmos.users SET password_hash = ? WHERE service = 'git' AND email = ?`, string(hash), ak).Exec() if err != nil { log.Printf("[S3] password update scylla: %v", err) } + var gUser string + scyllaSession.Query(`SELECT username FROM cosmos.users WHERE service = 'git' AND email = ?`, ak).Scan(&gUser) + if gUser != "" { + syncGiteaPassword(gUser, req.NewPassword) + } jsonOK(w, map[string]bool{"success": true}) } @@ -880,7 +897,7 @@ func handleS3Buckets(w http.ResponseWriter, r *http.Request) { // Always include the default private bucket if defBucket != "" { var defDisp string - scyllaSession.Query(`SELECT bucket_display_name FROM cosmos.users WHERE service='oort' AND email=?`, ak).Scan(&defDisp) + scyllaSession.Query(`SELECT bucket_display_name FROM cosmos.users WHERE service='git' AND email=?`, ak).Scan(&defDisp) if defDisp == "" { defDisp = "mybucket" } @@ -996,7 +1013,7 @@ func handleS3ProfileImage(w http.ResponseWriter, r *http.Request) { return } encoded := "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(bytes) - if err := scyllaSession.Query(`UPDATE cosmos.users SET profile_image = ? WHERE service = 'oort' AND email = ?`, encoded, ak).Exec(); err != nil { + if err := scyllaSession.Query(`UPDATE cosmos.users SET profile_image = ? WHERE service = 'git' AND email = ?`, encoded, ak).Exec(); err != nil { jsonErr(w, "db error", 500) return } @@ -1028,12 +1045,12 @@ func handleS3ProfileUpdate(w http.ResponseWriter, r *http.Request) { } var ex string - if scyllaSession.Query(`SELECT email FROM cosmos.users WHERE service = 'oort' AND username = ? ALLOW FILTERING`, req.Username).Scan(&ex) == nil && ex != ak { + if scyllaSession.Query(`SELECT email FROM cosmos.users WHERE username = ? ALLOW FILTERING`, req.Username).Scan(&ex) == nil && ex != ak { jsonErr(w, "username already taken", 409) return } - if err := scyllaSession.Query(`UPDATE cosmos.users SET name = ?, username = ? WHERE service = 'oort' AND email = ?`, req.Name, req.Username, ak).Exec(); err != nil { + if err := scyllaSession.Query(`UPDATE cosmos.users SET name = ?, username = ? WHERE service = 'git' AND email = ?`, req.Name, req.Username, ak).Exec(); err != nil { jsonErr(w, "db error", 500) return } @@ -1161,7 +1178,7 @@ func handleS3PublicProxy(w http.ResponseWriter, r *http.Request, username, path actualBucket = cached.(string) } else { var email, defBucket string - err := scyllaSession.Query(`SELECT email, bucket FROM cosmos.users WHERE service='oort' AND username=? ALLOW FILTERING`, username).Scan(&email, &defBucket) + err := scyllaSession.Query(`SELECT email, bucket FROM cosmos.users WHERE username=? ALLOW FILTERING`, username).Scan(&email, &defBucket) if err != nil { w.Header().Set("Content-Type", "text/html") w.WriteHeader(404) @@ -1170,7 +1187,7 @@ func handleS3PublicProxy(w http.ResponseWriter, r *http.Request, username, path } var defDisp string - scyllaSession.Query(`SELECT bucket_display_name FROM cosmos.users WHERE service='oort' AND email=?`, email).Scan(&defDisp) + scyllaSession.Query(`SELECT bucket_display_name FROM cosmos.users WHERE service='git' AND email=?`, email).Scan(&defDisp) if defDisp == "" { defDisp = "mybucket" } @@ -1488,7 +1505,7 @@ func handleS3Analytics(w http.ResponseWriter, r *http.Request) { } var disp string if b == defBucket { - scyllaSession.Query(`SELECT bucket_display_name FROM cosmos.users WHERE service='oort' AND email=?`, ak).Scan(&disp) + scyllaSession.Query(`SELECT bucket_display_name FROM cosmos.users WHERE service='git' AND email=?`, ak).Scan(&disp) if disp == "" { disp = "mybucket" } } else { scyllaSession.Query(`SELECT display_name FROM cosmos.buckets WHERE bucket_name = ?`, b).Scan(&disp) diff --git a/oortexpansion.go b/oortexpansion.go index b42341c..afb0a93 100644 --- a/oortexpansion.go +++ b/oortexpansion.go @@ -114,13 +114,13 @@ func getOwnerCredentials(bucketOrEmail string) (ak, sk, email string, err error) } else { err = scyllaSession.Query(`SELECT owner_email FROM cosmos.buckets WHERE bucket_name = ?`, bucketOrEmail).Scan(&email) if err != nil || email == "" { - scyllaSession.Query(`SELECT email FROM cosmos.users WHERE service = 'oort' AND bucket = ? ALLOW FILTERING`, bucketOrEmail).Scan(&email) + scyllaSession.Query(`SELECT email FROM cosmos.users WHERE bucket = ? ALLOW FILTERING`, bucketOrEmail).Scan(&email) } } if email == "" { return "", "", "", fmt.Errorf("owner not found") } - err = scyllaSession.Query(`SELECT access_key, secret_key FROM cosmos.users WHERE service = 'oort' AND email = ?`, email).Scan(&ak, &sk) + err = scyllaSession.Query(`SELECT access_key, secret_key FROM cosmos.users WHERE email = ? ALLOW FILTERING`, email).Scan(&ak, &sk) return ak, sk, email, err } diff --git a/orbitcontroller.go b/orbitcontroller.go index 707db61..e2cdbf3 100644 --- a/orbitcontroller.go +++ b/orbitcontroller.go @@ -126,18 +126,22 @@ func allocateOrbitPort() (int, error) { // getSessionUser extracts the email from the session cookie. func getSessionUser(r *http.Request) (string, error) { - cookie, err := r.Cookie("oort_session") - if err != nil || cookie.Value == "" { - cookie, err = r.Cookie("orbit_session") + var sid string + if c, err := r.Cookie("cosmos_sid"); err == nil && c.Value != "" { + sid = c.Value + } else if c, err := r.Cookie("oort_session"); err == nil && c.Value != "" { + sid = c.Value + } else if c, err := r.Cookie("orbit_session"); err == nil && c.Value != "" { + sid = c.Value } - if err != nil || cookie.Value == "" { + if sid == "" { return "", fmt.Errorf("unauthorized") } var email, name string - err = scyllaSession.Query( + err := scyllaSession.Query( `SELECT email, name FROM cosmos.users WHERE session_id = ? ALLOW FILTERING`, - cookie.Value, + sid, ).Scan(&email, &name) if err != nil || email == "" { return "", fmt.Errorf("invalid session") @@ -816,12 +820,8 @@ func handleOrbitListForgeRepos(w http.ResponseWriter, r *http.Request) { } var giteaUser string - _ = scyllaSession.Query(`SELECT username FROM cosmos.users WHERE service = 'git' AND email = ? ALLOW FILTERING`, email). + _ = scyllaSession.Query(`SELECT username FROM cosmos.users WHERE email = ? ALLOW FILTERING`, email). Scan(&giteaUser) - if giteaUser == "" { - _ = scyllaSession.Query(`SELECT username FROM cosmos.users WHERE service = 'oort' AND email = ? ALLOW FILTERING`, email). - Scan(&giteaUser) - } var repos []map[string]interface{} if giteaUser != "" { @@ -923,16 +923,20 @@ func handleOrbitProxy(w http.ResponseWriter, r *http.Request, path string) { // handleOrbitBackupToOort exports container filesystem snapshot and uploads directly into the user's Oort S3 bucket. func handleOrbitBackupToOort(w http.ResponseWriter, r *http.Request, appID string) { - cookie, err := r.Cookie("oort_session") - if err != nil || cookie.Value == "" { - cookie, err = r.Cookie("orbit_session") + var sid string + if c, err := r.Cookie("cosmos_sid"); err == nil && c.Value != "" { + sid = c.Value + } else if c, err := r.Cookie("oort_session"); err == nil && c.Value != "" { + sid = c.Value + } else if c, err := r.Cookie("orbit_session"); err == nil && c.Value != "" { + sid = c.Value } - if err != nil || cookie.Value == "" { + if sid == "" { http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized) return } - _, ak, sk, defaultBucket, err := lookupBySession("oort", cookie.Value) + _, ak, sk, defaultBucket, err := lookupBySession("", sid) if err != nil || ak == "" { http.Error(w, `{"error":"failed to authenticate S3 storage credentials"}`, http.StatusUnauthorized) return