Phase 3.4: backend self-managed auth cutover
All backend auth now goes through our own token service — Firebase Auth
dependency is fully removed from auth paths. FCM (firebase-admin messaging)
is still used for push.
Schema:
- auth_sessions (multi-device refresh tokens, bcrypt-hashed)
- otp_requests (Fazpass reference + rate-limit history)
- customers.email + google_sub + apple_sub (social identity)
- control_center_users.password_hash + failed_login_count + lockout_until
- firebase_uid columns made nullable (drop in later cleanup migration)
- 6 new app_config keys for OTP + CC lockout tuning
Services:
- password.service.js — bcrypt cost 12 + complexity (min 8, digit + upper +
lower)
- token.service.js — JWT HS256 access (1h) + opaque refresh (30d, bcrypt-
hashed, rotated on use); session_id claim pre-wires future Valkey-based
instant revocation; revokeSession + revokeAllSessionsForUser helpers
- social-identity.service.js — Google via google-auth-library, Apple via
jwks-rsa + jsonwebtoken
- otp.service.js — Fazpass stub (generates locally, logs the code) clearly
marked for replacement once real API docs arrive; rate-limit + resend
cooldown + verify-attempts all configurable via app_config
- auth.service.js — orchestrator: signInAnonymous, completeCustomer/Mitra-
PhoneSignIn, signInWithGoogle, signInWithApple, signInCcUser, refresh,
logout; reject-on-existing for identity conflicts
- cc-user.service.js — email+password helpers + lockout counters
Routes & middleware:
- authenticate middleware now verifies our JWT and attaches
request.auth = { userType, userId, sessionId }
- WebSocket handshake verifies our JWT (no more Firebase lookup)
- All existing routes updated to use request.auth.userId instead of
request.firebaseUser.uid
- New public routes:
/api/shared/auth/anonymous /refresh /logout
/api/client/auth/otp/request /otp/verify /google /apple /me /profile
/api/mitra/auth/otp/request /otp/verify /me
- New internal routes:
/internal/auth/login /refresh /logout /me (httpOnly cookie refresh)
/internal/control-center-users (accepts plain password, bcrypt-hashed)
/internal/control-center-users/me/password (self-service change)
/internal/control-center-users/:id/password (admin forced reset)
- Deleted legacy customer.routes.js (anonymous + link handled by auth now)
- app.internal.js: @fastify/cookie + CORS credentials for CC httpOnly cookie
Config:
- AUTH_JWT_SECRET + ACCESS_TOKEN_TTL_SECONDS + REFRESH_TOKEN_TTL_DAYS env
- FAZPASS_* env vars (TBD until real API docs)
- GOOGLE_OAUTH_CLIENT_IDS, APPLE_SERVICES_ID/TEAM_ID/KEY_ID/PRIVATE_KEY
- ADMIN_EMAIL + ADMIN_PASSWORD for seed
- CC_ORIGIN for internal-app CORS origin allowlist
Dependencies:
- Added: bcrypt, jsonwebtoken, jwks-rsa, google-auth-library, @fastify/cookie
- Kept: firebase-admin (messaging only)
Still outstanding: Fazpass API integration (stub in place), Apple Developer
prereqs for end-to-end iOS testing, client_app/mitra_app/control_center auth
flow rewrites.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import Fastify from 'fastify'
|
||||
import cors from '@fastify/cors'
|
||||
import cookie from '@fastify/cookie'
|
||||
import sensible from '@fastify/sensible'
|
||||
import { mitraManagementRoutes } from './routes/internal/mitra.routes.js'
|
||||
import { ccUserRoutes } from './routes/internal/cc-user.routes.js'
|
||||
@@ -13,7 +14,13 @@ import { errorHandler } from './plugins/error-handler.js'
|
||||
export const buildInternalApp = async () => {
|
||||
const app = Fastify({ logger: true })
|
||||
|
||||
await app.register(cors, { origin: true })
|
||||
// CORS: control center origin must be allowed with credentials for httpOnly refresh cookie
|
||||
const ccOrigin = process.env.CC_ORIGIN
|
||||
await app.register(cors, {
|
||||
origin: ccOrigin ? ccOrigin.split(',').map((s) => s.trim()) : true,
|
||||
credentials: true,
|
||||
})
|
||||
await app.register(cookie)
|
||||
await app.register(sensible)
|
||||
app.setErrorHandler(errorHandler)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import Fastify from 'fastify'
|
||||
import cors from '@fastify/cors'
|
||||
import sensible from '@fastify/sensible'
|
||||
import { customerRoutes } from './routes/public/customer.routes.js'
|
||||
import { sharedAuthRoutes } from './routes/public/shared.auth.routes.js'
|
||||
import { clientAuthRoutes } from './routes/public/client.auth.routes.js'
|
||||
import { mitraAuthRoutes } from './routes/public/mitra.auth.routes.js'
|
||||
import { sharedConfigRoutes } from './routes/public/shared.config.routes.js'
|
||||
@@ -20,7 +20,7 @@ export const buildPublicApp = async () => {
|
||||
await registerWebSocketPlugin(app)
|
||||
app.setErrorHandler(errorHandler)
|
||||
|
||||
app.register(customerRoutes, { prefix: '/api/shared/customer' })
|
||||
app.register(sharedAuthRoutes, { prefix: '/api/shared/auth' })
|
||||
app.register(sharedConfigRoutes, { prefix: '/api/shared/config' })
|
||||
app.register(sharedChatRoutes, { prefix: '/api/shared' })
|
||||
app.register(clientAuthRoutes, { prefix: '/api/client/auth' })
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
export const UserType = Object.freeze({
|
||||
CUSTOMER: 'customer',
|
||||
MITRA: 'mitra',
|
||||
CC_USER: 'cc_user',
|
||||
})
|
||||
|
||||
// Chat session statuses
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import 'dotenv/config'
|
||||
import admin from 'firebase-admin'
|
||||
import { getDb } from './client.js'
|
||||
import { initFirebase } from '../plugins/firebase.js'
|
||||
import { hashPassword } from '../services/password.service.js'
|
||||
|
||||
const sql = getDb()
|
||||
|
||||
const seed = async () => {
|
||||
initFirebase()
|
||||
|
||||
// Create super_admin role
|
||||
const [role] = await sql`
|
||||
INSERT INTO roles (name, permissions)
|
||||
@@ -24,21 +21,14 @@ const seed = async () => {
|
||||
RETURNING id
|
||||
`
|
||||
|
||||
// Create first super admin user in Firebase
|
||||
const email = process.env.SEED_ADMIN_EMAIL || 'admin@halobestie.com'
|
||||
const password = process.env.SEED_ADMIN_PASSWORD || 'ChangeMe123!'
|
||||
|
||||
let firebaseUser
|
||||
try {
|
||||
firebaseUser = await admin.auth().getUserByEmail(email)
|
||||
} catch {
|
||||
firebaseUser = await admin.auth().createUser({ email, password, displayName: 'Super Admin' })
|
||||
}
|
||||
const email = process.env.ADMIN_EMAIL || process.env.SEED_ADMIN_EMAIL || 'admin@halobestie.com'
|
||||
const password = process.env.ADMIN_PASSWORD || process.env.SEED_ADMIN_PASSWORD || 'ChangeMe123!'
|
||||
const passwordHash = await hashPassword(password)
|
||||
|
||||
await sql`
|
||||
INSERT INTO control_center_users (firebase_uid, email, display_name, role_id)
|
||||
VALUES (${firebaseUser.uid}, ${email}, 'Super Admin', ${role.id})
|
||||
ON CONFLICT (email) DO NOTHING
|
||||
INSERT INTO control_center_users (email, display_name, role_id, password_hash)
|
||||
VALUES (${email}, 'Super Admin', ${role.id}, ${passwordHash})
|
||||
ON CONFLICT (email) DO UPDATE SET password_hash = EXCLUDED.password_hash
|
||||
`
|
||||
|
||||
console.log(`Seed complete. Admin: ${email}`)
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import { verifyFirebaseToken } from './firebase.js'
|
||||
import { verifyAccessToken } from '../services/token.service.js'
|
||||
|
||||
/**
|
||||
* Fastify preHandler — verifies Firebase JWT and attaches decoded token to request.
|
||||
* Usage: add as preHandler on any route that requires authentication.
|
||||
* Fastify preHandler — verifies our JWT access token and attaches claims to request.auth.
|
||||
*
|
||||
* On success: request.auth = { userType, userId, sessionId }
|
||||
* On failure: returns 401 UNAUTHORIZED and short-circuits the handler.
|
||||
*
|
||||
* Future hook: if Valkey-based instant revocation is enabled, add a
|
||||
* SISMEMBER revoked_sessions <session_id> check here before accepting.
|
||||
*/
|
||||
export const authenticate = async (request, reply) => {
|
||||
const authHeader = request.headers.authorization
|
||||
@@ -15,18 +20,25 @@ export const authenticate = async (request, reply) => {
|
||||
|
||||
const token = authHeader.slice(7)
|
||||
try {
|
||||
request.firebaseUser = await verifyFirebaseToken(token)
|
||||
const claims = verifyAccessToken(token)
|
||||
if (!claims.userId || !claims.userType || !claims.sessionId) {
|
||||
return reply.code(401).send({
|
||||
success: false,
|
||||
error: { code: 'UNAUTHORIZED', message: 'Invalid token claims' },
|
||||
})
|
||||
}
|
||||
request.auth = claims
|
||||
} catch (err) {
|
||||
console.error('Auth failed:', err.code || err.message, '| token preview:', token.substring(0, 20) + '...')
|
||||
return reply.code(401).send({
|
||||
return reply.code(err.statusCode || 401).send({
|
||||
success: false,
|
||||
error: { code: 'UNAUTHORIZED', message: 'Invalid or expired token' },
|
||||
error: { code: err.code || 'UNAUTHORIZED', message: err.message || 'Invalid or expired token' },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a preHandler that checks if the CC user has the required permission.
|
||||
* Returns a preHandler that checks if the authenticated CC user has the required permission.
|
||||
* Requires `attachCcUser` (or equivalent) to have run earlier and set request.ccUser.
|
||||
* Usage: requirePermission('mitra', 'create')
|
||||
*/
|
||||
export const requirePermission = (resource, action) => {
|
||||
|
||||
@@ -7,6 +7,10 @@ const __dirname = dirname(fileURLToPath(import.meta.url))
|
||||
|
||||
let initialized = false
|
||||
|
||||
/**
|
||||
* Initializes Firebase Admin SDK. Phase 3.4+ only uses this for FCM (messaging);
|
||||
* authentication is handled by our own token service.
|
||||
*/
|
||||
export const initFirebase = () => {
|
||||
if (initialized) return
|
||||
|
||||
@@ -19,7 +23,3 @@ export const initFirebase = () => {
|
||||
})
|
||||
initialized = true
|
||||
}
|
||||
|
||||
export const verifyFirebaseToken = async (token) => {
|
||||
return admin.auth().verifyIdToken(token)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import websocket from '@fastify/websocket'
|
||||
import { verifyFirebaseToken } from './firebase.js'
|
||||
import { getCustomerByFirebaseUid } from '../services/customer.service.js'
|
||||
import { getMitraByFirebaseUid } from '../services/mitra.service.js'
|
||||
import { verifyAccessToken } from '../services/token.service.js'
|
||||
import { subscribe, publish } from './valkey.js'
|
||||
import { UserType, WsMessage } from '../constants.js'
|
||||
|
||||
@@ -64,18 +62,15 @@ export const registerWebSocketRoute = (app) => {
|
||||
// Handle auth message
|
||||
if (msg.type === WsMessage.AUTH) {
|
||||
try {
|
||||
const decoded = await verifyFirebaseToken(msg.token)
|
||||
const customer = await getCustomerByFirebaseUid(decoded.uid)
|
||||
const mitra = customer ? null : await getMitraByFirebaseUid(decoded.uid)
|
||||
|
||||
if (!customer && !mitra) {
|
||||
send({ type: WsMessage.ERROR, message: 'Account not found' })
|
||||
const claims = verifyAccessToken(msg.token)
|
||||
if (claims.userType !== UserType.CUSTOMER && claims.userType !== UserType.MITRA) {
|
||||
send({ type: WsMessage.ERROR, message: 'Unsupported user type for websocket' })
|
||||
socket.close()
|
||||
return
|
||||
}
|
||||
|
||||
const userType = customer ? UserType.CUSTOMER : UserType.MITRA
|
||||
const userId = customer ? customer.id : mitra.id
|
||||
const userType = claims.userType
|
||||
const userId = claims.userId
|
||||
const sessionId = msg.session_id
|
||||
|
||||
authenticatedUser = { type: userType, id: userId, sessionId }
|
||||
|
||||
@@ -1,17 +1,127 @@
|
||||
import { authenticate } from '../../plugins/auth.js'
|
||||
import { getCcUserByFirebaseUid } from '../../services/cc-user.service.js'
|
||||
import { getCcUserById } from '../../services/cc-user.service.js'
|
||||
import {
|
||||
signInCcUser,
|
||||
refreshTokens,
|
||||
logout,
|
||||
} from '../../services/auth.service.js'
|
||||
import { UserType } from '../../constants.js'
|
||||
|
||||
export const internalAuthRoutes = async (app) => {
|
||||
app.post('/verify', { preHandler: authenticate }, async (request, reply) => {
|
||||
const user = await getCcUserByFirebaseUid(request.firebaseUser.uid)
|
||||
if (!user) {
|
||||
return reply.code(403).send({
|
||||
success: false,
|
||||
error: { code: 'FORBIDDEN', message: 'Not a control center user' },
|
||||
})
|
||||
}
|
||||
// Attach to request for downstream permission checks
|
||||
request.ccUser = user
|
||||
return reply.send({ success: true, data: user })
|
||||
const REFRESH_COOKIE_NAME = 'cc_refresh_token'
|
||||
|
||||
const extractDeviceInfo = (request) => ({
|
||||
user_agent: request.headers['user-agent'] || null,
|
||||
ip: request.ip || null,
|
||||
})
|
||||
|
||||
const sendAuthError = (reply, err) => reply.code(err.statusCode || 500).send({
|
||||
success: false,
|
||||
error: { code: err.code || 'INTERNAL', message: err.message },
|
||||
})
|
||||
|
||||
const cookieOpts = () => ({
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
|
||||
path: '/',
|
||||
})
|
||||
|
||||
const setRefreshCookie = (reply, refreshToken, expiresAt) => {
|
||||
reply.setCookie(REFRESH_COOKIE_NAME, refreshToken, {
|
||||
...cookieOpts(),
|
||||
expires: new Date(expiresAt),
|
||||
})
|
||||
}
|
||||
|
||||
const clearRefreshCookie = (reply) => {
|
||||
reply.clearCookie(REFRESH_COOKIE_NAME, cookieOpts())
|
||||
}
|
||||
|
||||
export const internalAuthRoutes = async (app) => {
|
||||
app.post('/login', async (request, reply) => {
|
||||
const { email, password } = request.body || {}
|
||||
if (!email || !password) {
|
||||
return reply.code(422).send({
|
||||
success: false,
|
||||
error: { code: 'VALIDATION_ERROR', message: 'email and password are required' },
|
||||
})
|
||||
}
|
||||
try {
|
||||
const { tokens, profile } = await signInCcUser({
|
||||
email,
|
||||
password,
|
||||
deviceInfo: extractDeviceInfo(request),
|
||||
})
|
||||
setRefreshCookie(reply, tokens.refresh_token, tokens.refresh_token_expires_at)
|
||||
return reply.send({
|
||||
success: true,
|
||||
data: {
|
||||
access_token: tokens.access_token,
|
||||
access_token_expires_in: tokens.access_token_expires_in,
|
||||
profile,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return sendAuthError(reply, err)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/refresh', async (request, reply) => {
|
||||
const refreshToken = request.cookies?.[REFRESH_COOKIE_NAME]
|
||||
if (!refreshToken) {
|
||||
return reply.code(401).send({
|
||||
success: false,
|
||||
error: { code: 'REFRESH_MISSING', message: 'Refresh token missing' },
|
||||
})
|
||||
}
|
||||
try {
|
||||
const { tokens, profile } = await refreshTokens({
|
||||
refreshToken,
|
||||
deviceInfo: extractDeviceInfo(request),
|
||||
})
|
||||
setRefreshCookie(reply, tokens.refresh_token, tokens.refresh_token_expires_at)
|
||||
return reply.send({
|
||||
success: true,
|
||||
data: {
|
||||
access_token: tokens.access_token,
|
||||
access_token_expires_in: tokens.access_token_expires_in,
|
||||
profile,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
clearRefreshCookie(reply)
|
||||
return sendAuthError(reply, err)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/logout', { preHandler: authenticate }, async (request, reply) => {
|
||||
await logout({ sessionId: request.auth.sessionId })
|
||||
clearRefreshCookie(reply)
|
||||
return reply.send({ success: true })
|
||||
})
|
||||
|
||||
app.get('/me', { preHandler: authenticate }, async (request, reply) => {
|
||||
if (request.auth.userType !== UserType.CC_USER) {
|
||||
return reply.code(403).send({
|
||||
success: false,
|
||||
error: { code: 'FORBIDDEN', message: 'Control center account required' },
|
||||
})
|
||||
}
|
||||
const user = await getCcUserById(request.auth.userId)
|
||||
if (!user) {
|
||||
return reply.code(404).send({
|
||||
success: false,
|
||||
error: { code: 'NOT_FOUND', message: 'Control center account not found' },
|
||||
})
|
||||
}
|
||||
return reply.send({
|
||||
success: true,
|
||||
data: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
display_name: user.display_name,
|
||||
role: user.role,
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,33 +1,54 @@
|
||||
import { authenticate, requirePermission } from '../../plugins/auth.js'
|
||||
import { getCcUserByFirebaseUid, createCcUser, listCcUsers } from '../../services/cc-user.service.js'
|
||||
import {
|
||||
getCcUserById,
|
||||
createCcUserWithPassword,
|
||||
listCcUsers,
|
||||
updateCcUserPasswordHash,
|
||||
} from '../../services/cc-user.service.js'
|
||||
import {
|
||||
hashPassword,
|
||||
verifyPassword,
|
||||
validatePasswordComplexity,
|
||||
} from '../../services/password.service.js'
|
||||
import { UserType } from '../../constants.js'
|
||||
|
||||
const attachCcUser = async (request, reply) => {
|
||||
const user = await getCcUserByFirebaseUid(request.firebaseUser.uid)
|
||||
if (request.auth?.userType !== UserType.CC_USER) {
|
||||
return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
|
||||
}
|
||||
const user = await getCcUserById(request.auth.userId)
|
||||
if (!user) return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
|
||||
request.ccUser = user
|
||||
}
|
||||
|
||||
const sendValidation = (reply, err) => reply.code(err.statusCode || 422).send({
|
||||
success: false,
|
||||
error: { code: err.code || 'VALIDATION_ERROR', message: err.message },
|
||||
})
|
||||
|
||||
export const ccUserRoutes = async (app) => {
|
||||
// Create CC user (with initial password)
|
||||
app.post('/', {
|
||||
preHandler: [authenticate, attachCcUser, requirePermission('control_center_users', 'create')],
|
||||
}, async (request, reply) => {
|
||||
const { email, display_name, role_id } = request.body ?? {}
|
||||
if (!email || !display_name || !role_id) {
|
||||
return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'email, display_name, and role_id are required' } })
|
||||
const { email, display_name, role_id, password } = request.body ?? {}
|
||||
if (!email || !display_name || !role_id || !password) {
|
||||
return reply.code(422).send({
|
||||
success: false,
|
||||
error: { code: 'VALIDATION_ERROR', message: 'email, display_name, role_id, and password are required' },
|
||||
})
|
||||
}
|
||||
|
||||
// Create Firebase user with temporary password — admin will share credentials verbally
|
||||
const { initFirebase } = await import('../../plugins/firebase.js')
|
||||
const admin = (await import('firebase-admin')).default
|
||||
initFirebase()
|
||||
|
||||
const tempPassword = Math.random().toString(36).slice(-10) + 'A1!'
|
||||
const firebaseUser = await admin.auth().createUser({ email, password: tempPassword })
|
||||
|
||||
const user = await createCcUser({ firebase_uid: firebaseUser.uid, email, display_name, role_id })
|
||||
try {
|
||||
validatePasswordComplexity(password)
|
||||
} catch (err) {
|
||||
return sendValidation(reply, err)
|
||||
}
|
||||
const passwordHash = await hashPassword(password)
|
||||
const user = await createCcUserWithPassword({ email, display_name, role_id, password_hash: passwordHash })
|
||||
return reply.code(201).send({ success: true, data: user })
|
||||
})
|
||||
|
||||
// List CC users
|
||||
app.get('/', {
|
||||
preHandler: [authenticate, attachCcUser, requirePermission('control_center_users', 'read')],
|
||||
}, async (request, reply) => {
|
||||
@@ -35,4 +56,53 @@ export const ccUserRoutes = async (app) => {
|
||||
const result = await listCcUsers({ page: Number(page), limit: Number(limit) })
|
||||
return reply.send({ success: true, data: result })
|
||||
})
|
||||
|
||||
// Self-service password change
|
||||
app.patch('/me/password', {
|
||||
preHandler: [authenticate, attachCcUser],
|
||||
}, async (request, reply) => {
|
||||
const { current_password, new_password } = request.body || {}
|
||||
if (!current_password || !new_password) {
|
||||
return reply.code(422).send({
|
||||
success: false,
|
||||
error: { code: 'VALIDATION_ERROR', message: 'current_password and new_password are required' },
|
||||
})
|
||||
}
|
||||
const ok = await verifyPassword(current_password, request.ccUser.password_hash)
|
||||
if (!ok) {
|
||||
return reply.code(401).send({
|
||||
success: false,
|
||||
error: { code: 'INVALID_CREDENTIALS', message: 'Current password is incorrect' },
|
||||
})
|
||||
}
|
||||
try {
|
||||
validatePasswordComplexity(new_password)
|
||||
} catch (err) {
|
||||
return sendValidation(reply, err)
|
||||
}
|
||||
const hash = await hashPassword(new_password)
|
||||
await updateCcUserPasswordHash(request.ccUser.id, hash)
|
||||
return reply.send({ success: true })
|
||||
})
|
||||
|
||||
// Admin-forced password reset
|
||||
app.patch('/:id/password', {
|
||||
preHandler: [authenticate, attachCcUser, requirePermission('control_center_users', 'update')],
|
||||
}, async (request, reply) => {
|
||||
const { new_password } = request.body || {}
|
||||
if (!new_password) {
|
||||
return reply.code(422).send({
|
||||
success: false,
|
||||
error: { code: 'VALIDATION_ERROR', message: 'new_password is required' },
|
||||
})
|
||||
}
|
||||
try {
|
||||
validatePasswordComplexity(new_password)
|
||||
} catch (err) {
|
||||
return sendValidation(reply, err)
|
||||
}
|
||||
const hash = await hashPassword(new_password)
|
||||
await updateCcUserPasswordHash(request.params.id, hash)
|
||||
return reply.send({ success: true })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { authenticate, requirePermission } from '../../plugins/auth.js'
|
||||
import { getCcUserByFirebaseUid } from '../../services/cc-user.service.js'
|
||||
import { getCcUserById } from '../../services/cc-user.service.js'
|
||||
import { UserType } from '../../constants.js'
|
||||
import {
|
||||
getAnonymityConfig, setAnonymityConfig,
|
||||
getMaxCustomersPerMitra, setMaxCustomersPerMitra,
|
||||
@@ -11,7 +12,10 @@ import {
|
||||
} from '../../services/config.service.js'
|
||||
|
||||
const attachCcUser = async (request, reply) => {
|
||||
const user = await getCcUserByFirebaseUid(request.firebaseUser.uid)
|
||||
if (request.auth?.userType !== UserType.CC_USER) {
|
||||
return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
|
||||
}
|
||||
const user = await getCcUserById(request.auth.userId)
|
||||
if (!user) return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
|
||||
request.ccUser = user
|
||||
}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { authenticate, requirePermission } from '../../plugins/auth.js'
|
||||
import { getCcUserByFirebaseUid } from '../../services/cc-user.service.js'
|
||||
import { getCcUserById } from '../../services/cc-user.service.js'
|
||||
import { getMitraActivityLog, getMitraActivitySummary } from '../../services/mitra-activity.service.js'
|
||||
import { UserType } from '../../constants.js'
|
||||
|
||||
const attachCcUser = async (request, reply) => {
|
||||
const user = await getCcUserByFirebaseUid(request.firebaseUser.uid)
|
||||
if (!user) return reply.code(403).send({
|
||||
success: false,
|
||||
error: { code: 'FORBIDDEN', message: 'Not a control center user' },
|
||||
})
|
||||
if (request.auth?.userType !== UserType.CC_USER) {
|
||||
return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
|
||||
}
|
||||
const user = await getCcUserById(request.auth.userId)
|
||||
if (!user) return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
|
||||
request.ccUser = user
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { authenticate, requirePermission } from '../../plugins/auth.js'
|
||||
import { getCcUserByFirebaseUid } from '../../services/cc-user.service.js'
|
||||
import { getCcUserById } from '../../services/cc-user.service.js'
|
||||
import { createMitra, listMitras, updateMitraStatus } from '../../services/mitra.service.js'
|
||||
import { getOnlineMitras, getOnlineLogs } from '../../services/mitra-status.service.js'
|
||||
import { UserType } from '../../constants.js'
|
||||
|
||||
const attachCcUser = async (request, reply) => {
|
||||
const user = await getCcUserByFirebaseUid(request.firebaseUser.uid)
|
||||
if (request.auth?.userType !== UserType.CC_USER) {
|
||||
return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
|
||||
}
|
||||
const user = await getCcUserById(request.auth.userId)
|
||||
if (!user) return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
|
||||
request.ccUser = user
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import { authenticate, requirePermission } from '../../plugins/auth.js'
|
||||
import { getCcUserByFirebaseUid } from '../../services/cc-user.service.js'
|
||||
import { getCcUserById } from '../../services/cc-user.service.js'
|
||||
import { listRoles } from '../../services/roles.service.js'
|
||||
import { UserType } from '../../constants.js'
|
||||
|
||||
const attachCcUser = async (request, reply) => {
|
||||
const user = await getCcUserByFirebaseUid(request.firebaseUser.uid)
|
||||
if (request.auth?.userType !== UserType.CC_USER) {
|
||||
return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
|
||||
}
|
||||
const user = await getCcUserById(request.auth.userId)
|
||||
if (!user) return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
|
||||
request.ccUser = user
|
||||
}
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { authenticate, requirePermission } from '../../plugins/auth.js'
|
||||
import { getCcUserByFirebaseUid } from '../../services/cc-user.service.js'
|
||||
import { getCcUserById } from '../../services/cc-user.service.js'
|
||||
import { listSessions, getSessionById, rerouteSession } from '../../services/session.service.js'
|
||||
import { getSessionSensitivityLog } from '../../services/sensitivity.service.js'
|
||||
import { getDashboardStats } from '../../services/dashboard.service.js'
|
||||
import { UserType } from '../../constants.js'
|
||||
|
||||
const attachCcUser = async (request, reply) => {
|
||||
const user = await getCcUserByFirebaseUid(request.firebaseUser.uid)
|
||||
if (request.auth?.userType !== UserType.CC_USER) {
|
||||
return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
|
||||
}
|
||||
const user = await getCcUserById(request.auth.userId)
|
||||
if (!user) return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
|
||||
request.ccUser = user
|
||||
}
|
||||
|
||||
@@ -1,25 +1,134 @@
|
||||
import { authenticate } from '../../plugins/auth.js'
|
||||
import { getOrCreateCustomer, getCustomerByFirebaseUid, updateCustomerDisplayName } from '../../services/customer.service.js'
|
||||
import { getCustomerById, updateCustomerDisplayName } from '../../services/customer.service.js'
|
||||
import {
|
||||
completeCustomerPhoneSignIn,
|
||||
signInWithGoogle,
|
||||
signInWithApple,
|
||||
} from '../../services/auth.service.js'
|
||||
import { requestOtp, verifyOtp } from '../../services/otp.service.js'
|
||||
import { UserType } from '../../constants.js'
|
||||
|
||||
const extractDeviceInfo = (request) => ({
|
||||
user_agent: request.headers['user-agent'] || null,
|
||||
ip: request.ip || null,
|
||||
})
|
||||
|
||||
const sendAuthError = (reply, err) => reply.code(err.statusCode || 500).send({
|
||||
success: false,
|
||||
error: { code: err.code || 'INTERNAL', message: err.message },
|
||||
})
|
||||
|
||||
export const clientAuthRoutes = async (app) => {
|
||||
app.post('/verify', { preHandler: authenticate }, async (request, reply) => {
|
||||
const { uid, phone_number, name } = request.firebaseUser
|
||||
const customer = await getOrCreateCustomer({
|
||||
firebase_uid: uid,
|
||||
phone: phone_number || null,
|
||||
display_name: name || null,
|
||||
})
|
||||
return reply.send({ success: true, data: customer })
|
||||
// --- Phone OTP ---
|
||||
|
||||
app.post('/otp/request', async (request, reply) => {
|
||||
const { phone, channel } = request.body || {}
|
||||
try {
|
||||
const result = await requestOtp({
|
||||
phone,
|
||||
userType: UserType.CUSTOMER,
|
||||
ipAddress: request.ip,
|
||||
channel,
|
||||
})
|
||||
return reply.send({ success: true, data: result })
|
||||
} catch (err) {
|
||||
return sendAuthError(reply, err)
|
||||
}
|
||||
})
|
||||
|
||||
app.patch('/profile', { preHandler: authenticate }, async (request, reply) => {
|
||||
const customer = await getCustomerByFirebaseUid(request.firebaseUser.uid)
|
||||
app.post('/otp/verify', async (request, reply) => {
|
||||
const { otp_request_id, code, anonymous_customer_id } = request.body || {}
|
||||
try {
|
||||
const { phone, user_type } = await verifyOtp({ otpRequestId: otp_request_id, code })
|
||||
if (user_type !== UserType.CUSTOMER) {
|
||||
return reply.code(400).send({
|
||||
success: false,
|
||||
error: { code: 'WRONG_FLOW', message: 'This OTP was issued for a different user type' },
|
||||
})
|
||||
}
|
||||
const { tokens, profile } = await completeCustomerPhoneSignIn({
|
||||
phone,
|
||||
anonymousCustomerId: anonymous_customer_id || null,
|
||||
deviceInfo: extractDeviceInfo(request),
|
||||
})
|
||||
return reply.send({ success: true, data: { ...tokens, profile } })
|
||||
} catch (err) {
|
||||
return sendAuthError(reply, err)
|
||||
}
|
||||
})
|
||||
|
||||
// --- Google ---
|
||||
|
||||
app.post('/google', async (request, reply) => {
|
||||
const { id_token, anonymous_customer_id } = request.body || {}
|
||||
if (!id_token) {
|
||||
return reply.code(422).send({
|
||||
success: false,
|
||||
error: { code: 'VALIDATION_ERROR', message: 'id_token is required' },
|
||||
})
|
||||
}
|
||||
try {
|
||||
const { tokens, profile } = await signInWithGoogle({
|
||||
idToken: id_token,
|
||||
anonymousCustomerId: anonymous_customer_id || null,
|
||||
deviceInfo: extractDeviceInfo(request),
|
||||
})
|
||||
return reply.send({ success: true, data: { ...tokens, profile } })
|
||||
} catch (err) {
|
||||
return sendAuthError(reply, err)
|
||||
}
|
||||
})
|
||||
|
||||
// --- Apple ---
|
||||
|
||||
app.post('/apple', async (request, reply) => {
|
||||
const { id_token, anonymous_customer_id } = request.body || {}
|
||||
if (!id_token) {
|
||||
return reply.code(422).send({
|
||||
success: false,
|
||||
error: { code: 'VALIDATION_ERROR', message: 'id_token is required' },
|
||||
})
|
||||
}
|
||||
try {
|
||||
const { tokens, profile } = await signInWithApple({
|
||||
idToken: id_token,
|
||||
anonymousCustomerId: anonymous_customer_id || null,
|
||||
deviceInfo: extractDeviceInfo(request),
|
||||
})
|
||||
return reply.send({ success: true, data: { ...tokens, profile } })
|
||||
} catch (err) {
|
||||
return sendAuthError(reply, err)
|
||||
}
|
||||
})
|
||||
|
||||
// --- Current user profile ---
|
||||
|
||||
app.get('/me', { preHandler: authenticate }, async (request, reply) => {
|
||||
if (request.auth.userType !== UserType.CUSTOMER) {
|
||||
return reply.code(403).send({
|
||||
success: false,
|
||||
error: { code: 'FORBIDDEN', message: 'Customer account required' },
|
||||
})
|
||||
}
|
||||
const customer = await getCustomerById(request.auth.userId)
|
||||
if (!customer) {
|
||||
return reply.code(404).send({
|
||||
success: false,
|
||||
error: { code: 'NOT_FOUND', message: 'Customer account not found' },
|
||||
})
|
||||
}
|
||||
return reply.send({ success: true, data: customer })
|
||||
})
|
||||
|
||||
// --- Update display name ---
|
||||
|
||||
app.patch('/profile', { preHandler: authenticate }, async (request, reply) => {
|
||||
if (request.auth.userType !== UserType.CUSTOMER) {
|
||||
return reply.code(403).send({
|
||||
success: false,
|
||||
error: { code: 'FORBIDDEN', message: 'Customer account required' },
|
||||
})
|
||||
}
|
||||
const { display_name } = request.body || {}
|
||||
if (!display_name || typeof display_name !== 'string' || display_name.trim().length === 0) {
|
||||
return reply.code(422).send({
|
||||
@@ -27,7 +136,7 @@ export const clientAuthRoutes = async (app) => {
|
||||
error: { code: 'VALIDATION_ERROR', message: 'display_name is required' },
|
||||
})
|
||||
}
|
||||
const updated = await updateCustomerDisplayName(customer.id, display_name.trim())
|
||||
const updated = await updateCustomerDisplayName(request.auth.userId, display_name.trim())
|
||||
return reply.send({ success: true, data: updated })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
import { authenticate } from '../../plugins/auth.js'
|
||||
import { getCustomerByFirebaseUid } from '../../services/customer.service.js'
|
||||
import { getCustomerById } from '../../services/customer.service.js'
|
||||
import { createPairingRequest, cancelPairingRequest } from '../../services/pairing.service.js'
|
||||
import { getActiveSessionByCustomer, getActiveSessionByCustomerWithUnread, endSession, getCustomerHistory } from '../../services/session.service.js'
|
||||
import { getPricingForCustomer, isValidTier, isCustomerEligibleForFreeTrial, getFreeTrial } from '../../services/pricing.service.js'
|
||||
import { requestExtension } from '../../services/extension.service.js'
|
||||
import { EndedBy, TopicSensitivity } from '../../constants.js'
|
||||
import { EndedBy, TopicSensitivity, UserType } from '../../constants.js'
|
||||
|
||||
const resolveCustomer = async (request, reply) => {
|
||||
const customer = await getCustomerByFirebaseUid(request.firebaseUser.uid)
|
||||
if (request.auth?.userType !== UserType.CUSTOMER) {
|
||||
return reply.code(403).send({
|
||||
success: false,
|
||||
error: { code: 'FORBIDDEN', message: 'Customer account required' },
|
||||
})
|
||||
}
|
||||
const customer = await getCustomerById(request.auth.userId)
|
||||
if (!customer) {
|
||||
return reply.code(404).send({
|
||||
success: false,
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
import { authenticate } from '../../plugins/auth.js'
|
||||
import { createAnonymousCustomer, linkCustomerAccount } from '../../services/customer.service.js'
|
||||
|
||||
export const customerRoutes = async (app) => {
|
||||
app.post('/anonymous', { preHandler: authenticate }, async (request, reply) => {
|
||||
const { display_name } = request.body ?? {}
|
||||
if (!display_name?.trim()) {
|
||||
return reply.code(422).send({
|
||||
success: false,
|
||||
error: { code: 'DISPLAY_NAME_REQUIRED', message: 'Display name is required' },
|
||||
})
|
||||
}
|
||||
const firebase_uid = request.firebaseUser.uid
|
||||
const customer = await createAnonymousCustomer({ display_name: display_name.trim(), firebase_uid })
|
||||
return reply.code(201).send({ success: true, data: customer })
|
||||
})
|
||||
|
||||
app.post('/link', { preHandler: authenticate }, async (request, reply) => {
|
||||
const { customer_id } = request.body ?? {}
|
||||
const firebase_uid = request.firebaseUser.uid
|
||||
|
||||
if (!customer_id) {
|
||||
return reply.code(422).send({
|
||||
success: false,
|
||||
error: { code: 'VALIDATION_ERROR', message: 'customer_id is required' },
|
||||
})
|
||||
}
|
||||
|
||||
const customer = await linkCustomerAccount({ customer_id, firebase_uid })
|
||||
return reply.send({ success: true, data: customer })
|
||||
})
|
||||
}
|
||||
@@ -1,44 +1,75 @@
|
||||
import { authenticate } from '../../plugins/auth.js'
|
||||
import { getMitraByFirebaseUid, getMitraByPhone, setMitraFirebaseUid } from '../../services/mitra.service.js'
|
||||
import { getMitraById } from '../../services/mitra.service.js'
|
||||
import { completeMitraPhoneSignIn } from '../../services/auth.service.js'
|
||||
import { requestOtp, verifyOtp } from '../../services/otp.service.js'
|
||||
import { UserType } from '../../constants.js'
|
||||
|
||||
const extractDeviceInfo = (request) => ({
|
||||
user_agent: request.headers['user-agent'] || null,
|
||||
ip: request.ip || null,
|
||||
})
|
||||
|
||||
const sendAuthError = (reply, err) => reply.code(err.statusCode || 500).send({
|
||||
success: false,
|
||||
error: { code: err.code || 'INTERNAL', message: err.message },
|
||||
})
|
||||
|
||||
export const mitraAuthRoutes = async (app) => {
|
||||
app.post('/verify', { preHandler: authenticate }, async (request, reply) => {
|
||||
const { uid, phone_number } = request.firebaseUser
|
||||
|
||||
// First try lookup by firebase_uid (returning user)
|
||||
let mitra = await getMitraByFirebaseUid(uid)
|
||||
|
||||
// First-time login: link firebase_uid to mitra record via phone number
|
||||
if (!mitra && phone_number) {
|
||||
mitra = await getMitraByPhone(phone_number)
|
||||
if (mitra) {
|
||||
await setMitraFirebaseUid(mitra.id, uid)
|
||||
}
|
||||
app.post('/otp/request', async (request, reply) => {
|
||||
const { phone, channel } = request.body || {}
|
||||
try {
|
||||
const result = await requestOtp({
|
||||
phone,
|
||||
userType: UserType.MITRA,
|
||||
ipAddress: request.ip,
|
||||
channel,
|
||||
})
|
||||
return reply.send({ success: true, data: result })
|
||||
} catch (err) {
|
||||
return sendAuthError(reply, err)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/otp/verify', async (request, reply) => {
|
||||
const { otp_request_id, code } = request.body || {}
|
||||
try {
|
||||
const { phone, user_type } = await verifyOtp({ otpRequestId: otp_request_id, code })
|
||||
if (user_type !== UserType.MITRA) {
|
||||
return reply.code(400).send({
|
||||
success: false,
|
||||
error: { code: 'WRONG_FLOW', message: 'This OTP was issued for a different user type' },
|
||||
})
|
||||
}
|
||||
const { tokens, profile } = await completeMitraPhoneSignIn({
|
||||
phone,
|
||||
deviceInfo: extractDeviceInfo(request),
|
||||
})
|
||||
if (!profile.is_active) {
|
||||
return reply.code(403).send({
|
||||
success: false,
|
||||
error: { code: 'ACCOUNT_INACTIVE', message: 'Account is inactive. Contact your administrator.' },
|
||||
})
|
||||
}
|
||||
return reply.send({ success: true, data: { ...tokens, profile } })
|
||||
} catch (err) {
|
||||
return sendAuthError(reply, err)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/me', { preHandler: authenticate }, async (request, reply) => {
|
||||
if (request.auth.userType !== UserType.MITRA) {
|
||||
return reply.code(403).send({
|
||||
success: false,
|
||||
error: { code: 'FORBIDDEN', message: 'Mitra account required' },
|
||||
})
|
||||
}
|
||||
const mitra = await getMitraById(request.auth.userId)
|
||||
if (!mitra) {
|
||||
return reply.code(404).send({
|
||||
success: false,
|
||||
error: { code: 'ACCOUNT_NOT_FOUND', message: 'Account not found. Contact your administrator.' },
|
||||
error: { code: 'NOT_FOUND', message: 'Mitra account not found' },
|
||||
})
|
||||
}
|
||||
|
||||
if (!mitra.is_active) {
|
||||
return reply.code(403).send({
|
||||
success: false,
|
||||
error: { code: 'ACCOUNT_INACTIVE', message: 'Account is inactive. Contact your administrator.' },
|
||||
})
|
||||
}
|
||||
|
||||
return reply.send({
|
||||
success: true,
|
||||
data: {
|
||||
id: mitra.id,
|
||||
display_name: mitra.display_name,
|
||||
phone: mitra.phone,
|
||||
is_active: mitra.is_active,
|
||||
created_at: mitra.created_at,
|
||||
},
|
||||
})
|
||||
return reply.send({ success: true, data: mitra })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
import { authenticate } from '../../plugins/auth.js'
|
||||
import { getMitraByFirebaseUid } from '../../services/mitra.service.js'
|
||||
import { getMitraById } from '../../services/mitra.service.js'
|
||||
import { acceptPairingRequest, declinePairingRequest, getSessionStatus, getPendingRequestsForMitra } from '../../services/pairing.service.js'
|
||||
import { getActiveSessionsByMitra, getActiveSessionsByMitraWithUnread, endSession, getMitraHistory } from '../../services/session.service.js'
|
||||
import { respondToExtension } from '../../services/extension.service.js'
|
||||
import { EndedBy } from '../../constants.js'
|
||||
import { EndedBy, UserType } from '../../constants.js'
|
||||
|
||||
const resolveMitra = async (request, reply) => {
|
||||
const mitra = await getMitraByFirebaseUid(request.firebaseUser.uid)
|
||||
if (request.auth?.userType !== UserType.MITRA) {
|
||||
return reply.code(403).send({
|
||||
success: false,
|
||||
error: { code: 'FORBIDDEN', message: 'Mitra account required' },
|
||||
})
|
||||
}
|
||||
const mitra = await getMitraById(request.auth.userId)
|
||||
if (!mitra) {
|
||||
return reply.code(404).send({
|
||||
success: false,
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
import { authenticate } from '../../plugins/auth.js'
|
||||
import { getMitraByFirebaseUid } from '../../services/mitra.service.js'
|
||||
import { getMitraById } from '../../services/mitra.service.js'
|
||||
import * as mitraStatusService from '../../services/mitra-status.service.js'
|
||||
import { UserType } from '../../constants.js'
|
||||
|
||||
export const mitraStatusRoutes = async (app) => {
|
||||
// Resolve mitra from Firebase token
|
||||
const resolveMitra = async (request, reply) => {
|
||||
const mitra = await getMitraByFirebaseUid(request.firebaseUser.uid)
|
||||
if (request.auth?.userType !== UserType.MITRA) {
|
||||
return reply.code(403).send({
|
||||
success: false,
|
||||
error: { code: 'FORBIDDEN', message: 'Mitra account required' },
|
||||
})
|
||||
}
|
||||
const mitra = await getMitraById(request.auth.userId)
|
||||
if (!mitra) {
|
||||
return reply.code(404).send({
|
||||
success: false,
|
||||
|
||||
54
backend/src/routes/public/shared.auth.routes.js
Normal file
54
backend/src/routes/public/shared.auth.routes.js
Normal file
@@ -0,0 +1,54 @@
|
||||
import { authenticate } from '../../plugins/auth.js'
|
||||
import {
|
||||
signInAnonymous,
|
||||
refreshTokens,
|
||||
logout,
|
||||
} from '../../services/auth.service.js'
|
||||
|
||||
const extractDeviceInfo = (request) => ({
|
||||
user_agent: request.headers['user-agent'] || null,
|
||||
ip: request.ip || null,
|
||||
})
|
||||
|
||||
const sendAuthError = (reply, err) => reply.code(err.statusCode || 500).send({
|
||||
success: false,
|
||||
error: { code: err.code || 'INTERNAL', message: err.message },
|
||||
})
|
||||
|
||||
export const sharedAuthRoutes = async (app) => {
|
||||
// Issue an anonymous customer session
|
||||
app.post('/anonymous', async (request, reply) => {
|
||||
try {
|
||||
const { tokens, profile } = await signInAnonymous({ deviceInfo: extractDeviceInfo(request) })
|
||||
return reply.code(201).send({ success: true, data: { ...tokens, profile } })
|
||||
} catch (err) {
|
||||
return sendAuthError(reply, err)
|
||||
}
|
||||
})
|
||||
|
||||
// Rotate refresh token
|
||||
app.post('/refresh', async (request, reply) => {
|
||||
const { refresh_token } = request.body || {}
|
||||
if (!refresh_token) {
|
||||
return reply.code(422).send({
|
||||
success: false,
|
||||
error: { code: 'VALIDATION_ERROR', message: 'refresh_token is required' },
|
||||
})
|
||||
}
|
||||
try {
|
||||
const { tokens, profile } = await refreshTokens({
|
||||
refreshToken: refresh_token,
|
||||
deviceInfo: extractDeviceInfo(request),
|
||||
})
|
||||
return reply.send({ success: true, data: { ...tokens, profile } })
|
||||
} catch (err) {
|
||||
return sendAuthError(reply, err)
|
||||
}
|
||||
})
|
||||
|
||||
// Logout — revoke current session
|
||||
app.post('/logout', { preHandler: authenticate }, async (request, reply) => {
|
||||
await logout({ sessionId: request.auth.sessionId })
|
||||
return reply.send({ success: true })
|
||||
})
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
import { authenticate } from '../../plugins/auth.js'
|
||||
import { getCustomerByFirebaseUid } from '../../services/customer.service.js'
|
||||
import { getMitraByFirebaseUid } from '../../services/mitra.service.js'
|
||||
import { getMessages } from '../../services/chat.service.js'
|
||||
import { getSessionClosures } from '../../services/closure.service.js'
|
||||
import { registerDeviceToken } from '../../services/notification.service.js'
|
||||
@@ -11,22 +9,14 @@ import { TopicSensitivity, UserType } from '../../constants.js'
|
||||
const sql = getDb()
|
||||
|
||||
const resolveUser = async (request, reply) => {
|
||||
const customer = await getCustomerByFirebaseUid(request.firebaseUser.uid)
|
||||
if (customer) {
|
||||
request.userType = UserType.CUSTOMER
|
||||
request.userId = customer.id
|
||||
return
|
||||
if (request.auth?.userType !== UserType.CUSTOMER && request.auth?.userType !== UserType.MITRA) {
|
||||
return reply.code(403).send({
|
||||
success: false,
|
||||
error: { code: 'FORBIDDEN', message: 'Customer or mitra account required' },
|
||||
})
|
||||
}
|
||||
const mitra = await getMitraByFirebaseUid(request.firebaseUser.uid)
|
||||
if (mitra) {
|
||||
request.userType = UserType.MITRA
|
||||
request.userId = mitra.id
|
||||
return
|
||||
}
|
||||
return reply.code(404).send({
|
||||
success: false,
|
||||
error: { code: 'ACCOUNT_NOT_FOUND', message: 'Account not found' },
|
||||
})
|
||||
request.userType = request.auth.userType
|
||||
request.userId = request.auth.userId
|
||||
}
|
||||
|
||||
// Verify session belongs to the authenticated user
|
||||
|
||||
235
backend/src/services/auth.service.js
Normal file
235
backend/src/services/auth.service.js
Normal file
@@ -0,0 +1,235 @@
|
||||
import crypto from 'node:crypto'
|
||||
import {
|
||||
getCustomerById,
|
||||
getCustomerByPhone,
|
||||
getCustomerByGoogleSub,
|
||||
getCustomerByAppleSub,
|
||||
createAnonymousCustomerV2,
|
||||
createCustomerWithIdentity,
|
||||
upgradeCustomerIdentity,
|
||||
} from './customer.service.js'
|
||||
import {
|
||||
getMitraByPhone,
|
||||
getMitraById,
|
||||
createMitra,
|
||||
} from './mitra.service.js'
|
||||
import {
|
||||
getCcUserByEmail,
|
||||
getCcUserById,
|
||||
incrementCcUserFailedLogin,
|
||||
resetCcUserFailedLogin,
|
||||
} from './cc-user.service.js'
|
||||
import { verifyGoogleIdToken, verifyAppleIdToken } from './social-identity.service.js'
|
||||
import { verifyPassword } from './password.service.js'
|
||||
import { issueTokens, refreshTokens as rotateRefresh, revokeSession } from './token.service.js'
|
||||
import { getCcLoginLockoutConfig } from './config.service.js'
|
||||
import { UserType } from '../constants.js'
|
||||
|
||||
const generateAnonymousDisplayName = () => {
|
||||
const n = crypto.randomInt(1000, 10000)
|
||||
return `Teman Anonim #${n}`
|
||||
}
|
||||
|
||||
export class AuthError extends Error {
|
||||
constructor(message, code, statusCode) {
|
||||
super(message)
|
||||
this.code = code
|
||||
this.statusCode = statusCode
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeIdentityConflict = async ({ existing, anonymousCustomerId }) => {
|
||||
// If an authenticated identity is already linked to a DIFFERENT customer,
|
||||
// reject. Merge is deferred per PRD.
|
||||
if (existing && anonymousCustomerId && existing.id !== anonymousCustomerId) {
|
||||
throw new AuthError(
|
||||
'This account is already linked to another session. Please log out first.',
|
||||
'IDENTITY_ALREADY_LINKED', 409,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Anonymous ---
|
||||
|
||||
export const signInAnonymous = async ({ deviceInfo } = {}) => {
|
||||
const customer = await createAnonymousCustomerV2({
|
||||
display_name: generateAnonymousDisplayName(),
|
||||
})
|
||||
const tokens = await issueTokens({
|
||||
userType: UserType.CUSTOMER,
|
||||
userId: customer.id,
|
||||
deviceInfo,
|
||||
})
|
||||
return { tokens, profile: customer }
|
||||
}
|
||||
|
||||
// --- Phone OTP — Customer ---
|
||||
|
||||
export const completeCustomerPhoneSignIn = async ({ phone, anonymousCustomerId, deviceInfo }) => {
|
||||
const existing = await getCustomerByPhone(phone)
|
||||
await normalizeIdentityConflict({ existing, anonymousCustomerId })
|
||||
|
||||
let customer
|
||||
if (existing) {
|
||||
customer = existing
|
||||
} else if (anonymousCustomerId) {
|
||||
customer = await upgradeCustomerIdentity(anonymousCustomerId, { phone })
|
||||
} else {
|
||||
customer = await createCustomerWithIdentity({ phone, display_name: null })
|
||||
}
|
||||
|
||||
const tokens = await issueTokens({
|
||||
userType: UserType.CUSTOMER,
|
||||
userId: customer.id,
|
||||
deviceInfo,
|
||||
})
|
||||
return { tokens, profile: customer }
|
||||
}
|
||||
|
||||
// --- Phone OTP — Mitra ---
|
||||
|
||||
export const completeMitraPhoneSignIn = async ({ phone, deviceInfo }) => {
|
||||
let mitra = await getMitraByPhone(phone)
|
||||
if (!mitra) {
|
||||
mitra = await createMitra({ phone, display_name: phone })
|
||||
}
|
||||
const tokens = await issueTokens({
|
||||
userType: UserType.MITRA,
|
||||
userId: mitra.id,
|
||||
deviceInfo,
|
||||
})
|
||||
return { tokens, profile: mitra }
|
||||
}
|
||||
|
||||
// --- Google (customer only) ---
|
||||
|
||||
export const signInWithGoogle = async ({ idToken, anonymousCustomerId, deviceInfo }) => {
|
||||
const google = await verifyGoogleIdToken(idToken)
|
||||
const existing = await getCustomerByGoogleSub(google.sub)
|
||||
await normalizeIdentityConflict({ existing, anonymousCustomerId })
|
||||
|
||||
let customer
|
||||
if (existing) {
|
||||
customer = existing
|
||||
} else if (anonymousCustomerId) {
|
||||
customer = await upgradeCustomerIdentity(anonymousCustomerId, {
|
||||
google_sub: google.sub,
|
||||
email: google.email,
|
||||
display_name: google.name,
|
||||
})
|
||||
} else {
|
||||
customer = await createCustomerWithIdentity({
|
||||
google_sub: google.sub,
|
||||
email: google.email,
|
||||
display_name: google.name,
|
||||
})
|
||||
}
|
||||
|
||||
const tokens = await issueTokens({
|
||||
userType: UserType.CUSTOMER,
|
||||
userId: customer.id,
|
||||
deviceInfo,
|
||||
})
|
||||
return { tokens, profile: customer }
|
||||
}
|
||||
|
||||
// --- Apple (customer only) ---
|
||||
|
||||
export const signInWithApple = async ({ idToken, anonymousCustomerId, deviceInfo }) => {
|
||||
const apple = await verifyAppleIdToken(idToken)
|
||||
const existing = await getCustomerByAppleSub(apple.sub)
|
||||
await normalizeIdentityConflict({ existing, anonymousCustomerId })
|
||||
|
||||
let customer
|
||||
if (existing) {
|
||||
customer = existing
|
||||
} else if (anonymousCustomerId) {
|
||||
customer = await upgradeCustomerIdentity(anonymousCustomerId, {
|
||||
apple_sub: apple.sub,
|
||||
email: apple.email,
|
||||
})
|
||||
} else {
|
||||
customer = await createCustomerWithIdentity({
|
||||
apple_sub: apple.sub,
|
||||
email: apple.email,
|
||||
display_name: null,
|
||||
})
|
||||
}
|
||||
|
||||
const tokens = await issueTokens({
|
||||
userType: UserType.CUSTOMER,
|
||||
userId: customer.id,
|
||||
deviceInfo,
|
||||
})
|
||||
return { tokens, profile: customer }
|
||||
}
|
||||
|
||||
// --- Control center email/password ---
|
||||
|
||||
export const signInCcUser = async ({ email, password, deviceInfo }) => {
|
||||
const user = await getCcUserByEmail(email)
|
||||
// Constant-time response — same branch for "not found" vs "wrong password" OR lockout
|
||||
if (!user) {
|
||||
throw new AuthError('Invalid credentials', 'INVALID_CREDENTIALS', 401)
|
||||
}
|
||||
|
||||
// Lockout check
|
||||
if (user.lockout_until && new Date(user.lockout_until) > new Date()) {
|
||||
throw new AuthError(
|
||||
`Account locked until ${user.lockout_until}. Try again later.`,
|
||||
'ACCOUNT_LOCKED', 423,
|
||||
)
|
||||
}
|
||||
|
||||
const ok = await verifyPassword(password, user.password_hash)
|
||||
if (!ok) {
|
||||
const { max_attempts, lockout_minutes } = await getCcLoginLockoutConfig()
|
||||
await incrementCcUserFailedLogin(user.id, lockout_minutes, max_attempts)
|
||||
throw new AuthError('Invalid credentials', 'INVALID_CREDENTIALS', 401)
|
||||
}
|
||||
|
||||
await resetCcUserFailedLogin(user.id)
|
||||
|
||||
const tokens = await issueTokens({
|
||||
userType: UserType.CC_USER,
|
||||
userId: user.id,
|
||||
deviceInfo,
|
||||
})
|
||||
return {
|
||||
tokens,
|
||||
profile: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
display_name: user.display_name,
|
||||
role: user.role,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// --- Refresh ---
|
||||
|
||||
export const refreshTokens = async ({ refreshToken, deviceInfo }) => {
|
||||
const result = await rotateRefresh({ refreshToken, deviceInfo })
|
||||
let profile = null
|
||||
if (result.user_type === UserType.CUSTOMER) {
|
||||
profile = await getCustomerById(result.user_id)
|
||||
} else if (result.user_type === UserType.MITRA) {
|
||||
profile = await getMitraById(result.user_id)
|
||||
} else if (result.user_type === UserType.CC_USER) {
|
||||
const ccUser = await getCcUserById(result.user_id)
|
||||
profile = ccUser ? {
|
||||
id: ccUser.id,
|
||||
email: ccUser.email,
|
||||
display_name: ccUser.display_name,
|
||||
role: ccUser.role,
|
||||
} : null
|
||||
}
|
||||
return { tokens: result, profile }
|
||||
}
|
||||
|
||||
// --- Logout ---
|
||||
|
||||
export const logout = async ({ sessionId }) => {
|
||||
if (!sessionId) return
|
||||
await revokeSession(sessionId)
|
||||
}
|
||||
@@ -2,14 +2,16 @@ import { getDb } from '../db/client.js'
|
||||
|
||||
const sql = getDb()
|
||||
|
||||
export const getCcUserByFirebaseUid = async (firebase_uid) => {
|
||||
|
||||
export const getCcUserById = async (id) => {
|
||||
const [user] = await sql`
|
||||
SELECT
|
||||
u.id, u.email, u.display_name, u.created_at,
|
||||
u.password_hash, u.failed_login_count, u.lockout_until,
|
||||
r.id as role_id, r.name as role_name, r.permissions
|
||||
FROM control_center_users u
|
||||
JOIN roles r ON r.id = u.role_id
|
||||
WHERE u.firebase_uid = ${firebase_uid}
|
||||
WHERE u.id = ${id}
|
||||
`
|
||||
if (!user) return null
|
||||
return {
|
||||
@@ -17,20 +19,77 @@ export const getCcUserByFirebaseUid = async (firebase_uid) => {
|
||||
email: user.email,
|
||||
display_name: user.display_name,
|
||||
created_at: user.created_at,
|
||||
password_hash: user.password_hash,
|
||||
failed_login_count: user.failed_login_count,
|
||||
lockout_until: user.lockout_until,
|
||||
role: { id: user.role_id, name: user.role_name, permissions: user.permissions },
|
||||
}
|
||||
}
|
||||
|
||||
export const createCcUser = async ({ firebase_uid, email, display_name, role_id }) => {
|
||||
export const getCcUserByEmail = async (email) => {
|
||||
const [user] = await sql`
|
||||
INSERT INTO control_center_users (firebase_uid, email, display_name, role_id)
|
||||
VALUES (${firebase_uid}, ${email}, ${display_name}, ${role_id})
|
||||
SELECT
|
||||
u.id, u.email, u.display_name, u.created_at,
|
||||
u.password_hash, u.failed_login_count, u.lockout_until,
|
||||
r.id as role_id, r.name as role_name, r.permissions
|
||||
FROM control_center_users u
|
||||
JOIN roles r ON r.id = u.role_id
|
||||
WHERE u.email = ${email}
|
||||
`
|
||||
if (!user) return null
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
display_name: user.display_name,
|
||||
created_at: user.created_at,
|
||||
password_hash: user.password_hash,
|
||||
failed_login_count: user.failed_login_count,
|
||||
lockout_until: user.lockout_until,
|
||||
role: { id: user.role_id, name: user.role_name, permissions: user.permissions },
|
||||
}
|
||||
}
|
||||
|
||||
export const createCcUserWithPassword = async ({ email, display_name, role_id, password_hash }) => {
|
||||
const [user] = await sql`
|
||||
INSERT INTO control_center_users (email, display_name, role_id, password_hash)
|
||||
VALUES (${email}, ${display_name}, ${role_id}, ${password_hash})
|
||||
RETURNING id, email, display_name, role_id, created_at
|
||||
`
|
||||
const [role] = await sql`SELECT id, name FROM roles WHERE id = ${role_id}`
|
||||
return { ...user, role }
|
||||
}
|
||||
|
||||
export const updateCcUserPasswordHash = async (id, password_hash) => {
|
||||
await sql`
|
||||
UPDATE control_center_users SET password_hash = ${password_hash}
|
||||
WHERE id = ${id}
|
||||
`
|
||||
}
|
||||
|
||||
export const incrementCcUserFailedLogin = async (id, lockoutMinutes, maxAttempts) => {
|
||||
// Atomic: increment counter; if reaches maxAttempts set lockout_until
|
||||
const [row] = await sql`
|
||||
UPDATE control_center_users
|
||||
SET failed_login_count = failed_login_count + 1,
|
||||
lockout_until = CASE
|
||||
WHEN failed_login_count + 1 >= ${maxAttempts}
|
||||
THEN NOW() + (${lockoutMinutes} || ' minutes')::interval
|
||||
ELSE lockout_until
|
||||
END
|
||||
WHERE id = ${id}
|
||||
RETURNING failed_login_count, lockout_until
|
||||
`
|
||||
return row
|
||||
}
|
||||
|
||||
export const resetCcUserFailedLogin = async (id) => {
|
||||
await sql`
|
||||
UPDATE control_center_users
|
||||
SET failed_login_count = 0, lockout_until = NULL
|
||||
WHERE id = ${id}
|
||||
`
|
||||
}
|
||||
|
||||
export const listCcUsers = async ({ page = 1, limit = 20 }) => {
|
||||
const offset = (page - 1) * limit
|
||||
const items = await sql`
|
||||
|
||||
@@ -2,81 +2,6 @@ import { getDb } from '../db/client.js'
|
||||
|
||||
const sql = getDb()
|
||||
|
||||
export const createAnonymousCustomer = async ({ display_name, firebase_uid }) => {
|
||||
// Return existing customer if already linked to this Firebase UID
|
||||
const [existing] = await sql`
|
||||
SELECT id, display_name, is_anonymous, created_at
|
||||
FROM customers WHERE firebase_uid = ${firebase_uid}
|
||||
`
|
||||
if (existing) return existing
|
||||
|
||||
const [customer] = await sql`
|
||||
INSERT INTO customers (display_name, is_anonymous, firebase_uid)
|
||||
VALUES (${display_name}, true, ${firebase_uid})
|
||||
RETURNING id, display_name, is_anonymous, created_at
|
||||
`
|
||||
return customer
|
||||
}
|
||||
|
||||
export const linkCustomerAccount = async ({ customer_id, firebase_uid }) => {
|
||||
const [existing] = await sql`
|
||||
SELECT id, firebase_uid FROM customers WHERE id = ${customer_id}
|
||||
`
|
||||
if (!existing) throw Object.assign(new Error('Customer not found'), { code: 'NOT_FOUND', statusCode: 404 })
|
||||
if (existing.firebase_uid) throw Object.assign(new Error('Account already linked'), { code: 'ALREADY_REGISTERED', statusCode: 409 })
|
||||
|
||||
// Also fetch phone from firebase_uid if exists in another customer record for uniqueness
|
||||
const [firebaseLinked] = await sql`
|
||||
SELECT id FROM customers WHERE firebase_uid = ${firebase_uid}
|
||||
`
|
||||
if (firebaseLinked) throw Object.assign(new Error('Account already linked'), { code: 'ALREADY_REGISTERED', statusCode: 409 })
|
||||
|
||||
const [updated] = await sql`
|
||||
UPDATE customers
|
||||
SET firebase_uid = ${firebase_uid}, is_anonymous = false
|
||||
WHERE id = ${customer_id}
|
||||
RETURNING id, display_name, is_anonymous, phone, created_at
|
||||
`
|
||||
return updated
|
||||
}
|
||||
|
||||
export const getCustomerByFirebaseUid = async (firebase_uid) => {
|
||||
const [customer] = await sql`
|
||||
SELECT id, display_name, is_anonymous, phone, created_at
|
||||
FROM customers
|
||||
WHERE firebase_uid = ${firebase_uid}
|
||||
`
|
||||
return customer
|
||||
}
|
||||
|
||||
export const getOrCreateCustomer = async ({ firebase_uid, phone, display_name }) => {
|
||||
// Return existing customer if already linked to this Firebase UID
|
||||
const existing = await getCustomerByFirebaseUid(firebase_uid)
|
||||
if (existing) return existing
|
||||
|
||||
// Check if a customer with this phone already exists (re-login with new Firebase UID)
|
||||
if (phone) {
|
||||
const [byPhone] = await sql`
|
||||
SELECT id, display_name, is_anonymous, phone, created_at
|
||||
FROM customers WHERE phone = ${phone}
|
||||
`
|
||||
if (byPhone) {
|
||||
// Link the new Firebase UID to the existing phone-based customer
|
||||
await sql`UPDATE customers SET firebase_uid = ${firebase_uid} WHERE id = ${byPhone.id}`
|
||||
return { ...byPhone, firebase_uid }
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-create a registered (non-anonymous) customer for phone/social login
|
||||
// display_name is null — user must set it on first login
|
||||
const [customer] = await sql`
|
||||
INSERT INTO customers (firebase_uid, phone, display_name, is_anonymous)
|
||||
VALUES (${firebase_uid}, ${phone || null}, ${display_name || null}, false)
|
||||
RETURNING id, display_name, is_anonymous, phone, created_at
|
||||
`
|
||||
return customer
|
||||
}
|
||||
|
||||
export const updateCustomerDisplayName = async (customerId, displayName) => {
|
||||
const [customer] = await sql`
|
||||
UPDATE customers SET display_name = ${displayName}
|
||||
@@ -85,3 +10,72 @@ export const updateCustomerDisplayName = async (customerId, displayName) => {
|
||||
`
|
||||
return customer
|
||||
}
|
||||
|
||||
// --- Phase 3.4: Self-Managed Auth ---
|
||||
|
||||
const CUSTOMER_SELECT = sql`id, display_name, is_anonymous, phone, email, google_sub, apple_sub, created_at`
|
||||
|
||||
export const getCustomerById = async (id) => {
|
||||
const [row] = await sql`SELECT ${CUSTOMER_SELECT} FROM customers WHERE id = ${id}`
|
||||
return row
|
||||
}
|
||||
|
||||
export const getCustomerByPhone = async (phone) => {
|
||||
const [row] = await sql`SELECT ${CUSTOMER_SELECT} FROM customers WHERE phone = ${phone}`
|
||||
return row
|
||||
}
|
||||
|
||||
export const getCustomerByGoogleSub = async (googleSub) => {
|
||||
const [row] = await sql`SELECT ${CUSTOMER_SELECT} FROM customers WHERE google_sub = ${googleSub}`
|
||||
return row
|
||||
}
|
||||
|
||||
export const getCustomerByAppleSub = async (appleSub) => {
|
||||
const [row] = await sql`SELECT ${CUSTOMER_SELECT} FROM customers WHERE apple_sub = ${appleSub}`
|
||||
return row
|
||||
}
|
||||
|
||||
export const createAnonymousCustomerV2 = async ({ display_name }) => {
|
||||
const [row] = await sql`
|
||||
INSERT INTO customers (display_name, is_anonymous)
|
||||
VALUES (${display_name}, true)
|
||||
RETURNING ${CUSTOMER_SELECT}
|
||||
`
|
||||
return row
|
||||
}
|
||||
|
||||
export const createCustomerWithIdentity = async ({
|
||||
display_name,
|
||||
phone = null,
|
||||
email = null,
|
||||
google_sub = null,
|
||||
apple_sub = null,
|
||||
}) => {
|
||||
const [row] = await sql`
|
||||
INSERT INTO customers (display_name, is_anonymous, phone, email, google_sub, apple_sub)
|
||||
VALUES (${display_name}, false, ${phone}, ${email}, ${google_sub}, ${apple_sub})
|
||||
RETURNING ${CUSTOMER_SELECT}
|
||||
`
|
||||
return row
|
||||
}
|
||||
|
||||
export const upgradeCustomerIdentity = async (customerId, {
|
||||
phone,
|
||||
email,
|
||||
google_sub,
|
||||
apple_sub,
|
||||
display_name,
|
||||
}) => {
|
||||
const [row] = await sql`
|
||||
UPDATE customers SET
|
||||
is_anonymous = false,
|
||||
phone = COALESCE(${phone ?? null}, phone),
|
||||
email = COALESCE(${email ?? null}, email),
|
||||
google_sub = COALESCE(${google_sub ?? null}, google_sub),
|
||||
apple_sub = COALESCE(${apple_sub ?? null}, apple_sub),
|
||||
display_name = COALESCE(${display_name ?? null}, display_name)
|
||||
WHERE id = ${customerId}
|
||||
RETURNING ${CUSTOMER_SELECT}
|
||||
`
|
||||
return row
|
||||
}
|
||||
|
||||
@@ -2,28 +2,22 @@ import { getDb } from '../db/client.js'
|
||||
|
||||
const sql = getDb()
|
||||
|
||||
export const getMitraByFirebaseUid = async (firebase_uid) => {
|
||||
const [mitra] = await sql`
|
||||
SELECT id, display_name, phone, is_active, created_at
|
||||
FROM mitras
|
||||
WHERE firebase_uid = ${firebase_uid}
|
||||
`
|
||||
return mitra
|
||||
}
|
||||
|
||||
export const getMitraByPhone = async (phone) => {
|
||||
const [mitra] = await sql`
|
||||
SELECT id, display_name, phone, is_active, firebase_uid, created_at
|
||||
SELECT id, display_name, phone, is_active, created_at
|
||||
FROM mitras
|
||||
WHERE phone = ${phone}
|
||||
`
|
||||
return mitra
|
||||
}
|
||||
|
||||
export const setMitraFirebaseUid = async (id, firebase_uid) => {
|
||||
await sql`
|
||||
UPDATE mitras SET firebase_uid = ${firebase_uid} WHERE id = ${id}
|
||||
export const getMitraById = async (id) => {
|
||||
const [mitra] = await sql`
|
||||
SELECT id, display_name, phone, is_active, created_at
|
||||
FROM mitras
|
||||
WHERE id = ${id}
|
||||
`
|
||||
return mitra
|
||||
}
|
||||
|
||||
export const createMitra = async ({ phone, display_name }) => {
|
||||
|
||||
Reference in New Issue
Block a user