I need help. I’m building a web application with Django and React. I’m working on the registration and login functionality, and so far the registration works well and creates a user in the database. However, when I try to log in, it always returns a 401 error, even though the user is in the database.
This is the Django code:
from django.contrib.auth.hashers import check_password
from django.db import models
class Usuario_aplicacion(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=100)
email = models.EmailField()
def __str__(self):
return self.username
def check_password(self, raw_password):
return check_password(raw_password, self.password)
views.py:
import bcrypt
from django.contrib.auth import authenticate, login
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.views.decorators.csrf import csrf_exempt
from .UsuarioSerializer import UsuarioSerializer
from .models import Usuario_aplicacion
@api_view(['POST'])
@csrf_exempt
def registro(request):
serializer = UsuarioSerializer(data=request.data)
if serializer.is_valid():
usuario = serializer.save()
hashed_password = bcrypt.hashpw(usuario.password.encode('utf-8'), bcrypt.gensalt())
usuario.password = hashed_password.decode('utf-8')
usuario.save()
return Response({'message': 'User created'}, status=201)
return Response(serializer.errors, status=400)
@api_view(['POST'])
@csrf_exempt
def login_user(request):
username = request.data.get('username')
password = request.data.get('password')
try:
usuario = Usuario_aplicacion.objects.get(username=username)
if usuario.check_password(password):
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return Response({'success': True})
except Usuario_aplicacion.DoesNotExist:
pass
return Response({'success': False}, status=401)
UsuarioSerializer.py:
from django.contrib.auth.hashers import make_password
from rest_framework import serializers
from users.models import Usuario_aplicacion
class UsuarioSerializer(serializers.ModelSerializer):
class Meta:
model = Usuario_aplicacion
fields = ['username', 'password', 'email']
def create(self, validated_data):
usuario = Usuario_aplicacion(**validated_data)
usuario.save()
return usuario
and the form in react:
import React, { useState } from 'react';
import axios from 'axios';
function LoginForm() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [message, setMessage] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
axios.post('http://127.0.0.1:8000/apiusers/login/', {
username: username,
password: password,
})
.then(response => {
if (response.data.success) {
setMessage('Login successful');
} else {
setMessage('Login failed');
}
})
.catch(error => {
setMessage('Login failed');
});
};
return (
<form onSubmit={handleSubmit}>
<input type="hidden" name="csrfmiddlewaretoken" value="{% csrf_token %}" />
<label>
Username:
<input type="text" value={username} onChange={(event) => setUsername(event.target.value)} />
</label>
<label>
Password:
<input type="password" value={password} onChange={(event) => setPassword(event.target.value)} />
</label>
<button type="submit">Login</button>
{message && <div>{message}</div>}
</form>
);
}
export default LoginForm;