adonisjs / auth

Official Authentication package for AdonisJS
https://docs.adonisjs.com/guides/auth/introduction
MIT License
187 stars 65 forks source link

abilities not stringify before JOSN.parse #237

Closed llucasspot closed 4 months ago

llucasspot commented 4 months ago

Describe the bug

Error : AuthMiddleware using auth access token

HttpExceptionHandler :  SyntaxError: Unexpected token '*', "*" is not valid JSON
    at JSON.parse (<anonymous>)
    at _DbAccessTokensProvider.dbRowToAccessToken (/PROJECT_PATH/node_modules/@adonisjs/auth/modules/access_tokens_guard/token_providers/db.ts:110:23)
    at _DbAccessTokensProvider.verify (/PROJECT_PATH/node_modules/@adonisjs/auth/modules/access_tokens_guard/token_providers/db.ts:323:30)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at AccessTokensGuard.authenticate (/PROJECT_PATH/node_modules/@adonisjs/auth/modules/access_tokens_guard/guard.ts:183:19)
    at AccessTokensGuard.check (/PROJECT_PATH/node_modules/@adonisjs/auth/modules/access_tokens_guard/guard.ts:246:7)
    at Authenticator.authenticateUsing (/PROJECT_PATH/node_modules/@adonisjs/auth/src/authenticator.ts:221:11)
    at AuthMiddleware.handle (/PROJECT_PATH/app/middleware/auth_middleware.ts:22:5)

reading the code the error seams to be on https://github.com/adonisjs/auth/blob/develop/modules/access_tokens_guard/token_providers/db.ts file

protected dbRowToAccessToken(dbRow: AccessTokenDbColumns): AccessToken {
    return new AccessToken({
      identifier: dbRow.id,
      tokenableId: dbRow.tokenable_id,
      type: dbRow.type,
      name: dbRow.name,
      hash: dbRow.hash,
      abilities: JSON.parse(dbRow.abilities),
      createdAt:
        typeof dbRow.created_at === 'number' ? new Date(dbRow.created_at) : dbRow.created_at,
      updatedAt:
        typeof dbRow.updated_at === 'number' ? new Date(dbRow.updated_at) : dbRow.updated_at,
      lastUsedAt:
        typeof dbRow.last_used_at === 'number' ? new Date(dbRow.last_used_at) : dbRow.last_used_at,
      expiresAt:
        typeof dbRow.expires_at === 'number' ? new Date(dbRow.expires_at) : dbRow.expires_at,
    })
  }

dbRow.abilities needs to be stringifyed before parsed

dbRow.last_used_at = new Date()
    await db
      .from(this.table)
      .where({ id: dbRow.id, type: dbRow.type })
      .update({ last_used_at: dbRow.last_used_at })

    /**
     * Convert to access token instance
     */
    console.log(dbRow)
    const accessToken = this.dbRowToAccessToken(dbRow)

dbRow.abilities is still an array at this point

Reproduction repo

No response

llucasspot commented 4 months ago

https://github.com/adonisjs/auth/pull/238

llucasspot commented 4 months ago

My mistake, my access token migration file used json and not text for the abilities column (maybe a forgotten change when i was migrating v5 to v6)

I close the ticket thx