aboutsummaryrefslogtreecommitdiffstats
path: root/app/Controllers/Http/Dashboard/LoginController.ts
blob: 5a544482a41cbb0b1531b89f0dc2895e23afccfe (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
import type { HttpContext } from '@adonisjs/core/http'
import { schema, rules, validator } from '@adonisjs/validator'
import User from '#app/Models/User'
import crypto from 'node:crypto'
import { handleVerifyAndReHash } from '../../../../helpers/PasswordHash.js'

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

  /**
   * Login a user
   */
  public async login({ request, response, auth, session }: HttpContext) {
    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')
    }
  }
}