AuthController.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { AuthenticationException } from '@adonisjs/auth/build/standalone'
  2. import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
  3. import { UserRoles } from 'App/Models/User'
  4. import { schema, rules } from '@ioc:Adonis/Core/Validator'
  5. import UserService from 'App/Services/UserService'
  6. export default class AuthController {
  7. public async login({ request, auth }: HttpContextContract) {
  8. const { username, password } = request.all()
  9. return await auth.use('api').attempt(username, password, {
  10. expiresIn: '1 year'
  11. })
  12. }
  13. public async loginAdmin({ request, auth }: HttpContextContract) {
  14. const { username, password } = request.all()
  15. let token
  16. try {
  17. token = await auth.use('api').attempt(username, password, {
  18. expiresIn: '30 days'
  19. })
  20. } catch (error) {
  21. throw new AuthenticationException(error.message, error.code)
  22. }
  23. if (token.user.role === UserRoles.User) {
  24. throw new AuthenticationException('Unauthorized access', 'E_UNAUTHORIZED_ACCESS')
  25. }
  26. return token
  27. }
  28. public async register({ request, auth }: HttpContextContract) {
  29. const data = await request.validate({
  30. schema: schema.create({
  31. username: schema.string.optional({ trim: true }, [
  32. rules.regex(/^[a-zA-Z0-9_]{4,16}$/),
  33. rules.unique({ table: 'users', column: 'username' })
  34. ]),
  35. email: schema.string.optional({ trim: true }, [
  36. rules.email(),
  37. rules.unique({ table: 'users', column: 'email' })
  38. ]),
  39. password: schema.string({ trim: true }, [rules.minLength(6), rules.maxLength(18)])
  40. }),
  41. messages: {
  42. minLength: 'The min length of {{field}} is {{ options.minLength }}',
  43. maxLength: 'The max length of {{field}} is {{ options.maxLength }}',
  44. unique: '{{field}} not available',
  45. email: '{{field}} is not a valid email',
  46. regex: '{{field}} is not valid'
  47. }
  48. })
  49. const user = await UserService.register(data)
  50. return await auth.use('api').login(user)
  51. }
  52. }