Skip to content

Commit

Permalink
Merge branch 'master' of github.com:muety/anchr
Browse files Browse the repository at this point in the history
  • Loading branch information
muety committed Dec 30, 2021
2 parents f017eb8 + 669fc02 commit 0809d37
Show file tree
Hide file tree
Showing 17 changed files with 88 additions and 49 deletions.
16 changes: 8 additions & 8 deletions app/controllers/auth.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
const user = require('../models/user');

var express = require('express'),
router = express.Router(),
config = require('./../../config/config'),
authConfig = require('./../../config/auth'),
log = require('./../../config/middlewares/log')(),
morgan = require('../../config/middlewares/morgan'),
logger = require('./../../config/log')(),
auth = require('./../../config/middlewares/auth'),
utils = require('../../utils'),
Expand All @@ -31,7 +29,7 @@ var mail = function() {
module.exports = function (app, passport) {
app.use('/api/auth', router);

router.use(log);
router.use(morgan());

/**
* @swagger
Expand Down Expand Up @@ -65,7 +63,8 @@ module.exports = function (app, passport) {
res.status(201).end();
})
.catch(function (err) {
res.makeError(500, 'Failed to send confirmation mail.', err);
logger.error('Failed to send confirmation mail to user ' + user.local.email + ' - ' + err);
res.makeError(500, 'Failed to send confirmation mail.');
});
}, function (err) {
res.makeError(500, err.message);
Expand Down Expand Up @@ -196,7 +195,8 @@ module.exports = function (app, passport) {
user.save(function () {
res.redirect(config.clientUrl);
}, function(err) {
res.makeError(500, 'Failed to activate user', err);
logger.error('Failed to activate user by token ' + req.query.token + ' - ' + err);
res.makeError(500, 'Failed to activate user');
});
});
});
Expand Down Expand Up @@ -229,13 +229,13 @@ module.exports = function (app, passport) {
};

function initUser(user) {
Collection.findOne({ name: 'My shortlinks', owner: user._id }, function (err, result) {
Collection.findOne({ name: config.shortlinkCollectionName, owner: user._id }, function (err, result) {
if (err) return res.makeError(500, err.message, err);
if (result) return true;
else {
new Collection({
_id: utils.generateUUID(),
name: 'My shortlinks',
name: config.shortlinkCollectionName,
links: [],
owner: user._id,
shared: false
Expand Down
8 changes: 5 additions & 3 deletions app/controllers/collection.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
var express = require("express"),
router = express.Router(),
config = require("../../config/config"),
utils = require("../../utils"),
log = require("./../../config/middlewares/log")(),
morgan = require("./../../config/middlewares/morgan")(),
_ = require("underscore"),
auth = require("./../../config/middlewares/auth"),
mongoose = require("mongoose"),
Expand All @@ -14,7 +15,8 @@ var DEFAULT_PAGE_SIZE = 25;
module.exports = function (app, passport) {
app.use("/api/collection", router);
router.use(auth(passport));
router.use(log);

router.use(morgan);

/**
* @swagger
Expand Down Expand Up @@ -232,7 +234,7 @@ module.exports = function (app, passport) {

Collection.findOneAndUpdate(
{
name: "My shortlinks",
name: config.shortlinkCollectionName,
owner: req.user._id,
},
{
Expand Down
5 changes: 3 additions & 2 deletions app/controllers/image.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ var express = require('express'),
path = require('path'),
config = require('../../config/config'),
utils = require('../../utils'),
log = require('./../../config/middlewares/log')(),
morgan = require('./../../config/middlewares/morgan')(),
logger = require('./../../config/log')(),
_ = require('underscore'),
auth = require('./../../config/middlewares/auth'),
Expand All @@ -16,7 +16,8 @@ var express = require('express'),
module.exports = function (app, passport) {
app.use('/api/image', router);
app.use('/i', router);
router.use(log);

router.use(morgan);

/**
* @swagger
Expand Down
4 changes: 2 additions & 2 deletions app/controllers/metrics.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
var express = require('express'),
router = express.Router(),
log = require('./../../config/middlewares/log')(),
morgan = require('../../config/middlewares/morgan')(),
config = require('./../../config/config')
mongoose = require('mongoose'),
Collection = mongoose.model('Collection'),
Expand Down Expand Up @@ -153,7 +153,7 @@ module.exports = function(app) {
if (!config.exposeMetrics) return

app.use('/api/metrics', router);
router.use(log);
router.use(morgan);

initPromClient()

Expand Down
7 changes: 5 additions & 2 deletions app/controllers/remote.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@ var express = require('express'),
htmlparser = require('htmlparser2'),
cache = require('memory-cache'),
config = require('../../config/config'),
log = require('./../../config/middlewares/log')(),
morgan = require('../../config/middlewares/morgan')(),
logger = require('./../../config/log')(),
_ = require('underscore');

var CACHE_TIMEOUT = 1000 * 60 * 60 * 24;

module.exports = function(app) {
app.use('/api/remote', router);
router.use(log);

router.use(morgan);

/**
* @swagger
Expand Down Expand Up @@ -84,6 +86,7 @@ module.exports = function(app) {
var parser = new htmlparser.Parser(handler);
parser.parseComplete(response.data);
}).catch(function(err) {
logger.error('Failed to resolve title for URL ' + url + ' - ' + err)
return res.makeError(404, 'Not found');
});
});
Expand Down
4 changes: 2 additions & 2 deletions app/controllers/shared.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
var express = require("express"),
router = express.Router(),
log = require("./../../config/middlewares/log")(),
morgan = require("./../../config/middlewares/morgan")(),
_ = require("underscore"),
mongoose = require("mongoose"),
Collection = mongoose.model("Collection"),
Expand All @@ -10,7 +10,7 @@ var express = require("express"),
module.exports = function (app) {
app.use("/api/shared", router);

router.use(log);
router.use(morgan);

/**
* @swagger
Expand Down
23 changes: 19 additions & 4 deletions app/controllers/shortlink.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ var express = require('express'),
config = require('../../config/config'),
safeBrowseLookup = require('safe-browse-url-lookup'),
Shortlink = mongoose.model('Shortlink'),
Collection = mongoose.model('Collection'),
utils = require('../../utils'),
log = require('./../../config/middlewares/log')(),
morgan = require('./../../config/middlewares/morgan')(),
logger = require('./../../config/log')()
_ = require('underscore'),
auth = require('./../../config/middlewares/auth');
Expand All @@ -23,7 +24,8 @@ if (!config.googleApiKey) {
module.exports = function(app, passport) {
app.use('/api/shortlink', router);
app.use('/s', router);
router.use(log);

router.use(morgan);

/**
* @swagger
Expand All @@ -49,8 +51,21 @@ module.exports = function(app, passport) {

Shortlink.findOne({ _id: req.params.id }, { __v: false, id: false, createdBy: false, created: false }, function(err, obj) {
if (err || !obj) return res.makeError(404, "Not found.");
if (!asJson && obj.url) res.redirect(obj.url);
else res.send(obj.toObject());

if (!asJson && obj.url) {
// update counter asynchronously
var regex = new RegExp('.*' + req.params.id + '$', 'i')
Collection.findOneAndUpdate(
{ name: config.shortlinkCollectionName, 'links.url': regex },
{ $inc: { "links.$.hits": 1 } },
function(err, obj) {
console.log(1);
});

return res.redirect(obj.url);
}

res.send(obj.toObject());
});
});

Expand Down
21 changes: 16 additions & 5 deletions app/models/collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,28 @@ var mongoose = require('mongoose'),

var CollectionSchema = new Schema({
_id: String,
name: String,
created : Date,
modified : Date,
name: {
type: String,
required: true,
},
created: Date,
modified: Date,
links: [{
url: String,
description: String,
url: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
hits: Number,
date : Date,
}],
shared : Boolean,
owner: {
type: Schema.Types.ObjectId,
required: true,
ref: "UserSchema"
}
}, {
Expand Down
5 changes: 4 additions & 1 deletion app/models/shortlink.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ var mongoose = require('mongoose'),
utils = require('../../utils');

var ShortlinkSchema = new Schema({
url: String,
url: {
type: String,
required: true,
},
_id: String,
created : Date,
createdBy: {
Expand Down
1 change: 1 addition & 0 deletions config/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ var config = {
maxHtmlSizeKb: 1024,
imageProxyUrlTpl: process.env.ANCHR_IMAGE_PROXY_URL_TPL,
allowedFileTypes: ['image/'],
shortlinkCollectionName: process.env.ANCHR_SHORTLINK_COLLECTION || 'My shortlinks',
secret: process.env.ANCHR_SECRET || 'shhh',
tokenExpire: '7d',
workers: 2,
Expand Down
13 changes: 5 additions & 8 deletions config/middlewares/error.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
var log = require('./../log')();
var logger = require('./../log')();

module.exports = function () {
return function (req, res, next) {
res.makeError = function (code, message, fullError) {
if (fullError) log.default('req: %s %s %s %s %s %s %s', req.ip, req.method, req.originalUrl, (req.user ? ' ' + req.user._id : ''), code, fullError.message, fullError.stack);
else log.default('res: ', req.ip, req.method, req.originalUrl, (req.user ? ' ' + req.user._id : ''), code, message);

res.set('Connection', 'close');

this.status(code).send({ error:message, status:code });
res.makeError = function (code, message, err) {
logger.error('Error: ' + err ? err : message);
this.set('Connection', 'close');
this.status(code).send({ error: message, status: code });
};
next();
};
Expand Down
9 changes: 0 additions & 9 deletions config/middlewares/log.js

This file was deleted.

9 changes: 9 additions & 0 deletions config/middlewares/morgan.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const morgan = require('morgan');

morgan.token('user', function(req) {
return req.user ? req.user._id : null
})

module.exports = function () {
return morgan(':date[iso] :method :url :user :status :res[content-length] - :response-time ms')
};
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "anchr-multi-webservice",
"version": "2.0.1",
"version": "2.1.0",
"description": "⚓️ Anchr provides you with a toolbox for tiny tasks on the internet, especially bookmark collections",
"private": true,
"scripts": {
Expand All @@ -24,6 +24,7 @@
"memory-cache": "0.2.0",
"method-override": "3.0.0",
"mongoose": "^6.0.12",
"morgan": "^1.10.0",
"nodemailer": "^6.5.0",
"passport": "0.4.1",
"passport-facebook": "3.0.0",
Expand Down
2 changes: 2 additions & 0 deletions public/app/scripts/controllers/collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ angular.module('anchrClientApp')
description: result.description,
date: result.date
});
collectionsPagesCache = [];
}, function (err) {
Snackbar.show('Failed to save link: ' + err.data.error);
});
Expand All @@ -82,6 +83,7 @@ angular.module('anchrClientApp')
l.$delete(function (result) {
var c = $scope.getCollection(collId);
c.links.splice(findLinkInCollection(c, linkId), 1);
collectionsPagesCache = [];
}, function (err) {
Snackbar.show('Failed to delete link: ' + err.data.error);
});
Expand Down
5 changes: 4 additions & 1 deletion public/app/views/collection.html
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,10 @@ <h4 class="text-primary flex items-center">
<tbody>
<tr ng-repeat="l in getCollection(data.active).links | orderBy:'-date'">
<td class="td-link-container">
<a href="{{l.url}}" target="_blank">{{ l.url }}</a>
<div>
<a href="{{l.url}}" target="_blank">{{ l.url }}</a>
<small ng-if="l.hits" class="badge bg-primary collection-counter" title="Link was clicked {{l.hits}} times">{{l.hits}}</small>
</div>
<div class="text-small">({{ l.date | date : 'MMM d, y h:mm a' }})</div>
</td>
<td>{{ l.description || '–'}}</td>
Expand Down
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2750,7 +2750,7 @@ mongoose@^6.0.12:
sift "13.5.2"
sliced "1.0.1"

morgan@^1.9.1:
morgan@^1.10.0, morgan@^1.9.1:
version "1.10.0"
resolved "https://registry.yarnpkg.com/morgan/-/morgan-1.10.0.tgz#091778abc1fc47cd3509824653dae1faab6b17d7"
integrity sha512-AbegBVI4sh6El+1gNwvD5YIck7nSA36weD7xvIxG4in80j/UoK8AEGaWnnz8v1GxonMCltmlNs5ZKbGvl9b1XQ==
Expand Down

0 comments on commit 0809d37

Please sign in to comment.