Skip to content

Commit

Permalink
Added starter files for mod5, hello world to mod2
Browse files Browse the repository at this point in the history
  • Loading branch information
hwz committed Feb 18, 2015
1 parent 4c2a706 commit 071e580
Show file tree
Hide file tree
Showing 15 changed files with 379 additions and 4 deletions.
2 changes: 1 addition & 1 deletion module-2/completed/public/register.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ <h2>Register</h2>
<p class="text-warning">{{error_message}}</p>
<input type="username" ng-model="user.username" placeholder="Username" class="form-control"><br>
<input type="password" ng-model="user.password" placeholder="Password" class="form-control"><br>
<input type="submit" value="Log in" class="btn btn-primary" />
<input type="submit" value="Register" class="btn btn-primary" />
</form>
10 changes: 10 additions & 0 deletions module-2/helloworld.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script>
</head>
<body>
<input type="text" ng-model="inputText" placeholder="World" />
<h1>Hello {{inputText}}</h1>

</body>
</html>
4 changes: 2 additions & 2 deletions module-2/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ The only differences between `login.html` and `register.html` should be the form
<p class="text-warning">{{error_message}}</p>
<input type="username" ng-model="user.username" placeholder="Username" class="form-control"><br>
<input type="password" ng-model="user.password" placeholder="Password" class="form-control"><br>
<input type="submit" value="Log in" class="btn btn-primary" />
<input type="submit" value="Register" class="btn btn-primary" />
</form>
</div>
</body>
Expand Down Expand Up @@ -333,7 +333,7 @@ We can transform our `main.html`, `login.html`, and `register.html` into simple
<p class="text-warning">{{error_message}}</p>
<input type="username" ng-model="user.username" placeholder="Username" class="form-control"><br>
<input type="password" ng-model="user.password" placeholder="Password" class="form-control"><br>
<input type="submit" value="Log in" class="btn btn-primary" />
<input type="submit" value="Register" class="btn btn-primary" />
</form>
```

Expand Down
2 changes: 1 addition & 1 deletion module-5/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ We'll then add `current_user` to `newPost` before we send it to the backend. We'
$scope.post = function() {
$scope.newPost.created_by = $rootScope.current_user;
$scope.newPost.created_at = Date.now();
postService.save($scope.newPost}, function(){
postService.save($scope.newPost, function(){
$scope.posts = postService.query();
$scope.newPost = {created_by: '', text: '', created_at: ''};
});
Expand Down
Binary file added module-5/start/.DS_Store
Binary file not shown.
73 changes: 73 additions & 0 deletions module-5/start/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
//initialize mongoose schemas
require('./models/models');
var api = require('./routes/api');
var authenticate = require('./routes/authenticate')(passport);
var mongoose = require('mongoose'); //add for Mongo support
mongoose.connect('mongodb://localhost/test-chirp'); //connect to Mongo
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(session({
secret: 'keyboard cat'
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(passport.session());

app.use('/auth', authenticate);
app.use('/api', api);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

//// Initialize Passport
var initPassport = require('./passport-init');
initPassport(passport);

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});


module.exports = app;
9 changes: 9 additions & 0 deletions module-5/start/bin/www
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/usr/bin/env node
var debug = require('debug')('Start');
var app = require('../app');

app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
18 changes: 18 additions & 0 deletions module-5/start/models/models.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var postSchema = new mongoose.Schema({
created_by: String, //should be changed to ObjectId, ref "User"
created_at: {type: Date, default: Date.now},
text: String
});

var userSchema = new mongoose.Schema({
username: String,
password: String, //hash created from password
created_at: {type: Date, default: Date.now}
})


mongoose.model('Post', postSchema);
mongoose.model('User', userSchema);
22 changes: 22 additions & 0 deletions module-5/start/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "Start",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"bcrypt-nodejs": "0.0.3",
"body-parser": "~1.8.1",
"cookie-parser": "~1.3.3",
"debug": "^2.0.0",
"ejs": "~0.8.5",
"express": "~4.9.0",
"express-session": "^1.10.3",
"mongoose": "^3.8.23",
"morgan": "~1.3.0",
"passport": "^0.2.1",
"passport-local": "^1.0.0",
"serve-favicon": "~2.1.3"
}
}
95 changes: 95 additions & 0 deletions module-5/start/passport-init.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
var mongoose = require('mongoose');
var User = mongoose.model('User');
var LocalStrategy = require('passport-local').Strategy;
var bCrypt = require('bcrypt-nodejs');

module.exports = function(passport){

// Passport needs to be able to serialize and deserialize users to support persistent login sessions
passport.serializeUser(function(user, done) {
console.log('serializing user:',user.username);
done(null, user._id);
});

passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
console.log('deserializing user:',user.username);
done(err, user);
});
});

passport.use('login', new LocalStrategy({
passReqToCallback : true
},
function(req, username, password, done) {
// check in mongo if a user with username exists or not
User.findOne({ 'username' : username },
function(err, user) {
// In case of any error, return using the done method
if (err)
return done(err);
// Username does not exist, log the error and redirect back
if (!user){
console.log('User Not Found with username '+username);
return done(null, false);
}
// User exists but wrong password, log the error
if (!isValidPassword(user, password)){
console.log('Invalid Password');
return done(null, false); // redirect back to login page
}
// User and password both match, return user from done method
// which will be treated like success
return done(null, user);
}
);
}
));

passport.use('signup', new LocalStrategy({
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) {

// find a user in mongo with provided username
User.findOne({ 'username' : username }, function(err, user) {
// In case of any error, return using the done method
if (err){
console.log('Error in SignUp: '+err);
return done(err);
}
// already exists
if (user) {
console.log('User already exists with username: '+username);
return done(null, false);
} else {
// if there is no user, create the user
var newUser = new User();

// set the user's local credentials
newUser.username = username;
newUser.password = createHash(password);

// save the user
newUser.save(function(err) {
if (err){
console.log('Error in Saving user: '+err);
throw err;
}
console.log(newUser.username + ' Registration succesful');
return done(null, newUser);
});
}
});
})
);

var isValidPassword = function(user, password){
return bCrypt.compareSync(password, user.password);
};
// Generates hash using bCrypt
var createHash = function(password){
return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
};

};
8 changes: 8 additions & 0 deletions module-5/start/public/stylesheets/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
body {
padding: 50px;
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}

a {
color: #00B7FF;
}
90 changes: 90 additions & 0 deletions module-5/start/routes/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
var express = require('express');
var router = express.Router();
var mongoose = require( 'mongoose' );
var Post = mongoose.model('Post');
//Used for routes that must be authenticated.
function isAuthenticated (req, res, next) {
// if user is authenticated in the session, call the next() to call the next request handler
// Passport adds this method to request object. A middleware is allowed to add properties to
// request and response objects

//allow all get request methods
if(req.method === "GET"){
return next();
}
if (req.isAuthenticated()){
return next();
}

// if the user is not authenticated then redirect him to the login page
return res.redirect('/#login');
};

//Register the authentication middleware
router.use('/posts', isAuthenticated);

router.route('/posts')
//creates a new post
.post(function(req, res){

var post = new Post();
post.text = req.body.text;
post.created_by = req.body.created_by;
post.save(function(err, post) {
if (err){
return res.send(500, err);
}
return res.json(post);
});
})
//gets all posts
.get(function(req, res){
console.log('debug1');
Post.find(function(err, posts){
console.log('debug2');
if(err){
return res.send(500, err);
}
return res.send(200,posts);
});
});

//post-specific commands. likely won't be used
router.route('/posts/:id')
//gets specified post
.get(function(req, res){
Post.findById(req.params.id, function(err, post){
if(err)
res.send(err);
res.json(post);
});
})
//updates specified post
.put(function(req, res){
Post.findById(req.params.id, function(err, post){
if(err)
res.send(err);

post.created_by = req.body.created_by;
post.text = req.body.text;

post.save(function(err, post){
if(err)
res.send(err);

res.json(post);
});
});
})
//deletes the post
.delete(function(req, res) {
Post.remove({
_id: req.params.id
}, function(err) {
if (err)
res.send(err);
res.json("deleted :(");
});
});

module.exports = router;
Loading

0 comments on commit 071e580

Please sign in to comment.