Skip to content
Browse files

Implemented posts creation, delete, update and read in the admin page.

  • Loading branch information...
1 parent 4b3c458 commit b987c07644375991898acacc9ee6db19c7ea0f84 @pedrofranceschi pedrofranceschi committed
View
94 blogode.js
@@ -16,12 +16,12 @@ app.configure(function() {
});
var posts = require('./lib/posts');
-var admin = require('./lib/admin');
+var users = require('./lib/users');
app.get("/", function(req, res){
// return posts list
- posts.getPosts(function (posts){
+ posts.getPosts(10, function (posts){
res.render('index', {
locals: { 'posts': posts }
});
@@ -31,11 +31,11 @@ app.get("/", function(req, res){
app.get("/admin", function(req, res){
// return admin panel
- if(!req.session.admin_username) {
+ if(!req.session.username) {
return res.redirect("/admin/login");
}
- res.render('admin_panel', {
+ res.render('admin/panel', {
layout: false
});
});
@@ -44,11 +44,11 @@ app.get("/admin", function(req, res){
app.get("/admin/login", function(req, res){
// return admin login page
- if(req.session.admin_username) {
+ if(req.session.username) {
return res.redirect("/admin")
}
- res.render('admin_login', {
+ res.render('admin/login', {
layout: false
});
});
@@ -60,13 +60,89 @@ app.post("/admin/authenticate", function(req, res){
res.redirect('/admin/login')
}
- admin.verifyCredentials(req.param('username'), req.param('password'), function(isAdmin){
- if(isAdmin) {
- req.session.admin_username = req.param('username')
+ users.verifyCredentials(req.param('username'), req.param('password'), function(isValidUser, userId){
+ if(isValidUser) {
+ req.session.username = req.param('username');
+ req.session.user_id = userId;
}
res.redirect("/admin");
});
});
+app.get('/admin/posts', function(req, res) {
+ // return the list of posts (as admin)
+
+ if(!req.session.username) {
+ return res.redirect("/admin/login")
+ }
+ posts.getPosts(0, function (posts){
+ res.render('admin/posts/index', {
+ layout: false,
+ locals: { 'posts': posts }
+ });
+ });
+});
+
+app.get('/admin/posts/new', function(req, res) {
+ // return the formulary to create a new post
+
+ if(!req.session.username) {
+ return res.redirect("/admin/login")
+ }
+ res.render('admin/posts/new', {
+ layout: false
+ });
+});
+
+app.get('/admin/posts/:id', function(req, res) {
+ // return a post (to edit)
+
+ if(!req.session.username) {
+ return res.redirect("/admin/login")
+ }
+ posts.getPost(req.param('id'), function (post){
+ res.render('admin/posts/edit', {
+ layout: false,
+ locals: { 'post': post }
+ });
+ });
+});
+
+app.post('/admin/posts/save', function(req, res) {
+ if(!req.session.username) {
+ return res.redirect("/admin/login")
+ }
+ if(!req.param('title') || !req.param('body')) {
+ return res.redirect("/admin/posts/new");
+ }
+ posts.createPost(req.param('title'), req.param('body'), req.session.user_id, function(postId) {
+ return res.redirect('/admin/posts/' + postId);
+ });
+});
+
+app.post('/admin/posts/update', function(req, res) {
+ if(!req.session.username) {
+ return res.redirect("/admin/login")
+ }
+ if(!req.param('title') || !req.param('body')) {
+ return res.redirect("/admin/posts/new");
+ }
+ posts.updatePost(req.param('id'), req.param('title'), req.param('body'), function() {
+ return res.redirect('/admin/posts/' + req.param('id'));
+ });
+});
+
+app.get('/admin/posts/destroy/:id', function(req, res) {
+ if(!req.session.username) {
+ return res.redirect("/admin/login")
+ }
+ if(!req.param('id')) {
+ return res.redirect("/admin/posts/");
+ }
+ posts.destroyPost(req.param('id'), function () {
+ return res.redirect('/admin/posts/')
+ });
+});
+
app.listen(3000);
console.log("Server on port %s", app.address().port);
View
4 lib/database.js
@@ -19,8 +19,8 @@ exports.getDatabaseConnection = function(callback) {
}
exports._createTables = function(mysql_client, callback) {
- mysql_client.query("CREATE TABLE IF NOT EXISTS posts (id INT PRIMARY KEY AUTO_INCREMENT, author_id INT, title varchar(200), body text, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);")
- mysql_client.query("CREATE TABLE IF NOT EXISTS admins (id INT PRIMARY KEY AUTO_INCREMENT, name varchar(100), description varchar(500), email varchar(100), username varchar(100), password varchar(100), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);")
+ mysql_client.query("CREATE TABLE IF NOT EXISTS posts (id INT PRIMARY KEY AUTO_INCREMENT, user_id INT, title varchar(200), body text, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);")
+ mysql_client.query("CREATE TABLE IF NOT EXISTS users (id INT PRIMARY KEY AUTO_INCREMENT, name varchar(100), description varchar(500), email varchar(100), username varchar(100), password varchar(100), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);")
callback();
}
View
84 lib/posts.js
@@ -1,13 +1,91 @@
var sys = require('sys'),
database = require('./database.js');
-exports.getPosts = function(callback) {
+exports.getPosts = function(numberOfPosts, callback) {
+ var limitString = "";
+
+ if(numberOfPosts != 0) {
+ limitString = "LIMIT " + numberOfPosts;
+ }
+
database.getDatabaseConnection(function (mysql_client) {
- mysql_client.query("SELECT * FROM posts ORDER BY id DESC LIMIT 10;", function (error, results, fields) {
+ mysql_client.query("SELECT * FROM posts ORDER BY id DESC " + limitString + ";", function (error, results, fields) {
if(error) {
throw "Error getting posts: " + error;
}
- callback(results);
+ mysql_client.query("SELECT * FROM users;", function (error1, results1, fields1) {
+ if(error1) {
+ throw "Error getting posts' authors: " + error1;
+ }
+ var posts = new Array();
+ for (var i=0; i < results.length; i++) {
+ var postInfo = results[i];
+ var authorName = "";
+
+ for (var j=0; j < results1.length; j++) {
+ if(results1[j].id == postInfo.user_id) {
+ authorName = results1[j].name;
+ break;
+ }
+ }
+
+ postInfo['user_name'] = authorName;
+ posts.push(postInfo);
+ }
+ callback(posts);
+ });
+ });
+ });
+}
+
+exports.getPost = function(postId, callback) {
+ database.getDatabaseConnection(function (mysql_client) {
+ mysql_client.query("SELECT * FROM posts WHERE id = '" + escape(postId) + "';", function (error, results, fields) {
+ if(error) {
+ throw "Error getting post: " + error;
+ }
+ mysql_client.query("SELECT * FROM users WHERE id='" + escape(results[0].user_id) + "';", function (error1, results1, fields1) {
+ if(error1) {
+ throw "Error getting post's author: " + error1;
+ }
+ var postInfo = results[0]
+ postInfo['user_name'] = results1[0].name;
+
+ callback(postInfo);
+ });
+ });
+ });
+}
+
+exports.createPost = function(title, body, user_id, callback) {
+ database.getDatabaseConnection(function (mysql_client) {
+ mysql_client.query("INSERT INTO posts (title, body, user_id) VALUES ('" + escape(title) + "', '" + escape(body) + "', " + user_id + ");", function (error, results, fields) {
+ if(error) {
+ throw "Error creating post: " + error;
+ }
+ callback(results.insertId);
+ });
+ });
+}
+
+exports.updatePost = function(id, title, body, callback) {
+ database.getDatabaseConnection(function (mysql_client) {
+ mysql_client.query("UPDATE posts SET title='" + escape(title) + "', body='" + escape(body) + "' WHERE id='" + escape(id) + "';", function (error, results, fields) {
+ if(error) {
+ throw "Error creating post: " + error;
+ }
+ callback();
+ });
+ });
+}
+
+exports.destroyPost = function(id, callback) {
+ database.getDatabaseConnection(function (mysql_client) {
+ mysql_client.query("DELETE FROM posts WHERE id='" + escape(id) + "';", function (error, results, fields) {
+ if(error) {
+ throw "Error creating post: " + error;
+ }
+ callback();
});
});
}
View
7 lib/admin.js → lib/users.js
@@ -3,15 +3,14 @@ var sys = require('sys'),
exports.verifyCredentials = function(username, password, callback) {
database.getDatabaseConnection(function (mysql_client) {
- mysql_client.query("SELECT * FROM admins WHERE username='" + escape(username) + "' AND password='" + escape(password) + "';", function (error, results, fields) {
+ mysql_client.query("SELECT * FROM users WHERE username='" + escape(username) + "' AND password='" + escape(password) + "';", function (error, results, fields) {
if(error) {
throw "Error verifying credentials: " + error;
}
- var isAdmin = false;
if(results.length > 0) {
- isAdmin = true;
+ callback(true, results[0].id);
}
- callback(isAdmin);
+ callback(false, -1);
});
});
}
View
0 views/admin_login.ejs → views/admin/login.ejs
File renamed without changes.
View
3 views/admin/panel.ejs
@@ -0,0 +1,3 @@
+Admin panel.<br/><br/>
+
+<a href="/admin/posts">Manage posts</a>
View
7 views/admin/posts/edit.ejs
@@ -0,0 +1,7 @@
+<form method="post" action="/admin/posts/update" id="createRoomForm">
+ <h1>Edit Post</h1>
+ Title: <input type="text" name="title" size="62" value="<%= unescape(post.title) %>"></input><br/>
+ Body:<br/> <textarea name="body" rows="20" cols="50"><%= unescape(post.body) %></textarea><br/><br/>
+ <input type="hidden" name="id" value="<%= post.id %>"/><br/>
+ <input type="submit" value="Update" />
+</form>
View
7 views/admin/posts/index.ejs
@@ -0,0 +1,7 @@
+<h1>Manage posts</h1>
+
+<% for (var i=0; i < posts.length; i++) { %>
+ <b><%= unescape(posts[i].title) %></b> (by <%= posts[i].user_name %>) - <a href="/admin/posts/<%= posts[i].id %>">Edit</a> - <a href="/admin/posts/destroy/<%= posts[i].id %>">Delete</a><br/><br/>
+<% } %>
+
+<a href="/admin/posts/new">New post</a>
View
6 views/admin/posts/new.ejs
@@ -0,0 +1,6 @@
+<form method="post" action="/admin/posts/save" id="createRoomForm">
+ <h1>New Post</h1>
+ Title: <input type="text" name="title" size="62"/><br/>
+ Body:<br/> <textarea name="body" rows="20" cols="50"></textarea><br/><br/>
+ <input type="submit" value="Submit" />
+</form>
View
1 views/admin_panel.ejs
@@ -1 +0,0 @@
-Admin panel.
View
5 views/index.ejs
@@ -1,4 +1,5 @@
<% for (var i=0; i < posts.length; i++) { %>
- <h2><%= posts[i].title %></h2>
- <p><%= posts[i].body %></p><br/>
+ <h2><%= unescape(posts[i].title) %></h2>
+ <p>by <%= posts[i].user_name %></p>
+ <p><%= unescape(posts[i].body) %></p><br/>
<% } %>

0 comments on commit b987c07

Please sign in to comment.
Something went wrong with that request. Please try again.