- Add go.mod and go.sum for dependency management - Implement models for List, Field, Item, ItemValue, SyncRequest, SyncResponse, and NotificationEvent - Create notification handling functions including enqueueNotification and ignoreNotificationError - Implement sync functionality to handle data synchronization between client and server - Add web data handling and notification polling endpoints - Include tests for timestamp normalization and sync logic - Embed web assets for serving the frontend application
352 lines
10 KiB
Go
352 lines
10 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
const (
|
|
sessionCookieName = "collabtable_session"
|
|
sessionTTL = 24 * time.Hour
|
|
minPasswordLength = 8
|
|
maxUsernameLength = 64
|
|
)
|
|
|
|
var (
|
|
errAuthRequired = errors.New("Authentication required")
|
|
errSetupComplete = errors.New("Setup has already been completed.")
|
|
errInvalidCredentials = errors.New("Invalid username or password.")
|
|
errUsernameRequired = errors.New("Username is required.")
|
|
errPasswordTooShort = errors.New("Password must be at least 8 characters.")
|
|
errCurrentPasswordBad = errors.New("Current password is incorrect.")
|
|
)
|
|
|
|
type AuthService struct {
|
|
db *DB
|
|
secureCookie bool
|
|
}
|
|
|
|
func newAuthService(db *DB, secureCookie bool) *AuthService {
|
|
return &AuthService{db: db, secureCookie: secureCookie}
|
|
}
|
|
|
|
func normalizeUsername(value string) (string, error) {
|
|
value = strings.TrimSpace(value)
|
|
if value == "" || len([]rune(value)) > maxUsernameLength {
|
|
return "", errUsernameRequired
|
|
}
|
|
return value, nil
|
|
}
|
|
|
|
func validatePassword(value string) error {
|
|
if len([]rune(value)) < minPasswordLength {
|
|
return errPasswordTooShort
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func randomToken() (string, error) {
|
|
buffer := make([]byte, 32)
|
|
if _, err := rand.Read(buffer); err != nil {
|
|
return "", err
|
|
}
|
|
return base64.RawURLEncoding.EncodeToString(buffer), nil
|
|
}
|
|
|
|
func hashToken(token string) string {
|
|
sum := sha256.Sum256([]byte(token))
|
|
return hex.EncodeToString(sum[:])
|
|
}
|
|
|
|
func (a *AuthService) setSessionCookie(w http.ResponseWriter, token string, expiresAt time.Time) {
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: sessionCookieName,
|
|
Value: token,
|
|
Path: "/",
|
|
HttpOnly: true,
|
|
Secure: a.secureCookie,
|
|
SameSite: http.SameSiteLaxMode,
|
|
Expires: expiresAt,
|
|
})
|
|
}
|
|
|
|
func (a *AuthService) clearSessionCookie(w http.ResponseWriter) {
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: sessionCookieName,
|
|
Value: "",
|
|
Path: "/",
|
|
HttpOnly: true,
|
|
Secure: a.secureCookie,
|
|
SameSite: http.SameSiteLaxMode,
|
|
MaxAge: -1,
|
|
})
|
|
}
|
|
|
|
func (a *AuthService) startSession(ctx context.Context, w http.ResponseWriter, userID int64) error {
|
|
token, err := randomToken()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
expiresAt := time.Now().Add(sessionTTL)
|
|
if err := a.db.createSession(ctx, userID, hashToken(token), expiresAt); err != nil {
|
|
return err
|
|
}
|
|
a.setSessionCookie(w, token, expiresAt)
|
|
return nil
|
|
}
|
|
|
|
func (a *AuthService) currentUser(r *http.Request) (*AuthUser, error) {
|
|
cookie, err := r.Cookie(sessionCookieName)
|
|
if err != nil || cookie.Value == "" {
|
|
return nil, nil
|
|
}
|
|
return a.db.getSessionUser(r.Context(), hashToken(cookie.Value))
|
|
}
|
|
|
|
func (a *AuthService) requireSession(next func(http.ResponseWriter, *http.Request, *AuthUser)) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
user, err := a.currentUser(r)
|
|
if err != nil {
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
return
|
|
}
|
|
if user == nil {
|
|
writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error())
|
|
return
|
|
}
|
|
next(w, r, user)
|
|
})
|
|
}
|
|
|
|
func (a *AuthService) requireAPIToken(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
token := extractBearer(r)
|
|
if token == "" {
|
|
writeJSONError(w, http.StatusUnauthorized, "No bearer token provided")
|
|
return
|
|
}
|
|
userID, err := a.db.getAPITokenUserID(r.Context(), hashToken(token))
|
|
if err != nil {
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
return
|
|
}
|
|
if userID == 0 {
|
|
writeJSONError(w, http.StatusUnauthorized, "Invalid API token")
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func extractBearer(r *http.Request) string {
|
|
header := r.Header.Get("Authorization")
|
|
if !strings.HasPrefix(header, "Bearer ") {
|
|
return ""
|
|
}
|
|
return strings.TrimSpace(strings.TrimPrefix(header, "Bearer "))
|
|
}
|
|
|
|
type authStatusResponse struct {
|
|
SetupRequired bool `json:"setupRequired"`
|
|
Authenticated bool `json:"authenticated"`
|
|
Username string `json:"username,omitempty"`
|
|
}
|
|
|
|
type credentialsRequest struct {
|
|
Username string `json:"username"`
|
|
Password string `json:"password"`
|
|
}
|
|
|
|
func (a *AuthService) handleStatus(w http.ResponseWriter, r *http.Request) {
|
|
count, err := a.db.countUsers(r.Context())
|
|
if err != nil {
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
return
|
|
}
|
|
if count == 0 {
|
|
writeJSON(w, http.StatusOK, authStatusResponse{SetupRequired: true})
|
|
return
|
|
}
|
|
|
|
user, err := a.currentUser(r)
|
|
if err != nil {
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
return
|
|
}
|
|
if user == nil {
|
|
writeJSON(w, http.StatusOK, authStatusResponse{})
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username})
|
|
}
|
|
|
|
func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) {
|
|
var request credentialsRequest
|
|
if err := decodeJSON(r, &request); err != nil {
|
|
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
|
return
|
|
}
|
|
|
|
count, err := a.db.countUsers(r.Context())
|
|
if err != nil {
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
return
|
|
}
|
|
if count > 0 {
|
|
writeJSONError(w, http.StatusConflict, errSetupComplete.Error())
|
|
return
|
|
}
|
|
|
|
username, err := normalizeUsername(request.Username)
|
|
if err != nil {
|
|
writeJSONError(w, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
if err := validatePassword(request.Password); err != nil {
|
|
writeJSONError(w, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
return
|
|
}
|
|
user, err := a.db.createUser(r.Context(), username, string(hash))
|
|
if err != nil {
|
|
if errors.Is(err, ErrSingletonUserExists) {
|
|
writeJSONError(w, http.StatusConflict, errSetupComplete.Error())
|
|
return
|
|
}
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
return
|
|
}
|
|
if err := a.startSession(r.Context(), w, user.ID); err != nil {
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username})
|
|
}
|
|
|
|
func (a *AuthService) handleLogin(w http.ResponseWriter, r *http.Request) {
|
|
var request credentialsRequest
|
|
if err := decodeJSON(r, &request); err != nil {
|
|
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
|
return
|
|
}
|
|
|
|
username, err := normalizeUsername(request.Username)
|
|
if err != nil {
|
|
writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error())
|
|
return
|
|
}
|
|
user, err := a.db.getUserByUsername(r.Context(), username)
|
|
if err != nil {
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
return
|
|
}
|
|
if user == nil || bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(request.Password)) != nil {
|
|
writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error())
|
|
return
|
|
}
|
|
if err := a.startSession(r.Context(), w, user.ID); err != nil {
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username})
|
|
}
|
|
|
|
func (a *AuthService) handleLogout(w http.ResponseWriter, r *http.Request, _ *AuthUser) {
|
|
if cookie, err := r.Cookie(sessionCookieName); err == nil && cookie.Value != "" {
|
|
if err := a.db.deleteSession(r.Context(), hashToken(cookie.Value)); err != nil {
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
return
|
|
}
|
|
}
|
|
a.clearSessionCookie(w)
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
type updateCredentialsRequest struct {
|
|
CurrentPassword string `json:"currentPassword"`
|
|
NewUsername *string `json:"newUsername"`
|
|
NewPassword *string `json:"newPassword"`
|
|
}
|
|
|
|
func (a *AuthService) handleUpdateCredentials(w http.ResponseWriter, r *http.Request, user *AuthUser) {
|
|
var request updateCredentialsRequest
|
|
if err := decodeJSON(r, &request); err != nil {
|
|
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
|
return
|
|
}
|
|
if bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(request.CurrentPassword)) != nil {
|
|
writeJSONError(w, http.StatusBadRequest, errCurrentPasswordBad.Error())
|
|
return
|
|
}
|
|
|
|
username := user.Username
|
|
if request.NewUsername != nil {
|
|
username, _ = normalizeUsername(*request.NewUsername)
|
|
if username == "" {
|
|
writeJSONError(w, http.StatusBadRequest, errUsernameRequired.Error())
|
|
return
|
|
}
|
|
}
|
|
|
|
passwordHash := user.PasswordHash
|
|
if request.NewPassword != nil && *request.NewPassword != "" {
|
|
if err := validatePassword(*request.NewPassword); err != nil {
|
|
writeJSONError(w, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(*request.NewPassword), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
return
|
|
}
|
|
passwordHash = string(hash)
|
|
}
|
|
|
|
if err := a.db.updateUserCredentials(r.Context(), user.ID, username, passwordHash); err != nil {
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
return
|
|
}
|
|
if err := a.db.deleteSessionsForUser(r.Context(), user.ID); err != nil {
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
return
|
|
}
|
|
a.clearSessionCookie(w)
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
func (a *AuthService) handleTokenStatus(w http.ResponseWriter, r *http.Request, user *AuthUser) {
|
|
hasToken, err := a.db.hasAPIToken(r.Context(), user.ID)
|
|
if err != nil {
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]bool{"hasToken": hasToken})
|
|
}
|
|
|
|
func (a *AuthService) handleTokenRegenerate(w http.ResponseWriter, r *http.Request, user *AuthUser) {
|
|
token, err := randomToken()
|
|
if err != nil {
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
return
|
|
}
|
|
if err := a.db.regenerateAPIToken(r.Context(), user.ID, hashToken(token)); err != nil {
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]string{"token": token})
|
|
}
|