aboutsummaryrefslogtreecommitdiffstats
path: root/app/Controllers/Http/DashboardController.js
blob: 2f0696153865b510c4752969ac72ad917a9e931c (plain) (blame)
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
const {
  validateAll,
} = use('Validator');

const Service = use('App/Models/Service');
const Workspace = use('App/Models/Workspace');
const Persona = use('Persona');

const crypto = require('crypto');
const uuid = require('uuid/v4');

class DashboardController {
  async login({
    request,
    response,
    auth,
    session,
  }) {
    const validation = await validateAll(request.all(), {
      mail: 'required|email',
      password: 'required',
    });
    if (validation.fails()) {
      session.withErrors({
        type: 'danger',
        message: 'Invalid mail or password',
      }).flashExcept(['password']);
      return response.redirect('back');
    }

    const {
      mail,
      password,
    } = request.all();

    const hashedPassword = crypto.createHash('sha256').update(password).digest('base64');

    try {
      await auth.authenticator('session').attempt(mail, hashedPassword);
    } catch (error) {
      session.flash({
        type: 'danger',
        message: 'Invalid mail or password',
      });
      return response.redirect('back');
    }
    return response.redirect('/user/account');
  }

  async forgotPassword({
    request,
    view,
  }) {
    const validation = await validateAll(request.all(), {
      mail: 'required|email',
    });
    if (validation.fails()) {
      return view.render('others.message', {
        heading: 'Cannot reset your password',
        text: 'If your provided E-Mail address is linked to an account, we have just sent an E-Mail to that address.',
      });
    }
    try {
      await Persona.forgotPassword(request.input('mail'));
    } catch(e) {}

    return view.render('others.message', {
      heading: 'Reset password',
      text: 'If your provided E-Mail address is linked to an account, we have just sent an E-Mail to that address.',
    });
  }

  async resetPassword({
    request,
    view,
  }) {
    const validation = await validateAll(request.all(), {
      password: 'required',
      password_confirmation: 'required',
      token: 'required',
    });
    if (validation.fails()) {
      session.withErrors({
        type: 'danger',
        message: 'Passwords do not match',
      });
      return response.redirect('back');
    }

    const payload = {
      password: crypto.createHash('sha256').update(request.input('password')).digest('base64'),
      password_confirmation: crypto.createHash('sha256').update(request.input('password_confirmation')).digest('base64'),
    }

    try {
      await Persona.updatePasswordByToken(request.input('token'), payload);
    } catch(e) {
      return view.render('others.message', {
        heading: 'Cannot reset your password',
        text: 'Please make sure you are using a valid and recent link to reset your password and that your passwords entered match.',
      });
    }

    return view.render('others.message', {
      heading: 'Reset password',
      text: 'Successfully reset your password. You can now login to your account using your new password.',
    });
  }

  async account({
    auth,
    view,
    response,
  }) {
    try {
      await auth.check();
    } catch (error) {
      return response.redirect('/user/login');
    }

    return view.render('dashboard.account', {
      username: auth.user.username,
      email: auth.user.email,
      lastname: auth.user.lastname
    });
  }

  async edit({
    auth,
    request,
    session,
    view,
    response,
  }) {
    let validation = await validateAll(request.all(), {
      username: 'required',
      email: 'required',
      lastname: 'required'
    });
    if (validation.fails()) {
      session.withErrors(validation.messages()).flashExcept(['password']);
      return response.redirect('back');
    }

    // Check new username
    if (request.input('username') !== auth.user.username) {
      validation = await validateAll(request.all(), {
        username: 'required|unique:users,username',
        email: 'required',
      });
      if (validation.fails()) {
        session.withErrors(validation.messages()).flashExcept(['password']);
        return response.redirect('back');
      }
    }

    // Check new email
    if (request.input('email') !== auth.user.email) {
      validation = await validateAll(request.all(), {
        username: 'required',
        email: 'required|email|unique:users,email',
      });
      if (validation.fails()) {
        session.withErrors(validation.messages()).flashExcept(['password']);
        return response.redirect('back');
      }
    }

    // Update user account
    const { user } = auth;
    user.username = request.input('username');
    user.lastname = request.input('lastname');
    user.email = request.input('email');
    if (request.input('password')) {
      const hashedPassword = crypto.createHash('sha256').update(request.input('password')).digest('base64');
      user.password = hashedPassword;
    }
    user.save();

    return view.render('dashboard.account', {
      username: user.username,
      email: user.email,
      success: true,
    });
  }

  async data({
    auth,
    view,
  }) {
    const general = auth.user;
    const services = (await auth.user.services().fetch()).toJSON();
    const workspaces = (await auth.user.workspaces().fetch()).toJSON();

    return view.render('dashboard.data', {
      username: general.username,
      lastname: general.lastname,
      mail: general.email,
      created: general.created_at,
      updated: general.updated_at,
      stringify: JSON.stringify,
      services,
      workspaces,
    });
  }

  async export({
    auth,
    response,
  }) {
    const general = auth.user;
    const services = (await auth.user.services().fetch()).toJSON();
    const workspaces = (await auth.user.workspaces().fetch()).toJSON();

    const exportData = {
      username: general.username,
      lastname: general.lastname,
      mail: general.email,
      services,
      workspaces,
    };

    return response
      .header('Content-Type', 'application/force-download')
      .header('Content-disposition', 'attachment; filename=export.ferdi-data')
      .send(exportData);
  }

  async import({
    auth,
    request,
    session,
    response,
    view,
  }) {
    const validation = await validateAll(request.all(), {
      file: 'required',
    });
    if (validation.fails()) {
      session.withErrors(validation.messages()).flashExcept(['password']);
      return response.redirect('back');
    }

    let file;
    try {
      file = JSON.parse(request.input('file'));
    } catch (e) {
      session.flash({ type: 'danger', message: 'Invalid Ferdi account file' });
      return response.redirect('back');
    }

    if (!file || !file.services || !file.workspaces) {
      session.flash({ type: 'danger', message: 'Invalid Ferdi account file (2)' });
      return response.redirect('back');
    }

    const serviceIdTranslation = {};

    // Import services
    try {
      for (const service of file.services) {
        // Get new, unused uuid
        let serviceId;
        do {
          serviceId = uuid();
        } while ((await Service.query().where('serviceId', serviceId).fetch()).rows.length > 0); // eslint-disable-line no-await-in-loop

        await Service.create({ // eslint-disable-line no-await-in-loop
          userId: auth.user.id,
          serviceId,
          name: service.name,
          recipeId: service.recipeId,
          settings: JSON.stringify(service.settings),
        });

        serviceIdTranslation[service.id] = serviceId;
      }
    } catch (e) {
      const errorMessage = `Could not import your services into our system.\nError: ${e}`;
      return view.render('others.message', {
        heading: 'Error while importing',
        text: errorMessage,
      });
    }

    // Import workspaces
    try {
      for (const workspace of file.workspaces) {
        let workspaceId;
        do {
          workspaceId = uuid();
        } while ((await Workspace.query().where('workspaceId', workspaceId).fetch()).rows.length > 0); // eslint-disable-line no-await-in-loop

        const services = workspace.services.map((service) => serviceIdTranslation[service]);

        await Workspace.create({ // eslint-disable-line no-await-in-loop
          userId: auth.user.id,
          workspaceId,
          name: workspace.name,
          order: workspace.order,
          services: JSON.stringify(services),
          data: JSON.stringify(workspace.data),
        });
      }
    } catch (e) {
      const errorMessage = `Could not import your workspaces into our system.\nError: ${e}`;
      return view.render('others.message', {
        heading: 'Error while importing',
        text: errorMessage,
      });
    }

    return view.render('others.message', {
      heading: 'Successfully imported',
      text: 'Your account has been imported, you can now login as usual!',
    });
  }

  logout({
    auth,
    response,
  }) {
    auth.authenticator('session').logout();
    return response.redirect('/user/login');
  }

  delete({
    auth,
    response,
  }) {
    auth.user.delete();
    auth.authenticator('session').logout();
    return response.redirect('/user/login');
  }
}

module.exports = DashboardController;