I am using React as frontend
and Python & Flask as my backend
with Rauth
as OAuth2
for Facebook login and storing details of every user in db and using flask_login
as protection. Those information are Sports, Education, Phone number and other things.
What I am doing is after user gets logged in I am trying to fetch
his details from react app. But I am getting error user not logged in while on browser if I open that API I can see the json
.
@login_manager.user_loader
def load_user(id):
return User.select().where(User.id == id).first()
@app.route('/')
def index():
return redirect(WEB_URL)
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(WEB_URL)
@app.route('/me')
@login_required # After removing decorator still I am not getting
def me():
return jsonify({'email': current_user.email}), 200
@app.route('/authorize/<provider>')
def oauth_authorize(provider):
if not current_user.is_anonymous:
return redirect(WEB_URL)
oauth = OAuthSignIn.get_provider(provider)
return oauth.authorize()
@app.route('/callback/<provider>')
def oauth_callback(provider):
if not current_user.is_anonymous:
return redirect(WEB_URL)
oauth = OAuthSignIn.get_provider(provider)
social_id, username, email = oauth.callback()
if social_id is None:
return redirect(WEB_URL)
user = User.select().where(User.social_id == social_id).first()
if not user:
user = User(social_id=social_id, nickname=username, email=email)
user.save()
login_user(user, True)
return redirect(WEB_URL)
So from fronend I am calling /authorize/<provider>
which then redirects to /callback/<provider>
and logs user in.
Now When I am opening /me
on browser it works fine returns required json
or redirects me to homepage.
But when I am trying to fetch the api from frontend or Postman either I am getting user not found (if I remove the decorator login_required
) or returning the whole homepage.
I am fetching like this:
componentWillMount() {
fetch('http://localhost:5000/me').then(function(response) {
const contentType = response.headers.get("content-type");
if(contentType && contentType.includes("application/json")) {
return response.json();
}
}).then(function(json) {
debugger
const self = this;
if (json) self.serState({ loggedIn: true });
}).catch(function(error) { console.log(error); });
}
My frontend
is running on http://localhost:3000/
Got the Answer Backend add this line after importing flask_cors
CORS(app, supports_credentials=True)
And Fetch using
fetch('http://localhost:5000/me', {
method: 'GET',
credentials: 'include'
})