updates to saving settings
This commit is contained in:
138
map/app/controllers/authController.js
Normal file
138
map/app/controllers/authController.js
Normal file
@@ -0,0 +1,138 @@
|
||||
const nocodbService = require('../services/nocodb');
|
||||
const logger = require('../utils/logger');
|
||||
const { extractId } = require('../utils/helpers');
|
||||
|
||||
class AuthController {
|
||||
async login(req, res) {
|
||||
try {
|
||||
const { email, password } = req.body;
|
||||
|
||||
// Validate input
|
||||
if (!email || !password) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Email and password are required'
|
||||
});
|
||||
}
|
||||
|
||||
// Validate email format
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Invalid email format'
|
||||
});
|
||||
}
|
||||
|
||||
logger.info('Login attempt:', {
|
||||
email,
|
||||
ip: req.ip,
|
||||
cfIp: req.headers['cf-connecting-ip'],
|
||||
userAgent: req.headers['user-agent']
|
||||
});
|
||||
|
||||
// Fetch user from NocoDB
|
||||
const user = await nocodbService.getUserByEmail(email);
|
||||
|
||||
if (!user) {
|
||||
logger.warn(`No user found with email: ${email}`);
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
error: 'Invalid email or password'
|
||||
});
|
||||
}
|
||||
|
||||
// Check password
|
||||
if (user.Password !== password && user.password !== password) {
|
||||
logger.warn(`Invalid password for email: ${email}`);
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
error: 'Invalid email or password'
|
||||
});
|
||||
}
|
||||
|
||||
// Update last login time
|
||||
try {
|
||||
const userId = extractId(user);
|
||||
await nocodbService.update(
|
||||
require('../config').nocodb.loginSheetId,
|
||||
userId,
|
||||
{
|
||||
'Last Login': new Date().toISOString(),
|
||||
last_login: new Date().toISOString()
|
||||
}
|
||||
);
|
||||
} catch (updateError) {
|
||||
logger.warn('Failed to update last login time:', updateError.message);
|
||||
// Don't fail the login
|
||||
}
|
||||
|
||||
// Set session
|
||||
req.session.authenticated = true;
|
||||
req.session.userEmail = email;
|
||||
req.session.userName = user.Name || user.name || email;
|
||||
req.session.isAdmin = user.Admin === true || user.Admin === 1 ||
|
||||
user.admin === true || user.admin === 1;
|
||||
req.session.userId = extractId(user);
|
||||
|
||||
// Force session save
|
||||
req.session.save((err) => {
|
||||
if (err) {
|
||||
logger.error('Session save error:', err);
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
error: 'Session error. Please try again.'
|
||||
});
|
||||
}
|
||||
|
||||
logger.info(`User authenticated: ${email}, Admin: ${req.session.isAdmin}`);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Login successful',
|
||||
user: {
|
||||
email: email,
|
||||
name: req.session.userName,
|
||||
isAdmin: req.session.isAdmin
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Login error:', error.message);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: 'Authentication service error. Please try again later.'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async logout(req, res) {
|
||||
req.session.destroy((err) => {
|
||||
if (err) {
|
||||
logger.error('Logout error:', err);
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
error: 'Logout failed'
|
||||
});
|
||||
}
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Logged out successfully'
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async check(req, res) {
|
||||
res.json({
|
||||
authenticated: req.session?.authenticated || false,
|
||||
user: req.session?.authenticated ? {
|
||||
email: req.session.userEmail,
|
||||
name: req.session.userName,
|
||||
isAdmin: req.session.isAdmin || false
|
||||
} : null
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new AuthController();
|
||||
257
map/app/controllers/locationsController.js
Normal file
257
map/app/controllers/locationsController.js
Normal file
@@ -0,0 +1,257 @@
|
||||
const nocodbService = require('../services/nocodb');
|
||||
const logger = require('../utils/logger');
|
||||
const config = require('../config');
|
||||
const {
|
||||
syncGeoFields,
|
||||
validateCoordinates,
|
||||
checkBounds,
|
||||
extractId
|
||||
} = require('../utils/helpers');
|
||||
|
||||
class LocationsController {
|
||||
async getAll(req, res) {
|
||||
try {
|
||||
const { limit = 1000, offset = 0, where } = req.query;
|
||||
|
||||
const params = { limit, offset };
|
||||
if (where) params.where = where;
|
||||
|
||||
logger.info('Fetching locations from NocoDB');
|
||||
|
||||
const response = await nocodbService.getLocations(params);
|
||||
const locations = response.list || [];
|
||||
|
||||
// Process and validate locations
|
||||
const validLocations = locations.filter(loc => {
|
||||
loc = syncGeoFields(loc);
|
||||
|
||||
if (loc.latitude && loc.longitude) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Try to parse from geodata column
|
||||
if (loc.geodata && typeof loc.geodata === 'string') {
|
||||
const parts = loc.geodata.split(';');
|
||||
if (parts.length === 2) {
|
||||
loc.latitude = parseFloat(parts[0]);
|
||||
loc.longitude = parseFloat(parts[1]);
|
||||
return !isNaN(loc.latitude) && !isNaN(loc.longitude);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
logger.info(`Retrieved ${validLocations.length} valid locations out of ${locations.length} total`);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
count: validLocations.length,
|
||||
total: response.pageInfo?.totalRows || validLocations.length,
|
||||
locations: validLocations
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Error fetching locations:', error.message);
|
||||
|
||||
if (error.response) {
|
||||
res.status(error.response.status).json({
|
||||
success: false,
|
||||
error: 'Failed to fetch data from NocoDB',
|
||||
details: error.response.data
|
||||
});
|
||||
} else if (error.code === 'ECONNABORTED') {
|
||||
res.status(504).json({
|
||||
success: false,
|
||||
error: 'Request timeout'
|
||||
});
|
||||
} else {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: 'Internal server error'
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async getById(req, res) {
|
||||
try {
|
||||
const location = await nocodbService.getById(
|
||||
config.nocodb.tableId,
|
||||
req.params.id
|
||||
);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
location
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
logger.error(`Error fetching location ${req.params.id}:`, error.message);
|
||||
res.status(error.response?.status || 500).json({
|
||||
success: false,
|
||||
error: 'Failed to fetch location'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async create(req, res) {
|
||||
try {
|
||||
let locationData = { ...req.body };
|
||||
locationData = syncGeoFields(locationData);
|
||||
|
||||
const { latitude, longitude, ...additionalData } = locationData;
|
||||
|
||||
// Validate coordinates
|
||||
const validation = validateCoordinates(latitude, longitude);
|
||||
if (!validation.valid) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: validation.error
|
||||
});
|
||||
}
|
||||
|
||||
// Check bounds if configured
|
||||
if (config.map.bounds) {
|
||||
if (!checkBounds(validation.latitude, validation.longitude, config.map.bounds)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Location is outside allowed bounds'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Format geodata
|
||||
const geodata = `${validation.latitude};${validation.longitude}`;
|
||||
|
||||
// Prepare data for NocoDB
|
||||
const finalData = {
|
||||
geodata,
|
||||
'Geo-Location': geodata,
|
||||
latitude: validation.latitude,
|
||||
longitude: validation.longitude,
|
||||
...additionalData,
|
||||
created_at: new Date().toISOString(),
|
||||
created_by: req.session.userEmail
|
||||
};
|
||||
|
||||
logger.info('Creating new location:', {
|
||||
lat: validation.latitude,
|
||||
lng: validation.longitude
|
||||
});
|
||||
|
||||
const response = await nocodbService.create(
|
||||
config.nocodb.tableId,
|
||||
finalData
|
||||
);
|
||||
|
||||
logger.info('Location created successfully:', extractId(response));
|
||||
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
location: response
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Error creating location:', error.message);
|
||||
|
||||
if (error.response) {
|
||||
res.status(error.response.status).json({
|
||||
success: false,
|
||||
error: 'Failed to save location to NocoDB',
|
||||
details: error.response.data
|
||||
});
|
||||
} else {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: 'Internal server error'
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async update(req, res) {
|
||||
try {
|
||||
const locationId = req.params.id;
|
||||
|
||||
// Validate ID
|
||||
if (!locationId || locationId === 'undefined' || locationId === 'null') {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Invalid location ID'
|
||||
});
|
||||
}
|
||||
|
||||
let updateData = { ...req.body };
|
||||
|
||||
// Remove ID fields to avoid conflicts
|
||||
delete updateData.ID;
|
||||
delete updateData.Id;
|
||||
delete updateData.id;
|
||||
delete updateData._id;
|
||||
|
||||
// Sync geo fields
|
||||
updateData = syncGeoFields(updateData);
|
||||
|
||||
updateData.last_updated_at = new Date().toISOString();
|
||||
updateData.last_updated_by = req.session.userEmail;
|
||||
|
||||
logger.info(`Updating location ${locationId} by ${req.session.userEmail}`);
|
||||
|
||||
const response = await nocodbService.update(
|
||||
config.nocodb.tableId,
|
||||
locationId,
|
||||
updateData
|
||||
);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
location: response
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
logger.error(`Error updating location ${req.params.id}:`, error.message);
|
||||
|
||||
res.status(error.response?.status || 500).json({
|
||||
success: false,
|
||||
error: 'Failed to update location',
|
||||
details: error.response?.data?.message || error.message
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async delete(req, res) {
|
||||
try {
|
||||
const locationId = req.params.id;
|
||||
|
||||
// Validate ID
|
||||
if (!locationId || locationId === 'undefined' || locationId === 'null') {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Invalid location ID'
|
||||
});
|
||||
}
|
||||
|
||||
await nocodbService.delete(
|
||||
config.nocodb.tableId,
|
||||
locationId
|
||||
);
|
||||
|
||||
logger.info(`Location ${locationId} deleted by ${req.session.userEmail}`);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Location deleted successfully'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
logger.error(`Error deleting location ${req.params.id}:`, error.message);
|
||||
res.status(error.response?.status || 500).json({
|
||||
success: false,
|
||||
error: 'Failed to delete location'
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new LocationsController();
|
||||
370
map/app/controllers/settingsController.js
Normal file
370
map/app/controllers/settingsController.js
Normal file
@@ -0,0 +1,370 @@
|
||||
const nocodbService = require('../services/nocodb');
|
||||
const logger = require('../utils/logger');
|
||||
const config = require('../config');
|
||||
const { validateUrl, extractId, extractWalkSheetConfig } = require('../utils/helpers');
|
||||
|
||||
class SettingsController {
|
||||
// Default settings values
|
||||
static defaultSettings = {
|
||||
walk_sheet_title: 'Campaign Walk Sheet',
|
||||
walk_sheet_subtitle: 'Door-to-Door Canvassing Form',
|
||||
walk_sheet_footer: 'Thank you for your support!',
|
||||
qr_code_1_url: '',
|
||||
qr_code_1_label: '',
|
||||
qr_code_2_url: '',
|
||||
qr_code_2_label: '',
|
||||
qr_code_3_url: '',
|
||||
qr_code_3_label: ''
|
||||
};
|
||||
|
||||
async getStartLocation(req, res) {
|
||||
try {
|
||||
const settings = await nocodbService.getLatestSettings();
|
||||
|
||||
if (settings) {
|
||||
let lat, lng, zoom;
|
||||
|
||||
if (settings['Geo-Location']) {
|
||||
const parts = settings['Geo-Location'].split(';');
|
||||
if (parts.length === 2) {
|
||||
lat = parseFloat(parts[0]);
|
||||
lng = parseFloat(parts[1]);
|
||||
}
|
||||
} else if (settings.latitude && settings.longitude) {
|
||||
lat = parseFloat(settings.latitude);
|
||||
lng = parseFloat(settings.longitude);
|
||||
}
|
||||
|
||||
zoom = parseInt(settings.zoom) || config.map.defaultZoom;
|
||||
|
||||
if (lat && lng && !isNaN(lat) && !isNaN(lng)) {
|
||||
return res.json({
|
||||
success: true,
|
||||
location: {
|
||||
latitude: lat,
|
||||
longitude: lng,
|
||||
zoom: zoom
|
||||
},
|
||||
source: 'database',
|
||||
settingsId: extractId(settings),
|
||||
lastUpdated: settings.created_at
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Return defaults
|
||||
res.json({
|
||||
success: true,
|
||||
location: {
|
||||
latitude: config.map.defaultLat,
|
||||
longitude: config.map.defaultLng,
|
||||
zoom: config.map.defaultZoom
|
||||
},
|
||||
source: 'defaults'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Error fetching start location:', error);
|
||||
|
||||
// Return defaults on error
|
||||
res.json({
|
||||
success: true,
|
||||
location: {
|
||||
latitude: config.map.defaultLat,
|
||||
longitude: config.map.defaultLng,
|
||||
zoom: config.map.defaultZoom
|
||||
},
|
||||
source: 'defaults'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async updateStartLocation(req, res) {
|
||||
try {
|
||||
const { latitude, longitude, zoom } = req.body;
|
||||
|
||||
// Validate input
|
||||
if (!latitude || !longitude) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Latitude and longitude are required'
|
||||
});
|
||||
}
|
||||
|
||||
const lat = parseFloat(latitude);
|
||||
const lng = parseFloat(longitude);
|
||||
const mapZoom = parseInt(zoom) || 11;
|
||||
|
||||
if (isNaN(lat) || isNaN(lng) || lat < -90 || lat > 90 || lng < -180 || lng > 180) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Invalid coordinates'
|
||||
});
|
||||
}
|
||||
|
||||
if (!config.nocodb.settingsSheetId) {
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
error: 'Settings sheet not configured'
|
||||
});
|
||||
}
|
||||
|
||||
// Get current settings to preserve other fields
|
||||
let currentConfig = {};
|
||||
try {
|
||||
currentConfig = await nocodbService.getLatestSettings() || {};
|
||||
|
||||
// Debug logging to see what we're getting
|
||||
logger.info('Retrieved current config:', {
|
||||
id: currentConfig.Id || currentConfig.ID || currentConfig.id,
|
||||
walk_sheet_title: currentConfig.walk_sheet_title,
|
||||
walk_sheet_subtitle: currentConfig.walk_sheet_subtitle,
|
||||
walk_sheet_footer: currentConfig.walk_sheet_footer,
|
||||
hasFooter: !!currentConfig.walk_sheet_footer,
|
||||
footerType: typeof currentConfig.walk_sheet_footer,
|
||||
allKeys: Object.keys(currentConfig)
|
||||
});
|
||||
} catch (error) {
|
||||
logger.warn('Could not retrieve current settings for preservation, using defaults:', error.message);
|
||||
currentConfig = {};
|
||||
}
|
||||
|
||||
// Create new settings row - use values directly without || operator
|
||||
const walkSheetConfig = extractWalkSheetConfig(currentConfig, SettingsController.defaultSettings);
|
||||
|
||||
const settingData = {
|
||||
created_at: new Date().toISOString(),
|
||||
created_by: req.session.userEmail,
|
||||
// Map location fields (what we're updating)
|
||||
'Geo-Location': `${lat};${lng}`,
|
||||
latitude: lat,
|
||||
longitude: lng,
|
||||
zoom: mapZoom,
|
||||
// Preserve walk sheet fields using helper function
|
||||
...walkSheetConfig
|
||||
};
|
||||
|
||||
logger.info('Creating settings row with data:', {
|
||||
walk_sheet_footer: settingData.walk_sheet_footer,
|
||||
footerLength: settingData.walk_sheet_footer?.length
|
||||
});
|
||||
|
||||
const response = await nocodbService.create(
|
||||
config.nocodb.settingsSheetId,
|
||||
settingData
|
||||
);
|
||||
|
||||
logger.info('Created new settings row with start location');
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Start location saved successfully',
|
||||
location: { latitude: lat, longitude: lng, zoom: mapZoom },
|
||||
settingsId: extractId(response)
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Error updating start location:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: error.message || 'Failed to update start location'
|
||||
});
|
||||
}
|
||||
}
|
||||
async getWalkSheetConfig(req, res) {
|
||||
try {
|
||||
if (!config.nocodb.settingsSheetId) {
|
||||
logger.warn('SETTINGS_SHEET_ID not configured, returning defaults');
|
||||
return res.json({
|
||||
success: true,
|
||||
config: SettingsController.defaultSettings,
|
||||
source: 'defaults',
|
||||
message: 'Settings sheet not configured, using defaults'
|
||||
});
|
||||
}
|
||||
|
||||
const settings = await nocodbService.getLatestSettings();
|
||||
|
||||
if (!settings) {
|
||||
logger.info('No settings found in database, returning defaults');
|
||||
return res.json({
|
||||
success: true,
|
||||
config: SettingsController.defaultSettings,
|
||||
source: 'defaults',
|
||||
message: 'No settings found in database'
|
||||
});
|
||||
}
|
||||
|
||||
const walkSheetConfig = extractWalkSheetConfig(settings, SettingsController.defaultSettings);
|
||||
|
||||
logger.info(`Retrieved walk sheet config from database (ID: ${extractId(settings)})`);
|
||||
res.json({
|
||||
success: true,
|
||||
config: walkSheetConfig,
|
||||
source: 'database',
|
||||
settingsId: extractId(settings),
|
||||
lastUpdated: settings.created_at || settings.updated_at
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Failed to get walk sheet config:', error);
|
||||
|
||||
// Return defaults if there's an error
|
||||
res.json({
|
||||
success: true,
|
||||
config: SettingsController.defaultSettings,
|
||||
source: 'defaults',
|
||||
message: 'Error retrieving from database, using defaults',
|
||||
error: error.message
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async updateWalkSheetConfig(req, res) {
|
||||
try {
|
||||
if (!config.nocodb.settingsSheetId) {
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
error: 'Settings sheet not configured'
|
||||
});
|
||||
}
|
||||
|
||||
const configData = req.body;
|
||||
logger.info('Received walk sheet config:', JSON.stringify(configData, null, 2));
|
||||
|
||||
// Validate input
|
||||
if (!configData || typeof configData !== 'object') {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Invalid configuration data'
|
||||
});
|
||||
}
|
||||
|
||||
// Get current settings to preserve other fields
|
||||
let currentConfig = {};
|
||||
try {
|
||||
currentConfig = await nocodbService.getLatestSettings() || {};
|
||||
} catch (error) {
|
||||
logger.warn('Could not retrieve current settings for preservation, using defaults:', error.message);
|
||||
currentConfig = {};
|
||||
}
|
||||
|
||||
const userEmail = req.session.userEmail;
|
||||
const timestamp = new Date().toISOString();
|
||||
|
||||
// Prepare data for saving
|
||||
const walkSheetData = {
|
||||
created_at: timestamp,
|
||||
created_by: userEmail,
|
||||
// Preserve map location fields with consistent fallbacks
|
||||
'Geo-Location': currentConfig['Geo-Location'] || currentConfig.geodata || `${config.map.defaultLat};${config.map.defaultLng}`,
|
||||
latitude: currentConfig.latitude || config.map.defaultLat,
|
||||
longitude: currentConfig.longitude || config.map.defaultLng,
|
||||
zoom: currentConfig.zoom || config.map.defaultZoom,
|
||||
// Walk sheet fields (what we're updating)
|
||||
walk_sheet_title: (configData.walk_sheet_title || '').toString().trim(),
|
||||
walk_sheet_subtitle: (configData.walk_sheet_subtitle || '').toString().trim(),
|
||||
walk_sheet_footer: (configData.walk_sheet_footer || '').toString().trim(),
|
||||
'Walk Sheet Title': (configData.walk_sheet_title || '').toString().trim(),
|
||||
'Walk Sheet Subtitle': (configData.walk_sheet_subtitle || '').toString().trim(),
|
||||
'Walk Sheet Footer': (configData.walk_sheet_footer || '').toString().trim(),
|
||||
qr_code_1_url: validateUrl(configData.qr_code_1_url),
|
||||
qr_code_1_label: (configData.qr_code_1_label || '').toString().trim(),
|
||||
qr_code_2_url: validateUrl(configData.qr_code_2_url),
|
||||
qr_code_2_label: (configData.qr_code_2_label || '').toString().trim(),
|
||||
qr_code_3_url: validateUrl(configData.qr_code_3_url),
|
||||
qr_code_3_label: (configData.qr_code_3_label || '').toString().trim(),
|
||||
'QR Code 1 URL': validateUrl(configData.qr_code_1_url),
|
||||
'QR Code 1 Label': (configData.qr_code_1_label || '').toString().trim(),
|
||||
'QR Code 2 URL': validateUrl(configData.qr_code_2_url),
|
||||
'QR Code 2 Label': (configData.qr_code_2_label || '').toString().trim(),
|
||||
'QR Code 3 URL': validateUrl(configData.qr_code_3_url),
|
||||
'QR Code 3 Label': (configData.qr_code_3_label || '').toString().trim()
|
||||
};
|
||||
|
||||
const response = await nocodbService.create(
|
||||
config.nocodb.settingsSheetId,
|
||||
walkSheetData
|
||||
);
|
||||
|
||||
const newId = extractId(response);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Walk sheet configuration saved successfully',
|
||||
config: walkSheetData,
|
||||
settingsId: newId,
|
||||
timestamp: timestamp
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Failed to save walk sheet config:', error);
|
||||
logger.error('Error response:', error.response?.data);
|
||||
|
||||
let errorMessage = 'Failed to save walk sheet configuration';
|
||||
let errorDetails = null;
|
||||
|
||||
if (error.response?.data) {
|
||||
if (error.response.data.message) {
|
||||
errorMessage = error.response.data.message;
|
||||
}
|
||||
if (error.response.data.errors) {
|
||||
errorDetails = error.response.data.errors;
|
||||
}
|
||||
}
|
||||
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: errorMessage,
|
||||
details: errorDetails,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Public endpoint for start location (no auth required)
|
||||
async getPublicStartLocation(req, res) {
|
||||
try {
|
||||
const settings = await nocodbService.getLatestSettings();
|
||||
|
||||
if (settings) {
|
||||
let lat, lng, zoom;
|
||||
|
||||
if (settings['Geo-Location']) {
|
||||
const parts = settings['Geo-Location'].split(';');
|
||||
if (parts.length === 2) {
|
||||
lat = parseFloat(parts[0]);
|
||||
lng = parseFloat(parts[1]);
|
||||
}
|
||||
} else if (settings.latitude && settings.longitude) {
|
||||
lat = parseFloat(settings.latitude);
|
||||
lng = parseFloat(settings.longitude);
|
||||
}
|
||||
|
||||
zoom = parseInt(settings.zoom) || config.map.defaultZoom;
|
||||
|
||||
if (lat && lng && !isNaN(lat) && !isNaN(lng)) {
|
||||
logger.info(`Returning location from database: ${lat}, ${lng}, zoom: ${zoom}`);
|
||||
return res.json({
|
||||
latitude: lat,
|
||||
longitude: lng,
|
||||
zoom: zoom
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error fetching config start location:', error);
|
||||
}
|
||||
|
||||
// Return defaults
|
||||
logger.info(`Using default start location: ${config.map.defaultLat}, ${config.map.defaultLng}, zoom: ${config.map.defaultZoom}`);
|
||||
|
||||
res.json({
|
||||
latitude: config.map.defaultLat,
|
||||
longitude: config.map.defaultLng,
|
||||
zoom: config.map.defaultZoom
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new SettingsController();
|
||||
146
map/app/controllers/usersController.js
Normal file
146
map/app/controllers/usersController.js
Normal file
@@ -0,0 +1,146 @@
|
||||
const nocodbService = require('../services/nocodb');
|
||||
const logger = require('../utils/logger');
|
||||
const config = require('../config');
|
||||
const { sanitizeUser, extractId } = require('../utils/helpers');
|
||||
|
||||
class UsersController {
|
||||
async getAll(req, res) {
|
||||
try {
|
||||
if (!config.nocodb.loginSheetId) {
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
error: 'Login sheet not configured'
|
||||
});
|
||||
}
|
||||
|
||||
const response = await nocodbService.getAll(config.nocodb.loginSheetId, {
|
||||
limit: 100,
|
||||
sort: '-created_at'
|
||||
});
|
||||
|
||||
const users = response.list || [];
|
||||
|
||||
// Remove password field from response for security
|
||||
const safeUsers = users.map(sanitizeUser);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
users: safeUsers
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Error fetching users:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: 'Failed to fetch users'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async create(req, res) {
|
||||
try {
|
||||
const { email, password, name, admin } = req.body;
|
||||
|
||||
if (!email || !password) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Email and password are required'
|
||||
});
|
||||
}
|
||||
|
||||
if (!config.nocodb.loginSheetId) {
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
error: 'Login sheet not configured'
|
||||
});
|
||||
}
|
||||
|
||||
// Check if user already exists
|
||||
const existingUser = await nocodbService.getUserByEmail(email);
|
||||
|
||||
if (existingUser) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'User with this email already exists'
|
||||
});
|
||||
}
|
||||
|
||||
// Create new user
|
||||
const userData = {
|
||||
Email: email,
|
||||
email: email,
|
||||
Password: password,
|
||||
password: password,
|
||||
Name: name || '',
|
||||
name: name || '',
|
||||
Admin: admin === true,
|
||||
admin: admin === true,
|
||||
'Created At': new Date().toISOString(),
|
||||
created_at: new Date().toISOString()
|
||||
};
|
||||
|
||||
const response = await nocodbService.create(
|
||||
config.nocodb.loginSheetId,
|
||||
userData
|
||||
);
|
||||
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
message: 'User created successfully',
|
||||
user: {
|
||||
id: extractId(response),
|
||||
email: email,
|
||||
name: name,
|
||||
admin: admin
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Error creating user:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: 'Failed to create user'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async delete(req, res) {
|
||||
try {
|
||||
const userId = req.params.id;
|
||||
|
||||
if (!config.nocodb.loginSheetId) {
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
error: 'Login sheet not configured'
|
||||
});
|
||||
}
|
||||
|
||||
// Don't allow admins to delete themselves
|
||||
if (userId === req.session.userId) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Cannot delete your own account'
|
||||
});
|
||||
}
|
||||
|
||||
await nocodbService.delete(
|
||||
config.nocodb.loginSheetId,
|
||||
userId
|
||||
);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'User deleted successfully'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Error deleting user:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: 'Failed to delete user'
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new UsersController();
|
||||
Reference in New Issue
Block a user