-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.js
More file actions
75 lines (55 loc) · 1.53 KB
/
index.js
File metadata and controls
75 lines (55 loc) · 1.53 KB
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
var duplex = require("duplex")
, BufferStream = require("buffer-stream")
, env = process.env
module.exports = Auth
function Auth(first, second, third) {
if (typeof first === "string") {
return AuthClient(first, second, third)
}
return AuthServer(first, second)
}
function AuthClient(user, pass, stream) {
var auth = BufferStream().buffer()
stream.write(user + ":" + pass)
stream.on("data", isOpen)
return auth
function isOpen(data) {
var msg = data.toString()
if (msg === "open") {
return auth.empty(stream)
}
var parts = msg.split(":")
if (parts[0] === "error") {
auth.emit("error", new Error(parts[1]))
}
}
}
function AuthServer(stream, authorize) {
var auth = duplex()
, open = false
authorize = authorize || defaultAuthorize
auth.on("write", onWrite)
return auth
function onWrite(data) {
if (open) {
return stream.write(data)
}
var parts = data.toString().split(":")
, user = parts[0]
, pass = parts[1]
var success = authorize(user, pass)
if (success === true) {
open = true
auth.sendData("open")
stream.on("data", forward)
} else {
auth.sendData("error:" + success)
}
}
function forward(data) {
auth.sendData(data)
}
}
function defaultAuthorize(user, pass) {
return user === env.AUTH_STREAM_USER && pass === env.AUTH_STREAM_PASS
}