{"id":34957593,"url":"https://github.com/dharmveer97/location-based-geolocation-auth","last_synced_at":"2026-05-20T12:10:19.596Z","repository":{"id":323189933,"uuid":"1092428503","full_name":"dharmveer97/location-based-geolocation-auth","owner":"dharmveer97","description":"Production-ready authentication system with real-time location tracking. Restrict user access based   on geographical boundaries - perfect for office-only apps, geo-fenced services, and   location-sensitive operations. Built with Next.js 15, PostgreSQL, and JWT.","archived":false,"fork":false,"pushed_at":"2025-11-08T16:02:51.000Z","size":123,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-11-08T18:05:19.668Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","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/dharmveer97.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,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-11-08T16:01:50.000Z","updated_at":"2025-11-08T16:02:54.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/dharmveer97/location-based-geolocation-auth","commit_stats":null,"previous_names":["dharmveer97/location-based-geolocation-auth"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/dharmveer97/location-based-geolocation-auth","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dharmveer97%2Flocation-based-geolocation-auth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dharmveer97%2Flocation-based-geolocation-auth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dharmveer97%2Flocation-based-geolocation-auth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dharmveer97%2Flocation-based-geolocation-auth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dharmveer97","download_url":"https://codeload.github.com/dharmveer97/location-based-geolocation-auth/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dharmveer97%2Flocation-based-geolocation-auth/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28062750,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-12-26T02:00:06.189Z","response_time":55,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"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":[],"created_at":"2025-12-26T22:26:48.250Z","updated_at":"2025-12-26T22:26:48.869Z","avatar_url":"https://github.com/dharmveer97.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Location Auth 🔐\n\nA production-ready, location-based authentication system built with Next.js 15, PostgreSQL, and modern web technologies. Restrict user access based on geographical location - perfect for office-only access, geo-fenced applications, and location-sensitive services.\n\n## Quick Start\n\n### Prerequisites\n\n- Node.js 18+\n- PostgreSQL 12+\n- npm or yarn\n\n### Installation\n\n1. **Clone and install dependencies:**\n\n```bash\ngit clone \u003cyour-repo-url\u003e\ncd location-auth\nnpm install\n```\n\n2. **Set up environment variables:**\n\n```bash\ncp .env.example .env\n```\n\nEdit `.env` and update:\n\n```env\nDATABASE_URL=\"postgresql://username:password@localhost:5432/location_auth?schema=public\"\nJWT_SECRET=\"your-secure-jwt-secret-here\"\n```\n\nGenerate a secure JWT secret:\n\n```bash\nnode -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\"\n```\n\n3. **Create PostgreSQL database:**\n\n```bash\ncreatedb location_auth\n```\n\nOr using psql:\n\n```bash\npsql -U postgres -c \"CREATE DATABASE location_auth;\"\n```\n\n4. **Run database migrations:**\n\n```bash\nnpm run db:migrate\n```\n\n5. **Start the development server:**\n\n```bash\nnpm run dev\n```\n\nVisit [http://localhost:3000](http://localhost:3000)\n\n## Features\n\n### 🔐 Authentication\n- Secure JWT-based authentication\n- Password encryption with bcrypt\n- Session management with automatic expiration\n- Protected routes and API endpoints\n\n### 📍 Location-Based Access\n- Real-time location tracking using browser Geolocation API\n- Automatic validation every 30 seconds\n- Configurable radius (default: 100 meters)\n- Haversine formula for accurate distance calculation\n- Auto-logout when user moves outside allowed area\n\n### 🎨 Modern UI\n- Built with Shadcn UI components\n- Responsive design with Tailwind CSS\n- Toast notifications for user feedback\n- Clean, accessible interface\n\n### 💾 State Management\n- Zustand for global state\n- Persistent storage for user sessions\n- Optimized re-renders\n\n### 🧪 Testing\n- Jest + React Testing Library\n- Unit tests for utilities and components\n- Coverage reports\n- CI-ready test suite\n\n### 🔧 Developer Experience\n- Strict TypeScript configuration\n- ESLint with Next.js best practices\n- Hot reload in development\n- Comprehensive error handling\n\n## Project Structure\n\n```\nlocation-auth/\n├── app/                      # Next.js App Router\n│   ├── api/                  # API routes\n│   │   ├── auth/            # Authentication endpoints\n│   │   │   ├── login/\n│   │   │   ├── logout/\n│   │   │   ├── signup/\n│   │   │   └── verify/\n│   │   └── location/        # Location validation\n│   │       └── validate/\n│   ├── dashboard/           # Protected dashboard page\n│   ├── login/               # Login page\n│   ├── signup/              # Signup page\n│   └── layout.tsx           # Root layout\n├── components/              # React components\n│   └── ui/                  # Shadcn UI components\n├── lib/                     # Utility functions\n│   ├── jwt.ts              # JWT utilities\n│   ├── location.ts         # Location calculations\n│   ├── prisma.ts           # Prisma client\n│   └── utils.ts            # General utilities\n├── store/                   # Zustand stores\n│   └── auth-store.ts       # Authentication state\n├── prisma/                  # Database schema\n│   └── schema.prisma       # Prisma schema\n└── __tests__/              # Test files\n    ├── components/\n    ├── lib/\n    └── store/\n```\n\n## API Endpoints\n\n### Authentication\n\n#### POST `/api/auth/signup`\n\nCreate a new user account.\n\n**Request:**\n\n```json\n{\n  \"email\": \"user@example.com\",\n  \"password\": \"securepassword\",\n  \"name\": \"John Doe\",\n  \"latitude\": 37.7749,\n  \"longitude\": -122.4194\n}\n```\n\n**Response:**\n\n```json\n{\n  \"user\": {\n    \"id\": \"uuid\",\n    \"email\": \"user@example.com\",\n    \"name\": \"John Doe\"\n  },\n  \"token\": \"jwt-token\"\n}\n```\n\n#### POST `/api/auth/login`\n\nAuthenticate and receive a JWT token.\n\n**Request:**\n\n```json\n{\n  \"email\": \"user@example.com\",\n  \"password\": \"securepassword\",\n  \"latitude\": 37.7749,\n  \"longitude\": -122.4194\n}\n```\n\n**Response:**\n\n```json\n{\n  \"user\": {\n    \"id\": \"uuid\",\n    \"email\": \"user@example.com\",\n    \"name\": \"John Doe\",\n    \"allowedLatitude\": 37.7749,\n    \"allowedLongitude\": -122.4194,\n    \"allowedRadius\": 100\n  },\n  \"token\": \"jwt-token\"\n}\n```\n\n#### POST `/api/auth/logout`\n\nInvalidate the current session.\n\n**Headers:**\n\n```\nAuthorization: Bearer \u003ctoken\u003e\n```\n\n#### GET `/api/auth/verify`\n\nVerify token validity and get user info.\n\n**Headers:**\n\n```\nAuthorization: Bearer \u003ctoken\u003e\n```\n\n### Location\n\n#### POST `/api/location/validate`\n\nValidate current location against allowed area.\n\n**Headers:**\n\n```\nAuthorization: Bearer \u003ctoken\u003e\n```\n\n**Request:**\n\n```json\n{\n  \"latitude\": 37.7750,\n  \"longitude\": -122.4195\n}\n```\n\n**Response:**\n\n```json\n{\n  \"isValid\": true,\n  \"message\": \"Location is valid\"\n}\n```\n\n## Database Schema\n\n### User\n\n```prisma\nmodel User {\n  id                String    @id @default(uuid())\n  email             String    @unique\n  name              String\n  password          String\n  allowedLatitude   Float?\n  allowedLongitude  Float?\n  allowedRadius     Float     @default(100)\n  createdAt         DateTime  @default(now())\n  updatedAt         DateTime  @updatedAt\n  sessions          Session[]\n}\n```\n\n### Session\n\n```prisma\nmodel Session {\n  id        String   @id @default(uuid())\n  userId    String\n  user      User     @relation(fields: [userId], references: [id], onDelete: Cascade)\n  token     String   @unique\n  latitude  Float?\n  longitude Float?\n  createdAt DateTime @default(now())\n  expiresAt DateTime\n}\n```\n\n## Scripts\n\n```bash\n# Development\nnpm run dev              # Start dev server\nnpm run build            # Build for production\nnpm run start            # Start production server\n\n# Database\nnpm run db:migrate       # Run migrations\nnpm run db:studio        # Open Prisma Studio\nnpm run db:push          # Push schema to database\n\n# Code Quality\nnpm run lint             # Run ESLint\nnpm run lint:fix         # Fix ESLint issues\nnpm run type-check       # Run TypeScript checks\n\n# Testing\nnpm run test             # Run tests in watch mode\nnpm run test:ci          # Run tests once\nnpm run test:coverage    # Generate coverage report\n```\n\n## Environment Variables\n\n```env\n# Database\nDATABASE_URL=\"postgresql://user:password@localhost:5432/location_auth\"\n\n# JWT Secret (generate with: openssl rand -hex 32)\nJWT_SECRET=\"your-super-secret-jwt-key\"\n\n# Location Settings\nALLOWED_RADIUS=100\n\n# App URL\nNEXT_PUBLIC_APP_URL=\"http://localhost:3000\"\n```\n\n## How It Works\n\n### Signup Flow\n\n1. User provides email, password, and name\n2. Optionally enables location-based authentication\n3. If enabled, browser requests location permission\n4. Current location is saved as the allowed area\n5. Password is hashed with bcrypt\n6. User record is created in database\n7. JWT token is generated and session created\n8. User is redirected to dashboard\n\n### Login Flow\n\n1. User provides email and password\n2. System retrieves location (if required)\n3. Credentials are verified\n4. Location is checked against allowed area\n5. If valid, JWT token is generated\n6. Session is created with location data\n7. User gains access to protected routes\n\n### Location Monitoring\n\n1. Dashboard requests location every 30 seconds\n2. Location is sent to `/api/location/validate`\n3. Server calculates distance from allowed point\n4. If distance exceeds radius, session is invalidated\n5. User is automatically logged out\n6. Toast notification alerts the user\n\n## Security Best Practices\n\n### Implemented\n\n✅ Passwords hashed with bcrypt (10 rounds)\n✅ JWT tokens with 7-day expiration\n✅ HTTPS enforcement (configure in production)\n✅ Environment variable validation\n✅ SQL injection protection (Prisma ORM)\n✅ XSS protection (React escaping)\n✅ Session invalidation on logout\n✅ Strict TypeScript configuration\n\n### Recommended for Production\n\n- [ ] Rate limiting on API routes\n- [ ] CORS configuration\n- [ ] HTTP security headers\n- [ ] Database connection pooling\n- [ ] Error monitoring (Sentry, etc.)\n- [ ] Logging infrastructure\n- [ ] Regular security audits\n\n## Testing\n\nRun the test suite:\n\n```bash\n# Watch mode\nnpm run test\n\n# Single run\nnpm run test:ci\n\n# With coverage\nnpm run test:coverage\n```\n\nTests cover:\n\n- ✅ Location distance calculations\n- ✅ JWT token signing and verification\n- ✅ Auth store state management\n- ✅ UI component rendering and interactions\n\n## Deployment\n\n### Vercel (Recommended)\n\n1. Push code to GitHub\n2. Import project in Vercel\n3. Add environment variables\n4. Deploy\n\n### Other Platforms\n\nWorks on any platform supporting:\n\n- Node.js 18+\n- PostgreSQL database\n- Environment variables\n\nExamples: Railway, Render, Fly.io, AWS, Google Cloud\n\n## Troubleshooting\n\n### \"Prisma Client not initialized\"\n\n```bash\nnpx prisma generate\n```\n\n### \"Cannot connect to database\"\n\n1. Ensure PostgreSQL is running\n2. Check `DATABASE_URL` in `.env`\n3. Verify database exists\n\n### Location not working\n\n1. Use HTTPS (required in production)\n2. Grant browser location permissions\n3. Ensure device has GPS/location services\n\n### Build errors\n\n```bash\nnpm run type-check\nnpm run lint:fix\n```\n\n## Contributing\n\n1. Fork the repository\n2. Create a feature branch\n3. Make your changes\n4. Run tests: `npm run test:ci`\n5. Check types: `npm run type-check`\n6. Submit a pull request\n\n## License\n\nMIT License - feel free to use in your projects!\n\n## Tech Stack\n\n- **Framework:** Next.js 15 (App Router)\n- **Language:** TypeScript (Strict Mode)\n- **Database:** PostgreSQL\n- **ORM:** Prisma\n- **Auth:** JWT + bcrypt\n- **State:** Zustand\n- **UI:** Shadcn UI + Tailwind CSS\n- **Testing:** Jest + React Testing Library\n- **Linting:** ESLint\n\n## Verification\n\nAfter setup, verify everything works:\n\n```bash\nnpm run type-check    # ✓ TypeScript: No errors\nnpm run lint          # ✓ ESLint: No warnings\nnpm run test:ci       # ✓ Tests: 26/26 passing\n```\n\n## Support\n\nFor issues and questions:\n\n- 📝 [Open an issue](https://github.com/your-username/location-auth/issues)\n- 📖 [View documentation](https://github.com/your-username/location-auth/wiki)\n\n---\n\nBuilt with ❤️ using 100% open-source technologies\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdharmveer97%2Flocation-based-geolocation-auth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdharmveer97%2Flocation-based-geolocation-auth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdharmveer97%2Flocation-based-geolocation-auth/lists"}