Home > Software engineering >  User or pass wrong message in service api
User or pass wrong message in service api

Time:03-08

I have this two codes

import React, { useState, useEffect, createContext } from "react"; 
import { useNavigate } from "react-router-dom";
import { api, createSession } from "./Services/api"

export const AuthContext = createContext();

export const AuthProvider = ({children}) => {
    const navigate = useNavigate();
    const [user, setUser] = useState();
    const [loading, setLoading] = useState(true)
 
    useEffect(() => {
        const recoveredUser = localStorage.getItem("user")
        if(recoveredUser){
            setUser(JSON.parse(recoveredUser))
        }
        setLoading(false);
    }, []); 

    const refreshPage = ()=>{
        window.location.reload();
     }

    const login = async (username, pass) => {
        const response = await createSession(username, pass);
        
        const loggedUser = response.data.user;
        const token = response.data.jwt;

        localStorage.setItem("user", JSON.stringify(loggedUser))
        localStorage.setItem("token", token)
        
        api.defaults.headers.Authorization = {
            "identifier": username,
            "password": pass
        }

        setUser(loggedUser)
       
        navigate("/");       
    };

    const logout = () => {
        localStorage.clear();
        api.defaults.headers.Authorization = null;
        setUser(null);
        navigate("/login")
        refreshPage();
    };

    return(
        <AuthContext.Provider value={{authenticated: !!user, user, login, logout, loading}}> {children} </AuthContext.Provider>
    )
}

and this

import axios from "axios";

export const api = axios.create({
    baseURL: "https://communicationadmin.grupostra.com",
});

export const createSession = async(identifier, password) => {
    return api.post('/auth/local', {identifier, password});
}

and this is my login screen

import Input from '../components/Input';
import styles from './Login.module.css';
import { useState, useContext } from 'react';
import { AuthContext } from '../Auth'
import logo from '../img/grupostra_horizontal.png'
import openEye from '../img/eye.png'
import closedEye from '../img/closedeye.png'

function Login(){
    const { login } = useContext(AuthContext);
    const [eyeImg, setEyeImg] = useState(openEye);

    function handdleClick(){    
         if(eyeImg === openEye){
            setEyeImg(closedEye);
            document.querySelector('input:nth-child(4)').type = "";
        } else {
            setEyeImg(openEye)
            document.querySelector('input:nth-child(4)').type = "password";
        } 
    } 

    function handleSubmit(e){
        e.preventDefault();
        login(user, pass); 
    }

    const [user, setUser] = useState('');
    const [pass, setPass] = useState('');

    return(
        <div className={styles.container}>
            <div className={styles.form_container}>
                <img src={logo} alt="group" srcset="" />
                <p>Welcome</p>
                <form onSubmit={handleSubmit}>
                    <label htmlFor="username">Usuário</label>
                    <Input type="text" name="username" id="username" placeholder="User" setProps={setUser} value={user}/>
                    <label htmlFor="password">Senha</label>
                    <Input type="password" name="password" id="password" placeholder="Pass" setProps={setPass} value={pass}/>
                    <span onClick={handdleClick}><img src={eyeImg} className={styles.eyeImg} /></span>
                    <Input className="btn-hover" type="submit" name="submit" id="submit" value="Enter" />
                </form>
            </div>
        </div>
    )
}

export default Login

My question is how can or where a write an alert to show to users when your credentials are wrong? I tried some things, but i don't have sucess . (I want to show in a login screen) ........................................................................................

CodePudding user response:

If the server handle the "wrong credentials" as an HTTP Code 4XX or 5XX then you can just catch the exception an do something about it

async handleSubmit(e){
   e.preventDefault();
   await login(user, pass).catch(exp => alert("Something happened, maybe invalid credentials"))
}

CodePudding user response:

can you check your api response when it is giving error .when we are creating login api's if any error is there we are adding exceptions handlers to show those messages .if that is the case use below code

*

import Input from '../components/Input';
import styles from './Login.module.css';
import { useState, useContext } from 'react';
import { AuthContext } from '../Auth'
import logo from '../img/grupostra_horizontal.png'
import openEye from '../img/eye.png'
import closedEye from '../img/closedeye.png'
function Login(){
    const { login } = useContext(AuthContext);
    const [eyeImg, setEyeImg] = useState(openEye);
    const [error,seterror]=useState('')
    function handdleClick(){    
         if(eyeImg === openEye){
            setEyeImg(closedEye);
            document.querySelector('input:nth-child(4)').type = "";
        } else {
            setEyeImg(openEye)
            document.querySelector('input:nth-child(4)').type = "password";
        } 
    } 
    async function handleSubmit(e){
     try
     {
        e.preventDefault();
        awiat login(user, pass); 
     } catch(error){
        seterror(error.message.toString())
     }
        
    }
    const [user, setUser] = useState('');
    const [pass, setPass] = useState('');
    return(
        <div className={styles.container}>
            <div className={styles.form_container}>
                <img src={logo} alt="group" srcset="" />
                <p>Welcome</p>
                <p>{error}</P>
                <form onSubmit={handleSubmit}>
                    <label htmlFor="username">Usuário</label>
                    <Input type="text" name="username" id="username" placeholder="User" setProps={setUser} value={user}/>
                    <label htmlFor="password">Senha</label>
                    <Input type="password" name="password" id="password" placeholder="Pass" setProps={setPass} value={pass}/>
                    <span onClick={handdleClick}><img src={eyeImg} className={styles.eyeImg} /></span>
                    <Input className="btn-hover" type="submit" name="submit" id="submit" value="Enter" />
                </form>
            </div>
        </div>
    )
}
export default Login
  • Related