{"id":18493457,"url":"https://github.com/aswinbarath/smart-brain-api","last_synced_at":"2026-04-14T10:32:16.935Z","repository":{"id":117712693,"uuid":"346601270","full_name":"AswinBarath/Smart-brain-api","owner":"AswinBarath","description":"The Face Recognition API for Smart-brain react app","archived":false,"fork":false,"pushed_at":"2025-07-05T13:45:32.000Z","size":13500,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-07-05T15:00:35.656Z","etag":null,"topics":["bcrypt-nodejs","expressjs","nodejs","postgresql"],"latest_commit_sha":null,"homepage":"https://smart-brain-api-one.vercel.app","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/AswinBarath.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2021-03-11T06:28:42.000Z","updated_at":"2025-07-05T13:45:35.000Z","dependencies_parsed_at":null,"dependency_job_id":"40a7ac84-008c-432e-b23c-01d0e0c82d84","html_url":"https://github.com/AswinBarath/Smart-brain-api","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/AswinBarath/Smart-brain-api","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AswinBarath%2FSmart-brain-api","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AswinBarath%2FSmart-brain-api/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AswinBarath%2FSmart-brain-api/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AswinBarath%2FSmart-brain-api/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AswinBarath","download_url":"https://codeload.github.com/AswinBarath/Smart-brain-api/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AswinBarath%2FSmart-brain-api/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31793212,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-14T02:24:21.117Z","status":"ssl_error","status_checked_at":"2026-04-14T02:24:20.627Z","response_time":153,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bcrypt-nodejs","expressjs","nodejs","postgresql"],"created_at":"2024-11-06T13:14:32.528Z","updated_at":"2026-04-14T10:32:16.928Z","avatar_url":"https://github.com/AswinBarath.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Smart Brain API\n\n\u003cp\u003e\n\u003cimg src=\"assets/Smart brain React app.png\" alt=\"Smart Brain App Cover design\" width=800px /\u003e\n\u003c/p\u003e\n\nThe Face Recognition API for Smart-brain react app\n\n---\n\n## Table of content\n\n- [Smart Brain API](#smart-brain-api)\n  - [Table of content](#table-of-content)\n  - [Demo](#demo)\n  - [Screenshots](#screenshots)\n    - [Home Page](#home-page)\n    - [User Registeration Page](#user-registeration-page)\n    - [User Login Page](#user-login-page)\n  - [Technologies](#technologies)\n  - [What's unique in this Project](#whats-unique-in-this-project)\n  - [Setup Instructions](#setup-instructions)\n    - [Prerequisites](#prerequisites)\n    - [Local Development](#local-development)\n    - [Database Management](#database-management)\n  - [Deployment to Vercel](#deployment-to-vercel)\n    - [1. Database Setup](#1-database-setup)\n    - [2. Vercel Deployment](#2-vercel-deployment)\n    - [3. Database Migration (Production)](#3-database-migration-production)\n  - [API Endpoints](#api-endpoints)\n  - [Contributors](#contributors)\n  - [Updates Since Postgres to Prisma Migration](#updates-since-postgres-to-prisma-migration)\n- [Smart Brain API](#smart-brain-api-1)\n  - [🚀 Features](#-features)\n  - [📋 Table of Contents](#-table-of-contents)\n  - [🛠 Tech Stack](#-tech-stack)\n  - [🗄 Database Schema](#-database-schema)\n    - [User Model](#user-model)\n    - [Login Model](#login-model)\n  - [🔌 API Endpoints](#-api-endpoints)\n  - [🔧 Environment Variables](#-environment-variables)\n  - [📦 Installation](#-installation)\n  - [🔄 Database Migration History](#-database-migration-history)\n    - [Migration from Knex to Prisma](#migration-from-knex-to-prisma)\n      - [Key Changes Made:](#key-changes-made)\n      - [Migration Files:](#migration-files)\n  - [🆕 Recent Updates \\\u0026 Fixes](#-recent-updates--fixes)\n    - [1. CORS Configuration Fix](#1-cors-configuration-fix)\n    - [2. Registration Logic Fix](#2-registration-logic-fix)\n    - [3. Environment Variable Management](#3-environment-variable-management)\n    - [4. Enhanced Error Logging](#4-enhanced-error-logging)\n    - [5. Database Connection Testing](#5-database-connection-testing)\n  - [🚀 Deployment](#-deployment)\n    - [Vercel Deployment](#vercel-deployment)\n    - [Build Configuration](#build-configuration)\n  - [🧪 Testing](#-testing)\n    - [Local Testing](#local-testing)\n    - [Test Script](#test-script)\n  - [📁 Project Structure](#-project-structure)\n  - [🔒 Security Features](#-security-features)\n  - [🤝 Contributing](#-contributing)\n  - [📝 License](#-license)\n  - [🆘 Troubleshooting](#-troubleshooting)\n    - [Common Issues](#common-issues)\n    - [Debug Endpoints](#debug-endpoints)\n\n---\n\n## Demo\n\n\u003cp\u003e\n  \u003cimg src=\"./assets/Smart brain React app demo-min.gif\" alt=\"Smart Brain App Demo\" width=800px /\u003e\n\u003c/p\u003e\n\n---\n\n## Screenshots\n\n### Home Page\n\n\u003cp\u003e\n\u003cimg src=\"assets/Smart Brain App Home Page.PNG\" alt=\"Smart Brain App Home Page\" width=800px /\u003e\n\u003c/p\u003e\n\n### User Registeration Page\n\n\u003cp\u003e\n\u003cimg src=\"assets/Smart Brain App Register Page.PNG\" alt=\"Smart Brain App Register Page\" width=800px /\u003e\n\u003c/p\u003e\n\n### User Login Page\n\n\u003cp\u003e\n\u003cimg src=\"assets/Smart Brain App Sign In Page.PNG\" alt=\"Smart Brain App Sign In Page\" width=800px /\u003e\n\u003c/p\u003e\n\n\n---\n\n## Technologies\n\n![PostgreSQL](https://img.shields.io/badge/PostgreSQL-316192?style=for-the-badge\u0026logo=postgresql\u0026logoColor=white)\n\u0026nbsp;\n![Prisma](https://img.shields.io/badge/Prisma-3982CE?style=for-the-badge\u0026logo=Prisma\u0026logoColor=white)\n\u0026nbsp;\n![Express JS](https://img.shields.io/badge/Express.js-404D59?style=for-the-badge)\n\u0026nbsp;\n![React JS](https://img.shields.io/badge/React-20232A?style=for-the-badge\u0026logo=react\u0026logoColor=61DAFB)\n\u0026nbsp;\n![Node JS](https://img.shields.io/badge/Node.js-43853D?style=for-the-badge\u0026logo=node.js\u0026logoColor=white)\n\u0026nbsp;\n![Vercel](https://img.shields.io/badge/Vercel-000000?style=for-the-badge\u0026logo=vercel\u0026logoColor=white)\n\u0026nbsp;\n\n---\n\n## What's unique in this Project\n\n- An Image Recognition app which makes an API request to face recognition machine learning model\n- The App has built-in Authentication which takes care of the user login credentials securely through hashing\n- User Ranking is provided each time the Smart Brain Web App service is triggered for facial detection of images\n- The web app employs custom REST API on the backend with Prisma ORM and PostgreSQL for user data and hashed passwords\n\n---\n\n## Setup Instructions\n\n### Prerequisites\n- Node.js (v14 or higher)\n- PostgreSQL database\n- Clarifai API key\n\n### Local Development\n\n1. **Clone the repository**\n   ```bash\n   git clone \u003cyour-repo-url\u003e\n   cd Smart-brain-api\n   ```\n\n2. **Install dependencies**\n   ```bash\n   npm install\n   ```\n\n3. **Set up environment variables**\n   ```bash\n   cp env.example .env\n   ```\n   Edit `.env` with your actual values:\n   - `DATABASE_URL`: Your PostgreSQL connection string\n   - `CLARIFAI_API`: Your Clarifai API key\n\n4. **Set up the database**\n   ```bash\n   # Generate Prisma client\n   npx prisma generate\n   \n   # Push schema to database (for development)\n   npx prisma db push\n   \n   # Or run migrations (for production)\n   npx prisma migrate dev\n   ```\n\n5. **Start the development server**\n   ```bash\n   npm run start:dev\n   ```\n\n### Database Management\n\n- **View database in Prisma Studio:**\n  ```bash\n  npx prisma studio\n  ```\n\n- **Reset database:**\n  ```bash\n  npx prisma migrate reset\n  ```\n\n---\n\n## Deployment to Vercel\n\n### 1. Database Setup\n- Create a PostgreSQL database (recommended: [Neon](https://neon.tech) or [Supabase](https://supabase.com))\n- Get your database connection string\n\n### 2. Vercel Deployment\n1. **Install Vercel CLI**\n   ```bash\n   npm i -g vercel\n   ```\n\n2. **Deploy to Vercel**\n   ```bash\n   vercel\n   ```\n\n3. **Set Environment Variables in Vercel Dashboard**\n   - Go to your project in Vercel dashboard\n   - Navigate to Settings → Environment Variables\n   - Add:\n     - `DATABASE_URL`: Your PostgreSQL connection string\n     - `CLARIFAI_API`: Your Clarifai API key\n\n4. **Deploy with Database**\n   ```bash\n   # Generate Prisma client for production\n   npx prisma generate\n   \n   # Push schema to production database\n   npx prisma db push --accept-data-loss\n   \n   # Deploy\n   vercel --prod\n   ```\n\n### 3. Database Migration (Production)\n```bash\n# Run migrations on production database\nnpx prisma migrate deploy\n```\n\n---\n\n## API Endpoints\n\n- `POST /register` - Register a new user\n- `POST /signin` - Sign in existing user\n- `GET /profile/:id` - Get user profile\n- `PUT /image` - Update user entries count\n- `POST /imageurl` - Process image with Clarifai\n\n---\n\n## Contributors\n\n- T Aswin Barath \u003chttps://github.com/AswinBarath\u003e\n\n---\n\n## Updates Since Postgres to Prisma Migration\n\n# Smart Brain API\n\nA facial recognition web application backend built with Node.js, Express, and Prisma ORM. This API supports user registration, authentication, and image processing using the Clarifai API.\n\n## 🚀 Features\n\n- **User Authentication**: Secure registration and login with bcrypt password hashing\n- **Facial Recognition**: Image processing using Clarifai API\n- **Database Management**: PostgreSQL with Prisma ORM for type-safe database operations\n- **CORS Support**: Configured for cross-origin requests from frontend applications\n- **Production Ready**: Deployed on Vercel with environment variable management\n\n## 📋 Table of Contents\n\n- [Tech Stack](#tech-stack)\n- [Database Schema](#database-schema)\n- [API Endpoints](#api-endpoints)\n- [Environment Variables](#environment-variables)\n- [Installation](#installation)\n- [Database Migration History](#database-migration-history)\n- [Recent Updates \u0026 Fixes](#recent-updates--fixes)\n- [Deployment](#deployment)\n- [Testing](#testing)\n\n## 🛠 Tech Stack\n\n- **Backend**: Node.js, Express.js\n- **Database**: PostgreSQL with Prisma ORM\n- **Authentication**: bcrypt-nodejs\n- **Image Processing**: Clarifai API\n- **Deployment**: Vercel\n- **CORS**: Express CORS middleware\n\n## 🗄 Database Schema\n\n### User Model\n```prisma\nmodel User {\n  id     Int      @id @default(autoincrement())\n  name   String\n  email  String   @unique\n  joined DateTime @default(now())\n  entries Int     @default(0)\n\n  @@map(\"users\")\n}\n```\n\n### Login Model\n```prisma\nmodel Login {\n  id    Int    @id @default(autoincrement())\n  hash  String\n  email String @unique\n\n  @@map(\"login\")\n}\n```\n\n**Security Note**: Passwords are stored as hashed values in the `login` table, not in plain text in the `users` table. This follows security best practices.\n\n## 🔌 API Endpoints\n\n| Method | Endpoint | Description | Request Body |\n|--------|----------|-------------|--------------|\n| GET | `/` | Health check | - |\n| GET | `/test-db` | Database connection test | - |\n| POST | `/register` | User registration | `{email, password, name}` |\n| POST | `/signin` | User authentication | `{email, password}` |\n| GET | `/profile/:id` | Get user profile | - |\n| PUT | `/image` | Update user entries count | `{id}` |\n| POST | `/imageurl` | Process image with Clarifai | `{input}` |\n\n## 🔧 Environment Variables\n\nCreate a `.env` file with the following variables:\n\n```env\n# Database\nDATABASE_URL=\"postgresql://username:password@host:port/database\"\n\n# Clarifai API\nCLARIFAI_API=\"your_clarifai_api_key_here\"\n\n# Server\nPORT=3000\n```\n\n## 📦 Installation\n\n1. **Clone the repository**\n   ```bash\n   git clone \u003crepository-url\u003e\n   cd Smart-brain-api\n   ```\n\n2. **Install dependencies**\n   ```bash\n   npm install\n   ```\n\n3. **Set up environment variables**\n   ```bash\n   cp env.example .env\n   # Edit .env with your actual values\n   ```\n\n4. **Generate Prisma client**\n   ```bash\n   npx prisma generate\n   ```\n\n5. **Run database migrations**\n   ```bash\n   npx prisma migrate deploy\n   ```\n\n6. **Start the server**\n   ```bash\n   npm start\n   ```\n\n## 🔄 Database Migration History\n\n### Migration from Knex to Prisma\n\nThis project was migrated from Knex.js to Prisma ORM for better type safety and developer experience.\n\n#### Key Changes Made:\n\n1. **Schema Definition**: Converted from Knex migrations to Prisma schema\n2. **Database Client**: Replaced Knex with Prisma Client\n3. **Query Syntax**: Updated all database queries to use Prisma syntax\n4. **Type Safety**: Added TypeScript-like type safety with Prisma\n\n#### Migration Files:\n- `prisma/migrations/001_initial/migration.sql` - Initial schema creation\n\n## 🆕 Recent Updates \u0026 Fixes\n\n### 1. CORS Configuration Fix\n**Issue**: Frontend application couldn't connect to backend due to CORS policy restrictions.\n\n**Solution**: Updated CORS configuration in `server.js`:\n```javascript\napp.use(cors({\n  origin: ['https://smart-brain-app-six.vercel.app', 'http://localhost:3000'],\n  credentials: true,\n  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],\n  allowedHeaders: ['Content-Type', 'Authorization']\n}));\n```\n\n### 2. Registration Logic Fix\n**Issue**: Foreign key constraint violation when creating user records.\n\n**Problem**: The original code tried to create `login` record before `user` record, violating the foreign key constraint.\n\n**Solution**: Updated registration order in `controllers/register.js`:\n```javascript\n// Create user first, then login to satisfy FK constraint\nconst result = await prisma.$transaction(async (tx) =\u003e {\n    // 1. Create user record first\n    const user = await tx.user.create({\n        data: { email, name, joined: new Date() }\n    });\n    \n    // 2. Then create login record\n    const login = await tx.login.create({\n        data: { hash, email }\n    });\n    \n    return user;\n});\n```\n\n### 3. Environment Variable Management\n**Issue**: Vercel deployment failed due to missing environment variables.\n\n**Solution**: \n- Removed secret references from `vercel.json`\n- Set up environment variables directly in Vercel dashboard\n- Updated build script to include database migrations\n\n### 4. Enhanced Error Logging\n**Improvement**: Added detailed error logging for better debugging:\n```javascript\nconsole.error('Registration error details:', {\n    message: err.message,\n    code: err.code,\n    meta: err.meta,\n    stack: err.stack\n});\n```\n\n### 5. Database Connection Testing\n**Addition**: Created `/test-db` endpoint for database connectivity testing:\n```javascript\napp.get('/test-db', async (req, res) =\u003e {\n    try {\n        await prisma.$queryRaw`SELECT 1`;\n        res.json({ status: 'Database connection successful' });\n    } catch (error) {\n        res.status(500).json({ \n            status: 'Database connection failed', \n            error: error.message \n        });\n    }\n});\n```\n\n## 🚀 Deployment\n\n### Vercel Deployment\n\n1. **Connect to Git repository**\n2. **Set environment variables** in Vercel dashboard:\n   - `DATABASE_URL`\n   - `CLARIFAI_API`\n3. **Deploy automatically** on git push\n\n### Build Configuration\n```json\n{\n  \"build\": \"prisma generate \u0026\u0026 prisma migrate deploy\",\n  \"postinstall\": \"prisma generate\"\n}\n```\n\n## 🧪 Testing\n\n### Local Testing\n1. Start the server: `npm start`\n2. Test database connection: `GET http://localhost:3000/test-db`\n3. Test registration: Use the provided `test-register.js` script\n\n### Test Script\n```bash\nnode test-register.js\n```\n\n## 📁 Project Structure\n\n```\nSmart-brain-api/\n├── controllers/          # Route handlers\n│   ├── register.js      # User registration\n│   ├── signin.js        # User authentication\n│   ├── profile.js       # User profile management\n│   └── image.js         # Image processing\n├── lib/\n│   └── prisma.js        # Prisma client configuration\n├── prisma/\n│   ├── schema.prisma    # Database schema\n│   └── migrations/      # Database migrations\n├── server.js            # Express server setup\n├── package.json         # Dependencies and scripts\n└── vercel.json          # Vercel deployment config\n```\n\n## 🔒 Security Features\n\n- **Password Hashing**: bcrypt for secure password storage\n- **CORS Protection**: Configured for specific origins\n- **Input Validation**: Server-side validation for all endpoints\n- **Database Constraints**: Foreign key constraints for data integrity\n\n## 🤝 Contributing\n\n1. Fork the repository\n2. Create a feature branch\n3. Make your changes\n4. Test thoroughly\n5. Submit a pull request\n\n## 📝 License\n\nThis project is licensed under the ISC License.\n\n## 🆘 Troubleshooting\n\n### Common Issues\n\n1. **CORS Errors**: Ensure frontend domain is in CORS configuration\n2. **Database Connection**: Check `DATABASE_URL` environment variable\n3. **Registration Failures**: Verify database schema and foreign key constraints\n4. **Migration Issues**: Run `npx prisma migrate deploy` to apply migrations\n\n### Debug Endpoints\n- `GET /test-db` - Test database connectivity\n- Check server logs for detailed error messages\n\n---\n\n**Last Updated**: June 2025\n**Version**: 2.0.0 (PostgreSQL + Prisma Migration)\n\n---\n\n**[⬆ Back to Top](#Smart-Brain-App)**","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faswinbarath%2Fsmart-brain-api","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faswinbarath%2Fsmart-brain-api","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faswinbarath%2Fsmart-brain-api/lists"}