Browse Source

web i server: login, post thought, get thoughts

master
nau 8 years ago
parent
commit
21d8768a09
18 changed files with 890 additions and 100 deletions
  1. +1
    -1
      README.md
  2. +2
    -1
      controllers/thoughtController.js
  3. +4
    -3
      controllers/userController.js
  4. +3
    -2
      models/thoughtModel.js
  5. +1
    -1
      models/userModel.js
  6. +36
    -0
      node_modules/ngstorage/CHANGELOG.md
  7. +21
    -0
      node_modules/ngstorage/LICENSE
  8. +263
    -0
      node_modules/ngstorage/README.md
  9. +237
    -0
      node_modules/ngstorage/ngStorage.js
  10. +1
    -0
      node_modules/ngstorage/ngStorage.min.js
  11. +67
    -0
      node_modules/ngstorage/package.json
  12. +9
    -0
      server.js
  13. +111
    -0
      web/controllers.js
  14. +7
    -7
      web/index.html
  15. +0
    -70
      web/index.js
  16. +59
    -0
      web/login.html
  17. +15
    -15
      web/menu.htm
  18. +53
    -0
      web/newthought.html

+ 1
- 1
README.md

@ -5,4 +5,4 @@ MEAN fullstack
backend: nodejs + express + mongodb backend: nodejs + express + mongodb
frontend: javascript + angular + bootstrap
frontend: angular + materializecss

+ 2
- 1
controllers/thoughtController.js

@ -54,7 +54,8 @@ exports.addThought = function(req, res) {
var thought = new thoughtModel({ var thought = new thoughtModel({
time: req.body.time, time: req.body.time,
content: req.body.content, content: req.body.content,
user_id: req.body.user_id
username: req.body.username,
avatar: req.body.avatar
}); });
thought.save(function(err, thought) { thought.save(function(err, thought) {

+ 4
- 3
controllers/userController.js

@ -59,7 +59,7 @@ exports.addUser = function(req, res) {
username: req.body.username, username: req.body.username,
password: req.body.password, password: req.body.password,
description: req.body.description, description: req.body.description,
icon: req.body.icon,
avatar: req.body.avatar,
mail: req.body.mail, mail: req.body.mail,
admin: req.body.admin admin: req.body.admin
}); });
@ -124,12 +124,13 @@ exports.login = function(req, res) {
//expiresInMinutes: 1440 // expires in 24 hours //expiresInMinutes: 1440 // expires in 24 hours
expiresIn: '60m' expiresIn: '60m'
}); });
console.log(user);
// return the information including token as JSON // return the information including token as JSON
res.json({ res.json({
success: true, success: true,
message: 'Enjoy your token!', message: 'Enjoy your token!',
token: token
token: token,
avatar: user.avatar
}); });
} }

+ 3
- 2
models/thoughtModel.js

@ -5,7 +5,8 @@ var mongoose = require('mongoose'),
var thoughtSchema = new Schema({ var thoughtSchema = new Schema({
time: { type: String }, time: { type: String },
content: { type: String }, content: { type: String },
user_id: { type: String },
fav: { type: String } //array amb els users que posen fav
username: { type: String },
fav: { type: String }, //array amb els users que posen fav
avatar: { type: String }
}) })
module.exports = mongoose.model('thoughtModel', thoughtSchema); module.exports = mongoose.model('thoughtModel', thoughtSchema);

+ 1
- 1
models/userModel.js

@ -17,7 +17,7 @@ var userSchema = new Schema({
username: { type: String }, username: { type: String },
password: { type: String }, password: { type: String },
description: { type: String }, description: { type: String },
icon: { type: String },
avatar: { type: String },
mail: { type: String }, mail: { type: String },
admin: { type: Boolean } admin: { type: Boolean }
}) })

+ 36
- 0
node_modules/ngstorage/CHANGELOG.md

@ -0,0 +1,36 @@
### 0.3.0 / 2013.10.16
* Remove the force overwrite on each cycle which has been causing inadvertent side effects such as breaking object references, changing `$$hashKey`s, or modifying user code behaviors.
* Add dirty-check debouncing. ([#2](https://github.com/gsklee/ngStorage/issues/2))
* Now incorporating Grunt to empower unit testing as well as uglification. ([#14](https://github.com/gsklee/ngStorage/issues/14))
* A few bugfixes, some of which are IE-only. ([#9](https://github.com/gsklee/ngStorage/issues/9), [#10](https://github.com/gsklee/ngStorage/issues/10), [#11](https://github.com/gsklee/ngStorage/issues/11))
---
### 0.2.3 / 2013.08.26
* Fix dependency version definitions in `bower.json`.
---
### 0.2.2 / 2013.08.09
* Add explicit DI annotation. ([#5](https://github.com/gsklee/ngStorage/issues/5))
* Fix an error in IE9 when Web Storage is empty. ([#8](https://github.com/gsklee/ngStorage/issues/8))
* Use the standard `addEventListener()` instead of jqLite's `bind()` to avoid the jQuery-specific `event.originalEvent`. ([#6](https://github.com/gsklee/ngStorage/issues/6))
---
### 0.2.1 / 2013.07.24
* Improve compatibility with existing Web Storage data using `ngStorage-` as the namespace. ([#3](https://github.com/gsklee/ngStorage/issues/3), [#4](https://github.com/gsklee/ngStorage/issues/4))
---
### 0.2.0 / 2013.07.19
* ***BREAKING CHANGE:*** `$clear()` has been replaced by `$reset()` and now accepts an optional parameter as the default content after reset.
* Add `$default()` to make default value binding easier.
* Data changes in `$localStorage` now propagate to different browser tabs.
* Improve compatibility with existing Web Storage data. ([#1](https://github.com/gsklee/ngStorage/issues/1))
* Properties being hooked onto the services with a `$` prefix are considered to belong to AngularJS inner workings and will no longer be written into Web Storage.
---
### 0.1.0 / 2013.07.07
* Initial release.

+ 21
- 0
node_modules/ngstorage/LICENSE

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 Gias Kay Lee
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

+ 263
- 0
node_modules/ngstorage/README.md

@ -0,0 +1,263 @@
ngStorage
=========
[![Build Status](https://travis-ci.org/gsklee/ngStorage.svg)](https://travis-ci.org/gsklee/ngStorage)
[![Dependency Status](https://david-dm.org/gsklee/ngStorage.svg)](https://david-dm.org/gsklee/ngStorage)
[![devDependency Status](https://david-dm.org/gsklee/ngStorage/dev-status.svg)](https://david-dm.org/gsklee/ngStorage#info=devDependencies)
An [AngularJS](https://github.com/angular/angular.js) module that makes Web Storage working in the *Angular Way*. Contains two services: `$localStorage` and `$sessionStorage`.
### Differences with Other Implementations
* **No Getter 'n' Setter Bullshit** - Right from AngularJS homepage: "Unlike other frameworks, there is no need to [...] wrap the model in accessors methods. Just plain old JavaScript here." Now you can enjoy the same benefit while achieving data persistence with Web Storage.
* **sessionStorage** - We got this often-overlooked buddy covered.
* **Cleanly-Authored Code** - Written in the *Angular Way*, well-structured with testability in mind.
* **No Cookie Fallback** - With Web Storage being [readily available](http://caniuse.com/namevalue-storage) in [all the browsers AngularJS officially supports](http://docs.angularjs.org/misc/faq#canidownloadthesourcebuildandhosttheangularjsenvironmentlocally), such fallback is largely redundant.
Install
=======
### Bower
```bash
bower install ngstorage
```
*NOTE:* We are `ngstorage` and *NOT* `ngStorage`. The casing is important!
### NPM
```bash
npm install ngstorage
```
*NOTE:* We are `ngstorage` and *NOT* `ngStorage`. The casing is important!
### nuget
```bash
Install-Package gsklee.ngStorage
```
Or search for `Angular ngStorage` in the nuget package manager. <https://www.nuget.org/packages/gsklee.ngStorage>
CDN
===
### cdnjs
cdnjs now hosts ngStorage at <https://cdnjs.com/libraries/ngStorage>
To use it
``` html
<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.6/ngStorage.min.js"></script>
```
### jsDelivr
jsDelivr hosts ngStorage at <http://www.jsdelivr.com/#!ngstorage>
To use is
``` html
<script src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
```
Usage
=====
### Require ngStorage and Inject the Services
```javascript
angular.module('app', [
'ngStorage'
]).controller('Ctrl', function(
$scope,
$localStorage,
$sessionStorage
){});
```
### Read and Write | [Demo](http://plnkr.co/edit/3vfRkvG7R9DgQxtWbGHz?p=preview)
Pass `$localStorage` (or `$sessionStorage`) by reference to a hook under `$scope` in plain ol' JavaScript:
```javascript
$scope.$storage = $localStorage;
```
And use it like you-already-know:
```html
<body ng-controller="Ctrl">
<button ng-click="$storage.counter = $storage.counter + 1">{{$storage.counter}}</button>
</body>
```
> Optionally, specify default values using the `$default()` method:
>
> ```javascript
> $scope.$storage = $localStorage.$default({
> counter: 42
> });
> ```
With this setup, changes will be automatically sync'd between `$scope.$storage`, `$localStorage`, and localStorage - even across different browser tabs!
### Read and Write Alternative (Not Recommended) | [Demo](http://plnkr.co/edit/9ZmkzRkYzS3iZkG8J5IK?p=preview)
If you're not fond of the presence of `$scope.$storage`, you can always use watchers:
```javascript
$scope.counter = $localStorage.counter || 42;
$scope.$watch('counter', function() {
$localStorage.counter = $scope.counter;
});
$scope.$watch(function() {
return angular.toJson($localStorage);
}, function() {
$scope.counter = $localStorage.counter;
});
```
This, however, is not the way ngStorage is designed to be used with. As can be easily seen by comparing the demos, this approach is way more verbose, and may have potential performance implications as the values being watched quickly grow.
### Delete | [Demo](http://plnkr.co/edit/o4w3VGqmp8opfrWzvsJy?p=preview)
Plain ol' JavaScript again, what else could you better expect?
```javascript
// Both will do
delete $scope.$storage.counter;
delete $localStorage.counter;
```
This will delete the corresponding entry inside the Web Storage.
### Delete Everything | [Demo](http://plnkr.co/edit/YiG28KTFdkeFXskolZqs?p=preview)
If you wish to clear the Storage in one go, use the `$reset()` method:
```javascript
$localStorage.$reset();
````
> Optionally, pass in an object you'd like the Storage to reset to:
>
> ```javascript
> $localStorage.$reset({
> counter: 42
> });
> ```
### Permitted Values | [Demo](http://plnkr.co/edit/n0acYLdhk3AeZmPOGY9Z?p=preview)
You can store anything except those [not supported by JSON](http://www.json.org/js.html):
* `Infinity`, `NaN` - Will be replaced with `null`.
* `undefined`, Function - Will be removed.
### Usage from config phase
To read and set values during the Angular config phase use the `.get/.set`
functions provided by the provider.
```javascript
var app = angular.module('app', ['ngStorage'])
.config(['$localStorageProvider',
function ($localStorageProvider) {
$localStorageProvider.get('MyKey');
$localStorageProvider.set('MyKey', { k: 'value' });
}]);
```
### Prefix
To change the prefix used by ngStorage use the provider function `setKeyPrefix`
during the config phase.
```javascript
var app = angular.module('app', ['ngStorage'])
.config(['$localStorageProvider',
function ($localStorageProvider) {
$localStorageProvider.setKeyPrefix('NewPrefix');
}])
```
### Custom serialization
To change how ngStorage serializes and deserializes values (uses JSON by default) you can use your own functions.
```javascript
angular.module('app', ['ngStorage'])
.config(['$localStorageProvider',
function ($localStorageProvider) {
var mySerializer = function (value) {
// Do what you want with the value.
return value;
};
var myDeserializer = function (value) {
return value;
};
$localStorageProvider.setSerializer(mySerializer);
$localStorageProvider.setDeserializer(myDeserializer);
}];)
```
### Minification
Just run `$ npm install` to install dependencies. Then run `$ grunt` for minification.
### Hints
#### Watch the watch
ngStorage internally uses an Angular watch to monitor changes to the `$storage`/`$localStorage` objects. That means that a digest cycle is required to persist your new values into the browser local storage.
Normally this is not a problem, but, for example, if you launch a new window after saving a value...
```javascript
$scope.$storage.school = theSchool;
$log.debug("launching " + url);
var myWindow = $window.open("", "_self");
myWindow.document.write(response.data);
```
the new values will not reliably be saved into the browser local storage. Allow a digest cycle to occur by using a zero-value `$timeout` as:
```javascript
$scope.$storage.school = theSchool;
$log.debug("launching and saving the new value" + url);
$timeout(function(){
var myWindow = $window.open("", "_self");
myWindow.document.write(response.data);
});
```
or better using `$scope.$evalAsync` as:
```javascript
$scope.$storage.school = theSchool;
$log.debug("launching and saving the new value" + url);
$scope.$evalAsync(function(){
var myWindow = $window.open("", "_self");
myWindow.document.write(response.data);
});
```
And your new values will be persisted correctly.
Todos
=====
* ngdoc Documentation
* Namespace Support
* Unit Tests
* Grunt Tasks
Any contribution will be appreciated.

+ 237
- 0
node_modules/ngstorage/ngStorage.js

@ -0,0 +1,237 @@
(function (root, factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(['angular'], factory);
} else if (root.hasOwnProperty('angular')) {
// Browser globals (root is window), we don't register it.
factory(root.angular);
} else if (typeof exports === 'object') {
module.exports = factory(require('angular'));
}
}(this , function (angular) {
'use strict';
// In cases where Angular does not get passed or angular is a truthy value
// but misses .module we can fall back to using window.
angular = (angular && angular.module ) ? angular : window.angular;
function isStorageSupported($window, storageType) {
// Some installations of IE, for an unknown reason, throw "SCRIPT5: Error: Access is denied"
// when accessing window.localStorage. This happens before you try to do anything with it. Catch
// that error and allow execution to continue.
// fix 'SecurityError: DOM Exception 18' exception in Desktop Safari, Mobile Safari
// when "Block cookies": "Always block" is turned on
var supported;
try {
supported = $window[storageType];
}
catch(err) {
supported = false;
}
// When Safari (OS X or iOS) is in private browsing mode, it appears as though localStorage and sessionStorage
// is available, but trying to call .setItem throws an exception below:
// "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."
if(supported) {
var key = '__' + Math.round(Math.random() * 1e7);
try {
$window[storageType].setItem(key, key);
$window[storageType].removeItem(key, key);
}
catch(err) {
supported = false;
}
}
return supported;
}
/**
* @ngdoc overview
* @name ngStorage
*/
return angular.module('ngStorage', [])
/**
* @ngdoc object
* @name ngStorage.$localStorage
* @requires $rootScope
* @requires $window
*/
.provider('$localStorage', _storageProvider('localStorage'))
/**
* @ngdoc object
* @name ngStorage.$sessionStorage
* @requires $rootScope
* @requires $window
*/
.provider('$sessionStorage', _storageProvider('sessionStorage'));
function _storageProvider(storageType) {
var providerWebStorage = isStorageSupported(window, storageType);
return function () {
var storageKeyPrefix = 'ngStorage-';
this.setKeyPrefix = function (prefix) {
if (typeof prefix !== 'string') {
throw new TypeError('[ngStorage] - ' + storageType + 'Provider.setKeyPrefix() expects a String.');
}
storageKeyPrefix = prefix;
};
var serializer = angular.toJson;
var deserializer = angular.fromJson;
this.setSerializer = function (s) {
if (typeof s !== 'function') {
throw new TypeError('[ngStorage] - ' + storageType + 'Provider.setSerializer expects a function.');
}
serializer = s;
};
this.setDeserializer = function (d) {
if (typeof d !== 'function') {
throw new TypeError('[ngStorage] - ' + storageType + 'Provider.setDeserializer expects a function.');
}
deserializer = d;
};
this.supported = function() {
return !!providerWebStorage;
};
// Note: This is not very elegant at all.
this.get = function (key) {
return providerWebStorage && deserializer(providerWebStorage.getItem(storageKeyPrefix + key));
};
// Note: This is not very elegant at all.
this.set = function (key, value) {
return providerWebStorage && providerWebStorage.setItem(storageKeyPrefix + key, serializer(value));
};
this.remove = function (key) {
providerWebStorage && providerWebStorage.removeItem(storageKeyPrefix + key);
}
this.$get = [
'$rootScope',
'$window',
'$log',
'$timeout',
'$document',
function(
$rootScope,
$window,
$log,
$timeout,
$document
){
// The magic number 10 is used which only works for some keyPrefixes...
// See https://github.com/gsklee/ngStorage/issues/137
var prefixLength = storageKeyPrefix.length;
// #9: Assign a placeholder object if Web Storage is unavailable to prevent breaking the entire AngularJS app
// Note: recheck mainly for testing (so we can use $window[storageType] rather than window[storageType])
var isSupported = isStorageSupported($window, storageType),
webStorage = isSupported || ($log.warn('This browser does not support Web Storage!'), {setItem: angular.noop, getItem: angular.noop, removeItem: angular.noop}),
$storage = {
$default: function(items) {
for (var k in items) {
angular.isDefined($storage[k]) || ($storage[k] = angular.copy(items[k]) );
}
$storage.$sync();
return $storage;
},
$reset: function(items) {
for (var k in $storage) {
'$' === k[0] || (delete $storage[k] && webStorage.removeItem(storageKeyPrefix + k));
}
return $storage.$default(items);
},
$sync: function () {
for (var i = 0, l = webStorage.length, k; i < l; i++) {
// #8, #10: `webStorage.key(i)` may be an empty string (or throw an exception in IE9 if `webStorage` is empty)
(k = webStorage.key(i)) && storageKeyPrefix === k.slice(0, prefixLength) && ($storage[k.slice(prefixLength)] = deserializer(webStorage.getItem(k)));
}
},
$apply: function() {
var temp$storage;
_debounce = null;
if (!angular.equals($storage, _last$storage)) {
temp$storage = angular.copy(_last$storage);
angular.forEach($storage, function(v, k) {
if (angular.isDefined(v) && '$' !== k[0]) {
webStorage.setItem(storageKeyPrefix + k, serializer(v));
delete temp$storage[k];
}
});
for (var k in temp$storage) {
webStorage.removeItem(storageKeyPrefix + k);
}
_last$storage = angular.copy($storage);
}
},
$supported: function() {
return !!isSupported;
}
},
_last$storage,
_debounce;
$storage.$sync();
_last$storage = angular.copy($storage);
$rootScope.$watch(function() {
_debounce || (_debounce = $timeout($storage.$apply, 100, false));
});
// #6: Use `$window.addEventListener` instead of `angular.element` to avoid the jQuery-specific `event.originalEvent`
$window.addEventListener && $window.addEventListener('storage', function(event) {
if (!event.key) {
return;
}
// Reference doc.
var doc = $document[0];
if ( (!doc.hasFocus || !doc.hasFocus()) && storageKeyPrefix === event.key.slice(0, prefixLength) ) {
event.newValue ? $storage[event.key.slice(prefixLength)] = deserializer(event.newValue) : delete $storage[event.key.slice(prefixLength)];
_last$storage = angular.copy($storage);
$rootScope.$apply();
}
});
$window.addEventListener && $window.addEventListener('beforeunload', function() {
$storage.$apply();
});
return $storage;
}
];
};
}
}));

+ 1
- 0
node_modules/ngstorage/ngStorage.min.js

@ -0,0 +1 @@
/*! ngstorage 0.3.10 | Copyright (c) 2016 Gias Kay Lee | MIT License */!function(a,b){"use strict";"function"==typeof define&&define.amd?define(["angular"],b):a.hasOwnProperty("angular")?b(a.angular):"object"==typeof exports&&(module.exports=b(require("angular")))}(this,function(a){"use strict";function b(a,b){var c;try{c=a[b]}catch(d){c=!1}if(c){var e="__"+Math.round(1e7*Math.random());try{a[b].setItem(e,e),a[b].removeItem(e,e)}catch(d){c=!1}}return c}function c(c){var d=b(window,c);return function(){var e="ngStorage-";this.setKeyPrefix=function(a){if("string"!=typeof a)throw new TypeError("[ngStorage] - "+c+"Provider.setKeyPrefix() expects a String.");e=a};var f=a.toJson,g=a.fromJson;this.setSerializer=function(a){if("function"!=typeof a)throw new TypeError("[ngStorage] - "+c+"Provider.setSerializer expects a function.");f=a},this.setDeserializer=function(a){if("function"!=typeof a)throw new TypeError("[ngStorage] - "+c+"Provider.setDeserializer expects a function.");g=a},this.supported=function(){return!!d},this.get=function(a){return d&&g(d.getItem(e+a))},this.set=function(a,b){return d&&d.setItem(e+a,f(b))},this.remove=function(a){d&&d.removeItem(e+a)},this.$get=["$rootScope","$window","$log","$timeout","$document",function(d,h,i,j,k){var l,m,n=e.length,o=b(h,c),p=o||(i.warn("This browser does not support Web Storage!"),{setItem:a.noop,getItem:a.noop,removeItem:a.noop}),q={$default:function(b){for(var c in b)a.isDefined(q[c])||(q[c]=a.copy(b[c]));return q.$sync(),q},$reset:function(a){for(var b in q)"$"===b[0]||delete q[b]&&p.removeItem(e+b);return q.$default(a)},$sync:function(){for(var a,b=0,c=p.length;c>b;b++)(a=p.key(b))&&e===a.slice(0,n)&&(q[a.slice(n)]=g(p.getItem(a)))},$apply:function(){var b;if(m=null,!a.equals(q,l)){b=a.copy(l),a.forEach(q,function(c,d){a.isDefined(c)&&"$"!==d[0]&&(p.setItem(e+d,f(c)),delete b[d])});for(var c in b)p.removeItem(e+c);l=a.copy(q)}},$supported:function(){return!!o}};return q.$sync(),l=a.copy(q),d.$watch(function(){m||(m=j(q.$apply,100,!1))}),h.addEventListener&&h.addEventListener("storage",function(b){if(b.key){var c=k[0];c.hasFocus&&c.hasFocus()||e!==b.key.slice(0,n)||(b.newValue?q[b.key.slice(n)]=g(b.newValue):delete q[b.key.slice(n)],l=a.copy(q),d.$apply())}}),h.addEventListener&&h.addEventListener("beforeunload",function(){q.$apply()}),q}]}}return a=a&&a.module?a:window.angular,a.module("ngStorage",[]).provider("$localStorage",c("localStorage")).provider("$sessionStorage",c("sessionStorage"))});

+ 67
- 0
node_modules/ngstorage/package.json

@ -0,0 +1,67 @@
{
"name": "ngstorage",
"version": "0.3.11",
"author": {
"name": "Gias Kay Lee"
},
"licenses": [
{
"type": "MIT",
"url": "https://github.com/gsklee/ngStorage/blob/master/LICENSE"
}
],
"repository": {
"type": "git",
"url": "git+https://github.com/gsklee/ngStorage.git"
},
"main": "ngStorage.js",
"scripts": {
"test": "grunt test"
},
"devDependencies": {
"bower": "^1.x",
"grunt": "^0.4.1",
"grunt-cli": "^0.1.11",
"grunt-contrib-uglify": "^0.x",
"grunt-karma": "^0.x",
"karma": "^0.13.2",
"karma-chrome-launcher": "^0.2.0",
"karma-firefox-launcher": "^0.1.3",
"karma-mocha": "^0.2.0",
"karma-phantomjs-launcher": "^0.2.0",
"mocha": "^2.2.4",
"phantomjs-prebuilt": "^2.1.1"
},
"dependencies": {},
"gitHead": "0887aa096db14cde29a039a81f34abc190dbc996",
"description": "ngStorage =========",
"bugs": {
"url": "https://github.com/gsklee/ngStorage/issues"
},
"homepage": "https://github.com/gsklee/ngStorage#readme",
"_id": "ngstorage@0.3.11",
"_shasum": "1637c45b872d909d9cc7e18b374898d50b2e844f",
"_from": "ngstorage@latest",
"_npmVersion": "2.15.1",
"_nodeVersion": "0.12.14",
"_npmUser": {
"name": "egilkh",
"email": "egilkh@gmail.com"
},
"dist": {
"shasum": "1637c45b872d909d9cc7e18b374898d50b2e844f",
"tarball": "https://registry.npmjs.org/ngstorage/-/ngstorage-0.3.11.tgz"
},
"maintainers": [
{
"name": "egilkh",
"email": "egilkh@gmail.com"
}
],
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/ngstorage-0.3.11.tgz_1470033811992_0.22283236496150494"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/ngstorage/-/ngstorage-0.3.11.tgz"
}

+ 9
- 0
server.js

@ -40,6 +40,15 @@ router.get('/', function(req, res) {
app.use(router);*/ app.use(router);*/
app.use(express.static(__dirname + '/web')); app.use(express.static(__dirname + '/web'));
//CORS
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// API routes ------------------------------------------------------ // API routes ------------------------------------------------------
var apiRoutes = express.Router(); var apiRoutes = express.Router();

+ 111
- 0
web/controllers.js

@ -0,0 +1,111 @@
var url="http://localhost:3000/api/";
angular.module('thoughtsApp', [])
.controller('ThoughtsController', function(
$scope,
$http
) {
var thoughtsList = this;
if(window.sessionStorage.getItem('thoughtsToken'))
{
$scope.userLogged=true;
}else{
$scope.userLogged=false;
}
$http({
method : "GET",
url : url + "thoughts"
}).then(function mySucces(response) {
thoughtsList.thoughts = response.data;
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
thoughtsList.addTodo = function() {
todoList.todos.push({text:todoList.todoText, done:false});
todoList.todoText = '';
};
$scope.login = function(){
ActivateLoadBar();
var obj = {
username: $scope.username,
password: $scope.password
};
$http({
method : "POST",
url : url + "auth",
data: obj
}).then(function mySucces(response) {
if(response.data.success==true)
{
window.sessionStorage.setItem('thoughtsUsername', $scope.username);
window.sessionStorage.setItem('thoughtsToken', response.data.token);
window.sessionStorage.setItem('thoughtsUserAvatar', response.data.avatar);
toastr.success("Logged in");
setTimeout(function(){
window.location="index.html";
}, 1000);
}else{
toastr.error(response.data.message);
setTimeout(function(){
window.location="login.html";
}, 1000);
}
}, function myError(response) {
toastr.error(response.statusText);
});
};
$scope.logout = function(){
window.sessionStorage.removeItem('thoughtsUsername')
window.sessionStorage.removeItem('thoughtsToken');
window.sessionStorage.removeItem('thoughtsUserAvatar');
toastr.info("logging out");
setTimeout(function(){
window.location="index.html";
}, 1000);
}
$scope.postThought = function(){
ActivateLoadBar();
var obj = {
time: new Date(),
content: $scope.newthought,
username: window.sessionStorage.getItem('thoughtsUsername'),
avatar: window.sessionStorage.getItem('thoughtsUserAvatar'),
token: window.sessionStorage.getItem('thoughtsToken')
};
$http({
method : "POST",
url : url + "thoughts",
data: obj
}).then(function mySucces(response) {
$scope.myWelcome = response.data;
toastr.success("Thought published");
setTimeout(function(){
window.location="index.html";
}, 1000);
}, function myError(response) {
toastr.error(response.statusText);
});
};
});
/* LOADBAR */
function ActivateLoadBar(){
var html="";
html+="<br>";
html+="<div id='loadbar' class='progress'>";
html+=" <div class='indeterminate'></div>";
html+="</div>";
document.body.innerHTML+=html;
}
function DesactivateLoadBar(){
document.getElementById('loadbar').innerHTML="";
}
/* </LOADBAR */

+ 7
- 7
web/index.html

@ -1,6 +1,6 @@
<!DOCTYPE html> <!DOCTYPE html>
<html>
<html ng-app="thoughtsApp">
<head> <head>
<!--Import Google Icon Font--> <!--Import Google Icon Font-->
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
@ -15,22 +15,22 @@
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
</head> </head>
<body ng-app="thoughtsApp">
<body ng-controller="ThoughtsController as thoughtsList">
<div ng-include="'menu.htm'"></div> <div ng-include="'menu.htm'"></div>
<div class="container"> <div class="container">
<div ng-controller="ThoughtsController as thoughtsList">
<div>
<ul class="collection"> <ul class="collection">
<li class="collection-item avatar" ng-repeat="thought in thoughtsList.thoughts">
<li class="collection-item avatar" ng-repeat="thought in thoughtsList.thoughts | orderBy: '-time'">
<img ng-src="img/icons/animals/{{thought.avatar}}.png" class="circle"> <img ng-src="img/icons/animals/{{thought.avatar}}.png" class="circle">
<a ng-href="user.html?={{thought.username}}" class="title"> <a ng-href="user.html?={{thought.username}}" class="title">
{{thought.username}} {{thought.username}}
</a> </a>
<div class="chip">{{thought.time | date:'HH:mm'}}</div>
<p>{{thought.content}}</p> <p>{{thought.content}}</p>
<a href="#!" class="secondary-content"><i class="material-icons">grade</i></a>
<a href="#!" class="secondary-content"><i class="material-icons indigo-text text-lighten-2">grade</i></a>
</li> </li>
</ul> </ul>
@ -52,7 +52,7 @@
<script src="jslib/toastr.js"></script> <script src="jslib/toastr.js"></script>
<link type="text/css" rel="stylesheet" href="jslib/toastr.css"/> <link type="text/css" rel="stylesheet" href="jslib/toastr.css"/>
<script src="index.js"></script>
<script src="controllers.js"></script>
</body> </body>

+ 0
- 70
web/index.js

@ -1,70 +0,0 @@
angular.module('thoughtsApp', [])
.controller('ThoughtsController', function() {
var thoughtsList = this;
thoughtsList.thoughts = [
{
time: '9h',
content:'primer thought',
username: 'user1',
fav: '',
avatar: 'bat'
},
{
time: '10h',
content:'quart thought',
username: 'user4',
fav: '',
avatar: 'tiger'
},
{
time: '10h',
content:'segon thought, aquí, provant',
username: 'user2',
fav: '',
avatar: 'toucan'
},
{
time: '10h',
content:'tercer thought, responent',
username: 'user1',
fav: '',
avatar: 'bat'
},
{
time: '10h',
content:'hola com va',
username: 'user3',
fav: '',
avatar: 'macaw'
},
{
time: '10h',
content:'quart thought',
username: 'user5',
fav: '',
avatar: 'giraffe'
}];
thoughtsList.addTodo = function() {
todoList.todos.push({text:todoList.todoText, done:false});
todoList.todoText = '';
};
thoughtsList.remaining = function() {
var count = 0;
angular.forEach(todoList.todos, function(todo) {
count += todo.done ? 0 : 1;
});
return count;
};
thoughtsList.archive = function() {
var oldTodos = todoList.todos;
todoList.todos = [];
angular.forEach(oldTodos, function(todo) {
if (!todo.done) todoList.todos.push(todo);
});
};
});

+ 59
- 0
web/login.html

@ -0,0 +1,59 @@
<!DOCTYPE html>
<html ng-app="thoughtsApp">
<head>
<!--Import Google Icon Font-->
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/>
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Thoughts - new thought</title>
<!-- ANGULAR -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
</head>
<body ng-controller="ThoughtsController">
<div ng-include="'menu.htm'"></div>
<div class="container">
<div class="row">
<div class="input-field col s12">
<input ng-model="username" id="username" type="text" class="validate">
<label for="username">Username</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input ng-model="password" id="password" type="password" class="validate">
<label for="password">password</label>
</div>
</div>
<a href="index.html" class="waves-effect waves-light btn red lighten-2 ">Cancel</a>
<a ng-click="login()" class="waves-effect waves-light btn indigo lighten-2 right">Login</a>
</div>
<!--Import jQuery before materialize.js-->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="js/materialize.min.js"></script>
<script src="jslib/toastr.js"></script>
<link type="text/css" rel="stylesheet" href="jslib/toastr.css"/>
<script src="controllers.js"></script>
</body>
</html>

+ 15
- 15
web/menu.htm

@ -7,33 +7,32 @@
<li><a ><i class='material-icons'>settings_power</i></a></li> <li><a ><i class='material-icons'>settings_power</i></a></li>
</ul> </ul>
<div class='navbar-fixed'>
<nav> <nav>
<div class='nav-wrapper indigo lighten-2'> <div class='nav-wrapper indigo lighten-2'>
<a href='index.html' class='brand-logo'>Thoughts</a> <a href='index.html' class='brand-logo'>Thoughts</a>
<a href='#' data-activates='mobile-demo' class='button-collapse'><i class='material-icons'>menu</i></a> <a href='#' data-activates='mobile-demo' class='button-collapse'><i class='material-icons'>menu</i></a>
<ul class='right hide-on-med-and-down'>
<!-- if(userlogged==true){-->
<li><a href='neweviction.html'><i class='material-icons'>add</i></a></li>
<li><a href='editassembly.html'><i class='material-icons'>perm_identity</i></a></li>
<li><a onclick='onBtnLogout()' ><i class='material-icons'>settings_power</i></a></li>
<!-- }else{
<li><a href='signin.html'>Signup</a></li>
<li><a href='login.html'> Login</a></li>
}-->
</ul>
<ul class='right'>
<!-- Dropdown Trigger -->
<li><a href='neweviction.html'><i class='material-icons'>add</i></a></li>
<ul class='right' ng-hide="!userLogged">
<li><a href='newthought.html'><i class='material-icons'>add</i></a></li>
<li><a class="dropdown-button" href="#!" data-activates="dropdown1"><i class='material-icons'>perm_identity</i></a></li> <li><a class="dropdown-button" href="#!" data-activates="dropdown1"><i class='material-icons'>perm_identity</i></a></li>
<li><a ng-click="logout()"><i class='material-icons'>power_settings_new</i></a></li>
</ul>
<ul class='right' ng-hide="userLogged">
<li><a href='login.html'><i class='material-icons'>input</i></a></li>
</ul> </ul>
<ul class='side-nav' id='mobile-demo'> <ul class='side-nav' id='mobile-demo'>
<li><a href='index.html'>Home</a></li> <li><a href='index.html'>Home</a></li>
<!-- if(userlogged==true){--> <!-- if(userlogged==true){-->
<li><a href='neweviction.html'>Add eviction</a></li>
<li><a href='newthought.html'>Add eviction</a></li>
<li><a href='editassembly.html'>Edit assembly</a></li> <li><a href='editassembly.html'>Edit assembly</a></li>
<li><a onclick='onBtnLogout()'>Logout</a></li> <li><a onclick='onBtnLogout()'>Logout</a></li>
<!-- }else{ <!-- }else{
@ -43,3 +42,4 @@
</ul> </ul>
</div> </div>
</nav> </nav>
</div>

+ 53
- 0
web/newthought.html

@ -0,0 +1,53 @@
<!DOCTYPE html>
<html ng-app="thoughtsApp">
<head>
<!--Import Google Icon Font-->
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/>
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Thoughts - new thought</title>
<!-- ANGULAR -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
</head>
<body ng-controller="ThoughtsController">
<div ng-include="'menu.htm'"></div>
<div class="container">
<br>
<div class="badge indigo-text right">{{144 - newthought.length}}</div>
<div class="input-field col s6">
<textarea ng-model="newthought" id="textarea1" class="materialize-textarea"></textarea>
<label for="textarea1">New thought</label>
</div>
<a href="index.html" class="waves-effect waves-light btn red lighten-2 ">Cancel</a>
<a ng-click="postThought()" class="waves-effect waves-light btn indigo lighten-2 right">Publish</a>
</div>
<!--Import jQuery before materialize.js-->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="js/materialize.min.js"></script>
<script src="jslib/toastr.js"></script>
<link type="text/css" rel="stylesheet" href="jslib/toastr.css"/>
<script src="controllers.js"></script>
</body>
</html>

Loading…
Cancel
Save