From 21d8768a097eb576d1c08440defaff73dee06850 Mon Sep 17 00:00:00 2001 From: nau Date: Sun, 21 Aug 2016 20:57:24 +0200 Subject: [PATCH] web i server: login, post thought, get thoughts --- README.md | 2 +- controllers/thoughtController.js | 3 +- controllers/userController.js | 7 +- models/thoughtModel.js | 5 +- models/userModel.js | 2 +- node_modules/ngstorage/CHANGELOG.md | 36 ++++ node_modules/ngstorage/LICENSE | 21 ++ node_modules/ngstorage/README.md | 263 ++++++++++++++++++++++++ node_modules/ngstorage/ngStorage.js | 237 +++++++++++++++++++++ node_modules/ngstorage/ngStorage.min.js | 1 + node_modules/ngstorage/package.json | 67 ++++++ server.js | 9 + web/controllers.js | 111 ++++++++++ web/index.html | 14 +- web/index.js | 70 ------- web/login.html | 59 ++++++ web/menu.htm | 30 +-- web/newthought.html | 53 +++++ 18 files changed, 890 insertions(+), 100 deletions(-) create mode 100644 node_modules/ngstorage/CHANGELOG.md create mode 100644 node_modules/ngstorage/LICENSE create mode 100644 node_modules/ngstorage/README.md create mode 100644 node_modules/ngstorage/ngStorage.js create mode 100644 node_modules/ngstorage/ngStorage.min.js create mode 100644 node_modules/ngstorage/package.json create mode 100644 web/controllers.js delete mode 100644 web/index.js create mode 100644 web/login.html create mode 100644 web/newthought.html diff --git a/README.md b/README.md index f65127d..2bd3689 100644 --- a/README.md +++ b/README.md @@ -5,4 +5,4 @@ MEAN fullstack backend: nodejs + express + mongodb -frontend: javascript + angular + bootstrap +frontend: angular + materializecss diff --git a/controllers/thoughtController.js b/controllers/thoughtController.js index 5a28022..522ca6c 100644 --- a/controllers/thoughtController.js +++ b/controllers/thoughtController.js @@ -54,7 +54,8 @@ exports.addThought = function(req, res) { var thought = new thoughtModel({ time: req.body.time, content: req.body.content, - user_id: req.body.user_id + username: req.body.username, + avatar: req.body.avatar }); thought.save(function(err, thought) { diff --git a/controllers/userController.js b/controllers/userController.js index 415241d..ec8e6e4 100644 --- a/controllers/userController.js +++ b/controllers/userController.js @@ -59,7 +59,7 @@ exports.addUser = function(req, res) { username: req.body.username, password: req.body.password, description: req.body.description, - icon: req.body.icon, + avatar: req.body.avatar, mail: req.body.mail, admin: req.body.admin }); @@ -124,12 +124,13 @@ exports.login = function(req, res) { //expiresInMinutes: 1440 // expires in 24 hours expiresIn: '60m' }); - +console.log(user); // return the information including token as JSON res.json({ success: true, message: 'Enjoy your token!', - token: token + token: token, + avatar: user.avatar }); } diff --git a/models/thoughtModel.js b/models/thoughtModel.js index fe59933..8aa36f0 100644 --- a/models/thoughtModel.js +++ b/models/thoughtModel.js @@ -5,7 +5,8 @@ var mongoose = require('mongoose'), var thoughtSchema = new Schema({ time: { 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); diff --git a/models/userModel.js b/models/userModel.js index d66979d..406da20 100644 --- a/models/userModel.js +++ b/models/userModel.js @@ -17,7 +17,7 @@ var userSchema = new Schema({ username: { type: String }, password: { type: String }, description: { type: String }, - icon: { type: String }, + avatar: { type: String }, mail: { type: String }, admin: { type: Boolean } }) diff --git a/node_modules/ngstorage/CHANGELOG.md b/node_modules/ngstorage/CHANGELOG.md new file mode 100644 index 0000000..07536c2 --- /dev/null +++ b/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. diff --git a/node_modules/ngstorage/LICENSE b/node_modules/ngstorage/LICENSE new file mode 100644 index 0000000..b1bc16e --- /dev/null +++ b/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. diff --git a/node_modules/ngstorage/README.md b/node_modules/ngstorage/README.md new file mode 100644 index 0000000..e18ca57 --- /dev/null +++ b/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. + +CDN +=== + +### cdnjs +cdnjs now hosts ngStorage at + +To use it + +``` html + +``` + +### jsDelivr + +jsDelivr hosts ngStorage at + +To use is + +``` html + +``` + +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 + + + +``` + +> 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. diff --git a/node_modules/ngstorage/ngStorage.js b/node_modules/ngstorage/ngStorage.js new file mode 100644 index 0000000..0bbdb69 --- /dev/null +++ b/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; + } + ]; + }; + } + +})); diff --git a/node_modules/ngstorage/ngStorage.min.js b/node_modules/ngstorage/ngStorage.min.js new file mode 100644 index 0000000..54891eb --- /dev/null +++ b/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"))}); \ No newline at end of file diff --git a/node_modules/ngstorage/package.json b/node_modules/ngstorage/package.json new file mode 100644 index 0000000..ed3ffcf --- /dev/null +++ b/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" +} diff --git a/server.js b/server.js index c60dfcc..899d41e 100755 --- a/server.js +++ b/server.js @@ -40,6 +40,15 @@ router.get('/', function(req, res) { app.use(router);*/ 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 ------------------------------------------------------ var apiRoutes = express.Router(); diff --git a/web/controllers.js b/web/controllers.js new file mode 100644 index 0000000..017abdf --- /dev/null +++ b/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+="
"; + html+="
"; + html+="
"; + html+="
"; + document.body.innerHTML+=html; + } + function DesactivateLoadBar(){ + document.getElementById('loadbar').innerHTML=""; + } + /* - + @@ -15,22 +15,22 @@ - +
-
+
@@ -52,7 +52,7 @@ - + diff --git a/web/index.js b/web/index.js deleted file mode 100644 index d0adf9c..0000000 --- a/web/index.js +++ /dev/null @@ -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); - }); - }; - }); diff --git a/web/login.html b/web/login.html new file mode 100644 index 0000000..849c018 --- /dev/null +++ b/web/login.html @@ -0,0 +1,59 @@ + + + + + + + + + + + + Thoughts - new thought + + + + + + + +
+ +
+
+
+ + +
+
+
+
+ + +
+
+ + Cancel + Login + +
+ + + + + + + + + + + + + + + + + + + + diff --git a/web/menu.htm b/web/menu.htm index 278f8b5..c43b28b 100644 --- a/web/menu.htm +++ b/web/menu.htm @@ -7,33 +7,32 @@
  • settings_power
  • - +