Commit 628e5bf2 authored by abergavenny's avatar abergavenny
Browse files

Version 1.0.0

parent b463e8cc
version: '3'
services:
server:
build:
dockerfile: Dockerfile
context: ./server
ports:
- 3005:3000
volumes:
- ./client/dist:/app/public
- ./server:/app
- /app/node_modules
depends_on:
- database
environment:
- APP_PORT=3000
- CORS_ORIGIN=*
- JWT_SECRET=secret
- JWT_EXPIRES_IN=24h
- EMAIL_VERIFICATION=on
- SERVICE_CLIENT_URI=http://localhost:5173
- SERVICE_SERVER_URI=http://localhost:3005/auth
- SERVICE_CST_URI=http://193.196.138.36
- DB_HOST=database
- DB_PORT=27017
- DB_NAME=${DATABASE_NAME}
- DB_USER=${DATABASE_USER}
- DB_PASS=${DATABASE_PASS}
- MAILER_MODE=smtp
- MAILER_HOST=${MAIL_HOST}
- MAILER_PORT=${MAIL_PORT}
- MAILER_USER=${MAIL_USER}
- MAILER_PASS=${MAIL_PASS}
networks:
- dreiprozent-plus
database:
image: mongo:latest
restart: always
environment:
- MONGO_INITDB_ROOT_USERNAME=${MONGO_ROOT_USER}
- MONGO_INITDB_ROOT_PASSWORD=${MONGO_ROOT_PASS}
- MONGO_INITDB_DATABASE=${DATABASE_NAME}
- NEW_MONGO_NAME=${DATABASE_NAME}
- NEW_MONGO_USER=${DATABASE_USER}
- NEW_MONGO_PASS=${DATABASE_PASS}
volumes:
- ./db/init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro
- database-store:/data/db
networks:
- dreiprozent-plus
networks:
dreiprozent-plus:
driver: bridge
volumes:
database-store:
{
"name": "dreiprozent-plus",
"version": "1.0.0",
"repository": {
"type": "git",
"url": "git+https://github.com/abergavenny/dreiprozent-plus.git"
},
"keywords": [],
"author": "abergavenny",
"license": "MIT",
"bugs": {
"url": "https://github.com/abergavenny/dreiprozent-plus/issues"
},
"homepage": "https://github.com/abergavenny/dreiprozent-plus#readme"
}
.env
.git
.gitignore
docker-compose*
node_modules/
package-lock*
\ No newline at end of file
module.exports = {
env: {
es2021: true,
node: true
},
extends: 'eslint:recommended',
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module'
},
rules: {
}
}
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
.env.*
# parcel-bundler cache (https://parceljs.org/)
.cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Custom
package-lock.json
public/
\ No newline at end of file
FROM node:18-alpine
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "run", "start"]
\ No newline at end of file
FROM node:18-alpine
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "run", "dev"]
\ No newline at end of file
MIT License
Copyright (c) 2022 abergavenny
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# 3% Plus Server
## .env oder ../docker-compose.yml
```
# Application
APP_PORT=3000
CORS_ORIGIN=
JWT_SECRET=
JWT_EXPIRES_IN=24h
# Database
DB_HOST=
DB_PORT=27017
DB_NAME=
DB_USER=
DB_PASS=
# General
EMAIL_VERIFICATION=on|off
SERVICE_CLIENT_URI=
SERVICE_SERVER_URI=
SERVICE_CST_URI=
# Mailer
MAILER_MODE=smtp|sendmail
MAILER_HOST=
MAILER_PORT=
MAILER_USER=
MAILER_PASS=
```
/*
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
export default {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "C:\\Users\\remus\\AppData\\Local\\Temp\\jest",
// Automatically clear mock calls, instances, contexts and results before every test
// clearMocks: false,
// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
// coverageDirectory: undefined,
// An array of regexp pattern strings used to skip coverage collection
coveragePathIgnorePatterns: [
'\\\\node_modules\\\\'
],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: 'v8',
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "mjs",
// "cjs",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state before every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
testEnvironment: 'jest-environment-node'
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "\\\\node_modules\\\\",
// "\\.pnp\\.[^\\\\]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
}
db.createUser({
user: 'user',
pwd: 'pass',
roles: [{ role: 'readWrite', db: 'dreiprozent' }]
})
{
"name": "dreiprozent-plus-api",
"version": "1.0.0",
"description": "",
"main": "src/main.js",
"type": "module",
"scripts": {
"start": "nodemon -L src/index.js",
"dev": "nodemon -L src/index.js",
"test": "jest"
},
"repository": {
"type": "git",
"url": "git+https://github.com/abergavenny/dreiprozent-plus.git"
},
"keywords": [],
"author": "abergavenny",
"license": "MIT",
"bugs": {
"url": "https://github.com/abergavenny/dreiprozent-plus/issues"
},
"homepage": "https://github.com/abergavenny/dreiprozent-plus#readme",
"dependencies": {
"axios": "0.27.2",
"cors": "2.8.5",
"dotenv": "16.0.1",
"dotenv-expand": "8.0.3",
"express": "4.18.1",
"express-rate-limit": "6.5.1",
"express-validator": "6.14.2",
"helmet": "5.1.1",
"jsonwebtoken": "8.5.1",
"mongoose": "6.5.1",
"multer": "1.4.5-lts.1",
"nodemailer": "6.7.7",
"passport": "0.6.0",
"passport-jwt": "4.0.0",
"wild-strawberry": "0.1.0"
},
"devDependencies": {
"eslint": "^8.21.0",
"jest": "^28.1.3",
"nodemon": "^2.0.19",
"standard": "^17.0.0",
"supertest": "^6.2.4"
}
}
export const API_VERSION_PREFIX = '/api/v1'
export const ALLOWED_ROLES = ['administrator']
const model = {}
Object.freeze(model)
export const ModelEnum = model
const response = {
Confirm: 'CONFIRMATION_REQUIRED',
Created: 'ITEM_CREATED',
EmailInUse: 'EMAIL_ALREADY_IN_USE',
Exists: 'EXISTS',
Expired: 'TOKEN_EXPIRED',
InvalidInput: 'INVALID_INPUT',
LoggedIn: 'LOGIN_SUCCESSFUL',
MissingData: 'MISSING_DATA',
MissingParameter: 'MISSING_PARAMETER',
NotAllowed: 'NOT_ALLOWED',
NotCreated: 'CANNOT_CREATE_ITEM',
NotFound: 'NOT_FOUND',
PrefixUnavailable: 'PREFIX_UNAVAILABLE',
Registered: 'REGISTRATION_SUCCESSFUL',
UpdateSuccess: 'UPDATE_SUCCESSFUL',
ValidationError: 'VALIDATION_ERROR',
WrongCredentials: 'EMAIL_OR_PASSWORD_WRONG'
}
Object.freeze(response)
export const ResponseCode = response
import express from 'express'
import cors from 'cors'
import helmet from 'helmet'
import config from './config/appConfig.js'
import authHandler, { setupAuthentication } from './middleware/authHandler.js'
import errorHandler from './middleware/errorHandler.js'
import { apartmentRouter, authRouter, buildingRouter, selfRouter, simulationRouter, userRouter } from './routes/index.js'
export const app = express()
app.use(helmet.hidePoweredBy())
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cors({
origin: config.corsOrigin
}))
setupAuthentication(app)
app.use('/auth', authRouter)
app.use('/api/v1/apartments', authHandler, apartmentRouter)
app.use('/api/v1/buildings', authHandler, buildingRouter)
app.use('/api/v1/self', authHandler, selfRouter)
app.use('/api/v1/simulations', authHandler, simulationRouter)
app.use('/api/v1/users', authHandler, userRouter)
app.use('/', express.static('public'))
app.use(errorHandler)
app.use('*', (req, res) => res.redirect('/'))
export default app
function loadEnvironmentVariable (key) {
if (key === undefined) throw new Error('Key does not exist. (environment variables)')
return process.env[key]
}
export default {
port: loadEnvironmentVariable('APP_PORT'),
endpoints: {
app: loadEnvironmentVariable('SERVICE_CLIENT_URI'),
api: loadEnvironmentVariable('SERVICE_SERVER_URI')
},
corsOrigin: loadEnvironmentVariable('CORS_ORIGIN'),
db: {
host: loadEnvironmentVariable('DB_HOST'),
port: loadEnvironmentVariable('DB_PORT'),
name: loadEnvironmentVariable('DB_NAME'),
user: loadEnvironmentVariable('DB_USER'),
pass: loadEnvironmentVariable('DB_PASS'),
uri: loadEnvironmentVariable('DB_URI')
},
emailVerification: loadEnvironmentVariable('EMAIL_VERIFICATION'),
jwt: {
expiresIn: loadEnvironmentVariable('JWT_EXPIRES_IN'),
secrect: loadEnvironmentVariable('JWT_SECRET')
},
mailer: {
mode: loadEnvironmentVariable('MAILER_MODE'),
host: loadEnvironmentVariable('MAILER_HOST'),
port: loadEnvironmentVariable('MAILER_PORT'),
user: loadEnvironmentVariable('MAILER_USER'),
pass: loadEnvironmentVariable('MAILER_PASS')
},
simulationEndpoint: loadEnvironmentVariable('SERVICE_CST_URI')
}
import { validationResult } from 'express-validator'
import { Building, User } from '../db/index.js'
import { getUserFromRequest, success, warning } from '../helpers/index.js'
import { hashString } from '../utils/crypto.js'
import { ResponseCode } from '../ENUMS.js'
export const createApartment = async (req, res) => {
const validationErrors = validationResult(req)
if (!validationErrors.isEmpty()) {
return warning(res, { code: ResponseCode.ValidationError })
}
const { accessor } = getUserFromRequest(req)
const { apartmentName, buildingId, password, username } = req.body
const building = await Building.findOne({ _id: buildingId })
if (building) {
if (building.prefix) {
const result = await User.createBuildingUser(accessor, {
username: `${building.prefix}_${username}`,
encryptedPassword: hashString(password),
role: 'user',
createdBy: accessor,
linkedTo: building._id
})
if (result) {
await building.apartments.push({
name: apartmentName,
linkedTo: building._id,
owner: result._id
})
await building.save()
return success(res, { code: ResponseCode.Created, id: result._id }, 201)
}
}
return warning(res, { code: ResponseCode.InvalidInput })
}
warning(res, { code: ResponseCode.InvalidInput })
}
export const getApartment = async (req, res) => {
const validationErrors = validationResult(req)
if (!validationErrors.isEmpty()) {
return warning(res, { code: ResponseCode.ValidationError })
}
const { accessor, role } = getUserFromRequest(req)
const { id } = req.params
let result
if (role === 'administrator') {
result = await Building.findOne({
owner: accessor,
'apartments._id': id
})
.select('apartments._id apartments.name apartments.data apartments.linkedTo apartments.image apartments.owner')
} else {
result = await Building.findOne({
'apartments.owner': accessor,
'apartments._id': id
})
.select('apartments._id apartments.name apartments.data apartments.linkedTo apartments.image')
}
if (result) {
return success(res, { data: result.apartments.length > 0 ? result.apartments[0] : null })
}
warning(res, { code: ResponseCode.NotFound, data: null }, 404)
}
export const getApartments = async (req, res) => {
const { accessor, role } = getUserFromRequest(req)
if (role === 'administrator') {
const result = await Building.find({ owner: accessor }).select('apartments._id apartments.name apartments.data apartments.linkedTo apartments.owner')
success(res, { data: result?.map(item => item.apartments).flat() })
return
}
const result = await Building.findOne({ 'apartments.owner': accessor }, 'apartments.$')
if (result) {
return success(res, { data: result.apartments })
}
warning(res, { code: ResponseCode.NotFound, data: [] })
}
export const getFile = async (req, res) => {
const { id } = req.params
const result = await Building.findOne({ 'apartments._id': id }, 'apartments.$')
if (result) {
return res.send(result.apartments[0].image.buffer.data)
}
warning(res, { code: ResponseCode.NotFound })
}
export const updateFiles = async (req, res) => {
const { accessor } = getUserFromRequest(req)
const { id } = req.params
const image = req.file
const result = await Building.findOneAndUpdate({
owner: accessor,
'apartments._id': id
}, {
$set: {
'apartments.$.image': {
name: '',
originalName: image.originalname,
mimeType: image.mimetype,
buffer: {
data: image.buffer,
contentType: image.mimeType
},
updatedAt: Date.now()
}
}
}, { new: true, runValidators: true }).select('apartments._id')
success(res, { code: ResponseCode.UpdateSuccess, data: result })
}
export const updateHeatingData = async (req, res) => {
const validationErrors = validationResult(req)
if (!validationErrors.isEmpty()) {
return warning(res, { code: ResponseCode.ValidationError })
}
const { accessor } = getUserFromRequest(req)
const { id } = req.params
const {
apartmentComment,
area,
ceilingHeight,
centralHeating,
heatDemand,
heatingType,
largeHeatingElements,
mediumHeatingElements,
smallHeatingElements,
panelHeating,
powerDemand,
workingHeatingInstallations
} = req.body
const building = await Building.findOne({ 'apartments.owner': accessor, 'apartments._id': id }).select('apartments')
if (building === null || building.apartments.length === 0) {
return warning(res, { code: ResponseCode.NotFound })
}
const result = await Building.findOneAndUpdate({
'apartments._id': id
}, {
$set: {
updatedAt: Date.now(),
'apartments.$.data.apartmentComment': apartmentComment,
'apartments.$.data.area': area,
'apartments.$.data.ceilingHeight': ceilingHeight,
'apartments.$.data.centralHeating': centralHeating,
'apartments.$.data.heatDemand': heatDemand,
'apartments.$.data.heatingType': heatingType,
'apartments.$.data.largeHeatingElements': largeHeatingElements,
'apartments.$.data.mediumHeatingElements': mediumHeatingElements,
'apartments.$.data.smallHeatingElements': smallHeatingElements,
'apartments.$.data.panelHeating': panelHeating,
'apartments.$.data.powerDemand': powerDemand,
'apartments.$.data.workingHeatingInstallations': workingHeatingInstallations
}
}, { new: true, runValidators: true })
.select([
'apartments.data.apartmentComment',
'apartments.data.area',
'apartments.data.ceilingHeight',
'apartments.data.centralHeating',
'apartments.data.heatDemand',
'apartments.data.heatingType',
'apartments.data.largeHeatingElements',
'apartments.data.mediumHeatingElements',
'apartments.data.smallHeatingElements',
'apartments.data.panelHeating',
'apartments.data.powerDemand',
'apartments.data.workingHeatingInstallations'
])
if (result) {
if (result.apartments.length === 0) {
return warning(res, { code: ResponseCode.NotFound })
}
return success(res, {
code: ResponseCode.UpdateSuccess,
data: null
})
}
warning(res, { code: ResponseCode.NotFound })
}
export const updateWindowData = async (req, res) => {
const validationErrors = validationResult(req)
if (!validationErrors.isEmpty()) {
return warning(res, { code: ResponseCode.ValidationError })
}
const { accessor } = getUserFromRequest(req)
const { id } = req.params
const { averageWindowAge, averageWindowCondition, largeWindows, mediumWindows, roofWindows, smallWindows, windowComment, windowFrame, windowGlazing } = req.body
const building = await Building.findOne({ 'apartments.owner': accessor, 'apartments._id': id }).select('apartments')
if (building === null || building.apartments.length === 0) {
return warning(res, { code: ResponseCode.NotFound })
}
const result = await Building.findOneAndUpdate({
'apartments._id': id
}, {
$set: {
updatedAt: Date.now(),
'apartments.$.data.averageWindowAge': averageWindowAge,
'apartments.$.data.averageWindowCondition': averageWindowCondition,
'apartments.$.data.largeWindows': largeWindows,
'apartments.$.data.mediumWindows': mediumWindows,
'apartments.$.data.roofWindows': roofWindows,
'apartments.$.data.smallWindows': smallWindows,
'apartments.$.data.windowComment': windowComment,
'apartments.$.data.windowFrame': windowFrame,
'apartments.$.data.windowGlazing': windowGlazing
}
}, { new: true, runValidators: true })
.select([
'apartments.data.averageWindowAge',
'apartments.data.averageWindowCondition',
'apartments.data.largeWindows',
'apartments.data.mediumWindows',
'apartments.data.roofWindows',
'apartments.data.smallWindows',
'apartments.data.windowComment',
'apartments.data.windowFrame',
'apartments.data.windowGlazing'
])
if (result) {
if (result.apartments.length === 0) {
return warning(res, { code: ResponseCode.NotFound })
}
return success(res, {
code: ResponseCode.UpdateSuccess,
data: null
})
}
warning(res, { code: ResponseCode.NotFound })
}
import { randomBytes } from 'node:crypto'
import { validationResult } from 'express-validator'
import jwt from 'jsonwebtoken'
import config from '../config/appConfig.js'
import { Building, User } from '../db/index.js'
import { getUsernameFromEmail, success, warning } from '../helpers/index.js'
import Mailer from '../mailer.js'
import { hashString } from '../utils/crypto.js'
import { ResponseCode } from '../ENUMS.js'
const mailer = new Mailer()
if (config.mailer.mode === 'smtp') {
mailer.init({
host: config.mailer.host,
port: config.mailer.port,
user: config.mailer.user,
pass: config.mailer.pass
}, config.mailer.mode)
} else if (config.mailer.mode === 'sendmail') {
mailer.init({
sendmail: true
}, config.mailer.mode)
} else {
mailer.init(null, null)
}
export const confirm = async (req, res) => {
const validationErrors = validationResult(req)
if (!validationErrors.isEmpty()) {
return warning(res, { code: ResponseCode.ValidationError })
}
const { token } = req.params
const result = await User.findOneAndUpdate({ confirmationToken: token, confirmationExpireAt: { $gt: new Date() } }, {
emailConfirmed: true,
confirmationExpiresAt: null,
confirmationToken: null
}, {
new: true,
runValidators: true
})
res.redirect(`${config.endpoints.app}/?verified=${!!result}&expired=${!result}`)
}
export const login = async (req, res) => {
const validationErrors = validationResult(req)
if (!validationErrors.isEmpty()) {
return warning(res, { code: ResponseCode.ValidationError })
}
const { emailOrUsername, password } = req.body
const result = await User.findUserAndVerify(emailOrUsername, password)
if (result) {
if (config.emailVerification === 'on' && !result.emailConfirmed && result.role === 'administrator') {
return warning(res, { code: ResponseCode.Confirm }, 200)
}
const token = jwt.sign({
role: result.role,
userId: result._id
}, config.jwt.secrect, { expiresIn: config.jwt.expiresIn })
return success(res, { code: ResponseCode.LoggedIn, data: { token } })
}
warning(res, { code: ResponseCode.WrongCredentials }, 200)
}
export const register = async (req, res) => {
const validationErrors = validationResult(req)
if (!validationErrors.isEmpty()) {
return warning(res, { code: ResponseCode.ValidationError })
}
const { email, password, gmlid } = req.body
const result = await User.createNewAccount(email, {
email,
username: getUsernameFromEmail(email),
encryptedPassword: hashString(password),
role: 'administrator',
sharingAllowed: true
})
if (result) {
const building = await Building.create({
gmlid,
owner: result._id,
createdBy: result._id
})
if (config.emailVerification === 'on') {
const token = randomBytes(64).toString('hex')
const expireAt = Date.now() + 86400000 // DEVINFO Gültigkeit des Token 24h
await User.updateOne({ _id: result._id }, { linkedTo: building._id, confirmationToken: token, confirmationExpireAt: expireAt })
console.log(`LOG Confirmation Token: ${config.endpoints.api}/confirm/${token}`)
// DEVINFO Hier kann der E-Mail-Text (Registrierung/Bestätigung) bearbeitet werden.
const subject = '3% Plus - E-Mail-Bestätigung'
const message = `
Sehr geehrte Frau/Sehr geehrter Herr,
um Ihr Benutzerkonto verwenden zu können müssen Sie Ihre E-Mail bestätigen. Klicken Sie hierzu bitte auf den nachfolgenden Link:
${config.endpoints.api}/confirm/${token}
Mit freundlichen Grüßen
Ihr Administrator
Wenn diese E-Mail nicht an Sie gerichtet ist, dann löschen Sie diese Nachricht bitte oder informieren den Absender über die falsche Zustellung.
`
mailer.sendMail(email, subject, message, null)
} else {
await User.updateOne({ _id: result._id }, { linkedTo: building._id })
}
return success(res, { code: ResponseCode.Registered, data: { confirmRequired: config.emailVerification === 'on' } }, 201)
}
warning(res, { code: ResponseCode.EmailInUse }, 200)
}
export const resetPassword = async (req, res) => {
const validationErrors = validationResult(req)
if (!validationErrors.isEmpty()) {
return warning(res, { code: ResponseCode.ValidationError, validationErrors })
}
const { email } = req.body
const result = await User.findOne({ email })
if (result) {
const token = randomBytes(64).toString('hex')
const expireAt = Date.now() + 86400000 // DEVINFO Gültigkeit des Token 24h
await User.findByIdAndUpdate(result._id, {
resetExpireAt: expireAt,
resetToken: token,
lastResetRequest: Date.now()
}, {
runValidators: true
})
console.log(`LOG Reset Token: ${config.endpoints.app}/reset-password?token=${token}`)
// DEVINFO Hier kann der E-Mail-Text (Registrierung/Bestätigung) bearbeitet werden.
const subject = '3% Plus - Passwort vergessen'
const message = `
Sehr geehrte Frau/Sehr geehrter Herr,
um Ihr Passwort zurückzusetzen klicken Sie bitte auf den nachfolgenden Link:
${config.endpoints.app}/reset-password?token=${token}
Mit freundlichen Grüßen
Ihr Administrator
Wenn diese E-Mail nicht an Sie gerichtet ist, dann löschen Sie diese Nachricht bitte oder informieren den Absender über die falsche Zustellung.
`
mailer.sendMail(email, subject, message, null)
return success(res, {})
}
warning(res, { code: ResponseCode.NotFound, result }, 404)
}
export const updatePassword = async (req, res) => {
const validationErrors = validationResult(req)
if (!validationErrors.isEmpty()) {
return warning(res, { code: ResponseCode.ValidationError })
}
const { token } = req.params
const { password } = req.body
const result = await User.findOneAndUpdate({ resetToken: token, resetExpireAt: { $gt: new Date() } }, {
encryptedPassword: hashString(password)
}, {
new: true,
runValidators: true
})
if (result) {
return success(res, { code: ResponseCode.UpdateSuccess })
}
warning(res, { code: ResponseCode.NotFound })
}
import { validationResult } from 'express-validator'
import { Building, Management, Simulation, User } from '../db/index.js'
import { getUserFromRequest, success, warning } from '../helpers/index.js'
import { executeSimulation, getInformation } from '../services/external.js'
import { ResponseCode } from '../ENUMS.js'
export const createBuilding = async (req, res) => {
const validationErrors = validationResult(req)
if (!validationErrors.isEmpty()) {
return warning(res, { code: ResponseCode.ValidationError })
}
const { accessor } = getUserFromRequest(req)
const { buildingAddress, buildingGmlId, buildingName, buildingPrefix } = req.body
const mgmt = await Management.findOne()
if (mgmt.prefixList.indexOf(buildingPrefix) !== -1) {
return warning(res, { code: ResponseCode.PrefixUnavailable })
}
await mgmt.prefixList.push(buildingPrefix)
await mgmt.save()
const result = await Building.create({
prefix: buildingPrefix,
name: buildingName,
address: buildingAddress,
gmlid: buildingGmlId || null,
owner: accessor
})
if (result) {
const user = await User.findById(accessor)
user.ofBuilding = result._id
user.save()
return success(res, { code: ResponseCode.Created, id: result._id })
}
warning(res, { code: ResponseCode.NotCreated })
}
export const getApartments = async (req, res) => {
const validationErrors = validationResult(req)
if (!validationErrors.isEmpty()) {
return warning(res, { code: ResponseCode.ValidationError })
}
const { id } = req.params
const result = await Building.findOne({ _id: id }).select('apartments.name apartments.image apartments.linkedTo apartments.owner')
if (result) {
return success(res, { data: result.apartments })
}
warning(res, { code: ResponseCode.NotFound })
}
export const getBuilding = async (req, res) => {
const validationErrors = validationResult(req)
if (!validationErrors.isEmpty()) {
return warning(res, { code: ResponseCode.ValidationError })
}
const { accessor, role } = getUserFromRequest(req)
const { id } = req.params
let result
if (role === 'administrator') {
result = await Building.findOne({ _id: id, owner: accessor }).select('_id name address data apartments gmlid prefix createdAt')
} else {
result = await Building.findOne({ _id: id, 'apartments.owner': accessor }).select('_id name address data apartments gmlid prefix createdAt')
}
if (result) {
return success(res, { data: result })
}
warning(res, { code: ResponseCode.NotFound })
}
export const getBuildings = async (req, res) => {
const { accessor } = getUserFromRequest(req)
const result = await Building.find({ owner: accessor }).select('_id name address data apartments gmlid setupCompleted prefix createdAt')
if (result) {
return success(res, { data: result })
}
warning(res, { code: ResponseCode.NotFound })
}
export const getSimulation = async (req, res) => {
const { id } = req.params
const { gmlId } = req.query
const building = await Building.findById(id)
if (building) {
const simulationId = gmlId || building.gmlId
if (gmlId) {
await Building.findByIdAndUpdate({ _id: building._id }, { gmlId })
}
if (simulationId) {
const prefetched = await getInformation(simulationId)
// DEVINFO Hier könnte das Object für ein Request an die CS-T-API verändert werden.
// Wenn keine GML-Id in der Datenbank gespeichert wurden, kann über die API eine angefügt werden.
// Es wird ein Request zur Abfrage bestehender Information für die ausgewählt GML-Id ausgeführt.
// Die entsprechenden Object-Keys werden im Standard-Request-Body durch die neuen Daten ersetzt
// Request 1: /api/v1/buildings/<building_id>/simulations/run
// Request 2: /api/v1/buildings/<building_id>/simulations/run?gmlId=<gml_id>
// Example Id: DENW39AL1000nJfc
const simData = {
gmlId: simulationId,
atticType: 'unknown',
basementType: 'unknown',
comparisonRenovationType: 'no',
existingModuleArea: '0',
existingModuleEfficiency: '15',
renovationType: 'no',
roofType: 'unknown',
simulateModuleEfficiency: '15',
typeOfEnergy: 'unknown',
yearOfConstruction: '2000',
...prefetched
}
const simResult = await executeSimulation(simData)
if (simResult) {
const { successful, errorMessage, ...rest } = simResult
await Simulation.create({
buildingId: id,
gmlId: simulationId,
prefetched,
result: rest
})
return success(res, {
data: {
successful,
errorMessage,
prefetched,
result: rest
}
})
}
return warning(res, { code: ResponseCode.InvalidInput })
}
return warning(res, { code: ResponseCode.MissingParameter })
}
warning(res, { code: ResponseCode.NotFound })
}
export const getUsers = async (req, res) => {
const { id } = req.params
const result = await User.find({ linkedTo: id }).select('_id username')
if (result) {
return success(res, { data: result })
}
warning(res, { code: ResponseCode.UserNotFound })
}
export const updateBuilding = async (req, res) => {
const { id } = req.params
const { buildingAddress, gmlid, buildingName, buildingPrefix } = req.body
const building = await Building.findById(id)
if (building) {
const updateQuery = {
address: buildingAddress,
gmlid,
name: buildingName,
updatedAt: Date.now()
}
if (building.prefix === null && !building.setupCompleted) {
const mgmt = await Management.findOne()
if (mgmt.prefixList.indexOf(buildingPrefix) !== -1) {
return warning(res, { code: ResponseCode.PrefixUnavailable }, 200)
}
updateQuery.prefix = buildingPrefix
updateQuery.setupCompleted = true
await mgmt.prefixList.push(buildingPrefix)
await mgmt.save()
}
const result = await Building.findByIdAndUpdate(building._id, updateQuery, { new: true, runValidators: true })
if (result) {
return success(res, { data: result })
}
}
warning(res, { code: ResponseCode.NotFound })
}
export const updateBuildingDataBasement = async (req, res) => {
const validationErrors = validationResult(req)
if (!validationErrors.isEmpty()) {
return warning(res, { code: ResponseCode.ValidationError })
}
const { id } = req.params
const { basementInsulatingMaterial, basementInsulatingMaterialThickness, basementRefurbishmentComment, heatedBasement, insulatedBasementCeiling, insulatedBasementFloor } = req.body
const result = await Building.findByIdAndUpdate(id, {
$set: {
updatedAt: Date.now(),
'data.basementInsulatingMaterial': basementInsulatingMaterial,
'data.basementInsulatingMaterialThickness': basementInsulatingMaterialThickness,
'data.basementRefurbishmentComment': basementRefurbishmentComment,
'data.heatedBasement': heatedBasement,
'data.insulatedBasementCeiling': insulatedBasementCeiling,
'data.insulatedBasementFloor': insulatedBasementFloor
}
}, { new: true, runValidators: true })
.select([
'data.basementInsulatingMaterial',
'data.basementInsulatingMaterialThickness',
'data.basementRefurbishmentComment',
'data.heatedBasement',
'data.insulatedBasementCeiling',
'data.insulatedBasementFloor'
])
if (result) {
return success(res, {
code: ResponseCode.UpdateSuccess,
data: result.data
})
}
warning(res, { code: ResponseCode.NotFound })
}
export const updateBuildingDataCharacteristics = async (req, res) => {
const validationErrors = validationResult(req)
if (!validationErrors.isEmpty()) {
return warning(res, { code: ResponseCode.ValidationError })
}
const { id } = req.params
const { characteristicsComment, energyPerformanceCertificate, listedBuilding, livingSpace, numberOfFloors, yearOfConstruction } = req.body
const result = await Building.findByIdAndUpdate(id, {
$set: {
updatedAt: Date.now(),
'data.characteristicsComment': characteristicsComment,
'data.energyPerformanceCertificate': energyPerformanceCertificate,
'data.listedBuilding': listedBuilding,
'data.livingSpace': livingSpace,
'data.numberOfFloors': numberOfFloors,
'data.yearOfConstruction': yearOfConstruction
}
}, { new: true, runValidators: true })
.select([
'data.characteristicsComment',
'data.energyPerformanceCertificate',
'data.listedBuilding',
'data.livingSpace',
'data.numberOfFloors',
'data.yearOfConstruction'
])
if (result) {
return success(res, {
code: ResponseCode.UpdateSuccess,
data: result.data
})
}
warning(res, { code: ResponseCode.NotFound })
}
export const updateBuildingDataFacade = async (req, res) => {
const validationErrors = validationResult(req)
if (!validationErrors.isEmpty()) {
return warning(res, { code: ResponseCode.ValidationError })
}
const { id } = req.params
const { buildingStructure, buildingStructureThickness, facadeInsulatingMaterial, facadeInsulatingMaterialThickness, facadeEast, facadeNorth, facadeRefurbishmentComment, facadeSouth, facadeWest } = req.body
const result = await Building.findByIdAndUpdate(id, {
$set: {
updatedAt: Date.now(),
'data.buildingStructure': buildingStructure,
'data.buildingStructureThickness': buildingStructureThickness,
'data.facadeInsulatingMaterial': facadeInsulatingMaterial,
'data.facadeInsulatingMaterialThickness': facadeInsulatingMaterialThickness,
'data.facadeEast': facadeEast,
'data.facadeNorth': facadeNorth,
'data.facadeRefurbishmentComment': facadeRefurbishmentComment,
'data.facadeSouth': facadeSouth,
'data.facadeWest': facadeWest
}
}, { new: true, runValidators: true })
.select([
'data.buildingStructure',
'data.buildingStructureThickness',
'data.facadeInsulatingMaterial',
'data.facadeInsulatingMaterialThickness',
'data.facadeEast',
'data.facadeNorth',
'data.facadeRefurbishmentComment',
'data.facadeSouth',
'data.facadeWest'
])
if (result) {
return success(res, {
code: ResponseCode.UpdateSuccess,
data: result.data
})
}
warning(res, { code: ResponseCode.NotFound })
}
export const updateBuildingDataHeating = async (req, res) => {
const validationErrors = validationResult(req)
if (!validationErrors.isEmpty()) {
return warning(res, { code: ResponseCode.ValidationError })
}
const { id } = req.params
const { heatingConsumption, heatingInstallation, heatingInstallationComment, photovoltaic, photovoltaicArea, photovoltaicYield, pipeSystem, selfContainedCentralHeating, solarHeat, solarHeatArea } = req.body
const result = await Building.findByIdAndUpdate(id, {
$set: {
updatedAt: Date.now(),
'data.heatingConsumption': heatingConsumption,
'data.heatingInstallation': heatingInstallation,
'data.heatingInstallationComment': heatingInstallationComment,
'data.photovoltaic': photovoltaic,
'data.photovoltaicArea': photovoltaicArea,
'data.photovoltaicYield': photovoltaicYield,
'data.pipeSystem': pipeSystem,
'data.selfContainedCentralHeating': selfContainedCentralHeating,
'data.solarHeat': solarHeat,
'data.solarHeatArea': solarHeatArea
}
}, { new: true, runValidators: true })
.select([
'data.heatingConsumption',
'data.heatingInstallation',
'data.heatingInstallationComment',
'data.photovoltaic',
'data.photovoltaicArea',
'data.photovoltaicYield',
'data.pipeSystem',
'data.selfContainedCentralHeating',
'data.solarHeat',
'data.solarHeatArea'
])
if (result) {
return success(res, {
code: ResponseCode.UpdateSuccess,
data: result.data
})
}
warning(res, { code: ResponseCode.NotFound })
}
export const updateBuildingDataRoof = async (req, res) => {
const { id } = req.params
const { clouding, flatRoof, heatedAttic, roofArea, roofInsulatingMaterial, roofInsulatingMaterialThickness, roofRefurbishmentComment } = req.body
const result = await Building.findByIdAndUpdate(id, {
$set: {
updatedAt: Date.now(),
'data.clouding': clouding,
'data.flatRoof': flatRoof,
'data.heatedAttic': heatedAttic,
'data.roofArea': roofArea,
'data.roofInsulatingMaterial': roofInsulatingMaterial,
'data.roofInsulatingMaterialThickness': roofInsulatingMaterialThickness,
'data.roofRefurbishmentComment': roofRefurbishmentComment
}
}, { new: true, runValidators: true })
.select([
'data.clouding',
'data.flatRoof',
'data.heatedAttic',
'data.roofArea',
'data.roofInsulatingMaterial',
'data.roofInsulatingMaterialThickness',
'data.roofRefurbishmentComment'
])
if (result) {
return success(res, {
code: ResponseCode.UpdateSuccess,
data: result.data
})
}
warning(res, { code: ResponseCode.NotFound })
}
import { Building, User } from '../db/index.js'
import { getUserFromRequest, success, warning } from '../helpers/index.js'
import { ResponseCode } from '../ENUMS.js'
export const getSelf = async (req, res) => {
const { accessor, role } = getUserFromRequest(req)
const user = await User.findById(accessor).select('_id role linkedTo sharingAllowed')
if (user) {
let apartmentCount, buildingCount, buildingList
if (role === 'administrator') {
const buildings = await Building.find({ owner: user._id })
apartmentCount = buildings.apartments?.length || 0
buildingCount = buildings.length
buildingList = buildings.map(element => element._id)
}
return success(res, {
code: ResponseCode.Success,
data: {
id: user._id,
apartments: apartmentCount,
buildings: buildingCount,
buildingList,
sharingAllowed: user.sharingAllowed,
linkedTo: user.linkedTo,
role: user.role
}
})
}
warning(res, { code: ResponseCode.NotFound })
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment