root.js 8.68 KB
Newer Older
mntmn's avatar
mntmn committed
1
2
3
4
5
6
7
8
9
10
11
"use strict";

const config = require('config');

const redis = require('../helpers/redis');
const express = require('express');
const crypto = require('crypto');
const router = express.Router();
const mailer = require('../helpers/mailer');
const _ = require('underscore');

Wolfgang Knopki's avatar
Wolfgang Knopki committed
12
13
14
15
16
const fs = require('fs')
const SamlStrategy = require('passport-saml').Strategy
const passport = require('passport')
const Saml2js = require('saml2js');

mntmn's avatar
mntmn committed
17
18
19
20
21
const db = require('../models/db');
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const uuidv4 = require('uuid/v4');

Wolfgang Knopki's avatar
Wolfgang Knopki committed
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

// =========== PASSPORT =======
  passport.serializeUser(function (user, done) {
    done(null, user);
  });

  passport.deserializeUser(function (user, done) {
    done(null, user);
  });

  var samlStrategy = new SamlStrategy({
      // URL that goes from the Identity Provider -> Service Provider
      callbackUrl: config.path,

      entryPoint: config.entryPoint,
      issuer: config.issuer,
      identifierFormat: null,

      validateInResponseTo: false,
      disableRequestedAuthnContext: true
  },
  function (profile, done) {
    return done(null, {
      id: profile.nameID,
      idFormat: profile.nameIDFormat,
      email: profile.email,
      firstName: profile.givenName,
      lastName: profile.sn
    });
  });

  passport.use(samlStrategy);

 // to generate Service Provider's XML metadata
  router.get('/saml/metadata',
    function(req, res) {
      res.type('application/xml');
      var spMetadata = samlStrategy.generateServiceProviderMetadata(fs.readFileSync('/cert/certificate.pem', 'utf8'));
      res.status(200).send(spMetadata);
    }
  );

router.post('/saml/SSO', passport.authenticate('saml', { failureRedirect: '/login', failureFlash: true}), function(req, res){
    const xmlResponse = req.body.SAMLResponse;
    const parser = new Saml2js(xmlResponse);
Wolfgang Knopki's avatar
Wolfgang Knopki committed
67
68
69
70
71
    const response = parser.toObject();
    const email = response["mail"];
    console.log(parser.toJSON());
    console.log("Nickname "+ response["givenName"])
    const nickname = response["givenName"];
72
    //check, if user exists, if not create.
Wolfgang Knopki's avatar
Wolfgang Knopki committed
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
    db.User.findAll({where: {email: email}})
        .then(users => {
          if (users.length == 0) {
            crypto.randomBytes(16, function(ex, buf) {
                var token = buf.toString('hex');

                var u = {
                    _id: uuidv4(),
                    email: email,
                    account_type: "email",
                    nickname: nickname,
                    password_hash: "00000",
                    prefs_language: req.i18n.locale,
                    confirmation_token: token
                };

                db.User.create(u)
                    .error(err => {
                        res.sendStatus(400);
                    })
                    .then(u => {
                        var homeFolder = {
                            _id: uuidv4(),
                            name: req.i18n.__("home"),
                            space_type: "folder",
                            creator_id: u._id
                          };
                          db.Space.create(homeFolder)
                            .error(err => {
                              res.sendStatus(400);
                            })
                            .then(homeFolder => {
                              u.home_folder_id = homeFolder._id;
                              u.save()
                                .then(() => {
                                  // home folder created,
                                  // auto accept pending invites
                                  db.Membership.update({
                                    "state": "active"
                                  }, {
                                    where: {
                                      "email_invited": u.email,
                                      "state": "pending"
                                    }
                                  });
                                  res.status(201).json({});
                                })
                                .error(err => {
                                  res.status(400).json(err);
                                });
                            })
                    });
            });
          }
        }).then(user =>{
         db.User.findOne({where: {email: email}})
Wolfgang Knopki's avatar
Wolfgang Knopki committed
129
                .error(err => {
Wolfgang Knopki's avatar
Wolfgang Knopki committed
130
                  res.sendStatus(404);
Wolfgang Knopki's avatar
Wolfgang Knopki committed
131
                })
Wolfgang Knopki's avatar
Wolfgang Knopki committed
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
                .then(user => {
                    crypto.randomBytes(48, function(ex, buf) {
                                  var token = buf.toString('hex');

                                  var session = {
                                    user_id: user._id,
                                    token: token,
                                    ip: req.ip,
                                    device: "web",
                                    created_at: new Date(),
                                    url : "/"
                                  };

                                  db.Session.create(session)
                                    .error(err => {
                                      console.error("Error creating Session:",err);
                                      res.redirect(500, "/");
                                    })
                                    .then(() => {
                                      var domain = (process.env.NODE_ENV == "production") ? new URL(config.get('endpoint')).hostname : req.headers.hostname;
                                      console.log("session set successfully");
                                      res.cookie('sdsession', token, { domain: domain, httpOnly: true });
                                      res.redirect(302, "/")
                                    });
                        });
Wolfgang Knopki's avatar
Wolfgang Knopki committed
157
                });
Wolfgang Knopki's avatar
Wolfgang Knopki committed
158
         });
Wolfgang Knopki's avatar
Wolfgang Knopki committed
159
160
});

mntmn's avatar
mntmn committed
161
router.get('/', (req, res) => {
162
  res.render('index', { config:config, user:req.user });
mntmn's avatar
mntmn committed
163
164
165
166
167
168
169
});

router.get('/ping', (req, res) => {
  res.status(200).json({"status": "ok"})
});

router.get('/spaces', (req, res) => {
170
  res.render('spacedeck', { config:config, user:req.user });
mntmn's avatar
mntmn committed
171
172
173
});

router.get('/not_found', (req, res) => {
174
  res.render('not_found', {});
mntmn's avatar
mntmn committed
175
176
177
});

router.get('/confirm/:token', (req, res) => {
178
  res.render('spacedeck', { config:config, user:req.user });
mntmn's avatar
mntmn committed
179
180
181
});

router.get('/folders/:id', (req, res) => {
182
  res.render('spacedeck', { config:config, user:req.user });
mntmn's avatar
mntmn committed
183
184
185
});

router.get('/signup', (req, res) => {
186
  res.render('spacedeck', { config:config, user:req.user });
mntmn's avatar
mntmn committed
187
188
189
});

router.get('/accept/:id', (req, res) => {
190
  res.render('spacedeck', { config:config, user:req.user });
mntmn's avatar
mntmn committed
191
192
193
});

router.get('/password-reset', (req, res) => {
194
  res.render('spacedeck', { config:config, user:req.user });
mntmn's avatar
mntmn committed
195
196
197
});

router.get('/password-confirm/:token', (req, res) => {
198
  res.render('spacedeck', { config:config, user:req.user });
mntmn's avatar
mntmn committed
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
});

router.get('/de/*', (req, res) => {
  res.redirect("/t/de");
});

router.get('/de', (req, res) => {
  res.redirect("/t/de");
});

router.get('/fr/*', (req, res) => {
  res.redirect("/t/fr");
});

router.get('/fr', (req, res) => {
  res.redirect("/t/fr");
});
216

Mejans's avatar
Mejans committed
217
218
219
router.get('/oc/*', (req, res) => {
  res.redirect("/t/oc");
});
mntmn's avatar
mntmn committed
220

Mejans's avatar
Mejans committed
221
222
223
router.get('/oc', (req, res) => {
  res.redirect("/t/oc");
});
224

mntmn's avatar
mntmn committed
225
226
227
228
229
230
231
232
233
234
235
236
router.get('/en/*', (req, res) => {
  res.redirect("/t/en");
});

router.get('/en', (req, res) => {
  res.redirect("/t/end");
});

router.get('/account', (req, res) => {
  res.render('spacedeck');
});

Wolfgang Knopki's avatar
Wolfgang Knopki committed
237
238
239
240
241
242
243
244
245
246
router.get('/login', passport.authenticate('saml',
                           {
                             successRedirect: '/',
                             failureRedirect: '/login'
                           })
);


//  res.render('spacedeck', { config:config, user:req.user });
//});
mntmn's avatar
mntmn committed
247
248

router.get('/logout', (req, res) => {
249
  res.render('spacedeck', { config:config, user:req.user });
mntmn's avatar
mntmn committed
250
251
252
253
254
255
256
257
258
259
260
});

router.get('/t/:id', (req, res) => {
  res.cookie('spacedeck_locale', req.params.id, { maxAge: 900000, httpOnly: true });
  var path = "/";
  if (req.query.r=="login" || req.query.r=="signup") {
    path = "/"+req.query.r;
  }
  res.redirect(path);
});

261
262
263
264
router.get('/s/:hash', (req, res) => {
  var hash = req.params.hash;
  if (hash.split("-").length > 0) {
    hash = hash.split("-")[0];
mntmn's avatar
mntmn committed
265
  }
mntmn's avatar
mntmn committed
266

267
  db.Space.findOne({where: {"edit_hash": hash}}).then(function (space) {
mntmn's avatar
mntmn committed
268
269
    if (space) {
      if (req.accepts('text/html')){
270
	      res.redirect("/spaces/"+space._id + "?spaceAuth=" + hash);
mntmn's avatar
mntmn committed
271
      } else {
mntmn's avatar
mntmn committed
272
	      res.status(200).json(space);
mntmn's avatar
mntmn committed
273
      }
mntmn's avatar
mntmn committed
274
    } else {
mntmn's avatar
mntmn committed
275
      if (req.accepts('text/html')) {
276
	      res.status(404).render('not_found', {});
mntmn's avatar
mntmn committed
277
      } else {
mntmn's avatar
mntmn committed
278
	      res.status(404).json({});
mntmn's avatar
mntmn committed
279
      }
mntmn's avatar
mntmn committed
280
281
282
283
284
    }
  });
});

router.get('/spaces/:id', (req, res) => {
285
  res.render('spacedeck', { config:config, user:req.user });
mntmn's avatar
mntmn committed
286
287
});

Wolfgang Knopki's avatar
Wolfgang Knopki committed
288
module.exports = {router: router, passport:passport};