@waqarcoding/saas-server 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +37 -2
- package/bin/cli.js +79 -0
- package/bin/postinstall.js +46 -0
- package/lib/scaffold.js +117 -0
- package/package.json +44 -3
- package/template/config/db.config.js +28 -0
- package/template/config/env.config.js +41 -0
- package/template/controllers/auth_controller.js +102 -0
- package/template/controllers/item_controller.js +72 -0
- package/template/env.template +14 -0
- package/template/gitignore +2 -0
- package/template/models/user.model.js +45 -0
- package/template/package.template.json +25 -0
- package/template/plugins/realtime.plugin.js +31 -0
- package/template/routes/auth_routes.js +19 -0
- package/template/routes/item_routes.js +21 -0
- package/template/server.js +75 -0
- package/template/services/firebase_auth.service.js +82 -0
- package/template/services/item.service.js +35 -0
- package/template/services/mailer.service.js +117 -0
- package/template/services/notification.service.js +78 -0
- package/template/services/realtime.service.js +28 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Waqar Ahmed
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,38 @@
|
|
|
1
|
-
#
|
|
1
|
+
# saas-server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
It creates Express, MongoDB & Firebase Backend Template Ready.
|
|
4
|
+
|
|
5
|
+
## Usage
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npx saas-server my-backend
|
|
9
|
+
cd my-backend
|
|
10
|
+
# edit .env (MONGO_URI, Firebase, SMTP)
|
|
11
|
+
npm run dev
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Options:
|
|
15
|
+
|
|
16
|
+
- `--no-install` creates the project without running `npm install`
|
|
17
|
+
- `-h`, `--help` shows help
|
|
18
|
+
- `-v`, `--version` shows the version
|
|
19
|
+
|
|
20
|
+
## What you get
|
|
21
|
+
|
|
22
|
+
- Express 5 server (ES modules, class-based controllers, services and routes)
|
|
23
|
+
- MongoDB with Mongoose (`User` model)
|
|
24
|
+
- Firebase Admin: ID token verification middleware and FCM push notifications
|
|
25
|
+
- Nodemailer SMTP mailer: welcome, notification and forgot-password emails
|
|
26
|
+
- Auth routes: `POST /api/auth/login`, `POST /api/auth/forgot-password`, `GET /api/auth/me`
|
|
27
|
+
- Example protected CRUD routes at `/api/items`
|
|
28
|
+
- Health check at `/api/health`
|
|
29
|
+
|
|
30
|
+
## Requirements
|
|
31
|
+
|
|
32
|
+
- Node.js 18 or newer
|
|
33
|
+
- A running MongoDB (local or Atlas)
|
|
34
|
+
- A Firebase service account (project id, client email, private key) in `.env`
|
|
35
|
+
|
|
36
|
+
## License
|
|
37
|
+
|
|
38
|
+
MIT
|
package/bin/cli.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { scaffold } from '../lib/scaffold.js';
|
|
7
|
+
|
|
8
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
const ownPkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8'));
|
|
10
|
+
|
|
11
|
+
const args = process.argv.slice(2);
|
|
12
|
+
const flags = args.filter((a) => a.startsWith('-'));
|
|
13
|
+
const positional = args.filter((a) => !a.startsWith('-'));
|
|
14
|
+
|
|
15
|
+
if (flags.includes('-h') || flags.includes('--help')) {
|
|
16
|
+
console.log(`
|
|
17
|
+
${ownPkg.name} v${ownPkg.version}
|
|
18
|
+
${ownPkg.description}
|
|
19
|
+
|
|
20
|
+
Usage:
|
|
21
|
+
npx saas-server [project-name] [options]
|
|
22
|
+
|
|
23
|
+
Options:
|
|
24
|
+
--no-install Do not run "npm install" after creating the project
|
|
25
|
+
-v, --version Show version
|
|
26
|
+
-h, --help Show this help
|
|
27
|
+
|
|
28
|
+
Example:
|
|
29
|
+
npx saas-server my-backend
|
|
30
|
+
`);
|
|
31
|
+
process.exit(0);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (flags.includes('-v') || flags.includes('--version')) {
|
|
35
|
+
console.log(ownPkg.version);
|
|
36
|
+
process.exit(0);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// ---- Node version check ----
|
|
40
|
+
const major = Number(process.versions.node.split('.')[0]);
|
|
41
|
+
if (major < 18) {
|
|
42
|
+
console.error(`❌ Node.js 18 or newer is required (you have ${process.versions.node}).`);
|
|
43
|
+
process.exit(1);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const targetName = positional[0] || 'server';
|
|
47
|
+
const targetDir = path.resolve(process.cwd(), targetName);
|
|
48
|
+
|
|
49
|
+
if (fs.existsSync(targetDir) && fs.readdirSync(targetDir).length > 0) {
|
|
50
|
+
console.error(`❌ Folder "${targetName}" already exists and is not empty.`);
|
|
51
|
+
process.exit(1);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// ---- Copy template ----
|
|
55
|
+
console.log(`📁 Creating project in ${targetDir} ...`);
|
|
56
|
+
scaffold(targetDir, { name: path.basename(targetDir) });
|
|
57
|
+
|
|
58
|
+
// ---- Install dependencies ----
|
|
59
|
+
const noInstall = flags.includes('--no-install');
|
|
60
|
+
if (!noInstall) {
|
|
61
|
+
console.log('📦 Installing dependencies (this can take a minute) ...');
|
|
62
|
+
const result = spawnSync('npm', ['install'], {
|
|
63
|
+
cwd: targetDir,
|
|
64
|
+
stdio: 'inherit',
|
|
65
|
+
shell: process.platform === 'win32',
|
|
66
|
+
});
|
|
67
|
+
if (result.status !== 0) {
|
|
68
|
+
console.error('⚠️ npm install failed. Run it manually inside the project folder.');
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
console.log(`
|
|
73
|
+
🍺 Express + MongoDB + Firebase backend created!
|
|
74
|
+
|
|
75
|
+
Next steps:
|
|
76
|
+
cd ${targetName}
|
|
77
|
+
${noInstall ? 'npm install\n ' : ''}# edit .env: MONGO_URI, Firebase and SMTP values
|
|
78
|
+
npm run dev
|
|
79
|
+
`);
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Runs after "npm install saas-server" and copies the backend code
|
|
3
|
+
// into the folder where the command was typed (the project root).
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { scaffold } from '../lib/scaffold.js';
|
|
8
|
+
|
|
9
|
+
function real(p) {
|
|
10
|
+
try {
|
|
11
|
+
return fs.realpathSync(p);
|
|
12
|
+
} catch {
|
|
13
|
+
return path.resolve(p);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
try {
|
|
18
|
+
const pkgRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
19
|
+
const ownPkg = JSON.parse(fs.readFileSync(path.join(pkgRoot, 'package.json'), 'utf8'));
|
|
20
|
+
const initCwd = process.env.INIT_CWD;
|
|
21
|
+
|
|
22
|
+
// Skip: global installs, opt-out, or no project folder known
|
|
23
|
+
if (!initCwd || process.env.npm_config_global === 'true' || process.env.SAAS_SERVER_SKIP === '1') {
|
|
24
|
+
process.exit(0);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Only run when installed directly into <project>/node_modules/saas-server.
|
|
28
|
+
// This skips npx, transitive installs and installing inside this package itself.
|
|
29
|
+
const expected = path.join(initCwd, 'node_modules', ...ownPkg.name.split('/'));
|
|
30
|
+
if (real(pkgRoot) !== real(expected)) process.exit(0);
|
|
31
|
+
|
|
32
|
+
// Already scaffolded (re-install or deployment): do nothing
|
|
33
|
+
if (fs.existsSync(path.join(initCwd, 'server.js'))) process.exit(0);
|
|
34
|
+
|
|
35
|
+
const result = scaffold(initCwd);
|
|
36
|
+
|
|
37
|
+
console.log('\n[saas-server] Backend code added to: ' + initCwd);
|
|
38
|
+
if (result.created.length) console.log(' created: ' + result.created.join(', '));
|
|
39
|
+
if (result.skipped.length) console.log(' skipped (already exist): ' + result.skipped.join(', '));
|
|
40
|
+
result.warnings.forEach((w) => console.log(' warning: ' + w));
|
|
41
|
+
console.log(' next: edit .env, then run: npm run dev\n');
|
|
42
|
+
} catch (err) {
|
|
43
|
+
// Never fail the user's install because of the scaffolding step
|
|
44
|
+
console.warn('[saas-server] Could not copy template files: ' + err.message);
|
|
45
|
+
}
|
|
46
|
+
process.exit(0);
|
package/lib/scaffold.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
|
|
5
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
6
|
+
export const templateDir = path.join(__dirname, '..', 'template');
|
|
7
|
+
|
|
8
|
+
// npm strips .gitignore and mangles package.json/.env inside packages,
|
|
9
|
+
// so the template stores them under safe names and they are restored here.
|
|
10
|
+
const ROOT_RENAMES = {
|
|
11
|
+
'gitignore': '.gitignore',
|
|
12
|
+
'env.template': '.env',
|
|
13
|
+
'package.template.json': 'package.json',
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
function listFiles(dir, base = '') {
|
|
17
|
+
const out = [];
|
|
18
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
19
|
+
const rel = path.join(base, entry.name);
|
|
20
|
+
if (entry.isDirectory()) out.push(...listFiles(path.join(dir, entry.name), rel));
|
|
21
|
+
else out.push(rel);
|
|
22
|
+
}
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function safeName(name) {
|
|
27
|
+
const cleaned = String(name)
|
|
28
|
+
.toLowerCase()
|
|
29
|
+
.replace(/[^a-z0-9-_.]/g, '-')
|
|
30
|
+
.replace(/^[._-]+/, '');
|
|
31
|
+
return cleaned || 'server';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function mergePackageJson(targetDir, name, result) {
|
|
35
|
+
const tplPath = path.join(templateDir, 'package.template.json');
|
|
36
|
+
const tpl = JSON.parse(fs.readFileSync(tplPath, 'utf8'));
|
|
37
|
+
const pkgPath = path.join(targetDir, 'package.json');
|
|
38
|
+
|
|
39
|
+
// No package.json yet: write the template one.
|
|
40
|
+
if (!fs.existsSync(pkgPath)) {
|
|
41
|
+
tpl.name = safeName(name || path.basename(targetDir));
|
|
42
|
+
fs.writeFileSync(pkgPath, JSON.stringify(tpl, null, 2) + '\n');
|
|
43
|
+
result.created.push('package.json');
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Existing package.json: add what is missing, never overwrite.
|
|
48
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
|
|
49
|
+
let changed = false;
|
|
50
|
+
|
|
51
|
+
if (!pkg.type) {
|
|
52
|
+
pkg.type = 'module';
|
|
53
|
+
changed = true;
|
|
54
|
+
} else if (pkg.type !== 'module') {
|
|
55
|
+
result.warnings.push('package.json has "type": "' + pkg.type + '". The template needs "type": "module".');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
pkg.scripts = pkg.scripts || {};
|
|
59
|
+
for (const [key, value] of Object.entries(tpl.scripts || {})) {
|
|
60
|
+
if (!(key in pkg.scripts)) {
|
|
61
|
+
pkg.scripts[key] = value;
|
|
62
|
+
changed = true;
|
|
63
|
+
} else if (pkg.scripts[key] !== value && (key === 'start' || key === 'dev')) {
|
|
64
|
+
result.warnings.push('Script "' + key + '" already exists, so it was not replaced.');
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
pkg.dependencies = pkg.dependencies || {};
|
|
69
|
+
for (const [dep, version] of Object.entries(tpl.dependencies || {})) {
|
|
70
|
+
if (!(dep in pkg.dependencies)) {
|
|
71
|
+
pkg.dependencies[dep] = version;
|
|
72
|
+
changed = true;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (!pkg.main) {
|
|
77
|
+
pkg.main = tpl.main;
|
|
78
|
+
changed = true;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (changed) {
|
|
82
|
+
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
|
|
83
|
+
result.created.push('package.json (updated)');
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Copies the template into targetDir. Existing files are never overwritten.
|
|
89
|
+
* Returns { created, skipped, warnings }.
|
|
90
|
+
*/
|
|
91
|
+
export function scaffold(targetDir, { name } = {}) {
|
|
92
|
+
const result = { created: [], skipped: [], warnings: [] };
|
|
93
|
+
fs.mkdirSync(targetDir, { recursive: true });
|
|
94
|
+
|
|
95
|
+
for (const rel of listFiles(templateDir)) {
|
|
96
|
+
const parts = rel.split(path.sep);
|
|
97
|
+
const fileName = parts.pop();
|
|
98
|
+
const destName = parts.length === 0 && ROOT_RENAMES[fileName] ? ROOT_RENAMES[fileName] : fileName;
|
|
99
|
+
const destRel = path.join(...parts, destName);
|
|
100
|
+
|
|
101
|
+
if (destRel === 'package.json') {
|
|
102
|
+
mergePackageJson(targetDir, name, result);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const dest = path.join(targetDir, destRel);
|
|
107
|
+
if (fs.existsSync(dest)) {
|
|
108
|
+
result.skipped.push(destRel);
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
112
|
+
fs.copyFileSync(path.join(templateDir, rel), dest);
|
|
113
|
+
result.created.push(destRel);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return result;
|
|
117
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@waqarcoding/saas-server",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "It creates Express, MongoDB & Firebase Backend Template Ready",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"saas-server": "bin/cli.js"
|
|
8
|
+
},
|
|
9
|
+
"scripts": {
|
|
10
|
+
"postinstall": "node bin/postinstall.js"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"bin",
|
|
14
|
+
"lib",
|
|
15
|
+
"template"
|
|
16
|
+
],
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/waqarcoding/saas-server.git"
|
|
20
|
+
},
|
|
21
|
+
"keywords": [
|
|
22
|
+
"express",
|
|
23
|
+
"mongodb",
|
|
24
|
+
"mongoose",
|
|
25
|
+
"firebase",
|
|
26
|
+
"socket.io",
|
|
27
|
+
"backend",
|
|
28
|
+
"template",
|
|
29
|
+
"scaffold",
|
|
30
|
+
"generator",
|
|
31
|
+
"cli"
|
|
32
|
+
],
|
|
33
|
+
"author": "Waqar Ahmed",
|
|
34
|
+
"license": "MIT",
|
|
35
|
+
"engines": {
|
|
36
|
+
"node": ">=18"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"cors": "^2.8.5",
|
|
40
|
+
"dotenv": "^16.4.5",
|
|
41
|
+
"express": "^5.1.0",
|
|
42
|
+
"firebase-admin": "^13.0.0",
|
|
43
|
+
"mongoose": "^8.9.0",
|
|
44
|
+
"nodemailer": "^6.9.0",
|
|
45
|
+
"socket.io": "^4.8.0"
|
|
46
|
+
}
|
|
6
47
|
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import mongoose from 'mongoose';
|
|
2
|
+
import env from './env.config.js';
|
|
3
|
+
|
|
4
|
+
class Database {
|
|
5
|
+
constructor() {
|
|
6
|
+
this.uri = env.MONGO_URI;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
// ---------------- Connect ----------------
|
|
10
|
+
async connect() {
|
|
11
|
+
try {
|
|
12
|
+
if (!this.uri) {
|
|
13
|
+
throw new Error('MONGO_URI is not defined in environment variables');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const conn = await mongoose.connect(this.uri, {
|
|
17
|
+
serverSelectionTimeoutMS: 5000,
|
|
18
|
+
});
|
|
19
|
+
console.log(`🍃 MongoDB Connected: ${conn.connection.host}`);
|
|
20
|
+
} catch (err) {
|
|
21
|
+
console.error('❌ MongoDB connection error:', err.message);
|
|
22
|
+
console.error(' Is MongoDB running, and is MONGO_URI correct in .env?');
|
|
23
|
+
process.exit(1);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export default new Database();
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import 'dotenv/config';
|
|
2
|
+
|
|
3
|
+
class EnvConfig {
|
|
4
|
+
constructor() {
|
|
5
|
+
this.PORT = process.env.PORT || 5000;
|
|
6
|
+
this.NODE_ENV = process.env.NODE_ENV || 'development';
|
|
7
|
+
this.CLIENT_URL = process.env.CLIENT_URL || 'http://localhost:5173';
|
|
8
|
+
this.MONGO_URI = process.env.MONGO_URI || '';
|
|
9
|
+
|
|
10
|
+
// Firebase
|
|
11
|
+
this.FIREBASE_PROJECT_ID = process.env.FIREBASE_PROJECT_ID || '';
|
|
12
|
+
this.FIREBASE_CLIENT_EMAIL = process.env.FIREBASE_CLIENT_EMAIL || '';
|
|
13
|
+
this.FIREBASE_PRIVATE_KEY = (process.env.FIREBASE_PRIVATE_KEY || '').replace(/\\n/g, '\n');
|
|
14
|
+
|
|
15
|
+
// Mailer (SMTP)
|
|
16
|
+
this.SMTP_HOST = process.env.SMTP_HOST || 'smtp.gmail.com';
|
|
17
|
+
this.SMTP_PORT = Number(process.env.SMTP_PORT) || 587;
|
|
18
|
+
this.SMTP_USER = process.env.SMTP_USER || '';
|
|
19
|
+
this.SMTP_PASS = process.env.SMTP_PASS || '';
|
|
20
|
+
this.MAIL_FROM = process.env.MAIL_FROM || this.SMTP_USER;
|
|
21
|
+
|
|
22
|
+
this.validate();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// ---------------- Validation ----------------
|
|
26
|
+
validate() {
|
|
27
|
+
const required = [
|
|
28
|
+
'MONGO_URI',
|
|
29
|
+
'FIREBASE_PROJECT_ID',
|
|
30
|
+
'FIREBASE_CLIENT_EMAIL',
|
|
31
|
+
'FIREBASE_PRIVATE_KEY',
|
|
32
|
+
];
|
|
33
|
+
required.forEach((key) => {
|
|
34
|
+
if (!this[key]) {
|
|
35
|
+
console.warn(`⚠️ Missing environment variable: ${key}`);
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export default new EnvConfig();
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import firebaseAuth from '../services/firebase_auth.service.js';
|
|
2
|
+
import mailerService from '../services/mailer.service.js';
|
|
3
|
+
import User from '../models/user.model.js';
|
|
4
|
+
|
|
5
|
+
class AuthController {
|
|
6
|
+
// ---------------- LOGIN / SIGN UP SYNC ----------------
|
|
7
|
+
loginOrSignup = async (req, res) => {
|
|
8
|
+
try {
|
|
9
|
+
const authHeader = req.headers.authorization;
|
|
10
|
+
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
|
11
|
+
return res.status(401).json({ success: false, message: 'No token provided' });
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const idToken = authHeader.split(' ')[1];
|
|
15
|
+
const decodedUser = await firebaseAuth.verifyToken(idToken);
|
|
16
|
+
|
|
17
|
+
const userData = {
|
|
18
|
+
uid: decodedUser.uid,
|
|
19
|
+
name: req.body?.name || decodedUser.name || '',
|
|
20
|
+
picture: decodedUser.picture || '',
|
|
21
|
+
emailVerified: decodedUser.emailVerified,
|
|
22
|
+
// Only set email when present (phone-auth users have none)
|
|
23
|
+
...(decodedUser.email ? { email: decodedUser.email } : {}),
|
|
24
|
+
...(req.body?.fcmToken ? { fcmToken: req.body.fcmToken } : {}),
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const user = await User.findOneAndUpdate(
|
|
28
|
+
{ uid: userData.uid },
|
|
29
|
+
{ $set: userData },
|
|
30
|
+
{ upsert: true, new: true, setDefaultsOnInsert: true }
|
|
31
|
+
);
|
|
32
|
+
|
|
33
|
+
console.log('🔍 AuthController DB sync success:', user.email || user.uid);
|
|
34
|
+
res.status(200).json({
|
|
35
|
+
success: true,
|
|
36
|
+
message: 'Authentication successful',
|
|
37
|
+
data: user,
|
|
38
|
+
});
|
|
39
|
+
} catch (err) {
|
|
40
|
+
console.error('❌ AuthController loginOrSignup error:', err.message);
|
|
41
|
+
res.status(err.status || 500).json({
|
|
42
|
+
success: false,
|
|
43
|
+
message: err.message || 'Authentication failed',
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
// ---------------- GET CURRENT USER PROFILE ----------------
|
|
49
|
+
getMe = async (req, res) => {
|
|
50
|
+
try {
|
|
51
|
+
const user = await User.findOne({ uid: req.user.uid });
|
|
52
|
+
res.status(200).json({
|
|
53
|
+
success: true,
|
|
54
|
+
data: user || req.user,
|
|
55
|
+
});
|
|
56
|
+
} catch (err) {
|
|
57
|
+
console.error('❌ AuthController getMe error:', err.message);
|
|
58
|
+
res.status(500).json({
|
|
59
|
+
success: false,
|
|
60
|
+
message: err.message || 'Failed to fetch user profile',
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
// ---------------- FORGOT PASSWORD ----------------
|
|
66
|
+
forgotPassword = async (req, res) => {
|
|
67
|
+
const genericOk = {
|
|
68
|
+
success: true,
|
|
69
|
+
message: 'If an account exists for this email, a reset link has been sent',
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
try {
|
|
73
|
+
const { email } = req.body || {};
|
|
74
|
+
if (!email) {
|
|
75
|
+
return res.status(400).json({ success: false, message: 'Email is required' });
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const info = await mailerService.sendForgetPasswordEmail({ to: email });
|
|
79
|
+
if (!info) {
|
|
80
|
+
return res.status(503).json({
|
|
81
|
+
success: false,
|
|
82
|
+
message: 'Email service is not configured',
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
res.status(200).json(genericOk);
|
|
87
|
+
} catch (err) {
|
|
88
|
+
// Do not reveal whether an email is registered
|
|
89
|
+
if (err.code === 'auth/user-not-found' || err.code === 'auth/email-not-found') {
|
|
90
|
+
return res.status(200).json(genericOk);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
console.error('❌ AuthController forgotPassword error:', err.message);
|
|
94
|
+
res.status(500).json({
|
|
95
|
+
success: false,
|
|
96
|
+
message: 'Failed to send password reset email',
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export default new AuthController();
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import item_service from '../services/item.service.js';
|
|
2
|
+
|
|
3
|
+
class ItemController {
|
|
4
|
+
// ---------------- GET ALL ----------------
|
|
5
|
+
getAll = async (req, res) => {
|
|
6
|
+
try {
|
|
7
|
+
const data = await item_service.getAll();
|
|
8
|
+
res.status(200).json({ success: true, data });
|
|
9
|
+
} catch (err) {
|
|
10
|
+
console.error('❌ Item getAll error:', err);
|
|
11
|
+
res.status(500).json({ success: false, message: err.message || 'Server error' });
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
// ---------------- GET BY ID ----------------
|
|
16
|
+
getById = async (req, res) => {
|
|
17
|
+
try {
|
|
18
|
+
const { id } = req.params;
|
|
19
|
+
const data = await item_service.getById(id);
|
|
20
|
+
if (!data) {
|
|
21
|
+
return res.status(404).json({ success: false, message: 'Item not found' });
|
|
22
|
+
}
|
|
23
|
+
res.status(200).json({ success: true, data });
|
|
24
|
+
} catch (err) {
|
|
25
|
+
console.error('❌ Item getById error:', err);
|
|
26
|
+
res.status(500).json({ success: false, message: err.message || 'Server error' });
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
// ---------------- CREATE ----------------
|
|
31
|
+
create = async (req, res) => {
|
|
32
|
+
try {
|
|
33
|
+
const data = await item_service.create(req.body || {});
|
|
34
|
+
res.status(201).json({ success: true, data });
|
|
35
|
+
} catch (err) {
|
|
36
|
+
console.error('❌ Item create error:', err);
|
|
37
|
+
res.status(500).json({ success: false, message: err.message || 'Server error' });
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
// ---------------- UPDATE ----------------
|
|
42
|
+
update = async (req, res) => {
|
|
43
|
+
try {
|
|
44
|
+
const { id } = req.params;
|
|
45
|
+
const data = await item_service.update(id, req.body || {});
|
|
46
|
+
if (!data) {
|
|
47
|
+
return res.status(404).json({ success: false, message: 'Item not found' });
|
|
48
|
+
}
|
|
49
|
+
res.status(200).json({ success: true, data });
|
|
50
|
+
} catch (err) {
|
|
51
|
+
console.error('❌ Item update error:', err);
|
|
52
|
+
res.status(500).json({ success: false, message: err.message || 'Server error' });
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
// ---------------- DELETE ----------------
|
|
57
|
+
delete = async (req, res) => {
|
|
58
|
+
try {
|
|
59
|
+
const { id } = req.params;
|
|
60
|
+
const deleted = await item_service.delete(id);
|
|
61
|
+
if (!deleted) {
|
|
62
|
+
return res.status(404).json({ success: false, message: 'Item not found' });
|
|
63
|
+
}
|
|
64
|
+
res.status(200).json({ success: true, message: `Deleted ${id}` });
|
|
65
|
+
} catch (err) {
|
|
66
|
+
console.error('❌ Item delete error:', err);
|
|
67
|
+
res.status(500).json({ success: false, message: err.message || 'Server error' });
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export default new ItemController();
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
PORT=5000
|
|
2
|
+
NODE_ENV=development
|
|
3
|
+
CLIENT_URL=http://localhost:5173
|
|
4
|
+
MONGO_URI=mongodb://127.0.0.1:27017/app_db
|
|
5
|
+
|
|
6
|
+
FIREBASE_PROJECT_ID=your-project-id
|
|
7
|
+
FIREBASE_CLIENT_EMAIL=firebase-adminsdk-xxxxx@your-project-id.iam.gserviceaccount.com
|
|
8
|
+
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nYOUR_PRIVATE_KEY_HERE\n-----END PRIVATE KEY-----\n"
|
|
9
|
+
|
|
10
|
+
SMTP_HOST=smtp.gmail.com
|
|
11
|
+
SMTP_PORT=587
|
|
12
|
+
SMTP_USER=your-email@gmail.com
|
|
13
|
+
SMTP_PASS=your-16-char-app-password
|
|
14
|
+
MAIL_FROM="Your App <your-email@gmail.com>"
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import mongoose from 'mongoose';
|
|
2
|
+
import realtimePlugin from '../plugins/realtime.plugin.js';
|
|
3
|
+
const userSchema = new mongoose.Schema(
|
|
4
|
+
{
|
|
5
|
+
uid: {
|
|
6
|
+
type: String,
|
|
7
|
+
required: true,
|
|
8
|
+
unique: true,
|
|
9
|
+
},
|
|
10
|
+
// Not required: phone-auth users have no email.
|
|
11
|
+
// sparse + unique allows many users without an email.
|
|
12
|
+
email: {
|
|
13
|
+
type: String,
|
|
14
|
+
unique: true,
|
|
15
|
+
sparse: true,
|
|
16
|
+
lowercase: true,
|
|
17
|
+
trim: true,
|
|
18
|
+
},
|
|
19
|
+
name: {
|
|
20
|
+
type: String,
|
|
21
|
+
default: '',
|
|
22
|
+
trim: true,
|
|
23
|
+
},
|
|
24
|
+
picture: {
|
|
25
|
+
type: String,
|
|
26
|
+
default: '',
|
|
27
|
+
},
|
|
28
|
+
emailVerified: {
|
|
29
|
+
type: Boolean,
|
|
30
|
+
default: false,
|
|
31
|
+
},
|
|
32
|
+
fcmToken: {
|
|
33
|
+
type: String,
|
|
34
|
+
default: '',
|
|
35
|
+
},
|
|
36
|
+
},
|
|
37
|
+
{ timestamps: true }
|
|
38
|
+
);
|
|
39
|
+
userSchema.plugin(realtimePlugin, {
|
|
40
|
+
name: 'user',
|
|
41
|
+
userId: 'uid',
|
|
42
|
+
fields: ['uid', 'name', 'picture', 'emailVerified'],
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
export default mongoose.model('User', userSchema);
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "server",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Express, MongoDB & Socket.io,Push Notifications & Firebase Auth",
|
|
5
|
+
"main": "server.js",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=18"
|
|
9
|
+
},
|
|
10
|
+
"scripts": {
|
|
11
|
+
"start": "node server.js",
|
|
12
|
+
"dev": "node --watch server.js"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [],
|
|
15
|
+
"author": "",
|
|
16
|
+
"license": "ISC",
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"cors": "^2.8.5",
|
|
19
|
+
"dotenv": "^16.4.5",
|
|
20
|
+
"express": "^5.1.0",
|
|
21
|
+
"firebase-admin": "^13.0.0",
|
|
22
|
+
"mongoose": "^8.9.0",
|
|
23
|
+
"nodemailer": "^6.9.0"
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import realtime from '../services/realtime.service.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* name: event prefix, e.g. 'message' -> message:created / updated / deleted
|
|
5
|
+
* userId: field holding the owner's uid (default 'userId'). null = send to everyone
|
|
6
|
+
* fields: only send these fields (plus _id). Omit to send everything
|
|
7
|
+
*/
|
|
8
|
+
export default function realtimePlugin(
|
|
9
|
+
schema,
|
|
10
|
+
{ name, userId = 'uid', fields } = {}
|
|
11
|
+
) {
|
|
12
|
+
if (!name) throw new Error('realtimePlugin: "name" is required');
|
|
13
|
+
|
|
14
|
+
const scoped = userId && schema.path(userId);
|
|
15
|
+
|
|
16
|
+
const send = (event, doc) => {
|
|
17
|
+
if (!doc) return;
|
|
18
|
+
const obj = doc.toObject ? doc.toObject() : doc;
|
|
19
|
+
const data = fields
|
|
20
|
+
? Object.fromEntries(['_id', ...fields].map((f) => [f, obj[f]]))
|
|
21
|
+
: obj;
|
|
22
|
+
|
|
23
|
+
scoped
|
|
24
|
+
? realtime.toUser(obj[userId], `${name}:${event}`, data)
|
|
25
|
+
: realtime.toAll(`${name}:${event}`, data);
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
schema.post('save', (doc) => send('created', doc));
|
|
29
|
+
schema.post('findOneAndUpdate', (doc) => send('updated', doc));
|
|
30
|
+
schema.post('findOneAndDelete', (doc) => send('deleted', doc));
|
|
31
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { Router } from 'express';
|
|
2
|
+
import authController from '../controllers/auth_controller.js';
|
|
3
|
+
import firebaseAuth from '../services/firebase_auth.service.js';
|
|
4
|
+
|
|
5
|
+
class AuthRoutes {
|
|
6
|
+
constructor() {
|
|
7
|
+
this.router = Router();
|
|
8
|
+
this.initializeRoutes();
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// ---------------- Routes ----------------
|
|
12
|
+
initializeRoutes() {
|
|
13
|
+
this.router.post('/login', authController.loginOrSignup);
|
|
14
|
+
this.router.post('/forgot-password', authController.forgotPassword);
|
|
15
|
+
this.router.get('/me', firebaseAuth.authenticate, authController.getMe);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export default new AuthRoutes().router;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Router } from 'express';
|
|
2
|
+
import item_controller from '../controllers/item_controller.js';
|
|
3
|
+
import firebaseAuth from '../services/firebase_auth.service.js';
|
|
4
|
+
|
|
5
|
+
class ItemRoutes {
|
|
6
|
+
constructor() {
|
|
7
|
+
this.router = Router();
|
|
8
|
+
this.initializeRoutes();
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// ---------------- Routes ----------------
|
|
12
|
+
initializeRoutes() {
|
|
13
|
+
this.router.get('/', firebaseAuth.authenticate, item_controller.getAll);
|
|
14
|
+
this.router.get('/:id', firebaseAuth.authenticate, item_controller.getById);
|
|
15
|
+
this.router.post('/', firebaseAuth.authenticate, item_controller.create);
|
|
16
|
+
this.router.put('/:id', firebaseAuth.authenticate, item_controller.update);
|
|
17
|
+
this.router.delete('/:id', firebaseAuth.authenticate, item_controller.delete);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export default new ItemRoutes().router;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import http from 'http';
|
|
2
|
+
import express from 'express';
|
|
3
|
+
import cors from 'cors';
|
|
4
|
+
import env from './config/env.config.js';
|
|
5
|
+
import db from './config/db.config.js';
|
|
6
|
+
import auth_routes from './routes/auth_routes.js';
|
|
7
|
+
import item_routes from './routes/item_routes.js';
|
|
8
|
+
import realtime from './services/realtime.service.js';
|
|
9
|
+
|
|
10
|
+
class App {
|
|
11
|
+
constructor() {
|
|
12
|
+
this.app = express();
|
|
13
|
+
this.port = env.PORT || 5000;
|
|
14
|
+
this.server = http.createServer(this.app);
|
|
15
|
+
this.initializeMiddlewares();
|
|
16
|
+
this.initializeRoutes();
|
|
17
|
+
this.initializeErrorHandling();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// ---------------- Middlewares ----------------
|
|
21
|
+
initializeMiddlewares() {
|
|
22
|
+
this.app.use(cors({ origin: env.CLIENT_URL }));
|
|
23
|
+
this.app.use(express.json());
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// ---------------- Routes ----------------
|
|
27
|
+
initializeRoutes() {
|
|
28
|
+
// Root route
|
|
29
|
+
this.app.get('/', (req, res) => {
|
|
30
|
+
res.send('Hello, Express!');
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
// Health check route
|
|
34
|
+
this.app.get('/api/health', (req, res) => {
|
|
35
|
+
res.status(200).json({
|
|
36
|
+
success: true,
|
|
37
|
+
status: 'OK',
|
|
38
|
+
uptime: process.uptime(),
|
|
39
|
+
timestamp: new Date().toISOString(),
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
// Feature routes
|
|
44
|
+
this.app.use('/api/auth', auth_routes);
|
|
45
|
+
this.app.use('/api/items', item_routes);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// ---------------- 404 + Error Handling ----------------
|
|
49
|
+
initializeErrorHandling() {
|
|
50
|
+
this.app.use((req, res) => {
|
|
51
|
+
res.status(404).json({ success: false, message: 'Route not found' });
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
// eslint-disable-next-line no-unused-vars
|
|
55
|
+
this.app.use((err, req, res, next) => {
|
|
56
|
+
console.error('❌ Unhandled error:', err.message);
|
|
57
|
+
res.status(err.status || 500).json({
|
|
58
|
+
success: false,
|
|
59
|
+
message: err.message || 'Internal server error',
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// ---------------- Start ----------------
|
|
65
|
+
async start() {
|
|
66
|
+
await db.connect();
|
|
67
|
+
realtime.init(this.server, { origin: env.CLIENT_URL });
|
|
68
|
+
this.server.listen(this.port, () => {
|
|
69
|
+
console.log(`🚀 Server running at http://localhost:${this.port}`);
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const server = new App();
|
|
75
|
+
server.start();
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import admin from 'firebase-admin';
|
|
2
|
+
import env from '../config/env.config.js';
|
|
3
|
+
|
|
4
|
+
class FirebaseAuthService {
|
|
5
|
+
constructor() {
|
|
6
|
+
this.enabled = false;
|
|
7
|
+
|
|
8
|
+
const { FIREBASE_PROJECT_ID, FIREBASE_CLIENT_EMAIL, FIREBASE_PRIVATE_KEY } = env;
|
|
9
|
+
const notConfigured =
|
|
10
|
+
!FIREBASE_PROJECT_ID ||
|
|
11
|
+
!FIREBASE_CLIENT_EMAIL ||
|
|
12
|
+
!FIREBASE_PRIVATE_KEY ||
|
|
13
|
+
FIREBASE_PROJECT_ID === 'your-project-id' ||
|
|
14
|
+
FIREBASE_PRIVATE_KEY.includes('YOUR_PRIVATE_KEY_HERE');
|
|
15
|
+
|
|
16
|
+
// Placeholder credentials make initializeApp() throw and crash the
|
|
17
|
+
// whole server, so skip initialization until real values are set.
|
|
18
|
+
if (notConfigured) {
|
|
19
|
+
console.warn('⚠️ Firebase credentials not set in .env. Firebase features are disabled.');
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
try {
|
|
24
|
+
if (!admin.apps.length) {
|
|
25
|
+
admin.initializeApp({
|
|
26
|
+
credential: admin.credential.cert({
|
|
27
|
+
projectId: FIREBASE_PROJECT_ID,
|
|
28
|
+
clientEmail: FIREBASE_CLIENT_EMAIL,
|
|
29
|
+
privateKey: FIREBASE_PRIVATE_KEY,
|
|
30
|
+
}),
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
this.enabled = true;
|
|
34
|
+
console.log('🔥 Firebase Admin initialized');
|
|
35
|
+
} catch (err) {
|
|
36
|
+
console.error('❌ Firebase init error:', err.message);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// ---------------- Verify Firebase ID Token ----------------
|
|
41
|
+
async verifyToken(idToken) {
|
|
42
|
+
if (!this.enabled) {
|
|
43
|
+
throw Object.assign(new Error('Firebase is not configured on the server'), { status: 503 });
|
|
44
|
+
}
|
|
45
|
+
if (!idToken) {
|
|
46
|
+
throw Object.assign(new Error('Firebase ID token is required'), { status: 401 });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
try {
|
|
50
|
+
const decodedToken = await admin.auth().verifyIdToken(idToken);
|
|
51
|
+
|
|
52
|
+
return {
|
|
53
|
+
uid: decodedToken.uid,
|
|
54
|
+
email: decodedToken.email || '',
|
|
55
|
+
emailVerified: decodedToken.email_verified || false,
|
|
56
|
+
name: decodedToken.name || '',
|
|
57
|
+
picture: decodedToken.picture || '',
|
|
58
|
+
};
|
|
59
|
+
} catch (err) {
|
|
60
|
+
console.error('❌ FirebaseAuthService verifyToken error:', err.message);
|
|
61
|
+
throw Object.assign(new Error('Invalid or expired Firebase token'), { status: 401 });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ---------------- Express Route Middleware ----------------
|
|
66
|
+
authenticate = async (req, res, next) => {
|
|
67
|
+
try {
|
|
68
|
+
const authHeader = req.headers.authorization;
|
|
69
|
+
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
|
70
|
+
return res.status(401).json({ success: false, message: 'No token provided' });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const token = authHeader.split(' ')[1];
|
|
74
|
+
req.user = await this.verifyToken(token);
|
|
75
|
+
next();
|
|
76
|
+
} catch (err) {
|
|
77
|
+
res.status(err.status || 401).json({ success: false, message: err.message || 'Unauthorized' });
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export default new FirebaseAuthService();
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
class ItemService {
|
|
2
|
+
constructor() {
|
|
3
|
+
this.items = [];
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
async getAll() {
|
|
7
|
+
return this.items;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
async getById(id) {
|
|
11
|
+
return this.items.find((item) => item.id === id) || null;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
async create(payload) {
|
|
15
|
+
const newItem = { id: Date.now().toString(), ...payload };
|
|
16
|
+
this.items.push(newItem);
|
|
17
|
+
return newItem;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async update(id, payload) {
|
|
21
|
+
const index = this.items.findIndex((item) => item.id === id);
|
|
22
|
+
if (index === -1) return null;
|
|
23
|
+
this.items[index] = { ...this.items[index], ...payload, id };
|
|
24
|
+
return this.items[index];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async delete(id) {
|
|
28
|
+
const before = this.items.length;
|
|
29
|
+
this.items = this.items.filter((item) => item.id !== id);
|
|
30
|
+
return this.items.length < before;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export default new ItemService();
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import nodemailer from 'nodemailer';
|
|
2
|
+
import admin from 'firebase-admin';
|
|
3
|
+
import env from '../config/env.config.js';
|
|
4
|
+
import firebaseAuth from './firebase_auth.service.js';
|
|
5
|
+
import pushNotificationService from './notification.service.js';
|
|
6
|
+
|
|
7
|
+
class MailerService {
|
|
8
|
+
constructor() {
|
|
9
|
+
this.transporter = nodemailer.createTransport({
|
|
10
|
+
host: env.SMTP_HOST,
|
|
11
|
+
port: env.SMTP_PORT,
|
|
12
|
+
secure: env.SMTP_PORT === 465,
|
|
13
|
+
auth: {
|
|
14
|
+
user: env.SMTP_USER,
|
|
15
|
+
pass: env.SMTP_PASS,
|
|
16
|
+
},
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// ---------------- Send Generic Email ----------------
|
|
21
|
+
async sendMail({ to, subject, html, text = '' }) {
|
|
22
|
+
try {
|
|
23
|
+
if (!env.SMTP_USER || !env.SMTP_PASS) {
|
|
24
|
+
console.warn('⚠️ Mailer skipped: SMTP credentials not configured');
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const info = await this.transporter.sendMail({
|
|
29
|
+
from: env.MAIL_FROM,
|
|
30
|
+
to,
|
|
31
|
+
subject,
|
|
32
|
+
text,
|
|
33
|
+
html,
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
console.log('📧 Email sent:', info.messageId);
|
|
37
|
+
return info;
|
|
38
|
+
} catch (err) {
|
|
39
|
+
console.error('❌ MailerService sendMail error:', err.message);
|
|
40
|
+
throw err;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// ---------------- Welcome Email Helper ----------------
|
|
45
|
+
async sendWelcomeEmail({ to, name }) {
|
|
46
|
+
return this.sendMail({
|
|
47
|
+
to,
|
|
48
|
+
subject: 'Welcome aboard!',
|
|
49
|
+
html: `
|
|
50
|
+
<div style="font-family: sans-serif; line-height: 1.6; color: #333;">
|
|
51
|
+
<h2>Welcome${name ? `, ${name}` : ''}!</h2>
|
|
52
|
+
<p>Your account has been created successfully.</p>
|
|
53
|
+
</div>
|
|
54
|
+
`,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// ---------------- Notification Email ----------------
|
|
59
|
+
async sendNotificationEmail({ to, title, message, actionUrl = '', actionText = 'View Details' }) {
|
|
60
|
+
const buttonHtml = actionUrl
|
|
61
|
+
? `<p style="margin-top: 20px;">
|
|
62
|
+
<a href="${actionUrl}" style="background-color: #2563eb; color: #ffffff; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block;">
|
|
63
|
+
${actionText}
|
|
64
|
+
</a>
|
|
65
|
+
</p>`
|
|
66
|
+
: '';
|
|
67
|
+
|
|
68
|
+
return this.sendMail({
|
|
69
|
+
to,
|
|
70
|
+
subject: title,
|
|
71
|
+
text: `${title}\n\n${message}${actionUrl ? `\n\n${actionText}: ${actionUrl}` : ''}`,
|
|
72
|
+
html: `
|
|
73
|
+
<div style="font-family: sans-serif; line-height: 1.6; color: #333; max-width: 600px;">
|
|
74
|
+
<h2 style="color: #111;">${title}</h2>
|
|
75
|
+
<p>${message}</p>
|
|
76
|
+
${buttonHtml}
|
|
77
|
+
</div>
|
|
78
|
+
`,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// ---------------- Forget Password Email ----------------
|
|
83
|
+
async sendForgetPasswordEmail({ to, resetLink = '' }) {
|
|
84
|
+
try {
|
|
85
|
+
let link = resetLink;
|
|
86
|
+
if (!link) {
|
|
87
|
+
if (!firebaseAuth.enabled) {
|
|
88
|
+
throw new Error('Firebase is not configured on the server');
|
|
89
|
+
}
|
|
90
|
+
link = await admin.auth().generatePasswordResetLink(to);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return await this.sendMail({
|
|
94
|
+
to,
|
|
95
|
+
subject: 'Reset Your Password',
|
|
96
|
+
text: `We received a request to reset your password. Click the link below to set a new password:\n\n${link}\n\nIf you did not request this, please ignore this email.`,
|
|
97
|
+
html: `
|
|
98
|
+
<div style="font-family: sans-serif; line-height: 1.6; color: #333; max-width: 600px;">
|
|
99
|
+
<h2>Password Reset Request</h2>
|
|
100
|
+
<p>We received a request to reset your password. Click the button below to choose a new password:</p>
|
|
101
|
+
<p style="margin: 24px 0;">
|
|
102
|
+
<a href="${link}" style="background-color: #dc2626; color: #ffffff; padding: 12px 24px; text-decoration: none; border-radius: 5px; display: inline-block; font-weight: bold;">
|
|
103
|
+
Reset Password
|
|
104
|
+
</a>
|
|
105
|
+
</p>
|
|
106
|
+
<p style="font-size: 13px; color: #666;">If you didn't request a password reset, you can safely ignore this email.</p>
|
|
107
|
+
</div>
|
|
108
|
+
`,
|
|
109
|
+
});
|
|
110
|
+
} catch (err) {
|
|
111
|
+
console.error('❌ MailerService sendForgetPasswordEmail error:', err.message);
|
|
112
|
+
throw err;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export default new MailerService();
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import admin from 'firebase-admin';
|
|
2
|
+
import firebaseAuth from './firebase_auth.service.js';
|
|
3
|
+
|
|
4
|
+
class NotificationService {
|
|
5
|
+
// Resolved lazily so the server still starts when Firebase is not configured.
|
|
6
|
+
_messaging() {
|
|
7
|
+
if (!firebaseAuth.enabled) {
|
|
8
|
+
throw new Error('Firebase is not configured on the server');
|
|
9
|
+
}
|
|
10
|
+
return admin.messaging();
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// ---------------- Send to Single Device ----------------
|
|
14
|
+
async sendToDevice({ token, title, body, data = {} }) {
|
|
15
|
+
try {
|
|
16
|
+
if (!token) throw new Error('FCM device token is required');
|
|
17
|
+
|
|
18
|
+
const message = {
|
|
19
|
+
token,
|
|
20
|
+
notification: { title, body },
|
|
21
|
+
data: this._stringifyData(data),
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const response = await this._messaging().send(message);
|
|
25
|
+
console.log('🔔 Push notification sent:', response);
|
|
26
|
+
return response;
|
|
27
|
+
} catch (err) {
|
|
28
|
+
console.error('❌ NotificationService sendToDevice error:', err.message);
|
|
29
|
+
throw err;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// ---------------- Send to Multiple Devices (max 500 tokens per call) ----------------
|
|
34
|
+
async sendToMultiple({ tokens = [], title, body, data = {} }) {
|
|
35
|
+
try {
|
|
36
|
+
if (!tokens.length) return null;
|
|
37
|
+
|
|
38
|
+
const message = {
|
|
39
|
+
tokens,
|
|
40
|
+
notification: { title, body },
|
|
41
|
+
data: this._stringifyData(data),
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const response = await this._messaging().sendEachForMulticast(message);
|
|
45
|
+
console.log(`🔔 Multicast sent: ${response.successCount} succeeded, ${response.failureCount} failed`);
|
|
46
|
+
return response;
|
|
47
|
+
} catch (err) {
|
|
48
|
+
console.error('❌ NotificationService sendToMultiple error:', err.message);
|
|
49
|
+
throw err;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// ---------------- Send to Topic ----------------
|
|
54
|
+
async sendToTopic({ topic, title, body, data = {} }) {
|
|
55
|
+
try {
|
|
56
|
+
const message = {
|
|
57
|
+
topic,
|
|
58
|
+
notification: { title, body },
|
|
59
|
+
data: this._stringifyData(data),
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
const response = await this._messaging().send(message);
|
|
63
|
+
console.log(`🔔 Topic (${topic}) notification sent:`, response);
|
|
64
|
+
return response;
|
|
65
|
+
} catch (err) {
|
|
66
|
+
console.error('❌ NotificationService sendToTopic error:', err.message);
|
|
67
|
+
throw err;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
_stringifyData(data) {
|
|
72
|
+
return Object.fromEntries(
|
|
73
|
+
Object.entries(data).map(([k, v]) => [k, String(v)])
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export default new NotificationService();
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { Server } from 'socket.io';
|
|
2
|
+
import admin from 'firebase-admin';
|
|
3
|
+
|
|
4
|
+
class RealtimeService {
|
|
5
|
+
io = null;
|
|
6
|
+
|
|
7
|
+
init(httpServer, { origin = '*' } = {}) {
|
|
8
|
+
this.io = new Server(httpServer, { cors: { origin } });
|
|
9
|
+
|
|
10
|
+
// Verify the Firebase ID token; each user joins a room named by their uid
|
|
11
|
+
this.io.use(async (socket, next) => {
|
|
12
|
+
try {
|
|
13
|
+
const decoded = await admin.auth().verifyIdToken(socket.handshake.auth?.token);
|
|
14
|
+
socket.uid = decoded.uid;
|
|
15
|
+
next();
|
|
16
|
+
} catch {
|
|
17
|
+
next(new Error('unauthorized'));
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
this.io.on('connection', (socket) => socket.join(socket.uid));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
toAll(event, data) { this.io?.emit(event, data); }
|
|
25
|
+
toUser(uid, event, data) { this.io?.to(String(uid)).emit(event, data); }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export default new RealtimeService();
|