I'm new to Flask and React.
I'm confused on how I can get the Authorization Token to logout.
On Postman I can Register/login/logout a user just fine.
But when it comes to getting the header Authentication 'Bearer' from the frontend I find I'm stuck.
This is what I got so far when trying to fetch the Authorization.
const [ email, setEmail] = useState('')
const [ password, SetPassword] = useState('')
const onSubmitClick = (e) => {
e.preventDefault()
console.log('You pressed login')
let opts = {
'email': email,
'password': password
}
console.log(opts)
fetch('/auth/login', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(opts)
}).then(r => r.json())
.then(token => {
if (token.auth_token){
login(token)
console.log(token)
}
else {
console.log("Please type in the correct Email or Password")
}
})
}
const onLogoutClick = (e) => {
fetch('/auth/login', {
method: 'post',
headers: {
'Authorization': `Basic `,
'Content-Type': 'application/json'
},
}).then(r => r.json())
.then(token => {
if (token.auth_token){
login(token)
console.log(token)
}
else {
console.log("Please type in the correct Email or Password")
}
})
}
Login Api:
class LoginAPI(MethodView):
def post(self):
post_data = request.get_json()
try:
user = User.query.filter_by(
email=post_data.get('email')
).first()
if user and bcrypt.check_password_hash(
user.password, post_data.get('password')
):
auth_token = user.encode_auth_token(user.id)
if auth_token:
responseObject = {
'status': 'success',
'message': 'Successfully logged in.',
'auth_token': auth_token.decode()
}
return make_response(jsonify(responseObject)), 200
else:
responseObject = {
'status': 'fail',
'message': 'User does not exist.'
}
return make_response(jsonify(responseObject)), 404
except Exception as e:
print(e)
responseObject = {
'status': 'fail',
'message': 'Try again'
}
return make_response(jsonify(responseObject)), 500
Logout Api:
class LogoutAPI(MethodView):
def post(self):
auth_header = request.headers.get('Authorization')
if auth_header:
auth_token = auth_header.split(" ")[1]
else:
auth_token = ''
if auth_token:
resp = User.decode_auth_token(auth_token)
if not isinstance(resp, str):
blacklist_token = BlacklistToken(token=auth_token)
try:
db.session.add(blacklist_token)
db.session.commit()
responseObject = {
'status': 'success',
'message': 'Successfully logged out.'
}
return make_response(jsonify(responseObject)), 200
except Exception as e:
responseObject = {
'status': 'fail',
'message': e
}
return make_response(jsonify(responseObject)), 200
else:
responseObject = {
'status': 'fail',
'message': resp
}
return make_response(jsonify(responseObject)), 401
else:
responseObject = {
'status': 'fail',
'message': 'Provide a valid auth token.'
}
return make_response(jsonify(responseObject)), 403
Being new to reach I really believe I'm a silly mistake somewhere
Postman everything works fine, only problem is frontend logout!
Thanks a lot!