#14 Adds authentication
Closed 5 years ago by algogator. Opened 5 years ago by algogator.
fedora-commops/ algogator/fedora-happiness-packets master  into  master

file modified
+21 -8
@@ -1,17 +1,30 @@ 

  # fedora-happiness-packets

  

- This project conains the codebase for fedorahosted version of happinesspackets.io to be used during Appreciation week.

+ This project contains the codebase for fedora hosted version of happinesspackets.io to be used during Appreciation week.

  

- Google Summer of Code Application Prerequisites for this projects are here:

+ # Setup

  

- 1. Create a FAS Id, join CommOps group 

+ To run this project or the tests, you need to set up a virtualenv, install the dev requirements and set

+ the correct ``DJANGO_SETTINGS_MODULE``, for example with::

  

- 2. Suscribe and send introductions to commops and summer-coding mailing lists.

+     virtualenv --no-site-packages --prompt='(happinesspackets)' virtualenv/

+     source virtualenv/bin/activate

+     pip install -r requirements/dev.txt

+     export DJANGO_SETTINGS_MODULE=happinesspackets.settings.dev

+     ./manage.py collectstatic

+     python manage.py migrate

+     ./t

  

- 3. Ceate and share with us a Fedora wiki user page. For example, https://fedoraproject.org/wiki/User:Bee2502

+ To run on http://127.0.0.1:8000/ :

  

- 4. Follow the application process i.e create a subpage for your GSoC proposal and populate it with details. 

+     python manage.py runserver

  

- More info on that is here: https://docs.fedoraproject.org/mentored-projects/gsoc/2018/application.html

+ Don't forget to start the mail server:

  

- Don't worry if you dont know everything i.e. the timeline. We can help you with that but fill as many details as you can. 

\ No newline at end of file

+     python -m smtpd -n -c DebuggingServer localhost:2525

+ 

+ The ``t`` command is a very short shell script that runs the tests with the correct settings and reports on coverage.

+ 

+ To run the integration tests::

+ 

+     ./manage.py test -v 2 -p integration_test*.py --settings=happinesspackets.settings.tsting

file modified
+14 -2
@@ -154,6 +154,18 @@ 

      }

  }

  

- .emoji { 

-     vertical-align: initial;  

+ .emoji {

+     vertical-align: initial;

+ }

+ 

+ .btn-login, .btn-logout {

+   background: none;

+   color: white;

+   border: none;

+ }

+ 

+ .btn-login:hover, .btn-logout:hover {

+     background: none;

+     color: white;

+     border: none;

  }

@@ -0,0 +1,13 @@ 

+ from mozilla_django_oidc.auth import OIDCAuthenticationBackend

+ 

+ class OIDC(OIDCAuthenticationBackend):

+     def create_user(self, claims):

+         user = super(OIDC, self).create_user(claims)

+         user.username = claims.get('nickname', '')

+         user.email = claims.get('email', '')

+         try:

+             user.first_name = claims.get('name', '')

+         except:

+             user.first_name = user.username

+         user.save()

+         return user

@@ -26,11 +26,11 @@ 

  

  

  class MessageSendForm(forms.ModelForm):

-     hp = forms.CharField(label="do not fill", required=False)

+     # hp = forms.CharField(label="do not fill", required=False)

  

      class Meta:

          model = Message

-         fields = ['sender_name', 'sender_email', 'recipient_name', 'recipient_email', 'message',

+         fields = ['recipient_name', 'recipient_email', 'message',

                    'sender_named', 'sender_approved_public', 'sender_approved_public_named']

  

      def __init__(self, *args, **kwargs):
@@ -40,10 +40,6 @@ 

          self.helper.label_class = 'col-md-3'

          self.helper.field_class = 'col-md-8'

  

-         self.fields['sender_name'].label = 'Name'

-         self.fields['sender_email'].label = 'Email'

-         self.fields['sender_email'].help_text = "We'll send you a confirmation link before sending your message out."

-         self.fields['sender_email'].validators = [validate_email]

          self.fields['recipient_name'].label = 'Name'

          self.fields['recipient_email'].label = 'Email'

          self.fields['recipient_email'].validators = [validate_email]
@@ -54,7 +50,7 @@ 

          self.fields['sender_approved_public_named'].help_text = "Note: We only publish information if both the sender and the recipients agree."

  

          self.helper.layout = Layout(

-             Fieldset('This Happiness Packet is from...', 'sender_name', 'sender_email', 'hp'),

+             # Fieldset('This Happiness Packet is from...', 'sender_name', 'sender_email', 'hp'),

              Fieldset("Send this Happiness Packet to...", 'recipient_name', 'recipient_email'),

              Fieldset("Your message is...", 'message'),

              Fieldset("Privacy and permissions", 'sender_named', 'sender_approved_public', 'sender_approved_public_named'),
@@ -64,8 +60,8 @@ 

  

      def clean(self):

          super(MessageSendForm, self).clean()

-         if self.cleaned_data.get('hp'):

-             raise forms.ValidationError('')

+         # if self.cleaned_data.get('hp'):

+         #     raise forms.ValidationError('')

          if self.cleaned_data.get('sender_approved_public_named') and not self.cleaned_data.get('sender_approved_public'):

              self.add_error('sender_approved_public_named', "If you want us to publish the message including your names, "

                                                             "you must also check 'I agree to publish this message and"

@@ -11,6 +11,7 @@ 

  from django.utils.html import format_html

  from django.views.decorators.debug import sensitive_post_parameters

  from django.views.generic import FormView, TemplateView, UpdateView, ListView

+ from django.contrib.auth.mixins import LoginRequiredMixin

  

  from .forms import MessageSendForm, MessageRecipientForm

  from .models import Message, BLACKLIST_HMAC_SALT, BlacklistedEmail, strip_email
@@ -32,6 +33,11 @@ 

      def get_queryset(self):

          return super(StartView, self).get_queryset().order_by('?')[:2]

  

+     def get_context_data(self, **kwargs):

+         context = super(StartView, self).get_context_data(**kwargs)

+         user = self.request.user

+         return context

+ 

  

  class FaqView(TemplateView):

      template_name = 'messaging/faq.html'
@@ -72,8 +78,8 @@ 

          messages.success(self.request, message)

          return HttpResponseRedirect(self.success_url)

  

- 

- class MessageSendView(FormView):

+ class MessageSendView(LoginRequiredMixin, FormView):

+     login_url = '/oidc/authenticate/'

      template_name = 'messaging/message_send_form.html'

      form_class = MessageSendForm

  
@@ -84,6 +90,8 @@ 

      def form_valid(self, form):

          message = form.save(commit=False)

          message.sender_ip = self.request.META['REMOTE_ADDR']

+         message.sender_name = self.request.user.first_name

+         message.sender_email = self.request.user.email

          message.save()

          message.send_sender_confirmation(self.request.is_secure(), self.request.get_host())

          return HttpResponseRedirect(reverse('messaging:sender_confirmation_sent'))

@@ -12,11 +12,13 @@ 

  DEBUG = False

  

  ADMINS = (

-     ('Sasha Romijn', 'github@mxsasha.eu'),

+     ('Anna Philips', 'algogator@fedoraproject.org'),

+     ('Jona Azizaj', 'jonatoni@fedoraproject.org'),

+     ('Bhagyashree Uday', 'bee2502@fedoraproject.org'),

  )

  SERVER_EMAIL = ADMINS[0][1]

  

- DEFAULT_FROM_EMAIL = "Happiness Packets <info@happinesspackets.io>"

+ DEFAULT_FROM_EMAIL = "Happiness Packets <fedora.happinesspackets@gmail.com>"

  

  EMAIL_SUBJECT_PREFIX = "[happinesspackets] "

  
@@ -60,11 +62,11 @@ 

  

  # noinspection PyUnresolvedReferences

  MIDDLEWARE_CLASSES = [

+     'django.contrib.sessions.middleware.SessionMiddleware',

      'happinesspackets.utils.middleware.SetRemoteAddrFromForwardedFor',

      'opbeat.contrib.django.middleware.OpbeatAPMMiddleware',

      'dogslow.WatchdogMiddleware',

      'django.middleware.common.CommonMiddleware',

-     'django.contrib.sessions.middleware.SessionMiddleware',

      'django.middleware.csrf.CsrfViewMiddleware',

      'django.contrib.messages.middleware.MessageMiddleware',

  ]
@@ -101,6 +103,7 @@ 

  

  INSTALLED_APPS = [

      'django.contrib.auth',

+     'mozilla_django_oidc',

      'django.contrib.contenttypes',

      'django.contrib.sessions',

      'django.contrib.messages',
@@ -114,6 +117,21 @@ 

      'happinesspackets.messaging',

  ]

  

+ AUTHENTICATION_BACKENDS = (

+     'happinesspackets.messaging.auth.OIDC',

+ )

+ 

+ OIDC_RP_SIGN_ALGO = 'RS256'

+ OIDC_RP_IDP_SIGN_KEY = '-----BEGIN RSA PUBLIC KEY-----\nMIIBCgKCAQEAq/0/XjILQxF3OaQZtFE3wVJ5UUuxZbxiJ/z+Zai0EOHiaMMxVyoo\nibDRen615r525DQ8TmQyR0eMQEpQ6SUvaOunahpYohgAkbkYggUMQhcoCLme18ZJ\nBTNWTP8w4t7mcuZd1cy1KtHpEvH4gkrjp8N3vIv1lzFraSc+p2rHMbV+AX5CJQ1H\nohBdwaqyOBKp0nzY27gu2EH2vzCwXkO4zGtrHfjjGc0Ra4WG+xz1AWg833xcFj3p\nqM3vca09jDLBme+GT151LcCCXRNyOZPZ3ZX62NxkMyqvVJHC3Uu2Q1hSHO7f6AZk\nZXY88PXXEH52T2ZrWiISowjTcGUboP8goQIDAQAB\n-----END RSA PUBLIC KEY-----\n'

+ OIDC_RP_CLIENT_ID = os.environ.get('OIDC_RP_CLIENT_ID')

+ OIDC_RP_CLIENT_SECRET = os.environ.get('OIDC_RP_CLIENT_SECRET')

+ OIDC_OP_AUTHORIZATION_ENDPOINT = "https://iddev.fedorainfracloud.org/openidc/Authorization"

+ OIDC_OP_TOKEN_ENDPOINT = "https://iddev.fedorainfracloud.org/openidc/Token"

+ OIDC_OP_USER_ENDPOINT = "https://iddev.fedorainfracloud.org/openidc/UserInfo"

+ LOGIN_REDIRECT_URL = '/'

+ LOGOUT_REDIRECT_URL = '/'

+ LOGIN_REDIRECT_URL_FAILURE = '/error'

+ OIDC_RP_SCOPES = 'openid profile email'

  

  LOGGING = {

      'version': 1,

@@ -27,10 +27,11 @@ 

  ADMIN_ENABLED = True

  

  MIDDLEWARE_CLASSES = [

+     'django.contrib.sessions.middleware.SessionMiddleware',

+     'django.contrib.auth.middleware.AuthenticationMiddleware',

      'happinesspackets.utils.middleware.SetRemoteAddrFromForwardedFor',

      'dogslow.WatchdogMiddleware',

      'django.middleware.common.CommonMiddleware',

-     'django.contrib.sessions.middleware.SessionMiddleware',

      'django.middleware.csrf.CsrfViewMiddleware',

      'django.contrib.messages.middleware.MessageMiddleware',

      'debug_toolbar.middleware.DebugToolbarMiddleware',

@@ -6,6 +6,7 @@ 

  from django.contrib import admin

  

  urlpatterns = [

+     url(r'^oidc/', include('mozilla_django_oidc.urls')),

      url(r'^', include('happinesspackets.messaging.urls', namespace="messaging")),

  ]

  

file modified
+2
@@ -32,3 +32,5 @@ 

  python-dateutil==2.5.0

  factory-boy==2.9.2

  opbeat==3.3

+ mozilla-django-oidc==1.0.0

+ fedmsg==1.1.1

file modified
+18 -7
@@ -34,6 +34,22 @@ 

                  <li role="presentation" {% if url in request.path %}class="active"{% endif %}><a href="{{ url }}">FAQ</a></li>

                  {% url 'messaging:archive' as url %}

                  <li role="presentation" {% if url in request.path %}class="active"{% endif %}><a href="{{ url }}">Happiness Archive</a></li>

+                 {% if user.is_authenticated %}

+                 <form id="logout" action="{% url 'oidc_logout' %}" method="post">

+                     {% csrf_token %}

+                     <button type="submit" class="btn btn-logout">

+                     <span class="glyphicon glyphicon-log-out"></span>

+                     <span>&nbsp;Logout</span>

+                     </button>

+                 </form>

+                 {% else %}

+                 <form id="login" action="{% url 'oidc_authentication_init' %}" method="get">

+                     <button type="submit" class="btn btn-login">

+                     <span class="glyphicon glyphicon-log-in"></span>

+                     <span>&nbsp;Login</span>

+                     </button>

+                 </form>

+                 {% endif %}

              </ul>

          </div>

      </aside>
@@ -59,14 +75,9 @@ 

                  <a href="https://twitter.com/intent/tweet?button_hashtag=FedoraAppreciationWeek2k18" class="twitter-hashtag-button" data-size="large" data-dnt="true">Tweet #FedoraAppreciationWeek2k18</a>

                  <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>

                  <br>

-                 Open-Source Happiness Packets is an

-                 <a href="https://github.com/mxsasha/happinesspackets/">open-source project</a> by

-                 <a href="https://twitter.com/mxsash">Sasha Romijn</a> and

-                 <a href="https://twitter.com/thatdocslady">Mikey Ariel</a>.

+                 Fedora Happiness Packets is a fork of <a href="https://github.com/mxsasha/happinesspackets/">Happiness Packets</a> and part of GSoC 2018.

                  <br>

-                 Design and artwork by <a href="https://twitter.com/olasitarska">Ola Sitarska</a>.

-                 <br>

-                 Need help? <a href="mailto:info@happinesspackets.io">info@happinesspackets.io</a>

+                 Need help? <a href="mailto:fedora.happinesspackets@gmail.com">fedora.happinesspackets@gmail.com</a>

                  <img class="emoji" src="{% static 'images/emoji/loveletter.png' %}" alt="💌" title="Love letter" aria-label="Emoji: Love letter" style="vertical-align: text-bottom">

  

              </small></footer>

file modified
+2 -5
@@ -18,12 +18,9 @@ 

              <hr>

              <p>

                  Open-source happiness packets is an

-                 <a href="https://github.com/erikr/happinesspackets/" style="color: #F64747;">open-source project</a> by

-                 <a href="https://twitter.com/mxsash" style="color: #F64747;">Sasha Romijn</a> and

-                 <a href="https://twitter.com/thatdocslady" style="color: #F64747;">Mikey Ariel</a>.

-                 Design and artwork by <a href="https://twitter.com/olasitarska" style="color: #F64747;">Ola Sitarska</a>.

+                 <a href="https://github.com/erikr/happinesspackets/" style="color: #F64747;">open-source project</a>

                  <br>

-                 Need help? <a href="mailto:info@happinesspackets.io" style="color: #F64747;">info@happinesspackets.io</a>

+                 Need help? <a href="mailto:fedora.happinesspackets@gmail.com" style="color: #F64747;">fedora.happinesspackets@gmail.com</a>

              </p>

              <p>

                  Never want to receive email from us again?<br>