-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth-urlmatcher.js
80 lines (70 loc) · 1.76 KB
/
auth-urlmatcher.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
'use strict'
// external modules
var _ = require('lodash')
var Gex = require('gex')
module.exports = function (options) {
var seneca = this
function urlmatcher (args, done) {
var spec = args.spec
spec = _.isArray(spec) ? spec : [spec]
var checks = []
_.each(spec, function (path) {
if (_.isFunction(path)) {
checks.push(path)
return
}
if (_.isRegExp(path)) {
checks.push(function (req) {
return path.test(req.url)
})
return
}
if (!_.isString(path)) return done()
path = ~path.indexOf(':') ? path : 'prefix:' + path
var parts = path.split(':')
var kind = parts[0]
var spec = parts.slice(1)
function regex () {
var pat = spec
var mod = ''
var re
var m = /^\/(.*)\/([^\/]*)$/.exec(spec)
if (m) {
pat = m[1]
mod = m[2]
re = new RegExp(pat, mod)
return function (req) {
return re.test(req.url)
}
}
else {
return function () {
return false
}
}
}
var pass = {
prefix: function (req) {
return Gex(spec + '*').on(req.url)
},
suffix: function (req) {
return Gex('*' + spec).on(req.url)
},
contains: function (req) {
return Gex('*' + spec + '*').on(req.url)
},
gex: function (req) {
return Gex(spec).on(req.url)
},
exact: function (req) {
return spec === req.url
},
regex: regex()
}
pass.re = pass.regexp = pass.regex
checks.push(pass[kind])
})
return done(null, checks)
}
seneca.add({role: 'auth', cmd: 'urlmatcher'}, urlmatcher)
}