Fakultas Ilmu Komputer UI

views.py 3.62 KB
Newer Older
Usman Sidiq's avatar
Usman Sidiq committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import requests
import random
from urllib.parse import parse_qs, urlparse

from rest_framework.utils import json
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.permissions import IsAuthenticated
from rest_framework.authtoken.models import Token

from django.views.decorators.csrf import csrf_exempt

from django.http import JsonResponse, HttpResponse
from django.contrib.auth import authenticate
from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User
from pplbackend.settings import GOOGLE_OAUTH2_CLIENT_ID, GOOGLE_OAUTH2_CLIENT_SECRET

from registrasi.models import BisaGoUser

@csrf_exempt
def request_token(request):
    if request.method == "POST":
        email = request.POST["username"]
        password = request.POST["password"]
        google = request.POST.get("google", False)
        response = {}
        status = 200
        if google:
            access_token = request.POST["access_token"]
Usman Sidiq's avatar
Usman Sidiq committed
33
            name = request.POST["name"]
Usman Sidiq's avatar
Usman Sidiq committed
34
35
36
            try:
                user = User.objects.get(email=email)
            except User.DoesNotExist:
Usman Sidiq's avatar
Usman Sidiq committed
37
                user, status = _request_token_from_google(email, access_token, name)
Usman Sidiq's avatar
Usman Sidiq committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
        else:
            try:
                user = authenticate(request, username=email, password=password)
            except User.DoesNotExist:
                response["response"] = "User not exist"
                return JsonResponse(response, status=404)
        if status != 200:
            return response
        if user is not None:
            if user.is_active:
                #print("user active")
                token, create = Token.objects.get_or_create(user=user)
                response = {}
                response['username'] = user.username
                response['token'] = token.key
                response['token_type'] = "token"
                return JsonResponse(response, status=200)
            else:
                response["response"] = "Please activate your account"
                return JsonResponse(response, status=400)
        else:
            response["response"] = "Wrong password"
            return JsonResponse(response, status=400)
        
@csrf_exempt
Usman Sidiq's avatar
Usman Sidiq committed
63
def _request_token_from_google(email, access_token, name):
Usman Sidiq's avatar
Usman Sidiq committed
64
65
66
67
68
69
70
71
72
73
74
75
    payload = {'access_token': access_token}  # validate the token
    req = requests.get('https://www.googleapis.com/oauth2/v2/userinfo', params=payload)
    data = json.loads(req.text)
    if 'error' in data:
        content = {'message': 'wrong google token / this google token is already expired.'}
        return None, JsonResponse(content, status=404)
    user = User()
    user.username = email
    # provider random default password
    user.password = make_password(BaseUserManager().make_random_password())
    user.email = email
    user.is_active = True
Usman Sidiq's avatar
Usman Sidiq committed
76
    user.last_name = name
Usman Sidiq's avatar
Usman Sidiq committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
    user.save()
    random_generated_phone_number = 'x'.join([str(random.randint(0, 9)) for i in range(8)])
    BisaGoUser.objects.create(user=user, phone_number=random_generated_phone_number)
    return user, 200


@csrf_exempt
def validate_google_token(email, access_token):
    payload = {'access_token': access_token}  # validate the token
    req = requests.get('https://www.googleapis.com/oauth2/v2/userinfo', params=payload)
    data = json.loads(req.text)
    if 'error' in data:
        content = {'message': 'wrong google token / this google token is already expired.'}
        return None, JsonResponse(content, status=404)
    return User.objects.get(email=email)







99