Skip to content

Commit

Permalink
Merge pull request #13 from Villanueva-del-Trabuco-EGC/develop
Browse files Browse the repository at this point in the history
Subiendo la funcionalidad estable a master
  • Loading branch information
plss12 authored Dec 1, 2022
2 parents 0b696a4 + 67498c6 commit 8bc278b
Show file tree
Hide file tree
Showing 42 changed files with 1,234 additions and 58 deletions.
4 changes: 4 additions & 0 deletions .github/workflows/django.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ jobs:
run: |
cd decide
python manage.py migrate
- name: Generate translation files
run: |
sudo apt-get install gettext
django-admin compilemessages
- name: Run tests
run: |
cd decide
Expand Down
24 changes: 24 additions & 0 deletions decide/authentication/backends.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q


class EmailOrUsernameModelBackend(ModelBackend):

def authenticate(self, request, username=None, password=None, **kwargs):
auth_type = settings.AUTH_AUTHENTICATION_TYPE
if auth_type == 'username':
return super().authenticate(username, password)
user_model = get_user_model()
try:
if auth_type == 'both':
user = user_model.objects.get(
Q(username__iexact=username) | Q(email__iexact=username)
)
else:
user = user_model.objects.get(email__iexact=username)
if user.check_password(password):
return user
except user_model.DoesNotExist:
return None
15 changes: 15 additions & 0 deletions decide/authentication/locale/es_ES/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# decide auth translation
# This file is distributed under the same license as the main project

# Translators: Pablo Marin Gomez <[email protected]>, 2022

msgid ""
msgstr ""

"Language: es\n"
"Last-Translator: Pablo Marin Gomez\n"
"POT-Creation-Date: 2022-11-19 18:45+0100\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
53 changes: 53 additions & 0 deletions decide/authentication/templates/authentication/register.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
{% extends "base.html" %}
{% load i18n static %}
{% block content %}
<div class="container">
<form method="POST">
{% csrf_token %}
<div class="form-group">
<h1>Register</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<div class="form-row">
<div class="form-group col-md-6 mb-0">
<label for="first_name"><b>First Name</b></label>
<input type="text" placeholder="Enter first name" name="first_name" id="first_name">
</div>
<br>
<div class="form-group col-md-6 mb-0">
<label for="last_name"><b>Last Name</b></label>
<input type="text" placeholder="Enter last name" name="last_name" id="last_name">
</div>
<br>
</div>
<div class="form-row">
<div class="form-group col-md-6 mb-0">
<label for="username"><b>Username</b></label>
<input type="text" placeholder="Enter user name" name="username" id="username">
</div>
<br>
<div class="form-group col-md-6 mb-0">
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" id="email">
</div>
<br>
</div>
<div class="form-row">
<div class="form-group col-md-6 mb-0">
<label for="password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" id="password">
</div>
</div>
</div>

<p>By registering, you accept the <a href="#">Terms & Privacy</a>.</p>

<div class="form-group">
<button class="registerbtn" type="submit">Register</button>
</div>
<div class="container signin">
<p>Already have an account? <a href="/">Sign In</a></p>
</div>
</form>
</div>
{% endblock content %}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{% autoescape off %}
Hi {{ user.username }},

Please click on the link below to confirm your registration:

{{protocol}}://{{domain}}{% url 'activate' uidb64=uid token=token %}
{% endautoescape %}
2 changes: 1 addition & 1 deletion decide/authentication/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def test_register_bad_permissions(self):

token.update({'username': 'user1'})
response = self.client.post('/authentication/register/', token, format='json')
self.assertEqual(response.status_code, 401)
self.assertEqual(response.status_code, 400)

def test_register_bad_request(self):
data = {'username': 'admin', 'password': 'admin'}
Expand Down
14 changes: 14 additions & 0 deletions decide/authentication/tokens.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from django.contrib.auth.tokens import PasswordResetTokenGenerator
import six

class AccountActivateTokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self,user,timestamp):
return (
six.text_type(user.pk) +
six.text_type(timestamp) +
six.text_type(user.is_active)
)


account_activation_token = AccountActivateTokenGenerator()

2 changes: 2 additions & 0 deletions decide/authentication/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
from rest_framework.authtoken.views import obtain_auth_token

from .views import GetUserView, LogoutView, RegisterView
from . import views


urlpatterns = [
path('login/', obtain_auth_token),
path('logout/', LogoutView.as_view()),
path('getuser/', GetUserView.as_view()),
path('register/', RegisterView.as_view()),
path('activate/<uidb64>/<token>', views.activate, name='activate')
]
62 changes: 54 additions & 8 deletions decide/authentication/views.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
from django.contrib import messages
from rest_framework.response import Response
from rest_framework.status import (
HTTP_201_CREATED,
HTTP_400_BAD_REQUEST,
HTTP_401_UNAUTHORIZED
)
from rest_framework.views import APIView
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.shortcuts import get_object_or_404
from django.shortcuts import get_object_or_404, redirect
from django.core.exceptions import ObjectDoesNotExist
from django.template.loader import render_to_string
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.utils.encoding import force_bytes, force_str
from django.core.mail import EmailMessage
from django.contrib.auth import get_user_model
from django.views.generic import TemplateView

from .tokens import account_activation_token

from .serializers import UserSerializer

Expand All @@ -32,24 +40,62 @@ def post(self, request):

return Response({})

def activate(request, uidb64, token):
User = get_user_model()
try:
uid = force_str(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None

class RegisterView(APIView):
def post(self, request):
key = request.data.get('token', '')
tk = get_object_or_404(Token, key=key)
if not tk.user.is_superuser:
return Response({}, status=HTTP_401_UNAUTHORIZED)
if user is not None and account_activation_token.check_token(user, token):
print('Hola')
user.is_active = True
user.save()

messages.success(request, 'Thank you for your email confirmation. Now you can log in your account.')
return redirect('http://localhost:8000/authentication/register/')
else:
print('Fallo')
messages.error(request, 'Activation link is invalid!')

return redirect('http://localhost:8000/authentication/register/')

def activateEmail(request, user, to_email):
mail_subject = 'Activate your user account.'
message = render_to_string('template_activate_account.html',{
'user': user.username,
'domain': 'localhost:8000',
'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
'token':account_activation_token.make_token(user),
'protocol': 'https' if request.is_secure() else 'http'
})
email = EmailMessage(mail_subject, message, to=[to_email])
if email.send():
messages.success(request, f'Dear {user}, please check your email {to_email} inbox' +
' and click on received activation link to confirm and complete the registration. Note: Check your spam folder.')
else:
messages.error(request, f'Problem sending confirmation email to {to_email}, check if you typed it correctly.')

class RegisterView(APIView, TemplateView):

template_name = 'authentication/register.html'

def post(self, request):
username = request.data.get('username', '')
pwd = request.data.get('password', '')
email = request.data.get('email','')
if not username or not pwd:
return Response({}, status=HTTP_400_BAD_REQUEST)

try:
user = User(username=username)
user.set_password(pwd)
user.email = email
user.is_active = False
user.save()
token, _ = Token.objects.get_or_create(user=user)
activateEmail(request,user,email)
except IntegrityError:
return Response({}, status=HTTP_400_BAD_REQUEST)
return Response({'user_pk': user.pk, 'token': token.key}, HTTP_201_CREATED)
15 changes: 15 additions & 0 deletions decide/base/locale/es_ES/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# decide base translation
# This file is distributed under the same license as the main project

# Translators: Pablo Marin Gomez <[email protected]>, 2022

msgid ""
msgstr ""

"Language: es\n"
"Last-Translator: Pablo Marin Gomez\n"
"POT-Creation-Date: 2022-11-19 18:00+0100\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
3 changes: 2 additions & 1 deletion decide/base/templates/base.html
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
{% load i18n static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>{% block title %}Decide!{% endblock %}</title>
<title>{% block title %}{% trans "decide" %}!{% endblock %}</title>
{% block extrahead %}{% endblock %}
</head>
<body>
Expand Down
45 changes: 45 additions & 0 deletions decide/booth/locale/es_ES/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# decide booth translation
# This file is distributed under the same license as the main project

# Translators: Pablo Marin Gomez <[email protected]>, 2022

msgid ""
msgstr ""

"Language: es\n"
"Last-Translator: Pablo Marin Gomez\n"
"POT-Creation-Date: 2022-11-19 16:00+0100\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

msgid "decide"
msgstr "Decide"

msgid "logout"
msgstr "Salir"

msgid "vID"
msgstr "ID de la votación"

msgid "vName"
msgstr "Nombre de la votación"

msgid "Login"
msgstr "Identificarse"

msgid "LoginGitHub"
msgstr "Identificarse con GitHub"

msgid "LoginFacebook"
msgstr "Identificarse con Facebook"

msgid "Vote"
msgstr "Votar"

msgid "Error"
msgstr "Error"

msgid "Conglatulations. Your vote has been sent"
msgstr "¡Enhorabuena! Tu voto se ha enviado"
38 changes: 35 additions & 3 deletions decide/booth/templates/booth/booth.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<div id="app-booth">
<!-- Navbar -->
<b-navbar type="dark" variant="secondary">
<b-navbar-brand tag="h1">Decide</b-navbar-brand>
<b-navbar-brand tag="h1">{% trans "decide" %}</b-navbar-brand>
<b-navbar-nav class="ml-auto" v-if="!signup">
<b-nav-item href="#" v-on:click="decideLogout">
{% trans "logout" %}
Expand All @@ -27,7 +27,9 @@
</b-alert>

<div class="voting">
<h1>[[ voting.id ]] - [[ voting.name ]]</h1>
<h1>{% trans "vID" %}: [[ voting.id ]] </h1>
<h3>{% trans "vName" %}: [[ voting.name ]]</h3>


<!-- Register -->
<b-form @submit="onSubmitLogin" v-if="signup">
Expand All @@ -47,8 +49,22 @@ <h1>[[ voting.id ]] - [[ voting.name ]]</h1>
v-model="form.password"
required />
</b-form-group>
<b-button type="submit" variant="primary">{% trans "Login" %}</b-button>
<br>
<b-button type="submit" variant="primary">{% trans "Login" %}</b-button>
</b-form>
<!--LOGIN CON GITHUB-->

{% if not user.is_authenticated and not user.is_staff %}
<a href="{% url 'social:begin' 'github' %}?next={{ request.path }}" class="btn btn-secondary">
<span>Login with GitHub</span>
</a>
{% elif not user.is_staff %}
<p>Registrado en {{user.social_auth.get.provider}} como {{user}}</p>
<b-button type="button" variant="primary" v-if="signup" v-on:click="getSocialAuthUser">
Vote with {{user.social_auth.get.provider}}
</b-button>
{% endif %}


<!-- Voting -->
<div v-if="!signup">
Expand Down Expand Up @@ -206,6 +222,22 @@ <h2>[[ voting.question.desc ]]</h2>
this.alertLvl = lvl;
this.alertMsg = msg;
this.alertShow = true;
},
getSocialAuthUser() {
this.signup = false;
var un = "{{ user.username }}";
var pw = "{{ randomPassword }}";
this.form = {username : un, password : pw};
this.postData("{% url "gateway" "authentication" "/login/" %}", this.form)
.then(data => {
console.log(this.form)
document.cookie = 'decide='+data.token+';';
this.token = data.token;
this.getUser();
})
.catch(error => {
this.showAlert("danger", '{% trans "Error: " %}' + error);
});
}
},
})
Expand Down
Loading

0 comments on commit 8bc278b

Please sign in to comment.