| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- import { AuthenticationException } from '@adonisjs/auth/build/standalone'
- import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
- import User, { UserRoles } from 'App/Models/User'
- import { schema, rules } from '@ioc:Adonis/Core/Validator'
- export default class AuthController {
- public async login({ request, auth }: HttpContextContract) {
- const { username, password } = request.all()
- return await auth.use('api').attempt(username, password, {
- expiresIn: '30 days'
- })
- }
- public async loginAdmin({ request, auth }: HttpContextContract) {
- const { username, password } = request.all()
- let token
- try {
- token = await auth.use('api').attempt(username, password, {
- expiresIn: '30 days'
- })
- } catch (error) {
- throw new AuthenticationException(error.message, error.code)
- }
- if (token.user.role !== UserRoles.Admin) {
- throw new AuthenticationException('Unauthorized access', 'E_UNAUTHORIZED_ACCESS')
- }
- return token
- }
- public async register({ request, auth }: HttpContextContract) {
- const data = await request.validate({
- schema: schema.create({
- username: schema.string({ trim: true }, [
- rules.regex(/^[a-zA-Z0-9_]{4,16}$/),
- rules.unique({ table: 'users', column: 'username' })
- ]),
- email: schema.string({ trim: true }, [
- rules.email(),
- rules.unique({ table: 'users', column: 'email' })
- ]),
- password: schema.string({ trim: true }, [rules.minLength(6), rules.maxLength(18)])
- }),
- messages: {
- minLength: '{{field}} 最小长度为 {{ options.minLength }}',
- maxLength: '{{field}} 最大长度为 {{ options.maxLength }}',
- unique: '{{field}} 不可用',
- email: '{{field}} 不是有效的邮箱',
- regex: '{{field}} 只能包含字母、数字和下划线,长度为4-16位'
- }
- })
- const user = new User()
- user.merge(data)
- await user.save()
- return await auth.use('api').login(user)
- }
- }
|