AuthController.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. export default class AuthController {
  6. public async login({ request, auth }: HttpContextContract) {
  7. const { username, password } = request.all()
  8. return await auth.use('api').attempt(username, password, {
  9. expiresIn: '30 days'
  10. })
  11. }
  12. public async loginAdmin({ request, auth }: HttpContextContract) {
  13. const { username, password } = request.all()
  14. let token
  15. try {
  16. token = await auth.use('api').attempt(username, password, {
  17. expiresIn: '30 days'
  18. })
  19. } catch (error) {
  20. throw new AuthenticationException(error.message, error.code)
  21. }
  22. if (token.user.role !== UserRoles.Admin) {
  23. throw new AuthenticationException('Unauthorized access', 'E_UNAUTHORIZED_ACCESS')
  24. }
  25. return token
  26. }
  27. public async register({ request, auth }: HttpContextContract) {
  28. const data = await request.validate({
  29. schema: schema.create({
  30. username: schema.string({ trim: true }, [
  31. rules.regex(/^[a-zA-Z0-9_]{4,16}$/),
  32. rules.unique({ table: 'users', column: 'username' })
  33. ]),
  34. email: schema.string({ trim: true }, [
  35. rules.email(),
  36. rules.unique({ table: 'users', column: 'email' })
  37. ]),
  38. password: schema.string({ trim: true }, [rules.minLength(6), rules.maxLength(18)])
  39. }),
  40. messages: {
  41. minLength: '{{field}} 最小长度为 {{ options.minLength }}',
  42. maxLength: '{{field}} 最大长度为 {{ options.maxLength }}',
  43. unique: '{{field}} 不可用',
  44. email: '{{field}} 不是有效的邮箱',
  45. regex: '{{field}} 只能包含字母、数字和下划线,长度为4-16位'
  46. }
  47. })
  48. const user = new User()
  49. user.merge(data)
  50. await user.save()
  51. return await auth.use('api').login(user)
  52. }
  53. }