api/app/services/auth_service.ts
2025-07-30 12:56:52 +02:00

74 lines
1.8 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 generateCode(email: string, expiresIn: string) {
// TODO: Generate magic link token
// const identifier = email
// const token = encryption.encrypt(identifier, 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 { success: false, email: null }
// Delete code from cache
await cache.delete({ key })
return {
email,
success: true,
}
}
generateToken(email: string, expiresIn: string) {
// Generate token
const identifier = email.toLowerCase()
const token = encryption.encrypt(identifier, expiresIn)
return {
token,
expiresIn,
email: identifier,
}
}
validateToken(token: string) {
// Decrypt token
const decrypted = encryption.decrypt(token)
if (!decrypted) return { success: false, email: null }
// Validate email format
const email = (decrypted as string).toLowerCase()
if (!email.includes('@')) return { success: false, email: null }
return {
success: true,
email,
}
}
}