-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
55 lines (46 loc) · 1.55 KB
/
index.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
module.exports = function(subdomain, app, fn){
if(!subdomain || typeof subdomain !== "string") {
throw new Error("The first parameter must be a string representing the subdomain")
}
//check fn handles three params..
if(!fn || typeof fn !== "function" || fn.length < 3) {
throw new Error("The second parameter must be a function that handles fn(req, res, next) params.")
}
// The middleware
return function(req, res, next){
var isSecondLevelDomain = (req.hostname.match(/\./g) || []).length >= 2 ? true : false
if(isSecondLevelDomain) {
app.set('subdomain offset', 3)
}
var givenSubdomains = subdomain.split('.').reverse()
var match = false, matchByAsterisk = false
givenSubdomains.every((sd, i) => {
sd = sd.toLocaleLowerCase()
if (typeof req.subdomains[i] == 'undefined'){
//match = false
return false
}
else{
var actual = req.subdomains[i].toLocaleLowerCase()
}
if (sd == '*'){
match = true
matchByAsterisk = true
}
else{
match = sd == actual
matchByAsterisk = false
}
return match
})
if (req.subdomains.length > givenSubdomains.length && !matchByAsterisk){
match = false
}
if (match){
fn(req, res, next)
}
else{
next()
}
}
}