74 lines
1.6 KiB
TypeScript
74 lines
1.6 KiB
TypeScript
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
|
|
import Logger from '@ioc:Adonis/Core/Logger'
|
|
import Nonce from 'App/Models/Nonce'
|
|
import Database from '@ioc:Adonis/Lucid/Database'
|
|
import { DateTime } from 'luxon'
|
|
|
|
type AuthSuccResult = {
|
|
user: string,
|
|
role: string,
|
|
token: string
|
|
}
|
|
|
|
export default class AuthController {
|
|
|
|
|
|
/**TODO #3 implement rememberMe function */
|
|
public async login({auth, request, response}: HttpContextContract) {
|
|
const username = request.body().username
|
|
const password = request.body().password
|
|
// const rememberMe = request.body().rememberMe ?? false
|
|
|
|
try {
|
|
const token = await auth.use('api').attempt(username, password)
|
|
|
|
const result : AuthSuccResult = {
|
|
user: auth.user?.username ?? '',
|
|
role: auth.user?.role ?? '',
|
|
token: token.token
|
|
}
|
|
|
|
return response.ok(result)
|
|
|
|
} catch (error) {
|
|
return response.forbidden(error.message)
|
|
}
|
|
}
|
|
|
|
public async logout({auth}: HttpContextContract) {
|
|
try {
|
|
await auth.use('api').revoke()
|
|
return
|
|
}
|
|
catch(error) {
|
|
Logger.error(error.message)
|
|
}
|
|
}
|
|
|
|
public async nonce(ctx: HttpContextContract) {
|
|
const requestId = ctx.request.header('X-REQUEST-ID')
|
|
|
|
try {
|
|
this.deleteExpiredNonces()
|
|
|
|
const nonce = await Nonce.create({
|
|
requestId: requestId
|
|
})
|
|
|
|
return nonce.nonce
|
|
}
|
|
catch(err){
|
|
return ctx.response.forbidden(err)
|
|
}
|
|
}
|
|
|
|
private async deleteExpiredNonces(){
|
|
try {
|
|
await Database.from('nonces').where('expiry_date', '<', DateTime.now().toFormat('yyyy-MM-dd HH:mm:ss')).delete()
|
|
}
|
|
catch(err){
|
|
throw err
|
|
}
|
|
}
|
|
}
|