This repository has been archived by the owner on Sep 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
app.js
234 lines (208 loc) · 7.79 KB
/
app.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/*
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, nomen: true, node: true, indent: 4, maxerr: 50 */
"use strict";
// Required modules
var express = require("express"),
path = require("path"),
fs = require("fs"),
http = require("http"),
https = require("https"),
url = require("url"),
passport = require("passport"),
GitHubStrategy = require("passport-github").Strategy,
repository = require("./lib/repository"),
routes = require("./lib/routes"),
downloadData = require("./lib/downloadData"),
logging = require("./lib/logging"),
_ = require("lodash"),
constants = require("constants"),
request = require("request");
// Load cert and secret configuration
var config = JSON.parse(fs.readFileSync(path.resolve(__dirname, "config/config.json"))),
key,
cert,
ca,
caPathList;
config.hostname = config.hostname || "localhost";
config.securePort = config.securePort || 4040;
config.redirectPort = config.redirectPort || 4000;
config.storage = config.storage || "./ramstorage.js";
config.repositoryBaseURL = config.repositoryBaseURL || "";
config.helpURL = config.helpURL || "";
config.admins = config.admins || [];
config.sizeLimit = config.sizeLimit || "10mb";
// Load the custom footer HTML from disk, if it's defined.
if (config.customFooter) {
config.customFooter = fs.readFileSync(config.customFooter);
} else {
config.customFooter = "";
}
var callbackScheme = "https://",
callbackPort = config.securePort;
// We just use HTTP on localhost for testing
if (config.hostname === "localhost" && config.port) {
callbackScheme = "http://";
callbackPort = config.port;
}
if (!config.insecure) {
key = fs.readFileSync(path.resolve(__dirname, "config/certificate.key"));
cert = fs.readFileSync(path.resolve(__dirname, "config/certificate.cert"));
}
caPathList = config.caCertificates;
if (caPathList) {
if (!_.isArray(caPathList)) {
caPathList = [caPathList];
}
ca = caPathList.map(function (certPath) {
return fs.readFileSync(certPath);
});
}
// Check for other required config parameters
["githubClientId", "githubClientSecret", "sessionSecret"].forEach(function (param) {
if (!config[param]) {
throw new Error("Configuration error: must specify " + param + " in config.json");
}
});
// Configure submodules
logging.configure(config);
repository.configure(config);
// Set up Passport for authentication
// Session serialization. Since we don't need anything other than the registry user id
// (which is of the form "authservice:id"), we just pass the user id into and out
// of the session directly.
passport.serializeUser(function (registryUserId, done) {
done(null, registryUserId);
});
passport.deserializeUser(function (registryUserId, done) {
done(null, registryUserId);
});
// Set up the GitHub authentication strategy. The registry user id
// is just "github:" plus the user's GitHub username.
passport.use(
new GitHubStrategy(
{
clientID: config.githubClientId,
clientSecret: config.githubClientSecret,
callbackURL: callbackScheme + config.hostname + ":" + callbackPort + "/auth/github/callback"
},
function (accessToken, refreshToken, profile, done) {
request({
method: 'GET',
uri: url.parse(profile._json.organizations_url),
qs: {
access_token: accessToken
},
headers: {
"User-Agent": "brackets-registry"
},
json: true,
}, function (error, response, body) {
if (error) {
return done(error);
}
// body must be an array, if not it is an error.
if (!Array.isArray(body)) {
return done(body);
}
var orgs = body.map(function (item) {
return {
login: "github:" + item.login,
id: item.id
};
});
var user = {
owner: "github:" + profile.username,
orgs: orgs
};
done(null, user);
});
}
)
);
// Create and configure the app
var app = express();
app.configure(function () {
app.set("views", path.resolve(__dirname, "views"));
app.set("view engine", "html");
app.engine("html", require("hbs").__express);
app.use(express.favicon(path.resolve(__dirname, "public/favicon.ico")));
app.use(express.logger("dev"));
app.use(express.limit(config.sizeLimit));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({ secret: config.sessionSecret }));
app.use(passport.initialize());
app.use(passport.session());
// this route is accessible from localhost only and no csrf should be applied
app.post("/stats", downloadData.collectDownloadedData);
app.use(express.csrf());
app.use(function (req, res, next) {
// Must come before router (so locals are exposed properly) but after the CSRF middleware
// (so _csrf is set).
res.locals.csrfToken = req.csrfToken();
next();
});
app.use(app.router);
// JSLint doesn't like "express.static" because static is a keyword.
app.use(express["static"](path.resolve(__dirname, "public")));
// This is used for local testing with the FileStorage
if (config.directory) {
app.use("/files", express["static"](path.resolve(__dirname, config.directory)));
}
});
// Set up routes
routes.setup(app, config);
if (config.hostname === "localhost" && config.port) {
http.createServer(app).listen(config.port);
console.log("HTTP Listening on ", config.port);
} else {
// Start the HTTPS server
https.createServer({
key: key,
cert: cert,
ca: ca,
secureProtocol: "SSLv23_method",
secureOptions: constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3
}, app).listen(config.securePort);
console.log("HTTPS Listening on ", config.securePort);
// Redirect HTTP to HTTPS
http.createServer(function (req, res) {
res.writeHead(301, {
'Content-Type': 'text/plain',
'Location': 'https://' + config.hostname + ":" + config.securePort + req.url
});
res.end('Redirecting to SSL\n');
}).listen(config.redirectPort);
}
// If it's configured, turn on the REPL for localhost
if (config.repl) {
var replify = require("replify");
replify({
name: "registry"
}, app, {
repository: repository,
logging: logging
});
}