Skip to content

Commit

Permalink
Merge pull request #38 from valor-software/master
Browse files Browse the repository at this point in the history
Update to angular2 v0.44
  • Loading branch information
mgonto committed Oct 19, 2015
2 parents f2d440b + 8a9d63b commit 78ecb66
Show file tree
Hide file tree
Showing 38 changed files with 394 additions and 10,069 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ build/Release
ehthumbs.db
Icon?
Thumbs.db
.idea

# Node Files #
node_modules
Expand Down
4 changes: 2 additions & 2 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@ Clone this repository as well as [the server](https://github.com/auth0/nodejs-jw

First, run the server app in the port `3001`.

Then, run `npm install` on this project and run `npm startwatch` to start the app. Then just navigate to [http://localhost:3000](http://localhost:3000) :boom:

Then, run `npm install` on this project and run `npm start` to start the app. Then just navigate to [http://localhost:3000](http://localhost:3000) :boom:
Use `npm run server` to run API server.
2 changes: 2 additions & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules/
.env
50 changes: 50 additions & 0 deletions backend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# NODE TODO API

This is a NodeJS full API that you can use to test with your SPAs or Mobile apps.

## How to use it

This service is deployed in Heroku and saves the TODOs in memory, so once the dyno dies, all the todos are removed.

It's deployed on [http://auth0-todo-test-api.herokuapp.com/](http://auth0-todo-test-api.herokuapp.com/)

## Available APIs

### Open API

The Open API lets anyone do CRUD operation on a set of TODOs. This means that you can add a TODO and then John Doe can delete it.

Available methods:

* **POST /api/open/todos**: Adds a new TODO
* **PUT /api/open/todos/:id**: Updates the TODO with id `id`
* **GET /api/open/todos/:id**: Returns the TODO with id `id`
* **DELETE /api/open/todos/:id**: Deletes the TODO with id `id`
* **GET /api/open/todos**: Gets all fo the TODOs

### User based API

You can use this API to save TODO items for a particular user. For that, you need to use Auth0 to get the `id_token` (JWT) and send it in every request as part of the `Authorization` header.

This server validates JWT from the following account:

* **Domain**: `samples.auth0.com`
* **ClientID**: `BUIJSW9x60sIHBw8Kd9EmCbj8eDIFxDC`

Available methods:

* **POST /api/todos**: Adds a new TODO
* **PUT /api/todos/:id**: Updates the TODO with id `id`
* **GET /api/todos/:id**: Returns the TODO with id `id`
* **DELETE /api/todos/:id**: Deletes the TODO with id `id`
* **GET /api/todos**: Gets all fo the TODOs

## Running this for your Auth0 account

If you want, you can run this server for YOUR Auth0 account. For that, you just need to create a `.env` file and set the `AUTH0_CLIENT_ID` and `AUTH0_CLIENT_SECRET` variables with the information from your account:

````bash
AUTH0_CLIENT_ID=YourClientId
AUTH0_CLIENT_SECRET=YourClientSecret
````

8 changes: 8 additions & 0 deletions backend/anonymous-routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
var express = require('express'),
quoter = require('./quoter');

var app = module.exports = express.Router();

app.get('/api/random-quote', function(req, res) {
res.status(200).send(quoter.getRandomOne());
});
3 changes: 3 additions & 0 deletions backend/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"secret": "ngEurope rocks!"
}
38 changes: 38 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"name": "in-memory-todo",
"version": "0.1.0",
"description": "An In memory todo for Logged in and not Logged in users",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://github.com/auth0/in-memory-todo.git"
},
"keywords": [
"todo",
"in",
"memory",
"jwt",
"auth0"
],
"author": "Martin Gontovnikas",
"license": "MIT",
"bugs": {
"url": "https://github.com/auth0/in-memory-todo/issues"
},
"homepage": "https://github.com/auth0/in-memory-todo",
"dependencies": {
"body-parser": "^1.6.5",
"compression": "^1.0.11",
"cors": "^2.4.1",
"dotenv": "^0.4.0",
"errorhandler": "^1.1.1",
"express": "^4.8.5",
"express-jwt": "^0.3.1",
"jsonwebtoken": "^1.1.2",
"lodash": "^2.4.1",
"morgan": "^1.2.3"
}
}
16 changes: 16 additions & 0 deletions backend/protected-routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
var express = require('express'),
jwt = require('express-jwt'),
config = require('./config'),
quoter = require('./quoter');

var app = module.exports = express.Router();

var jwtCheck = jwt({
secret: config.secret
});

app.use('/api/protected', jwtCheck);

app.get('/api/protected/random-quote', function(req, res) {
res.status(200).send(quoter.getRandomOne());
});
7 changes: 7 additions & 0 deletions backend/quoter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
var quotes = require('./quotes.json');

exports.getRandomOne = function() {
var totalAmount = quotes.length;
var rand = Math.ceil(Math.random() * totalAmount);
return quotes[rand];
}
46 changes: 46 additions & 0 deletions backend/quotes.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
["Chuck Norris doesn't call the wrong number. You answer the wrong phone.",
"Chuck Norris has already been to Mars; that's why there are no signs of life.",
"Chuck Norris and Superman once fought each other on a bet. The loser had to start wearing his underwear on the outside of his pants.",
"Some magicans can walk on water, Chuck Norris can swim through land.",
"Chuck Norris once urinated in a semi truck's gas tank as a joke....that truck is now known as Optimus Prime.",
"Chuck Norris doesn't flush the toilet, he scares the sh*t out of it",
"Chuck Norris counted to infinity - twice.",
"Chuck Norris can cut through a hot knife with butter",
"Chuck Norris is the reason why Waldo is hiding.",
"Death once had a near-Chuck Norris experience",
"When the Boogeyman goes to sleep every night, he checks his closet for Chuck Norris.",
"Chuck Norris can slam a revolving door.",
"Chuck Norris once kicked a horse in the chin. Its decendants are known today as Giraffes.",
"Chuck Norris will never have a heart attack. His heart isn't nearly foolish enough to attack him.",
"Chuck Norris once got bit by a rattle snake........ After three days of pain and agony ..................the rattle snake died",
"Chuck Norris can win a game of Connect Four in only three moves.",
"When Chuck Norris does a pushup, he isn't lifting himself up, he's pushing the Earth down.",
"There is no theory of evolution. Just a list of animals Chuck Norris allows to live.",
"Chuck Norris can light a fire by rubbing two ice-cubes together.",
"Chuck Norris doesn’t wear a watch. HE decides what time it is.",
"The original title for Alien vs. Predator was Alien and Predator vs Chuck Norris.",
"The film was cancelled shortly after going into preproduction. No one would pay nine dollars to see a movie fourteen seconds long.",
"Chuck Norris doesn't read books. He stares them down until he gets the information he wants.",
"Chuck Norris made a Happy Meal cry.",
"Outer space exists because it's afraid to be on the same planet with Chuck Norris.",
"If you spell Chuck Norris in Scrabble, you win. Forever.",
"Chuck Norris can make snow angels on a concrete slab.",
"Chuck Norris destroyed the periodic table, because Chuck Norris only recognizes the element of surprise.",
"Chuck Norris has to use a stunt double when he does crying scenes.",
"Chuck Norris' hand is the only hand that can beat a Royal Flush.",
"There is no theory of evolution. Just a list of creatures Chuck Norris has allowed to live.",
"Chuck Norris does not sleep. He waits.",
"Chuck Norris tells a GPS which way to go.",
"Some people wear Superman pajamas. Superman wears Chuck Norris pajamas.",
"Chuck Norris's tears cure cancer ..... to bad he has never cried",
"Chuck Norris doesn't breathe, he holds air hostage.",
"Chuck Norris had a staring contest with Medusa, and won.",
"When life hands Chuck Norris lemons, he makes orange juice.",
"When Chuck Norris goes on a picnic, the ants bring him food.",
"Chuck Norris gives Freddy Krueger nightmares.",
"They once made a Chuck Norris toilet paper, but there was a problem: It wouldn't take shit from anybody.",
"Chuck Norris can punch a cyclops between the eyes.",
"Chuck Norris doesn't mow his lawn, he stands on the porch and dares it to grow",
"Chuck Norris put out a forest fire. using only gasoline",
"Chuck Norris CAN believe it's not butter.",
"Custom t-shirts provided by Spreadshirt"]
43 changes: 43 additions & 0 deletions backend/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
var logger = require('morgan'),
cors = require('cors'),
http = require('http'),
express = require('express'),
errorhandler = require('errorhandler'),
dotenv = require('dotenv'),
bodyParser = require('body-parser');

var app = express();

dotenv.load();

// Parsers
// old version of line
// app.use(bodyParser.urlencoded());
// new version of line
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());

app.use(function(err, req, res, next) {
if (err.name === 'StatusError') {
res.send(err.status, err.message);
} else {
next(err);
}
});

if (process.env.NODE_ENV === 'development') {
app.use(express.logger('dev'));
app.use(errorhandler())
}

app.use(require('./anonymous-routes'));
app.use(require('./protected-routes'));
app.use(require('./user-routes'));

var port = process.env.PORT || 3001;

http.createServer(app).listen(port, function (err) {
console.log('listening in http://localhost:' + port);
});

14 changes: 14 additions & 0 deletions backend/statusError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
function StatusError(msg, status) {
var err = Error.call(this, msg);
err.status = status;
err.name = 'StatusError';
return err;
}


StatusError.prototype = Object.create(Error.prototype, {
constructor: { value: StatusError }
});

module.exports = StatusError;

54 changes: 54 additions & 0 deletions backend/user-routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
var express = require('express'),
_ = require('lodash'),
config = require('./config'),
jwt = require('jsonwebtoken');

var app = module.exports = express.Router();

// XXX: This should be a database of users :).
var users = [{
id: 1,
username: 'gonto',
password: 'gonto'
}];

function createToken(user) {
return jwt.sign(_.omit(user, 'password'), config.secret, { expiresInMinutes: 60*5 });
}

app.post('/users', function(req, res) {
if (!req.body.username || !req.body.password) {
return res.status(400).send("You must send the username and the password");
}
if (_.find(users, {username: req.body.username})) {
return res.status(400).send("A user with that username already exists");
}

var profile = _.pick(req.body, 'username', 'password', 'extra');
profile.id = _.max(users, 'id').id + 1;

users.push(profile);

res.status(201).send({
id_token: createToken(profile)
});
});

app.post('/sessions/create', function(req, res) {
if (!req.body.username || !req.body.password) {
return res.status(400).send("You must send the username and the password");
}

var user = _.find(users, {username: req.body.username});
if (!user) {
return res.status(401).send("The username or password don't match");
}

if (!user.password === req.body.password) {
return res.status(401).send("The username or password don't match");
}

res.status(201).send({
id_token: createToken(user)
});
});
1 change: 0 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
<!-- styles -->
<link rel="stylesheet" type="text/css" href="/node_modules/bootstrap/dist/css/bootstrap.css">
<!-- Angular 2 -->
<script src="/lib/traceur-runtime.min.js"></script>
<script type="text/javascript" src="/node_modules/whatwg-fetch/fetch.js"></script>
<script type="text/javascript" src="/node_modules/jwt-decode/build/jwt-decode.js"></script>
</head>
Expand Down

0 comments on commit 78ecb66

Please sign in to comment.