Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

151 Initial AllAuth Integration #210

Merged
merged 2 commits into from
Jan 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions accounts/adapters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from django.shortcuts import redirect


class HydroServerSocialAccountAdapter(DefaultSocialAccountAdapter):
def pre_social_login(self, request, sociallogin):
if not sociallogin.is_existing:
# print(sociallogin.account)
print(sociallogin.account.extra_data)
# if not sociallogin.account.extra_data.get('email'):
# # Save social login data in session and redirect to email form
# request.session['sociallogin'] = sociallogin.serialize()
# return redirect('account_email_selection') # Your custom email form
3 changes: 2 additions & 1 deletion accounts/admin.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from django.contrib import admin
from .models import Person, Organization
from .models import Person, PersonType, Organization

admin.site.register(Person)
admin.site.register(Organization)
admin.site.register(PersonType)
62 changes: 62 additions & 0 deletions accounts/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
from django import forms
from allauth.account.forms import SignupForm
from .models import Person, PersonType


class HydroServerSignUpForm(SignupForm):
first_name = forms.CharField(
label='First Name',
max_length=30,
required=False,
widget=forms.TextInput(attrs={'placeholder': 'First Name'})
)

middle_name = forms.CharField(
label='Middle Name',
max_length=30,
required=False,
widget=forms.TextInput(attrs={'placeholder': 'Middle Name'})
)

last_name = forms.CharField(
label='Last Name',
max_length=30,
required=True,
widget=forms.TextInput(attrs={'placeholder': 'Last Name'})
)

address = forms.CharField(
label='Address',
max_length=255,
required=False,
widget=forms.TextInput(attrs={'placeholder': 'Address'})
)

phone = forms.CharField(
label='Phone Number',
max_length=10,
required=False,
widget=forms.TextInput(attrs={
'placeholder': 'Phone Number',
'class': 'phone-number-mask'
})
)

type = forms.ModelChoiceField(
label='Type',
queryset=PersonType.objects.all(),
required=True,
)

class Meta:
model = Person

def save(self, request):
person = super(HydroServerSignUpForm, self).save(request)
person.middle_name = str(self.cleaned_data.get('middle_name'))
person.phone = str(self.cleaned_data.get('phone'))
person.address = str(self.cleaned_data.get('address'))
person.type = str(self.cleaned_data.get('type'))
person.save()

return person
20 changes: 20 additions & 0 deletions accounts/migrations/0007_persontype.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Generated by Django 5.0.6 on 2024-12-10 19:39

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('accounts', '0006_alter_apikey_permissions_and_more'),
]

operations = [
migrations.CreateModel(
name='PersonType',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
],
),
]
1 change: 1 addition & 0 deletions accounts/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from .apikey import APIKey
from .organization import Organization
from .person import Person
from .persontype import PersonType
7 changes: 7 additions & 0 deletions accounts/models/person.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils import timezone
from django.db.models.signals import pre_save
from django.dispatch import receiver
from accounts.models.organization import Organization
from accounts.models.apikey import PermissionChecker
from django.conf import settings
Expand Down Expand Up @@ -208,3 +210,8 @@ class PasswordReset(models.Model):

def is_valid(self):
return timezone.now() - self.timestamp <= timedelta(days=1)


@receiver(pre_save, sender=Person)
def update_username_from_email(sender, instance, **kwargs):
instance.username = instance.email
8 changes: 8 additions & 0 deletions accounts/models/persontype.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from django.db import models


class PersonType(models.Model):
name = models.CharField(max_length=255)

def __str__(self):
return self.name
12 changes: 6 additions & 6 deletions core/router.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
from ninja import Router
from typing import List
from hydroserver.auth import JWTAuth, BasicAuth, APIKeyHeaderAuth, anonymous_auth
from hydroserver.security import session_auth, basic_auth, anonymous_auth


class DataManagementRouter(Router):
def dm_list(self, route, response):
return super(DataManagementRouter, self).api_operation(
['GET'], # ['GET', 'HEAD'],
route,
auth=[JWTAuth(), BasicAuth(), APIKeyHeaderAuth(), anonymous_auth],
auth=[session_auth, basic_auth, anonymous_auth],
response={
200: List[response]
},
Expand All @@ -19,7 +19,7 @@ def dm_get(self, route, response):
return super(DataManagementRouter, self).api_operation(
['GET'], # ['GET', 'HEAD'],
route,
auth=[JWTAuth(), BasicAuth(), APIKeyHeaderAuth(), anonymous_auth],
auth=[session_auth, basic_auth, anonymous_auth],
response={
200: response,
403: str,
Expand All @@ -31,7 +31,7 @@ def dm_get(self, route, response):
def dm_post(self, route, response):
return super(DataManagementRouter, self).post(
route,
auth=[JWTAuth(), BasicAuth(), APIKeyHeaderAuth()],
auth=[session_auth, basic_auth],
response={
201: response,
401: str,
Expand All @@ -44,7 +44,7 @@ def dm_post(self, route, response):
def dm_patch(self, route, response):
return super(DataManagementRouter, self).patch(
route,
auth=[JWTAuth(), BasicAuth(), APIKeyHeaderAuth()],
auth=[session_auth, basic_auth],
response={
203: response,
401: str,
Expand All @@ -57,7 +57,7 @@ def dm_patch(self, route, response):
def dm_delete(self, route):
return super(DataManagementRouter, self).delete(
route,
auth=[JWTAuth(), BasicAuth(), APIKeyHeaderAuth()],
auth=[session_auth, basic_auth],
response={
204: None,
401: str,
Expand Down
8 changes: 4 additions & 4 deletions core/views/datastream.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from django.db import transaction, IntegrityError
from django.http import StreamingHttpResponse
from django.db.models import Q
from hydroserver.auth import JWTAuth, BasicAuth, anonymous_auth
from hydroserver.security import session_auth, basic_auth, anonymous_auth
from core.router import DataManagementRouter
from core.models import Datastream, Observation, Thing, Sensor, ObservedProperty, Unit, ProcessingLevel
from sensorthings.types import ISOTimeString
Expand Down Expand Up @@ -203,7 +203,7 @@ def delete_datastream(request, datastream_id: UUID = Path(...)):

@router.post(
'{datastream_id}/csv',
auth=[JWTAuth(), BasicAuth()],
auth=[session_auth, basic_auth],
response={
201: None,
400: str,
Expand Down Expand Up @@ -251,7 +251,7 @@ def upload_observations(request, datastream_id: UUID = Path(...), file: Uploaded

@router.get(
'{datastream_id}/csv',
auth=[JWTAuth(), BasicAuth(), anonymous_auth],
auth=[session_auth, basic_auth, anonymous_auth],
response={
200: None,
403: str,
Expand All @@ -275,7 +275,7 @@ def get_datastream_csv(request, datastream_id: UUID = Path(...)):

@router.get(
'{datastream_id}/metadata',
auth=[JWTAuth(), BasicAuth(), anonymous_auth],
auth=[session_auth, basic_auth, anonymous_auth],
response={
200: DatastreamMetadataGetResponse,
403: str,
Expand Down
10 changes: 5 additions & 5 deletions core/views/thing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from datetime import datetime
from django.db import transaction, IntegrityError
from django.db.models import Q
from hydroserver.auth import JWTAuth, BasicAuth, anonymous_auth
from hydroserver.security import session_auth, basic_auth, anonymous_auth
from accounts.models import Person
from core.models import Thing, Location, ThingAssociation, Unit, Sensor, ProcessingLevel, ObservedProperty, Datastream
from core.router import DataManagementRouter
Expand Down Expand Up @@ -186,7 +186,7 @@ def delete_thing(request, thing_id: UUID = Path(...)):

@router.patch(
'{thing_id}/ownership',
auth=[JWTAuth(), BasicAuth()],
auth=[session_auth, basic_auth],
response={
203: ThingGetResponse,
401: str,
Expand Down Expand Up @@ -262,7 +262,7 @@ def update_thing_ownership(request, data: ThingOwnershipPatchBody, thing_id: UUI

@router.patch(
'{thing_id}/privacy',
auth=[JWTAuth(), BasicAuth()],
auth=[session_auth, basic_auth],
response={
203: ThingGetResponse,
401: str,
Expand Down Expand Up @@ -296,7 +296,7 @@ def update_thing_privacy(request, data: ThingPrivacyPatchBody, thing_id: UUID =

@router.get(
'{thing_id}/metadata',
auth=[JWTAuth(), BasicAuth(), anonymous_auth],
auth=[session_auth, basic_auth, anonymous_auth],
response={
200: ThingMetadataGetResponse,
401: str,
Expand Down Expand Up @@ -363,7 +363,7 @@ def get_thing_metadata(request, thing_id: UUID = Path(...), include_assignable_m

@router.get(
'{thing_id}/datastreams',
auth=[JWTAuth(), BasicAuth(), anonymous_auth],
auth=[session_auth, basic_auth, anonymous_auth],
response={
200: List[DatastreamGetResponse]
},
Expand Down
4 changes: 0 additions & 4 deletions hydroserver/auth/__init__.py

This file was deleted.

46 changes: 0 additions & 46 deletions hydroserver/auth/apikey.py

This file was deleted.

23 changes: 0 additions & 23 deletions hydroserver/auth/jwt.py

This file was deleted.

6 changes: 6 additions & 0 deletions hydroserver/security/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from .anonymous import anonymous_auth
from .basic import BasicAuth
from .session import SessionAuth

basic_auth = BasicAuth()
session_auth = SessionAuth()
File renamed without changes.
File renamed without changes.
16 changes: 16 additions & 0 deletions hydroserver/security/session.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from typing import Optional, Any
from ninja.security.apikey import APIKeyCookie
from ninja.errors import HttpError
from django.http import HttpRequest
from django.conf import settings


class SessionAuth(APIKeyCookie):
param_name: str = settings.SESSION_COOKIE_NAME

def authenticate(self, request: HttpRequest, key: Optional[str]) -> Optional[Any]:
if request.user.is_authenticated:
request.authenticated_user = request.user
return request.user
else:
raise HttpError(401, 'Invalid or missing session cookie')
Loading
Loading