How I can use login (email and password) validation in Adonisjs api and send message client side

how I can use login (email and password) validation in Adonisjs api and send message client side

I want to this:
check the email and password in the database
if incorrect send error message: user does not exists or the password does not match…
if true send succes message: successful entry!

I try @adonisjs/validator But it s not for me!
I think I need Custom exceptions and I couldn’t find any examples for this

i use backend: Adonisjs Api frontend: angular 7

how can i do it step by step?

can someone help me

Step 1: Be more specific about what it is you’re hoping to achieve
Step 2: Tell us what you’ve already tried that isn’t working

We’ll go from there.

hi, willvincent

firstly thanks for your reply…

My first meeting with adonisjs …
I looked at the adonis documentation but don’t understand
and I looked at the adonis forum I could not find a way for understanding

I use adonis js as api,
I want to do this:

  • check email in database and display error message
  • check password in database and display error message

and then I’ll use this verification in my other forms

step by step how can I do it
can you please tell me


this UserController.js

‘use strict’;

const User = use(‘App/Models/User’);

class UserController {

async login({ request, response, auth }) {

const {email, password} = request.only([‘email’, ‘password’])

    try {
        if(await auth.attempt(email, password)) {
            let user = await User.findBy('email', email)
            let token = await auth.generate(user)

            Object.assign(user, token)

            return response.json(user)
        }
    } catch (e) {
        console.log(e)
        return response.json({message: 'böyle bir kullanıcı kayıtlı değildir!'})
    }

}

}

module.exports = UserController

this routes.js

Route.group( () => {

Route.post(‘register’, ‘UserController.register’)
Route.post(‘login’, ‘UserController.login’)
.middleware(‘verifyPassword’)
.validator(‘LoginUser’)

}).prefix(‘api’)

this Validator (App/Validators/LoginUser.js)

‘use strict’

class LoginUser {

get rules () {
return {
email: ‘required|email|unique:users’,
password: ‘required’
}
}

get messages () {
return {
‘email.required’: ‘You must provide a email address.’,
‘email.email’: ‘You must provide a valid email address.’,
‘email.unique’: ‘This email is already registered.’,
‘password.required’: ‘You must provide a password’
}
}

async fails(errorMessages) {
return this.ctx.response.status(400).json({
message: errorMessages[0].message
});
}

}

module.exports = LoginUser

this VerifyPassword.js (App/Middleware/VerifyPassword.js)

class VerifyPassword {

async handle ({ request, auth, response }, next, properties) {

const { email, password } = request.all();
const user = await User.findBy('email', email)
const passwControl = await Hash.verify(password, user.password)

if (!passwControl) {
  return response.status(400).json({
    message: "incorrect password!"
  });
}

await next()

}
}

module.exports = VerifyPassword

can someone please help me

Hi @necati

Do you get any error messages? From first fast look it seems like it should work fine

hi McSneaky,

firstly thanks for reply

I want to this:
check the email and password in the database
if incorrect send error message: user does not exists or the password does not match…
if true send succes message: successful entry!

I try @adonisjs/validator But it s not for me!
I think I need Custom exceptions and I couldn’t find any examples for this

how i can to do it step by step plase tell me?


I try this:
(App/Exceptions/UserExitException.js)

‘use strict’

const { LogicalException } = require(’@adonisjs/generic-exceptions’)

class UserExitException extends LogicalException {
/**

  • Handle this exception by itself
    */
    handle (error, { response }) {
    if(error.code === ‘E_USER_NOT_FOUND’ || ‘E_PASSWORD_MISMATCH’ ) {
    return response.json({
    error: ‘user does not exists or the password does not match’
    })
    }

}
}

module.exports = UserExitException


BUT I DON’T KNOW WHERE and HOW TO USE THİS METHOD

I try this and working
is this right method?


async login({ request, response, auth }) {

    const { email, password } = request.only(['email', 'password'])

    try {

        if (await auth.attempt(email, password)) {

            let user = await User.findBy('email', email)

            let token = await auth.generate(user)

            Object.assign(user, token)

            return response.json(user)
        }

    } catch (e) {

        if (e.code === 'E_USER_NOT_FOUND') {
            return response.send('user does not exists');
        }

        if (e.code === 'E_PASSWORD_MISMATCH') {
            return response.send('password does not match');
        }
    }
}

I would put some status code to the response. Something like

return response.status(401).send('password ...')

So the client will know that there was an error.

1 Like

ok thank u