Creating user and token in repl

This should be straight forward, but I could not find anything during multiple Google searches.

I have created a new adonis.js api application (version 4.1) which comes pre-baked with user and token migration/model, I can create a new user record using the repl but want to also create a new token record.

What is the proper way to import the configured auth class?

I see that auth is part of the context when executing a controller action, i.e.

class UserController {

  async login ({ auth, request }) {
    const { email, password } = request.all()
    await auth.attempt(email, password)

    return 'Logged in successfully'
  }
}

I want to run this code in repl

https://adonisjs.com/docs/4.1/authentication#_generateuser

const user = await User.find(1)

const token = await auth.generate(user)

I am assuming I can create an instance of auth once I import the class?

const Auth = use('......?????')
const auth = new Auth()

Tried multiple paths and none worked.

Ok, I am now able to create a token for the user, however I cannot authenticate using that token?

adonis repl

const Config = use('Config')
const Auth = use('@adonisjs/auth/src/Auth')
const auth = new Auth({}, Config)

const User = use('App/Models/User')
const user = await User.find(5)

auth.generate(user)

This is using api authentication configuration:

  • config/auth.js
'use strict'

/** @type {import('@adonisjs/framework/src/Env')} */
const Env = use('Env')

module.exports = {
  authenticator: 'api',
  api: {
    serializer: 'lucid',
    model: 'App/Models/User',
    scheme: 'api',
    uid: 'email',
    password: 'password'
  }
}

Route is configured:

Route.get('/widgets', 'WidgetController.index').middleware(['auth'])

Logging SQL when I make the request using bearer token that matches token record in the database:

info: serving app on http://127.0.0.1:3333
{
  method: 'first',
  options: {},
  timeout: false,
  cancelOnTimeout: false,
  bindings: [ 'api_token', false, 1 ],
  __knexQueryUid: 'd372681a-ca4f-4ac8-8561-0788ce7ff00d',
  sql: 'select * from "users" where exists (select * from ' +
    '"tokens" where "token" is null and "type" = ? and ' +
    '"is_revoked" = ? and "users"."id" = "tokens"."user_id") ' +
    'limit ?'
}

That query seems very odd where token is null; the create tokens database migration does not allow null for that column?

Maybe that is neither here nor there?

Thinking when I generate the token it is not being generated correctly?

Any guidance is appreciated.

1 Like

Hi @house9 and welcome to forums!

It might be late already, but can you elaborate little bit what are you trying to achieve?

1 Like

I want to create a user with a valid api token via the repl and then I want to authenticate a protected route using that token via HTTP.