Compare commits

..

89 commits

Author SHA1 Message Date
Leopere d5c94ce67f
Update README.md 2019-08-22 01:06:07 -04:00
Leopere 6e32ace806
Commented out new sponsor links. 2019-08-22 01:00:01 -04:00
Leopere a6d61ebf35
More tidying up leaving some details for future netizens. 2019-08-22 00:55:03 -04:00
Leopere 98385954dc
Deprecation notice for the time being.
Unfortunately due to many blockers that arose due to time constraints of involved parties a fork ended up being the best possible solution.  Credit will be given to the original codebase and repository.
2019-07-11 18:20:56 -04:00
Leopere 4900d13a47
Fixed Discord Server URL
The old TellForm server was replaced with the OMF server.
2019-07-11 18:13:37 -04:00
Leopere 210c7544e7
Merge pull request #344 from wodka/simplify-docker
improve docker images, fix jsep and initial build
2019-07-03 16:43:59 -04:00
wodka a9e04b4894 add missing bower install 2019-07-03 22:13:28 +02:00
wodka d07063f636 fixes for admin creation 2019-07-03 09:47:52 +02:00
wodka 643954896b fix user creation 2019-07-01 16:13:21 +02:00
wodka 77cabf15e5 attach socket.io to current server if ports are equal 2019-07-01 11:49:27 +02:00
wodka b3bf791d3c improve docker images, fix jsep and initial build 2019-07-01 10:03:29 +02:00
Leopere c3153ed514
Merge pull request #338 from tellform/Leopere-discordmove-1
Going to update the chat to something I can manage.
2019-06-07 19:47:24 -04:00
Leopere e29742f83a
Going to update the chat to something I can manage.
I have no access to manage Gitter and it seems a slight refocus might not be terrible.
2019-06-07 19:36:57 -04:00
Arielle Baldwynn a24f90ce91 added example env 2019-04-29 19:28:21 -07:00
Arielle Baldwynn 4eae4de2ce added countable web productions as sponsor 2019-04-29 19:16:36 -07:00
Arielle Baldwynn 39c656c41e fixed nginx dockerfile 2019-04-29 19:09:25 -07:00
Arielle Baldwynn 15a6324a90 got npm install to work 2019-04-29 16:02:27 -07:00
Arielle Baldwynn 17b428b304 Merge branch 'master' of github.com:tellform/tellform into stable2.1 2019-04-29 14:15:52 -07:00
Arielle Baldwynn 81e66f0025
Update README.md 2019-02-19 10:27:56 -08:00
Arielle Baldwynn b1917c9fdd
Merge pull request #330 from mattiasaxell/master
fix Swedish translations
2019-02-02 13:01:51 -08:00
Mattias 6453716c99 fix translations 2019-01-31 10:15:21 +01:00
Arielle Baldwynn 639ba9fdb8
Merge pull request #328 from bokub/patch-2
Remove dead link from README
2019-01-09 16:31:30 -08:00
Boris K 1a9e847741
Remove dead link from README 2019-01-09 21:05:00 +01:00
Arielle Baldwynn 995e6aa41c
Merge pull request #316 from LoneRifle/patch-2
deleteSubmissions - remove spurious condition
2018-10-23 22:42:44 -07:00
Arielle Baldwynn d7f0cc8127
Merge pull request #317 from spkjess/master
update markdown
2018-10-23 22:42:27 -07:00
Jess Sze e8afc9e7e6 add registry 2018-10-20 17:17:29 +08:00
Jess Sze ad35ae9215 update markdown 2018-10-20 17:03:24 +08:00
LoneRifle 5bc0d623a5
deleteSubmissions - remove spurious condition
`FormSubmission.remove` should not use `admin` as a condition:
 - the field is not present in the schema or in any created submissions
 - the user is unlikely to be the admin of a submission 

Remove this field to facilitate deletes

Fixes #315
2018-10-20 16:33:12 +08:00
David Baldwynn 13d9bd9ece fixed bugs with authentication 2018-09-11 14:09:17 -07:00
David Baldwynn 19c85f9845 fixed css aligment for form multi choice questions 2018-09-11 16:46:59 -04:00
Arielle Baldwynn 188705b640
Merge pull request #301 from pshah123/master
Fix Issues from PR #299
2018-08-31 13:27:24 -07:00
David Baldwynn 386b6be968 got stable release to work 2018-08-31 15:56:49 -04:00
David Baldwynn d9ef557edd u 2018-08-31 15:26:13 -04:00
David Baldwynn 52a1ab2bff got form running and fixed swedish translations 2018-08-31 15:25:43 -04:00
David Baldwynn 80beec8ad2
Merge pull request #305 from drew23c/drew
stored the logos in docs/ folder and added the logos for tellform sponsors...
2018-07-09 12:34:35 -07:00
Andrew Caldwell 3b0dee9ea3 stored the logos in docs/ folder and added the logos for tellform backers in readme.md 2018-07-06 13:47:44 -04:00
Priansh Shah 01ac456f62 fix merge 2018-04-24 23:15:52 +03:00
Priansh Shah 9715088e86 Revert "fix styling on form"
This reverts commit 9a9c1ae02e.
2018-04-24 23:05:46 +03:00
Priansh Shah 0f2cf42ceb revert changelog 2018-04-24 23:05:40 +03:00
Priansh Shah 65fd117b04 revert changelog 2018-04-24 23:05:05 +03:00
Priansh Shah 985c3c1aae revert custom Earlybird changes to form 2018-04-24 23:04:16 +03:00
Priansh Shah 808439cf47 Revert "Merge branch 'master' into server"
This reverts commit 83ca05e64b, reversing
changes made to 78082f7152.
2018-04-24 23:03:36 +03:00
Priansh Shah eaab2ff339 Revert "disable signups"
This reverts commit ca875ed01d.
2018-04-24 23:03:15 +03:00
Priansh Shah f99049d155 Revert "fix jsep import, add fillin for HTTPS server, remove debug flag"
This reverts commit 78082f7152.
2018-04-24 23:01:58 +03:00
David Baldwynn 8c4e519fbe
Merge pull request #299 from earlybird/master
Add JSEP CDN
2018-04-24 09:26:39 -07:00
Priansh Shah 9a9c1ae02e fix styling on form 2018-04-10 00:35:12 +00:00
Priansh Shah 2835280ff3 fix mobile responsiveness 2018-04-09 21:41:37 +00:00
Priansh Shah 7afc7eef87 update changelog 2018-04-09 21:36:17 +00:00
Priansh Shah 45f8fe7a02 fix form styling 2018-04-09 21:34:26 +00:00
Priansh Shah 623cb865c2 fix readme 2018-04-09 20:35:09 +00:00
Priansh Shah d6e48544a4 Merge branch 'master' of https://github.com/earlybird/tellform 2018-04-09 20:31:10 +00:00
Priansh Shah ca875ed01d disable signups 2018-04-09 20:30:44 +00:00
Priansh Shah 33b0fc02c4
Merge pull request #1 from earlybird/server
fix jsep import, add fillin for HTTPS server, remove debug flag
2018-04-09 16:25:04 -04:00
Priansh Shah 83ca05e64b
Merge branch 'master' into server 2018-04-09 16:24:29 -04:00
Priansh Shah 78082f7152 fix jsep import, add fillin for HTTPS server, remove debug flag 2018-04-09 20:22:41 +00:00
Priansh Shah e2ff321ec8
add JSEP cdn 2018-04-09 05:47:04 -04:00
David Baldwynn 38b3618f8b
Merge pull request #291 from mattiasaxell/patch-4
Create swedish.js translation
2018-03-05 12:39:55 -08:00
David Baldwynn f5dc78b6d7
Merge pull request #292 from mattiasaxell/patch-5
Create swedish.js - Swedish translation
2018-03-03 16:18:06 -08:00
David Baldwynn f384f5fee4
Merge pull request #293 from mattiasaxell/patch-6
Create swedish.js first translation
2018-03-03 16:17:57 -08:00
David Baldwynn 3421c92eab
Merge pull request #290 from mattiasaxell/patch-2
Adding Swedish translation to config
2018-03-03 16:17:42 -08:00
David Baldwynn f47a8d41ae
Merge pull request #294 from mattiasaxell/patch-7
Create swedish.js - first Swedish translation
2018-03-03 16:17:29 -08:00
Mattias Axell 53fa777ce0
Create swedish.js first Swedish translation 2018-02-28 18:12:54 +01:00
Mattias Axell e725aa1ea3
Create swedish.js first translation 2018-02-28 17:22:21 +01:00
Mattias Axell c63e905c25
Create swedish.js - Swedish translation 2018-02-28 16:31:35 +01:00
Mattias Axell ee2c59805e
Create swedish.js translation 2018-02-28 16:28:34 +01:00
Mattias Axell a0092baf31
Update typo in Swedish translation 2018-02-28 15:55:06 +01:00
Mattias Axell b6f5c5f897
First translation to Swedish
Proposing first translation of TellForm into Swedish.
2018-02-28 15:52:24 +01:00
David Baldwynn 66765278d2
Merge pull request #285 from MaximePawlakFr/fixFrenchTranslations
Fix french translations in modules, form_modules and locales.
2018-02-14 19:07:22 -08:00
Maxime 1ace06555c Fix french translations in modules, form_modules and locales. 2018-02-14 17:28:19 +01:00
David Baldwynn 4086219189
Merge pull request #283 from theasp/master
Fix MAILER_STMP_SECURE
2018-01-29 16:13:30 -08:00
Andrew Phillips 7357756625 Fix MAILER_STMP_SECURE
This should resolve https://github.com/tellform/tellform/issues/281,
matching the description in the Configuration section of `README.md`.
This also corrects the case of `TRUE` in an example.
2018-01-25 13:31:04 -04:00
David Baldwynn ff24843e3a Merge branch 'master' of github.com:tellform/tellform 2017-11-21 13:36:34 -08:00
David Baldwynn 4447785a56 removed secure grunt task 2017-11-21 13:36:14 -08:00
David Baldwynn 341ce5a88f
Merge pull request #265 from felixcheruiyot/master
Fix wrong vendor.min.js file reference URL
2017-11-20 20:33:33 -08:00
FELIX CHERUIYOT ed662281cd
Merge pull request #1 from felixcheruiyot/felixcheruiyot-patch-1
Fix missing vendor file reference
2017-11-17 07:44:07 +03:00
FELIX CHERUIYOT 13c3263667
Fix missing vendor file reference
vendor.min.js not found
2017-11-17 07:43:21 +03:00
David Baldwynn 084a8005fd fixed form vendor files 2017-11-11 19:56:41 -08:00
David Baldwynn 24cffeee37 fixed problem with production assets 2017-11-08 11:31:46 -08:00
David Baldwynn d132133d67 Merge branch 'master' of github.com:tellform/tellform 2017-11-06 17:55:46 -05:00
David Baldwynn 1539846121 fixed google analytics 2017-11-06 17:55:43 -05:00
David Baldwynn ed815f68e5
Update README.md 2017-11-06 14:35:29 -08:00
David Baldwynn 552f4d8396
Update gitter.im links 2017-11-06 14:29:43 -08:00
David Baldwynn 7c3834dcae Merge branch 'master' of github.com:tellform/tellform 2017-11-06 14:12:37 -08:00
David Baldwynn 5b847b33ec moved grunt to dev dependencies 2017-11-06 14:10:27 -08:00
David Baldwynn 86f74ce85f
Merge pull request #257 from tellform/fixSetupScript
Fixed Setup Script
2017-11-06 13:58:20 -08:00
David Baldwynn 147effe028
Added buildpack for Heroku Deploy Button 2017-11-06 13:57:13 -08:00
David Baldwynn b29d5bad36 fixed admin setup script 2017-11-06 13:44:29 -08:00
David Baldwynn 53658da890 Merge branch 'master' of github.com:tellform/tellform 2017-11-05 16:28:29 -08:00
David Baldwynn 3dc51d9d2c fixed bug in core.routes.js 2017-11-05 19:23:01 -05:00
85 changed files with 8401 additions and 15185 deletions

View file

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

124
.env.example Normal file
View file

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

View file

@ -11,9 +11,5 @@ services:
addons:
code_climate:
repo_token: 6c3a1b81a09b2338d6f30913c1bcad115026689752cbb499a0a25061cda6fbcf
install:
- npm install phantomjs
- npm install -g grunt
- npm install
script:
- yarn run travis
after_script:
- grunt coverage

View file

@ -4,33 +4,16 @@
# Run:
# docker run -it tellform-prod
FROM phusion/baseimage:0.9.19
MAINTAINER David Baldwynn <team@tellform.com>
FROM node:10-alpine
MAINTAINER Arielle Baldwynn <team@tellform.com>
# Install Utilities
RUN apt-get update -q \
&& apt-get install -yqq \
curl \
ant \
# Install some needed packages
RUN apk add --no-cache \
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/*
&& rm -rf /tmp/*
# Install NPM Global Libraries
RUN npm install --quiet -g grunt bower pm2 && npm cache clean
RUN npm install --quiet -g grunt bower pm2 && npm cache clean --force
WORKDIR /opt/tellform
RUN mkdir -p /opt/tellform/public/lib
@ -47,6 +30,39 @@ COPY ./gruntfile.js /opt/tellform/gruntfile.js
COPY ./server.js /opt/tellform/server.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
# and utilities docker container cache to not needing to rebuild
# and install node_modules/ everytime we build the docker, but only
@ -54,6 +70,8 @@ COPY ./scripts/create_admin.js /opt/tellform/scripts/create_admin.js
# Add npm package.json
COPY ./package.json /opt/tellform/package.json
RUN npm install --only=production --quiet
RUN bower install --allow-root
RUN grunt build
# Run TellForm server
CMD ["node", "server.js"]

View file

@ -10,56 +10,7 @@ TellForm Installation Instructions
## Local deployment with Docker
### 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)
Refer to [docker_files](https://github.com/tellform/docker_files).
## AWS AMI Deployment

122
README.md
View file

@ -1,17 +1,34 @@
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)
![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)
[![Gitter](https://badges.gitter.im/tellform/tellform.svg)](https://gitter.im/tellform/tellform?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
-->
> An *opensource alternative to TypeForm* that can create [stunning mobile-ready forms](https://tellform.com/examples) , surveys and questionnaires.
To Join the fork's community please follow this Discord button here.
![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)
-->
<!--
## Table of Contents
- [Features](#features)
- [How to Contribute](#how-to-contribute)
- [Quickstart](#quickstart)
@ -23,11 +40,8 @@ TellForm 2.1.0
- [Backers](#backers)
- [Contributors](#contributors)
- [Mentions on the Web](#mentions-on-the-web)
## Features
### Currently following features are implemented:
- Multi-Language Support
- 11 possible question types
- Editable start and end pages
@ -37,7 +51,6 @@ TellForm 2.1.0
- Embeddable Forms
- Forms as a Service API
- Deployable with Heroku and DockerHub
### On the Roadmap for v3.0.0
- Implement encryption for all form data
- Add Typeform API integration
@ -46,37 +59,27 @@ TellForm 2.1.0
- Add Stripe/Payment Form field
- Add Custom Background and Dropdown Field Images
- Add File Upload Form Field
## How to Contribute
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.
## Quickstart
Before you start, make sure you have
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)
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.
```bash
$ npm install
$ bower install
```
Setup environment.
```bash
$ grunt build
```
Create your user account
```bash
$ node ./scripts/setup.js
```
OR create your .env file
```
GOOGLE_ANALYTICS_ID=yourGAID
@ -84,92 +87,67 @@ PRERENDER_TOKEN=yourPrerender.ioToken
COVERALLS_REPO_TOKEN=yourCoveralls.ioToken
BASE_URL=localhost
DSN_KEY=yourPrivateRavenKey
# Mail config
MAILER_EMAIL_ID=user@domain.com
MAILER_PASSWORD=some-pass
MAILER_FROM=user@domain.com
# Use this for one of Nodemailer's pre-configured service providers
MAILER_SERVICE_PROVIDER=SendGrid
# Use these for a custom service provider
# Note: MAILER_SMTP_HOST will override MAILER_SERVICE_PROVIDER
MAILER_SMTP_HOST=smtp.domain.com
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___
#### To run the development version:
Set ```NODE_ENV=development``` in .env file
```$ grunt```
#### To run the production version:
Set ```NODE_ENV=production``` in .env file
```$ 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)
## Deploying with Docker
To deploy with docker, first install docker [here](https://docs.docker.com/engine/installation/).
Then run these commands
```
$ docker run -p 27017:27017 -d --name some-mongo mongo
$ docker run -p 127.0.0.1:6379:6379 -d --name some-redis redis
$ 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
```
Then run follow these steps:
### Step 1: Clone the repo
`$ 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.
Important: You need to fill out all of the ENV variables in the "Mail Settings" section or your TellForm instance won't work.
If you want to have https, make sure to change 'TLS_FLAVOR'
### Step 3: Start your TellForm instance
`docker-compose up -d`
TellForm should now be accessible on http://localhost
## Testing Your Application
You can run the full test suite included with TellForm with the test task:
```
$ 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/).
To execute only the server tests, run the test:server task:
```
$ grunt test:server
```
And to run only the client tests, run the test:client task:
```
$ 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.
To calculate your total test coverage with Istanbul, run the coverage task
```bash
$ grunt coverage
```
To calculate your server-side test coverage with Istanbul, run the coverage task
```bash
$ grunt coverage:server
```
To calculate your client-side test coverage with Istanbul, run the coverage task
```bash
$ grunt coverage:client
```
## 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`.
| 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 |
@ -198,42 +176,24 @@ 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 |
| 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 |
## Where to get help
[Gitter Chat](https://gitter.im/tellform/tellform)
[Gitter Chat](https://gitter.im/tellform/Lobby)
[Official Twitter](https://twitter.com/tellform_real)
-->
## 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).
<a href="https://m.do.co/c/a86fd8843e09" style="padding: 30px 0">
<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>
<a href="https://countable.ca" style="padding: 30px 0">
<img src="https://countable.ca/logo.cb446ab0.svg" height="30px">
</a> -->
## 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">
<img src="https://opencollective.com/proxy/images/?src=https%3A%2F%2Fd1ts43dypk8bqh.cloudfront.net%2Fv1%2Favatars%2F6fd61b2c-62b6-438a-9168-bab7ef1489b8" height= "64">
@ -252,8 +212,6 @@ Love our work and community? [Become a backer](https://opencollective.com/tellfo
<!-- ALL-CONTRIBUTORS-LIST:END -->
## 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/)
[BootCSS Expo](http://expo.bootcss.com/)

View file

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

View file

@ -9,8 +9,7 @@ var mongoose = require('mongoose'),
FormSubmission = mongoose.model('FormSubmission'),
config = require('../../config/config'),
diff = require('deep-diff'),
_ = require('lodash'),
helpers = require('./helpers.server.controller');
_ = require('lodash');
/**
* Delete a forms submissions
@ -20,7 +19,7 @@ exports.deleteSubmissions = function(req, res) {
var submission_id_list = req.body.deleted_submissions,
form = req.form;
FormSubmission.remove({ form: req.form, admin: req.user, _id: {$in: submission_id_list} }, function(err){
FormSubmission.remove({ form: req.form, _id: {$in: submission_id_list} }, function(err){
if(err){
res.status(400).send({
@ -105,15 +104,15 @@ exports.create = function(req, res) {
form.admin = req.user._id;
form.save(function(err, createdForm) {
form.save(function(err) {
debugger;
if (err) {
return res.status(500).send({
message: errorHandler.getErrorMessage(err)
});
}
createdForm = helpers.removeSensitiveModelData('private_form', createdForm);
return res.json(createdForm);
return res.json(form);
});
};
@ -124,19 +123,16 @@ exports.read = function(req, res) {
if(!req.user || (req.form.admin.id !== req.user.id) ){
readForRender(req, res);
} else {
if(!req.form){
var newForm = req.form.toJSON();
if (req.userId) {
if(req.form.admin._id+'' === req.userId+''){
return res.json(newForm);
}
return res.status(404).send({
message: 'Form Does Not Exist'
});
}
var newForm = req.form.toJSON();
if(newForm.admin._id === req.user._id){
return res.json(newForm);
}
newForm = helpers.removeSensitiveModelData('private_form', newForm);
return res.json(newForm);
}
};
@ -152,7 +148,9 @@ var readForRender = exports.readForRender = function(req, res) {
});
}
newForm = helpers.removeSensitiveModelData('public_form', newForm);
delete newForm.lastModified;
delete newForm.__v;
delete newForm.created;
if(newForm.startPage && !newForm.startPage.showStart){
delete newForm.startPage;
@ -168,8 +166,11 @@ exports.update = function(req, res) {
var form = req.form;
var updatedForm = req.body.form;
if(form.form_fields === undefined){
form.form_fields = [];
}
if(!form.analytics){
if(form.analytics === undefined){
form.analytics = {
visitors: [],
gaCode: ''
@ -191,6 +192,11 @@ exports.update = function(req, res) {
delete updatedForm.admin;
}
if(form.analytics === null){
form.analytics.visitors = [];
form.analytics.gaCode = '';
}
//Do this so we can create duplicate fields
var checkForValidId = new RegExp('^[0-9a-fA-F]{24}$');
for(var i=0; i < req.body.form.form_fields.length; i++){
@ -208,7 +214,6 @@ exports.update = function(req, res) {
message: errorHandler.getErrorMessage(err)
});
} else {
savedForm = helpers.removeSensitiveModelData('private_form', savedForm);
res.json(savedForm);
}
});
@ -250,8 +255,6 @@ exports.list = function(req, res) {
});
} else {
for(var i=0; i<forms.length; i++){
forms[i] = helpers.removeSensitiveModelData('private_form', forms[i]);
forms[i].numberOfResponses = 0;
if(forms[i].submissions){
forms[i].numberOfResponses = forms[i].submissions.length;
@ -272,7 +275,6 @@ exports.formByID = function(req, res, next, id) {
message: 'Form is invalid'
});
}
Form.findById(id)
.populate('admin')
.exec(function(err, form) {
@ -285,7 +287,12 @@ exports.formByID = function(req, res, next, id) {
}
else {
//Remove sensitive information from User object
req.form = helpers.removeSensitiveModelData('private_form', form);
var _form = form;
_form.admin.password = null;
_form.admin.salt = null;
_form.provider = null;
req.form = _form;
return next();
}
});
@ -313,7 +320,13 @@ exports.formByIDFast = function(req, res, next, id) {
}
else {
//Remove sensitive information from User object
req.form = helpers.removeSensitiveModelData('public_form', form);
var _form = form;
if(_form.admin){
_form.admin.password = null;
_form.admin.salt = null;
_form.provider = null;
}
req.form = _form;
return next();
}
});

View file

@ -1,44 +0,0 @@
module.exports = {
removeSensitiveModelData: function(type, object){
var privateFields = {
'public_form': ['__v', 'analytics.visitors', 'analytics.views', 'analytics.conversionRate', 'analytics.fields', 'lastModified', 'created'],
'private_form': ['__v'],
'public_user': ['passwordHash', 'password', 'provider', 'salt', 'lastModified', 'created', 'resetPasswordToken', 'resetPasswordExpires', 'token', 'apiKey', '__v'],
'private_user': ['passwordHash', 'password', 'provider', 'salt', 'resetPasswordToken', 'resetPasswordExpires', 'token', '__v']
}
function removeKeysFromDict(dict, keys){
for(var i=0; i<keys.length; i++){
var curr_key = keys[i];
if( dict.hasOwnProperty(curr_key) ){
delete dict[curr_key];
}
}
}
switch(type){
case 'private_form':
removeKeysFromDict(object, privateFields['private_form']);
if(object.admin){
removeKeysFromDict(object.admin, privateFields['private_user']);
}
break;
case 'public_form':
removeKeysFromDict(object, privateFields['public_form']);
if(object.admin){
removeKeysFromDict(object.admin, privateFields['public_user']);
}
break;
default:
if(privateFields.hasOwnProperty(type)){
removeKeysFromDict(object, privateFields[type]);
}
break;
}
return object;
}
}

View file

@ -12,8 +12,7 @@ var errorHandler = require('../errors.server.controller'),
fs = require('fs'),
i18n = require('i18n'),
async = require('async'),
pug = require('pug'),
helpers = require('../helpers.server.controller');
pug = require('pug');
var nev = require('email-verification')(mongoose);
@ -180,8 +179,6 @@ exports.signin = function(req, res, next) {
}
res.cookie('langCookie', user.language, { maxAge: 90000, httpOnly: true });
user = helpers.removeSensitiveModelData('private_user', user);
return res.json(user);
});
}
@ -201,12 +198,16 @@ exports.signout = function(req, res) {
/* Generate API Key for User */
exports.generateAPIKey = function(req, res) {
if (!req.isAuthenticated()){
return res.status(400).send({
message: 'User is not Authorized'
});
}
User.findById(req.user.id)
.exec( function(err, user) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
return res.status(400).send(err);
}
if (!user) {
@ -225,8 +226,12 @@ exports.generateAPIKey = function(req, res) {
}
var newUser = _user.toObject();
delete newUser.salt;
delete newUser.__v;
delete newUser.passwordHash;
delete newUser.provider;
return res.json({ id: newUser._id, apiKey: newUser.apiKey });
return res.json(newUser);
});
});

View file

@ -3,7 +3,36 @@
/**
* Module dependencies.
*/
var auth = require('../../../config/passport_helpers');
var _ = require('lodash'),
mongoose = require('mongoose'),
User = mongoose.model('User');
/**
* User middleware
*/
exports.userByID = function (req, res, next, id) {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({
message: 'User is invalid'
});
}
User.findOne({
_id: id
}).exec(function (err, user) {
if (err) {
return next(err);
} else if (!user) {
return res.status(404).send({
message: 'User does not exist'
});
}
req.profile = user;
next();
});
};
/**
* Require login routing middleware
*/
@ -16,3 +45,22 @@ exports.requiresLogin = function(req, res, next) {
return next();
}
};
/**
* User authorizations routing middleware
*/
exports.hasAuthorization = function(roles) {
var _this = this;
return function(req, res, next) {
_this.requiresLogin(req, res, function() {
if (_.intersection(req.user.roles, roles).length) {
return next();
} else {
return res.status(403).send({
message: 'User is not authorized'
});
}
});
};
};

View file

@ -84,6 +84,7 @@ exports.forgot = function(req, res) {
const fn = pug.compileFile(__dirname + "/../../views/templates/reset-password-email.server.view.pug");
res.locals['url'] = 'http://' + req.headers.host + '/auth/reset/' + token;
console.log(res.locals);
var renderedHtml = fn(res.locals);
done(null, renderedHtml, user);
},
@ -141,7 +142,7 @@ exports.validateResetToken = function(req, res) {
});
}
if (!user) {
return res.redirect(400, '/#!/password/reset/invalid');
return res.redirect('/#!/password/reset/invalid');
}
res.redirect('/#!/password/reset/' + req.params.token);
@ -186,7 +187,7 @@ exports.reset = function(req, res, next) {
done(null, savedUser);
});
} else {
done('invalid_reset_token', null);
done('Password reset token is invalid or has expired.', null);
}
});
},
@ -210,18 +211,12 @@ exports.reset = function(req, res, next) {
}
], function(err) {
if (err) {
if(err === 'invalid_reset_token'){
return res.status(400).send({
message: 'Password reset token is invalid or has expired.'
});
}
return res.status(500).send({
res.status(500).send({
message: err.message || err
});
}
res.json({
return res.json({
message: 'Successfully changed your password!'
});
});

View file

@ -5,8 +5,7 @@
*/
var _ = require('lodash'),
errorHandler = require('../errors.server.controller.js'),
mongoose = require('mongoose'),
helpers = require('../helpers.server.controller');
mongoose = require('mongoose');
/**
* Update user details
@ -15,9 +14,10 @@ exports.update = function(req, res) {
// Init Variables
var user = req.user;
// To improve security we remove the roles from the req.body object
// For security measurement we remove the roles from the req.body object
delete req.body.roles;
if (user) {
// Merge existing user
user = _.extend(user, req.body);
user.updated = Date.now();
@ -32,19 +32,29 @@ exports.update = function(req, res) {
if (err) {
res.status(500).send(loginErr);
} else {
user = helpers.removeSensitiveModelData('private_user', user);
res.json(user);
}
});
});
} else {
res.status(401).send({
message: 'User is not signed in'
});
}
};
/**
* Send User
*/
exports.getUser = function(req, res) {
var user = helpers.removeSensitiveModelData('private_user', req.user);
var _user = req.user;
delete _user.password;
delete _user.salt;
delete _user.provider;
delete _user.__v;
return res.json(user);
res.json(req.user || null);
res.end();
};

View file

@ -101,17 +101,12 @@ var FormSchema = new Schema({
visitors: [VisitorDataSchema]
},
form_fields: {
type: [FieldSchema],
default: []
},
submissions: {
type: [{
form_fields: [FieldSchema],
submissions: [{
type: Schema.Types.ObjectId,
ref: 'FormSubmission'
}],
dfeault: []
},
admin: {
type: Schema.Types.ObjectId,
ref: 'User',
@ -158,7 +153,6 @@ var FormSchema = new Schema({
type: Boolean,
default: false
},
isLive: {
type: Boolean,
default: true
@ -294,6 +288,26 @@ FormSchema.plugin(timeStampPlugin, {
useVirtual: false
});
FormSchema.pre('save', function (next) {
switch(this.language){
case 'spanish':
this.language = 'es';
break;
case 'french':
this.language = 'fr';
break;
case 'italian':
this.language = 'it';
break;
case 'german':
this.language = 'de';
break;
default:
break;
}
next();
});
function getDeletedIndexes(needle, haystack){
var deletedIndexes = [];

View file

@ -0,0 +1,26 @@
'use strict';
const constants = require('../../libs/constants'),
config = require('../../../config/config');
module.exports = exports = function lastModifiedPlugin (schema, options) {
schema.add({
language: {
type: String,
enum: constants.languageTypes,
default: config.defaultLanguage,
required: options.required || 'Must be a valid language'
}
});
schema.pre('save', function (next) {
var currWord = this.language;
//English is the default backup language
this.language = 'en';
if(constants.wordToLangCode.has(currWord)){
this.language = constants.wordToLangCode[currWord];
}
next();
});
};

View file

@ -9,19 +9,29 @@ var mongoose = require('mongoose'),
config = require('../../config/config'),
timeStampPlugin = require('../libs/timestamp.server.plugin'),
path = require('path'),
querystring = require('querystring'),
nodemailer = require('nodemailer');
querystring = require('querystring');
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);
/**
* A Validation function for local strategy properties
*/
var validateLocalStrategyProperty = function(property) {
var propHasLength;
if (property) {
propHasLength = !!property.length;
} else {
console.log('Mail server is ready to take our messages');
propHasLength = false;
}
});
return ((this.provider !== 'local' && !this.updated) || propHasLength);
};
/**
* A Validation function for username
*/
var validateUsername = function(username) {
return (username.match(/^[a-zA-Z0-9.-_]+$/) !== null);
};
/**
* User Schema
@ -63,6 +73,8 @@ var UserSchema = new Schema({
type: String,
default: 'local'
},
providerData: {},
additionalProvidersData: {},
roles: {
type: [{
type: String,
@ -99,6 +111,10 @@ var UserSchema = new Schema({
}
});
UserSchema.virtual('displayName').get(function () {
return this.firstName + ' ' + this.lastName;
});
UserSchema.plugin(timeStampPlugin, {
createdPath: 'created',
modifiedPath: 'lastModified',

View file

@ -12,7 +12,6 @@ module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
// Setting up the users profile api
app.route('/users/password').post(users.requiresLogin, users.changePassword);
app.route('/users/me').get(auth.isAuthenticatedOrApiKey, users.getUser);
app.route('/users').put(auth.isAuthenticatedOrApiKey, users.update);
@ -20,7 +19,8 @@ module.exports = function(app) {
app.route('/auth/verify/:token').get(users.validateVerificationToken);
app.route('/auth/verify').post(users.resendVerificationEmail);
// Setting up the password reset api
// Setting up the users password api
app.route('/users/password').post(users.requiresLogin, users.changePassword);
app.route('/auth/forgot').post(users.forgot);
app.route('/auth/reset/:token').get(users.validateResetToken);
app.route('/auth/reset/:token').post(users.reset);
@ -33,4 +33,7 @@ module.exports = function(app) {
app.route('/auth/signout').get(users.signout);
app.route('/auth/genkey').get(users.requiresLogin, users.generateAPIKey);
// Finish by binding the user middleware
app.param('userId', users.userByID);
};

View file

@ -69,6 +69,7 @@ describe('Form Routes Unit tests', function() {
.send({form: myForm})
.expect(401)
.end(function(FormSaveErr, FormSaveRes) {
console.log(FormSaveRes.text);
// Call the assertion callback
done(FormSaveErr);
});

View file

@ -17,6 +17,7 @@ var exampleDemo = {
address: '880-9650 Velit. St.',
city: '',
dateOfBirth: '10',
displayName: 'Test User',
email: 'polydaic@gmail.com',
firstName: 'Test User',
hin: '',
@ -81,6 +82,7 @@ describe('FormSubmission Model Unit Tests:', function() {
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test1@test.com'+Date.now(),
username: 'test1'+Date.now(),
password: 'password',

View file

@ -6,23 +6,24 @@ var should = require('should'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
config = require('../../config/config'),
tmpUser = mongoose.model(config.tempUserCollection),
async = require('async');
tmpUser = mongoose.model(config.tempUserCollection);
/**
* Globals
*/
var credentials, _User, userSession;
var credentials, _User, activateToken, userSession;
/**
* Form routes tests
*/
describe('User CRUD tests', function() {
before(function() {
this.timeout(30000);
beforeEach(function() {
// Create user credentials
credentials = {
email: 'test099@test.com',
username: 'test099',
email: 'test732@test.com',
username: 'test732',
password: 'password3223'
};
@ -30,424 +31,77 @@ describe('User CRUD tests', function() {
_User = {
email: credentials.email,
username: credentials.username,
password: credentials.password,
firstName: 'John',
lastName: 'Smith'
password: credentials.password
};
//Initialize Session
userSession = Session(app);
});
describe(' > Create, Verify and Activate a User > ', function() {
this.timeout(10000);
it('should be able to create and activate a User', function(done) {
async.waterfall([
function(callback) {
it(' > Create, Verify and Activate a User > ', function() {
it('should be able to create a temporary (non-activated) User', function(done) {
userSession.post('/auth/signup')
.send(_User)
.expect(200)
.end(function(err) {
callback(err)
});
},
function(callback) {
tmpUser.findOne({username: _User.username})
.lean()
.exec(function (err, user) {
.end(function(FormSaveErr) {
// Handle error
should.not.exist(FormSaveErr);
tmpUser.findOne({username: _User.username}, function (err, user) {
should.not.exist(err);
should.exist(user);
_User.username.should.equal(user.username);
_User.firstName.should.equal(user.firstName);
_User.lastName.should.equal(user.lastName);
callback(err, user.GENERATED_VERIFYING_URL);
});
},
function(activateToken, callback) {
userSession.get('/auth/verify/' + activateToken)
activateToken = user.GENERATED_VERIFYING_URL;
userSession.get('/auth/verify/'+activateToken)
.expect(200)
.end(function(err, res) {
(res.text).should.equal('User successfully verified');
callback(err);
});
},
function(callback) {
.end(function(VerifyErr, VerifyRes) {
// Handle error
if (VerifyErr) {
return done(VerifyErr);
}
(VerifyRes.text).should.equal('User successfully verified');
userSession.post('/auth/signin')
.send(credentials)
.expect('Content-Type', /json/)
.expect(200)
.end(function(err, res) {
(res.body.username).should.equal(credentials.username);
callback(err);
});
},
function(callback) {
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) {
return done(signinErr);
}
var user = signinRes.body;
(user.username).should.equal(credentials.username);
userSession.get('/auth/signout')
.expect(200)
.end(function(err, res) {
(res.text).should.equal('You have successfully logged out.');
callback(err);
});
},
function(callback) {
User.findOne({ username: _User.username })
.lean()
.exec(function(err, user){
should.exist(user);
callback(err);
});
.end(function(signoutErr, signoutRes) {
// Handle signout error
if (signoutErr) {
return done(signoutErr);
}
], function (err) {
done(err);
});
});
after(function(done){
User.remove().exec(done);
});
});
(signoutRes.text).should.equal('You have successfully logged out.');
describe(' > Reset Password > ', function(){
this.timeout(10000);
beforeEach(function(done){
var UserObj = new User(_User);
UserObj.save(function(err){
done(err);
done();
});
});
it('should be able to reset password of a created User with a valid passwordResetToken', function(done) {
var changedPassword = 'password1234';
var resetPasswordToken;
async.waterfall([
function(callback) {
userSession.post('/auth/forgot')
.send({ username: _User.username })
.expect(200)
.end(function(err) {
callback(err);
});
},
function(callback) {
User.findOne({ username: _User.username })
.lean()
.exec(function(err, user){
if(err){
callback(err);
}
callback(null, user.resetPasswordToken)
});
},
function(resetPasswordToken, callback) {
userSession.get('/auth/reset/' + resetPasswordToken)
.expect(302)
.end(function(err) {
callback(err, resetPasswordToken);
});
},
function(resetPasswordToken, callback) {
userSession.post('/auth/reset/' + resetPasswordToken)
.send({
newPassword: changedPassword,
verifyPassword: changedPassword
})
.expect(200)
.end(function(err, res) {
callback(err, resetPasswordToken);
});
},
function(resetPasswordToken, callback) {
User.findOne({ username: _User.username })
.exec(function(err, user){
should.exist(user);
user.authenticate(changedPassword).should.be.true();
should.not.exist(user.resetPasswordToken);
callback(err);
});
}
], function (err, result) {
credentials.password = changedPassword;
done(err);
});
});
it('should be not able to reset password of a created User with a invalid passwordResetToken', function(done) {
var changedPassword = 'password4321';
var resetPasswordToken = 'thisIsNotAValidToken';
async.waterfall([
function(callback) {
userSession.post('/auth/forgot')
.send({ username: credentials.username })
.expect(200)
.end(function(err, res) {
callback(err);
});
},
function(callback) {
userSession.get('/auth/reset/' + resetPasswordToken)
.expect(400)
.end(function(err) {
callback(err);
});
},
function(callback) {
userSession.post('/auth/reset/' + resetPasswordToken)
.send({
newPassword: changedPassword,
verifyPassword: changedPassword
})
.expect(400)
.end(function(err, res) {
callback(err);
});
},
function(callback) {
User.findOne({ username: _User.username })
.exec(function(err, user){
should.exist(user);
user.authenticate(changedPassword).should.be.false();
callback(err);
});
}
], function (err, result) {
done(err);
});
});
afterEach(function(done){
User.remove({ username: credentials.username }).exec(done);
});
});
describe(' > User Profile Changes > ', function(){
var profileSession = new Session(app);
this.timeout(10000);
beforeEach(function(done){
var UserObj = new User(_User);
UserObj.save(function(err, user){
done(err);
});
});
it('should be able to change password when logged in', function(done) {
var changedPassword = 'aVeryBadPassword';
async.waterfall([
function(callback) {
userSession.post('/auth/signin')
.send({
username: _User.username,
password: _User.password
})
.expect(200)
.end(function(err, res) {
callback(err);
});
},
function(callback) {
userSession.post('/users/password')
.send({
currentPassword: _User.password,
newPassword: changedPassword,
verifyPassword: changedPassword
})
.expect(200)
.end(function(err, res) {
callback(err);
});
},
function(callback) {
User.findOne({ username: _User.username })
.exec(function(err, user){
user.authenticate(changedPassword).should.be.true();
callback(err);
});
}
], function (err) {
done(err);
});
});
it('should be able to update user when logged in', function(done) {
var newUser = {};
newUser.firstName = 'goodnight';
newUser.lastName = 'everyone';
newUser.email = 'grcg@gcrc.com';
newUser.username = 'grcg';
async.waterfall([
function(callback) {
userSession.post('/auth/signin')
.send({
username: _User.username,
password: _User.password
})
.expect(200)
.end(function(err, res) {
callback(err);
});
},
function(callback) {
userSession.put('/users')
.send(newUser)
.expect(200)
.end(function(err, res) {
callback(err);
});
},
function(callback) {
User.findOne({ username: newUser.username })
.exec(function(err, user){
user.firstName.should.equal(newUser.firstName);
user.lastName.should.equal(newUser.lastName);
user.email.should.equal(newUser.email);
user.username.should.equal(newUser.username);
callback(err);
});
}
], function (err) {
done(err);
});
});
it('should be able to fetch user when logged in', function(done) {
async.waterfall([
function(callback) {
userSession.post('/auth/signin')
.send({
username: _User.username,
password: _User.password
})
.expect(200)
.end(function(err, res) {
callback(err);
});
},
function(callback) {
userSession.get('/users/me')
.expect(200)
.end(function(err, res) {
var user = res.body;
user.firstName.should.equal(_User.firstName);
user.lastName.should.equal(_User.lastName);
user.email.should.equal(_User.email);
user.username.should.equal(_User.username);
callback(err);
});
}
], function (err) {
done(err);
});
});
afterEach(function(done){
userSession.get('/auth/signout')
.end(function(err, res) {
User.remove().exec(done);
});
});
});
describe(' > User API > ', function(){
var apiKey;
this.timeout(10000);
before(function(done){
var UserObj = new User(_User);
UserObj.save(function(err, user){
done(err);
});
});
it('should be able to request API Key', function(done) {
async.waterfall([
function(callback) {
userSession.post('/auth/signin')
.send({
username: _User.username,
password: _User.password
})
.expect(200)
.end(function(err, res) {
callback(err);
});
},
function(callback) {
userSession.get('/auth/genkey')
.expect(200)
.end(function(err, res) {
apiKey = res.body.apiKey;
callback(err);
});
},
function(callback) {
userSession.get('/auth/signout')
.expect(200)
.end(function(err, res) {
callback(err);
});
},
function(callback) {
userSession.get('/users/me?apikey=' + apiKey)
.expect(200)
.end(function(err, res) {
var user = res.body;
user.firstName.should.equal(_User.firstName);
user.lastName.should.equal(_User.lastName);
user.email.should.equal(_User.email);
user.username.should.equal(_User.username);
callback(err);
});
},
], function (err) {
done(err);
});
});
it('should be able to update user with API key', function(done) {
var newUser = {};
newUser.firstName = 'goodnight';
newUser.lastName = 'everyone';
newUser.email = 'grcg@gcrc.com';
newUser.username = 'grcg';
async.waterfall([
function(callback) {
userSession.put('/users?apikey=' + apiKey)
.send(newUser)
.expect(200)
.end(function(err, res) {
callback(err);
});
},
function(callback) {
User.findOne({ username: newUser.username })
.exec(function(err, user){
user.firstName.should.equal(newUser.firstName);
user.lastName.should.equal(newUser.lastName);
user.email.should.equal(newUser.email);
user.username.should.equal(newUser.username);
callback(err);
});
}
], function (err) {
done(err);
});
});
after(function(done){
User.remove().exec(done);
});
});
after(function(done) {
afterEach(function(done) {
User.remove().exec(function () {
tmpUser.remove().exec(function(){
userSession.destroy();

View file

@ -59,6 +59,9 @@ html(lang='en', xmlns='http://www.w3.org/1999/xhtml')
script(type='text/javascript').
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')
link(rel='stylesheet', href='/static/lib/font-awesome/css/font-awesome.min.css')
link(rel='stylesheet', href='/static/lib/bootstrap/dist/css/bootstrap.min.css')
@ -82,7 +85,7 @@ html(lang='en', xmlns='http://www.w3.org/1999/xhtml')
//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')
//Application JavaScript Files

View file

@ -52,7 +52,7 @@ html(lang='en', xmlns='http://www.w3.org/1999/xhtml')
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='')

View file

@ -37,7 +37,7 @@
"angular-translate": "~2.11.0",
"ng-translate": "*",
"deep-diff": "^0.3.4",
"jsep": "^0.3.1",
"jsep": "0.3.1",
"ngclipboard": "^1.1.1",
"mobile-detect": "^1.3.3",
"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
host: process.env.MAILER_SMTP_HOST || '',
port: process.env.MAILER_SMTP_PORT || 465,
secure: process.env.MAILER_SMTP_SECURE || true,
secure: (process.env.MAILER_SMTP_SECURE === 'TRUE'),
auth: {
user: process.env.MAILER_EMAIL_ID || '',
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
host: process.env.MAILER_SMTP_HOST || '',
port: process.env.MAILER_SMTP_PORT || 465,
secure: process.env.MAILER_SMTP_SECURE || true,
secure: (process.env.MAILER_SMTP_SECURE === 'TRUE'),
auth: {
user: process.env.MAILER_EMAIL_ID || '',
pass: process.env.MAILER_PASSWORD || ''

View file

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

60
config/env/secure.js vendored Executable file
View file

@ -0,0 +1,60 @@
'use strict';
module.exports = {
baseUrl: 'https://forms.polydaic.com',
port: 8443,
db: {
uri: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || process.env.MONGODB_URI || 'mongodb://127.0.0.1/mean',
options: {
user: '',
pass: ''
}
},
log: {
// Can specify one of 'combined', 'common', 'dev', 'short', 'tiny'
format: 'combined',
// Stream defaults to process.stdout
// Uncomment to enable logging to a log on the file system
options: {
stream: 'access.log'
}
},
sessionCookie: {
path: '/',
httpOnly: false,
// If secure is set to true then it will cause the cookie to be set
// only when SSL-enabled (HTTPS) is used, and otherwise it won't
// set a cookie. 'true' is recommended yet it requires the above
// mentioned pre-requisite.
secure: true,
// Only set the maxAge to null if the cookie shouldn't be expired
// at all. The cookie will expunge when the browser is closed.
maxAge: 7200,
// To set the cookie in a specific domain uncomment the following
// setting:
domain: process.env.BASE_URL || 'localhost:3000'
},
assets: {
css: 'public/dist/application.min.css',
js: 'public/dist/application.min.js'
},
mailer: {
from: process.env.MAILER_FROM || '',
options: process.env.MAILER_SMTP_HOST ? { //Uses custom SMTP if MAILER_SMTP_HOST is set
host: process.env.MAILER_SMTP_HOST || '',
port: process.env.MAILER_SMTP_PORT || 587,
secure: (process.env.MAILER_SMTP_SECURE === 'TRUE'),
auth: {
user: process.env.MAILER_EMAIL_ID || '',
pass: process.env.MAILER_PASSWORD || ''
}
} : {
service: process.env.MAILER_SERVICE_PROVIDER || '',
auth: {
user: process.env.MAILER_EMAIL_ID || '',
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
host: process.env.MAILER_SMTP_HOST || '',
port: process.env.MAILER_SMTP_PORT || 587,
secure: process.env.MAILER_SMTP_SECURE || true,
secure: (process.env.MAILER_SMTP_SECURE === 'TRUE'),
auth: {
user: process.env.MAILER_EMAIL_ID || '',
pass: process.env.MAILER_PASSWORD || ''

View file

@ -186,6 +186,24 @@ module.exports = function(db) {
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
app.engine('server.view.pug', consolidate.pug);
@ -248,15 +266,6 @@ module.exports = function(db) {
app.use(passport.initialize());
app.use(passport.session());
//Setup i18n
i18n.configure({
locales: supportedLanguages,
directory: __dirname + '/locales',
defaultLocale: 'en',
cookie: 'userLang'
});
app.use(i18n.init);
//Visitor Language Detection
app.use(function(req, res, next) {
@ -324,6 +333,7 @@ module.exports = function(db) {
// Error page
res.status(500).render('500', {
__: i18n.__,
error: err.stack
});
});
@ -333,10 +343,27 @@ module.exports = function(db) {
client.captureError(new Error('Page Not Found'));
res.status(404).render('404', {
url: req.originalUrl,
error: 'Not Found'
error: 'Not Found',
__: i18n.__
});
});
if (process.env.NODE_ENV === 'secure') {
// Load SSL key and certificate
var privateKey = fs.readFileSync('./config/sslcerts/key.pem', 'utf8');
var certificate = fs.readFileSync('./config/sslcerts/cert.pem', 'utf8');
// Create HTTPS Server
var httpsServer = https.createServer({
key: privateKey,
cert: certificate
}, app);
// Return HTTPS server instance
return httpsServer;
}
app = configureSocketIO(app, db);
// Return Express server instance

View file

@ -2,20 +2,20 @@
"404_HEADER": "404 - Page non trouvée",
"500_HEADER": "500 - Erreur interne du serveur",
"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.",
"EMAIL_GREETING": "Bonjour!",
"VERIFICATION_EMAIL_PARAGRAPH_1": "Bienvenue sur TellForm! Voici un lien spécial pour activer votre nouveau compte:",
"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 !",
"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_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": "¡Active su nueva cuenta TellForm!",
"VERIFICATION_EMAIL_TEXT": "Verifique su cuenta haciendo clic en el siguiente enlace, o copiándolo y pegándolo en su navegador: $ {URL}",
"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_SUBJECT": "Activer votre nouveau compte 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}",
"EMAIL_SIGNATURE": "- L'équipe TellForm",
"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_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_SUBJECT": "Bienvenue dans %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_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_PARAGRAPH_2": "Si vous ne l'avez pas demandé, veuillez ignorer cet e-mail et votre mot de passe restera inchangé."
}

22
config/locales/sv.json Normal file
View file

@ -0,0 +1,22 @@
{
"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

@ -63,6 +63,7 @@ logger.setupFileLogger = function setupFileLogger() {
return false;
}
};
/**
@ -75,7 +76,7 @@ logger.getLogOptions = function getLogOptions() {
var _config = _.clone(config, true);
var configFileLogger = _config.log.fileLogger;
if (process.env.NODE_ENV !== 'test' && !_.has(_config, 'log.fileLogger.directoryPath') || !_.has(_config, 'log.fileLogger.fileName')) {
if (!_.has(_config, 'log.fileLogger.directoryPath') || !_.has(_config, 'log.fileLogger.fileName')) {
console.log('unable to find logging file configuration');
return false;
}
@ -96,6 +97,7 @@ logger.getLogOptions = function getLogOptions() {
handleExceptions: true,
humanReadableUnhandledException: true
};
};
/**

View file

@ -6,24 +6,14 @@ module.exports.isAuthenticatedOrApiKey = function isAuthenticated(req, res, next
if (req.isAuthenticated()) {
return next();
}
// Try authenticate with API KEY
if (req.headers.apikey || req.query.apikey || req.body.apikey) {
if(!req.body.apikey && req.headers.apikey){
req.body.apikey = req.headers.apikey;
} else if(!req.query.apikey && req.headers.apikey){
req.query.apikey = req.headers.apikey;
}
passport.authenticate('localapikey', function (err, user, info) {
if (err) {
return res.status(500).send('Internal Server Error with API. Sorry about that!');
}
if (err)
return res.sendStatus(500);
if (!user) {
console.log('no user for apikey');
if (!user)
return res.status(401).send(info.message || '');
}
req.login(user, function(loginErr) {
if (loginErr) return res.sendStatus(500);
@ -38,3 +28,23 @@ module.exports.isAuthenticatedOrApiKey = function isAuthenticated(req, res, next
}
};
module.exports.hasRole = function hasRole(roleRequired) {
if (!roleRequired) {
throw new Error('Required role needs to be set');
}
return function(req, res, next) {
return module.exports.isAuthenticated(req, res, function() {
if (req.user && req.user.roles && req.user.roles.indexOf(roleRequired) !== -1){
return next();
}
return res.sendStatus(403);
});
};
};
module.exports.hasAdminRole = function hasAdminRole() {
return module.exports.hasRole('admin');
};

View file

@ -9,7 +9,14 @@ var config = require('./config'),
// Define the Socket.io configuration method
module.exports = function (app, db) {
var server = http.createServer(app);
var io = socketio(config.socketPort, { transports: ['websocket', 'polling'] });
var io;
// 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){
var redis = require('socket.io-redis');

View file

@ -11,15 +11,13 @@ module.exports = function() {
return User.findOne({
'apiKey': apiKey
}, function(err, user) {
if (err) {
if (err)
return done(err);
}
if (!user){
if (!user)
return done(null, false, {
message: 'Unknown API Key'
});
}
return done(null, user);
});

55
docker-compose.yml Normal file
View file

@ -0,0 +1,55 @@
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.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

View file

@ -1,4 +1,4 @@
'use strict';
var bowerArray = ['public/lib/angular/angular.min.js',
'public/lib/angular-scroll/angular-scroll.min.js',
@ -123,7 +123,7 @@ module.exports = function(grunt) {
compress: true
},
files: {
'public/dist/vendor.min.js': bowerArray
'public/dist/form-vendor.min.js': bowerArray
}
}
},
@ -204,22 +204,62 @@ module.exports = function(grunt) {
singleRun: true
}
},
protractor: {
options: {
configFile: 'protractor.conf.js',
keepAlive: true,
noColor: false
},
e2e: {
options: {
args: {} // Target-specific arguments
}
}
},
mocha_istanbul: {
coverage: {
src: watchFiles.allTests, // a folder works nicely
options: {
mask: '*.test.js',
require: ['server.js']
}
},
coverageClient: {
src: watchFiles.clientTests, // specifying file patterns works as well
options: {
coverageFolder: 'coverageClient',
mask: '*.test.js',
require: ['server.js']
}
},
coverageServer: {
src: watchFiles.serverTests,
options: {
coverageFolder: 'coverageServer',
mask: '*.test.js',
require: ['server.js'],
reportFormats: ['html','lcovonly']
}
require: ['server.js']
}
},
lcovMerge: {
coveralls: {
src: watchFiles.allTests, // multiple folders also works
options: {
emitters: ['event'],
require: ['server.js'],
coverage: true, // this will make the grunt.event.on('coverage') event listener to be triggered
root: './lib', // define where the cover task should consider the root of libraries that are covered by tests
reportFormats: ['cobertura','lcovonly']
}
}
},
src: ['./coverageServer/*.info', './coverageClient/lcov-report/*.info']
istanbul_check_coverage: {
default: {
options: {
coverageFolder: 'coverage*', // will check both coverage folders and merge the coverage results
check: {
lines: 80,
statements: 80
}
}
}
},
html2js: {
options: {
@ -247,7 +287,7 @@ module.exports = function(grunt) {
options: {
module: 'TellForm.templates'
},
src: ['public/modules/**/views/**.html', 'public/modules/**/views/**/*.html', 'public/form_modules/forms/base/**/*.html'],
src: ['public/modules/**/views/**.html', 'public/modules/**/views/**/*.html', 'public/form_modules/forms/base/**/*.html', '!public/modules/forms/base/**/*.html'],
dest: 'public/dist/populate_template_cache.js'
}
},
@ -283,7 +323,9 @@ module.exports = function(grunt) {
});
// Code coverage tasks.
grunt.registerTask('coveralls', ['test:client', 'karma:unit', 'mocha_istanbul:coverageServer', 'lcovMerge']);
grunt.registerTask('coveralls', ['env:test','mocha_istanbul:coveralls']);
grunt.registerTask('coverage', ['env:test', 'mocha_istanbul:coverage']);
grunt.registerTask('coverage:client', ['env:test', 'mocha_istanbul:coverageClient']);
grunt.registerTask('coverage:server', ['env:test', 'mocha_istanbul:coverageServer']);
// Default task(s).
@ -293,11 +335,8 @@ module.exports = function(grunt) {
// Debug task.
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).
grunt.registerTask('lint', ['jshint', 'csslint']);
grunt.registerTask('lint', ['jshint', 'csslint', 'i18nlint:client', 'i18nlint:server']);
grunt.registerTask('lint:tests', ['jshint:allTests']);
// Build task(s).
@ -307,11 +346,9 @@ module.exports = function(grunt) {
grunt.registerTask('setup', ['execute']);
// Test task(s).
grunt.registerTask('test', ['test:server', 'test:client']);
grunt.registerTask('test', ['lint:tests', 'test:server', 'test:client']);
grunt.registerTask('test:server', ['lint:tests', 'env:test', 'mochaTest']);
grunt.registerTask('test:client', ['lint:tests', 'html2js:main', 'html2js:forms', 'env:test', 'karma:unit']);
grunt.registerTask('test:travis', ['coverage:server', 'test:client', 'lcovMerge']);
grunt.registerTask('testdebug', ['env:test', 'karma:debug']);
};

View file

@ -29,18 +29,9 @@ module.exports = function(config) {
'public/modules/**/views/**/*.html': ['ng-html2js'],
'public/modules/**/views/*.html': ['ng-html2js'],
'public/form_modules/forms/base/views/**/*.html': ['ng-html2js'],
'public/form_modules/forms/base/views/*.html': ['ng-html2js'],
'public/modules/*/*.js': ['coverage'],
'public/modules/*/*[!tests]*/*.js': ['coverage']
},
// configure coverage reporter
coverageReporter: {
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'lcov', subdir: 'report-lcov' },
],
dir : 'coverageClient/'
'public/form_modules/forms/base/views/*.html': ['ng-html2js']
//'public/modules/*/*.js': ['coverage'],
//'public/modules/*/*[!tests]*/*.js': ['coverage'],
},
ngHtml2JsPreprocessor: {

19
nginx/Dockerfile Normal file
View file

@ -0,0 +1,19 @@
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

116
nginx/conf/nginx.conf Normal file
View file

@ -0,0 +1,116 @@
# 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 %}
}
}

7
nginx/conf/tls.conf Normal file
View file

@ -0,0 +1,7 @@
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;

26
nginx/config.py Normal file
View file

@ -0,0 +1,26 @@
#!/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")

29
nginx/letsencrypt.py Normal file
View file

@ -0,0 +1,29 @@
#!/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)

25
nginx/start.py Normal file
View file

@ -0,0 +1,25 @@
#!/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;"])

12420
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -21,25 +21,25 @@
"generate": "all-contributors generate",
"start": "grunt",
"test": "grunt test",
"travis": "grunt test:travis",
"postinstall": "bower install --config.interactive=false; grunt build;",
"postinstall": "bower install --config.interactive=false",
"init": "node scripts/setup.js"
},
"dependencies": {
"async": "^1.4.2",
"body-parser": "~1.14.1",
"bower": "~1.6.5",
"body-parser": "^1.19.0",
"bower": "^1.8.8",
"chalk": "^1.1.3",
"compression": "~1.6.0",
"compression": "^1.7.4",
"connect": "^3.4.1",
"connect-mongo": "~0.8.2",
"connect-mongo": "^2.0.0",
"consolidate": "~0.14.5",
"cookie-parser": "~1.4.0",
"deep-diff": "^0.3.4",
"dotenv": "^2.0.0",
"email-verification": "github:tellform/node-email-verification",
"express": "~4.13.3",
"express-session": "~1.12.1",
"envfile": "^2.1.1",
"express": "^4.16.4",
"express-session": "^1.16.1",
"glob": "^7.0.3",
"grunt": "~0.4.1",
"grunt-concurrent": "~2.3.0",
@ -48,17 +48,17 @@
"grunt-contrib-jshint": "~1.0.0",
"grunt-contrib-uglify": "~0.11.0",
"grunt-env": "~0.4.1",
"grunt-html2js": "~0.3.5",
"grunt-html2js": "^0.6.0",
"grunt-ng-annotate": "~1.0.1",
"helmet": "3.5.0",
"helmet": "^3.16.0",
"i18n": "^0.8.3",
"jit-grunt": "^0.9.1",
"lodash": "^4.17.4",
"main-bower-files": "~2.9.0",
"lodash": "^4.17.11",
"main-bower-files": "^2.13.1",
"method-override": "~2.3.0",
"mkdirp": "^0.5.1",
"mongoose": "~4.4.19",
"morgan": "~1.8.1",
"morgan": "^1.9.1",
"nodemailer": "~4.0.0",
"passport": "~0.3.0",
"passport-anonymous": "^1.0.1",
@ -66,12 +66,13 @@
"passport-localapikey-update": "^0.5.0",
"path-exists": "^2.1.0",
"prerender-node": "^2.2.1",
"pug": "^2.0.0-rc.4",
"pug": "^2.0.3",
"random-js": "^1.0.8",
"raven": "^0.9.0",
"request": "^2.83.0",
"request": "^2.88.0",
"socket.io": "^1.4.6",
"socket.io-redis": "^1.0.0",
"swig": "~1.4.1",
"uuid-token-generator": "^0.5.0",
"winston": "^2.3.1"
},
@ -88,8 +89,8 @@
"grunt-contrib-uglify": "^0.11.1",
"grunt-contrib-watch": "~0.6.1",
"grunt-execute": "^0.2.2",
"grunt-i18nlint": "github:jwarby/grunt-i18nlint",
"grunt-karma": "~0.12.1",
"grunt-lcov-merge": "^1.2.3",
"grunt-mocha-istanbul": "^3.0.1",
"grunt-mocha-test": "~0.12.1",
"grunt-newer": "~1.1.1",
@ -97,7 +98,7 @@
"grunt-usemin": "^3.1.1",
"grunt-wiredep": "^3.0.1",
"istanbul": "^0.4.0",
"jasmine-core": "^2.6",
"jasmine-core": "^2.4.1",
"karma": "~0.13.14",
"karma-chrome-launcher": "~0.2.1",
"karma-coverage": "~0.5.3",
@ -110,7 +111,7 @@
"mocha": "^3.1.2",
"mocha-lcov-reporter": "^1.0.0",
"nightwatch": "^0.9.8",
"phantomjs-prebuilt": "^2.1.15",
"phantomjs": "^1.9.18",
"selenium-server": "^3.0.1",
"should": "~7.1.1",
"supertest": "~1.2.0",

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

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)',
OPTIONAL: 'facultatif',
ERROR_EMAIL_INVALID: 'Merci de rentrer une adresse mail valide',
ERROR_NOT_A_NUMBER: 'Merce de ne rentrer que des nombres',
ERROR_NOT_A_NUMBER: 'Merci de ne rentrer que des nombres',
ERROR_URL_INVALID: 'Merci de rentrer une url valide',
OK: 'OK',
ENTER: 'presser ENTRÉE',
ENTER: 'Appuyer sur ENTRÉE',
YES: 'Oui',
NO: 'Non',
NEWLINE: 'presser SHIFT+ENTER pour créer une nouvelle ligne',
NEWLINE: 'Appuyer sur SHIFT+ENTER pour créer une nouvelle ligne',
CONTINUE: 'Continuer',
LEGAL_ACCEPT: 'Jaccepte',
LEGAL_NO_ACCEPT: 'Je naccepte pas',
@ -35,11 +35,11 @@ angular.module('view-form').config(['$translateProvider', function ($translatePr
ERROR: 'Erreur',
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_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 sur "Public" dans le panneau "Configuration" du formulaire admin.',
   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.',
});
}]);

View file

@ -0,0 +1,45 @@
'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,6 +120,7 @@ div.form-fields {
vertical-align: top;
zoom: 1;
width: 16px;
margin-top: 1px;
padding: 0;
height: 17px;
font-size: 12px;

View file

@ -2,7 +2,7 @@
// Setting up route
angular.module('core').config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider, Authorization) {
function($stateProvider, $urlRouterProvider) {
// Redirect to home view when route not found
$urlRouterProvider.otherwise('/forms');
}
@ -48,7 +48,7 @@ angular.module(ApplicationConfiguration.applicationModuleName).run(['$rootScope'
var authenticator, permissions, user;
permissions = next && next.data && next.data.permissions ? next.data.permissions : null;
Auth.ensureHasCurrentUser(User);
Auth.ensureHasCurrentUser();
user = Auth.currentUser;
if(user){

View file

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

View file

@ -0,0 +1,16 @@
'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;
$scope.user = $rootScope.user = Auth.ensureHasCurrentUser(User);
$scope.user = $rootScope.user = Auth.ensureHasCurrentUser();
$scope.authentication = $rootScope.authentication = Auth;
@ -23,7 +23,7 @@ angular.module('core').controller('HeaderController', ['$rootScope', '$scope', '
var promise = User.logout();
promise.then(function() {
Auth.logout();
Auth.ensureHasCurrentUser(User);
Auth.ensureHasCurrentUser();
$scope.user = $rootScope.user = null;
$state.go('listForms');

View file

@ -153,7 +153,7 @@ angular.module('forms').config(['$translateProvider', function ($translateProvid
MULTIPLE_CHOICE: 'Multiple Choice',
DROPDOWN: 'Dropdown',
DATE: 'Date',
PARAGRAPH_FIELD: 'Paragraph',
PARAGRAPH_T: 'Paragraph',
YES_NO: 'Yes/No',
LEGAL: 'Legal',
RATING: 'Rating',

View file

@ -10,17 +10,17 @@ angular.module('forms').config(['$translateProvider', function ($translateProvid
PUBLIC: 'Public',
PRIVATE: "Privé",
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',
CANCEL: 'Annuler',
DISPLAY_START_PAGE: "Afficher la page de démarrage?",
DISPLAY_END_PAGE: "Afficher la page de fin personnalisée?",
DISPLAY_START_PAGE: "Afficher la page de démarrage ?",
DISPLAY_END_PAGE: "Afficher la page de fin personnalisée ?",
// Afficher les formulaires
CREATE_A_NEW_FORM: "Créer un nouveau formulaire",
CREATE_FORM: "Créer un formulaire",
CREATED_ON: 'Créé le',
MY_FORMS: 'Mes formes',
MY_FORMS: 'Mes formulaires',
NAME: "Nom",
LANGUE: 'Langue',
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",
CHANGE_WIDTH_AND_HEIGHT: "Changez les valeurs de largeur et de hauteur pour mieux vous convenir",
POWERED_BY: "Alimenté par",
TELLFORM_URL: "Votre TellForm est en permanence sur cette URL",
TELLFORM_URL: "Votre TellForm est disponible à cette URL",
// Modifier la vue de formulaire
DISABLED: "Désactivé",
@ -129,7 +129,7 @@ angular.module('forms').config(['$translateProvider', function ($translateProvid
// Vue de conception
BACKGROUND_COLOR: "Couleur d'arrière-plan",
DESIGN_HEADER: "Changez l'apparence de votre formulaire",
DESIGN_HEADER: "Changer l'apparence de votre formulaire",
QUESTION_TEXT_COLOR: "Couleur du texte de la question",
ANSWER_TEXT_COLOR: "Couleur du texte de la réponse",
BTN_BACKGROUND_COLOR: "Couleur d'arrière-plan du bouton",
@ -152,7 +152,7 @@ angular.module('forms').config(['$translateProvider', function ($translateProvid
MULTIPLE_CHOICE: 'Choix multiple',
DROPDOWN: 'Menu Déroulant',
DATE: 'Date',
PARAGRAPH_FIELD: "Paragraphe",
PARAGRAPH_T: "Paragraphe",
OUI_NON: 'Oui / Non',
LEGAL: 'Légal',
RATING: "Évaluation",

View file

@ -151,7 +151,7 @@ angular.module('forms').config(['$translateProvider', function ($translateProvid
MULTIPLE_CHOICE: 'Mehrfachauswahl',
DROPDOWN: 'Dropdown-Liste',
DATE: 'Datum',
PARAGRAPH_FIELD: "Absatz",
PARAGRAPH_T: "Absatz",
YES_NO: 'Ja / Nein',
LEGAL: "Rechtliche",
RATING: 'Bewertung',

View file

@ -152,7 +152,7 @@ angular.module('forms').config(['$translateProvider', function ($translateProvid
MULTIPLE_CHOICE: 'Scelta multipla',
DROPDOWN: 'Dropdown',
DATE: 'Data',
PARAGRAPH_FIELD: 'Paragrafo',
PARAGRAPH_T: 'Paragrafo',
YES_NO: 'Sì / no',
LEGAL: 'Legale',
RATING: 'Valutazione',

View file

@ -153,7 +153,7 @@ angular.module('forms').config(['$translateProvider', function ($translateProvid
MULTIPLE_CHOICE: 'Opciones múltiples',
DROPDOWN: 'Desplegable',
DATE: 'Fecha',
PARAGRAPH_FIELD: 'Párrafo',
PARAGRAPH_T: 'Párrafo',
YES_NO: 'Si/No',
LEGAL: 'Legal',
RATING: 'Puntaje',

View file

@ -0,0 +1,189 @@
'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

@ -30,7 +30,7 @@ angular.module('forms').service('FormFields', [ '$rootScope', '$translate', 'Aut
},
{
name : 'textarea',
value : $translate.instant('PARAGRAPH_FIELD'),
value : $translate.instant('PARAGRAPH'),
},
{
name : 'yes_no',

View file

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

View file

@ -5,9 +5,9 @@ angular.module('users').config(['$translateProvider', function ($translateProvid
$translateProvider.translations('fr', {
ACCESS_DENIED_TEXT: 'Vouz nêtes pas autorisé à accéder à cette page.',
USERNAME_LABEL: 'Nom dutilisateur',
PASSWORD_LABEL: 'Mot de Passe',
PASSWORD_LABEL: 'Mot de passe',
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',
UPDATE_PASSWORD_LABEL: 'Mettre à jour le mot de passe',
FIRST_NAME_LABEL: 'Prénom',
@ -15,37 +15,37 @@ angular.module('users').config(['$translateProvider', function ($translateProvid
LANGUAGE_LABEL: 'Langue',
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_ERROR: 'Erreur: impossible denregistrer votre Profile.',
PROFILE_SAVE_ERROR: 'Erreur: impossible denregistrer votre profil.',
FORGOT_PASSWORD_LINK: 'Mot de passe oublié ?',
REVERIFY_ACCOUNT_LINK: 'Re-envoyez un email de vérification',
REVERIFY_ACCOUNT_LINK: 'Re-envoyer un email de vérification',
SIGNIN_BTN: 'Connexion',
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_TEXT: 'Votre compte Tellform a été crée avec succès.',
VERIFICATION_EMAIL_SENT: 'Un email de verification a été envoyer à',
SUCCESS_HEADER: 'Votre compte a été enregistré !',
SUCCESS_TEXT: 'Votre compte Tellform a été créé avec succès.',
VERIFICATION_EMAIL_SENT: 'Un email de verification a été envoyé à',
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 boite mail. Si vous ne lavez pas reçu dans les prochaines 24h, contactez-nous a ',
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 à ',
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',
ENTER_YOUR_EMAIL: 'Entrer votre email',
SUBMIT_BTN: 'Enregistrer',
ASK_FOR_NEW_PASSWORD: 'Demander un nouveau mot de pass ',
ASK_FOR_NEW_PASSWORD: 'Demander un nouveau mot de passe ',
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_CHANGE_SUCCESS: 'Mot de passe enregistré avec succès',
CONTINUE_TO_LOGIN: 'Allez à la page de connexion',
CONTINUE_TO_LOGIN: 'Aller à la page de connexion',
VERIFY_SUCCESS: 'Votre compte est activé !',
VERIFY_ERROR: 'Le lien de vérification est invalide ou à expiré',
VERIFY_ERROR: 'Le lien de vérification est invalide ou a expiré',
ERROR: 'Erreur'
});

View file

@ -0,0 +1,71 @@
'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

@ -5,24 +5,25 @@ angular.module('users').config(['$stateProvider',
function($stateProvider) {
var checkLoggedin = function($q, $timeout, $state, User, Auth) {
var deferred = $q.defer();
if (Auth.currentUser && Auth.currentUser.email) {
return;
$timeout(deferred.resolve);
}
else {
return User.getCurrent().then(
function(user) {
Auth.login(user);
return;
Auth.currentUser = User.getCurrent(
function() {
Auth.login();
$timeout(deferred.resolve());
},
function() {
Auth.logout();
$timeout(deferred.reject());
$state.go('signin', {reload: true});
return;
});
}
return deferred.promise;
};
var checkSignupDisabled = function($window, $timeout, $q) {

View file

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

View file

@ -1,29 +0,0 @@
'use strict';
angular.module('users').controller('ChangePasswordController', ['$scope', '$rootScope', '$http', '$state', 'Users', 'Auth',
function($scope, $rootScope, $http, $state, Users, Auth) {
$scope.user = Auth.currentUser;
console.log($scope.user)
$scope.cancel = function(){
$scope.user = Auth.currentUser;
}
// Change user password
$scope.changeUserPassword = function() {
$scope.success = $scope.error = null;
$http.post('/users/password', $scope.passwordDetails).success(function(response) {
// If successful show success message and clear form
$scope.success = true;
$scope.error = null;
$scope.passwordDetails = null;
}).error(function(response) {
$scope.success = null;
$scope.error = response.message;
});
};
*/
}
]);

View file

@ -5,9 +5,41 @@ angular.module('users').controller('SettingsController', ['$scope', '$rootScope'
$scope.user = Auth.currentUser;
// Check if there are additional accounts
$scope.hasConnectedAdditionalSocialAccounts = function(provider) {
for (var i in $scope.user.additionalProvidersData) {
return true;
}
return false;
};
$scope.cancel = function(){
$scope.user = Auth.currentUser;
};
// Check if provider is already in use with current user
$scope.isConnectedSocialAccount = function(provider) {
return $scope.user.provider === provider || ($scope.user.additionalProvidersData && $scope.user.additionalProvidersData[provider]);
};
// Remove a user social account
$scope.removeUserSocialAccount = function(provider) {
$scope.success = $scope.error = null;
$http.delete('/users/accounts', {
params: {
provider: provider
}
}).success(function(response) {
// If successful show success message and clear form
$scope.success = true;
$scope.error = null;
$scope.user = response;
}).error(function(response) {
$scope.success = null;
$scope.error = response.message;
});
};
// Update a user profile
$scope.updateUserProfile = function(isValid) {
@ -19,7 +51,6 @@ angular.module('users').controller('SettingsController', ['$scope', '$rootScope'
$scope.success = true;
$scope.error = null;
$scope.user = response;
$scope.$apply();
}, function(response) {
$scope.success = null;
$scope.error = response.data.message;
@ -28,5 +59,21 @@ angular.module('users').controller('SettingsController', ['$scope', '$rootScope'
$scope.submitted = true;
}
};
// Change user password
$scope.changeUserPassword = function() {
$scope.success = $scope.error = null;
$http.post('/users/password', $scope.passwordDetails).success(function(response) {
// If successful show success message and clear form
$scope.success = true;
$scope.error = null;
$scope.passwordDetails = null;
}).error(function(response) {
$scope.success = null;
$scope.error = response.message;
});
};
}
]);

View file

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

View file

@ -1,181 +0,0 @@
'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('module-templates'));
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

@ -1,6 +1,6 @@
<header data-ng-include="'/static/modules/core/views/header.client.view.html'"></header>
<section class="row" data-ng-controller="ChangePasswordController">
<section class="row" data-ng-controller="SettingsController">
<h3 class="col-md-12 text-center">{{ 'CHANGE_PASSWORD' | translate }}</h3>
<div class="col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6">
<form data-ng-submit="changeUserPassword()" class="signin form-horizontal" autocomplete="off">

View file

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

View file

@ -3,21 +3,19 @@
* Module dependencies.
*/
require('dotenv').config({path: './.env'});
if(!process.env.NODE_ENV){
process.env.NODE_ENV = 'development';
}
//Don't check .env file if we are in travis-ci
if(!process.env.TRAVIS){
require('dotenv').config({path: './.env'});
}
require('events').EventEmitter.prototype._maxListeners = 0;
var config = require('./config/config'),
mongoose = require('mongoose'),
chalk = require('chalk');
chalk = require('chalk'),
nodemailer = require('nodemailer');
/**
* Main application entry file.
@ -36,11 +34,22 @@ mongoose.connection.on('error', function (err) {
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
var app = require('./config/express')(db);
//Create admin account
if (process.env.CREATE_ADMIN_ACCOUNT === 'TRUE') {
if (process.env.CREATE_ADMIN === 'TRUE') {
var create_admin = require('./scripts/create_admin');
create_admin.run(app, db, function(err){
@ -65,6 +74,9 @@ console.log('--');
console.log(chalk.green('Environment:\t\t\t' + process.env.NODE_ENV));
console.log(chalk.green('Port:\t\t\t\t' + config.port));
console.log(chalk.green('Database:\t\t\t' + config.db.uri));
if (process.env.NODE_ENV === 'secure') {
console.log(chalk.green('HTTPs:\t\t\t\ton'));
}
console.log('--');
process.on('uncaughtException', function (err) {

7203
yarn.lock

File diff suppressed because it is too large Load diff