Firebase part IV: validation and login

1st Oct 19
design plan

I will discuss how I added validation to the signup and will add a login route.

I create a helper function checking whether the string is empty.

const isEmpty = (string) => {
    if(string.trim() === '') return true;
    else return false;
}

Also a helper function to check for a valid email (regEx expression too long to include but took it from regEx email on the web): 

const isEmail = (email) => {
    const regEx = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+).....;
    if(email.match(regEx)) return true;
    else return false;
}

 

Now in my signup route I add a check for the email input: 

 let errors = {};

    if(isEmpty(newUser.email)){
        errors.email = 'email must not be empty';
    }else if(!isEmail(newUser.email)){
        errors.email = 'Must be a valid email address'
    }

 And for the rest of the input fields: 

 if(isEmpty(newUser.password)) errors.password = 'Must not be empty';
 if(newUser.password !== newUser.confirmPassword) errors.confirmPassword = 'Passwords must match';
 if(isEmpty(newUser.handle)) errors.handle = 'Must not be empty';

I need to check whether there are errors in my errors object and if so return a bad request response with the errors object.

    if(Object.keys(errors).length > 0) return res.status(400).json(errors);

 

Login Route

Similar to the sign route I assign the request data to an object called user and validate the data.

app.post('/login', (req, res) => {
    const user = {
        email: req.body.email,
        password: req.body.password
    };

    let errors = {};
    
    if(isEmpty(user.email)) errors.email = 'Must not be empty';
    if(isEmpty(user.password)) errors.password = 'Must not be empty';
    if(Object.keys(errors).length > 0) return res.status(400).json(errors);

If there are no errors I use the firebase library to login the user, get the token and return the token with the response.

  firebaseLib.auth().signInWithEmailAndPassword(user.email, user.password)
        .then(data => {
            return data.user.getIdToken()
        })
        .then(token => {
            return res.json({token});
        })
        .catch(err => {
            console.error(err);
            if(err.code === 'auth/user-not-found' || err.code === 'auth/wrong-password'){
                return res.status(403).json({general : 'Unknown login credentials'})    
            }else return res.status(500).json({error: err.code});          
        });

 

I have recently completed my apprenticeship.  I am currently building the API to a React JS site using Firebase.