Files
duty-schedule-api/app/Controllers/Http/AuthController.ts
2021-10-22 05:29:50 +02:00

70 lines
1.5 KiB
TypeScript

import { OpaqueTokenContract } from '@ioc:Adonis/Addons/Auth'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import Logger from '@ioc:Adonis/Core/Logger'
import User from 'App/Models/User'
type AuthSuccResult = {
notification: {
type: string,
text: string
}
user: string,
role: string,
token: string
}
type AuthErrResult = {
notification: {
text: string,
type: 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 = {
notification: {
type: 'success',
text: 'Login successful!'
},
user: auth.user?.username ?? '',
role: auth.user?.role ?? '',
token: token.token
}
return response.ok(result)
} catch (error) {
const result : AuthErrResult = {
notification: {
type: 'danger',
text: error.message
}
}
return response.forbidden(result)
}
}
public async logout({auth, response}: HttpContextContract) {
Logger.info("entering logout function")
try {
await auth.use('api').revoke()
return response.ok('Logged out successfully')
}
catch(error) {
Logger.error(error.message)
}
}
}