Signup and Login using Adonisjs with MYSQL database

Signup and Login using Adonisjs with MYSQL database

Adonisjs is a node JS framework which provides a MVC and ORM functionalities to make better, efficient and fast development environment. If you have not installed the Adonisjs framework click here to learn how to install the framework. In this post we will learn the code to Signup and Login using Adonisjs with MYSQL database.

For this I am creating a controller using the following command –

adonis make:controller AuthController --type http

for creating models we can use make:model command to create the model. Models are basically Lucid models, which provides many benefits includes fetching and persisting model data and an expressive API to mange relationships.

adonis make:model User

here is the controller with singup and login functionality..

'use strict'
const {validateAll} = use('Validator')
const User = use('App/Models/User')
const Hash = use('Hash')

class AuthController {

    /**
     * signup functionality
     * @param {*} param0 
     */
    async signup({request,response}){
        const rules = {
            email: 'required',
            fullname: 'required',
            password: 'required'
        }
//validate the request parameters
        const validation = await validateAll(request.all(), rules)
        if(validation.fails()){
//return the json response
            return response.json({'code':'error','message':validation.messages().map(function(v,i){
                return v['message']
            }),'data':[]})
        }
        //insert data into database
        const user = new User(); //user model
        user.firstName = request.input('fullname')
        user.email = request.input('email')
        user.password = request.input('password') //it automatically generate Hash of the password
        await user.save()
        if(user.id > 0){
            return response.json({'code':'success','message':'Successfully registered','data':user})
        }
        return response.json({'code':'error','message':'Something went wrong','data':[]})
    }

    /**
     * login functionality
     * @param {*} param0 
     */
    async login({request,response}){
        const rules = {
            email: 'required',
            password: 'required'
        }
        const validation = await validateAll(request.all(), rules)
        if(validation.fails()){
            return response.json({'code':'error','message':validation.messages().map(function(v,i){
                return v['message']
            }),'data':[]})
        }
        //get user data by email
        const userDetail = await User.query().where('email',request.input('email')).first()
        if(userDetail){
//verify the hashed password from database
            const verifyStatus = await Hash.verify(request.input('password'),userDetail.password)
            if(verifyStatus){
                return response.json({'code':'success','message':'Log in successful','data':userDetail})
            }else{
                return response.json({'code':'error','message':'Invalid password','data':[]})
            }
        }else{
            return response.json({'code':'error','message':'User Not found','data':[]})
        }

    }
}

module.exports = AuthController

It will create a User model class with which you can perform database queries with user table in mysql database. here is the model code :

'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

tokens () is default function in the model if there is Token model in the model directory and db table which having the has many relationship with users table.

Now go to the start/routes.js and create the route as follows :

Route.post('/login','AuthController.login');
Route.post('/signup','AuthController.signup');

Now you can run the functionality with the path http://127.0.0.1:3333/signup & login. here 3333 is the port number added in the env file. That’s it and enjoy Adonisjs.

Techspook

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment