update for new structure

This commit is contained in:
Michael Schramm 2020-06-01 03:43:50 +02:00
parent a63603b530
commit e7208ea992
353 changed files with 28 additions and 47642 deletions

View File

@ -1,104 +0,0 @@
{
"projectName": "OhMyForm",
"projectOwner": "ohmyform",
"files": [
"README.md"
],
"imageSize": 100,
"commit": true,
"contributors": [
{
"login": "whitef0x0",
"name": "David Baldwynn",
"avatar_url": "https://avatars2.githubusercontent.com/u/1160417?v=3",
"profile": "http://baldwynn.me",
"contributions": [
"code",
"tool",
"infra",
"doc",
"example",
"design",
"fundingFinding",
"review",
"test"
]
},
{
"login": "lalop",
"name": "Samuel Laulhau",
"avatar_url": "https://avatars2.githubusercontent.com/u/313117?v=3",
"profile": "https://samuellaulhau.fr",
"contributions": [
"code",
"translation"
]
},
{
"login": "arunpattnaik",
"name": "Arun Pattnaik",
"avatar_url": "https://avatars0.githubusercontent.com/u/313507?v=3",
"profile": "http://arun.co",
"contributions": [
"design"
]
},
{
"login": "toanalien",
"name": "Thiên Toán",
"avatar_url": "https://avatars0.githubusercontent.com/u/5405744?v=3",
"profile": "https://toanalien.com",
"contributions": [
"bug",
"code",
"doc"
]
},
{
"login": "AdrianP-",
"name": "Adrian Portabales",
"avatar_url": "https://avatars2.githubusercontent.com/u/8615608?v=3",
"profile": "https://github.com/AdrianP-",
"contributions": [
"bug",
"code"
]
},
{
"login": "spekulatius",
"name": "Peter Thaleikis",
"avatar_url": "https://avatars3.githubusercontent.com/u/8433587?v=3",
"profile": "https://github.com/spekulatius",
"contributions": [
"doc"
]
},
{
"login": "mickaelandrieu",
"name": "Mickaël Andrieu",
"avatar_url": "https://avatars1.githubusercontent.com/u/1247388?v=3",
"profile": "http://www.mickael-andrieu.com",
"contributions": [
"doc"
]
},
{
"login": "ahmad-luqman",
"name": "Ahmad Luqman",
"avatar_url": "https://avatars1.githubusercontent.com/u/1522464?v=3",
"profile": "https://github.com/ahmad-luqman",
"contributions": [
"doc"
]
},
{
"login": "PeterDaveHello",
"name": "Peter Dave Hello",
"avatar_url": "https://avatars0.githubusercontent.com/u/3691490?v=3",
"profile": "https://www.peterdavehello.org/",
"contributions": [
"doc"
]
}
]
}

View File

@ -1,5 +0,0 @@
{
"directory": "public/lib",
"analytics": false,
"registry": "https://registry.bower.io"
}

View File

@ -1,15 +0,0 @@
{
"adjoining-classes": false,
"box-model": false,
"box-sizing": false,
"floats": false,
"font-sizes": false,
"important": false,
"known-properties": false,
"overqualified-elements": false,
"qualified-headings": false,
"regex-selectors": false,
"unique-headings": false,
"universal-selector": false,
"unqualified-attributes": false
}

View File

@ -1,25 +0,0 @@
# EditorConfig is awesome: http://EditorConfig.org
# How-to with your editor: http://editorconfig.org/#download
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
indent_style = space
insert_final_newline = true
[{Dockerfile,Procfile}]
trim_trailing_whitespace = true
# Standard at: https://github.com/felixge/node-style-guide
[{*.js,*.json}]
trim_trailing_whitespace = true
quote_type = single
curly_bracket_next_line = false
spaces_around_operators = true
space_after_control_statements = true
space_after_anonymous_functions = false
spaces_in_brackets = false

View File

@ -1,125 +0,0 @@
# OhMyForm Configuration File
## TODO: Have commented out examples that would work.
###################################
# Common configuration variables
###################################
# Set this to the path where Mailu data and configuration is stored
# Mac users: Change to a Docker accessible folder
ROOT=/opt/ohmyform_data
# Set to what environment you will be running OhMyForm in (production or development)
NODE_ENV=development
# Set to a randomly generated 16 bytes string
SECRET_KEY=ChangeMeChangeMe
# URI of Mongo database that OhMyForm will connect to
#DO NOT CHANGE
MONGODB_URI=mongodb://mongo/ohmyform
# URL Redis server that OhMyForm will connect to
#DO NOT CHANGE
REDIS_URL=redis://redis:6379
# Port that the OhMyForm Node app will listen on
PORT=5000
# Domain that OhMyForm's admin panel will be hosted at
BASE_URL=ohmyform.dev
# Port that SocketIO server (for analytics) will listen on
SOCKET_PORT=20523
#Choose what kind of TLS you want.
#Can be either 'cert' (supply your certificates in ./cert/), 'notls' (no https at all) or 'letsencrypt' that autoconfigures your instance with letsencrypt
TLS_FLAVOR=notls
###################################
# Optional features
###################################
# Set this to enable coveralls.io support
COVERALLS_REPO_TOKEN=
# Disable signups for your OhMyForm instance
SIGNUP_DISABLED=FALSE
# Disable per-user custom subdomains
SUBDOMAINS_DISABLED=FALSE
# Url that subdomains will be hosted at (has to have domain name as ADMIN_URL)
# Only used when SUBDOMAINS_DISABLED=FALSE
SUBDOMAIN_URL=*.ohmyform.dev
# Enable running OhMyForm in pm2's 'cluster' mode
ENABLE_CLUSTER_MODE=FALSE
###################################
# Mail settings
# IMPORTANT: These settings need to be set
# to be set in order for your instance to work
###################################
# Set this to set the username credential of your SMTP service
MAILER_EMAIL_ID=
# Set this to set the password credential of your SMTP service
MAILER_PASSWORD=
# Set this to set the email address that all email should be sent from for signup/verification emails
MAILER_FROM=
# Set this to any services from https://nodemailer.com/smtp/well-known/ to use a 'well-known' email provider
MAILER_SERVICE_PROVIDER=
# Set these if you are not using a 'MAILER_SERVICE_PROVIDER' and want to specify your SMTP server's address and port
MAILER_SMTP_HOST=
MAILER_SMTP_PORT=
# Set this if you are using a custom SMTP server that supports SSL
MAILER_SMTP_SECURE
###################################
# Automatic Admin Creation Settings
###################################
# Set this to "TRUE" if you wish to automatically create an admin user on startup
CREATE_ADMIN=FALSE
# Set this to set the email used by your default admin account
ADMIN_EMAIL=admin@admin.com
# Set this to set the username of your default admin acconut
ADMIN_USERNAME=root
# Set this to set the password of your default admin account
ADMIN_PASSWORD=root
###################################
# Advanced settings
###################################
# Set this to server your websockets server on a seperate URL
SOCKETS_URL=
# Set this to change the port that OhMyForm will listen on
PORT=5000
# Set this to your Google Analytics ID to enable tracking with GA
GOOGLE_ANALYTICS_ID=
# Set this to your Sentry.io DSN code to enable front-end JS error tracking with Sentry.io
RAVEN_DSN
# Set this to set the 'name' meta property in the HTML <head>
APP_NAME=
# Set this to set the 'keywords' meta property in the HTML <head>
APP_KEYWORDS=
# Set this to set the 'description' meta property in the HTML head
APP_DESC=

View File

@ -1,54 +0,0 @@
{
"loopfunc": true,
"node": true, // Enable globals available when code is running inside of the NodeJS runtime environment.
"browser": true, // Standard browser globals e.g. `window`, `document`.
"esnext": true, // Allow ES.next specific features such as `const` and `let`.
"bitwise": false, // Prohibit bitwise operators (&, |, ^, etc.).
"camelcase": false, // Permit only camelcase for `var` and `object indexes`.
"curly": false, // Require {} for every new block or scope.
"eqeqeq": true, // Require triple equals i.e. `===`.
"immed": true, // Require immediate invocations to be wrapped in parens e.g. `( function(){}() );`
"latedef": false, // Prohibit variable use before definition.
"newcap": false, // Require capitalization of all constructor functions e.g. `new F()`.
"noarg": true, // Prohibit use of `arguments.caller` and `arguments.callee`.
"quotmark": "single", // Define quotes to string values.
"regexp": true, // Prohibit `.` and `[^...]` in regular expressions.
"undef": true, // Require all non-global variables be declared before they are used.
"unused": false, // Warn unused variables.
"strict": true, // Require `use strict` pragma in every file.
"trailing": true, // Prohibit trailing whitespaces.
"smarttabs": false, // Suppresses warnings about mixed tabs and spaces
"globals": { // Globals variables.
"jasmine": true,
"angular": true,
"devel": false,
"_": true,
"saveAs": true,
"ApplicationConfiguration": true,
"Session": true,
"$": true,
"$window": true,
"io": true,
"jsep": true,
"MobileDetect": true
},
"predef": [ // Extra globals.
"define",
"require",
"exports",
"module",
"describe",
"before",
"beforeEach",
"after",
"afterEach",
"it",
"inject",
"expect",
"_",
"spyOn"
],
"indent": 4, // Specify indentation spacing
"devel": true, // Allow development statements e.g. `console.log();`.
"noempty": true // Prohibit use of empty blocks.
}

View File

@ -1 +0,0 @@
/app/tests

2
api/.gitignore vendored
View File

@ -1,2 +0,0 @@
/node_modules
/yarn.lock

View File

@ -1,4 +0,0 @@
{
"singleQuote": true,
"trailingComma": "all"
}

View File

@ -1,17 +0,0 @@
FROM node:10 AS builder
MAINTAINER OhMyForm <admin@ohmyform.com>
WORKDIR /usr/src/app
# just copy everhing
COPY . .
RUN yarn install --frozen-lockfile
RUN yarn build
FROM node:10-alpine
COPY --from=builder /usr/src/app /usr/src/app
EXPOSE 3000
CMD [ "yarn", "start:prod" ]

View File

@ -1,55 +0,0 @@
<p align="center">
<a href="http://ohmyform.com/" target="blank"><img src="https://ohmyform.com/img/logo_text.svg" width="320" alt="OhMyForm Logo" /></a>
</p>
## Description
[OhMyForm](https://github.com/ohmyforn) api backend
## Installation
```bash
$ yarn install
```
## Running the app
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# incremental rebuild (webpack)
$ npm run webpack
$ npm run start:hmr
# production mode
$ npm run start:prod
```
## Test
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Support
TODO
## Stay in touch
- Website - [https://ohmyform.com](https://ohmyform.com/)
## License
TODO

View File

@ -1,5 +0,0 @@
{
"language": "ts",
"collection": "@nestjs/schematics",
"sourceRoot": "src"
}

View File

@ -1,6 +0,0 @@
{
"watch": ["src"],
"ext": "ts",
"ignore": ["src/**/*.spec.ts"],
"exec": "node --inspect-brk -r ts-node/register src/main.ts"
}

View File

@ -1,6 +0,0 @@
{
"watch": ["src"],
"ext": "ts",
"ignore": ["src/**/*.spec.ts"],
"exec": "ts-node -r tsconfig-paths/register src/main.ts"
}

View File

@ -1,79 +0,0 @@
{
"name": "ohmyform",
"version": "0.1.0",
"description": "Opensource alternative to TypeForm",
"author": "multiple",
"license": "MIT",
"scripts": {
"build": "rimraf dist && tsc -p tsconfig.build.json",
"format": "prettier --write \"src/**/*.ts\"",
"start": "ts-node -r tsconfig-paths/register src/main.ts",
"start:dev": "tsc-watch -p tsconfig.build.json --onSuccess \"node dist/main.js\"",
"start:debug": "tsc-watch -p tsconfig.build.json --onSuccess \"node --inspect-brk dist/main.js\"",
"start:prod": "node dist/main.js",
"lint": "tslint -p tsconfig.json -c tslint.json",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@godaddy/terminus": "^4.1.2",
"@nest-modules/mailer": "^1.1.3",
"@nestjs/common": "^6.5.2",
"@nestjs/core": "^6.5.2",
"@nestjs/jwt": "^6.1.1",
"@nestjs/mongoose": "^6.1.2",
"@nestjs/passport": "^6.1.0",
"@nestjs/platform-express": "^6.5.2",
"@nestjs/swagger": "^3.1.0",
"@nestjs/terminus": "^6.5.0",
"@types/bcrypt": "^3.0.0",
"@types/mongoose": "^5.5.11",
"bcrypt": "^3.0.6",
"class-transformer": "^0.2.3",
"class-validator": "^0.9.1",
"handlebars": "^4.1.2",
"mongoose": "^5.6.7",
"nestjs-typegoose": "^5.2.1",
"passport": "^0.4.0",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0",
"reflect-metadata": "^0.1.12",
"rimraf": "^2.6.2",
"rxjs": "^6.3.3",
"swagger-ui-express": "^4.0.7",
"typegoose": "^5.9.0"
},
"devDependencies": {
"@nestjs/testing": "6.1.1",
"@types/express": "4.16.1",
"@types/jest": "24.0.11",
"@types/node": "11.13.4",
"@types/supertest": "2.0.7",
"jest": "24.7.1",
"prettier": "1.17.0",
"supertest": "4.0.2",
"ts-jest": "24.0.2",
"ts-node": "8.1.0",
"tsc-watch": "2.2.1",
"tsconfig-paths": "3.8.0",
"tslint": "5.16.0",
"typescript": "3.4.3"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

View File

@ -1,20 +0,0 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import {ApiExcludeEndpoint} from "@nestjs/swagger"
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@ApiExcludeEndpoint()
@Get()
getIndex(): object {
return {
message: 'hello humanoid',
_links: {
doc: '/doc',
health: '/health'
}
};
}
}

View File

@ -1,35 +0,0 @@
import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
import { MongooseModule } from '@nestjs/mongoose';
import { TypegooseModule } from 'nestjs-typegoose';
import { TerminusOptionsService } from './terminus-options.service';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from "./user/user.module"
import { FormModule } from "./form/form.module"
import { AuthModule } from './auth/auth.module';
import { MailModule } from "./mail/mail.module"
import { MailerModule } from "@nest-modules/mailer"
@Module({
imports: [
TypegooseModule.forRoot('mongodb://localhost/ohmyform', { useNewUrlParser: true }),
MongooseModule.forRoot('mongodb://localhost/ohmyform'),
TerminusModule.forRootAsync({
useClass: TerminusOptionsService,
}),
MailerModule.forRoot({
transport: 'smtp://localhost:1025',
defaults: {
from:'"OhMyForm" <noreply@ohmyform.com>',
}
}),
UserModule,
FormModule,
AuthModule,
MailModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

View File

@ -1,8 +0,0 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

View File

@ -1,9 +0,0 @@
import {AuthController} from "./controllers/auth.controller"
import {RecoverController} from "./controllers/recover.controller"
import {RegisterController} from "./controllers/register.controller"
export default [
AuthController,
RecoverController,
RegisterController,
]

View File

@ -1,23 +0,0 @@
import { Module } from '@nestjs/common';
import { UserModule } from '../user/user.module';
import { PassportModule } from '@nestjs/passport';
import { jwtConstants } from "./constants"
import { JwtModule } from "@nestjs/jwt"
import controllers from './auth.controllers'
import providers from './auth.providers'
import { MailModule } from "../mail/mail.module"
@Module({
imports: [
UserModule,
PassportModule,
MailModule,
JwtModule.register({
secret: jwtConstants.secret,
signOptions: { expiresIn: '12h' },
}),
],
controllers,
providers
})
export class AuthModule {}

View File

@ -1,15 +0,0 @@
import { AuthService } from "./services/auth.service"
import { PasswordService } from "./services/password.service"
import { PasswordStrategy } from "./strategies/password.strategy"
import { JwtStrategy } from "./strategies/jwt.strategy"
import { JwtRefreshStrategy } from "./strategies/jwt.refresh.strategy"
import { RegisterService } from "./services/register.service"
export default [
AuthService,
PasswordService,
PasswordStrategy,
JwtStrategy,
JwtRefreshStrategy,
RegisterService,
]

View File

@ -1,3 +0,0 @@
export const jwtConstants = {
secret: 'secretKey',
};

View File

@ -1,30 +0,0 @@
import { Controller, Request, Post, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from "../services/auth.service"
import { AuthJwtDto } from "../dto/auth.jwt.dto"
import {ApiBearerAuth, ApiImplicitBody, ApiImplicitQuery, ApiResponse, ApiUseTags} from "@nestjs/swagger"
@ApiUseTags('authentication')
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@ApiResponse({ status: 201, description: 'Successful login.', type: AuthJwtDto})
@ApiResponse({ status: 401, description: 'Invalid Credentials.'})
@ApiImplicitQuery({name: 'username', type: String})
@ApiImplicitQuery({name: 'password', type: String})
@UseGuards(AuthGuard('password'))
@Post('login')
async login(@Request() req): Promise<AuthJwtDto> {
return this.authService.createToken(req.user);
}
@ApiBearerAuth()
@ApiResponse({ status: 201, description: 'Consumed Refresh Token.', type: AuthJwtDto})
@ApiResponse({ status: 401, description: 'Invalid Token.'})
@UseGuards(AuthGuard('jwt.refresh'))
@Post('refresh')
async refresh(@Request() req): Promise<AuthJwtDto> {
return this.authService.createToken(req.user);
}
}

View File

@ -1,29 +0,0 @@
import { Controller, Request, Post, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from "../services/auth.service"
import { AuthJwtDto } from "../dto/auth.jwt.dto"
import {ApiBearerAuth, ApiImplicitBody, ApiImplicitQuery, ApiResponse, ApiUseTags} from "@nestjs/swagger"
@ApiUseTags('authentication')
@Controller('auth/recover')
export class RecoverController {
constructor(private readonly authService: AuthService) {}
@ApiResponse({ status: 201, description: 'Successful registration.', type: AuthJwtDto})
@ApiImplicitQuery({name: 'email', type: String})
@ApiImplicitQuery({name: 'username', type: String})
@Post('request')
async request(@Request() req): Promise<AuthJwtDto> {
// TODO
return null
}
@ApiResponse({ status: 201, description: 'Successful registration.', type: AuthJwtDto})
@ApiImplicitQuery({name: 'token', type: String})
@ApiImplicitQuery({name: 'password', type: String})
@Post('finish')
async finish(@Request() req): Promise<AuthJwtDto> {
// TODO
return null
}
}

View File

@ -1,18 +0,0 @@
import { Controller, Post, Body } from '@nestjs/common';
import { AuthService } from "../services/auth.service"
import { ApiBadRequestResponse, ApiCreatedResponse, ApiUseTags } from "@nestjs/swagger"
import { RegisterDto } from "../dto/register.dto"
import {RegisterService} from "../services/register.service"
@ApiUseTags('authentication')
@Controller('auth')
export class RegisterController {
constructor(private readonly registerService: RegisterService) {}
@ApiCreatedResponse({ description: 'Successful registration.'})
@ApiBadRequestResponse({})
@Post('register')
async register(@Body() params: RegisterDto): Promise<void> {
await this.registerService.register(params.username, params.email, params.password)
}
}

View File

@ -1,9 +0,0 @@
import { ApiModelProperty } from '@nestjs/swagger';
export class AuthJwtDto {
@ApiModelProperty()
accessToken: string;
@ApiModelProperty()
refreshToken: string;
}

View File

@ -1,20 +0,0 @@
import { ApiModelProperty } from "@nestjs/swagger"
import { IsEmail, IsNotEmpty, Validate } from "class-validator"
import { UsernameAlreadyInUse } from "../../user/validators/UsernameAlreadyInUse"
import { EmailAlreadyInUse } from "../../user/validators/EmailAlreadyInUse"
export class RegisterDto {
@ApiModelProperty()
@IsNotEmpty()
@Validate(UsernameAlreadyInUse)
readonly username: string;
@ApiModelProperty()
@IsNotEmpty()
readonly password: string;
@ApiModelProperty()
@Validate(EmailAlreadyInUse)
@IsEmail()
readonly email: string;
}

View File

@ -1,8 +0,0 @@
export interface AuthUser {
id: string;
username: string;
email: string;
roles: [string];
created: Date;
lastUpdated: Date;
}

View File

@ -1,18 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';
describe('AuthService', () => {
let service: AuthService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuthService],
}).compile();
service = module.get<AuthService>(AuthService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -1,70 +0,0 @@
import { Injectable } from '@nestjs/common';
import { UserService } from '../../user/services/user.service';
import { PasswordService } from "./password.service"
import { JwtService } from '@nestjs/jwt';
import { AuthUser } from "../interfaces/auth.user.interface"
import { User } from "../../user/models/user.model"
import { AuthJwtDto } from "../dto/auth.jwt.dto"
@Injectable()
export class AuthService {
constructor(
private readonly usersService: UserService,
private readonly passwordService: PasswordService,
private readonly jwtService: JwtService
) {}
async verifyForLogin(identifier: string, pass: string): Promise<AuthUser | null> {
try {
const user = await this.usersService.findOneByIdentifier(identifier);
if (await this.passwordService.verify(pass, user.passwordHash, user.salt)) {
return AuthService.setupAuthUser(user)
}
} catch (e) {}
return null;
}
async validate(identifier: string): Promise<AuthUser | null> {
try {
return AuthService.setupAuthUser(
await this.usersService.findOneByIdentifier(identifier)
)
} catch (e) {}
return null;
}
private static setupAuthUser(user:User):AuthUser {
return {
id: user._id,
username: user.username,
email: user.email,
roles: user.roles,
created: user.created,
lastUpdated: user.lastModified
};
}
async createToken(user: AuthUser): Promise<AuthJwtDto> {
const payload = {
id: user.id,
username: user.username,
scope: user.roles,
};
return {
accessToken: this.jwtService.sign(payload),
// TODO add refresh token invalidation uppon usage! They should only work once
refreshToken: this.jwtService.sign(
{
...payload,
refresh: true
},
{
expiresIn: '30days',
}
),
};
}
}

View File

@ -1,30 +0,0 @@
import { Injectable } from "@nestjs/common"
import * as crypto from 'crypto'
import * as bcrypt from 'bcrypt'
@Injectable()
export class PasswordService {
async verify (password: string, hash: string, salt?: string): Promise<boolean> {
console.log('try to verify password', password)
if (password[0] === '$') {
return await bcrypt.compare(password, hash)
}
//Generate salt if it doesn't exist yet
if(!salt){
salt = crypto.randomBytes(64).toString('base64');
}
return hash === crypto.pbkdf2Sync(
password,
new Buffer(salt, 'base64'),
10000,
128,
'SHA1'
).toString('base64');
}
hash (password): Promise<string> {
return bcrypt.hash(password, 4)
}
}

View File

@ -1,33 +0,0 @@
import { Injectable } from "@nestjs/common"
import { MailService } from "../../mail/services/mail.service"
import { User } from "../../user/models/user.model"
import { PasswordService } from "./password.service"
import { UserService } from "../../user/services/user.service"
@Injectable()
export class RegisterService {
constructor(
private readonly mailService: MailService,
private readonly passwordService: PasswordService,
private readonly userService: UserService
) {}
async register (username: string, email: string, password: string): Promise<void> {
let user = new User()
user.email = email
user.username = username
user.passwordHash = await this.passwordService.hash(password)
await this.userService.save(user)
await this.mailService.sendEmail(
{
template: 'auth/register',
to: email
},
{
confirm: 'some url'
}
)
}
}

View File

@ -1,26 +0,0 @@
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { jwtConstants } from '../constants';
import { AuthService } from "../services/auth.service"
import { AuthUser } from "../interfaces/auth.user.interface"
@Injectable()
export class JwtRefreshStrategy extends PassportStrategy(Strategy, 'jwt.refresh') {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: jwtConstants.secret,
});
}
async validate(payload: any): Promise<AuthUser | null> {
if (!payload.refresh) {
return null
}
// TODO add refresh token invalidation uppon usage! They should only work once
return this.authService.validate(payload.username);
}
}

View File

@ -1,21 +0,0 @@
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { jwtConstants } from '../constants';
import { AuthService } from "../services/auth.service"
import {AuthUser} from "../interfaces/auth.user.interface"
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: jwtConstants.secret,
});
}
async validate(payload: any): Promise<AuthUser | null> {
return this.authService.validate(payload.username);
}
}

View File

@ -1,16 +0,0 @@
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { AuthService } from '../services/auth.service';
import {AuthUser} from "../interfaces/auth.user.interface"
@Injectable()
export class PasswordStrategy extends PassportStrategy(Strategy, 'password') {
constructor(private readonly authService: AuthService) {
super();
}
validate(username: string, password: string): Promise<AuthUser | null> {
return this.authService.verifyForLogin(username, password);
}
}

View File

@ -1,6 +0,0 @@
import { IsMongoId } from 'class-validator';
export class FindOneDto {
@IsMongoId()
id: string;
}

View File

@ -1,47 +0,0 @@
import {Controller, Request, Get, Post, Put, Delete, UseGuards, Param, NotImplementedException} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth, ApiImplicitQuery, ApiResponse, ApiUseTags } from "@nestjs/swagger"
import { FormService } from "../services/form.service"
import { FormDto } from "../dto/form.dto"
import { FindOneDto } from "../../core/dto/find.one.dto"
@ApiUseTags('forms')
@ApiBearerAuth()
@Controller('forms')
export class FormController {
constructor(private readonly formService: FormService) {}
@Get()
@UseGuards(AuthGuard('jwt'))
async list(@Request() req): Promise<FormDto[]> {
// TODO calculate total forms, add for pagination
const results = await this.formService.findBy({})
return results.map(form => new FormDto(form))
}
@Post()
@UseGuards(AuthGuard('jwt'))
async create(@Request() req): Promise<FormDto> {
throw new NotImplementedException()
}
@ApiResponse({ status: 200, description: 'Form Object', type: FormDto})
@ApiImplicitQuery({name: 'id', type: String})
@Get(':id')
@UseGuards(AuthGuard('jwt'))
async read(@Param() params: FindOneDto): Promise<FormDto> {
return new FormDto(await this.formService.findById(params.id));
}
@Put(':id')
@UseGuards(AuthGuard('jwt'))
async update(@Param() params: FindOneDto, @Request() req): Promise<FormDto> {
throw new NotImplementedException()
}
@Delete(':id')
@UseGuards(AuthGuard('jwt'))
async delete(@Param() params: FindOneDto): Promise<void> {
throw new NotImplementedException()
}
}

View File

@ -1,25 +0,0 @@
import { Controller, Get, Param, NotFoundException } from '@nestjs/common';
import { ApiImplicitQuery, ApiResponse, ApiUseTags } from "@nestjs/swagger"
import { FormService } from "../services/form.service"
import { Form } from "../models/form.model"
import { PublicFormDto } from "../dto/public.form.dto"
import { FindOneDto } from "../../core/dto/find.one.dto"
@ApiUseTags('forms')
@Controller('public')
export class PublicController {
constructor(private readonly formService: FormService) {}
@ApiResponse({ status: 200, description: 'Form Object', type: PublicFormDto})
@ApiImplicitQuery({name: 'id', type: String})
@Get(':id')
async read(@Param() params: FindOneDto): Promise<PublicFormDto> {
const form:Form = await this.formService.findById(params.id)
if (!form.isLive) {
throw new NotFoundException();
}
return new PublicFormDto(form);
}
}

View File

@ -1,39 +0,0 @@
import { ApiModelProperty } from '@nestjs/swagger';
import { Form } from "../models/form.model"
export class FormDto {
@ApiModelProperty()
id: string;
@ApiModelProperty()
title: string;
@ApiModelProperty()
live: boolean;
@ApiModelProperty()
created: Date;
@ApiModelProperty()
lastModified: Date;
@ApiModelProperty()
fields: any;
@ApiModelProperty()
info: {
responses: number;
}
constructor(partial: Partial<Form>) {
this.id = partial._id.toString()
this.title = partial.title
this.live = partial.isLive
this.created = partial.created
this.lastModified = partial.lastModified
this.fields = partial.form_fields
this.info = {
responses: 0 // TODO
}
}
}

View File

@ -1,17 +0,0 @@
import { ApiModelProperty } from '@nestjs/swagger';
import { Form } from "../models/form.model"
export class PublicFormDto {
@ApiModelProperty()
id: string;
@ApiModelProperty()
title: string;
fields: [];
constructor(partial: Partial<Form>) {
this.id = partial._id.toString();
this.title = partial.title
}
}

View File

@ -1,7 +0,0 @@
import { FormController } from "./controllers/form.controller"
import { PublicController } from "./controllers/public.controller"
export default [
FormController,
PublicController,
]

View File

@ -1,15 +0,0 @@
import { Module } from '@nestjs/common';
import controllers from './form.controllers';
import providers from './form.providers'
import {TypegooseModule} from "nestjs-typegoose"
import {Form} from "./models/form.model"
@Module({
imports: [
TypegooseModule.forFeature([Form]),
],
exports: [],
controllers,
providers,
})
export class FormModule {}

View File

@ -1,5 +0,0 @@
import { FormService } from "./services/form.service"
export default [
FormService
]

View File

@ -1,5 +0,0 @@
import { Document } from 'mongoose';
export interface Button extends Document{
}

View File

@ -1,5 +0,0 @@
import { Document } from 'mongoose';
export interface Field extends Document{
}

View File

@ -1,51 +0,0 @@
import { Document } from 'mongoose';
import { Field } from "./field.interface"
import { Button } from "./button.interface"
export class Form extends Document{
readonly firstName: string;
readonly language: string;
readonly analytics: string;
readonly form_fields: Field[];
readonly admin: any;
readonly startPage: {
readonly showStart: boolean;
readonly introTitle: string;
readonly introParagraph: string;
readonly introButtonText: string;
readonly buttons: Button[];
};
readonly endPage: {
readonly showEnd: boolean;
readonly title: string;
readonly paragraph: string;
readonly buttonText: string;
readonly buttons: Button[];
};
readonly selfNotifications: {
readonly fromField: string;
readonly toEmails: string;
readonly subject: string;
readonly htmlTemplate: string;
readonly enabled: boolean;
};
readonly respondentNotifications: {
readonly toField: string;
readonly fromEmails: string;
readonly subject: string;
readonly htmlTemplate: string;
readonly enabled: boolean;
};
readonly showFooter: boolean;
readonly isLive: boolean;
readonly design: {
readonly colors: {
readonly backgroundColor: string;
readonly questionColor: string;
readonly answerColor: string;
readonly buttonColor: string;
readonly buttonTextColor: string;
};
readonly font: string;
};
}

View File

@ -1,14 +0,0 @@
import {prop} from "typegoose"
import {VisitorData} from "./visitor.data"
import {Exclude} from "class-transformer"
export class Analytics {
@Exclude()
readonly _id: string;
@prop()
gaCode: string;
@prop()
visitors: VisitorData[]
}

View File

@ -1,30 +0,0 @@
import {Exclude} from "class-transformer"
import {prop} from "typegoose"
export class Button {
@Exclude()
readonly _id: string;
@prop({
match: /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/
})
url: string;
@prop()
action: string;
@prop()
text: string;
@prop({
match: [/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/],
default: '#5bc0de'
})
bgColor: string;
@prop({
match: [/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/],
default: '#ffffff'
})
color: string;
}

View File

@ -1,37 +0,0 @@
import {prop, Ref, Typegoose} from "typegoose"
import {Exclude} from "class-transformer"
export class Colors {
@Exclude()
readonly _id: string;
@prop({
match: [/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/],
default: '#fff'
})
readonly backgroundColor: string;
@prop({
match: [/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/],
default: '#333'
})
readonly questionColor: string;
@prop({
match: [/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/],
default: '#333'
})
readonly answerColor: string;
@prop({
match: [/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/],
default: '#fff'
})
readonly buttonColor: string;
@prop({
match: [/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/],
default: '#333'
})
readonly buttonTextColor: string;
}

View File

@ -1,14 +0,0 @@
import {prop} from "typegoose"
import {Colors} from "./colors"
import {Exclude} from "class-transformer"
export class Design {
@Exclude()
readonly _id: string;
@prop()
readonly colors: Colors;
@prop()
readonly font: string;
}

View File

@ -1,29 +0,0 @@
import {prop} from "typegoose"
import {Button} from "./button"
import {Exclude} from "class-transformer"
export class EndPage {
@Exclude()
readonly _id: string;
@prop({
default: false
})
readonly showEnd: boolean;
@prop({
default: 'Thank you for filling out the form'
})
readonly title: string;
@prop()
readonly paragraph: string;
@prop({
default: 'Go back to Form'
})
readonly buttonText: string;
@prop()
readonly buttons: Button[];
}

View File

@ -1,19 +0,0 @@
import {prop} from "typegoose"
import {VisitorData} from "./visitor.data"
import {Exclude} from "class-transformer"
export class FieldOption {
@Exclude()
readonly _id: string;
@prop()
option_id: number;
@prop()
option_title: string;
@prop({
trim: true
})
option_value: string;
}

View File

@ -1,83 +0,0 @@
import {arrayProp, prop} from "typegoose"
import {LogicJump} from "./logic.jump"
import {RatingField} from "./rating.field"
import {FieldOption} from "./field.option"
import {Exclude} from "class-transformer"
export class Field {
@Exclude()
readonly _id: string;
@prop({
default: false
})
isSubmission: boolean;
@prop()
submissionId: string;
@prop({
trim: true
})
title: string;
@prop({
default: ''
})
description: string;
@prop()
logicJump: LogicJump;
@prop()
ratingOptions: RatingField;
@arrayProp({
items: FieldOption
})
fieldOptions: FieldOption[];
@prop({
default: true
})
required: boolean;
@prop({
default: false
})
disabled: boolean;
@prop({
default: false
})
deletePreserved: boolean;
@arrayProp({
items: String
})
validFieldTypes: boolean;
@prop({
enum: [
'textfield',
'date',
'email',
'legal',
'textarea',
'link',
'statement',
'dropdown',
'rating',
'radio',
'hidden',
'yes_no',
'number'
]
})
fieldType: string;
@prop({
default: ''
})
fieldValue: any;
}

View File

@ -1,45 +0,0 @@
import {prop, Ref} from "typegoose"
import {VisitorData} from "./visitor.data"
import {Exclude} from "class-transformer"
import {Field} from "./field"
export class LogicJump {
@Exclude()
readonly _id: string;
@prop({
enum: [
'field == static',
'field != static',
'field > static',
'field >= static',
'field <= static',
'field < static',
'field contains static',
'field !contains static',
'field begins static',
'field !begins static',
'field ends static',
'field !ends static'
]
})
expressionString: string;
@prop({
ref: Field
})
fieldA: Ref<Field>;
@prop()
valueB: string;
@prop({
ref: Field
})
jumpTo: Ref<Field>;
@prop({
default: false
})
enabled: boolean;
}

View File

@ -1,38 +0,0 @@
import {arrayProp, prop} from "typegoose"
import {VisitorData} from "./visitor.data"
import {Exclude} from "class-transformer"
export class RatingField {
@Exclude()
readonly _id: string;
@prop({
min: 1,
max: 10
})
steps: number;
@prop({
enum: [
'Heart',
'Star',
'thumbs-up',
'thumbs-down',
'Circle',
'Square',
'Check Circle',
'Smile Outlined',
'Hourglass',
'bell',
'Paper Plane',
'Comment',
'Trash'
]
})
shape: string;
@arrayProp({
items: String
})
validShapes: [string];
}

View File

@ -1,30 +0,0 @@
import {prop} from "typegoose"
import {Exclude} from "class-transformer"
export class RespondentNotifications {
@Exclude()
readonly _id: string;
@prop()
readonly toField: string;
@prop({
match: [/.+\@.+\..+/, 'Please fill a valid email address']
})
readonly fromEmails: string;
@prop({
default: 'OhMyForm: Thank you for filling out this OhMyForm'
})
readonly subject: string;
@prop({
default: 'Hello, <br><br> Weve received your submission. <br><br> Thank you & have a nice day!',
})
readonly htmlTemplate: string;
@prop({
default: false
})
readonly enabled: boolean;
}

View File

@ -1,24 +0,0 @@
import {prop} from "typegoose"
import {Exclude} from "class-transformer"
export class SelfNotifications {
@Exclude()
readonly _id: string;
@prop()
readonly fromField: string;
@prop()
readonly toEmails: string;
@prop()
readonly subject: string;
@prop()
readonly htmlTemplate: string;
@prop({
default: false
})
readonly enabled: boolean;
}

View File

@ -1,29 +0,0 @@
import {prop} from "typegoose"
import {Button} from "./button"
import {Exclude} from "class-transformer"
export class StartPage {
@Exclude()
readonly _id: string;
@prop({
default: false
})
readonly showStart: boolean;
@prop({
default: 'Welcome to Form'
})
readonly introTitle: string;
@prop()
readonly introParagraph: string;
@prop({
default: 'Start'
})
readonly introButtonText: string;
@prop()
readonly buttons: Button[];
}

View File

@ -1,44 +0,0 @@
import {Exclude} from "class-transformer"
import {arrayProp, prop} from "typegoose"
import {Field} from "./field"
import {Ref} from "typegoose/lib/prop"
export class VisitorData {
@Exclude()
readonly _id: string;
@prop()
readonly introParagraph: string;
@prop()
readonly referrer: string;
@arrayProp({
itemsRef: Field
})
readonly filledOutFields: Ref<Field>[];
@prop()
readonly timeElapsed: number;
@prop()
readonly isSubmitted: boolean;
@prop({
enum: ['en', 'fr', 'es', 'it', 'de'],
default: 'en',
})
readonly language: string;
@prop()
readonly ipAddr: string;
@prop({
enum: ['desktop', 'phone', 'tablet', 'other'],
default: 'other'
})
readonly deviceType: string;
@prop()
readonly userAgent: string;
}

View File

@ -1,72 +0,0 @@
import {arrayProp, prop, Ref, Typegoose} from "typegoose"
import {Analytics} from "./embedded/analytics"
import {Field} from "./embedded/field"
import {StartPage} from "./embedded/start.page"
import {EndPage} from "./embedded/end.page"
import {SelfNotifications} from "./embedded/self.notifications"
import {RespondentNotifications} from "./embedded/respondent.notifications"
import {Design} from "./embedded/design"
import {User} from "../../user/models/user.model"
export class Form extends Typegoose {
readonly _id: any;
@prop({
trim: true,
required: 'Form Title cannot be blank'
})
readonly title: string;
@prop()
readonly created: any;
@prop()
readonly lastModified: any;
@prop({
enum: ['en', 'fr', 'es', 'it', 'de'],
default: 'en',
required: 'Form must have a language'
})
readonly language: string;
@prop()
readonly analytics: Analytics;
@arrayProp({
items: Field,
default: []
})
readonly form_fields: Field[];
@prop({
ref: User,
required: 'Form must have an Admin'
})
readonly admin: Ref<User>;
@prop()
readonly startPage: StartPage;
@prop()
readonly endPage: EndPage;
@prop()
readonly selfNotifications: SelfNotifications;
@prop()
readonly respondentNotifications: RespondentNotifications;
@prop({
default: true
})
readonly showFooter: boolean;
@prop({
default: true
})
readonly isLive: boolean;
@prop()
readonly design: Design;
}

View File

@ -1,18 +0,0 @@
import {Injectable} from '@nestjs/common';
import { InjectModel } from 'nestjs-typegoose';
import { ModelType } from 'typegoose';
import {Form} from "../models/form.model"
import {User} from "../../user/models/user.model"
@Injectable()
export class FormService {
constructor(@InjectModel(Form) private readonly formModel: ModelType<Form>) {}
async findById(id: string): Promise<Form> {
return await this.formModel.findById(id).exec()
}
async findBy(conditions): Promise<Form[]> {
return await this.formModel.find(conditions).exec()
}
}

View File

@ -1,12 +0,0 @@
export class OptionsDto {
template: string;
language?: string;
to: string;
cc?: string[];
bcc?: string[];
}

View File

@ -1,5 +0,0 @@
import { MailService } from "./services/mail.service"
export default [
MailService
]

View File

@ -1,12 +0,0 @@
import { Module } from '@nestjs/common';
import providers from './mail.providers'
import exportList from './mail.exports'
import { HandlebarsAdapter, MailerModule } from "@nest-modules/mailer"
@Module({
imports: [
],
providers,
exports: exportList,
})
export class MailModule {}

View File

@ -1,5 +0,0 @@
import { MailService } from "./services/mail.service"
export default [
MailService
]

View File

@ -1,35 +0,0 @@
import {Inject, Injectable, NotFoundException} from '@nestjs/common';
import { OptionsDto } from "../dto/options.dto"
import { MailerService } from '@nest-modules/mailer';
import * as Handlebars from 'handlebars'
import * as fs from 'fs';
@Injectable()
export class MailService {
constructor(
private readonly nodeMailer: MailerService
) {}
async sendEmail(options:OptionsDto, placeholders:any): Promise<boolean> {
const template = fs.readFileSync(`${__dirname}/../../../views/en/mail/${options.template}.hbs`, 'UTF-8');
const parts = Handlebars
.compile(template)
(placeholders)
.split('---')
const mail:any = {
to: options.to,
subject: parts[0],
text: parts[1],
}
if (parts.length > 2) {
mail.html = parts[2]
}
await this.nodeMailer.sendMail(mail)
return false
}
}

View File

@ -1,33 +0,0 @@
import {NestFactory, Reflector} from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';
import { ClassSerializerInterceptor, ValidationPipe } from '@nestjs/common';
import { useContainer } from "class-validator"
const pkg = require('../package.json')
async function bootstrap() {
const app = await NestFactory.create(AppModule, { cors: true });
useContainer(app.select(AppModule), { fallbackOnErrors: true });
app.useGlobalPipes(new ValidationPipe({
disableErrorMessages: false,
transform: true,
}));
app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)))
const options = new DocumentBuilder()
.setTitle('OhMyForm')
.setDescription('API documentation')
.setVersion(pkg.version)
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('doc', app, document);
await app.listen(3000);
}
bootstrap();

View File

@ -1,29 +0,0 @@
import {
TerminusEndpoint,
TerminusOptionsFactory,
DNSHealthIndicator,
MongooseHealthIndicator,
TerminusModuleOptions
} from '@nestjs/terminus';
import { Injectable } from '@nestjs/common';
@Injectable()
export class TerminusOptionsService implements TerminusOptionsFactory {
constructor(
private readonly dns: DNSHealthIndicator,
private readonly mongoose: MongooseHealthIndicator
) {}
createTerminusOptions(): TerminusModuleOptions {
const healthEndpoint: TerminusEndpoint = {
url: '/health',
healthIndicators: [
async () => this.dns.pingCheck('mail', 'https://google.com'),
async () => this.mongoose.pingCheck('mongo')
],
};
return {
endpoints: [healthEndpoint],
};
}
}

View File

@ -1,53 +0,0 @@
import {Controller, Request, Get, Post, Put, Delete, UseGuards, Param, NotImplementedException} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth, ApiImplicitQuery, ApiResponse, ApiUseTags } from "@nestjs/swagger"
import { UserService } from "../services/user.service"
import { UserDto } from "../dto/user.dto"
import { FindOneDto } from "../../core/dto/find.one.dto"
@ApiUseTags('users')
@ApiBearerAuth()
@Controller('users')
export class UserController {
constructor(private readonly userService: UserService) {}
@Get()
@UseGuards(AuthGuard('jwt'))
async list(@Request() req): Promise<UserDto[]> {
// TODO calculate total forms, add for pagination
const results = await this.userService.findBy({})
return results.map(form => new UserDto(form))
}
@ApiResponse({ status: 200, description: 'User Object', type: UserDto})
@Post()
@UseGuards(AuthGuard('jwt'))
async create(@Request() req): Promise<UserDto> {
throw new NotImplementedException()
}
@ApiResponse({ status: 200, description: 'User Object', type: UserDto})
@ApiImplicitQuery({name: 'id', type: String})
@Get(':id')
@UseGuards(AuthGuard('jwt'))
async read(@Param() params: FindOneDto): Promise<UserDto> {
return new UserDto(await this.userService.findById(params.id));
}
@ApiResponse({ status: 200, description: 'User Object', type: UserDto})
@ApiImplicitQuery({name: 'id', type: String})
@Put(':id')
@UseGuards(AuthGuard('jwt'))
async update(@Param() params: FindOneDto, @Request() req): Promise<UserDto> {
throw new NotImplementedException()
}
@ApiResponse({ status: 200, description: 'User Object', type: UserDto})
@ApiImplicitQuery({name: 'id', type: String})
@Delete(':id')
@UseGuards(AuthGuard('jwt'))
async delete(@Param() params: FindOneDto): Promise<void> {
throw new NotImplementedException()
}
}

View File

@ -1,27 +0,0 @@
import { ApiModelProperty } from '@nestjs/swagger';
import {User} from "../models/user.model"
export class UserDto {
@ApiModelProperty()
id: string;
@ApiModelProperty()
username: string;
@ApiModelProperty()
email: string;
@ApiModelProperty()
roles: string[];
@ApiModelProperty()
created: Date;
constructor(partial: Partial<User>) {
this.id = partial._id.toString()
this.username = partial.username
this.email = partial.email
this.roles = partial.roles
this.created = partial.created
}
}

View File

@ -1,97 +0,0 @@
import {arrayProp, pre, prop, Typegoose} from 'typegoose';
import { IsString } from 'class-validator';
import {Exclude} from "class-transformer"
@pre<User>('save', (next) => {
this.lastModified = new Date()
next()
})
export class User extends Typegoose {
@Exclude()
readonly _id: string;
@prop({
trim: true,
default: ''
})
firstName: string;
@prop({
trim: true,
default: ''
})
lastName: string;
@prop({
trim: true,
lowercase: true,
unique: true, // 'Account already exists with this email',
match: [
/^(([^<>()\[\]\\.,;:\s@']+(\.[^<>()\[\]\\.,;:\s@']+)*)|('.+'))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
'Please fill a valid email address'
],
required: [true, 'Email is required']
})
email: string;
@prop({
unique: true,
lowercase: true,
match: [
/^[a-zA-Z0-9\-]+$/,
'Username can only contain alphanumeric characters and \'-\''
],
required: [true, 'Username is required']
})
username: string;
@prop({
default: ''
})
passwordHash: string;
@prop()
salt: string;
@prop({
default: 'local'
})
provider: string;
@arrayProp({
items: String,
enum: ['user', 'admin', 'superuser'],
default: ['user']
})
roles: [string];
@prop({
enum: ['en', 'fr', 'es', 'it', 'de'],
default: 'en',
})
language: string;
@prop({
default: Date.now
})
readonly created: Date;
@prop()
readonly lastModified: Date;
@prop()
resetPasswordToken: string;
@prop()
resetPasswordExpires: Date;
@prop()
token: string;
@prop({
unique: true,
index: true,
sparse: true
})
apiKey: string;
}

View File

@ -1,18 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UserService } from './users.service';
describe('UsersService', () => {
let service: UserService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UserService],
}).compile();
service = module.get<UserService>(UserService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -1,44 +0,0 @@
import {Injectable, NotFoundException} from '@nestjs/common';
import { InjectModel } from 'nestjs-typegoose';
import { ModelType } from 'typegoose';
import { User } from "../models/user.model"
import {Form} from "../../form/models/form.model"
@Injectable()
export class UserService {
constructor(@InjectModel(User) private readonly userModel: ModelType<User>) {}
async findOneByIdentifier(identifier: string): Promise<User> {
const results = await this.userModel.find().or([
{
username: identifier
},
{
email: identifier
}
]).exec();
if (results.length !== 1) {
throw new NotFoundException()
}
return results[0]
}
async findById(id: string): Promise<User> {
return await this.userModel.findById(id).exec()
}
async findOneBy(conditions): Promise<User> {
return await this.userModel.findOne(conditions).exec()
}
async findBy(conditions): Promise<User[]> {
return await this.userModel.find(conditions).exec()
}
async save(user: User): Promise<User> {
let model = new this.userModel(user)
return await model.save()
}
}

View File

@ -1,5 +0,0 @@
import { UserController } from "./controllers/user.controller"
export default [
UserController,
]

View File

@ -1,9 +0,0 @@
import { UserService } from "./services/user.service"
import { UsernameAlreadyInUse } from "./validators/UsernameAlreadyInUse"
import { EmailAlreadyInUse } from "./validators/EmailAlreadyInUse"
export default [
UserService,
UsernameAlreadyInUse,
EmailAlreadyInUse,
]

View File

@ -1,16 +0,0 @@
import { Module } from '@nestjs/common';
import { TypegooseModule } from 'nestjs-typegoose';
import providers from './user.providers'
import exportList from './user.exports'
import { User } from "./models/user.model"
import controllers from './user.controllers'
@Module({
imports: [
TypegooseModule.forFeature([User]),
],
controllers,
providers,
exports: exportList,
})
export class UserModule {}

View File

@ -1,9 +0,0 @@
import { UserService } from "./services/user.service"
import { UsernameAlreadyInUse } from "./validators/UsernameAlreadyInUse"
import { EmailAlreadyInUse } from "./validators/EmailAlreadyInUse"
export default [
UserService,
UsernameAlreadyInUse,
EmailAlreadyInUse,
]

View File

@ -1,20 +0,0 @@
import { ValidationArguments, ValidatorConstraint } from "class-validator"
import { Inject, Injectable } from "@nestjs/common"
import { UserService } from "../services/user.service"
@ValidatorConstraint({ name: 'EmailAlreadyInUse', async: true })
@Injectable()
export class EmailAlreadyInUse {
constructor(
@Inject('UserService') private readonly userService: UserService,
) {}
async validate(text: string) {
const user = await this.userService.findOneBy({email: text});
return !user;
}
defaultMessage(args: ValidationArguments) {
return 'User with this email already exists.';
}
}

View File

@ -1,20 +0,0 @@
import { ValidationArguments, ValidatorConstraint } from "class-validator"
import { Inject, Injectable } from "@nestjs/common"
import { UserService } from "../services/user.service"
@ValidatorConstraint({ name: 'UsernameAlreadyInUse', async: true })
@Injectable()
export class UsernameAlreadyInUse {
constructor(
@Inject('UserService') private readonly userService: UserService,
) {}
async validate(text: string) {
const user = await this.userService.findOneBy({username: text});
return !user;
}
defaultMessage(args: ValidationArguments) {
return 'User with this username already exists.';
}
}

View File

@ -1,4 +0,0 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

View File

@ -1,15 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true
},
"exclude": ["node_modules", "dist"]
}

View File

@ -1,59 +0,0 @@
{
"defaultSeverity": "error",
"extends": [
"tslint:recommended"
],
"jsRules": {
"no-unused-expression": true
},
"rules": {
"eofline": false,
"quotemark": [
true,
"single"
],
"indent": false,
"member-access": [
false
],
"ordered-imports": [
false
],
"max-line-length": [
true,
150
],
"member-ordering": [
false
],
"curly": false,
"interface-name": [
false
],
"array-type": [
false
],
"no-empty-interface": false,
"no-empty": false,
"arrow-parens": false,
"object-literal-sort-keys": false,
"no-unused-expression": false,
"max-classes-per-file": [
false
],
"variable-name": [
false
],
"one-line": [
false
],
"one-variable-per-declaration": [
false
],
"whitespace": [
true,
"check-postbrace"
]
},
"rulesDirectory": []
}

View File

@ -1,19 +0,0 @@
Password Reset Request
---
Hi,
if you have not requested a new password you can ignore this email. To set a new password for your account
just follow this link: {{ recover }}
See you soon
---
<h1>Hi, </h1>
<p>
if you have not requested a new password you can ignore this email. To set a new password for your account
just follow this link: <a href="{{ recover }}">{{ recover }}</a>
</p>
<p>
See you soon
</p>

View File

@ -1,14 +0,0 @@
Welcome to OhMyForm
---
Welcome to OhMyForm!
please confirm your account by following the following link: {{ confirm }}
enjoy!
---
<h1>Welcome to OhMyForm!</h1>
<p>
please confirm your account by following the following link: <a href="{{ confirm }}">{{ confirm }}</a>
</p>
<p>enjoy!</p>

View File

@ -1,32 +0,0 @@
'use strict';
var config = require('../../config/config');
/**cd
* Module dependencies.
*/
exports.index = function(req, res) {
res.render('index', {
user: req.user || null,
request: req
});
};
exports.form = function(req, res) {
//Allow form to be embedded
res.removeHeader('X-Frame-Options');
res.render('form', {
user: req.user || null,
request: req
});
};
exports.redoc = function(req, res) {
res.render('redoc', {
request: req
});
};

View File

@ -1,46 +0,0 @@
'use strict';
/**
* Get unique error field name
*/
var getUniqueErrorMessage = function(err) {
var output;
try {
var fieldName = err.err.substring(err.err.lastIndexOf('.$') + 2, err.err.lastIndexOf('_1'));
output = fieldName.charAt(0).toUpperCase() + fieldName.slice(1) + ' already exists';
} catch (ex) {
output = 'Unique field already exists';
}
return output;
};
/**
* Get the error message from error object
*/
exports.getErrorMessage = function(err) {
var message = '';
if(!err) {
return 'Unknown Error';
} else if(typeof err === 'string'){
message = err;
} else if (err.code) {
switch (err.code) {
case 11000:
case 11001:
message = getUniqueErrorMessage(err);
break;
default:
message = 'Something went wrong';
}
} else {
for (var errName in err.errors) {
if (err.errors[errName].message) message = err.errors[errName].message;
}
}
return message;
};

View File

@ -1,561 +0,0 @@
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Form = mongoose.model('Form'),
FormSubmission = mongoose.model('FormSubmission'),
config = require('../../config/config'),
diff = require('deep-diff'),
_ = require('lodash'),
nodemailer = require('nodemailer'),
emailNotifications = require('../libs/send-email-notifications'),
constants = require('../libs/constants'),
helpers = require('./helpers.server.controller'),
async = require('async');
var smtpTransport = nodemailer.createTransport(config.mailer.options);
/**
* Delete a forms submissions
*/
exports.deleteSubmissions = function(req, res) {
var submission_id_list = req.body.deleted_submissions;
FormSubmission.remove({ form: req.form, _id: {$in: submission_id_list} }, function(err){
if(err){
res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
return;
}
res.status(200).send('Form submissions successfully deleted');
});
};
/**
* Submit a form entry
*/
exports.createSubmission = function(req, res) {
var timeElapsed = 0;
if(typeof req.body.timeElapsed === 'number'){
timeElapsed = req.body.timeElapsed;
}
var submission = new FormSubmission({
form: req.body._id,
form_fields: req.body.form_fields,
timeElapsed: timeElapsed,
percentageComplete: req.body.percentageComplete,
ipAddr: req.body.ipAddr,
geoLocation: req.body.geoLocation,
device: req.body.device
});
submission.save(function(err, submission){
if (err) {
console.error(err.message);
return res.status(500).send({
message: errorHandler.getErrorMessage(err)
});
}
var form = req.body;
var formFieldDict = emailNotifications.createFieldDict(form.form_fields);
async.waterfall([
function(callback) {
if (form.selfNotifications && form.selfNotifications.enabled) {
if(form.selfNotifications.fromField){
form.selfNotifications.fromEmails = formFieldDict[form.selfNotifications.fromField];
} else {
form.selfNotifications.fromEmails = config.mailer.options.from;
}
emailNotifications.send(form.selfNotifications, formFieldDict, smtpTransport, function(err){
if(err){
return callback({
message: 'Failure sending submission self-notification email'
});
}
callback();
});
} else {
callback();
}
},
function(callback) {
if (form.respondentNotifications && form.respondentNotifications.enabled && form.respondentNotifications.toField) {
form.respondentNotifications.toEmails = formFieldDict[form.respondentNotifications.toField];
emailNotifications.send(form.respondentNotifications, formFieldDict, smtpTransport, function(err){
if(err){
return callback({
message: 'Failure sending submission respondent-notification email'
});
}
callback();
});
} else {
callback();
}
}
], function (err) {
if(err){
return res.status(400).send(err);
}
res.status(200).send('Form submission successfully saved');
});
});
};
/**
* Get List of Submissions for a given Form
*/
exports.listSubmissions = function(req, res) {
FormSubmission.find({ form: req.form._id }).sort('created').lean().exec(function(err, _submissions) {
if (err) {
console.error(err);
return res.status(500).send({
message: errorHandler.getErrorMessage(err)
});
}
res.json(_submissions);
});
};
/**
* Get Visitor Analytics Data for a given Form
*/
exports.getVisitorData = function(req, res) {
var results = [];
Form.aggregate([
{
$match: {
_id: mongoose.Types.ObjectId(req.form.id),
admin: mongoose.Types.ObjectId(req.user.id)
}
},
{
$facet: {
'deviceStatistics': [
{
$unwind: '$analytics.visitors'
},
{
$project: {
_id: 0,
deviceType: '$analytics.visitors.deviceType',
SubmittedTimeElapsed: {
$cond: [
{
$eq: ['$analytics.visitors.isSubmitted', true]
},
'$analytics.visitors.timeElapsed',
0
]
},
SubmittedResponses: {
$cond: [
{
$eq: ['$analytics.visitors.isSubmitted', true]
},
1,
0
]
}
}
},
{
$group: {
_id: '$deviceType',
total_time: { $sum: '$SubmittedTimeElapsed' },
responses: { $sum: '$SubmittedResponses' },
visits: { $sum: 1 }
}
},
{
$project: {
total_time: '$total_time',
responses: '$responses',
visits: '$visits',
average_time: {
$cond: [
{ $eq: [ '$responses', 0 ] },
0,
{ $divide: ['$total_time', '$responses'] }
]
},
conversion_rate: {
$multiply: [
100,
{
$cond: [
{ $eq: [ '$visits', 0 ] },
0,
{ $divide: ['$responses', '$visits'] }
]
}
]
}
}
}
],
'globalStatistics': [
{
$unwind: '$analytics.visitors'
},
{
$project: {
_id: 0,
deviceType: '$analytics.visitors.deviceType',
SubmittedTimeElapsed: {
$cond: [
{
$eq: ['$analytics.visitors.isSubmitted', true]
},
'$analytics.visitors.timeElapsed',
0
]
},
SubmittedResponses: {
$cond: [
{
$eq: ['$analytics.visitors.isSubmitted', true]
},
1,
0
]
}
}
},
{
$group: {
_id: null,
total_time: { $sum: '$SubmittedTimeElapsed' },
responses: { $sum: '$SubmittedResponses' },
visits: { $sum: 1 }
}
},
{
$project: {
_id: 0,
total_time: '$total_time',
responses: '$responses',
visits: '$visits',
average_time: {
$cond: [
{ $eq: [ '$responses', 0 ] },
0,
{ $divide: ['$total_time', '$responses'] }
]
},
conversion_rate: {
$multiply: [
100,
{
$cond: [
{ $eq: [ '$visits', 0 ] },
0,
{ $divide: ['$responses', '$visits'] }
]
}
]
}
}
}
],
}
}
])
.cursor()
.exec()
.on('end', function() {
res.json(results);
})
.on('data', function(entry){
results.push(entry);
});
};
/**
* Create a new form
*/
exports.create = function(req, res) {
if(!req.body.form){
return res.status(400).send({
message: 'Invalid Input'
});
}
var form = new Form(req.body.form);
form.admin = req.user._id;
form.save(function(err, createdForm) {
if (err) {
return res.status(500).send({
message: errorHandler.getErrorMessage(err)
});
}
createdForm = helpers.removeSensitiveModelData('private_form', createdForm.toJSON());
return res.json(createdForm);
});
};
/**
* Show the current form
*/
exports.read = function(req, res) {
if(!req.user || (req.form.admin.id !== req.user.id) ){
readForRender(req, res);
} else {
if(!req.form){
return res.status(404).send({
message: 'Form Does Not Exist'
});
}
var newForm = helpers.removeSensitiveModelData('private_form', req.form.toJSON());
return res.json(newForm);
}
};
/**
* Show the current form for rendering form live
*/
var readForRender = exports.readForRender = function(req, res) {
var newForm = req.form;
if (!newForm.isLive && !req.user) {
return res.status(401).send({
message: 'Form is Not Public'
});
}
newForm = helpers.removeSensitiveModelData('public_form', newForm);
if(newForm.startPage && !newForm.startPage.showStart){
delete newForm.startPage;
}
return res.json(newForm);
};
/**
* Update a form
*/
exports.update = function(req, res) {
var form = req.form;
var updatedForm = req.body.form;
if(!form.analytics){
form.analytics = {
visitors: [],
gaCode: ''
};
}
if (req.body.changes) {
var formChanges = req.body.changes;
formChanges.forEach(function (change) {
diff.applyChange(form._doc, true, change);
});
} else {
if(!updatedForm){
return res.status(400).send({
message: 'Updated Form is empty'
});
}
delete updatedForm.lastModified;
delete updatedForm.created;
delete updatedForm.id;
delete updatedForm._id;
delete updatedForm.__v;
//Unless we have 'admin' privileges, updating the form's admin is disabled
if(updatedForm && req.user.roles.indexOf('admin') === -1) {
delete updatedForm.admin;
}
//Do this so we can create duplicate fields
var checkForValidId = new RegExp('^[0-9a-fA-F]{24}$');
for(var i=0; i < req.body.form.form_fields.length; i++){
var field = req.body.form.form_fields[i];
if(!checkForValidId.exec(field._id+'')){
delete field._id;
}
}
form = _.extend(form, updatedForm);
}
form.save(function(err, savedForm) {
if (err) {
res.status(500).send({
message: errorHandler.getErrorMessage(err)
});
} else {
savedForm = helpers.removeSensitiveModelData('private_form', savedForm.toJSON());
res.json(savedForm);
}
});
};
/**
* Delete a form
*/
exports.delete = function(req, res) {
var form = req.form;
Form.remove({_id: form._id}, function(err) {
if (err) {
res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(
helpers.removeSensitiveModelData('private_form', form)
);
}
});
};
/**
* Get All of Users' Forms
*/
exports.list = function(req, res) {
//Allow 'admin' user to view all forms
var searchObj = {admin: req.user};
if(req.user.isAdmin()) searchObj = {};
Form.find(searchObj)
.sort('-created')
.select('title language isLive')
.lean()
.exec(function(err, forms) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
var form_ids = forms.map(function(form){
return form._id;
});
//Get number of submissions for each form
FormSubmission
.aggregate()
.match({
form: {
$in: form_ids
}
})
.group({
_id: '$form',
responses: { $sum: 1 }
})
.cursor()
.exec()
.on('end', function() {
forms = forms.map(function (form) {
if (!form.submissionNum) {
form.submissionNum = 0;
}
return helpers.removeSensitiveModelData('private_form', form);
});
res.json(forms);
})
.on('data', function(result){
forms = forms.map(function (form) {
if (_.isEqual(form._id, result._id)) {
form.submissionNum = result.responses;
}
return form;
});
});
});
};
/**
* Form middleware
*/
exports.formByID = function(req, res, next, id) {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({
message: 'Form is invalid'
});
}
Form.findById(id)
.select('admin title language form_fields startPage endPage showFooter isLive design analytics.gaCode respondentNotifications selfNotifications')
.populate('admin')
.exec(function(err, form) {
if (err) {
return next(err);
} else if (!form || form === null) {
res.status(404).send({
message: 'Form not found'
});
}
else {
req.form = form;
return next();
}
});
};
/**
* FastForm middleware
*/
exports.formByIDFast = function(req, res, next, id) {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({
message: 'Form is invalid'
});
}
Form.findById(id)
.lean()
.select('title language form_fields startPage endPage showFooter isLive design analytics.gaCode selfNotifications respondentNotifications')
.exec(function(err, form) {
if (err) {
return next(err);
} else if (!form || form === null) {
res.status(404).send({
message: 'Form not found'
});
}
else {
//Remove sensitive information from User object
req.form = form;
return next();
}
});
};
/**
* Form authorization middleware
*
* reject access if the owner of the form is not the current user and the user is not an admin
*/
exports.hasAuthorization = function(req, res, next) {
var form = req.form;
if (!req.form.admin || req.form.admin.id !== req.user.id && req.user.roles.indexOf('admin') < 0) {
return res.status(403).send({
message: 'User '+req.user.username+' is not authorized to edit Form: '+form.title
});
}
return next();
};

View File

@ -1,33 +0,0 @@
'use strict';
const constants = require('../libs/constants');
const _ = require('lodash');
module.exports = {
removeKeysFromDict: function(dict, keys){
for(var i=0; i<keys.length; i++){
var curr_key = keys[i];
if( dict.hasOwnProperty(curr_key) ){
delete dict[curr_key];
}
}
return dict;
},
removeSensitiveModelData: function(type, actual_object){
if (typeof actual_object.toJSON === 'function') {
actual_object = actual_object.toJSON();
}
var object = _.cloneDeep(actual_object);
if(constants.privateFields.hasOwnProperty(type)) {
object = this.removeKeysFromDict(object, constants.privateFields[type]);
}
if(object.admin){
object.admin = this.removeKeysFromDict(object.admin, constants.privateFields.private_user);
}
debugger;
return object;
}
};

View File

@ -1,16 +0,0 @@
'use strict';
/**
* Module dependencies.
*/
let _ = require('lodash');
/**
* Extend user's controller
*/
module.exports = _.extend(
require('./users/users.authentication.server.controller'),
require('./users/users.authorization.server.controller'),
require('./users/users.password.server.controller'),
require('./users/users.profile.server.controller')
);

View File

@ -1,238 +0,0 @@
'use strict';
/**
* Module dependencies.
*/
var errorHandler = require('../errors.server.controller'),
mongoose = require('mongoose'),
passport = require('passport'),
config = require('../../../config/config'),
User = mongoose.model('User'),
tokgen = require('../../libs/tokenGenerator'),
fs = require('fs'),
i18n = require('i18n'),
async = require('async'),
pug = require('pug'),
helpers = require('../helpers.server.controller');
var nev = require('email-verification')(mongoose);
// NEV setup and configuration ================
var config_nev = function () {
nev.configure({
verifyMailOptions: {
from: config.mailer.from
},
confirmMailOptions: {
from: config.mailer.from
},
persistentUserModel: User,
tempUserCollection: config.tempUserCollection,
emailAndUsernameUnique: true,
expirationTime: 86400, // 24 hours
verificationURL: config.baseUrl+'/#!/verify/${URL}',
transportOptions: config.mailer.options,
verifySendMailCallback: function(err, info) {
if (err) {
throw err;
}
}
}, function(err, options){
if(err) {
throw err;
}
});
nev.generateTempUserModel(User, function(err){
if(err) {
throw err;
}
});
};
config_nev();
exports.validateVerificationToken = function(req, res){
const fn = pug.compileFile(__dirname + '/../../views/welcome.email.view.pug');
var renderedHtml = fn(res.locals);
var emailTemplate = {
subject: i18n.__('WELCOME_EMAIL_SUBJECT', config.app.title),
html: renderedHtml,
text: i18n.__('WELCOME_EMAIL_TEXT')
};
nev.confirmTempUser(req.params.token, emailTemplate, function(err, user) {
if(err) {
return res.status(500).send( {message: err } );
} else if (user){
return res.status(200).send('User successfully verified');
}
// redirect to resend verification email
else {
return res.status(400).send( {message: 'Verification token is invalid or has expired'} );
}
});
};
exports.resendVerificationEmail = function(req, res, next){
const fn = pug.compileFile(__dirname + '/../../views/verification.email.view.pug');
var renderedHtml = fn(res.locals);
var emailTemplate = {
subject: i18n.__('VERIFICATION_EMAIL_SUBJECT'),
html: renderedHtml,
text: i18n.__('VERIFICATION_EMAIL_TEXT')
};
nev.resendVerificationEmail(req.body.email, emailTemplate, function(err, userFound) {
if(err) {
return res.status(500).send( {message: errorHandler.getErrorMessage(err) } );
}
if (userFound){
res.status(200).send('Verification email successfully Re-Sent');
}else {
// user hasn't been found yet
res.status(400).send( {message: 'Error: User has not been registered yet'} );
}
});
};
/**
* Signup
*/
exports.signup = function(req, res) {
// For security measures we remove the roles from the req.body object
delete req.body.roles;
// Init Variables
var user = new User(req.body);
// Set language to visitor's language
user.language = req.cookies.userLang;
// Add missing user fields
user.provider = 'local';
// Then save the temporary user
nev.createTempUser(user, function (err, existingPersistentUser, newTempUser) {
if (err) {
console.error('failed to register user', err)
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
// new user created
if (newTempUser) {
let renderedHtml;
try {
let fn = pug.compileFile(__dirname + '/../../views/verification.email.view.pug', {});
renderedHtml = fn(res.locals);
} catch (e) {
console.error('failed to compile mail template', e);
renderedHtml = 'welcome!';
}
let URL = newTempUser[nev.options.URLFieldName];
let emailTemplate = {
subject: i18n.__('VERIFICATION_EMAIL_SUBJECT'),
html: renderedHtml,
text: i18n.__('VERIFICATION_EMAIL_TEXT')
};
nev.sendVerificationEmail(user.email, URL, emailTemplate, function (sendEmailErr, info) {
if (sendEmailErr) {
console.error('failed to send verification email', sendEmailErr)
return res.status(400).send({
message: 'Could not send Verification Email'
});
}
return res.status(200).send({message: 'An email has been sent to you. Please check it to verify your account.'});
});
} else {
return res.status(400).send({message: 'User with username/email already exists!'});
}
});
};
/**
* Signin after passport authentication
*/
exports.signin = function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err || !user) {
res.status(400).send(info);
} else {
// Remove sensitive data before login
user.password = null;
user.salt = null;
user.provider = null;
req.login(user, function(loginErr) {
if (loginErr) {
return res.status(400).send({
message: errorHandler.getErrorMessage(loginErr)
});
}
res.cookie('langCookie', user.language, { maxAge: 90000, httpOnly: true });
user = helpers.removeSensitiveModelData('private_user', user.toJSON());
return res.json(user);
});
}
})(req, res, next);
};
/**
* Signout
*/
exports.signout = function(req, res) {
if(req.cookies.hasOwnProperty('userLang')){
res.clearCookie('userLang');
}
req.logout();
return res.status(200).send('You have successfully logged out.');
};
/* Generate API Key for User */
exports.generateAPIKey = function(req, res) {
User.findById(req.user.id)
.exec( function(err, user) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
if (!user) {
return res.status(400).send({
message: 'User does not Exist'
});
}
user.apiKey = tokgen();
user.save(function(userSaveErr, _user) {
if (userSaveErr) {
return res.status(400).send({
message: errorHandler.getErrorMessage(userSaveErr)
});
}
var newUser = _user.toObject();
return res.json({ id: newUser._id, apiKey: newUser.apiKey });
});
});
};

View File

@ -1,18 +0,0 @@
'use strict';
/**
* Module dependencies.
*/
var auth = require('../../../config/passport_helpers');
/**
* Require login routing middleware
*/
exports.requiresLogin = function(req, res, next) {
if (!req.isAuthenticated()) {
return res.status(401).send({
message: 'User is not logged in'
});
} else {
return next();
}
};

View File

@ -1,287 +0,0 @@
'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
errorHandler = require('../errors.server.controller'),
mongoose = require('mongoose'),
passport = require('passport'),
User = mongoose.model('User'),
config = require('../../../config/config'),
nodemailer = require('nodemailer'),
async = require('async'),
crypto = require('crypto'),
pug = require('pug');
var smtpTransport = nodemailer.createTransport(config.mailer.options);
/**
* Forgot for reset password (forgot POST)
*/
exports.forgot = function(req, res) {
async.waterfall([
// Generate random token
function(done) {
crypto.randomBytes(20, function(err, buffer) {
var token = buffer.toString('hex');
done(err, token);
});
},
// Lookup user by username
function(token, done) {
if (req.body.username) {
User.findOne({
$or: [
{'username': req.body.username.toLowerCase()},
{'email': req.body.username}
]
}, '-salt -password', function(err, user) {
if(err){
return res.status(500).send({
message: err.message
});
}
if (!user) {
var tempUserModel = mongoose.model(config.tempUserCollection);
tempUserModel.findOne({
$or: [
{'username': req.body.username.toLowerCase()},
{'email': req.body.username}
]
}).lean().exec(function(err, user) {
if(err){
return res.status(500).send({
message: err.message
});
}
if(!user){
return res.status(400).send({
message: 'No account with that username or email has been found'
});
}
return res.status(400).send({
message: 'The account associated with this email has not been activated yet'
});
});
} else {
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
user.save(function(err) {
done(err, token, user);
});
}
});
} else {
return res.status(400).send({
message: 'Username field must not be blank'
});
}
},
function(token, user, done) {
const fn = pug.compileFile(__dirname + '/../../views/templates/reset-password-email.server.view.pug');
res.locals.url = 'http://' + req.headers.host + '/auth/reset/' + token;
var renderedHtml = fn(res.locals);
done(null, renderedHtml, user);
},
// If valid email, send reset email using service
function(emailHTML, user, done) {
var mailOptions = {
to: user.email,
from: config.mailer.from,
subject: 'Password Reset',
html: emailHTML
};
var userEmail = user.email;
var emailUsername = userEmail.split('@')[0];
var domain = userEmail.split('@')[1];
var obfuscatedUser = emailUsername.substring(0, 1) + emailUsername.substring(1).replace(/./g, '*');
var domainName = domain.split('.')[0];
var tld = domain.split('.')[1];
var obfuscatedDomainName = domainName.replace(/./g, '*');
var obfuscatedEmail = obfuscatedUser + '@' + obfuscatedDomainName + '.' + tld;
smtpTransport.sendMail(mailOptions, function(err) {
done(err, obfuscatedEmail);
});
}
], function(err, obfuscatedEmail) {
if (err) {
return res.status(400).send({
message: 'Couldn\'t send reset password email due to internal server errors. Please contact support at team@ohmyform.com.'
});
} else {
return res.send({
message: 'An email has been sent to ' + obfuscatedEmail + ' with further instructions.'
});
}
});
};
/**
* Reset password GET from email token
*/
exports.validateResetToken = function(req, res) {
User.findOne({
resetPasswordToken: req.params.token,
resetPasswordExpires: {
$gt: Date.now()
}
}, function(err, user) {
if(err){
return res.status(500).send({
message: err.message
});
}
if (!user) {
return res.redirect(400, '/#!/password/reset/invalid');
}
res.redirect('/#!/password/reset/' + req.params.token);
});
};
/**
* Reset password POST from email token
*/
exports.reset = function(req, res, next) {
if(req.body.newPassword.length < 4){
return res.status(400).send({
message: 'Password must be at least 4 characters long'
});
}
if(req.body.newPassword !== req.body.verifyPassword){
return res.status(400).send({
message: 'Passwords do not match'
});
}
// Init Variables
var passwordDetails = req.body;
async.waterfall([
function(done) {
User.findOne({
resetPasswordToken: req.params.token,
resetPasswordExpires: {
$gt: Date.now()
}
}, function(err, user) {
if (!err && user) {
user.password = passwordDetails.newPassword;
user.resetPasswordToken = null;
user.resetPasswordExpires = null;
user.save(function(err, savedUser) {
if (err) {
done(err, null);
}
done(null, savedUser);
});
} else {
done('invalid_reset_token', null);
}
});
},
function(user, done) {
const fn = pug.compileFile(__dirname + '/../../views/templates/reset-password-confirm-email.server.view.pug');
const renderedHtml = fn(res.locals);
done(null, renderedHtml, user);
},
// If valid email, send reset email using service
function(emailHTML, user, done) {
var mailOptions = {
to: user.email,
from: config.mailer.from,
subject: 'Your password has been changed',
html: emailHTML
};
smtpTransport.sendMail(mailOptions, function(err) {
done(err);
});
}
], function(err) {
if (err) {
if(err === 'invalid_reset_token'){
return res.status(400).send({
message: 'Password reset token is invalid or has expired.'
});
}
return res.status(500).send({
message: err.message || err
});
}
res.json({
message: 'Successfully changed your password!'
});
});
};
/**
* Change Password
*/
exports.changePassword = function(req, res) {
// Init Variables
var passwordDetails = req.body;
if (req.user) {
if (passwordDetails.newPassword) {
User.findById(req.user.id, function(err, user) {
if (!err && user) {
if (user.authenticate(passwordDetails.currentPassword)) {
if (passwordDetails.newPassword === passwordDetails.verifyPassword) {
user.password = passwordDetails.newPassword;
user.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
req.login(user, function(err) {
if (err) {
res.status(400).send(err);
} else {
res.send({
message: 'Password changed successfully'
});
}
});
}
});
} else {
res.status(400).send({
message: 'Passwords do not match'
});
}
} else {
res.status(400).send({
message: 'Current password is incorrect'
});
}
} else {
res.status(400).send({
message: 'User is not found'
});
}
});
} else {
res.status(400).send({
message: 'Please provide a new password'
});
}
} else {
res.status(400).send({
message: 'User is not signed in'
});
}
};

View File

@ -1,52 +0,0 @@
'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
errorHandler = require('../errors.server.controller.js'),
mongoose = require('mongoose'),
helpers = require('../helpers.server.controller');
/**
* Update user details
*/
exports.update = function(req, res) {
// Init Variables
var user = req.user;
// To improve security we remove the roles from the req.body object
delete req.body.roles;
debugger;
// Merge existing user
user = _.extend(user, req.body);
user.updated = Date.now();
user.save(function(err) {
if (err) {
return res.status(500).send({
message: errorHandler.getErrorMessage(err)
});
}
req.login(user, function(loginErr) {
if (err) {
res.status(500).send(loginErr);
} else {
user = helpers.removeSensitiveModelData('private_user', user.toJSON());
res.json(user);
}
});
});
};
/**
* Send User
*/
exports.getUser = function(req, res) {
var user = helpers.removeSensitiveModelData('private_user', req.user.toJSON());
return res.json(user);
};

View File

@ -1,99 +0,0 @@
'use strict';
var constants = module.exports = {
extraneousFormFieldProps: [
'validFieldTypes',
'disabled',
'required',
'isSubmission',
'title',
'fieldOptions',
'ratingOptions',
'logicJump',
'description',
'created',
'lastModified',
'deletePreserved'
],
fieldTypes: [
'textfield',
'date',
'email',
'legal',
'textarea',
'link',
'statement',
'dropdown',
'rating',
'radio',
'hidden',
'yes_no',
'number'
],
ratingShapeTypes: [
'Heart',
'Star',
'thumbs-up',
'thumbs-down',
'Circle',
'Square',
'Check Circle',
'Smile Outlined',
'Hourglass',
'bell',
'Paper Plane',
'Comment',
'Trash'
],
deviceTypes: ['desktop', 'phone', 'tablet', 'other'],
languageTypes: ['en', 'fr', 'es', 'it', 'de'],
langCodeToWord: {
'en': 'English',
'fr': 'Français',
'es': 'Español',
'it': 'Italiàno',
'de': 'Deutsch'
},
wordToLangCode: {
'English': 'en',
'Français': 'fr',
'Español': 'es',
'Italiàno': 'it',
'Deutsch': 'de'
},
privateFields: {
'public_form': ['__v', 'analytics.visitors', 'analytics.views', 'analytics.conversionRate', 'analytics.fields', 'lastModified', 'created'],
'private_form': ['__v'],
'public_user': ['passwordHash', 'password', 'provider', 'salt', 'lastModified', 'created', 'resetPasswordToken', 'resetPasswordExpires', 'token', 'apiKey', '__v'],
'private_user': ['passwordHash', 'password', 'provider', 'salt', 'resetPasswordToken', 'resetPasswordExpires', 'token', '__v']
},
expressionStringTypes: ['field == static',
'field != static',
'field > static',
'field >= static',
'field <= static',
'field < static',
'field contains static',
'field !contains static',
'field begins static',
'field !begins static',
'field ends static',
'field !ends static'],
userRoleTypes: ['user', 'admin', 'superuser'],
regex: {
username: /^[a-zA-Z0-9\-]+$/,
url: /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/,
hexCode: /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,
email: /^(([^<>()\[\]\\.,;:\s@']+(\.[^<>()\[\]\\.,;:\s@']+)*)|('.+'))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
}
};

View File

@ -1,48 +0,0 @@
'use strict';
const jsdom = require('jsdom');
var JSDOM = jsdom.JSDOM;
module.exports = {
send: function(emailSettings, emailTemplateVars, smtpTransport, cb){
var parsedTemplate = this.parseTemplate(emailSettings.htmlTemplate, emailTemplateVars, false);
var parsedSubject = this.parseTemplate(emailSettings.subject, emailTemplateVars, true);
var mailOptions = {
replyTo: emailSettings.fromEmails,
from: 'noreply@ohmyform.com',
cc: emailSettings.toEmails,
subject: parsedSubject,
html: parsedTemplate
};
smtpTransport.sendMail(mailOptions, function(err){
cb(err);
});
},
parseTemplate: function(emailTemplate, emailTemplateVars, onlyText){
var dom = new JSDOM('<!doctype html>'+emailTemplate);
Object.keys(emailTemplateVars).forEach(function (key) {
var elem = dom.window.document.querySelector('span.placeholder-tag[data-id=\'' + key + '\']');
if(elem !== null){
elem.outerHTML = emailTemplateVars[key];
}
});
if(onlyText){
return dom.window.document.documentElement.textContent;
}
return dom.serialize();
},
createFieldDict: function(form_fields){
var formFieldDict = {};
form_fields.forEach(function(field){
if(field.hasOwnProperty('fieldValue') && field.hasOwnProperty('_id')){
formFieldDict[field._id] = String(field.fieldValue);
}
});
return formFieldDict;
}
};

View File

@ -1,37 +0,0 @@
'use strict';
// Plugin
module.exports = function timestamp (schema, options) {
options = options || (options === {});
// Options
var fields = {},
createdPath = options.createdPath || 'created',
modifiedPath = options.modifiedPath || 'modified',
useVirtual = (options.useVirtual !== undefined) ? options.useVirtual : true;
// Add paths to schema if not present
if (!schema.paths[createdPath]) {
fields[modifiedPath] = { type: Date };
}
if (useVirtual) {
// Use the ObjectID for extracting the created time
schema.virtual(createdPath).get(function () {
return new Date(this._id.generationTime * 1000);
});
} else {
if (!schema.paths[createdPath]) {
fields[createdPath] = {
type: Date,
default: Date.now
};
}
}
schema.add(fields);
// Update the modified timestamp on save
schema.pre('save', function (next) {
this[modifiedPath] = new Date();
next();
});
};

View File

@ -1,8 +0,0 @@
'use strict';
var TokenGenerator = require('uuid-token-generator');
var tokgen = new TokenGenerator(256, TokenGenerator.BASE62);
module.exports = function() {
return tokgen.generate();
};

View File

@ -1,244 +0,0 @@
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
_ = require('lodash'),
timeStampPlugin = require('../libs/timestamp.server.plugin'),
async = require('async'),
constants = require('../libs/constants');
//Mongoose Models
var FieldSchema = require('./form_field.server.model.js');
var ButtonSchema = new Schema({
url: {
type: String,
match: [/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/],
},
action: String,
text: String,
bgColor: {
type: String,
match: [/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/],
default: '#5bc0de'
},
color: {
type: String,
match: [/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/],
default: '#ffffff'
}
});
var VisitorDataSchema = new Schema({
socketId: {
type: String
},
referrer: {
type: String
},
filledOutFields: {
type: [Schema.Types.ObjectId]
},
timeElapsed: {
type: Number
},
isSubmitted: {
type: Boolean
},
language: {
type: String,
enum: constants.languageTypes,
default: 'en',
},
ipAddr: {
type: String
},
deviceType: {
type: String,
enum: ['desktop', 'phone', 'tablet', 'other'],
default: 'other'
},
userAgent: {
type: String
}
});
var formSchemaOptions = {
toJSON: {
virtuals: true
}
};
/**
* Form Schema
*/
var FormSchema = new Schema({
title: {
type: String,
trim: true,
required: 'Form Title cannot be blank'
},
language: {
type: String,
enum: ['en', 'fr', 'es', 'it', 'de'],
default: 'en',
required: 'Form must have a language'
},
analytics:{
gaCode: {
type: String
},
visitors: [VisitorDataSchema]
},
form_fields: {
type: [FieldSchema],
default: []
},
admin: {
type: Schema.Types.ObjectId,
ref: 'User',
required: 'Form must have an Admin'
},
startPage: {
showStart:{
type: Boolean,
default: false
},
introTitle:{
type: String,
default: 'Welcome to Form'
},
introParagraph:{
type: String
},
introButtonText:{
type: String,
default: 'Start'
},
buttons:[ButtonSchema]
},
endPage: {
showEnd:{
type: Boolean,
default: false
},
title:{
type: String,
default: 'Thank you for filling out the form'
},
paragraph:{
type: String
},
buttonText:{
type: String,
default: 'Go back to Form'
},
buttons:[ButtonSchema]
},
selfNotifications: {
fromField: {
type: String
},
toEmails: {
type: String
},
subject: {
type: String
},
htmlTemplate: {
type: String
},
enabled: {
type: Boolean,
default: false
}
},
respondentNotifications: {
toField: {
type: String
},
fromEmails: {
type: String,
match: [/.+\@.+\..+/, 'Please fill a valid email address']
},
subject: {
type: String,
default: 'OhMyForm: Thank you for filling out this OhMyForm'
},
htmlTemplate: {
type: String,
default: 'Hello, <br><br> Weve received your submission. <br><br> Thank you & have a nice day!',
},
enabled: {
type: Boolean,
default: false
}
},
showFooter: {
type: Boolean,
default: true
},
isLive: {
type: Boolean,
default: true
},
design: {
colors: {
backgroundColor: {
type: String,
match: [/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/],
default: '#fff'
},
questionColor: {
type: String,
match: [/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/],
default: '#333'
},
answerColor: {
type: String,
match: [/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/],
default: '#333'
},
buttonColor: {
type: String,
match: [/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/],
default: '#fff'
},
buttonTextColor: {
type: String,
match: [/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/],
default: '#333'
}
},
font: String
}
}, formSchemaOptions);
FormSchema.plugin(timeStampPlugin, {
createdPath: 'created',
modifiedPath: 'lastModified',
useVirtual: false
});
FormSchema.pre('save', function (next) {
if(this.form_fields && this.form_fields.length){
this.form_fields = this.form_fields.filter(function(field){
return !field.deletePreserved;
});
}
next();
});
FormSchema.index({created: 1});
mongoose.model('Form', FormSchema);
module.exports = mongoose.model('Form');

View File

@ -1,167 +0,0 @@
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
util = require('util'),
timeStampPlugin = require('../libs/timestamp.server.plugin'),
_ = require('lodash'),
Schema = mongoose.Schema,
LogicJumpSchema = require('./logic_jump.server.model'),
tokgen = require('../libs/tokenGenerator'),
constants = require('../libs/constants');
var FieldOptionSchema = new Schema({
option_id: {
type: Number
},
option_title: {
type: String
},
option_value: {
type: String,
trim: true
}
});
var RatingFieldSchema = new Schema({
steps: {
type: Number,
min: 1,
max: 10
},
shape: {
type: String,
enum: constants.ratingShapeTypes
},
validShapes: {
type: [String]
}
});
/**
* FormField Schema
*/
function BaseFieldSchema(){
Schema.apply(this, arguments);
this.add({
isSubmission: {
type: Boolean,
default: false
},
submissionId: {
type: Schema.Types.ObjectId
},
title: {
type: String,
trim: true
},
description: {
type: String,
default: ''
},
logicJump: LogicJumpSchema,
ratingOptions: RatingFieldSchema,
fieldOptions: [FieldOptionSchema],
required: {
type: Boolean,
default: true
},
disabled: {
type: Boolean,
default: false
},
deletePreserved: {
type: Boolean,
default: false
},
validFieldTypes: {
type: [String]
},
fieldType: {
type: String,
enum: constants.fieldTypes
},
fieldValue: {
type: Schema.Types.Mixed,
default: ''
}
});
this.plugin(timeStampPlugin, {
createdPath: 'created',
modifiedPath: 'lastModified',
useVirtual: false
});
this.pre('save', function (next) {
this.validFieldTypes = mongoose.model('Field').schema.path('fieldType').enumValues;
if(this.fieldType === 'rating' && this.ratingOptions.validShapes.length === 0){
this.ratingOptions.validShapes = constants.ratingShapeTypes;
}
next();
});
}
util.inherits(BaseFieldSchema, Schema);
var FormFieldSchema = new BaseFieldSchema();
FormFieldSchema.pre('validate', function(next) {
var error = new mongoose.Error.ValidationError(this);
//If field is rating check that it has ratingOptions
if(this.fieldType !== 'rating'){
if(this.ratingOptions && this.ratingOptions.steps && this.ratingOptions.shape){
error.errors.ratingOptions = new mongoose.Error.ValidatorError({path: 'ratingOptions', message: 'ratingOptions is only allowed for type \'rating\' fields.', type: 'notvalid', value: this.ratingOptions});
console.error(error);
return(next(error));
}
} else {
//Setting default values for ratingOptions
if(!this.ratingOptions.steps) {
this.ratingOptions.steps = 10;
}
if(!this.ratingOptions.shape){
this.ratingOptions.shape = 'Star';
}
}
//If field is multiple choice check that it has field
if(this.fieldType !== 'dropdown' && this.fieldType !== 'radio' && this.fieldType !== 'checkbox'){
if(this.fieldOptions && this.fieldOptions.length > 0){
error.errors.ratingOptions = new mongoose.Error.ValidatorError({path:'fieldOptions', message: 'fieldOptions are only allowed for type dropdown, checkbox or radio fields.', type: 'notvalid', value: this.ratingOptions});
console.error(error);
return next(error);
}
}
return next();
});
//Submission fieldValue correction
FormFieldSchema.pre('save', function(next) {
if(this.fieldType === 'dropdown' && this.isSubmission){
this.fieldValue = this.fieldValue.option_value;
}
return next();
});
var Field = mongoose.model('Field', FormFieldSchema);
var RatingOptions = mongoose.model('RatingOptions', RatingFieldSchema);
module.exports = FormFieldSchema;

View File

@ -1,85 +0,0 @@
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
timeStampPlugin = require('../libs/timestamp.server.plugin'),
FieldSchema = require('./form_field.server.model'),
helpers = require('../controllers/helpers.server.controller'),
constants = require('../libs/constants');
/**
* Form Submission Schema
*/
var FormSubmissionSchema = new Schema({
form_fields: [FieldSchema],
form: {
type: Schema.Types.ObjectId,
ref: 'Form',
required: true
},
ipAddr: {
type: String
},
geoLocation: {
Country: {
type: String
},
City: {
type: String
}
},
device: {
type: {
type: String
},
name: {
type: String
}
},
timeElapsed: {
type: Number
},
percentageComplete: {
type: Number
}
});
FormSubmissionSchema.pre('save', function (next) {
//Iterate through form fields and format data
for(var i = 0; i < this.form_fields.length; i++){
if(this.form_fields[i].fieldType === 'dropdown'){
this.form_fields[i].fieldValue = this.form_fields[i].fieldValue.option_value;
}
helpers.removeKeysFromDict(this.form_fields[i], constants.extraneousFormFieldProps);
}
next();
});
FormSubmissionSchema.path('form_fields', {
set: function(form_fields){
for (var i = 0; i < form_fields.length; i++) {
form_fields[i].isSubmission = true;
form_fields[i]._id = new mongoose.mongo.ObjectID();
helpers.removeKeysFromDict(form_fields[i], constants.extraneousFormFieldProps);
}
return form_fields;
}
});
FormSubmissionSchema.plugin(timeStampPlugin, {
createdPath: 'created',
modifiedPath: 'lastModified',
useVirtual: false
});
mongoose.model('FormSubmission', FormSubmissionSchema);
module.exports = mongoose.model('FormSubmission');

Some files were not shown because too many files have changed in this diff Show More