Trouble with User Logging in username instead of email


#1

I’m not exactly what is wrong. I am following this tutorial. The tutorial uses email for logging in , but I wanted to use username so I made a few adjustments, however it does not seem to work.

This is what I have:

login.edge

@layout('layouts.main')
@section('title')
JobPostr - Login
@endsection
@section('extra_css')
{{ style('forms') }}
@endsection

@section('content')
<h1>Login Now</h1>
<div class="job-container">
  @if(flashMessage('loginError'))
  <span> {{ flashMessage('loginError') }} </span>
  @endif
  <form  action="{{ route('UserController.login') }}" method="POST">
    {{ csrfField() }}
    <label for="username">Username</label>
    <input type="text" name="username" value="{{ old('username','') }}">
    @if(hasErrorFor('username'))
    <span>
      {{ getErrorFor('username')}}
    </span>
    @endif

    <label for="password">Password</label>
    <input type="password" name="password">
    @if(hasErrorFor('password'))
      <span>
        {{ getErrorFor('password')}}
      </span>
    @endif

    <button type="submit">Login Now</button>
  </form>
</div>
@endsection

routes.js

'use strict'

/*
|--------------------------------------------------------------------------
| Routes
|--------------------------------------------------------------------------
|
| Http routes are entry points to your web application. You can create
| routes for different URL's and bind Controller actions to them.
|
| A complete guide on routing is available here.
| http://adonisjs.com/docs/4.1/routing
|
*/

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

Route.get('/', 'JobController.home'); //renders view in controller

Route.on('/signup').render('auth.signup')
Route.post('/signup', 'UserController.create').validator('CreateUser') //goes through validator first

Route.on('/login').render('auth.login')
Route.post('/login', 'UserController.login').validator('LoginUser')

Route.get('/logout', async({auth, response})=>{
  await auth.logout();
  return response.redirect('/');
});

User.js

'use strict'

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

/** @type {typeof import('@adonisjs/lucid/src/Lucid/Model')} */
const Model = use('Model')

class User extends Model {
  static boot () {
    super.boot()

    /**
     * A hook to hash the user password before saving
     * it to the database.
     */
    this.addHook('beforeSave', async (userInstance) => {
      if (userInstance.dirty.password) {
        userInstance.password = await Hash.make(userInstance.password)
      }
    })
  }

  /**
   * A relationship on tokens is required for auth to
   * work. Since features like `refreshTokens` or
   * `rememberToken` will be saved inside the
   * tokens table.
   *
   * @method tokens
   *
   * @return {Object}
   */
  tokens () {
    return this.hasMany('App/Models/Token')
  }
}

module.exports = User

UserController.js

'use strict'
const User = use('App/Models/User')

class UserController {
  async create({request, response, auth}){

    const user = await User.create(request.only(['username','email', 'password'])) //request include csrf token
    await auth.login(user);
    return response.redirect('/');
  }

  async login({request, response, auth, session}){
    const {username, password} = request.all();

    try {
      await auth.attempt(username, password);
      return response.redirect('/')
    } catch (error) {
      session.flash({loginError: "These credentials are incorrect (:_;)"});
      return response.redirect('/login');
    }

  }

}

module.exports = UserController

LoginUser.js

'use strict'

class LoginUser {

  get rules () {
    return {
      // validation rules
      "username": "required",
      "password": "required"
    }
  }
  get validateAll () {
    return true
  }
  get messages(){
    return {
      'required': 'Woah now, {{field}} is required'
    }
  }

  async fails(error){
    this.ctx.session.withErrors(error).flashAll();
    return this.ctx.response.redirect('back');
  }
}

module.exports = LoginUser

auth.js

'use strict'

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

module.exports = {
  
  authenticator: 'session',

  session: {
    serializer: 'lucid',
    model: 'App/Models/User',
    scheme: 'session',
    uid: 'username',
    password: 'password'
  },

  basic: {
    serializer: 'lucid',
    model: 'App/Models/User',
    scheme: 'basic',
    uid: 'username',
    password: 'password'
  },

  api: {
    serializer: 'lucid',
    model: 'App/Models/User',
    scheme: 'api',
    uid: 'email',
    password: 'password'
  }
}

#2

Nvm. It magically works now.