Phase 1: Communications Module - Complete
Backend infrastructure: - PostgreSQL models (users, channels, messages, DMs, files, artifacts) - JWT authentication with password hashing - Auth API (register, login, logout, get user) - Channels API (create, list, join, leave) - Messages API with @grimlock mention detection - AI responds automatically when @mentioned - Background task processing for AI responses Database: - SQLAlchemy ORM models - Alembic ready for migrations - PostgreSQL + Redis in docker-compose Features working: - User registration and login - Create/join public channels - Send messages in channels - @grimlock triggers AI response with channel context - Real-time ready (WebSocket next) Next: WebSocket for real-time updates, frontend interface
This commit is contained in:
46
backend/core/auth.py
Normal file
46
backend/core/auth.py
Normal file
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
Authentication Utilities
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
import os
|
||||
|
||||
# Security configuration
|
||||
SECRET_KEY = os.getenv("SECRET_KEY", "your-secret-key-change-in-production")
|
||||
ALGORITHM = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 7 days
|
||||
|
||||
# Password hashing
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
"""Verify a password against a hash"""
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
"""Hash a password"""
|
||||
return pwd_context.hash(password)
|
||||
|
||||
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
|
||||
"""Create a JWT access token"""
|
||||
to_encode = data.copy()
|
||||
|
||||
if expires_delta:
|
||||
expire = datetime.utcnow() + expires_delta
|
||||
else:
|
||||
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
|
||||
to_encode.update({"exp": expire})
|
||||
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
||||
return encoded_jwt
|
||||
|
||||
def decode_token(token: str) -> Optional[dict]:
|
||||
"""Decode and verify a JWT token"""
|
||||
try:
|
||||
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||
return payload
|
||||
except JWTError:
|
||||
return None
|
||||
35
backend/core/database.py
Normal file
35
backend/core/database.py
Normal file
@@ -0,0 +1,35 @@
|
||||
"""
|
||||
Database Configuration
|
||||
"""
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy.pool import StaticPool
|
||||
import os
|
||||
|
||||
# Database URL from environment
|
||||
DATABASE_URL = os.getenv(
|
||||
"DATABASE_URL",
|
||||
"postgresql://grimlock:grimlock@localhost:5432/grimlock"
|
||||
)
|
||||
|
||||
# Create engine
|
||||
engine = create_engine(
|
||||
DATABASE_URL,
|
||||
echo=os.getenv("DEBUG", "false").lower() == "true",
|
||||
pool_pre_ping=True,
|
||||
pool_size=10,
|
||||
max_overflow=20
|
||||
)
|
||||
|
||||
# Session factory
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
# Dependency to get DB session
|
||||
def get_db():
|
||||
"""FastAPI dependency for database sessions"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
146
backend/core/models.py
Normal file
146
backend/core/models.py
Normal file
@@ -0,0 +1,146 @@
|
||||
"""
|
||||
Database Models - SQLAlchemy ORM
|
||||
"""
|
||||
|
||||
from sqlalchemy import Column, Integer, String, Text, Boolean, DateTime, ForeignKey, Enum, Table
|
||||
from sqlalchemy.orm import relationship, declarative_base
|
||||
from sqlalchemy.sql import func
|
||||
from datetime import datetime
|
||||
import enum
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
# Association tables for many-to-many relationships
|
||||
channel_members = Table(
|
||||
'channel_members',
|
||||
Base.metadata,
|
||||
Column('channel_id', Integer, ForeignKey('channels.id', ondelete='CASCADE'), primary_key=True),
|
||||
Column('user_id', Integer, ForeignKey('users.id', ondelete='CASCADE'), primary_key=True),
|
||||
Column('joined_at', DateTime, default=func.now())
|
||||
)
|
||||
|
||||
class UserRole(str, enum.Enum):
|
||||
ENGINEER = "engineer"
|
||||
BD = "bd"
|
||||
ADMIN = "admin"
|
||||
EXEC = "exec"
|
||||
|
||||
class ChannelType(str, enum.Enum):
|
||||
PUBLIC = "public"
|
||||
PRIVATE = "private"
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
email = Column(String(255), unique=True, index=True, nullable=False)
|
||||
name = Column(String(255), nullable=False)
|
||||
password_hash = Column(String(255), nullable=False)
|
||||
role = Column(Enum(UserRole), default=UserRole.ENGINEER, nullable=False)
|
||||
is_active = Column(Boolean, default=True, nullable=False)
|
||||
is_online = Column(Boolean, default=False, nullable=False)
|
||||
last_seen = Column(DateTime, default=func.now())
|
||||
created_at = Column(DateTime, default=func.now())
|
||||
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
|
||||
|
||||
# Relationships
|
||||
messages = relationship("Message", back_populates="user", cascade="all, delete-orphan")
|
||||
sent_dms = relationship("DirectMessage", foreign_keys="DirectMessage.sender_id", back_populates="sender")
|
||||
received_dms = relationship("DirectMessage", foreign_keys="DirectMessage.recipient_id", back_populates="recipient")
|
||||
channels = relationship("Channel", secondary=channel_members, back_populates="members")
|
||||
files = relationship("File", back_populates="uploaded_by_user")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<User {self.email}>"
|
||||
|
||||
class Channel(Base):
|
||||
__tablename__ = "channels"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100), unique=True, index=True, nullable=False)
|
||||
description = Column(Text)
|
||||
type = Column(Enum(ChannelType), default=ChannelType.PUBLIC, nullable=False)
|
||||
created_by = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'))
|
||||
created_at = Column(DateTime, default=func.now())
|
||||
|
||||
# Relationships
|
||||
messages = relationship("Message", back_populates="channel", cascade="all, delete-orphan")
|
||||
members = relationship("User", secondary=channel_members, back_populates="channels")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<Channel #{self.name}>"
|
||||
|
||||
class Message(Base):
|
||||
__tablename__ = "messages"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
channel_id = Column(Integer, ForeignKey('channels.id', ondelete='CASCADE'), nullable=False)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), nullable=True) # NULL if AI
|
||||
content = Column(Text, nullable=False)
|
||||
is_ai_message = Column(Boolean, default=False, nullable=False)
|
||||
reply_to_message_id = Column(Integer, ForeignKey('messages.id', ondelete='SET NULL'), nullable=True)
|
||||
created_at = Column(DateTime, default=func.now())
|
||||
edited_at = Column(DateTime, nullable=True)
|
||||
|
||||
# Relationships
|
||||
channel = relationship("Channel", back_populates="messages")
|
||||
user = relationship("User", back_populates="messages")
|
||||
replies = relationship("Message", remote_side=[id], backref="parent_message")
|
||||
artifacts = relationship("Artifact", back_populates="message", cascade="all, delete-orphan")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<Message {self.id} in #{self.channel.name if self.channel else 'Unknown'}>"
|
||||
|
||||
class DirectMessage(Base):
|
||||
__tablename__ = "direct_messages"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
sender_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
|
||||
recipient_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
|
||||
content = Column(Text, nullable=False)
|
||||
is_ai_message = Column(Boolean, default=False, nullable=False)
|
||||
read_at = Column(DateTime, nullable=True)
|
||||
created_at = Column(DateTime, default=func.now())
|
||||
edited_at = Column(DateTime, nullable=True)
|
||||
|
||||
# Relationships
|
||||
sender = relationship("User", foreign_keys=[sender_id], back_populates="sent_dms")
|
||||
recipient = relationship("User", foreign_keys=[recipient_id], back_populates="received_dms")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<DM from {self.sender_id} to {self.recipient_id}>"
|
||||
|
||||
class File(Base):
|
||||
__tablename__ = "files"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
filename = Column(String(255), nullable=False)
|
||||
original_filename = Column(String(255), nullable=False)
|
||||
file_path = Column(String(500), nullable=False)
|
||||
file_size = Column(Integer, nullable=False) # bytes
|
||||
mime_type = Column(String(100), nullable=False)
|
||||
uploaded_by = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'))
|
||||
channel_id = Column(Integer, ForeignKey('channels.id', ondelete='CASCADE'), nullable=True)
|
||||
created_at = Column(DateTime, default=func.now())
|
||||
|
||||
# Relationships
|
||||
uploaded_by_user = relationship("User", back_populates="files")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<File {self.original_filename}>"
|
||||
|
||||
class Artifact(Base):
|
||||
__tablename__ = "artifacts"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
message_id = Column(Integer, ForeignKey('messages.id', ondelete='CASCADE'), nullable=False)
|
||||
filename = Column(String(255), nullable=False)
|
||||
file_path = Column(String(500), nullable=False)
|
||||
file_type = Column(String(50), nullable=False) # pdf, csv, docx, etc.
|
||||
created_at = Column(DateTime, default=func.now())
|
||||
|
||||
# Relationships
|
||||
message = relationship("Message", back_populates="artifacts")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<Artifact {self.filename}>"
|
||||
Reference in New Issue
Block a user