Mikael's blog

A developers sixth time trying to maintain a blog

Source Code - Root / controllers / adminController.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
/*****************************************
 *   Admin Controller
 *****************************************
 *   Author:  mikael.lofjard@gmail.com
 *   Website: http://lofjard.se
 *   License: MIT License
 ****************************************/
  
var AdminController = (function() {
  
  var querystring = require('querystring');
  var fs = require('fs');
  var path = require('path');
  
  var viewManager = require('../viewManager').ViewManager;
  var responseManager = require('../responseManager').ResponseManager;
  var cacheManager = require('../cacheManager').CacheManager;
  var env = require('../environmentManager').EnvironmentManager;
  var misc = require('../misc').Misc;
  
  var db = null;
  var uploadPath = null;
  
  function checkAuthorization(request, response) {
    var authorized = (request.headers['x-lofjard-blog-ssl'] == 'SUCCESS');
    if (authorized) {
      return true;
    } else {
      response.writeHead(401, { "Content-Type" : "text/html" });
      response.end("401 Unauthorized: I don't think you are who you claim to be, or you aren't who I want you to be. What you are is a person without the proper credentials.");
      return false;
    }
  }
  
  function evalUnEscape (val) {
    eval('val = "'+val+'"');
    return val;
  }
  
  function getCurrentUser(request) {
    var dn = request.headers['x-lofjard-blog-dn'];
    if (typeof(dn) != 'undefined') {
      var user = dn.replace(/.+\/CN=(.+?)\/.+/, "$1");
      // unescape encoded user
      var user = evalUnEscape(user);
      // double decode utf-8
      var user = decodeURIComponent(escape(decodeURIComponent(escape(user))));
      return user;
    }
    return 'Unauthorized';
  }
  
  return {
  
    init: function(dbInit, uploadPathInit) {
      db = dbInit;
      uploadPath = uploadPathInit;
    },
  
    index: function(request, response) {
      if (checkAuthorization(request, response)) {
        db.view('drafts/byDateTime', { descending: true }, function (err, doc) {
          if (err) {
            env.info("CouchDB: DB Read error");
            response.writeHead(500, { "Content-Type" : "text/html" });
            response.end("500 Internal server error. CouchDB error.");
            return;
          }
  
  
          var adminData = {};
          adminData.currentUser = getCurrentUser(request);
          adminData.drafts = new Array();
          for (var i in doc) {
            doc[i].value.readableDateTime = misc.prettyDate(doc[i].key);
            doc[i].value.docId = doc[i].id;
            adminData.drafts.push(doc[i].value);
          }
  
          var responseData = viewManager.renderView(response, 'admin', adminData);
          responseManager.writeResponse(request, response, responseData, true);
          return;
        });
      }
    },
  
    getPostAsJson: function(request, response) {
      if (checkAuthorization(request, response)) {
  
        var docId = request.params.id;
  
        db.get(docId, function (err, doc) {
          var headers =  { "Content-Type" : "application/json;charset=utf-8" }
          var responseData = { headers : headers, content: JSON.stringify(doc) }
          responseManager.writeResponse(request, response, responseData, true);
        });
      }
    },
  
    upload: function(request, response) {
      request.setEncoding('binary');
      var postData = '';
  
      request.addListener('data', function (postDataChunk) {
        //console.log('Handler: Post data recieved.');
        postData += postDataChunk;
      });
  
      request.addListener('end', function () {
  
        var ending = request.headers['x-file-name'];
        ending = ending.substring(ending.length - 3, ending.length);
        var newFileName = misc.getGuid() + '.' + ending;
  
        fs.writeFile(path.join(uploadPath, newFileName), postData, { encoding: 'binary' }, function(err) {
          if (err) {
            response.writeHead(500);
            response.write("File write error.");
            response.end();
          } else {
            response.writeHead(200, 'application/json');
            response.write(JSON.stringify( { filename: newFileName } ));
            response.end();
          }
        })
      });
    },
  
    submitPost: function(request, response) {
      if (checkAuthorization(request, response)) {  
        request.setEncoding('utf8');
        var postData = '';
  
        request.addListener('data', function (postDataChunk) {
          //console.log('Handler: Post data recieved.');
          postData += postDataChunk;
        });
  
        request.addListener('end', function () {
          var data = querystring.parse(postData);
  
          // validate here if needed
          if (data.pictureAltText === '') data.pictureAltText = null;
          if (data.pictureSubText === '') data.pictureSubText = null;
          if (data.pictureURL === '') data.pictureURL = null;
  
          // transform post data to blogpost
          var blogpost = {};
          blogpost.type = "blogpost";
          blogpost.author = data.author;
          blogpost.dateTime = data.dateTime;
          blogpost.htmlContent = data.htmlContent;
          blogpost.pictureAltText = data.pictureAltText;
          blogpost.pictureSubText = data.pictureSubText;
          blogpost.pictureURL = data.pictureURL;
          blogpost.published = (data.published === 'true'); // simple string to bool conversion
          blogpost.readableKey = data.readableKey;
          blogpost.title = data.title;
          blogpost.tags = data.tags.split(',');
  
          //write to db
          if (data.docId === '0')
          {
            env.info("Admin Controller: Saving new blogpost");
            db.save(blogpost, function (err, res) {
              if (err) {
                env.info("CouchDB: Error saving blogpost");
                response.writeHead(500, { "Content-Type" : "text/html" });
                response.end("500 Internal server error. CouchDB error.");
                return;
              }
              cacheManager.clearOnNewPost();
  
              //return json
              response.writeHead(200, { "Content-Type" : "application/json" });
              response.end('{ "success" : "ok", "id" : "' + res.id + '" }');
              return;
            });
          } else {
            console.log("Admin Controller: Updating blogpost with id " + data.docId);
            db.save(data.docId, blogpost, function (err, res) {
              if (err) {
                env.info("CouchDB: Error updating blogpost");
                response.writeHead(500, { "Content-Type" : "text/html" });
                response.end("500 Internal server error. CouchDB error.");
                return;
              }
  
              cacheManager.clearOnEditPost('/post/' + blogpost.readableKey);
  
              //return json
              response.writeHead(200, { "Content-Type" : "application/json" });
              response.end('{ "success" : "ok", "id" : "' + res.id + '" }');
              return;
            });
          }
          return;
        }); 
      }
    }
  };
  
}());
  
typeof(exports) != 'undefined' ? exports.AdminController = AdminController : null;