| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- 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'
- import UserBalance from 'App/Models/UserBalance'
- import Decimal from 'decimal.js'
- import randomstring from 'randomstring'
- export default class AuthController {
- public async login({ request, auth }: HttpContextContract) {
- const { username, password } = request.all()
- return await auth.use('api').attempt(username, password, {
- expiresIn: '1 year'
- })
- }
- 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.optional({ trim: true }, [
- rules.regex(/^[a-zA-Z0-9_]{4,16}$/),
- rules.unique({ table: 'users', column: 'username' })
- ]),
- email: schema.string.optional({ trim: true }, [
- rules.email(),
- rules.unique({ table: 'users', column: 'email' })
- ]),
- password: schema.string({ trim: true }, [rules.minLength(6), rules.maxLength(18)])
- }),
- messages: {
- minLength: 'The min length of {{field}} is {{ options.minLength }}',
- maxLength: 'The max length of {{field}} is {{ options.maxLength }}',
- unique: '{{field}} not available',
- email: '{{field}} is not a valid email',
- regex: '{{field}} is not valid'
- }
- })
- const user = new User()
- user.merge(data)
- if (!user.username) {
- user.username = 'fs_' + randomstring.generate(8)
- }
- await user.save()
- // await UserBalance.create({
- // userId: user.id,
- // balance: new Decimal('9999')
- // })
- return await auth.use('api').login(user)
- }
- }
|