Thanks to visit codestin.com
Credit goes to github.com

Skip to content

TheChaoticor/project231

Repository files navigation

Slack Connect

A full-stack application that enables users to connect their Slack workspace, send messages immediately, and schedule messages for future delivery. Built with React, TypeScript, Node.js, and Express.js.

Features

🔐 Secure Slack Integration

  • OAuth 2.0 Flow: Complete Slack workspace connection with secure token management
  • Token Storage: Encrypted storage of access and refresh tokens in SQLite database
  • Auto Token Refresh: Automatic token renewal for uninterrupted service
  • Connection Status: Real-time connection status monitoring

💬 Message Management

  • Immediate Sending: Send messages directly to any Slack channel
  • Message Scheduling: Schedule messages for specific future dates and times
  • Channel Selection: Browse and select from all available channels
  • Rich Messaging: Support for text messages with full formatting

📅 Scheduled Message Features

  • Visual Dashboard: View all scheduled messages with status indicators
  • Message Categories: Organized by status (Pending, Sent, Cancelled, Failed)
  • Cancellation: Cancel pending messages before they're sent
  • Real-time Updates: Automatic status updates and refresh
  • Error Handling: Detailed error messages for failed sends

🎨 Modern UI/UX

  • Responsive Design: Optimized for desktop and mobile devices
  • Clean Interface: Professional Slack-inspired design language
  • Interactive Elements: Smooth animations and hover effects
  • Status Indicators: Clear visual feedback for all operations
  • Real-time Notifications: Toast notifications for user actions

Technology Stack

Frontend

  • React 18 with TypeScript
  • Tailwind CSS for styling
  • Lucide React for icons
  • Date-fns for date formatting
  • Vite for build tooling

Backend

  • Node.js with Express.js (TypeScript)
  • SQLite3 for data persistence
  • Node-cron for scheduled task processing
  • Axios for HTTP requests
  • CORS enabled for cross-origin requests

Architecture

  • RESTful API design
  • Modular service architecture
  • Database abstraction layer
  • OAuth 2.0 security implementation
  • Scheduled task management system

Setup Instructions

Prerequisites

  • Node.js 18+ installed
  • Slack workspace with admin privileges
  • Git (for cloning the repository)

1. Clone the Repository

git clone <repository-url>
cd slack-connect

2. Install Dependencies

npm install

3. Slack App Configuration

  1. Create a Slack App:

    • Go to Slack API
    • Click "Create New App" → "From scratch"
    • Name your app "Slack Connect" and select your workspace
  2. Configure OAuth & Permissions:

    • Navigate to "OAuth & Permissions" in the sidebar
    • Add the following Bot Token Scopes:
      • channels:read - View basic information about public channels
      • chat:write - Send messages as the app
      • users:read - View people in the workspace
  3. Set Redirect URLs:

    • In "OAuth & Permissions", add this redirect URL:
    • http://localhost:5173/auth/callback
  4. Get Your Credentials:

    • Copy the Client ID from "Basic Information"
    • Copy the Client Secret from "Basic Information"

4. Environment Configuration

  1. Copy Environment File:
cp .env.example .env
  1. Update .env with your Slack credentials:
# Slack OAuth Configuration
SLACK_CLIENT_ID=your_slack_client_id_here
SLACK_CLIENT_SECRET=your_slack_client_secret_here
SLACK_REDIRECT_URI=http://localhost:5173/auth/callback

# Server Configuration
PORT=3001
CLIENT_URL=http://localhost:5173
NODE_ENV=development

5. Create Required Directories

mkdir -p data

6. Start the Application

npm run dev

This will start:

7. Connect Your Workspace

  1. Open http://localhost:5173 in your browser
  2. Click "Connect to Slack"
  3. Authorize the app in the popup window
  4. Start sending and scheduling messages!

Project Structure

slack-connect/
├── server/                    # Backend application
│   ├── index.ts              # Main server entry point
│   ├── database/             # Database layer
│   │   └── index.ts          # SQLite database management
│   ├── services/             # Business logic services
│   │   ├── slack.service.ts  # Slack API integration
│   │   └── scheduler.service.ts # Message scheduling
│   └── routes/               # API routes
│       ├── auth.routes.ts    # Authentication endpoints
│       ├── slack.routes.ts   # Slack operations
│       └── messages.routes.ts # Message management
├── src/                      # Frontend application
│   ├── App.tsx              # Main application component
│   ├── components/          # React components
│   │   ├── SlackConnection.tsx # OAuth connection UI
│   │   ├── MessageComposer.tsx # Message creation form
│   │   └── ScheduledMessages.tsx # Scheduled messages dashboard
│   └── types/               # TypeScript type definitions
├── public/                  # Static files
│   └── auth-callback.html   # OAuth callback handler
├── data/                    # Database files (created at runtime)
└── README.md               # This file

API Documentation

Authentication Endpoints

  • GET /auth/slack - Get Slack OAuth URL
  • POST /auth/slack/callback - Handle OAuth callback
  • GET /auth/status/:teamId - Check connection status

Slack Operations

  • GET /slack/channels/:teamId - Get available channels
  • POST /slack/send-message - Send immediate message
  • GET /slack/user/:teamId - Get user information

Message Management

  • POST /messages/schedule - Schedule a new message
  • GET /messages/scheduled/:teamId - Get scheduled messages
  • POST /messages/cancel/:messageId - Cancel scheduled message

Database Schema

slack_tokens

CREATE TABLE slack_tokens (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  userId TEXT NOT NULL,
  teamId TEXT NOT NULL UNIQUE,
  accessToken TEXT NOT NULL,
  refreshToken TEXT,
  expiresAt INTEGER,
  scope TEXT NOT NULL,
  teamName TEXT NOT NULL,
  createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
  updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP
);

scheduled_messages

CREATE TABLE scheduled_messages (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  userId TEXT NOT NULL,
  teamId TEXT NOT NULL,
  channel TEXT NOT NULL,
  channelName TEXT NOT NULL,
  message TEXT NOT NULL,
  scheduledTime DATETIME NOT NULL,
  status TEXT NOT NULL DEFAULT 'pending',
  createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
  updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP,
  errorMessage TEXT,
  FOREIGN KEY (teamId) REFERENCES slack_tokens (teamId)
);

Architectural Overview

OAuth 2.0 Flow

  1. Authorization Request: User clicks "Connect to Slack" → redirected to Slack OAuth
  2. User Authorization: User grants permissions in Slack
  3. Authorization Code: Slack redirects back with authorization code
  4. Token Exchange: Backend exchanges code for access token
  5. Token Storage: Encrypted storage in SQLite database
  6. Connection Established: User can now send messages

Token Management

  • Secure Storage: Tokens encrypted in SQLite database
  • Automatic Refresh: Background process renews expired tokens
  • Connection Monitoring: Regular health checks ensure valid connections
  • Error Handling: Graceful handling of expired or invalid tokens

Scheduled Task Processing

  • Cron-based Scheduler: Runs every minute to check for pending messages
  • Status Tracking: Real-time status updates (pending → sent/failed/cancelled)
  • Error Recovery: Failed messages are marked with detailed error information
  • Concurrent Processing: Multiple messages processed simultaneously

Security Features

  • Token Encryption: All sensitive data encrypted at rest
  • CORS Protection: Configured for specific origins
  • Input Validation: Comprehensive validation on all endpoints
  • Error Sanitization: Safe error messages without sensitive information

Challenges & Learnings

1. OAuth Integration Complexity

Challenge: Implementing secure Slack OAuth flow with popup windows Solution: Created dedicated callback handler with cross-window communication Learning: OAuth flows require careful state management and error handling

2. Scheduled Message Reliability

Challenge: Ensuring messages are sent reliably at the correct time Solution: Implemented robust cron-based scheduler with status tracking Learning: Background tasks need comprehensive error handling and recovery

3. Token Management Security

Challenge: Securely storing and refreshing OAuth tokens Solution: Database encryption and automatic refresh mechanisms Learning: Token lifecycle management is critical for long-term reliability

4. Real-time UI Updates

Challenge: Keeping UI synchronized with backend state changes Solution: Polling-based updates with optimistic UI updates Learning: Real-time features enhance user experience significantly

5. Cross-Origin Communication

Challenge: OAuth popup communication between windows Solution: PostMessage API for secure cross-window communication Learning: Browser security features require careful consideration

Development Scripts

# Start development servers (both frontend and backend)
npm run dev

# Start backend only
npm run server:dev

# Start frontend only
npm run client:dev

# Build for production
npm run build

# Run linting
npm run lint

Environment Variables

Variable Description Example
SLACK_CLIENT_ID Slack app client ID 1234567890.1234567890
SLACK_CLIENT_SECRET Slack app client secret abcd1234efgh5678ijkl
SLACK_REDIRECT_URI OAuth redirect URI http://localhost:5173/auth/callback
PORT Backend server port 3001
CLIENT_URL Frontend URL for CORS http://localhost:5173
NODE_ENV Environment mode development

Troubleshooting

Common Issues

  1. "Client ID not found" Error

    • Ensure SLACK_CLIENT_ID is correctly set in .env
    • Verify the Client ID in your Slack app settings
  2. OAuth Redirect Mismatch

    • Check that redirect URL in Slack app matches .env setting
    • Ensure no trailing slashes in URLs
  3. Messages Not Sending

    • Verify bot has been added to the target channel
    • Check that required scopes are granted
  4. Database Connection Error

    • Ensure data/ directory exists
    • Check file permissions for database creation
  5. Scheduled Messages Not Processing

    • Verify server is running continuously
    • Check server logs for cron job errors

Debug Mode

Set NODE_ENV=development for detailed error messages and logging.

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published