sei-ec-remote / project-4-issues

Open an issue to receive help on project 4
0 stars 0 forks source link

Unauthorized error when making API call #35

Closed alquador closed 2 years ago

alquador commented 2 years ago

What stack are you using?

(ex: MERN(mongoose + react), DR(django + react), PEN, etc.)

DR

What's the problem you're trying to solve?

I am trying to make the api call to pull the index from one of my models but I keep running into an unauthorized error. Yet, when I log in my user id, email and token all are logged in the console.

Post any code you think might be relevant (one fenced block per file)

import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'

import { signIn } from '../../api/auth'
import messages from '../shared/AutoDismissAlert/messages'

import Form from 'react-bootstrap/Form'
import Button from 'react-bootstrap/Button'

const SignIn = (props) => {
    // constructor(props) {
    //  super(props)

    //  this.state = {
    //      email: '',
    //      password: '',
    //  }
    // }
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    const navigate = useNavigate()

    const [token, setToken] = useState()
    if(!token) {
        return <SignIn setToken={setToken} />
      }

    // handleChange = (event) =>
    //  this.setState({
    //      [event.target.name]: event.target.value,
    //  })

    const onSignIn = (event) => {
        event.preventDefault()
        console.log('the props', props)
        const { msgAlert, setUser } = props

        const credentials = {email, password}

        signIn(credentials)
            .then((res) => setUser(res.data.user))
            .then(() =>
                msgAlert({
                    heading: 'Sign In Success',
                    message: messages.signInSuccess,
                    variant: 'success',
                })
            )
            .then(() => navigate('/profiles'))
            .catch((error) => {
                setEmail('')
                setPassword('')
                msgAlert({
                    heading: 'Sign In Failed with error: ' + error.message,
                    message: messages.signInFailure,
                    variant: 'danger',
                })
            })
    }

    return (
        <div className='row'>
            <div className='col-sm-10 col-md-8 mx-auto mt-5'>
                <h3>Sign In</h3>
                <Form onSubmit={onSignIn}>
                    <Form.Group controlId='email'>
                        <Form.Label>Email address</Form.Label>
                        <Form.Control
                            required
                            type='email'
                            name='email'
                            value={email}
                            placeholder='Enter email'
                            onChange={e => setEmail(e.target.value)}
                        />
                    </Form.Group>
                    <Form.Group controlId='password'>
                        <Form.Label>Password</Form.Label>
                        <Form.Control
                            required
                            name='password'
                            value={password}
                            type='password'
                            placeholder='Password'
                            onChange={e => setPassword(e.target.value)}
                        />
                    </Form.Group>
                    <Button variant='primary' type='submit'>
                        Submit
                    </Button>
                </Form>
            </div>
        </div>
    )
}

export default SignIn
import apiUrl from '../apiConfig'
import axios from 'axios'

export const signUp = (credentials) => {
    return axios({
        method: 'POST',
        url: apiUrl + '/sign-up/',
        data: {
            credentials: {
                email: credentials.email,
                password: credentials.password,
                password_confirmation: credentials.passwordConfirmation,
            },
        },
    })
}

export const signIn = (credentials) => {
    return axios({
        url: apiUrl + '/sign-in/',
        method: 'POST',
        data: {
            credentials: {
                email: credentials.email,
                password: credentials.password,
            },
        },
        headers: {
            Authorization: `Token token=${user.token}`,
        },
    })
}

export const signOut = (user) => {
    return axios({
        url: apiUrl + '/sign-out/',
        method: 'DELETE',
        headers: {
            Authorization: `Token token=${user.token}`,
        },
    })
}

export const changePassword = (passwords, user) => {
    return axios({
        url: apiUrl + '/change-password/',
        method: 'PATCH',
        headers: {
            Authorization: `Token token=${user.token}`,
        },
        data: {
            passwords: {
                old: passwords.oldPassword,
                new: passwords.newPassword,
            },
        },
    })
}
import apiUrl from '../apiConfig'
import axios from 'axios'

// index function
export const getAllProfiles = () => {
    return axios(`${apiUrl}/profiles/`)
}

// index of user's profiles function
export const getMyProfiles = (user) => {
    return axios({
        url: `${apiUrl}/profiles/mine/`,
        method: 'GET',
        headers: {
            Authorization: `Token token=${user.token}`
        }
    })
}

//index of a specific user's profiles function
export const getOwnerProfiles = (ownerId) => {
    return axios(`${apiUrl}/profiles/user/${ownerId}/`)
}

//show function
export const getOneProfile = (profileId) => {
    return axios(`${apiUrl}/profiles/${profileId}/`)
}

// POST -> create function
export const createProfile = (user, newProfile) => {
    console.log('user', user)
    console.log('this is newProfile', newProfile)
    return axios({
        url: `${apiUrl}/profiles/`,
        method: 'POST',
        headers: {
            Authorization: `Token token=${user.token}`
        },
        data: { profile: newProfile }
    })
}

// PATCH -> update function
export const updateProfile = (user, updatedProfile) => {
    console.log('user', user)
    console.log('this is updatedProfile', updatedProfile)
    return axios({
        url: `${apiUrl}/profiles/${updatedProfile._id}/`,
        method: 'PATCH',
        headers: {
            Authorization: `Token token=${user.token}`
        },
        data: { profile: updatedProfile }
    })
}

// DELETE -> remove function
export const removeProfile = (user, profileId) => {
    console.log('user', user)
    return axios({
        url: `${apiUrl}/profiles/${profileId}/`,
        method: 'DELETE',
        headers: {
            Authorization: `Token token=${user.token}`
        }
    })
}

If you see an error message, post it here. If you don't, what unexpected behavior are you seeing?

Screen Shot 2022-04-26 at 1 43 04 PM

Weird error... because I am successfully making the api call for the specific users. I have tried several user logins successfully, and can successfully create a new sign up and log in with a token.

What is your best guess as to the source of the problem?

I think the issue is stemming from either a timing issue in react, or the user token is not recognized.

What things have you already tried to solve the problem?

I have tried setting state to a token within the signin to be able to pull the model data from the api with no luck. I have tried adding a authorization header to sign in and it does not like that... I have tried googling and applying solutions from there.

Paste a link to your repository here https://github.com/alquador/Project-4-Client

tkolsrud commented 2 years ago

Hey allison, we're taking a look at this. Sorry no helpful suggestions yet, but we're on it!

alquador commented 2 years ago

Thank you so much! Sorry I have been trying things all day and thinking I was on to something, but nope :(