aboutsummaryrefslogtreecommitdiffstats
path: root/app/Controllers/Http/Dashboard/LoginController.ts
blob: ffb9eeb691a0af6e840b95306507e10de260f57e (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
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
import { schema, rules, validator } from '@ioc:Adonis/Core/Validator';
import User from 'App/Models/User';
import crypto from 'node:crypto';
import { handleVerifyAndReHash } from '../../../../helpers/PasswordHash';

export default class LoginController {
  /**
   * Display the login form
   */
  public async show({ view }: HttpContextContract) {
    return view.render('dashboard/login');
  }

  /**
   * Login a user
   */
  public async login({
    request,
    response,
    auth,
    session,
  }: HttpContextContract) {
    try {
      await validator.validate({
        schema: schema.create({
          mail: schema.string([rules.email(), rules.required()]),
          password: schema.string([rules.required()]),
        }),
        data: request.only(['mail', 'password']),
      });
    } catch {
      session.flash({
        type: 'danger',
        message: 'Invalid mail or password',
      });
      session.flashExcept(['password']);

      return response.redirect('/user/login');
    }

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

      // Check if user with email exists
      const user = await User.query().where('email', mail).first();
      if (!user?.email) {
        throw new Error('User credentials not valid (Invalid email)');
      }

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

      // Verify password
      let isMatchedPassword = false;
      try {
        isMatchedPassword = await handleVerifyAndReHash(user, hashedPassword);
      } catch (error) {
        return response.internalServerError({ message: error.message });
      }

      if (!isMatchedPassword) {
        throw new Error('User credentials not valid (Invalid password)');
      }

      await auth.use('web').login(user);

      return response.redirect('/user/account');
    } catch {
      session.flash({
        type: 'danger',
        message: 'Invalid mail or password',
      });
      session.flashExcept(['password']);

      return response.redirect('/user/login');
    }
  }
}