safak / youtube

5.07k stars 5.49k forks source link

Get 401 unauthorized while try to to login i can login with the same user name and password with postman but can't login from the application #145

Closed Manojooo7 closed 1 year ago

Manojooo7 commented 1 year ago

This is my login route

router.post("/login", async (req,res)=>{
    try{
        const user = await User.findOne({username: req.body.username});
        if (!user) {
          return res.status(401).json("Wrong user name!")
        }
        const hashedPassword =  CryptoJS.AES.decrypt(
            user.password, 
            process.env.PASS_SEC
            );
        const OriginalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);
        if (OriginalPassword !==req.body.password) {
          return res.status(401).json("Wrong password!");
        }

        const accessToken = jwt.sign({
            id:user._id,
            isAdmin: user.isAdmin,
        },process.env.JWT_SEC,{expiresIn:"3d"}
        );

        const {password, ...others} = user._doc;

        return res.status(200).json({...others, accessToken});
    }catch(err){
        res.status(500).json(err)
        console.log(err);
    }});

This is Request methods

import axios from "axios";

const BASE_URL = "http://localhost:5000/api/";
const TOKEN = "MY_TOKEN";

export const publicRequest = axios.create({
    baseURL: BASE_URL,
});

export const userRequest = axios.create({
    baseURL: BASE_URL,
    header: {token: `Bearer ${TOKEN}`}
})

This my user redux

import { createSlice } from "@reduxjs/toolkit";

const userSlice = createSlice({
  name: "user",
  initialState: {
    currentUser: null,
    isFetching: false,
    error: false
  },
  reducers: {
    loginStart:(state)=>{
      state.isFetching=true
    },
    loginSuccess:(state,action)=>{
      state.isFetching=false;
      state.currentUser=action.payload
    },
    loginFailure:(state)=>{
      state.isFetching=false;
      state.error=true;
    },
    },
  });

export const { loginStart,loginSuccess: loginSuccess,loginFailure: loginFailure } = userSlice.actions;
export default userSlice.reducer;

and this is my login function

const Login = () => { 
    const[userName,setUsername] = useState("");
    const[password,setPassword] = useState("");
    const dispatch = useDispatch()

    const handleClick = (e) =>{
        e.preventDefault()
        login(dispatch,{userName,password})
    }
  return (   
  <Container>
    <Wrapper>
        <Title>SIGN IN</Title>
        <Form>
            <Input placeholder="username" 
            onChange={(e)=>setUsername(e.target.value)}/>
            <Input placeholder="password"
            type="password"
            onChange={(e)=>setPassword(e.target.value)}
            />
            <Button onClick={handleClick}>LOGIN</Button>
            <Link>FORGET PASSWORD</Link>
            <Link>CREATE A NEW ACCOUNT</Link>
        </Form>
    </Wrapper>
</Container>
  )
}

export default Login

API call

import { loginFailure,loginStart,loginSuccess } from "./userRedux";
import {publicRequest} from "../requestMethods";

export const login= async (dispatch, user)=>{
    dispatch(loginStart());
    try {
        const res = await publicRequest.post("auth/login", user);
        dispatch(loginSuccess(res.data));
    } catch (err) {
        dispatch(loginFailure());
        console.log(err);
    }
};

I want to complete this project but I'm stuck here please help me to solve this error

Manojooo7 commented 1 year ago

I did a silly mistake using camel case on use state in a wrong way

Wrong Code const[userName,setUsername] = useState("");

Right Code const[username,setUsername] = useState("");