+exports.init = function (config) {
+ gConfig = config;
+};
+
+exports.login = function (req, res, next) {
+ verifyUser(req.body.username, req.body.password, function (error, user) {
+ if (error) return next(new HttpError(401, 'Invalid credentials'));
+
+ var accessToken = LOGIN_TOKEN_PREFIX + uuid();
+
+ tokenStore.set(accessToken, user, function (error) {
+ if (error) return next(new HttpError(500, error));
+
+ next(new HttpSuccess(201, { accessToken: accessToken, user: user }));
+ });
+ });
+};
+
+exports.verify = function (req, res, next) {
+ var accessToken = req.query.access_token || req.body.accessToken;
+
+ tokenStore.get(accessToken, function (error, user) {
+ if (error) return next(new HttpError(401, 'Invalid Access Token'));
+
+ req.user = user;
+
+ next();
+ });
+
+};
+
+exports.verifyIfNeeded = function (req, res, next) {
+ if (!gConfig.folderListingEnabled) return exports.verify(req, res, next);
+ next();
+};
+
+exports.logout = function (req, res, next) {
+ var accessToken = req.query.access_token || req.body.accessToken;
+
+ tokenStore.del(accessToken, function (error) {
+ if (error) console.error(error);
+
+ next(new HttpSuccess(200, {}));
+ });
+};
+
+exports.getProfile = function (req, res, next) {
+ next(new HttpSuccess(200, { username: req.user.username }));
+};
+
+exports.getTokens = function (req, res, next) {
+ tokenStore.getApiTokens(function (error, result) {
+ if (error) return next(new HttpError(500, error));
+
+ next(new HttpSuccess(200, { accessTokens: result }));
+ });
+};
+
+exports.createToken = function (req, res, next) {
+ var accessToken = API_TOKEN_PREFIX + uuid();
+
+ tokenStore.set(accessToken, req.user, function (error) {
+ if (error) return next(new HttpError(500, error));
+
+ next(new HttpSuccess(201, { accessToken: accessToken }));
+ });
+};
+
+exports.delToken = function (req, res, next) {
+ tokenStore.del(req.params.token, function (error) {
+ if (error) console.error(error);
+
+ next(new HttpSuccess(200, {}));
+ });