Commit ef3ec8b3 authored by Noe Nieto's avatar Noe Nieto 💬

experiments with JWT token

parent 786f4ada
......@@ -12,9 +12,29 @@
{% endblock %}
{% block content %}
<form method="post" action=".">
<form id="registrate" method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="{% trans 'Submit' %}" />
</form>
{% endblock %}
{% block js_scripts %}
<script>
const READY_STATE_DONE = 4;
var formilo = document.getElementById('registrate');
formilo.onsubmit = function (event){
var peto = new XMLHttpRequest();
peto.onreadystatechange = function (evt){
if (peto.readyState == READY_STATE_DONE) {
console.log('State:', peto.readyState, '\nRequest:\n', peto);
}
};
peto.open('POST', formilo.action);
peto.send(new FormData(formilo));
return false;
}
</script>
{% endblock %}
import logging
from django import forms
from django.conf import settings
from django.contrib.auth import logout
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth import get_user_model
from captcha.fields import CaptchaField
from cart.models import ChosenReward
from ldapregister.forms import RegistrationForm
from registration.backends.simple.views import RegistrationView
from woocommerce import API as WOOCOMMERCE_API
log = logging.getLogger(__name__)
User = get_user_model()
class CartRegistrationForm(RegistrationForm):
......@@ -81,3 +89,37 @@ class CartRegistrationView(RegistrationView):
reward = ChosenReward(user=user, reward=self.reward)
reward.save()
return user
def _jwt_token(self, username, password):
# do the JWT thingy
jwt_wcapi = WOOCOMMERCE_API(
url=settings.WOO_URL,
consumer_key=settings.WOO_CONSUMER_KEY,
consumer_secret=settings.WOO_CONSUMER_SECRET,
wp_api=True,
version="jwt-auth/v1",
query_string_auth=settings.WOO_QUERY_STRING_AUTH,
)
jwt_response = jwt_wcapi.post("token", {"username": username, "password": password})
jwt_json = jwt_response.json()
jwt_status = jwt_response.status_code
jwt_token = jwt_json.get("token", None)
if jwt_status == 200 and jwt_token is not None:
return 'Bearer {}' + jwt_token
def form_valid(self, form):
"""
Pre authenticate user on shop/wordpress with JWT/
response is an instance of HttpResponseRedirect
"""
response = super().form_valid(form)
# Authorization and Access-Control-Allow-Origin headers don't really reach javascript
token = self._jwt_token(
username=form.cleaned_data[User.USERNAME_FIELD],
password=form.cleaned_data['password1']
)
response['Location'] = '{}?token={}'.format(response['Location'], token)
return response
......@@ -72,6 +72,6 @@ SPDX-License-Identifier: AGPL-3.0
</div>
</footer>
{% block js_scripts %}{% endblock %}
</body>
</html>
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