Unverified Commit c266ea8e authored by Gabriel Geraldo's avatar Gabriel Geraldo Committed by GitHub

Merge pull request #2 from avraiel/user_auth

User auth merge into main line to fix mistake

mistake: not pulling after a successful merge reqeust done
parents e05abcf3 3900960e
from django.db import models from django.db import models
from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import AbstractUser, UserManager
class CustomUserManager(UserManager):
def create_user(self, email, password, **extra_fields):
if not email:
raise ValueError('Email for user must be set.')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self.create_user(email, password, **extra_fields)
# Create your models here. # Create your models here.
class CustomUser(AbstractUser): class CustomUser(AbstractUser):
...@@ -19,5 +40,7 @@ class CustomUser(AbstractUser): ...@@ -19,5 +40,7 @@ class CustomUser(AbstractUser):
USERNAME_FIELD = 'email' USERNAME_FIELD = 'email'
REQUIRED_FIELDS = [] REQUIRED_FIELDS = []
objects = CustomUserManager()
def __str__(self): def __str__(self):
return self.first_name return self.first_name
\ No newline at end of file
{% extends "base.html" %} {% extends "base.html" %}
{% block head %}
<script src="https://accounts.google.com/gsi/client" async></script>
{% endblock %}
{% block content %} {% block content %}
<form method="POST" autocomplete="off"> <form method="POST" autocomplete="off">
{% csrf_token %} {% csrf_token %}
{{ loginform.as_p }} {{ loginform.as_p }}
<input type="submit" value="Log In"/> <input type="submit" value="Log In"/>
<div id="g_id_onload"
data-client_id="1091426130026-resqtjvbfu1mguphrr5seg6d31k1ttqf.apps.googleusercontent.com"
data-context="signin"
data-ux_mode="redirect"
data-login_uri="http://localhost:8000/accounts/auth-receiver"
data-itp_support="true">
</div>
<div class="g_id_signin"
data-type="standard"
data-shape="pill"
data-theme="filled_black"
data-text="signin_with"
data-size="large"
data-logo_alignment="left">
</div>
</form> </form>
{% endblock %} {% endblock %}
\ No newline at end of file
...@@ -7,5 +7,6 @@ app_name = "accounts" ...@@ -7,5 +7,6 @@ app_name = "accounts"
urlpatterns = [ urlpatterns = [
path('login', views.login_page, name="login"), path('login', views.login_page, name="login"),
path('register', views.register, name="register"), path('register', views.register, name="register"),
path('logout', views.user_logout, name="logout") path('logout', views.user_logout, name="logout"),
path('auth-receiver', views.auth_receiver, name="auth-receiver")
] ]
\ No newline at end of file
import os
from django.shortcuts import render, redirect from django.shortcuts import render, redirect
from django.http import HttpResponse from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from google.oauth2 import id_token
from google.auth.transport import requests
from .forms import CustomUserCreationForm, CustomUserAuthenticationForm from .forms import CustomUserCreationForm, CustomUserAuthenticationForm
from django.contrib.auth.models import auth from django.contrib.auth.models import auth
from django.contrib.auth import authenticate, login, logout from django.contrib.auth import authenticate, login, logout
from . import models
def register(request): def register(request):
# return HttpResponse("I am in Register") # return HttpResponse("I am in Register")
form = CustomUserCreationForm() form = CustomUserCreationForm()
print(request.POST)
if request.method == "POST": if request.method == "POST":
form = CustomUserCreationForm(request.POST) form = CustomUserCreationForm(request.POST)
if form.is_valid(): if form.is_valid():
...@@ -23,7 +32,7 @@ def register(request): ...@@ -23,7 +32,7 @@ def register(request):
def login_page(request): def login_page(request):
form = CustomUserAuthenticationForm() form = CustomUserAuthenticationForm()
print(request.POST)
if request.method == "POST": if request.method == "POST":
form = CustomUserAuthenticationForm(request, data = request.POST) form = CustomUserAuthenticationForm(request, data = request.POST)
if form.is_valid(): if form.is_valid():
...@@ -42,4 +51,40 @@ def login_page(request): ...@@ -42,4 +51,40 @@ def login_page(request):
def user_logout(request): def user_logout(request):
auth.logout(request) auth.logout(request)
return redirect("index") return redirect("index")
\ No newline at end of file
@csrf_exempt
def auth_receiver(request):
"""
Google calls this URL after the user has signed in with their Google account.
"""
token = request.POST['credential']
try:
user_data = id_token.verify_oauth2_token(
token, requests.Request(), os.environ['GOOGLE_OAUTH_CLIENT_ID']
)
except ValueError:
return HttpResponse(status=403)
# In a real app, I'd also save any new user here to the database. See below for a real example I wrote for Photon Designer.
# You could also authenticate the user here using the details from Google (https://docs.djangoproject.com/en/4.2/topics/auth/default/#how-to-log-a-user-in)
email = user_data['email']
password = user_data['sub']+'google'+user_data['name']
logInUser = authenticate(request, email = email, password = password)
if logInUser is not None:
pass
else:
first_name = user_data['given_name']
last_name = user_data['family_name']
role = "STUDENT"
user = models.CustomUser.objects.create_user(email=email, password=password, first_name=first_name, last_name=last_name, role=role)
auth.login(request, logInUser)
print("Login Successful")
return redirect("index")
\ No newline at end of file
...@@ -2,6 +2,8 @@ ...@@ -2,6 +2,8 @@
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<title>{% block title %}Red Brick Board{% endblock %}</title> <title>{% block title %}Red Brick Board{% endblock %}</title>
{% block head %}
{% endblock %}
{% load bootstrap5 %} {% load bootstrap5 %}
{% bootstrap_css %} {% bootstrap_css %}
{% bootstrap_javascript %} {% bootstrap_javascript %}
......
asgiref==3.7.2 asgiref==3.7.2
beautifulsoup4==4.12.3 beautifulsoup4==4.12.3
cachetools==5.3.3
certifi==2024.2.2
charset-normalizer==3.3.2
Django==4.2.11 Django==4.2.11
django-bootstrap-v5==1.0.11 django-bootstrap-v5==1.0.11
google-auth==2.28.2
idna==3.6
pyasn1==0.5.1
pyasn1-modules==0.3.0
python-dotenv==1.0.1 python-dotenv==1.0.1
requests==2.31.0
rsa==4.9
soupsieve==2.5 soupsieve==2.5
sqlparse==0.4.4 sqlparse==0.4.4
tzdata==2024.1 tzdata==2024.1
urllib3==2.2.1
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment