api/app/services/auth_service.ts
2025-05-19 13:25:42 +02:00

43 lines
1.1 KiB
TypeScript

import encryption from '@adonisjs/core/services/encryption'
import cache from '@adonisjs/cache/services/main'
import env from '#start/env'
export class AuthService {
async generateToken(email: string, expiresIn: string) {
// Generate magic link token
const token = encryption.encrypt(email, expiresIn)
const magicLink = env.get('PUBLIC_AUTH_URL') + '/success?signature=' + token
// Generate code
const formattedOTP = Math.floor(Math.random() * 1000000)
.toString()
.padStart(6, '0')
await cache.set({
key: 'auth:otp:' + formattedOTP,
value: email,
ttl: expiresIn,
})
const emailTitle = `${formattedOTP} est votre code de vérification pour ${env.get('APP_NAME')}`
return {
emailTitle,
formattedOTP,
magicLink,
expiresIn,
email,
token,
}
}
async validateCode(code: string) {
// Validate code
const key = 'auth:otp:' + code
const email = await cache.get({ key })
if (!email) return false
// Delete code from cache
await cache.delete({ key })
return email
}
}