Daniel Kilanko
Daniel Kilanko

Reputation: 110

How to build a DRF API and consume it in the same project

I'm working on a DRF API, i will like to consume the API on the same project rather than using Django ORM structure,

I have successfully Login a user and generated a token. Now i want to restrict a Django View based on a response of an API call

class Login(generic.FormView):
    template_name = 'registration/login.html'
    form_class = LoginForm
    success_url = reverse_lazy('customer_dashboard')

    def form_valid(self, form):
        parameters = {
            'username': str(form.cleaned_data['username']),
            'password': str(form.cleaned_data['password']),
        }
        #  Param from LOGIN form posted to API, if token response, means user is authenticated and active
        headers = {"Content-Type": 'application/json'}
        response = requests.post(str(settings.API_END_POINT + '/api-token-auth/'), json=parameters, headers=headers)
        data = response.json()

        #  response CODE 2xx means a success, if POST request is success, then save USE TOKEN and ID to session
        if response.status_code in settings.SUCCESS_CODES:
            self.request.session['validated_user_token'] = data['token']
            self.request.session['validated_user_id'] = data['user_id']

            #  get request from all_user end_point and match USER ID from before to list to fetch user details
            headers = {"Content-Type": 'application/json', "Authorization": "Token " + settings.API_TOKEN}
            response = requests.get(str(settings.API_END_POINT + '/users_api/'),  headers=headers)
            users = response.json()

            print(self.request.session['validated_user_id'])
            for user in users:
                if user['id'] == self.request.session['validated_user_id']:
                    messages.success(self.request, 'Hi' + ' ' + user['first_name'] + ' ' + user['last_name'])
        else:
            messages.error(self.request, 'Invalid Credentials')

        return super(Login, self).form_valid(form)

Here i have the username the password passed to an API post request, that authenticate the credentials and return a Token and User_id. Now based on the i will like to restrict the Dashboard(codes below) to those users authenticated above.

class CustomerDashboard(generic.TemplateView):
    template_name = 'customer/dashboard.html'

I will like the CustomerDashboard() to be restricted to users that have been authenticated by the API call

Upvotes: 0

Views: 300

Answers (1)

Dharanidhar Reddy
Dharanidhar Reddy

Reputation: 878

I have no idea why you actually made login this complicated. You can use built-in authentication. you can tweak this for any other functionality.

urls.py

from django.contrib.auth import views

urlpatterns = [
    path('login/', views.LoginView.as_view(redirect_authenticated_user=True), name='login'),
    path('dashboard/', dashboard.Dashboard.as_view(), name='dashboard'),
]

views.py

from django.contrib.auth.mixins import LoginRequiredMixin
class Dashboard(LoginRequiredMixin, generic.TemplateView):
    template_name = "dashboard.html"
    ...

This worked perfectly fine for me.

Upvotes: 1

Related Questions