76 lines
2.1 KiB
TypeScript
76 lines
2.1 KiB
TypeScript
import type { HttpContext } from '@adonisjs/core/http'
|
|
import { requestLoginValidator, verifyCodeValidator } from '#validators/auth'
|
|
import mail from '@adonisjs/mail/services/main'
|
|
import { AuthService } from '#services/auth_service'
|
|
import { inject } from '@adonisjs/core'
|
|
import app from '@adonisjs/core/services/app'
|
|
import env from '#start/env'
|
|
|
|
@inject()
|
|
export default class AuthController {
|
|
constructor(private authService: AuthService) {}
|
|
|
|
// POST /auth/request
|
|
async requestLogin({ request, response, captcha }: HttpContext) {
|
|
// Validate captcha
|
|
if (app.inProduction) {
|
|
const validateResult = await (captcha.use('turnstile') as any).validate()
|
|
if (!validateResult.success) {
|
|
return response.badRequest({
|
|
message: 'Captcha validation failed',
|
|
error: validateResult.errorCodes,
|
|
})
|
|
}
|
|
}
|
|
|
|
// Generate token
|
|
const expiresIn = '15 minutes'
|
|
const { email } = await request.validateUsing(requestLoginValidator)
|
|
const payload = await this.authService.generateToken(email, expiresIn)
|
|
|
|
// Send email
|
|
await mail.send((message) => {
|
|
message
|
|
.from(env.get('MAIL_FROM')!)
|
|
.to(email)
|
|
.subject(payload.emailTitle)
|
|
.htmlView('mails/auth', payload)
|
|
.textView('mails/auth-fallback', payload)
|
|
}).then(console.log).catch(console.error)
|
|
|
|
return {
|
|
success: true,
|
|
data: {
|
|
token: payload.token,
|
|
},
|
|
}
|
|
}
|
|
|
|
// POST /auth/verify
|
|
async verifyCode({ request }: HttpContext) {
|
|
// Validate code
|
|
const { code } = await request.validateUsing(verifyCodeValidator)
|
|
const email = await this.authService.validateCode(code)
|
|
if (!email) {
|
|
return {
|
|
success: false,
|
|
message: 'Le code est invalide ou a expiré',
|
|
}
|
|
}
|
|
|
|
// TOOD: Login
|
|
// Find user by email (string similary)
|
|
}
|
|
|
|
magicLink({}: HttpContext) {
|
|
// Validate signed url (adonis)
|
|
// + login current device
|
|
// + SSE to notify other devices (and login)
|
|
}
|
|
|
|
listen({}: HttpContext) {
|
|
// Listen for SSE events
|
|
// Need an AUTH token to connect
|
|
// AUTH token sent to client in requestLogin
|
|
}
|
|
}
|