# ✅ Mobile Login - Root Database Fix

## 🎯 Issue Fixed

**Problem**: Mobile login was trying to authenticate from project database, but user management is now in the **root database** (SaaS model).

**Solution**: Updated mobile login to use the `Login` model from root database, same as web login.

---

## 🔄 How It Works Now

### Old Flow (Wrong):
1. Get project database connection
2. Query `treeusers` table in project DB
3. Authenticate user

### New Flow (Correct):
1. Query `login` table in **root database**
2. Find user by `member_id` (email) + `treelogy_id`
3. Authenticate user with bcrypt
4. Get project DB connection only for tree count
5. Return user data + token

---

## 📋 Database Structure

### Root Database (Main DB)
- **Table**: `login`
- **Key Fields**:
  - `login_id` - User ID
  - `member_id` - Username/Email
  - `password` - Bcrypt hashed
  - `treelogy_id` - Project ID
  - `client_id` - Client ID
  - `status` - 'Y' for active

### Project Database (e.g., treecensus_pune)
- **Table**: `treedetailsentered`
- Used only for:
  - Tree survey data
  - Today's tree count for user

---

## 🚀 Test Login Command

### PowerShell:
```powershell
curl.exe -X POST "http://172.17.46.11:63318/api/mobile/project/1/login" `
  -H "Content-Type: application/x-www-form-urlencoded" `
  -d "email=YOUR_MEMBER_ID&password=YOUR_PASSWORD"
```

### Bash/Git Bash:
```bash
curl -X POST "http://172.17.46.11:63318/api/mobile/project/1/login" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "email=YOUR_MEMBER_ID" \
  -d "password=YOUR_PASSWORD"
```

---

## 📝 How to Create a Test User

### Option 1: Using Web Login API (Recommended)
```bash
# First, create a Super Admin if not exists
curl -X POST "http://172.17.46.11:63318/api/superadmin/init" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Super Admin",
    "member_id": "admin",
    "password": "admin123"
  }'

# Then create a project user
curl -X POST "http://172.17.46.11:63318/api/login" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -d '{
    "treelogy_id": 1,
    "client_id": 1,
    "member_id": "testuser",
    "password": "test123",
    "name": "Test User",
    "mobile_number": "1234567890",
    "fbcode": "TU001"
  }'
```

### Option 2: Direct SQL Insert
```sql
-- Connect to root database
\c your_root_database

-- Create a test user
INSERT INTO login (
  treelogy_id, client_id, member_id, password, name, 
  mobile_number, fbcode, role_id, status, created_at, updated_at
)
VALUES (
  1,  -- treelogy_id (your project ID)
  1,  -- client_id
  'testuser',  -- member_id (this is the "email" for mobile login)
  '$2a$10$YourBcryptHashedPasswordHere',  -- bcrypt hashed password
  'Test User',  -- name
  '1234567890',  -- mobile_number
  'TU001',  -- fbcode
  3,  -- role_id (PROJECT_USER role)
  'Y',  -- status
  NOW(),
  NOW()
);
```

### Generate Bcrypt Hash (Node.js):
```javascript
const bcrypt = require('bcryptjs');
const hash = bcrypt.hashSync('your_password', 10);
console.log(hash);
```

---

## 🔍 Verify User Exists

```sql
-- Check if user exists in root database
SELECT login_id, member_id, name, treelogy_id, status 
FROM login 
WHERE member_id = 'testuser' AND treelogy_id = 1;
```

---

## ✅ Expected Response

### Success:
```json
{
  "tag": "login",
  "success": 1,
  "error": 0,
  "uid": 123,
  "email": "testuser",
  "token": "eyJhbGc...",
  "user": {
    "first_name": "Test User",
    "last_name": "",
    "email": "testuser",
    "mobile_no": "1234567890",
    ...
  },
  "treedetail": 5,
  "totalCountForDay": 5
}
```

### User Not Found:
```json
{
  "tag": "login",
  "success": 2,
  "error": 1,
  "error_msg": "no such user!"
}
```

### Wrong Password:
```json
{
  "tag": "login",
  "success": 3,
  "error": 1,
  "error_msg": "incorrect password!"
}
```

---

## 🐛 Troubleshooting

### Error: "no such user!"
**Check**:
1. User exists in `login` table (root DB)
2. `member_id` matches what you're sending as `email`
3. `treelogy_id` matches the URL parameter
4. `status` = 'Y'

```sql
SELECT * FROM login WHERE member_id = 'YOUR_EMAIL' AND treelogy_id = 1;
```

### Error: "incorrect password!"
**Check**:
1. Password is bcrypt hashed in database
2. You're sending the plain text password (not hashed)
3. Hash was generated correctly

### Error: "Project not found"
**Check**:
1. Project exists in `treelogy` table
2. `treelogy_id` in URL is correct

```sql
SELECT * FROM treelogy WHERE treelogy_id = 1;
```

---

## 📊 Database Schema Reference

### Root DB - login table:
```sql
CREATE TABLE login (
  login_id SERIAL PRIMARY KEY,
  treelogy_id INTEGER REFERENCES treelogy(treelogy_id),
  client_id INTEGER REFERENCES client(id),
  member_id VARCHAR(255),
  password VARCHAR(255),  -- bcrypt hashed
  name VARCHAR(255),
  mobile_number VARCHAR(20),
  fbcode VARCHAR(50),
  role_id INTEGER REFERENCES user_master(id),
  status VARCHAR(1) DEFAULT 'Y',
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);
```

---

## 🎉 Summary

- ✅ Login now uses **root database** (`login` table)
- ✅ Matches web login authentication flow
- ✅ Supports SaaS multi-tenant architecture
- ✅ User management centralized in root DB
- ✅ Project data stays in project-specific databases

---

**Restart your server and test with a valid user from the `login` table!**

