AuthController.ts 2.6 KB

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