1

So, I have created a django-rest-framework backend with JWT Authentication and now, I am trying to solve the problem where when user manually provides a URL, I have to check If the user was previously logged in.

So since, I am storing the token to localStorage when the user logged in. I am doing this:

componentDidMount() {
    if (localStorage.getItem('token')) {
        // fetch current user
        this.props.ctx.toggleLoggedIn()
        // this.props.ctx.setUsername('')
    }   
}

If I find a token in localStorage, then I have to fetch the current User and then, toggleLoggedIn and also set the current user's username in the context.

So, I am planning to create another API end-point which provides the current user when a token is given. The problem is I don't know how to start that!

1 Answer 1

2

It might be that i misunderstand, but for me it seems like you're trying to solve this a bit backwards. When the user login, get token and store this in localStorage. Right after login fetch the user profile and store this as well.

If the user manually provides a url, you should now have both token and user. If you don't have a token or it's expired, redirect to login page and clear local storage.

I would create a higher order component that checks if the token is valid and use this for all "protected" pages.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.