Sotaro KARASAWA 9 лет назад
Родитель
Сommit
c56ad39be0
6 измененных файлов с 55 добавлено и 32 удалено
  1. 5 0
      lib/models/user.js
  2. 32 22
      lib/routes/attachment.js
  3. 3 3
      lib/routes/index.js
  4. 1 1
      lib/views/_form.html
  5. 8 4
      resource/js/crowi-form.js
  6. 6 2
      resource/js/crowi.js

+ 5 - 0
lib/models/user.js

@@ -258,6 +258,11 @@ module.exports = function(crowi) {
   };
 
   userSchema.statics.filterToPublicFields = function(user) {
+    debug('Filter', user);
+    if (typeof user !== 'object') {
+      return user;
+    }
+
     var filteredUser = {};
     var fields = USER_PUBLIC_FIELDS.split(' ');
     for (var i = 0; i < fields.length; i++) {

+ 32 - 22
lib/routes/attachment.js

@@ -9,30 +9,43 @@ module.exports = function(crowi, app) {
     , config = crowi.getConfig()
     , fs = require('fs')
     , fileUploader = require('../util/fileUploader')(crowi, app)
+    , ApiResponse = require('../util/apiResponse')
     , actions = {}
     , api = {};
 
   actions.api = api;
 
+  /**
+   * @api {get} /attachments.list Get attachments of the page
+   * @apiName ListAttachments
+   * @apiGroup Attachment
+   *
+   * @apiParam {String} page_id
+   */
   api.list = function(req, res){
-    var id = req.params.pageId;
+    var id = req.query.page_id || null;
+    if (!id) {
+      return res.json(ApiResponse.error('Parameters page_id is required.'));
+    }
 
     Attachment.getListByPageId(id)
     .then(function(attachments) {
-      res.json({
-        status: true,
-        data: {
-          attachments: attachments
-        }
-      });
+      return res.json(ApiResponse.success({
+        attachments: attachments
+      }));
     });
   };
 
   /**
+   * @api {post} /attachments.add Add attachment to the page
+   * @apiName AddAttachments
+   * @apiGroup Attachment
    *
+   * @apiParam {String} page_id
+   * @apiParam {File} file
    */
   api.add = function(req, res){
-    var id = req.params.pageId,
+    var id = req.body.page_id,
       path = decodeURIComponent(req.body.path),
       pageCreated = false,
       page = {};
@@ -42,10 +55,7 @@ module.exports = function(crowi, app) {
     var tmpFile = req.files.file || null;
     debug('Uploaded tmpFile: ', tmpFile);
     if (!tmpFile) {
-      return res.json({
-        status: false,
-        message: 'File error.'
-      });
+      return res.json(ApiResponse.error('File error.'));
     }
 
     new Promise(function(resolve, reject) {
@@ -80,22 +90,20 @@ module.exports = function(crowi, app) {
           return Attachment.create(id, req.user, filePath, originalName, fileName, fileType, fileSize);
         }).then(function(data) {
           var imageUrl = fileUploader.generateUrl(data.filePath);
-          return res.json({
-            status: true,
-            filename: imageUrl,
-            attachment: data,
+
+          page.creator = User.filterToPublicFields(page.creator);
+          data.creator = User.filterToPublicFields(data.creator);
+          return res.json(ApiResponse.success({
             page: page,
+            attachment: data,
+            filename: imageUrl,
             pageCreated: pageCreated,
-            message: 'Successfully uploaded.',
-          });
+          }));
         }).catch(function (err) {
           debug('Error on saving attachment data', err);
           // @TODO
           // Remove from S3
-          return res.json({
-            status: false,
-            message: 'Error while uploading.',
-          });
+          return res.json(ApiResponse.error('Error while uploading.'));
         }).finally(function() {
           fs.unlink(tmpPath, function (err) {
             if (err) {
@@ -104,6 +112,8 @@ module.exports = function(crowi, app) {
           });
         })
       ;
+    }).catch(function(err) {
+      return res.json(ApiResponse.error('Error.'));
     });
   };
 

+ 3 - 3
lib/routes/index.js

@@ -86,9 +86,6 @@ module.exports = function(crowi, app) {
   app.get( '/_api/check_username'     , user.api.checkUsername);
   app.post('/_api/me/picture/upload'  , loginRequired(crowi, app) , me.api.uploadPicture);
   app.get( '/_api/user/bookmarks'     , loginRequired(crowi, app) , user.api.bookmarks);
-  app.get( '/_api/attachment/page/:pageId', loginRequired(crowi, app) , attachment.api.list);
-  app.post('/_api/attachment/page/:pageId', loginRequired(crowi, app) , attachment.api.add);
-  app.post('/_api/attachment/:id/remove',loginRequired(crowi, app), attachment.api.remove);
 
   app.get( '/user/:username([^/]+)/bookmarks'      , loginRequired(crowi, app) , page.userBookmarkList);
   app.get( '/user/:username([^/]+)/recent-create'  , loginRequired(crowi, app) , page.userRecentCreatedList);
@@ -109,6 +106,9 @@ module.exports = function(crowi, app) {
   app.post('/_api/bookmarks.remove'   , accessTokenParser(crowi, app) , loginRequired(crowi, app) , csrf, bookmark.api.remove);
   app.post('/_api/likes.add'          , accessTokenParser(crowi, app) , loginRequired(crowi, app) , csrf, page.api.like);
   app.post('/_api/likes.remove'       , accessTokenParser(crowi, app) , loginRequired(crowi, app) , csrf, page.api.unlike);
+  app.get( '/_api/attachments.list'   , accessTokenParser(crowi, app) , loginRequired(crowi, app) , attachment.api.list);
+  app.post('/_api/attachments.add'    , accessTokenParser(crowi, app) , loginRequired(crowi, app) , csrf, attachment.api.add);
+  app.post('/_api/attachments.remove' , accessTokenParser(crowi, app) , loginRequired(crowi, app) , csrf, attachment.api.remove);
 
   app.get( '/_api/revisions.get'      , accessTokenParser(crowi, app) , loginRequired(crowi, app) , revision.api.get);
   app.get( '/_api/revisions.list'     , accessTokenParser(crowi, app) , loginRequired(crowi, app) ,revision.api.list);

+ 1 - 1
lib/views/_form.html

@@ -49,7 +49,7 @@
           {% endfor %}
         </select>
         {% endif %}
-        <input type="hidden" name="_csrf" value="{{ csrf() }}">
+        <input type="hidden" id="edit-form-csrf" name="_csrf" value="{{ csrf() }}">
         <input type="submit" class="btn btn-primary" id="edit-form-submit" value="ページを更新" />
       </div>
     </div>

+ 8 - 4
resource/js/crowi-form.js

@@ -409,11 +409,14 @@ $(function() {
 
   var $inputForm = $('form.uploadable textarea#form-body');
   if ($inputForm.length > 0) {
+    var csrfToken = $('form.uploadable input#edit-form-csrf').val();
     var pageId = $('#content-main').data('page-id') || 0;
     var attachmentOption = {
-      uploadUrl: '/_api/attachment/page/' + pageId,
+      uploadUrl: '/_api/attachments.add',
       extraParams: {
-        path: location.pathname
+        path: location.pathname,
+        page_id: pageId,
+        _csrf: csrfToken
       },
       progressText: '(Uploading file...)',
       urlText: "\n![file]({filename})\n"
@@ -421,8 +424,9 @@ $(function() {
 
     attachmentOption.onFileUploadResponse = function(res) {
       var result = JSON.parse(res.response);
+      console.log(result);
 
-      if (result.status && result.pageCreated) {
+      if (result.ok && result.pageCreated) {
         var page = result.page,
             pageId = page._id;
 
@@ -431,7 +435,7 @@ $(function() {
 
         unbindInlineAttachment($inputForm);
 
-        attachmentOption.uploadUrl = '/_api/attachment/page/' + pageId,
+        attachmentOption.extraParams.page_id = pageId;
         bindInlineAttachment($inputForm, attachmentOption);
       }
       return true;

+ 6 - 2
resource/js/crowi.js

@@ -559,8 +559,12 @@ $(function() {
 
     // attachment
     var $pageAttachmentList = $('.page-attachments ul');
-    $.get('/_api/attachment/page/' + pageId, function(res) {
-      var attachments = res.data.attachments;
+    $.get('/_api/attachments.list', {page_id: pageId}, function(res) {
+      if (!res.ok) {
+        return ;
+      }
+
+      var attachments = res.attachments;
       if (attachments.length > 0) {
         $.each(attachments, function(i, file) {
           $pageAttachmentList.append(