I want to log in on Flutter, but it does not remain Authenticated in Django as well as on Flutter.
I just want the user to stay logged in on Flutter by storing tokens so it remains authenticated, but if possible also on Django server.
Views.py
class LoginAPIView(APIView):
def post(self, request):
username = request.data.get('username')
phonenumber = request.data.get('phonenumber')
password = request.data.get('password')
try:
user = UserProfile.objects.get(
username=username, phone_number=phonenumber)
except UserProfile.DoesNotExist:
# Handle the case where the user with the given username doesn't exist
return Response({"message": "A user or phone number does not found."}, status=status.HTTP_400_BAD_REQUEST)
print(user)
if user.password == password:
if user is not None: # if user.check_password(password):
# Password is correct, log in the user
print(user)
login(request, user)
# Generate JWT token
payload = {
'user_id': user.id,
'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
'iat': datetime.datetime.utcnow()
}
token = jwt.encode(payload, 'secret', algorithm='HS256')
uname = username
# Set the token as a cookie
# print(token)"jwt": token,
return Response({"message": "Successfully Login", "jwt": token, "uname": uname}, status=status.HTTP_200_OK)
# response = Response(
# {"message": "Successfully Login", "uname": uname}, status=status.HTTP_200_OK)
# response.set_cookie(key='jwt', value=token, httponly=True)
return response
else:
# Password is incorrect
raise AuthenticationFailed(
{"message": "Password Incorrect"}, code=status.HTTP_401_UNAUTHORIZED)
Flutter Code:
onPressed: () async {
var username = usernameController.text;
final phonenumber = phoneNumberController.text;
final password = passwordController.text;
const apiUrl = 'http://127.0.0.1:8000/Login/';
AuthService authService = AuthService();
var token;
final response = await http.post(
Uri.parse(apiUrl),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({
'Authorization': 'Bearer $token',
'username': username,
'phonenumber': phonenumber,
'password': password,
}),
);
if (response.statusCode == 200) {
// Handle successful response
final Map<String, dynamic> responseData =
json.decode(response.body);
final String token = responseData['jwt'];
print(token);
setState(() {
message = responseData['message'];
uname = responseData['uname'];
});
const storage = FlutterSecureStorage();
// await storage.write(key: 'jwt', value: token);
In General you would required 2 API
Here is the Simple Process you can follow as a starting point
JWT tokenfrom your server.JWT tokenyou will have to store as you're doing in the code you've provided.JWT Tokenanddeserializeit just to see if theJWT tokenis expired or not, if its not you can mark your userauthenticatedotherwise you can call 2nd API torefresh the token