Compare commits

..

2 commits

Author SHA1 Message Date
David Baldwynn 69de0eaa40 removed presave logic 2017-12-10 03:57:38 -05:00
David Baldwynn 17edc21dea fixed create new form 2017-11-23 20:22:22 -05:00
88 changed files with 43473 additions and 15876 deletions

View file

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

View file

@ -1,124 +0,0 @@
# TellForm Configuration File
###################################
# 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/tellform_data
# Set to what environment you will be running TellForm in (production or development)
NODE_ENV=development
# Set to a randomly generated 16 bytes string
SECRET_KEY=ChangeMeChangeMe
# URI of Mongo database that TellForm will connect to
#DO NOT CHANGE
MONGODB_URI=mongodb://mongo/tellform
# URL Redis server that TellForm will connect to
#DO NOT CHANGE
REDIS_URL=redis://redis:6379
# Port that the TellForm Node app will listen on
PORT=5000
# Domain that TellForm's admin panel will be hosted at
BASE_URL=tellform.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 TellForm 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=*.tellform.dev
# Enable running TellForm 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 TellForm 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=

6
.gitignore vendored
View file

@ -1,11 +1,14 @@
data/
dist dist
.vagrant .vagrant
npm-debug.* npm-debug.*
docs/Oscar_Credentials.md
scripts/test_oscarhost.js scripts/test_oscarhost.js
scripts/oscarhost/private/
coverage/ coverage/
e2e_coverage/ e2e_coverage/
uploads/
app/e2e_tests/screeshots/* app/e2e_tests/screeshots/*
tmp
# iOS / Apple # iOS / Apple
# =========== # ===========
@ -22,7 +25,6 @@ Oscar_Credentials.*
npm-debug.log npm-debug.log
node_modules/ node_modules/
public/lib/ public/lib/
public/dist
app/tests/coverage/ app/tests/coverage/
.bower-*/ .bower-*/
.idea/ .idea/

View file

@ -4,16 +4,33 @@
# Run: # Run:
# docker run -it tellform-prod # docker run -it tellform-prod
FROM node:10-alpine FROM phusion/baseimage:0.9.19
MAINTAINER Arielle Baldwynn <team@tellform.com> MAINTAINER David Baldwynn <team@tellform.com>
# Install some needed packages # Install Utilities
RUN apk add --no-cache \ RUN apt-get update -q \
git \ && apt-get install -yqq \
&& rm -rf /tmp/* curl \
ant \
git \
gcc \
make \
build-essential \
libkrb5-dev \
python \
sudo \
apt-utils \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# Install nodejs
RUN curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
RUN sudo apt-get install -yq nodejs \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# Install NPM Global Libraries # Install NPM Global Libraries
RUN npm install --quiet -g grunt bower pm2 && npm cache clean --force RUN npm install --quiet -g grunt bower pm2 && npm cache clean
WORKDIR /opt/tellform WORKDIR /opt/tellform
RUN mkdir -p /opt/tellform/public/lib RUN mkdir -p /opt/tellform/public/lib
@ -30,39 +47,6 @@ COPY ./gruntfile.js /opt/tellform/gruntfile.js
COPY ./server.js /opt/tellform/server.js COPY ./server.js /opt/tellform/server.js
COPY ./scripts/create_admin.js /opt/tellform/scripts/create_admin.js COPY ./scripts/create_admin.js /opt/tellform/scripts/create_admin.js
# Set default ENV
ENV NODE_ENV=development
ENV SECRET_KEY=ChangeMeChangeMe
#ENV MONGODB_URI=mongodb://mongo/tellform
#ENV REDIS_URL=redis://redis:6379
ENV PORT=5000
ENV BASE_URL=localhost
ENV SOCKET_PORT=20523
ENV SIGNUP_DISABLED=FALSE
ENV SUBDOMAINS_DISABLED=FALSE
ENV ENABLE_CLUSTER_MODE=FALSE
ENV MAILER_EMAIL_ID=tellform@localhost
ENV MAILER_PASSWORD=
ENV MAILER_FROM=tellform@localhost
ENV MAILER_SERVICE_PROVIDER=
ENV MAILER_SMTP_HOST=
ENV MAILER_SMTP_PORT=
ENV MAILER_SMTP_SECURE=
ENV CREATE_ADMIN=FALSE
ENV ADMIN_EMAIL=admin@tellform.com
ENV ADMIN_USERNAME=root
ENV ADMIN_PASSWORD=root
ENV APP_NAME=Tellform
ENV APP_KEYWORDS=
ENV APP_DESC=
# optional ENV settings
ENV COVERALLS_REPO_TOKEN=
ENV GOOGLE_ANALYTICS_ID=
ENV RAVEN_DSN=
# Copies the local package.json file to the container # Copies the local package.json file to the container
# and utilities docker container cache to not needing to rebuild # and utilities docker container cache to not needing to rebuild
# and install node_modules/ everytime we build the docker, but only # and install node_modules/ everytime we build the docker, but only
@ -70,8 +54,6 @@ ENV RAVEN_DSN=
# Add npm package.json # Add npm package.json
COPY ./package.json /opt/tellform/package.json COPY ./package.json /opt/tellform/package.json
RUN npm install --only=production --quiet RUN npm install --only=production --quiet
RUN bower install --allow-root
RUN grunt build
# Run TellForm server # Run TellForm server
CMD ["node", "server.js"] CMD ["node", "server.js"]

View file

@ -10,7 +10,56 @@ TellForm Installation Instructions
## Local deployment with Docker ## Local deployment with Docker
Refer to [docker_files](https://github.com/tellform/docker_files). ### Prerequisites
Make you sure have the following packages and versions on your machine:
```
"node": ">=6.11.2"
"npm": ">=3.3.6"
"bower": ">=1.8.0"
"grunt-cli": ">=1.2.0"
"grunt": ">=0.4.5"
"docker": ">=17.06.0-ce"
"docker-compose": ">=1.14.0"
```
### Install dependencies
```
$ npm install
```
### Prepare .env file:
Create `.env` file at project root folder. Fill in `MAILER_SERVICE_PROVIDER`, `MAILER_EMAIL_ID`, `MAILER_PASSWORD` and `MAILER_FROM`.
```
APP_NAME=TellForm
BASE_URL=localhost:3000
PORT=3000
DB_PORT_27017_TCP_ADDR=tellform-mongo
REDIS_DB_PORT_6379_TCP_ADDR=tellform-redis
MAILER_SERVICE_PROVIDER=<TO-FILL-IN>
MAILER_EMAIL_ID=<TO-FILL-IN>
MAILER_PASSWORD=<TO-FILL-IN>
MAILER_FROM=<TO-FILL-IN>
SIGNUP_DISABLED=false
SUBDOMAINS_DISABLED=true
DISABLE_CLUSTER_MODE=true
```
### Build docker image
```
$ docker-compose build
```
### Run docker containers with docker-compose
Create and start mongo & redis docker container:
```
$ docker-compose up
```
Your application should run on port 3000 or the port you specified in your .env file, so in your browser just go to [http://localhost:3000](http://localhost:3000)
## AWS AMI Deployment ## AWS AMI Deployment

122
README.md
View file

@ -1,34 +1,17 @@
TellForm 2.1.0 TellForm 2.1.0
======== ========
DEPRECATION WARNING UNTIL FURTHER NOTICE.
There are many oudated and vulnerable dependencies within this project and I recommend that you use this code repository for internal testing and development only.
There were too many impassable hurdles to really continue forward at the pace that I was hoping with TellForm @leopere~ If you want to follow my progress on an alternative in the mean time check out https://OhMyForm.com or our Discord server. We managed to get the base Docker image fixed before forking the code so you can give this a try however not much has changed at the moment.
<!--
[![Code Shelter](https://www.codeshelter.co/static/badges/badge-flat.svg)](https://www.codeshelter.co/)
[![Build Status](https://travis-ci.org/tellform/tellform.svg?branch=master)](https://travis-ci.org/tellform/tellform) [![Build Status](https://travis-ci.org/tellform/tellform.svg?branch=master)](https://travis-ci.org/tellform/tellform)
![Project Status](https://img.shields.io/badge/status-2.1.0-green.svg) ![Project Status](https://img.shields.io/badge/status-2.1.0-green.svg)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/3491e86eb7194308b8fc80711d736ede)](https://www.codacy.com/app/david-baldwin/tellform?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=tellform/tellform&amp;utm_campaign=Badge_Grade) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/3491e86eb7194308b8fc80711d736ede)](https://www.codacy.com/app/david-baldwin/tellform?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=tellform/tellform&amp;utm_campaign=Badge_Grade)
--> [![Gitter](https://badges.gitter.im/tellform/tellform.svg)](https://gitter.im/tellform/tellform?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
To Join the fork's community please follow this Discord button here. > An *opensource alternative to TypeForm* that can create [stunning mobile-ready forms](https://tellform.com/examples) , surveys and questionnaires.
![Discord](https://img.shields.io/discord/595773457862492190.svg?label=Discord%20Chat)
## Readme and Issues
The README.md is still effectively in tact however it's all been commented out so that it's no longer visible on the main github repository page. You may visit it by navigating through the repositories files themselves.
No new or old issues will be tended to so the Issues Board has been closed. We don't recommend using this repositories codebase as its no longer maintained and is only intended for reference code. If you wish to use the fork which should remain backwards compatible feel free to explore [https://ohmyform.com](https://ohmyform.com/) or its GitHub repository at [https://github.com/ohmyform/ohmyform/](https://github.com/ohmyform/ohmyform/) where the code base is started from TellForm we are planning on keeping it reverse compatible however the code is Sublicensed AGPL and is going to have a stable release prepared for the public hopefully but September 12th 2019. It should be a drop in replacement for TellForm which should expand on the vision of TellForm but hopefully bring it all up to date.
<!--
> An *opensource alternative to TypeForm* that can create [stunning mobile-ready forms](https://tellform.com/examples) , surveys and questionnaires.-->
<!--
[![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/tellform/tellform/tree/master) [![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/tellform/tellform/tree/master)
-->
<!--
## Table of Contents ## Table of Contents
- [Features](#features) - [Features](#features)
- [How to Contribute](#how-to-contribute) - [How to Contribute](#how-to-contribute)
- [Quickstart](#quickstart) - [Quickstart](#quickstart)
@ -40,8 +23,11 @@ No new or old issues will be tended to so the Issues Board has been closed. We
- [Backers](#backers) - [Backers](#backers)
- [Contributors](#contributors) - [Contributors](#contributors)
- [Mentions on the Web](#mentions-on-the-web) - [Mentions on the Web](#mentions-on-the-web)
## Features ## Features
### Currently following features are implemented: ### Currently following features are implemented:
- Multi-Language Support - Multi-Language Support
- 11 possible question types - 11 possible question types
- Editable start and end pages - Editable start and end pages
@ -51,6 +37,7 @@ No new or old issues will be tended to so the Issues Board has been closed. We
- Embeddable Forms - Embeddable Forms
- Forms as a Service API - Forms as a Service API
- Deployable with Heroku and DockerHub - Deployable with Heroku and DockerHub
### On the Roadmap for v3.0.0 ### On the Roadmap for v3.0.0
- Implement encryption for all form data - Implement encryption for all form data
- Add Typeform API integration - Add Typeform API integration
@ -59,27 +46,37 @@ No new or old issues will be tended to so the Issues Board has been closed. We
- Add Stripe/Payment Form field - Add Stripe/Payment Form field
- Add Custom Background and Dropdown Field Images - Add Custom Background and Dropdown Field Images
- Add File Upload Form Field - Add File Upload Form Field
## How to Contribute ## How to Contribute
Please checkout our CONTRIBUTING.md on ways to contribute to TellForm. Please checkout our CONTRIBUTING.md on ways to contribute to TellForm.
All contributors are eligible to get a free [TellForm Sticker](https://www.stickermule.com/marketplace/15987-tellform-round-sticker). All you have to do is submit a PR, get it accepted, email your address to team [at] tellform.com and we'll send you a sticker that you can proudly put on your laptop. All contributors are eligible to get a free [TellForm Sticker](https://www.stickermule.com/marketplace/15987-tellform-round-sticker). All you have to do is submit a PR, get it accepted, email your address to team [at] tellform.com and we'll send you a sticker that you can proudly put on your laptop.
## Quickstart ## Quickstart
Before you start, make sure you have Before you start, make sure you have
1. [Redis](https://redis.io/) installed and running at 127.0.0.1:6379 1. [Redis](https://redis.io/) installed and running at 127.0.0.1:6379
2. [MongoDB](https://www.mongodb.com/) installed and running at 127.0.0.1:27017 (OR specify the host and port in config/env/all) 2. [MongoDB](https://www.mongodb.com/) installed and running at 127.0.0.1:27017 (OR specify the host and port in config/env/all)
Also make sure to install [DNS Masq](http://www.thekelleys.org.uk/dnsmasq/doc.html) or equivalent if running it locally on your computer (look at dns_masq_setup_osx for instructions on OSX) Also make sure to install [DNS Masq](http://www.thekelleys.org.uk/dnsmasq/doc.html) or equivalent if running it locally on your computer (look at dns_masq_setup_osx for instructions on OSX)
Install dependencies first. Install dependencies first.
```bash ```bash
$ npm install $ npm install
$ bower install $ bower install
``` ```
Setup environment. Setup environment.
```bash ```bash
$ grunt build $ grunt build
``` ```
Create your user account Create your user account
```bash ```bash
$ node ./scripts/setup.js $ node ./scripts/setup.js
``` ```
OR create your .env file OR create your .env file
``` ```
GOOGLE_ANALYTICS_ID=yourGAID GOOGLE_ANALYTICS_ID=yourGAID
@ -87,67 +84,92 @@ PRERENDER_TOKEN=yourPrerender.ioToken
COVERALLS_REPO_TOKEN=yourCoveralls.ioToken COVERALLS_REPO_TOKEN=yourCoveralls.ioToken
BASE_URL=localhost BASE_URL=localhost
DSN_KEY=yourPrivateRavenKey DSN_KEY=yourPrivateRavenKey
# Mail config # Mail config
MAILER_EMAIL_ID=user@domain.com MAILER_EMAIL_ID=user@domain.com
MAILER_PASSWORD=some-pass MAILER_PASSWORD=some-pass
MAILER_FROM=user@domain.com MAILER_FROM=user@domain.com
# Use this for one of Nodemailer's pre-configured service providers # Use this for one of Nodemailer's pre-configured service providers
MAILER_SERVICE_PROVIDER=SendGrid MAILER_SERVICE_PROVIDER=SendGrid
# Use these for a custom service provider # Use these for a custom service provider
# Note: MAILER_SMTP_HOST will override MAILER_SERVICE_PROVIDER # Note: MAILER_SMTP_HOST will override MAILER_SERVICE_PROVIDER
MAILER_SMTP_HOST=smtp.domain.com MAILER_SMTP_HOST=smtp.domain.com
MAILER_SMTP_PORT=465 MAILER_SMTP_PORT=465
MAILER_SMTP_SECURE=TRUE MAILER_SMTP_SECURE=true
``` ```
Side note: ___Currently we are using Raven and Sentry [https://www.getsentry.com](https://www.getsentry.com) for error logging. To use it you must provide a valid private DSN key in your .env file and a public DSN key in app/views/layout.index.html___ Side note: ___Currently we are using Raven and Sentry [https://www.getsentry.com](https://www.getsentry.com) for error logging. To use it you must provide a valid private DSN key in your .env file and a public DSN key in app/views/layout.index.html___
#### To run the development version: #### To run the development version:
Set ```NODE_ENV=development``` in .env file Set ```NODE_ENV=development``` in .env file
```$ grunt``` ```$ grunt```
#### To run the production version: #### To run the production version:
Set ```NODE_ENV=production``` in .env file Set ```NODE_ENV=production``` in .env file
```$ grunt``` ```$ grunt```
Your application should run on port 3000 or the port you specified in your .env file, so in your browser just go to [http://localhost:3000](http://localhost:3000) Your application should run on port 3000 or the port you specified in your .env file, so in your browser just go to [http://localhost:3000](http://localhost:3000)
## Deploying with Docker ## Deploying with Docker
To deploy with docker, first install docker [here](https://docs.docker.com/engine/installation/). To deploy with docker, first install docker [here](https://docs.docker.com/engine/installation/).
Then run follow these steps:
### Step 1: Clone the repo Then run these commands
`$ git clone https://github.com/tellform/docker_files.git`
### Step 2: Setup TellForm Configuration ```
Create your .env file by copying the .env.dist file included in the repo and changing it to suit your deployment. $ docker run -p 27017:27017 -d --name some-mongo mongo
Important: You need to fill out all of the ENV variables in the "Mail Settings" section or your TellForm instance won't work. $ docker run -p 127.0.0.1:6379:6379 -d --name some-redis redis
If you want to have https, make sure to change 'TLS_FLAVOR' $ docker run --rm -p 3000:3000 --link some-redis:redis-db --link some-mongo:db -e "SUBDOMAINS_DISABLED=TRUE" -e "DISABLE_CLUSTER_MODE=TRUE" -e "MAILER_EMAIL_ID=<YourEmailAPI_ID>" -e "MAILER_FROM=<noreply@yourdomain.com>" -e "MAILER_SERVICE_PROVIDER=<YourEmailAPIProvider>" -e "MAILER_PASSWORD=<YourAPIKey>" -e "BASE_URL=localhost" -p 80:80 tellform/development
### Step 3: Start your TellForm instance ```
`docker-compose up -d`
TellForm should now be accessible on http://localhost
## Testing Your Application ## Testing Your Application
You can run the full test suite included with TellForm with the test task: You can run the full test suite included with TellForm with the test task:
``` ```
$ grunt test $ grunt test
``` ```
This will run both the server-side tests (located in the app/tests/ directory) and the client-side tests (located in the public/modules/*/tests/). This will run both the server-side tests (located in the app/tests/ directory) and the client-side tests (located in the public/modules/*/tests/).
To execute only the server tests, run the test:server task: To execute only the server tests, run the test:server task:
``` ```
$ grunt test:server $ grunt test:server
``` ```
And to run only the client tests, run the test:client task: And to run only the client tests, run the test:client task:
``` ```
$ grunt test:client $ grunt test:client
``` ```
Currently the live example uses heroku github deployments. The Docker file is out of date and does not work. If someone wishes to get it working feel free to submit a pull request. Currently the live example uses heroku github deployments. The Docker file is out of date and does not work. If someone wishes to get it working feel free to submit a pull request.
To calculate your total test coverage with Istanbul, run the coverage task To calculate your total test coverage with Istanbul, run the coverage task
```bash ```bash
$ grunt coverage $ grunt coverage
``` ```
To calculate your server-side test coverage with Istanbul, run the coverage task To calculate your server-side test coverage with Istanbul, run the coverage task
```bash ```bash
$ grunt coverage:server $ grunt coverage:server
``` ```
To calculate your client-side test coverage with Istanbul, run the coverage task To calculate your client-side test coverage with Istanbul, run the coverage task
```bash ```bash
$ grunt coverage:client $ grunt coverage:client
``` ```
## Configuration ## Configuration
TellForm's configuration is done with environment variables. To set an option for TellForm, open/create your .env file and set add `ENV_VAR=somevalue` to set the ENV_VAR variable to the value `somevalue`. TellForm's configuration is done with environment variables. To set an option for TellForm, open/create your .env file and set add `ENV_VAR=somevalue` to set the ENV_VAR variable to the value `somevalue`.
| Property | Valid Values | Default Value | Description | Required? | | Property | Valid Values | Default Value | Description | Required? |
|-------------------------|--------------------------------------------------------|----------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------|--------------------------------------------| |-------------------------|--------------------------------------------------------|----------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------|--------------------------------------------|
| NODE_ENV | "development", "production", "test" or "secure" | development | Set which version of the app you want to run (either secure/SSL, dev, prod or test) | No | | NODE_ENV | "development", "production", "test" or "secure" | development | Set which version of the app you want to run (either secure/SSL, dev, prod or test) | No |
@ -176,24 +198,42 @@ TellForm's configuration is done with environment variables. To set an option fo
| APP_KEYWORDS | A comma-seperated list of phrases/words | typeform, pdfs, forms, opensource, formbuilder, google forms, nodejs | Sets the value of the <meta> description attribute. | No | | APP_KEYWORDS | A comma-seperated list of phrases/words | typeform, pdfs, forms, opensource, formbuilder, google forms, nodejs | Sets the value of the <meta> description attribute. | No |
| RAVEN_DSN | A valid Sentry.io DSN | N/A | Set this to your Sentry.io Public DSN to enable remote logging | No | | RAVEN_DSN | A valid Sentry.io DSN | N/A | Set this to your Sentry.io Public DSN to enable remote logging | No |
| GOOGLE_ANALYTICS_ID | A valid Google Analytics ID | N/A | Set this to your GA id to enable GA tracking on your TellForm instance | No | | GOOGLE_ANALYTICS_ID | A valid Google Analytics ID | N/A | Set this to your GA id to enable GA tracking on your TellForm instance | No |
## Where to get help ## Where to get help
[Gitter Chat](https://gitter.im/tellform/Lobby)
[Gitter Chat](https://gitter.im/tellform/tellform)
[Official Twitter](https://twitter.com/tellform_real) [Official Twitter](https://twitter.com/tellform_real)
-->
## Sponsors ## Sponsors
Further Sponsorships are no longer accepted.
<!--
Does your company use TellForm? Help keep the project bug-free and feature rich by [sponsoring the project](https://opencollective.com/tellform#sponsor). Does your company use TellForm? Help keep the project bug-free and feature rich by [sponsoring the project](https://opencollective.com/tellform#sponsor).
<a href="https://countable.ca" style="padding: 30px 0">
<img src="https://countable.ca/logo.cb446ab0.svg" height="30px"> <a href="https://m.do.co/c/a86fd8843e09" style="padding: 30px 0">
</a> --> <img src="/docs/readme_logos/do_logo.png" height="30px">
</a>
<a href="https://getsentry.com/" style="padding: 30px 0">
<img src="/docs/readme_logos/sentry_logo.png" height="30px">
</a>
<a href="https://statuspage.io/" style="padding: 30px 0">
<img src="/docs/readme_logos/statuspage_logo.png" height="30px">
</a>
<br><br>
<a href="https://www.stickermule.com/unlock?ref_id=0939360701" style="padding: 30px 0">
<img src="/docs/readme_logos/stickermule_logo.png" height="30px">
</a>
<a href="https://sparkpost.com/" style="padding: 30px 0">
<img src="/docs/readme_logos/sparkpost_logo.png" height="30px">
</a>
<a href="https://therooststand.com/" style="padding: 30px 0">
<img src="/docs/readme_logos/roost_logo.png" height="30px">
</a>
## Backers ## Backers
Love our work and community? <!--[Become a backer](https://opencollective.com/tellform).--> Love our work and community? [Become a backer](https://opencollective.com/tellform).
<a href="https://opencollective.com/elliot" target="_blank"> <a href="https://opencollective.com/elliot" target="_blank">
<img src="https://opencollective.com/proxy/images/?src=https%3A%2F%2Fd1ts43dypk8bqh.cloudfront.net%2Fv1%2Favatars%2F6fd61b2c-62b6-438a-9168-bab7ef1489b8" height= "64"> <img src="https://opencollective.com/proxy/images/?src=https%3A%2F%2Fd1ts43dypk8bqh.cloudfront.net%2Fv1%2Favatars%2F6fd61b2c-62b6-438a-9168-bab7ef1489b8" height= "64">
@ -212,6 +252,8 @@ Love our work and community? <!--[Become a backer](https://opencollective.com/te
<!-- ALL-CONTRIBUTORS-LIST:END --> <!-- ALL-CONTRIBUTORS-LIST:END -->
## Mentions on the Web ## Mentions on the Web
[Mister Ad](http://start.mister-ad.biz/newsticker/open-source-alternative-zu-typeform-tellform-in-der-kurzvorstellung/)
[t3n.de](http://t3n.de/news/open-source-alternative-typeform-tellform-707295/) [t3n.de](http://t3n.de/news/open-source-alternative-typeform-tellform-707295/)
[BootCSS Expo](http://expo.bootcss.com/) [BootCSS Expo](http://expo.bootcss.com/)

View file

@ -28,10 +28,5 @@
"description": "Which mail service/API you will be using (i.e. SparkPost, Mandrill, etc)", "description": "Which mail service/API you will be using (i.e. SparkPost, Mandrill, etc)",
"value": "SendGrid" "value": "SendGrid"
} }
}, }
"buildpacks": [
{
"url": "https://github.com/heroku/heroku-buildpack-nodejs#v111"
}
]
} }

View file

@ -19,7 +19,7 @@ exports.deleteSubmissions = function(req, res) {
var submission_id_list = req.body.deleted_submissions, var submission_id_list = req.body.deleted_submissions,
form = req.form; form = req.form;
FormSubmission.remove({ form: req.form, _id: {$in: submission_id_list} }, function(err){ FormSubmission.remove({ form: req.form, admin: req.user, _id: {$in: submission_id_list} }, function(err){
if(err){ if(err){
res.status(400).send({ res.status(400).send({
@ -48,7 +48,7 @@ exports.deleteSubmissions = function(req, res) {
exports.createSubmission = function(req, res) { exports.createSubmission = function(req, res) {
var timeElapsed = 0; var timeElapsed = 0;
if(typeof req.body.timeElapsed === 'number'){ if(typeof req.body.timeElapsed === 'number'){
timeElapsed = req.body.timeElapsed; timeElapsed = req.body.timeElapsed;
} }
@ -88,15 +88,17 @@ exports.listSubmissions = function(req, res) {
} }
res.json(_submissions); res.json(_submissions);
}); });
}; };
/** /**
* Create a new form * Create a new form
*/ */
exports.create = function(req, res) { exports.create = function(req, res) {
debugger;
if(!req.body.form){ if(!req.body.form){
return res.status(400).send({ return res.status(401).send({
message: 'Invalid Input' message: 'Invalid Input'
}); });
} }

View file

@ -190,7 +190,7 @@ exports.signin = function(req, res, next) {
*/ */
exports.signout = function(req, res) { exports.signout = function(req, res) {
if(req.cookies.hasOwnProperty('userLang')){ if(req.cookies.hasOwnProperty('userLang')){
res.clearCookie('userLang'); res.destroyCookie('userLang');
} }
req.logout(); req.logout();
return res.status(200).send('You have successfully logged out.'); return res.status(200).send('You have successfully logged out.');

View file

@ -71,6 +71,7 @@ var VisitorDataSchema = new Schema({
userAgent: { userAgent: {
type: String type: String
} }
}); });
var formSchemaOptions = { var formSchemaOptions = {
@ -218,7 +219,7 @@ FormSchema.virtual('analytics.fields').get(function () {
var visitors = this.analytics.visitors; var visitors = this.analytics.visitors;
var that = this; var that = this;
if(!this.form_fields || this.form_fields.length === 0) { if(this.form_fields.length === 0) {
return null; return null;
} }
@ -330,117 +331,6 @@ function formFieldsAllHaveIds(form_fields){
return true; return true;
} }
FormSchema.pre('save', function (next) {
var that = this;
var _original;
async.series([
function(cb) {
that.constructor
.findOne({_id: that._id}).exec(function (err, original) {
if (err) {
return cb(err);
} else if (!original){
return next();
} else {
_original = original;
return cb(null);
}
});
},
function(cb) {
if(that.form_fields && that.isModified('form_fields') && formFieldsAllHaveIds(that.toObject().form_fields)){
var current_form = that.toObject(),
old_form_fields = _original.toObject().form_fields,
new_ids = _.map(_.map(current_form.form_fields, 'globalId'), function(id){ return ''+id;}),
old_ids = _.map(_.map(old_form_fields, 'globalId'), function(id){ return ''+id;}),
deletedIds = getDeletedIndexes(old_ids, new_ids);
//Check if any form_fileds were deleted
if( deletedIds.length > 0 ){
var modifiedSubmissions = [];
async.forEachOfSeries(deletedIds,
function (deletedIdIndex, key, cb_id) {
var deleted_id = old_ids[deletedIdIndex];
//Find FormSubmissions that contain field with _id equal to 'deleted_id'
FormSubmission.
find({ form: that, form_fields: {$elemMatch: {globalId: deleted_id} } }).
exec(function(err, submissions){
if(err) {
return cb_id(err);
}
//Preserve fields that have at least one submission
if (submissions.length) {
//Add submissions
modifiedSubmissions.push.apply(modifiedSubmissions, submissions);
}
return cb_id(null);
});
},
function (err) {
if(err){
console.error(err.message);
return cb(err);
}
//Iterate through all submissions with modified form_fields
async.forEachOfSeries(modifiedSubmissions, function (submission, key, callback) {
var submission_form_fields = submission.toObject().form_fields;
var currentform_form_fields = that.toObject().form_fields;
//Iterate through ids of deleted fields
for (var i = 0; i < deletedIds.length; i++) {
var index = _.findIndex(submission_form_fields, function (field) {
var tmp_id = field.globalId + '';
return tmp_id === old_ids[deletedIds[i]];
});
var deletedField = submission_form_fields[index];
//Hide field if it exists
if (deletedField) {
//Delete old form_field
submission_form_fields.splice(index, 1);
deletedField.deletePreserved = true;
//Move deleted form_field to start
submission_form_fields.unshift(deletedField);
currentform_form_fields.unshift(deletedField);
}
}
submission.form_fields = submission_form_fields;
that.form_fields = currentform_form_fields;
return callback(null);
}, function (err) {
return cb(err);
});
});
} else {
return cb(null);
}
} else {
return cb(null);
}
}
],
function(err){
if(err){
return next(err);
}
next();
});
});
FormSchema.index({created: 1}); FormSchema.index({created: 1});
mongoose.model('Form', FormSchema); mongoose.model('Form', FormSchema);

View file

@ -9,7 +9,19 @@ var mongoose = require('mongoose'),
config = require('../../config/config'), config = require('../../config/config'),
timeStampPlugin = require('../libs/timestamp.server.plugin'), timeStampPlugin = require('../libs/timestamp.server.plugin'),
path = require('path'), path = require('path'),
querystring = require('querystring'); querystring = require('querystring'),
nodemailer = require('nodemailer');
var smtpTransport = nodemailer.createTransport(config.mailer.options);
// verify connection configuration on startup
smtpTransport.verify(function(error, success) {
if (error) {
console.log('Your mail configuration is incorrect', error);
} else {
console.log('Mail server is ready to take our messages');
}
});
/** /**
* A Validation function for local strategy properties * A Validation function for local strategy properties

View file

@ -9,8 +9,7 @@ var should = require('should'),
User = mongoose.model('User'), User = mongoose.model('User'),
Form = mongoose.model('Form'), Form = mongoose.model('Form'),
Field = mongoose.model('Field'), Field = mongoose.model('Field'),
FormSubmission = mongoose.model('FormSubmission'), FormSubmission = mongoose.model('FormSubmission');
async = require('async');
/** /**
* Globals * Globals
@ -69,7 +68,7 @@ describe('Form Routes Unit tests', function() {
.send({form: myForm}) .send({form: myForm})
.expect(401) .expect(401)
.end(function(FormSaveErr, FormSaveRes) { .end(function(FormSaveErr, FormSaveRes) {
console.log(FormSaveRes.text);
// Call the assertion callback // Call the assertion callback
done(FormSaveErr); done(FormSaveErr);
}); });
@ -84,7 +83,7 @@ describe('Form Routes Unit tests', function() {
}); });
}); });
it(' > should be able to read/get a live Form if not signed in', function(done) { it(' > should be able to read/get a Form if not signed in', function(done) {
// Create new Form model instance // Create new Form model instance
var FormObj = new Form(myForm); var FormObj = new Form(myForm);
@ -106,23 +105,6 @@ describe('Form Routes Unit tests', function() {
}); });
}); });
it(' > should be able to read/get a non-live Form if not signed in', function(done) {
// Create new Form model instance
var FormObj = new Form(myForm);
FormObj.isLive = false;
// Save the Form
FormObj.save(function(err, form) {
if(err) return done(err);
userSession.get('/subdomain/' + credentials.username + '/forms/' + form._id + '/render')
.expect(401, {message: 'Form is Not Public'})
.end(function(err, res) {
done(err);
});
});
});
it(' > should not be able to delete an Form if not signed in', function(done) { it(' > should not be able to delete an Form if not signed in', function(done) {
// Set Form user // Set Form user
myForm.admin = user; myForm.admin = user;
@ -164,16 +146,6 @@ describe('Form Routes Unit tests', function() {
}); });
}); });
it(' > should not be able to create a Form if body is empty', function(done) {
loginSession.post('/forms')
.send({form: null})
.expect(400, {"message":"Invalid Input"})
.end(function(FormSaveErr, FormSaveRes) {
// Call the assertion callback
done(FormSaveErr);
});
});
it(' > should not be able to save a Form if no title is provided', function(done) { it(' > should not be able to save a Form if no title is provided', function(done) {
// Set Form with a invalid title field // Set Form with a invalid title field
myForm.title = ''; myForm.title = '';
@ -193,22 +165,10 @@ describe('Form Routes Unit tests', function() {
done(); done();
}); });
}); });
it(' > should be able to create a Form if form_fields are undefined', function(done) { it(' > should be able to update a Form if signed in', function(done) {
myForm.analytics = null;
myForm.form_fields = null;
loginSession.post('/forms')
.send({form: myForm})
.expect(200)
.end(function(FormSaveErr, FormSaveRes) {
// Call the assertion callback
done(FormSaveErr);
});
});
it(' > should be able to update a Form if signed in and Form is valid', function(done) {
// Save a new Form // Save a new Form
loginSession.post('/forms') loginSession.post('/forms')
@ -222,7 +182,7 @@ describe('Form Routes Unit tests', function() {
} }
// Update Form title // Update Form title
myForm.title = 'WHY YOU GOTTA BE SO FORMULAIC?'; myForm.title = 'WHY YOU GOTTA BE SO MEAN?';
// Update an existing Form // Update an existing Form
loginSession.put('/forms/' + FormSaveRes.body._id) loginSession.put('/forms/' + FormSaveRes.body._id)
@ -237,12 +197,13 @@ describe('Form Routes Unit tests', function() {
// Set assertions // Set assertions
(FormUpdateRes.body._id).should.equal(FormSaveRes.body._id); (FormUpdateRes.body._id).should.equal(FormSaveRes.body._id);
(FormUpdateRes.body.title).should.match(myForm.title); (FormUpdateRes.body.title).should.match('WHY YOU GOTTA BE SO MEAN?');
// Call the assertion callback // Call the assertion callback
done(); done();
}); });
}); });
}); });
it(' > should be able to delete a Form if signed in', function(done) { it(' > should be able to delete a Form if signed in', function(done) {
@ -277,9 +238,10 @@ describe('Form Routes Unit tests', function() {
done(); done();
}); });
}); });
}); });
it(' > should be able to save new form while logged in', function(done){ it('should be able to save new form while logged in', function(done){
// Save a new Form // Save a new Form
authenticatedSession.post('/forms') authenticatedSession.post('/forms')
.send({form: myForm}) .send({form: myForm})
@ -309,70 +271,12 @@ describe('Form Routes Unit tests', function() {
}); });
}); });
it(' > should be able to get list of users\' forms sorted by date created while logged in', function(done) {
var myForm1 = {
title: 'First Form',
language: 'en',
admin: user.id,
form_fields: [
new Field({'fieldType':'textfield', 'title':'First Name', 'fieldValue': ''}),
new Field({'fieldType':'checkbox', 'title':'nascar', 'fieldValue': ''}),
new Field({'fieldType':'checkbox', 'title':'hockey', 'fieldValue': ''})
],
isLive: true
};
var myForm2 = {
title: 'Second Form',
language: 'en',
admin: user.id,
form_fields: [
new Field({'fieldType':'textfield', 'title':'Last Name', 'fieldValue': ''}),
new Field({'fieldType':'checkbox', 'title':'formula one', 'fieldValue': ''}),
new Field({'fieldType':'checkbox', 'title':'football', 'fieldValue': ''})
],
isLive: true
};
var FormObj1 = new Form(myForm1);
var FormObj2 = new Form(myForm2);
async.waterfall([
function(callback) {
FormObj1.save(function(err){
callback(err);
});
},
function(callback) {
FormObj2.save(function(err){
callback(err);
});
},
function(callback) {
loginSession.get('/forms')
.expect(200)
.end(function(err, res) {
res.body.length.should.equal(2);
res.body[0].title.should.equal('Second Form');
res.body[1].title.should.equal('First Form');
// Call the assertion callback
callback(err);
});
}
], function (err) {
done(err);
});
});
afterEach('should be able to signout user', function(done){ afterEach('should be able to signout user', function(done){
authenticatedSession.get('/auth/signout') authenticatedSession.get('/auth/signout')
.expect(200) .expect(200)
.end(function(signoutErr, signoutRes) { .end(function(signoutErr, signoutRes) {
// Handle signout error // Handle signout error
if (signoutErr) { if (signoutErr) return done(signoutErr);
return done(signoutErr);
}
authenticatedSession.destroy(); authenticatedSession.destroy();
done(); done();
}); });

View file

@ -199,7 +199,6 @@ describe('FormSubmission Model Unit Tests:', function() {
it('should preserve deleted form_fields that have submissions without any problems', function(done) { it('should preserve deleted form_fields that have submissions without any problems', function(done) {
var fieldPropertiesToOmit = ['deletePreserved', 'globalId', 'lastModified', 'created', '_id', 'submissionId', 'isSubmission', 'validFieldTypes', 'title'];
var old_fields = myForm.toObject().form_fields; var old_fields = myForm.toObject().form_fields;
var new_form_fields = _.clone(myForm.toObject().form_fields); var new_form_fields = _.clone(myForm.toObject().form_fields);
new_form_fields.splice(0, 1); new_form_fields.splice(0, 1);
@ -211,8 +210,8 @@ describe('FormSubmission Model Unit Tests:', function() {
should.not.exist(err); should.not.exist(err);
should.exist(_form.form_fields); should.exist(_form.form_fields);
var actual_fields = _.deepOmit(_form.toObject().form_fields, fieldPropertiesToOmit); var actual_fields = _.deepOmit(_form.toObject().form_fields, ['deletePreserved', 'globalId', 'lastModified', 'created', '_id', 'submissionId']);
old_fields = _.deepOmit(old_fields, fieldPropertiesToOmit); old_fields = _.deepOmit(old_fields, ['deletePreserved', 'globalId', 'lastModified', 'created', '_id', 'submissionId']);
should.deepEqual(actual_fields, old_fields, 'old form_fields not equal to newly saved form_fields'); should.deepEqual(actual_fields, old_fields, 'old form_fields not equal to newly saved form_fields');
done(); done();

View file

@ -5,8 +5,8 @@ block content
div.row.valign div.row.valign
h3.col-md-12.text-center=__('500_HEADER') h3.col-md-12.text-center=__('500_HEADER')
div.col-md-4.col-md-offset-4 div.col-md-4.col-md-offset-4
if process.env.NODE_ENV == 'development' || process.env.NODE_ENV == 'test' if process.env.NODE_ENV == 'development'
div.col-md-12.text-center(style="padding-bottom: 50px;") div.col-md-12.text-center(style="padding-bottom: 50px;")
| #{error} | #{error}
else else
div.col-md-12.text-center(style="padding-bottom: 50px;")=__('500_BODY') div.col-md-12.text-center(style="padding-bottom: 50px;")=__('500_BODY')

View file

@ -57,10 +57,7 @@ html(lang='en', xmlns='http://www.w3.org/1999/xhtml')
//Embedding socketUrl //Embedding socketUrl
if socketUrl if socketUrl
script(type='text/javascript'). script(type='text/javascript').
socketUrl = "!{socketUrl}" socketUrl = !{socketUrl}
//JSEP
script(src='https://cdn.jsdelivr.net/npm/jsep@0.3.4/build/jsep.min.js', type='text/javascript')
script(src='/static/lib/jquery/dist/jquery.min.js', type='text/javascript') script(src='/static/lib/jquery/dist/jquery.min.js', type='text/javascript')
link(rel='stylesheet', href='/static/lib/font-awesome/css/font-awesome.min.css') link(rel='stylesheet', href='/static/lib/font-awesome/css/font-awesome.min.css')
@ -82,10 +79,10 @@ html(lang='en', xmlns='http://www.w3.org/1999/xhtml')
//Socket.io Client Dependency //Socket.io Client Dependency
script(src='/static/lib/socket.io-client/dist/socket.io.min.js') script(src='/static/lib/socket.io-client/dist/socket.io.min.js')
script(src='/static/lib/jquery-ui/jquery-ui.js', type='text/javascript') script(src='/static/lib/jquery-ui/jquery-ui.js', type='text/javascript')
script(src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js', integrity='sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa', crossorigin='anonymous')
//Minified Bower Dependencies //Minified Bower Dependencies
script(src='/static/lib/angular/angular.min.js') script(src='/static/dist/vendor.min.js')
script(src='/static/dist/form-vendor.min.js')
script(src='/static/lib/angular-ui-date/src/date.js', type='text/javascript') script(src='/static/lib/angular-ui-date/src/date.js', type='text/javascript')
//Application JavaScript Files //Application JavaScript Files

View file

@ -52,7 +52,7 @@ html(lang='en', xmlns='http://www.w3.org/1999/xhtml')
block content block content
script window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;ga('create','#{google_analytics_id}','auto');ga('send','pageview') script window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;ga('create','{{google_analytics_id}}','auto');ga('send','pageview')
script(src='https://www.google-analytics.com/analytics.js', async='', defer='') script(src='https://www.google-analytics.com/analytics.js', async='', defer='')

View file

@ -37,7 +37,7 @@
"angular-translate": "~2.11.0", "angular-translate": "~2.11.0",
"ng-translate": "*", "ng-translate": "*",
"deep-diff": "^0.3.4", "deep-diff": "^0.3.4",
"jsep": "0.3.1", "jsep": "^0.3.1",
"ngclipboard": "^1.1.1", "ngclipboard": "^1.1.1",
"mobile-detect": "^1.3.3", "mobile-detect": "^1.3.3",
"socket.io-client": "^1.7.2", "socket.io-client": "^1.7.2",

2
config/env/all.js vendored
View file

@ -40,7 +40,7 @@ module.exports = {
options: process.env.MAILER_SMTP_HOST ? { //Uses custom SMTP if MAILER_SMTP_HOST is set options: process.env.MAILER_SMTP_HOST ? { //Uses custom SMTP if MAILER_SMTP_HOST is set
host: process.env.MAILER_SMTP_HOST || '', host: process.env.MAILER_SMTP_HOST || '',
port: process.env.MAILER_SMTP_PORT || 465, port: process.env.MAILER_SMTP_PORT || 465,
secure: (process.env.MAILER_SMTP_SECURE === 'TRUE'), secure: process.env.MAILER_SMTP_SECURE || true,
auth: { auth: {
user: process.env.MAILER_EMAIL_ID || '', user: process.env.MAILER_EMAIL_ID || '',
pass: process.env.MAILER_PASSWORD || '' pass: process.env.MAILER_PASSWORD || ''

View file

@ -21,7 +21,7 @@ module.exports = {
options: process.env.MAILER_SMTP_HOST ? { //Uses custom SMTP if MAILER_SMTP_HOST is set options: process.env.MAILER_SMTP_HOST ? { //Uses custom SMTP if MAILER_SMTP_HOST is set
host: process.env.MAILER_SMTP_HOST || '', host: process.env.MAILER_SMTP_HOST || '',
port: process.env.MAILER_SMTP_PORT || 465, port: process.env.MAILER_SMTP_PORT || 465,
secure: (process.env.MAILER_SMTP_SECURE === 'TRUE'), secure: process.env.MAILER_SMTP_SECURE || true,
auth: { auth: {
user: process.env.MAILER_EMAIL_ID || '', user: process.env.MAILER_EMAIL_ID || '',
pass: process.env.MAILER_PASSWORD || '' pass: process.env.MAILER_PASSWORD || ''

View file

@ -28,8 +28,9 @@ module.exports = {
domain: process.env.BASE_URL || '.tellform.com' domain: process.env.BASE_URL || '.tellform.com'
}, },
assets: { assets: {
css: ['public/dist/application.min.css'], bower_js: 'public/dist/vendor.min.js',
js: ['public/dist/application.min.js', 'public/dist/populate_template_cache.js'], css: 'public/dist/application.min.css',
form_js: ['public/dist/form-application.min.js', 'public/dist/form_populate_template_cache.js', 'public/dist/form-vendor.min.js'] js: 'public/dist/application.min.js',
form_js: 'public/dist/form-application.min.js'
} }
}; };

View file

@ -44,7 +44,7 @@ module.exports = {
options: process.env.MAILER_SMTP_HOST ? { //Uses custom SMTP if MAILER_SMTP_HOST is set options: process.env.MAILER_SMTP_HOST ? { //Uses custom SMTP if MAILER_SMTP_HOST is set
host: process.env.MAILER_SMTP_HOST || '', host: process.env.MAILER_SMTP_HOST || '',
port: process.env.MAILER_SMTP_PORT || 587, port: process.env.MAILER_SMTP_PORT || 587,
secure: (process.env.MAILER_SMTP_SECURE === 'TRUE'), secure: process.env.MAILER_SMTP_SECURE || true,
auth: { auth: {
user: process.env.MAILER_EMAIL_ID || '', user: process.env.MAILER_EMAIL_ID || '',
pass: process.env.MAILER_PASSWORD || '' pass: process.env.MAILER_PASSWORD || ''

2
config/env/test.js vendored
View file

@ -30,7 +30,7 @@ module.exports = {
options: process.env.MAILER_SMTP_HOST ? { //Uses custom SMTP if MAILER_SMTP_HOST is set options: process.env.MAILER_SMTP_HOST ? { //Uses custom SMTP if MAILER_SMTP_HOST is set
host: process.env.MAILER_SMTP_HOST || '', host: process.env.MAILER_SMTP_HOST || '',
port: process.env.MAILER_SMTP_PORT || 587, port: process.env.MAILER_SMTP_PORT || 587,
secure: (process.env.MAILER_SMTP_SECURE === 'TRUE'), secure: process.env.MAILER_SMTP_SECURE || true,
auth: { auth: {
user: process.env.MAILER_EMAIL_ID || '', user: process.env.MAILER_EMAIL_ID || '',
pass: process.env.MAILER_PASSWORD || '' pass: process.env.MAILER_PASSWORD || ''

View file

@ -148,6 +148,8 @@ module.exports = function(db) {
// reassign url // reassign url
req.url = subdomainPath; req.url = subdomainPath;
req.userId = user._id;
// Q.E.D. // Q.E.D.
return next(); return next();
}); });
@ -186,24 +188,6 @@ module.exports = function(db) {
level: 9 level: 9
})); }));
//Setup i18n
i18n.configure({
locales: supportedLanguages,
directory: __dirname + '/locales',
defaultLocale: 'en',
cookie: 'userLang'
});
app.use(i18n.init);
app.use(function(req, res, next) {
// express helper for natively supported engines
res.locals.__ = res.__ = function() {
return i18n.__.apply(req, arguments);
};
next();
});
// Set template engine as defined in the config files // Set template engine as defined in the config files
app.engine('server.view.pug', consolidate.pug); app.engine('server.view.pug', consolidate.pug);
@ -216,7 +200,7 @@ module.exports = function(db) {
app.use(morgan(logger.getLogFormat(), logger.getMorganOptions())); app.use(morgan(logger.getLogFormat(), logger.getMorganOptions()));
// Environment dependent middleware // Environment dependent middleware
if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') { if (process.env.NODE_ENV === 'development') {
// Disable views cache // Disable views cache
app.set('view cache', false); app.set('view cache', false);
} else if (process.env.NODE_ENV === 'production') { } else if (process.env.NODE_ENV === 'production') {
@ -266,17 +250,22 @@ module.exports = function(db) {
app.use(passport.initialize()); app.use(passport.initialize());
app.use(passport.session()); app.use(passport.session());
//Setup i18n
i18n.configure({
locales: supportedLanguages,
directory: __dirname + '/locales',
defaultLocale: 'en',
cookie: 'userLang'
});
app.use(i18n.init);
//Visitor Language Detection //Visitor Language Detection
app.use(function(req, res, next) { app.use(function(req, res, next) {
var acceptLanguage = req.headers['accept-language']; var acceptLanguage = req.headers['accept-language'];
var languages, supportedLanguage; var languages = acceptLanguage.match(/[a-z]{2}(?!-)/g) || [];
if(acceptLanguage){
languages = acceptLanguage.match(/[a-z]{2}(?!-)/g) || [];
supportedLanguage = containsAnySupportedLanguages(languages);
}
var supportedLanguage = containsAnySupportedLanguages(languages);
if(!req.user && supportedLanguage !== null){ if(!req.user && supportedLanguage !== null){
var currLanguage = res.cookie('userLang'); var currLanguage = res.cookie('userLang');
@ -299,7 +288,7 @@ module.exports = function(db) {
app.use(function (req, res, next) { app.use(function (req, res, next) {
// Website you wish to allow to connect // Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'https://sentry.io'); res.setHeader('Access-Control-Allow-Origin', 'https://sentry.polydaic.com');
// Request methods you wish to allow // Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
@ -331,11 +320,16 @@ module.exports = function(db) {
// Log it // Log it
client.captureError(err); client.captureError(err);
// Error page if(process.env.NODE_ENV === 'production'){
res.status(500).render('500', { res.status(500).render('500', {
__: i18n.__, error: 'Internal Server Error'
error: err.stack });
}); } else {
// Error page
res.status(500).render('500', {
error: err.stack
});
}
}); });
// Assume 404 since no middleware responded // Assume 404 since no middleware responded
@ -343,8 +337,7 @@ module.exports = function(db) {
client.captureError(new Error('Page Not Found')); client.captureError(new Error('Page Not Found'));
res.status(404).render('404', { res.status(404).render('404', {
url: req.originalUrl, url: req.originalUrl,
error: 'Not Found', error: 'Not Found'
__: i18n.__
}); });
}); });

View file

@ -2,20 +2,21 @@
"404_HEADER": "404 - Page non trouvée", "404_HEADER": "404 - Page non trouvée",
"500_HEADER": "500 - Erreur interne du serveur", "500_HEADER": "500 - Erreur interne du serveur",
"404_BODY": "%s n'est pas un chemin valide.", "404_BODY": "%s n'est pas un chemin valide.",
"500_BODY": "Une erreur inattendue semble s'être produite, pourquoi ne pas essayer d'actualiser votre page ? Ou vous pouvez nous contacter si le problème persiste.", "500_BODY": "Une erreur inattendue semble s'être produite, pourquoi ne pas essayer d'actualiser votre page? Ou vous pouvez nous contacter si le problème persiste.",
"EMAIL_GREETING": "Bonjour !", "EMAIL_GREETING": "Bonjour!",
"VERIFICATION_EMAIL_PARAGRAPH_1": "Bienvenue sur TellForm ! Voici un lien spécial pour activer votre nouveau compte : ", "VERIFICATION_EMAIL_PARAGRAPH_1": "Bienvenue sur TellForm! Voici un lien spécial pour activer votre nouveau compte:",
"VERIFICATION_EMAIL_LINK_TEXT": "Activer mon compte", "VERIFICATION_EMAIL_LINK_TEXT": "Activer mon compte",
"VERIFICATION_EMAIL_PARAGRAPH_2": "Merci infiniment d'utiliser nos services ! Si vous avez des questions ou des suggestions, n'hésitez pas à nous envoyer un courriel ici", "VERIFICATION_EMAIL_PARAGRAPH_2": "Merci beaucoup pour l'utilisation de nos services! Si vous avez des questions ou des suggestions, n'hésitez pas à nous envoyer un courriel ici",
"VERIFICATION_EMAIL_SUBJECT": "Activer votre nouveau compte TellForm !", "VERIFICATION_EMAIL_SUBJECT": "¡Active su nueva cuenta TellForm!",
"VERIFICATION_EMAIL_TEXT": "Merci de vérifier votre compte en cliquant sur le lien suivant, ou en le copiant dans votre navigateur web : ${URL}", "VERIFICATION_EMAIL_TEXT": "Verifique su cuenta haciendo clic en el siguiente enlace, o copiándolo y pegándolo en su navegador: $ {URL}",
"EMAIL_SIGNATURE": "- L'équipe TellForm", "EMAIL_SIGNATURE": "- L'équipe TellForm",
"WELCOME_EMAIL_PARAGRAPH_1": "Nous aimerions vous accueillir en tant que nouveau membre !", "WELCOME_EMAIL_PARAGRAPH_1": "Nous aimerions vous accueillir en tant que nouveau membre!",
"WELCOME_EMAIL_PARAGRAPH_2": "Nous espérons que vous apprécierez l'utilisation de TellForm ! Si vous avez des problèmes, n'hésitez pas à nous envoyer un e-mail ici", "WELCOME_EMAIL_PARAGRAPH_2": "Nous espérons que vous apprécierez l'utilisation de TellForm! Si vous avez des problèmes, n'hésitez pas à nous envoyer un e-mail ici",
"WELCOME_EMAIL_SUBJECT": "Bienvenue dans %s!", "WELCOME_EMAIL_SUBJECT": "Bienvenue dans %s!",
"WELCOME_EMAIL_TEXT": "Votre compte a été vérifié avec succès.", "WELCOME_EMAIL_TEXT": "Votre compte a été vérifié avec succès.",
"RESET_PASSWORD_CONFIRMATION_EMAIL_PARAGRAPH_1": "Ceci est un message de courtoisie pour confirmer que votre mot de passe a été modifié.", "RESET_PASSWORD_CONFIRMATION_EMAIL_PARAGRAPH_1": "Ceci est un message de courtoisie pour confirmer que votre mot de passe a été modifié.",
"RESET_PASSWORD_REQUEST_EMAIL_PARAGRAPH_1": "Voici un lien spécial qui vous permettra de réinitialiser votre mot de passe. Veuillez noter qu'il expirera dans une heure pour votre protection :", "RESET_PASSWORD_REQUEST_EMAIL_PARAGRAPH_1": "Voici un lien spécial qui vous permettra de réinitialiser votre mot de passe Veuillez noter qu'il expirera dans une heure pour votre protection:",
"RESET_PASSWORD_REQUEST_EMAIL_LINK_TEXT": "Réinitialiser votre mot de passe", "RESET_PASSWORD_REQUEST_EMAIL_LINK_TEXT": "Réinitialiser votre mot de passe",
"RESET_PASSWORD_REQUEST_EMAIL_PARAGRAPH_2": "Si vous ne l'avez pas demandé, veuillez ignorer cet e-mail et votre mot de passe restera inchangé." "RESET_PASSWORD_REQUEST_EMAIL_PARAGRAPH_2": "Si vous ne l'avez pas demandé, veuillez ignorer cet e-mail et votre mot de passe restera inchangé.",
} "RESET_PASSWORD_CONFIRMATION_EMAIL_BODY_1": "RESET_PASSWORD_CONFIRMATION_EMAIL_BODY_1"
}

View file

@ -1,22 +0,0 @@
{
"500_HEADER": "500 - Internt Serverfel",
"404_HEADER": "404 - Sidan hittades inte",
"404_BODY": "%s är inte en giltig sökväg",
"500_BODY": "Ett oväntat fel verkar ha inträffat. Kan du prova med att uppdatera sidan? Eller kan du kontakta oss om problemet återuppstår igen?",
"EMAIL_GREETING": "Hej där!",
"VERIFICATION_EMAIL_PARAGRAPH_1": "Välkommen till TellForm! Här är en speciell länk till dig för att aktivera ditt nya konto:",
"VERIFICATION_EMAIL_LINK_TEXT": "Aktivera mitt konto",
"VERIFICATION_EMAIL_PARAGRAPH_2": "Tack så mycket för att du använder våra tjänster! Om du har några frågor eller förslag är du varmt välkommen att e-posta oss här på",
"VERIFICATION_EMAIL_SUBJECT": "Aktivera ditt nya TellForm-konto!",
"VERIFICATION_EMAIL_TEXT": "Vänligen verifiera ditt konto genom att klicka på den följande länken, eller genom att kopiera och klistra in den i din webbläsare: ${URL}",
"EMAIL_SIGNATURE": "- TellForm-gruppen",
"WELCOME_EMAIL_PARAGRAPH_1": "Vi skulle vilja välkomna dig som vår nyaste medlem!",
"WELCOME_EMAIL_PARAGRAPH_2": "Vi hoppas att du gillar att använda TellForm! Om du stöter på några problem är du varmt välkommen att e-posta oss här på",
"WELCOME_EMAIL_SUBJECT": "Välkommen till %s!",
"WELCOME_EMAIL_TEXT": "Ditt konto har framgångsrikt blivit verifierat.",
"RESET_PASSWORD_CONFIRMATION_EMAIL_PARAGRAPH_1": "Detta är ett artigt meddelande för att bekräfta att ditt lösenord just har ändrats.",
"RESET_PASSWORD_REQUEST_EMAIL_PARAGRAPH_1": "Här är en speciell länk som kommer tillåta dig att återställa ditt lösenord. Vänligen notera att det kommer utgå om en timma för din säkerhet:",
"RESET_PASSWORD_REQUEST_EMAIL_LINK_TEXT": "Återställ Ditt Lösenord",
"RESET_PASSWORD_REQUEST_EMAIL_PARAGRAPH_2": "Om du inte begärde detta, vänligen ignorera detta meddelande och ditt lösenord kommer att förbli oförändrat.",
"RESET_PASSWORD_CONFIRMATION_EMAIL_BODY_1": "RESET_PASSWORD_CONFIRMATION_EMAIL_BODY_1"
}

View file

@ -9,14 +9,7 @@ var config = require('./config'),
// Define the Socket.io configuration method // Define the Socket.io configuration method
module.exports = function (app, db) { module.exports = function (app, db) {
var server = http.createServer(app); var server = http.createServer(app);
var io; var io = socketio(config.socketPort, { transports: ['websocket', 'polling'] });
// make it possible to only expose one domain
if (process.env.SOCKET_PORT != process.env.PORT) {
io = socketio(config.socketPort, { transports: ['websocket', 'polling'] });
} else {
io = socketio(server, { transports: ['websocket', 'polling'] });
}
if(config.enableClusterMode){ if(config.enableClusterMode){
var redis = require('socket.io-redis'); var redis = require('socket.io-redis');

View file

@ -14,6 +14,8 @@ module.exports = function () {
passwordField: 'password' passwordField: 'password'
}, },
function (username, password, done) { function (username, password, done) {
console.log('\n\n\n\n\nusername: '+username);
console.log('password: '+password)
User.findOne({ User.findOne({
$or: [ $or: [
{'username': username.toLowerCase()}, {'username': username.toLowerCase()},

View file

@ -1,55 +0,0 @@
version: "3"
services:
redis:
restart: always
image: redis
networks:
- back-tier
mongo:
restart: always
image: mongo
volumes:
- ".data/mongo:/data"
networks:
- back-tier
tellform:
build:
context: .
environment:
CREATE_ADMIN: "TRUE"
MONGODB_URI: mongodb://mongo/tellform
REDIS_URL: redis://redis
# volumes:
# - .:/opt/tellform
links:
- mongo
- redis
ports:
- "5000:5000"
depends_on:
- mongo
- redis
networks:
- back-tier
web:
# image: tellform/nginx:stable
build:
context: ./nginx
# image: nginx:1.13
restart: always
ports:
- "80:80"
- "443:443"
- "20523:20523"
environment:
NODE_ENV: development
#volumes:
# - "$ROOT/certs:/certs"
# - ./nginx/conf.d:/etc/nginx/conf.d
networks:
- back-tier
networks:
back-tier:
driver: bridge

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 105 KiB

View file

@ -123,7 +123,7 @@ module.exports = function(grunt) {
compress: true compress: true
}, },
files: { files: {
'public/dist/form-vendor.min.js': bowerArray 'public/dist/vendor.min.js': bowerArray
} }
} }
}, },
@ -151,8 +151,8 @@ module.exports = function(grunt) {
}, },
production: { production: {
files: { files: {
'public/dist/application.js': '<%= applicationJavaScriptFiles %>', 'public/dist/application.js': ['public/application.js', 'public/config.js', 'public/form_modules/**/*.js'],
'public/dist/form-application.js': '<%= formApplicationJavaScriptFiles %>' 'public/dist/form_application.js': ['public/form-application.js', 'public/form-config.js', 'public/form_modules/**/*.js']
} }
} }
}, },
@ -329,12 +329,15 @@ module.exports = function(grunt) {
grunt.registerTask('coverage:server', ['env:test', 'mocha_istanbul:coverageServer']); grunt.registerTask('coverage:server', ['env:test', 'mocha_istanbul:coverageServer']);
// Default task(s). // Default task(s).
grunt.registerTask('default', ['lint', 'loadConfig', 'ngAnnotate', 'uglify', 'html2js:main', 'html2js:forms', 'env', 'concurrent:default']); grunt.registerTask('default', ['lint', 'html2js:main', 'html2js:forms', 'env', 'concurrent:default']);
grunt.registerTask('dev', ['lint', 'html2js:main', 'html2js:forms', 'env:dev', 'concurrent:default']); grunt.registerTask('dev', ['lint', 'html2js:main', 'html2js:forms', 'env:dev', 'concurrent:default']);
// Debug task. // Debug task.
grunt.registerTask('debug', ['lint', 'html2js:main', 'html2js:forms', 'concurrent:debug']); grunt.registerTask('debug', ['lint', 'html2js:main', 'html2js:forms', 'concurrent:debug']);
// Secure task(s).
grunt.registerTask('secure', ['env:secure', 'lint', 'html2js:main', 'html2js:forms', 'concurrent:default']);
// Lint task(s). // Lint task(s).
grunt.registerTask('lint', ['jshint', 'csslint', 'i18nlint:client', 'i18nlint:server']); grunt.registerTask('lint', ['jshint', 'csslint', 'i18nlint:client', 'i18nlint:server']);
grunt.registerTask('lint:tests', ['jshint:allTests']); grunt.registerTask('lint:tests', ['jshint:allTests']);

View file

@ -1,19 +0,0 @@
FROM alpine:edge
RUN apk add --no-cache nginx certbot openssl python py-jinja2
COPY *.py /
COPY conf /conf
RUN chmod +x /start.py
RUN chmod +x /letsencrypt.py
RUN chmod +x /config.py
ENV NODE_ENV=development
ENV PORT=5000
ENV SOCKET_PORT=20523
ENV TLS_FLAVOR=notls
ENV BASE_URL=localhost
ENV SUBDOMAIN_URL=*.localhost
ENV SOCKETS_URL=ws.localhost
CMD /start.py

View file

@ -1,116 +0,0 @@
# Basic configuration
user nginx;
worker_processes 1;
error_log /dev/stderr info;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
# Standard HTTP configuration with slight hardening
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /dev/stdout;
sendfile on;
keepalive_timeout 65;
server_tokens off;
#Websockets Server
server {
{% if NODE_ENV == "development" %}
listen {{SOCKET_PORT}};
{% else %}
listen 80;
listen [::]:80;
server_name {{ SOCKETS_URL }};
# Only enable HTTPS if TLS is enabled with no error
{% if TLS and not TLS_ERROR %}
listen 443 ssl;
listen [::]:443 ssl;
include /etc/nginx/tls.conf;
add_header Strict-Transport-Security max-age=15768000;
if ($scheme = http) {
return 301 https://$host$request_uri;
}
{% endif %}
{% endif %}
location / {
proxy_pass http://tellform:20523;
proxy_read_timeout 90;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# WebSocket support
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
{% if TLS and not TLS_ERROR %}
proxy_set_header X-Forwarded-Proto https;
{% endif %}
}
{% if TLS_FLAVOR == 'letsencrypt' %}
location ^~ /.well-known/acme-challenge/ {
proxy_pass http://127.0.0.1:8008;
}
{% endif %}
}
server {
#Add server_name for per-user subdomains
{% if SUBDOMAINS_DISABLED == "FALSE" %}
server_name {{BASE_URL}} {{SUBDOMAIN_URL}};
{% else %}
server_name {{BASE_URL}};
{% endif %}
listen 80;
listen [::]:80;
# Only enable HTTPS if TLS is enabled with no error
{% if TLS and not TLS_ERROR %}
listen 443 ssl;
listen [::]:443 ssl;
include /etc/nginx/tls.conf;
add_header Strict-Transport-Security max-age=15768000;
if ($scheme = http) {
return 301 https://$host$request_uri;
}
{% endif %}
root /usr/share/nginx/html;
index index.html index.htm;
location / {
proxy_pass http://tellform:5000;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for ;
{% if TLS and not TLS_ERROR %}
proxy_set_header X-Forwarded-Proto https;
{% endif %}
}
{% if TLS_FLAVOR == 'letsencrypt' %}
location ^~ /.well-known/acme-challenge/ {
proxy_pass http://127.0.0.1:8008;
}
{% endif %}
}
}

View file

@ -1,7 +0,0 @@
ssl_protocols TLSv1.1 TLSv1.2;
ssl_ciphers 'ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384';
ssl_prefer_server_ciphers on;
ssl_session_timeout 10m;
ssl_certificate {{ TLS[0] }};
ssl_certificate_key {{ TLS[1] }};
ssl_dhparam /certs/dhparam.pem;

View file

@ -1,26 +0,0 @@
#!/usr/bin/python
import jinja2
import os
convert = lambda src, dst, args: open(dst, "w").write(jinja2.Template(open(src).read()).render(**args))
args = os.environ.copy()
# TLS configuration
args["TLS"] = {
"cert": ("/certs/cert.pem", "/certs/key.pem"),
"letsencrypt": ("/certs/letsencrypt/live/mailu/fullchain.pem",
"/certs/letsencrypt/live/mailu/privkey.pem"),
"notls": None
}[args["TLS_FLAVOR"]]
if args["TLS"] and not all(os.path.exists(file_path) for file_path in args["TLS"]):
print("Missing cert or key file, disabling TLS")
args["TLS_ERROR"] = "yes"
# Build final configuration paths
convert("/conf/tls.conf", "/etc/nginx/tls.conf", args)
convert("/conf/nginx.conf", "/etc/nginx/nginx.conf", args)
os.system("nginx -s reload")

View file

@ -1,29 +0,0 @@
#!/usr/bin/python
import os
import time
import subprocess
command = [
"certbot",
"-n", "--agree-tos", # non-interactive
"-d", os.environ["HOSTNAMES"],
"-m", "{}@{}".format(os.environ["POSTMASTER"], os.environ["DOMAIN"]),
"certonly", "--standalone",
"--server", "https://acme-v02.api.letsencrypt.org/directory",
"--cert-name", "tellform",
"--preferred-challenges", "http", "--http-01-port", "8008",
"--keep-until-expiring",
"--rsa-key-size", "4096",
"--config-dir", "/certs/letsencrypt",
"--post-hook", "./config.py"
]
# Wait for nginx to start
time.sleep(5)
# Run certbot every hour
while True:
subprocess.call(command)
time.sleep(3600)

View file

@ -1,25 +0,0 @@
#!/usr/bin/python
import os
import subprocess
#Set default port
if not os.environ["PORT"]:
os.environ["PORT"] = "5000"
#Set default sockets port
if not os.environ["SOCKET_PORT"]:
os.environ["SOCKET_PORT"] = "20523"
# Actual startup script
if not os.path.exists("/certs/dhparam.pem") and os.environ["TLS_FLAVOR"] != "notls":
os.system("openssl dhparam -out /certs/dhparam.pem 2048")
if os.environ["TLS_FLAVOR"] == "letsencrypt":
subprocess.Popen(["/letsencrypt.py"])
elif os.environ["TLS_FLAVOR"] == "cert":
if not os.path.exists("/certs/cert.pem"):
os.system("openssl req -newkey rsa:2048 -x509 -keyout /certs/key.pem -out /certs/cert.pem -days 365 -nodes -subj '/C=NA/ST=None/L=None/O=None/CN=" + os.environ["BASE_URL"] + "'")
subprocess.call(["/config.py"])
os.execv("/usr/sbin/nginx", ["nginx", "-g", "daemon off;"])

14204
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -21,25 +21,25 @@
"generate": "all-contributors generate", "generate": "all-contributors generate",
"start": "grunt", "start": "grunt",
"test": "grunt test", "test": "grunt test",
"postinstall": "bower install --config.interactive=false", "postinstall": "bower install --config.interactive=false; grunt build;",
"init": "node scripts/setup.js" "init": "node scripts/setup.js"
}, },
"dependencies": { "dependencies": {
"async": "^1.4.2", "async": "^1.4.2",
"body-parser": "^1.19.0", "bcrypt": "^0.8.7",
"bower": "^1.8.8", "body-parser": "~1.14.1",
"bower": "~1.6.5",
"chalk": "^1.1.3", "chalk": "^1.1.3",
"compression": "^1.7.4", "compression": "~1.6.0",
"connect": "^3.4.1", "connect": "^3.4.1",
"connect-mongo": "^2.0.0", "connect-mongo": "~0.8.2",
"consolidate": "~0.14.5", "consolidate": "~0.14.5",
"cookie-parser": "~1.4.0", "cookie-parser": "~1.4.0",
"deep-diff": "^0.3.4", "deep-diff": "^0.3.4",
"dotenv": "^2.0.0", "dotenv": "^2.0.0",
"email-verification": "github:tellform/node-email-verification", "email-verification": "github:tellform/node-email-verification",
"envfile": "^2.1.1", "express": "~4.13.3",
"express": "^4.16.4", "express-session": "~1.12.1",
"express-session": "^1.16.1",
"glob": "^7.0.3", "glob": "^7.0.3",
"grunt": "~0.4.1", "grunt": "~0.4.1",
"grunt-concurrent": "~2.3.0", "grunt-concurrent": "~2.3.0",
@ -48,17 +48,17 @@
"grunt-contrib-jshint": "~1.0.0", "grunt-contrib-jshint": "~1.0.0",
"grunt-contrib-uglify": "~0.11.0", "grunt-contrib-uglify": "~0.11.0",
"grunt-env": "~0.4.1", "grunt-env": "~0.4.1",
"grunt-html2js": "^0.6.0", "grunt-html2js": "~0.3.5",
"grunt-ng-annotate": "~1.0.1", "grunt-ng-annotate": "~1.0.1",
"helmet": "^3.16.0", "helmet": "3.5.0",
"i18n": "^0.8.3", "i18n": "^0.8.3",
"jit-grunt": "^0.9.1", "jit-grunt": "^0.9.1",
"lodash": "^4.17.11", "lodash": "^4.17.4",
"main-bower-files": "^2.13.1", "main-bower-files": "~2.9.0",
"method-override": "~2.3.0", "method-override": "~2.3.0",
"mkdirp": "^0.5.1", "mkdirp": "^0.5.1",
"mongoose": "~4.4.19", "mongoose": "~4.4.19",
"morgan": "^1.9.1", "morgan": "~1.8.1",
"nodemailer": "~4.0.0", "nodemailer": "~4.0.0",
"passport": "~0.3.0", "passport": "~0.3.0",
"passport-anonymous": "^1.0.1", "passport-anonymous": "^1.0.1",
@ -66,15 +66,17 @@
"passport-localapikey-update": "^0.5.0", "passport-localapikey-update": "^0.5.0",
"path-exists": "^2.1.0", "path-exists": "^2.1.0",
"prerender-node": "^2.2.1", "prerender-node": "^2.2.1",
"pug": "^2.0.3", "pug": "^2.0.0-rc.4",
"random-js": "^1.0.8", "random-js": "^1.0.8",
"raven": "^0.9.0", "raven": "^0.9.0",
"request": "^2.88.0", "request": "^2.83.0",
"socket.io": "^1.4.6", "socket.io": "^1.4.6",
"socket.io-redis": "^1.0.0", "socket.io-redis": "^1.0.0",
"swig": "~1.4.1", "swig": "~1.4.1",
"uuid-token-generator": "^0.5.0", "uuid-token-generator": "^0.5.0",
"winston": "^2.3.1" "wildcard-subdomains": "github:tellform/wildcard-subdomains",
"winston": "^2.3.1",
"winston-logrotate": "^1.2.0"
}, },
"devDependencies": { "devDependencies": {
"all-contributors-cli": "^4.3.0", "all-contributors-cli": "^4.3.0",

0
public/dist/.placeholder vendored Normal file
View file

1349
public/dist/application.js vendored Normal file

File diff suppressed because it is too large Load diff

4
public/dist/application.min.css vendored Normal file

File diff suppressed because one or more lines are too long

1
public/dist/application.min.js vendored Normal file

File diff suppressed because one or more lines are too long

1394
public/dist/form-application.js vendored Normal file

File diff suppressed because one or more lines are too long

2
public/dist/form-application.min.js vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

Before

Width:  |  Height:  |  Size: 46 KiB

After

Width:  |  Height:  |  Size: 46 KiB

20
public/dist/vendor.min.js vendored Normal file

File diff suppressed because one or more lines are too long

0
public/dist/vendor.min.js.report.txt vendored Normal file
View file

20611
public/dist/vendor_forms_uglified.js vendored Normal file

File diff suppressed because one or more lines are too long

19430
public/dist/vendor_uglified.js vendored Normal file

File diff suppressed because one or more lines are too long

View file

@ -14,13 +14,13 @@ angular.module('view-form').config(['$translateProvider', function ($translatePr
COMPLETING_NEEDED: '{{answers_not_completed}} réponse(s) doive(nt) être complétée(s)', COMPLETING_NEEDED: '{{answers_not_completed}} réponse(s) doive(nt) être complétée(s)',
OPTIONAL: 'facultatif', OPTIONAL: 'facultatif',
ERROR_EMAIL_INVALID: 'Merci de rentrer une adresse mail valide', ERROR_EMAIL_INVALID: 'Merci de rentrer une adresse mail valide',
ERROR_NOT_A_NUMBER: 'Merci de ne rentrer que des nombres', ERROR_NOT_A_NUMBER: 'Merce de ne rentrer que des nombres',
ERROR_URL_INVALID: 'Merci de rentrer une url valide', ERROR_URL_INVALID: 'Merci de rentrer une url valide',
OK: 'OK', OK: 'OK',
ENTER: 'Appuyer sur ENTRÉE', ENTER: 'presser ENTRÉE',
YES: 'Oui', YES: 'Oui',
NO: 'Non', NO: 'Non',
NEWLINE: 'Appuyer sur SHIFT+ENTER pour créer une nouvelle ligne', NEWLINE: 'presser SHIFT+ENTER pour créer une nouvelle ligne',
CONTINUE: 'Continuer', CONTINUE: 'Continuer',
LEGAL_ACCEPT: 'Jaccepte', LEGAL_ACCEPT: 'Jaccepte',
LEGAL_NO_ACCEPT: 'Je naccepte pas', LEGAL_NO_ACCEPT: 'Je naccepte pas',
@ -33,13 +33,13 @@ angular.module('view-form').config(['$translateProvider', function ($translatePr
OPTION_PLACEHOLDER: 'Tapez ou sélectionnez une option', OPTION_PLACEHOLDER: 'Tapez ou sélectionnez une option',
ADD_NEW_LINE_INSTR: 'Appuyez sur MAJ + ENTRÉE pour ajouter une nouvelle ligne', ADD_NEW_LINE_INSTR: 'Appuyez sur MAJ + ENTRÉE pour ajouter une nouvelle ligne',
ERROR: 'Erreur', ERROR: 'Erreur',
FORM_404_HEADER: '404 - Le formulaire n\'existe pas', FORM_404_HEADER: '404 - Le formulaire n\'existe pas',
FORM_404_BODY: 'Le formulaire auquel vous essayez d\'accéder n\'existe pas. Désolé pour ça !', FORM_404_BODY: 'Le formulaire auquel vous essayez d\'accéder n\'existe pas. Désolé pour ça!',
FORM_UNAUTHORIZED_HEADER: 'Non autorisé à accéder au formulaire', FORM_UNAUTHORIZED_HEADER: 'Non autorisé à accéder au formulaire',
   FORM_UNAUTHORIZED_BODY1: 'Le formulaire auquel vous essayez d\'accéder est actuellement privé et inaccessible publiquement.',    FORM_UNAUTHORIZED_BODY1: 'Le formulaire auquel vous essayez d\'accéder est actuellement privé et inaccessible publiquement.',
   FORM_UNAUTHORIZED_BODY2: 'Si vous êtes le propriétaire du formulaire, vous pouvez le définir en "Public" dans le panneau "Configuration" du formulaire admin.',    FORM_UNAUTHORIZED_BODY2: 'Si vous êtes le propriétaire du formulaire, vous pouvez le définir sur "Public" dans le panneau "Configuration" du formulaire admin.',
}); });
}]); }]);

View file

@ -1,45 +0,0 @@
'use strict';
angular.module('view-form').config(['$translateProvider', function ($translateProvider) {
$translateProvider.translations('se', {
FORM_SUCCESS: 'Formulärsvaret skickades framgångsrikt in!',
REVIEW: 'Granska',
BACK_TO_FORM: 'Gå tillbaka till Formuläret',
EDIT_FORM: 'Ändra denna TellForm',
CREATE_FORM: 'Skapa denna TellForm',
ADVANCEMENT: '{{done}} utav {{total}} svar',
CONTINUE_FORM: 'Fortsätt till Form',
REQUIRED: 'krävs',
COMPLETING_NEEDED: '{{answers_not_completed}} svar behöver färdigställas',
OPTIONAL: 'valfri',
ERROR_EMAIL_INVALID: 'Vänligen ange en giltig e-postadress',
ERROR_NOT_A_NUMBER: 'Vänligen ange endast giltiga nummer',
ERROR_URL_INVALID: 'Vänligen en giltig url',
OK: 'OK',
ENTER: 'tryck ENTER',
YES: 'Ja',
NO: 'Nej',
NEWLINE: 'tryck SHIFT+ENTER för att skapa ny rad',
CONTINUE: 'Fortsätt',
LEGAL_ACCEPT: 'Jag accepterar',
LEGAL_NO_ACCEPT: 'Jag accepterar inte',
DELETE: 'Radera',
CANCEL: 'Avbryt',
SUBMIT: 'Skicka',
UPLOAD_FILE: 'Ladda upp din Fil',
Y: 'J',
N: 'N',
OPTION_PLACEHOLDER: 'Skriv eller välj ett alternativ',
ADD_NEW_LINE_INSTR: 'Tryck SHIFT+ENTER för att lägga till ny rad',
ERROR: 'Fel',
FORM_404_HEADER: '404 - Formulär Existerar Inte',
FORM_404_BODY: 'Formuläret du försöker besöka till existerar inte. Ursäkta för det!',
FORM_UNAUTHORIZED_HEADER: 'Inte Auktoriserad att Tillgå Formulär',
FORM_UNAUTHORIZED_BODY1: 'Formuläret du försöker att besöka är för närvarande privat och inte tillgänglig offentligt.',
FORM_UNAUTHORIZED_BODY2: 'Om du är ägaren till formuläret kan du ställa in den till "Offentlig" i panelen "Konfiguration" i formulärets administration.',
});
}]);

View file

@ -120,7 +120,6 @@ div.form-fields {
vertical-align: top; vertical-align: top;
zoom: 1; zoom: 1;
width: 16px; width: 16px;
margin-top: 1px;
padding: 0; padding: 0;
height: 17px; height: 17px;
font-size: 12px; font-size: 12px;

View file

@ -26,7 +26,8 @@
ng-change="nextField()"> ng-change="nextField()">
<ui-select-match placeholder="{{ 'OPTION_PLACEHOLDER' | translate }}"> <ui-select-match placeholder="{{ 'OPTION_PLACEHOLDER' | translate }}">
</ui-select-match> </ui-select-match>
<ui-select-choices repeat="option in field.fieldOptions | filter: $select.search"> <ui-select-choices repeat="option in field.fieldOptions | filter: $select.search"
ng-class="{'active': option.option_value === field.fieldValue }">
<span ng-bind-html="option.option_value | highlight: $select.search"></span> <span ng-bind-html="option.option_value | highlight: $select.search"></span>
</ui-select-choices> </ui-select-choices>
</ui-select> </ui-select>

View file

@ -2,7 +2,7 @@
// Setting up route // Setting up route
angular.module('core').config(['$stateProvider', '$urlRouterProvider', angular.module('core').config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) { function($stateProvider, $urlRouterProvider, Authorization) {
// Redirect to home view when route not found // Redirect to home view when route not found
$urlRouterProvider.otherwise('/forms'); $urlRouterProvider.otherwise('/forms');
} }
@ -15,13 +15,10 @@ angular.module(ApplicationConfiguration.applicationModuleName).run(['$rootScope'
$rootScope.$stateParams = $stateParams; $rootScope.$stateParams = $stateParams;
// add previous state property // add previous state property
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) { $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState) {
$state.previous = { $state.previous = fromState;
state: fromState,
params: fromParams
}
var statesToIgnore = ['', 'home', 'signin', 'resendVerifyEmail', 'verify', 'signup', 'signup-success', 'forgot', 'reset-invalid', 'reset', 'reset-success']; var statesToIgnore = ['home', 'signin', 'resendVerifyEmail', 'verify', 'signup', 'signup-success', 'forgot', 'reset-invalid', 'reset', 'reset-success'];
//Redirect to listForms if user is authenticated //Redirect to listForms if user is authenticated
if(statesToIgnore.indexOf(toState.name) > 0){ if(statesToIgnore.indexOf(toState.name) > 0){
@ -48,7 +45,7 @@ angular.module(ApplicationConfiguration.applicationModuleName).run(['$rootScope'
var authenticator, permissions, user; var authenticator, permissions, user;
permissions = next && next.data && next.data.permissions ? next.data.permissions : null; permissions = next && next.data && next.data.permissions ? next.data.permissions : null;
Auth.ensureHasCurrentUser(); Auth.ensureHasCurrentUser(User);
user = Auth.currentUser; user = Auth.currentUser;
if(user){ if(user){

View file

@ -4,12 +4,12 @@ angular.module('core').config(['$translateProvider', function ($translateProvide
$translateProvider.translations('fr', { $translateProvider.translations('fr', {
MENU: 'MENU', MENU: 'MENU',
SIGNUP_TAB: 'Créer un compte', SIGNUP_TAB: 'Créer un Compte',
SIGNIN_TAB: 'Connexion', SIGNIN_TAB: 'Connexion',
SIGNOUT_TAB: 'Créer un compte', SIGNOUT_TAB: 'Créer un compte',
EDIT_PROFILE: 'Modifier mon profil', EDIT_PROFILE: 'Modifier Mon Profil',
MY_SETTINGS: 'Mes paramètres', MY_SETTINGS: 'Mes Paramètres',
CHANGE_PASSWORD: 'Changer mon mot de passe', CHANGE_PASSWORD: 'Changer mon Mot de Pass',
TOGGLE_NAVIGATION: 'Basculer la navigation', TOGGLE_NAVIGATION: 'Basculer la navigation',
}); });
}]); }]);

View file

@ -1,16 +0,0 @@
'use strict';
angular.module('core').config(['$translateProvider', function ($translateProvider) {
$translateProvider.translations('se', {
MENU: 'MENY',
SIGNUP_TAB: 'Registrera konto',
SIGNIN_TAB: 'Logga In',
SIGNOUT_TAB: 'Logga Ut',
EDIT_PROFILE: 'Redigera Profil',
MY_SETTINGS: 'Mina Inställningar',
CHANGE_PASSWORD: 'Byt Lösenord',
TOGGLE_NAVIGATION: 'Växla navigation'
});
}]);

View file

@ -5,7 +5,7 @@ angular.module('core').controller('HeaderController', ['$rootScope', '$scope', '
$rootScope.signupDisabled = $window.signupDisabled; $rootScope.signupDisabled = $window.signupDisabled;
$scope.user = $rootScope.user = Auth.ensureHasCurrentUser(); $scope.user = $rootScope.user = Auth.ensureHasCurrentUser(User);
$scope.authentication = $rootScope.authentication = Auth; $scope.authentication = $rootScope.authentication = Auth;
@ -23,7 +23,7 @@ angular.module('core').controller('HeaderController', ['$rootScope', '$scope', '
var promise = User.logout(); var promise = User.logout();
promise.then(function() { promise.then(function() {
Auth.logout(); Auth.logout();
Auth.ensureHasCurrentUser(); Auth.ensureHasCurrentUser(User);
$scope.user = $rootScope.user = null; $scope.user = $rootScope.user = null;
$state.go('listForms'); $state.go('listForms');

View file

@ -6,38 +6,9 @@
var scope, var scope,
HeaderController; HeaderController;
var sampleUser = {
firstName: 'Full',
lastName: 'Name',
email: 'test@test.com',
username: 'test@test.com',
language: 'en',
password: 'password',
provider: 'local',
roles: ['user'],
_id: 'ed873933b1f1dea0ce12fab9'
};
// Load the main application module // Load the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName)); beforeEach(module(ApplicationConfiguration.applicationModuleName));
//Mock Authentication Service
beforeEach(module(function($provide) {
$provide.service('Auth', function() {
return {
ensureHasCurrentUser: function() {
return sampleUser;
},
isAuthenticated: function() {
return true;
},
getUserState: function() {
return true;
}
};
});
}));
beforeEach(inject(function($controller, $rootScope) { beforeEach(inject(function($controller, $rootScope) {
scope = $rootScope.$new(); scope = $rootScope.$new();

View file

@ -10,17 +10,17 @@ angular.module('forms').config(['$translateProvider', function ($translateProvid
PUBLIC: 'Public', PUBLIC: 'Public',
PRIVATE: "Privé", PRIVATE: "Privé",
GA_TRACKING_CODE: "Code de suivi Google Analytics", GA_TRACKING_CODE: "Code de suivi Google Analytics",
DISPLAY_FOOTER: "Afficher le pied de formulaire ?", DISPLAY_FOOTER: "Afficher le pied de formulaire?",
SAVE_CHANGES: 'Enregistrer les modifications', SAVE_CHANGES: 'Enregistrer les modifications',
CANCEL: 'Annuler', CANCEL: 'Annuler',
DISPLAY_START_PAGE: "Afficher la page de démarrage ?", DISPLAY_START_PAGE: "Afficher la page de démarrage?",
DISPLAY_END_PAGE: "Afficher la page de fin personnalisée ?", DISPLAY_END_PAGE: "Afficher la page de fin personnalisée?",
// Afficher les formulaires // Afficher les formulaires
CREATE_A_NEW_FORM: "Créer un nouveau formulaire", CREATE_A_NEW_FORM: "Créer un nouveau formulaire",
CREATE_FORM: "Créer un formulaire", CREATE_FORM: "Créer un formulaire",
CREATED_ON: 'Créé le', CREATED_ON: 'Créé le',
MY_FORMS: 'Mes formulaires', MY_FORMS: 'Mes formes',
NAME: "Nom", NAME: "Nom",
LANGUE: 'Langue', LANGUE: 'Langue',
FORM_PAUSED: 'Formulaire en pause', FORM_PAUSED: 'Formulaire en pause',
@ -53,7 +53,7 @@ angular.module('forms').config(['$translateProvider', function ($translateProvid
COPY_AND_PASTE: "Copiez et collez ceci pour ajouter votre TellForm à votre site Web", COPY_AND_PASTE: "Copiez et collez ceci pour ajouter votre TellForm à votre site Web",
CHANGE_WIDTH_AND_HEIGHT: "Changez les valeurs de largeur et de hauteur pour mieux vous convenir", CHANGE_WIDTH_AND_HEIGHT: "Changez les valeurs de largeur et de hauteur pour mieux vous convenir",
POWERED_BY: "Alimenté par", POWERED_BY: "Alimenté par",
TELLFORM_URL: "Votre TellForm est disponible à cette URL", TELLFORM_URL: "Votre TellForm est en permanence sur cette URL",
// Modifier la vue de formulaire // Modifier la vue de formulaire
DISABLED: "Désactivé", DISABLED: "Désactivé",
@ -129,7 +129,7 @@ angular.module('forms').config(['$translateProvider', function ($translateProvid
// Vue de conception // Vue de conception
BACKGROUND_COLOR: "Couleur d'arrière-plan", BACKGROUND_COLOR: "Couleur d'arrière-plan",
DESIGN_HEADER: "Changer l'apparence de votre formulaire", DESIGN_HEADER: "Changez l'apparence de votre formulaire",
QUESTION_TEXT_COLOR: "Couleur du texte de la question", QUESTION_TEXT_COLOR: "Couleur du texte de la question",
ANSWER_TEXT_COLOR: "Couleur du texte de la réponse", ANSWER_TEXT_COLOR: "Couleur du texte de la réponse",
BTN_BACKGROUND_COLOR: "Couleur d'arrière-plan du bouton", BTN_BACKGROUND_COLOR: "Couleur d'arrière-plan du bouton",

View file

@ -84,6 +84,7 @@ angular.module('forms').config(['$translateProvider', function ($translateProvid
ADD_OPTION: 'Option hinzufügen', ADD_OPTION: 'Option hinzufügen',
NUM_OF_STEPS: 'Anzahl der Schritte', NUM_OF_STEPS: 'Anzahl der Schritte',
CLICK_FIELDS_FOOTER: 'Klicken Sie auf Felder, um sie hier hinzuzufügen', CLICK_FIELDS_FOOTER: 'Klicken Sie auf Felder, um sie hier hinzuzufügen',
FORM: 'Formular',
IF_THIS_FIELD: 'Wenn dieses Feld', IF_THIS_FIELD: 'Wenn dieses Feld',
IS_EQUAL_TO: 'ist gleich', IS_EQUAL_TO: 'ist gleich',
IS_NOT_EQUAL_TO: 'ist nicht gleich', IS_NOT_EQUAL_TO: 'ist nicht gleich',

View file

@ -1,189 +0,0 @@
'use strict';
angular.module('forms').config(['$translateProvider', function ($translateProvider) {
$translateProvider.translations('sv', {
// Konfigurera Formulär Tab Vy
ADVANCED_SETTINGS: 'Avancerade Inställningar',
FORM_NAME: 'Namn På Formulär',
FORM_STATUS: 'Status På Formulär',
PUBLIC: 'Offentlig',
PRIVATE: 'Privat',
GA_TRACKING_CODE: 'Google Analytics Spårningskod',
DISPLAY_FOOTER: 'Visa Formulär Footer?',
SAVE_CHANGES: 'Spara Ändringar',
CANCEL: 'Avbryt',
DISPLAY_START_PAGE: 'Visa Startsida?',
DISPLAY_END_PAGE: 'Visa Anpassad Avslutningssida?',
// Lista Formulär-vy
CREATE_A_NEW_FORM: 'Skapa ett nytt formulär',
CREATE_FORM: 'Skapa formulär',
CREATED_ON: 'Skapad den',
MY_FORMS: 'Mina Formulär',
NAME: 'Namn',
SPRACHE: 'Språk',
FORM_PAUSED: 'Formulär pausat',
// Redigera Fält Modal
EDIT_FIELD: 'Redigera detta fält',
SAVE_FIELD: 'Spara',
ON: 'PÅ',
AUS: 'AV',
REQUIRED_FIELD: 'Obligatoriskt',
LOGIC_JUMP: 'Logiskt Hopp',
SHOW_BUTTONS: 'Ytterligare Knappar',
SAVE_START_PAGE: 'Spara',
// Admin-vy
ARE_YOU_SURE: "Är du ABSOLUT säker?",
READ_WARNING: 'Oförväntade dåliga saker kommer hända om du inte läser detta!',
DELETE_WARNING1: 'Denna handling kan INTE göras ogjord. Den kommer att permanent radera "',
DELETE_WARNING2: '"Formuläret och alla associerade inskick.',
DELETE_CONFIRM: 'Vänligen skriv in namnet av formuläret för att bekräfta',
I_UNDERSTAND: "Jag förstår konsekvenserna, radera detta formulär.",
DELETE_FORM_SM: 'Radera',
DELETE_FORM_MD: 'Radera Formulär',
DELETE: 'Radera',
FORM: 'Formulär',
VIEW: 'Vy',
LIVE: 'Live',
PREVIEW: 'Förhandsvy',
COPY: 'Kopiera',
COPY_AND_PASTE: 'Kopiera och Klistra in detta för att lägga till din TellForm till din hemsida.',
CHANGE_WIDTH_AND_HEIGHT: 'Ändra bredd- och höjdvärden för att det ska passa dig bäst',
POWERED_BY: 'Genererad av',
TELLFORM_URL: "Din TellForm är permanent på denna URL",
// Redigera Form-vy
DISABLED: 'Avaktiverat',
JA: 'JA',
NO: 'NEJ',
ADD_LOGIC_JUMP: 'Lägg till Logic Jump',
ADD_FIELD_LG: 'Klicka för att Lägga Till Nytt Fält',
ADD_FIELD_MD: 'Lägg Till Nytt Fält',
ADD_FIELD_SM: 'Lägg Till Fält',
EDIT_START_PAGE: 'Redigera Startsida',
EDIT_END_PAGE: 'Redigera Slutsida',
WELCOME_SCREEN: 'Startsida',
END_SCREEN: 'Slutsida',
INTRO_TITLE: 'Titel',
INTRO_PARAGRAPH: "Stycke",
INTRO_BTN: 'Startknapp',
TITLE: "Titel",
PARAGRAPH: "Stycke",
BTN_TEXT: 'Gå Tillbaka Knapp',
BUTTONS: 'Knappar',
BUTTON_TEXT: 'Text',
BUTTON_LINK: 'Länk',
ADD_BUTTON: 'Lägg Till Knapp',
PREVIEW_FIELD: 'Förhandsgranska Fråga',
QUESTION_TITLE: 'Titel',
QUESTION_DESCRIPTION: 'Beskrivning',
OPTIONS: 'Alternativ',
ADD_OPTION: 'Lägg Till Alternativ',
NUM_OF_STEPS: 'Antal Steg',
CLICK_FIELDS_FOOTER: 'Klicka på fälten för att lägga till dem här',
IF_THIS_FIELD: 'Om detta fält',
IS_EQUAL_TO: 'är lika med',
IS_NOT_EQUAL_TO: 'inte lika med',
IS_GREATER_THAN: 'är större än',
IS_GREATER_OR_EQUAL_THAN: 'är större eller lika med än',
IS_SMALLER_THAN: 'är mindre än',
IS_SMALLER_OR_EQUAL_THAN: 'är mindre eller lika med än',
CONTAINS: 'innehåller',
DOES_NOT_CONTAINS: 'inte innehåller',
ENDS_WITH: 'slutar med',
DOES_NOT_END_WITH: 'inte slutar med',
STARTS_WITH: 'börjar med',
DOES_NOT_START_WITH: 'inte börjar med',
THEN_JUMP_TO: 'hoppa då till',
// Redigera Inskicks-vy
TOTAL_VIEWS: 'totalt antal unika besök',
RESPONSES: 'svar',
COMPLETION_RATE: 'grad av fullföljande',
AVERAGE_TIME_TO_COMPLETE: 'snitt på tid för fullföljande',
DESKTOP_AND_LAPTOP: 'Datorer',
TABLETS: "Plattor",
PHONES: 'Telefoner',
OTHER: 'Andra',
UNIQUE_VISITS: 'Unika Besök',
FIELD_TITLE: 'Titel på fält',
FIELD_VIEWS: 'Vyer på fält',
FIELD_DROPOFF: 'Fullföljande på fält',
FIELD_RESPONSES: 'Svar på fält',
DELETE_SELECTED: 'Ausgewählte löschen',
EXPORT_TO_EXCEL: 'Exportera till Excel',
EXPORT_TO_CSV: 'Exportera till CSV',
EXPORT_TO_JSON: 'Exportera till JSON',
PERCENTAGE_COMPLETE: 'Procent fullföljt',
TIME_ELAPSED: 'Tid som gått',
DEVICE: 'Utrustning',
LOCATION: 'Ort',
IP_ADDRESS: 'IP-Adress',
DATE_SUBMITTED: 'Datum för inskick',
// Designvy
BACKGROUND_COLOR: 'Bakgrundsfärg',
DESIGN_HEADER: 'Ändra hur ditt Formulär ser ut',
QUESTION_TEXT_COLOR: 'Frågetextens färg',
ANSWER_TEXT_COLOR: 'Svarstextens färg',
BTN_BACKGROUND_COLOR: 'Knappens bakgrundsfärg',
BTN_TEXT_COLOR: 'Knappens textfärg',
// Delningsvy
EMBED_YOUR_FORM: 'Bädda in ditt Formulär',
SHARE_YOUR_FORM: 'Dela ditt Formulär',
// Admin-tab
CREATE_TAB: 'Skapa',
DESIGN_TAB: 'Designa',
CONFIGURE_TAB: 'Konfigurera',
ANALYZE_TAB: 'Analysera',
SHARE_TAB: 'Dela',
// Fälttyper
SHORT_TEXT: 'Korttext',
EMAIL: 'E-post',
MULTIPLE_CHOICE: 'Flervalsfråga',
DROPDOWN: 'Rullgardinslista',
DATE: 'Datum',
PARAGRAPH_T: "Stycke",
YES_NO: 'Ja / Nej',
LEGAL: "Juridiskt",
RATING: 'Betygssättning',
NUMBERS: 'Nummer',
SIGNATURE: "Signatur",
FILE_UPLOAD: 'Filuppladdning',
OPTION_SCALE: 'Alternativskala',
PAYMENT: "Betalning",
STATEMENT: 'Uttalande',
LINK: 'Länk',
// Förhandsgranskning Formulär
FORM_SUCCESS: 'Formulär framgångsrikt inskickat!',
REVIEW: 'Granska',
BACK_TO_FORM: 'Gå Tillbaka till Formulär',
EDIT_FORM: 'Redigera denna TellForm',
ADVANCEMENT: '{{done}} av {{total}} svarade',
CONTINUE_FORM: 'Fortsätt till Formulär',
REQUIRED: 'obligatorisk',
COMPLETING_NEEDED: '{{answers_not_completed}} svar kräver komplettering',
OPTIONAL: 'valfri',
ERROR_EMAIL_INVALID: 'Vänligen ange en giltig e-postadress',
ERROR_NOT_A_NUMBER: 'Vänligen ange endast giltiga nummer',
ERROR_URL_INVALID: 'Vänligen en giltig URL',
OK: 'OK',
ENTER: 'tryck ENTER',
NEWLINE: 'tryck SHIFT+ENTER för att skapa ny rad',
CONTINUE: 'Fortsätt',
LEGAL_ACCEPT: "Jag accepterar",
LEGAL_NO_ACCEPT: "Jag accepterar inte",
SUBMIT: 'Skicka',
UPLOAD_FILE: 'Ladda upp din Fil'
});
}]);

View file

@ -10,33 +10,13 @@ angular.module('forms').directive('editSubmissionsFormDirective', ['$rootScope',
myform: '=' myform: '='
}, },
controller: function($scope){ controller: function($scope){
$scope.table = { $scope.table = {
masterChecker: false, masterChecker: false,
rows: [] rows: []
}; };
$scope.deletionInProgress = false; var getSubmissions = function(){
$scope.waitingForDeletion = false;
//Waits until deletionInProgress is false before running getSubmissions
$scope.$watch("deletionInProgress",function(newVal, oldVal){
if(newVal === oldVal) return;
if(newVal === false && $scope.waitingForDeletion) {
$scope.getSubmissions();
$scope.waitingForDeletion = false;
}
});
$scope.handleSubmissionsRefresh = function(){
if(!$scope.deletionInProgress) {
$scope.getSubmissions();
} else {
$scope.waitingForDeletion = true;
}
};
$scope.getSubmissions = function(cb){
$http({ $http({
method: 'GET', method: 'GET',
url: '/forms/'+$scope.myform._id+'/submissions' url: '/forms/'+$scope.myform._id+'/submissions'
@ -56,19 +36,10 @@ angular.module('forms').directive('editSubmissionsFormDirective', ['$rootScope',
} }
$scope.table.rows = submissions; $scope.table.rows = submissions;
});
if(cb && typeof cb === 'function'){
cb();
}
}, function errorCallback(err){
console.error(err);
if(cb && typeof cb === 'function'){
cb(err);
}
});
}; };
$scope.getVisitors = function(){ var getVisitors = function(){
$http({ $http({
method: 'GET', method: 'GET',
url: '/forms/'+$scope.myform._id+'/visitors' url: '/forms/'+$scope.myform._id+'/visitors'
@ -81,23 +52,8 @@ angular.module('forms').directive('editSubmissionsFormDirective', ['$rootScope',
}); });
}; };
$scope.handleSubmissionsRefresh(); getSubmissions();
$scope.getVisitors(); getVisitors();
//Fetch submissions and visitor data every 1.67 min
var updateSubmissions = $interval($scope.handleSubmissionsRefresh, 100000);
var updateVisitors = $interval($scope.getVisitors, 1000000);
//Prevent $intervals from running after directive is destroyed
$scope.$on('$destroy', function() {
if (updateSubmissions) {
$interval.cancel($scope.updateSubmissions);
}
if (updateVisitors) {
$interval.cancel($scope.updateVisitors);
}
});
/* /*
** Analytics Functions ** Analytics Functions
@ -116,48 +72,14 @@ angular.module('forms').directive('editSubmissionsFormDirective', ['$rootScope',
return (totalTime/numSubmissions).toFixed(0); return (totalTime/numSubmissions).toFixed(0);
})(); })();
$scope.DeviceStatistics = (function(){ var updateFields = $interval(getSubmissions, 100000);
var newStatItem = function(){ var updateFields = $interval(getVisitors, 1000000);
return {
visits: 0,
responses: 0,
completion: 0,
average_time: 0,
total_time: 0
};
};
var stats = { $scope.$on('$destroy', function() {
desktop: newStatItem(), if (updateFields) {
tablet: newStatItem(), $interval.cancel($scope.updateFields);
phone: newStatItem(),
other: newStatItem()
};
if($scope.myform.analytics && $scope.myform.analytics.visitors) {
var visitors = $scope.myform.analytics.visitors;
for (var i = 0; i < visitors.length; i++) {
var visitor = visitors[i];
var deviceType = visitor.deviceType;
stats[deviceType].visits++;
if (visitor.isSubmitted) {
stats[deviceType].total_time = stats[deviceType].total_time + visitor.timeElapsed;
stats[deviceType].responses++;
}
if(stats[deviceType].visits) {
stats[deviceType].completion = 100*(stats[deviceType].responses / stats[deviceType].visits).toFixed(2);
}
if(stats[deviceType].responses){
stats[deviceType].average_time = (stats[deviceType].total_time / stats[deviceType].responses).toFixed(0);
}
}
} }
return stats; });
})();
/* /*
** Table Functions ** Table Functions
@ -187,24 +109,25 @@ angular.module('forms').directive('editSubmissionsFormDirective', ['$rootScope',
//Delete selected submissions of Form //Delete selected submissions of Form
$scope.deleteSelectedSubmissions = function(){ $scope.deleteSelectedSubmissions = function(){
$scope.deletionInProgress = true;
var delete_ids = _.chain($scope.table.rows).filter(function(row){ var delete_ids = _.chain($scope.table.rows).filter(function(row){
return !!row.selected; return !!row.selected;
}).pluck('_id').value(); }).pluck('_id').value();
return $http({ url: '/forms/'+$scope.myform._id+'/submissions', $http({ url: '/forms/'+$scope.myform._id+'/submissions',
method: 'DELETE', method: 'DELETE',
data: {deleted_submissions: delete_ids}, data: {deleted_submissions: delete_ids},
headers: {'Content-Type': 'application/json;charset=utf-8'} headers: {'Content-Type': 'application/json;charset=utf-8'}
}).success(function(data, status){ }).success(function(data, status){
$scope.deletionInProgress = true;
//Remove deleted ids from table //Remove deleted ids from table
$scope.table.rows = $scope.table.rows.filter(function(field){ var tmpArray = [];
return !field.selected; for(var i=0; i<$scope.table.rows.length; i++){
}); if(!$scope.table.rows[i].selected){
tmpArray.push($scope.table.rows[i]);
}
}
$scope.table.rows = tmpArray;
}) })
.error(function(err){ .error(function(err){
$scope.deletionInProgress = true;
console.error(err); console.error(err);
}); });
}; };

View file

@ -1,11 +1,10 @@
'use strict'; 'use strict';
//TODO: DAVID: URGENT: Make this a $resource that fetches valid field types from server //TODO: DAVID: URGENT: Make this a $resource that fetches valid field types from server
angular.module('forms').service('FormFields', [ '$rootScope', '$translate', 'Auth', angular.module('forms').service('FormFields', [ '$rootScope', '$translate', '$window',
function($rootScope, $translate, Auth) { function($rootScope, $translate, $window) {
$translate.use($rootScope.language);
var language = Auth.ensureHasCurrentUser().language; console.log($translate.instant('SHORT_TEXT'));
$translate.use(language);
this.types = [ this.types = [
{ {

View file

@ -126,7 +126,6 @@ div.form-fields {
border: 1px solid #000; border: 1px solid #000;
border: 1px solid rgba(0,0,0,.2); border: 1px solid rgba(0,0,0,.2);
margin-right: 7px; margin-right: 7px;
margin-top: 1px;
-webkit-border-radius: 3px; -webkit-border-radius: 3px;
-moz-border-radius: 3px; -moz-border-radius: 3px;
border-radius: 3px; border-radius: 3px;

View file

@ -57,10 +57,7 @@ angular.module('forms').config(['$stateProvider',
}); });
return deferred.promise; return deferred.promise;
}, }
formId: ['$stateParams', function ($stateParams) {
return $stateParams.formId;
}]
}, },
controller: 'AdminFormController' controller: 'AdminFormController'
}).state('viewForm.configure', { }).state('viewForm.configure', {

View file

@ -2,6 +2,6 @@
// Use Application configuration module to register a new module // Use Application configuration module to register a new module
ApplicationConfiguration.registerModule('forms', [ ApplicationConfiguration.registerModule('forms', [
'ngFileUpload', 'ui.date', 'ui.sortable', 'ngFileUpload', 'ui.router.tabs', 'ui.date', 'ui.sortable',
'angular-input-stars', 'users', 'ngclipboard' 'angular-input-stars', 'users', 'ngclipboard'
]);//, 'colorpicker.module' @TODO reactivate this module ]);//, 'colorpicker.module' @TODO reactivate this module

View file

@ -8,7 +8,6 @@ angular.module('forms').factory('GetForms', ['$resource', 'FORM_URL',
}, { }, {
'query' : { 'query' : {
method: 'GET', method: 'GET',
url: '/forms',
isArray: true isArray: true
}, },
'get' : { 'get' : {

View file

@ -57,7 +57,22 @@
_id: '525a8422f6d0f87f0e407a33' _id: '525a8422f6d0f87f0e407a33'
}; };
//Mock myForm Service var newFakeModal = function(){
var result = {
opened: true,
close: function( item ) {
//The user clicked OK on the modal dialog, call the stored confirm callback with the selected item
this.opened = false;
},
dismiss: function( type ) {
//The user clicked cancel on the modal dialog, call the stored cancel callback
this.opened = false;
}
};
return result;
};
//Mock Users Service
beforeEach(module(function($provide) { beforeEach(module(function($provide) {
$provide.service('myForm', function($q) { $provide.service('myForm', function($q) {
return sampleForm; return sampleForm;
@ -144,27 +159,6 @@
}); });
})); }));
var newFakeModal = function(){
var modal = {
opened: true,
close: function( item ) {
//The user clicked OK on the modal dialog, call the stored confirm callback with the selected item
this.opened = false;
},
dismiss: function( type ) {
//The user clicked cancel on the modal dialog, call the stored cancel callback
this.opened = false;
},
result: {
then: function (cb) {
if(cb && typeof cb === 'function'){
cb();
}
}
}
};
return modal;
};
//Mock $uibModal //Mock $uibModal
beforeEach(inject(function($uibModal) { beforeEach(inject(function($uibModal) {
@ -205,7 +199,7 @@
expect(scope.myform).toEqualData(sampleForm); expect(scope.myform).toEqualData(sampleForm);
}); });
it('$scope.removeCurrentForm() with valid form data should send a DELETE request with the id of form', inject(function($uibModal) { it('$scope.removeCurrentForm() with valid form data should send a DELETE request with the id of form', function() {
var controller = createAdminFormController(); var controller = createAdminFormController();
//Set $state transition //Set $state transition
@ -220,7 +214,7 @@
$httpBackend.flush(); $httpBackend.flush();
$state.ensureAllTransitionsHappened(); $state.ensureAllTransitionsHappened();
})); });
it('$scope.update() should send a PUT request with the id of form', function() { it('$scope.update() should send a PUT request with the id of form', function() {
var controller = createAdminFormController(); var controller = createAdminFormController();

View file

@ -86,6 +86,7 @@
}); });
})); }));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable // This allows us to inject a service but then attach it to a variable
// with the same name as the service. // with the same name as the service.
@ -105,13 +106,25 @@
// Initialize the Forms controller. // Initialize the Forms controller.
createListFormsController = function(){ createListFormsController = function(){
return $controller('ListFormsController', { return $controller('ListFormsController', { $scope: scope });
$scope: scope,
myForms: sampleFormList
});
}; };
})); }));
it('$scope.findAll() should query all User\'s Forms', inject(function() {
var controller = createListFormsController();
// Set GET response
$httpBackend.expectGET(/^(\/forms)$/).respond(200, sampleFormList);
// Run controller functionality
scope.findAll();
$httpBackend.flush();
// Test scope value
expect( scope.myforms ).toEqualData(sampleFormList);
}));
it('$scope.duplicateForm() should duplicate a Form', inject(function() { it('$scope.duplicateForm() should duplicate a Form', inject(function() {
var dupSampleForm = sampleFormList[2], var dupSampleForm = sampleFormList[2],
@ -122,6 +135,12 @@
var controller = createListFormsController(); var controller = createListFormsController();
// Set GET response
$httpBackend.expectGET(/^(\/forms)$/).respond(200, sampleFormList);
// Run controller functionality
scope.findAll();
$httpBackend.flush();
// Set GET response // Set GET response
$httpBackend.expect('POST', '/forms').respond(200, dupSampleForm); $httpBackend.expect('POST', '/forms').respond(200, dupSampleForm);
// Run controller functionality // Run controller functionality
@ -145,6 +164,13 @@
var controller = createListFormsController(); var controller = createListFormsController();
// Set GET response
$httpBackend.expectGET(/^(\/forms)$/).respond(200, sampleFormList);
// Run controller functionality
scope.findAll();
$httpBackend.flush();
// Set GET response // Set GET response
$httpBackend.expect('DELETE', /^(\/forms\/)([0-9a-fA-F]{24})$/).respond(200, delSampleForm); $httpBackend.expect('DELETE', /^(\/forms\/)([0-9a-fA-F]{24})$/).respond(200, delSampleForm);

View file

@ -2,7 +2,7 @@
(function() { (function() {
// Forms Controller Spec // Forms Controller Spec
describe('EditFormSubmissions Directive-Controller Tests', function() { describe('EditSubmissions Directive-Controller Tests', function() {
// Initialize global variables // Initialize global variables
var el, scope, controller, $httpBackend; var el, scope, controller, $httpBackend;
@ -10,25 +10,13 @@
firstName: 'Full', firstName: 'Full',
lastName: 'Name', lastName: 'Name',
email: 'test@test.com', email: 'test@test.com',
username: 'test1234', username: 'test@test.com',
password: 'password', password: 'password',
provider: 'local', provider: 'local',
roles: ['user'], roles: ['user'],
_id: 'ed873933b1f1dea0ce12fab9' _id: 'ed873933b1f1dea0ce12fab9'
}; };
var sampleVisitors = [{
socketId: '33b1f1dea0ce12fab9ed8739',
referrer: 'https://tellform.com/examples',
lastActiveField: 'ed873933b0ce121f1deafab9',
timeElapsed: 100000,
isSubmitted: true,
language: 'en',
ipAddr: '192.168.1.1',
deviceType: 'desktop',
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) FxiOS/1.0 Mobile/12F69 Safari/600.1.4'
}]
var sampleForm = { var sampleForm = {
title: 'Form Title', title: 'Form Title',
admin: 'ed873933b1f1dea0ce12fab9', admin: 'ed873933b1f1dea0ce12fab9',
@ -39,18 +27,7 @@
{fieldType:'checkbox', title:'hockey', fieldOptions: [], fieldValue: '', required: true, disabled: false, deletePreserved: false, _id: 'ed8317393deab0ce121ffab9'} {fieldType:'checkbox', title:'hockey', fieldOptions: [], fieldValue: '', required: true, disabled: false, deletePreserved: false, _id: 'ed8317393deab0ce121ffab9'}
], ],
analytics: { analytics: {
visitors: sampleVisitors, visitors: []
conversionRate: 80.5,
fields: [
{
dropoffViews: 0,
responses: 1,
totalViews: 1,
continueRate: 100,
dropoffRate: 0,
field: {fieldType:'textfield', title:'First Name', fieldOptions: [], fieldValue: '', required: true, disabled: false, deletePreserved: false, _id: 'ed873933b0ce121f1deafab9'}
}
]
}, },
submissions: [], submissions: [],
startPage: { startPage: {
@ -84,8 +61,7 @@
], ],
admin: sampleUser, admin: sampleUser,
form: sampleForm, form: sampleForm,
timeElapsed: 10.33, timeElapsed: 10.33
selected: false
}, },
{ {
form_fields: [ form_fields: [
@ -95,8 +71,7 @@
], ],
admin: sampleUser, admin: sampleUser,
form: sampleForm, form: sampleForm,
timeElapsed: 2.33, timeElapsed: 2.33
selected: false
}, },
{ {
form_fields: [ form_fields: [
@ -106,8 +81,7 @@
], ],
admin: sampleUser, admin: sampleUser,
form: sampleForm, form: sampleForm,
timeElapsed: 11.11, timeElapsed: 11.11
selected: false
}]; }];
// The $resource service augments the response object with methods for updating and deleting the resource. // The $resource service augments the response object with methods for updating and deleting the resource.
@ -144,12 +118,10 @@
$httpBackend.whenGET(/^(\/forms\/)([0-9a-fA-F]{24})$/).respond(200, sampleForm); $httpBackend.whenGET(/^(\/forms\/)([0-9a-fA-F]{24})$/).respond(200, sampleForm);
$httpBackend.whenGET('/forms').respond(200, sampleForm); $httpBackend.whenGET('/forms').respond(200, sampleForm);
$httpBackend.whenGET(/^(\/forms\/)([0-9a-fA-F]{24})$/).respond(200, sampleForm); $httpBackend.whenGET(/^(\/forms\/)([0-9a-fA-F]{24})$/).respond(200, sampleForm);
$httpBackend.whenGET(/^(\/forms\/)([0-9a-fA-F]{24})\/submissions$/).respond(200, sampleSubmissions); //Instantiate directive.
$httpBackend.whenGET(/^(\/forms\/)([0-9a-fA-F]{24})\/visitors$/).respond(200, sampleVisitors);
//Instantiate directive.
var tmp_scope = $rootScope.$new(); var tmp_scope = $rootScope.$new();
tmp_scope.myform = sampleForm; tmp_scope.myform = sampleForm;
tmp_scope.myform.submissions = sampleSubmissions;
tmp_scope.user = sampleUser; tmp_scope.user = sampleUser;
//gotacha: Controller and link functions will execute. //gotacha: Controller and link functions will execute.
@ -169,7 +141,6 @@
it('$scope.toggleAllCheckers should toggle all checkboxes in table', function(){ it('$scope.toggleAllCheckers should toggle all checkboxes in table', function(){
//Run Controller Logic to Test //Run Controller Logic to Test
scope.table.rows = sampleSubmissions;
scope.table.masterChecker = true; scope.table.masterChecker = true;
scope.toggleAllCheckers(); scope.toggleAllCheckers();
@ -180,7 +151,6 @@
}); });
it('$scope.isAtLeastOneChecked should return true when at least one checkbox is selected', function(){ it('$scope.isAtLeastOneChecked should return true when at least one checkbox is selected', function(){
scope.table.rows = sampleSubmissions;
scope.table.masterChecker = true; scope.table.masterChecker = true;
scope.toggleAllCheckers(); scope.toggleAllCheckers();
@ -191,22 +161,16 @@
}); });
it('$scope.deleteSelectedSubmissions should delete all submissions that are selected', function(){ it('$scope.deleteSelectedSubmissions should delete all submissions that are selected', function(){
$httpBackend.expect('GET', /^(\/forms\/)([0-9a-fA-F]{24})(\/submissions)$/).respond(200, sampleSubmissions);
scope.table.masterChecker = true; scope.table.masterChecker = true;
scope.getSubmissions(function(err){ scope.toggleAllCheckers();
scope.toggleAllCheckers();
$httpBackend.expect('DELETE', /^(\/forms\/)([0-9a-fA-F]{24})(\/submissions)$/).respond(200); $httpBackend.expect('DELETE', /^(\/forms\/)([0-9a-fA-F]{24})(\/submissions)$/).respond(200);
//Run Controller Logic to Test //Run Controller Logic to Test
scope.deleteSelectedSubmissions().then(function(){ scope.deleteSelectedSubmissions();
expect(scope.table.rows.length).toEqual(0);
});
expect(err).not.toBeDefined();
});
$httpBackend.flush(); $httpBackend.flush();
expect(scope.table.rows.length).toEqual(0);
}); });
}); });

View file

@ -62,52 +62,6 @@
beforeEach(module('module-templates')); beforeEach(module('module-templates'));
beforeEach(module('stateMock')); beforeEach(module('stateMock'));
//Mock FormFields Service
beforeEach(module(function($provide) {
$provide.service('FormFields', function() {
return {
types: [
{
name : 'textfield',
value : 'Short Text'
},
{
name : 'email',
value : 'Email'
}
]
};
});
}));
var newFakeModal = function(){
var modal = {
opened: true,
close: function( item ) {
//The user clicked OK on the modal dialog, call the stored confirm callback with the selected item
this.opened = false;
},
dismiss: function( type ) {
//The user clicked cancel on the modal dialog, call the stored cancel callback
this.opened = false;
},
result: {
then: function (cb) {
if(cb && typeof cb === 'function'){
cb();
}
}
}
};
return modal;
};
//Mock $uibModal
beforeEach(inject(function($uibModal) {
var modal = newFakeModal();
spyOn($uibModal, 'open').and.returnValue(modal);
}));
beforeEach(inject(function($compile, $controller, $rootScope, _$httpBackend_) { beforeEach(inject(function($compile, $controller, $rootScope, _$httpBackend_) {
//Instantiate directive. //Instantiate directive.
var tmp_scope = $rootScope.$new(); var tmp_scope = $rootScope.$new();
@ -143,12 +97,26 @@
scope.myform = _.cloneDeep(sampleForm); scope.myform = _.cloneDeep(sampleForm);
}); });
it('$scope.addNewField() should open the new field modal', function() { it('$scope.addNewField() should ADD a new field to $scope.myform.form_fields', function() {
//Run controller methods //Run controller methods
scope.addNewField('textfield'); scope.addNewField(true, 'textfield');
expect(scope.editFieldModal.opened).toBeTruthy(); var expectedFormField = {
title: 'Short Text2',
fieldType: 'textfield',
fieldValue: '',
required: true,
disabled: false,
deletePreserved: false,
logicJump: Object({ })
};
var actualFormField = _.cloneDeep(_.last(scope.myform.form_fields));
delete actualFormField._id;
expect(scope.myform.form_fields.length).toEqual(sampleForm.form_fields.length+1);
expect(actualFormField).toEqualData(expectedFormField);
}); });
it('$scope.deleteField() should DELETE a field to $scope.myform.form_fields', function() { it('$scope.deleteField() should DELETE a field to $scope.myform.form_fields', function() {

View file

@ -5,6 +5,7 @@
describe('FieldIcon Directive Tests', function() { describe('FieldIcon Directive Tests', function() {
// Initialize global variables // Initialize global variables
var scope, var scope,
FormFields,
faClasses = { faClasses = {
'textfield': 'fa fa-pencil-square-o', 'textfield': 'fa fa-pencil-square-o',
'dropdown': 'fa fa-th-list', 'dropdown': 'fa fa-th-list',
@ -27,68 +28,10 @@
// Load the main application module // Load the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName)); beforeEach(module(ApplicationConfiguration.applicationModuleName));
//Mock FormFields Service
var FormFields = {
types: [
{
name : 'textfield',
value : 'Short Text'
},
{
name : 'email',
value : 'Email'
},
{
name : 'radio',
value : 'Muliple Choice'
},
{
name : 'dropdown',
value : 'Dropdown'
},
{
name : 'date',
value : 'Date'
},
{
name : 'textarea',
value : 'Paragraph',
},
{
name : 'yes_no',
value : 'Yes/No',
},
{
name : 'legal',
value : 'Legal',
},
{
name : 'rating',
value : 'Rating',
},
{
name : 'link',
value : 'Link',
},
{
name : 'number',
value : 'Numbers',
},
{
name : 'statement',
value : 'Statement'
}
]
};
beforeEach(module(function($provide) {
$provide.service('FormFields', function() {
return FormFields;
});
}));
beforeEach(inject(function ($rootScope, _FormFields_) { beforeEach(inject(function ($rootScope, _FormFields_) {
scope = $rootScope.$new(); scope = $rootScope.$new();
})); FormFields = _FormFields_;
}));
it('should be able render all field-icon types', inject(function($compile) { it('should be able render all field-icon types', inject(function($compile) {
var currType, currClass; var currType, currClass;

View file

@ -5,63 +5,11 @@
describe('Field Directive Tests', function() { describe('Field Directive Tests', function() {
// Initialize global variables // Initialize global variables
var scope, var scope,
FormFields,
$templateCache, $templateCache,
$httpBackend, $httpBackend,
$compile; $compile;
var FormFields = {
types: [
{
name : 'textfield',
value : 'Short Text'
},
{
name : 'email',
value : 'Email'
},
{
name : 'radio',
value : 'Muliple Choice'
},
{
name : 'dropdown',
value : 'Dropdown'
},
{
name : 'date',
value : 'Date'
},
{
name : 'textarea',
value : 'Paragraph',
},
{
name : 'yes_no',
value : 'Yes/No',
},
{
name : 'legal',
value : 'Legal',
},
{
name : 'rating',
value : 'Rating',
},
{
name : 'link',
value : 'Link',
},
{
name : 'number',
value : 'Numbers',
},
{
name : 'statement',
value : 'Statement'
}
]
};
var sampleUser = { var sampleUser = {
firstName: 'Full', firstName: 'Full',
lastName: 'Name', lastName: 'Name',
@ -117,15 +65,9 @@
beforeEach(module('ngSanitize', 'ui.select')); beforeEach(module('ngSanitize', 'ui.select'));
//Mock FormFields Service
beforeEach(module(function($provide) {
$provide.service('FormFields', function() {
return FormFields;
});
}));
beforeEach(inject(function($rootScope, _FormFields_, _$compile_, _$httpBackend_) { beforeEach(inject(function($rootScope, _FormFields_, _$compile_, _$httpBackend_) {
scope = $rootScope.$new(); scope = $rootScope.$new();
FormFields = _FormFields_;
// Point global variables to injected services // Point global variables to injected services
$httpBackend = _$httpBackend_; $httpBackend = _$httpBackend_;
@ -134,7 +76,6 @@
$compile = _$compile_; $compile = _$compile_;
})); }));
it('should be able to render all field types in html', inject(function($rootScope) { it('should be able to render all field types in html', inject(function($rootScope) {
scope.fields = sampleFields; scope.fields = sampleFields;

View file

@ -4,73 +4,15 @@
// Forms Controller Spec // Forms Controller Spec
describe('onFinishRender Directive Tests', function() { describe('onFinishRender Directive Tests', function() {
// Initialize global variables // Initialize global variables
var scope; var scope,
FormFields;
var FormFields = {
types: [
{
name : 'textfield',
value : 'Short Text'
},
{
name : 'email',
value : 'Email'
},
{
name : 'radio',
value : 'Muliple Choice'
},
{
name : 'dropdown',
value : 'Dropdown'
},
{
name : 'date',
value : 'Date'
},
{
name : 'textarea',
value : 'Paragraph',
},
{
name : 'yes_no',
value : 'Yes/No',
},
{
name : 'legal',
value : 'Legal',
},
{
name : 'rating',
value : 'Rating',
},
{
name : 'link',
value : 'Link',
},
{
name : 'number',
value : 'Numbers',
},
{
name : 'statement',
value : 'Statement'
}
]
};
// Load the main application module // Load the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName)); beforeEach(module(ApplicationConfiguration.applicationModuleName));
//Mock FormFields Service beforeEach(inject(function ($rootScope, _FormFields_) {
beforeEach(module(function($provide) {
$provide.service('FormFields', function() {
return FormFields;
});
}));
beforeEach(inject(function ($rootScope) {
scope = $rootScope.$new(); scope = $rootScope.$new();
FormFields = _FormFields_;
spyOn($rootScope, '$broadcast'); spyOn($rootScope, '$broadcast');
})); }));

View file

@ -5,9 +5,9 @@ angular.module('users').config(['$translateProvider', function ($translateProvid
$translateProvider.translations('fr', { $translateProvider.translations('fr', {
ACCESS_DENIED_TEXT: 'Vouz nêtes pas autorisé à accéder à cette page.', ACCESS_DENIED_TEXT: 'Vouz nêtes pas autorisé à accéder à cette page.',
USERNAME_LABEL: 'Nom dutilisateur', USERNAME_LABEL: 'Nom dutilisateur',
PASSWORD_LABEL: 'Mot de passe', PASSWORD_LABEL: 'Mot de Passe',
CURRENT_PASSWORD_LABEL: 'Mot de passe actuel', CURRENT_PASSWORD_LABEL: 'Mot de passe actuel',
NEW_PASSWORD_LABEL: 'Nouveau mot de passe', NEW_PASSWORD_LABEL: 'Nouveau Mot de Passe',
VERIFY_PASSWORD_LABEL: 'Vérifier le mot de passe', VERIFY_PASSWORD_LABEL: 'Vérifier le mot de passe',
UPDATE_PASSWORD_LABEL: 'Mettre à jour le mot de passe', UPDATE_PASSWORD_LABEL: 'Mettre à jour le mot de passe',
FIRST_NAME_LABEL: 'Prénom', FIRST_NAME_LABEL: 'Prénom',
@ -15,37 +15,37 @@ angular.module('users').config(['$translateProvider', function ($translateProvid
LANGUAGE_LABEL: 'Langue', LANGUAGE_LABEL: 'Langue',
EMAIL_LABEL: 'Email', EMAIL_LABEL: 'Email',
UPDATE_PROFILE_BTN: 'Modifier le profil', UPDATE_PROFILE_BTN: 'Modifier le Profil',
PROFILE_SAVE_SUCCESS: 'Profil enregistré avec succès', PROFILE_SAVE_SUCCESS: 'Profil enregistré avec succès',
PROFILE_SAVE_ERROR: 'Erreur: impossible denregistrer votre profil.', PROFILE_SAVE_ERROR: 'Erreur: impossible denregistrer votre Profile.',
FORGOT_PASSWORD_LINK: 'Mot de passe oublié ?', FORGOT_PASSWORD_LINK: 'Mot de passe oublié ?',
REVERIFY_ACCOUNT_LINK: 'Re-envoyer un email de vérification', REVERIFY_ACCOUNT_LINK: 'Re-envoyez un email de vérification',
SIGNIN_BTN: 'Connexion', SIGNIN_BTN: 'Connexion',
SIGNUP_BTN: 'Créer un compte', SIGNUP_BTN: 'Créer un compte',
SAVE_PASSWORD_BTN: 'Enregistrer votre nouveau mot de passe', SAVE_PASSWORD_BTN: 'Enregistrer votre nouveau Mot de Passe',
SUCCESS_HEADER: 'Votre compte a été enregistré !', SUCCESS_HEADER: 'Votre Compte a été enregistré !',
SUCCESS_TEXT: 'Votre compte Tellform a été créé avec succès.', SUCCESS_TEXT: 'Votre compte Tellform a été crée avec succès.',
VERIFICATION_EMAIL_SENT: 'Un email de verification a été envoyé à', VERIFICATION_EMAIL_SENT: 'Un email de verification a été envoyer à',
NOT_ACTIVATED_YET: 'Mais votre compte n\'est pas activé', NOT_ACTIVATED_YET: 'Mais votre compte n\'est pas activé',
BEFORE_YOU_CONTINUE: 'Avant de continuer, vous devez valider votre adresse mail. Merci de vérifier votre boîte mail. Si vous ne lavez pas reçu dans les prochaines 24h, contactez-nous à ', BEFORE_YOU_CONTINUE: 'Avant de continuer, vous devez valider votre adresse mail. Merci de vérifier votre boite mail. Si vous ne lavez pas reçu dans les prochaines 24h, contactez-nous a ',
CHECK_YOUR_EMAIL: 'Vérifiez vos emails, et cliquez sur le lien de validation pour activer votre compte. Si vous avez une question contactez-nous à', CHECK_YOUR_EMAIL: 'Vérifiez vos emails, et cliquez sur le lien de validation pour activer votre compte. Si vous avez une question contactez-nous à',
PASSWORD_RESTORE_HEADER: 'Mot de passe perdu', PASSWORD_RESTORE_HEADER: 'Mot de passe perdu',
ENTER_YOUR_EMAIL: 'Entrer votre email', ENTER_YOUR_EMAIL: 'Entrer votre email',
SUBMIT_BTN: 'Enregistrer', SUBMIT_BTN: 'Enregistrer',
ASK_FOR_NEW_PASSWORD: 'Demander un nouveau mot de passe ', ASK_FOR_NEW_PASSWORD: 'Demander un nouveau mot de pass ',
PASSWORD_RESET_INVALID: 'Ce lien de réinitialisation de mot de passe a déjà expiré', PASSWORD_RESET_INVALID: 'Ce lien de réinitialisation de mot de passe a déjà expiré',
PASSWORD_RESET_SUCCESS: 'Mot de passe réinitialisé avec succès', PASSWORD_RESET_SUCCESS: 'Mot de passe réinitialisé avec succès',
PASSWORD_CHANGE_SUCCESS: 'Mot de passe enregistré avec succès', PASSWORD_CHANGE_SUCCESS: 'Mot de passe enregistré avec succès',
CONTINUE_TO_LOGIN: 'Aller à la page de connexion', CONTINUE_TO_LOGIN: 'Allez à la page de connexion',
VERIFY_SUCCESS: 'Votre compte est activé !', VERIFY_SUCCESS: 'Votre compte est activé !',
VERIFY_ERROR: 'Le lien de vérification est invalide ou a expiré', VERIFY_ERROR: 'Le lien de vérification est invalide ou à expiré',
ERROR: 'Erreur' ERROR: 'Erreur'
}); });

View file

@ -1,71 +0,0 @@
'use strict';
angular.module('users').config(['$translateProvider', function ($translateProvider) {
$translateProvider.translations('sv', {
ACCESS_DENIED_TEXT: 'Du behöver vara inloggad för att kunna besöka denna sida',
USERNAME_OR_EMAIL_LABEL: 'Användarnamn eller E-post',
USERNAME_LABEL: 'Användarnamn',
PASSWORD_LABEL: 'Lösenord',
CURRENT_PASSWORD_LABEL: 'Nuvarande Lösenord',
NEW_PASSWORD_LABEL: 'Nytt Lösenord',
VERIFY_PASSWORD_LABEL: 'Bekräfta Lösenord',
UPDATE_PASSWORD_LABEL: 'Uppdatera Lösenord',
FIRST_NAME_LABEL: 'Förnamn',
LAST_NAME_LABEL: 'Efternamn',
LANGUAGE_LABEL: 'Språk',
EMAIL_LABEL: 'E-post',
SIGNUP_ACCOUNT_LINK: 'Har du inte redan ett konto? Registrera dig här',
SIGN_IN_ACCOUNT_LINK: 'Har du redan ett konto? Logga in här',
SIGNUP_HEADER_TEXT: 'Registrera',
SIGNIN_HEADER_TEXT: 'Logga in',
SIGNUP_ERROR_TEXT: 'Kunde inte slutföra registrering på grund av fel',
ENTER_ACCOUNT_EMAIL: 'Ange e-postadress för ditt konto.',
RESEND_VERIFICATION_EMAIL: 'Skicka om E-post för Verifiering',
SAVE_CHANGES: 'Spara Ändringar',
CANCEL_BTN: 'Avbryt',
EDIT_PROFILE: 'Redigera din profil',
UPDATE_PROFILE_BTN: 'Uppdatera Profil',
PROFILE_SAVE_SUCCESS: 'Profil sparades framgångsrikt',
PROFILE_SAVE_ERROR: 'Kunde Inte Spara Din Profil.',
CONNECTED_SOCIAL_ACCOUNTS: 'Kopplade sociala konton',
CONNECT_OTHER_SOCIAL_ACCOUNTS: 'Koppla andra sociala konton',
FORGOT_PASSWORD_LINK: 'Glömt ditt lösenord?',
REVERIFY_ACCOUNT_LINK: 'Skicka om e-postmeddelande för verifiering',
SIGNIN_BTN: 'Logga in',
SIGNUP_BTN: 'Registrera',
SAVE_PASSWORD_BTN: 'Spara Lösenord',
SUCCESS_HEADER: 'Registrering Framgånsrik',
SUCCESS_TEXT: 'Du har framgångsrikt registrerat ett konto på TellForm.',
VERIFICATION_EMAIL_SENT: 'Ett Verifieringsmeddelande har blivit Skickat',
VERIFICATION_EMAIL_SENT_TO: 'Ett verifieringsmeddelande har blivit skickat till',
NOT_ACTIVATED_YET: 'Men ditt konto är ännu inte aktiverat',
BEFORE_YOU_CONTINUE: 'Innan du fortsätter, försäkra dig om att kolla din e-post för vår verifiering. Om du inte tar emot den inom 24 timmar så skicka oss ett meddelande på ',
CHECK_YOUR_EMAIL: 'Kolla din e-post och klicka på aktiveringslänken för att aktivera ditt konto. Om du har några frågor så skicka oss ett meddelande på ',
CONTINUE: 'Fortsätt',
PASSWORD_RESTORE_HEADER: 'Återställ ditt lösenord',
ENTER_YOUR_EMAIL: 'Ange e-postadressen till ditt konto.',
SUBMIT_BTN: 'Skicka',
ASK_FOR_NEW_PASSWORD: 'Fråga efter ny lösenordsåterställning',
PASSWORD_RESET_INVALID: 'Länken till återställning av lösenord är ogiltig',
PASSWORD_RESET_SUCCESS: 'Lösenordet återställdes framgångsrikt',
PASSWORD_CHANGE_SUCCESS: 'Lösenordet ändrades framgångsrikt',
RESET_PASSWORD: 'Återställ ditt lösenord',
CHANGE_PASSWORD: 'Ändra ditt lösenord',
CONTINUE_TO_LOGIN: 'Fortsätt till logga in-sidan',
VERIFY_SUCCESS: 'Kontot framgångsrikt aktiverat',
VERIFY_ERROR: 'Verifieringslänken är ogiltig eller har utgått',
ERROR: 'Fel'
});
}]);

View file

@ -8,23 +8,21 @@ angular.module('users').controller('AuthenticationController', ['$scope', '$loca
$scope.error = ''; $scope.error = '';
$scope.forms = {}; $scope.forms = {};
var statesToIgnore = ['', 'home', 'signin', 'resendVerifyEmail', 'verify', 'signup', 'signup-success', 'forgot', 'reset-invalid', 'reset', 'reset-success'];
$scope.signin = function() { $scope.signin = function() {
if(!$scope.forms.signinForm.$invalid){ if(!$scope.forms.signinForm.$invalid){
User.login($scope.credentials).then( User.login($scope.credentials).then(
function(response) { function(response) {
Auth.login(response); Auth.login(response);
$scope.user = $rootScope.user = Auth.ensureHasCurrentUser(); $scope.user = $rootScope.user = Auth.ensureHasCurrentUser(User);
if(statesToIgnore.indexOf($state.previous.state.name) === -1) { if($state.previous.name !== 'home' && $state.previous.name !== 'verify' && $state.previous.name !== '') {
$state.go($state.previous.state.name, $state.previous.params); $state.go($state.previous.name);
} else { } else {
$state.go('listForms'); $state.go('listForms');
} }
}, },
function(error) { function(error) {
$rootScope.user = Auth.ensureHasCurrentUser(); $rootScope.user = Auth.ensureHasCurrentUser(User);
$scope.user = $rootScope.user; $scope.user = $rootScope.user;
$scope.error = error; $scope.error = error;

View file

@ -1,7 +1,7 @@
'use strict'; 'use strict';
angular.module('users').factory('Auth', ['$window', 'User', angular.module('users').factory('Auth', ['$window',
function($window, User) { function($window) {
var userState = { var userState = {
isLoggedIn: false isLoggedIn: false
@ -16,13 +16,13 @@ angular.module('users').factory('Auth', ['$window', 'User',
// Note: we can't make the User a dependency of Auth // Note: we can't make the User a dependency of Auth
// because that would create a circular dependency // because that would create a circular dependency
// Auth <- $http <- $resource <- LoopBackResource <- User <- Auth // Auth <- $http <- $resource <- LoopBackResource <- User <- Auth
ensureHasCurrentUser: function() { ensureHasCurrentUser: function(User) {
if (service._currentUser && service._currentUser.username) { if (service._currentUser && service._currentUser.username) {
return service._currentUser; return service._currentUser;
} else if ($window.user){ } else if ($window.user){
service._currentUser = $window.user; service._currentUser = $window.user;
return service._currentUser; return service._currentUser;
} else { } else{
User.getCurrent().then(function(user) { User.getCurrent().then(function(user) {
// success // success
service._currentUser = user; service._currentUser = user;

View file

@ -0,0 +1,181 @@
'use strict';
(function() {
// Forms Controller Spec
describe('Authentication Controller Tests', function() {
// Initialize global variables
var AuthenticationController,
scope,
$httpBackend,
$stateParams,
$location,
$state;
var sampleUser = {
firstName: 'Full',
lastName: 'Name',
email: 'test@test.com',
username: 'test@test.com',
password: 'password',
provider: 'local',
roles: ['user'],
_id: 'ed873933b1f1dea0ce12fab9'
};
var sampleForm = {
title: 'Form Title',
admin: 'ed873933b1f1dea0ce12fab9',
language: 'english',
form_fields: [
{fieldType:'textfield', title:'First Name', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'nascar', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'hockey', fieldValue: '', deletePreserved: false}
],
_id: '525a8422f6d0f87f0e407a33'
};
var expectedForm = {
title: 'Form Title',
admin: 'ed873933b1f1dea0ce12fab9',
language: 'english',
form_fields: [
{fieldType:'textfield', title:'First Name', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'nascar', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'hockey', fieldValue: '', deletePreserved: false}
],
visible_form_fields: [
{fieldType:'textfield', title:'First Name', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'nascar', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'hockey', fieldValue: '', deletePreserved: false}
],
_id: '525a8422f6d0f87f0e407a33'
};
var sampleCredentials = {
username: sampleUser.username,
password: sampleUser.password,
};
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Load the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
beforeEach(module('stateMock'));
// Mock Users Service
beforeEach(module(function($provide) {
$provide.service('User', function($q) {
return {
getCurrent: function() {
var deferred = $q.defer();
deferred.resolve( JSON.stringify(sampleUser) );
return deferred.promise;
},
login: function(credentials) {
var deferred = $q.defer();
if( credentials.password === sampleUser.password && credentials.username === sampleUser.username){
deferred.resolve( JSON.stringify(sampleUser) );
}else {
deferred.resolve('Error: User could not be loggedin');
}
return deferred.promise;
},
logout: function() {
var deferred = $q.defer();
deferred.resolve(null);
return deferred.promise;
},
signup: function(credentials) {
var deferred = $q.defer();
if( credentials.password === sampleUser.password && credentials.username === sampleUser.username){
deferred.resolve( JSON.stringify(sampleUser) );
}else {
deferred.resolve('Error: User could not be signed up');
}
return deferred.promise;
}
};
});
}));
// Mock Authentication Service
beforeEach(module(function($provide) {
$provide.service('Auth', function() {
return {
ensureHasCurrentUser: function() {
return sampleUser;
},
isAuthenticated: function() {
return true;
},
getUserState: function() {
return true;
}
};
});
}));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function($controller, $rootScope, _$state_, _$location_, _$stateParams_, _$httpBackend_, CurrentForm, Forms) {
// Set a new global scope
scope = $rootScope.$new();
scope.abc = 'hello';
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
$state = _$state_;
// $httpBackend.whenGET(/\.html$/).respond('');
$httpBackend.whenGET('/users/me/').respond('');
// Initialize the Forms controller.
AuthenticationController = $controller('AuthenticationController', { $scope: scope });
}));
it('$scope.signin should sigin in user with valid credentials', inject(function(Auth) {
//Set $state transition
// $state.expectTransitionTo('listForms');
//Set POST response
// $httpBackend.expect('POST', '/auth/signin', sampleCredentials).respond(200, sampleUser);
scope.abc = 'sampleCredentials';
//Run Controller Logic to Test
scope.signin();
// $httpBackend.flush();
// Test scope value
// expect(Auth.ensureHasCurrentUser()).toEqualData(sampleUser);
}));
});
}());

View file

@ -5,14 +5,14 @@ var config = require('../config/config'),
exports.run = function(app, db, cb) { exports.run = function(app, db, cb) {
var User = mongoose.model('User'); var User = mongoose.model('User');
var email = config.admin.email || 'admin@admin.com'; var email = 'admin@admin.com' || config.admin.email;
var newUser = new User({ var newUser = new User({
firstName: 'Admin', firstName: 'Admin',
lastName: 'Account', lastName: 'Account',
email: email, email: email,
username: config.admin.username || 'root', username: 'root' || config.admin.username,
password: config.admin.password || 'root', password: 'root' || config.admin.password,
provider: 'local', provider: 'local',
roles: ['admin', 'user'] roles: ['admin', 'user']
}); });

View file

@ -5,7 +5,7 @@
*/ */
process.env.NODE_ENV = 'production'; process.env.NODE_ENV = 'production';
var config = require('../config/config'), var config = require('../config/config'),
mongoose = require('mongoose'), mongoose = require('mongoose'),
inquirer = require('inquirer'), inquirer = require('inquirer'),
envfile = require('envfile'), envfile = require('envfile'),

View file

@ -14,8 +14,7 @@ require('events').EventEmitter.prototype._maxListeners = 0;
var config = require('./config/config'), var config = require('./config/config'),
mongoose = require('mongoose'), mongoose = require('mongoose'),
chalk = require('chalk'), chalk = require('chalk');
nodemailer = require('nodemailer');
/** /**
* Main application entry file. * Main application entry file.
@ -34,22 +33,11 @@ mongoose.connection.on('error', function (err) {
process.exit(-1); process.exit(-1);
}); });
const smtpTransport = nodemailer.createTransport(config.mailer.options);
// verify connection configuration on startup
smtpTransport.verify(function(error, success) {
if (error) {
console.error(chalk.red('Your mail configuration is incorrect: ' + error));
// verify but to abort!
// process.exit(-1);
}
});
// Init the express application // Init the express application
var app = require('./config/express')(db); var app = require('./config/express')(db);
//Create admin account //Create admin account
if (process.env.CREATE_ADMIN === 'TRUE') { if (process.env.CREATE_ADMIN_ACCOUNT === 'TRUE') {
var create_admin = require('./scripts/create_admin'); var create_admin = require('./scripts/create_admin');
create_admin.run(app, db, function(err){ create_admin.run(app, db, function(err){