1 |
|
2 |
|
3 |
|
4 |
|
5 | var async = require('async');
|
6 | var debug = require('debug')('antisocial-friends');
|
7 | var VError = require('verror').VError;
|
8 | var WError = require('verror').WError;
|
9 |
|
10 | module.exports = function mountFriendExchangeToken(antisocialApp) {
|
11 |
|
12 | var router = antisocialApp.router;
|
13 | var config = antisocialApp.config;
|
14 | var db = antisocialApp.db;
|
15 | var authUserMiddleware = antisocialApp.authUserMiddleware;
|
16 |
|
17 | var exchangeRegex = /^\/([a-zA-Z0-9\-.]+)\/exchange-token$/;
|
18 |
|
19 | debug('mounting GET /username/exchange-token', exchangeRegex);
|
20 |
|
21 | router.post(exchangeRegex, function (req, res) {
|
22 | var matches = req.path.match(exchangeRegex);
|
23 | var username = matches[1];
|
24 |
|
25 | var endpoint = req.body.endpoint;
|
26 | var requestToken = req.body.requestToken;
|
27 |
|
28 | async.waterfall([
|
29 | function getUser(cb) {
|
30 | debug('/exchange-token getUser');
|
31 | db.getInstances('users', [{
|
32 | 'property': 'username',
|
33 | 'value': username
|
34 | }], function (err, userInstances) {
|
35 | if (err) {
|
36 | return cb(new VError(err, 'user not found'));
|
37 | }
|
38 |
|
39 | if (userInstances.length > 1) {
|
40 | return cb(new VError('more than one user matching username'));
|
41 | }
|
42 |
|
43 | cb(err, userInstances[0]);
|
44 | });
|
45 | },
|
46 | function findFriend(user, cb) {
|
47 | debug('/exchange-token findFriend');
|
48 |
|
49 | db.getInstances('friends', [{
|
50 | 'property': 'localRequestToken',
|
51 | 'value': requestToken
|
52 | }], function (err, friendInstances) {
|
53 | if (err) {
|
54 | return cb(new VError(err, 'error reading friend'));
|
55 | }
|
56 |
|
57 | for (var i = 0; i < friendInstances.length; i++) {
|
58 | var friend = friendInstances[i];
|
59 | if (friend.remoteEndPoint === endpoint && user.id === friend.userId) {
|
60 | return cb(null, user, friend);
|
61 | }
|
62 | }
|
63 |
|
64 | cb(new VError('friend not found'));
|
65 | });
|
66 | }
|
67 | ], function (err, user, friend) {
|
68 | if (err) {
|
69 | var e = new WError(err, 'exchange token failed');
|
70 | return res.status(400).send(e.cause().message);
|
71 | }
|
72 |
|
73 | var payload = {
|
74 | 'status': friend.status,
|
75 | 'accessToken': friend.localAccessToken,
|
76 | 'publicKey': friend.keys.public,
|
77 | 'name': user.name,
|
78 | 'username': user.username
|
79 | };
|
80 |
|
81 | res.send(payload);
|
82 | });
|
83 | });
|
84 |
|
85 | };
|