Fakultas Ilmu Komputer UI

Commit 77d929fa authored by Rayza Arasj Mahardhika's avatar Rayza Arasj Mahardhika
Browse files

spiked in custom passwordless auth backend

parent 236109be
Pipeline #24827 failed with stage
in 1 minute and 54 seconds
from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class AccountsConfig(AppConfig):
name = 'accounts'
import sys
from accounts.models import ListUser, Token
class PasswordlessAuthenticationBackend(object):
def authenticate(self, request, uid):
print('uid', uid, file=sys.stderr)
if not Token.objects.filter(uid=uid).exists():
print('no token found', file=sys.stderr)
return None
token = Token.objects.get(uid=uid)
print('got token', file=sys.stderr)
try:
user = ListUser.objects.get(email=token.email)
print('got user', file=sys.stderr)
return user
except ListUser.DoesNotExist:
print('new user', file=sys.stderr)
return ListUser.objects.create(email=token.email)
def get_user(self, email):
return ListUser.objects.get(email=email)
\ No newline at end of file
# Generated by Django 2.2.5 on 2019-11-13 15:44
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='Token',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('email', models.EmailField(max_length=254)),
('uid', models.CharField(max_length=255)),
],
),
migrations.CreateModel(
name='ListUser',
fields=[
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('email', models.EmailField(max_length=254, primary_key=True, serialize=False)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'abstract': False,
},
),
]
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager, PermissionsMixin
)
class Token(models.Model):
email = models.EmailField()
uid = models.CharField(max_length=255)
class ListUserManager(BaseUserManager):
def create_user(self, email):
ListUser.objects.create(email=email)
def create_superuser(self, email, password):
self.create_user(email)
class ListUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(primary_key=True)
USERNAME_FIELD = 'email'
#REQUIRED_FIELDS = ['email', 'height']
objects = ListUserManager()
@property
def is_staff(self):
return self.email == 'harry.percival@example.com'
@property
def is_active(self):
return True
<html>
<h1>Email sent</h1>
<p>Check your email, you'll find a message with a link that will log you into
the site.</p>
</html>
from django.test import TestCase
# Create your tests here.
from django.urls import path, include
from accounts.views import send_login_email, login, logout
urlpatterns = [
path(r'send_email', send_login_email, name='send_login_email'),
path(r'login', login, name='login'),
path(r'logout', logout, name='logout'),
]
\ No newline at end of file
import uuid
import sys
from django.contrib.auth import authenticate
from django.contrib.auth import login as auth_login, logout as auth_logout
from django.core.mail import send_mail
from django.shortcuts import redirect, render
from accounts.models import Token
def send_login_email(request):
email = request.POST['email']
uid = str(uuid.uuid4())
Token.objects.create(email=email, uid=uid)
print('saving uid', uid, 'for email', email, file=sys.stderr)
url = request.build_absolute_uri(f'/accounts/login?uid={uid}')
send_mail(
'Your login link for Superlists',
f'Use this link to log in:\n\n{url}',
'noreply@superlists',
[email],
)
return render(request, 'login_email_sent.html')
def login(request):
print('login view', file=sys.stderr)
uid = request.GET.get('uid')
user = authenticate(uid=uid)
if user is not None:
auth_login(request, user)
return redirect('/')
def logout(request):
auth_logout(request)
return redirect('/')
\ No newline at end of file
......@@ -11,34 +11,46 @@
</head>
<body>
<div class="container">
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3 jumbotron">
<div class="text-center" id="centering-div">
<h1>{% block header_text %}{% endblock %}</h1>
<form method="POST" action="{% block form_action %}{% endblock %}">
<div class="navbar">
{% if user.is_authenticated %}
<p>Logged in as {{ user.email }}</p>
<p><a id="id_logout" href="{% url 'logout' %}">Log out</a></p>
{% else %}
<form method="POST" action ="{% url 'send_login_email' %}">
Enter email to log in: <input name="email" type="text" />
{% csrf_token %}
</form>
{% endif %}
</div>
<div class="row">
<div class="col-md-6 col-md-offset-3 jumbotron">
<div class="text-center" id="centering-div">
<h1>{% block header_text %}{% endblock %}</h1>
<form method="POST" action="{% block form_action %}{% endblock %}">
<input name="item_text" id="id_new_item"
class="form-control input-lg"
placeholder="Enter a to-do item" />
​{% csrf_token %}
{% if error %}
​{% csrf_token %}
{% if error %}
<div class="form-group has-error">
<span class="help-block">{{ error }}</span>
</div>
{% endif %}
</form>
</div>
</div>
</div>
{% endif %}
</form>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-3">
​{% block table %}
​{% endblock %}
</div>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-3">
​{% block table %}
​{% endblock %}
</div>
</div>
</div>
</body>
</body>
</html>
\ No newline at end of file
......@@ -41,7 +41,13 @@ INSTALLED_APPS = [
'django.contrib.messages',
'django.contrib.staticfiles',
'lists',
'django_mutpy'
'django_mutpy',
'accounts',
]
AUTH_USER_MODEL = 'accounts.ListUser'
AUTHENTICATION_BACKENDS = [
'accounts.authentication.PasswordlessAuthenticationBackend',
]
MIDDLEWARE = [
......@@ -104,6 +110,23 @@ AUTH_PASSWORD_VALIDATORS = [
},
]
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
},
},
'root': {'level': 'INFO'},
}
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
......@@ -123,4 +146,10 @@ USE_TZ = True
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
\ No newline at end of file
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'throwawayram@gmail.com'
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD')
EMAIL_PORT = 587
EMAIL_USE_TLS = True
......@@ -17,10 +17,12 @@ from django.contrib import admin
from django.urls import path, include
from lists import views as lists_views
from lists import urls as lists_urls
from accounts import urls as accounts_urls
urlpatterns = [
# path('admin/', admin.site.urls),
path('', lists_views.home_page, name='home'),
path('lists/', include(lists_urls)),
path('about/', lists_views.about_page, name='about')
path('about/', lists_views.about_page, name='about'),
path('accounts/', include(accounts_urls)),
]
Supports Markdown
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