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

Profile feature #2

Merged
merged 6 commits into from
Dec 17, 2020
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
8 changes: 4 additions & 4 deletions zubhub_backend/zubhub/creators/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
from .models import Location

class CustomAccountAdapter(DefaultAccountAdapter):

def save_user(self, request, user, form, commit=False):
creator = super().save_user(request, user, form, commit)
data = form.cleaned_data
location = Location.objects.get(name = data.get('location'))
location = Location.objects.get(name=data.get('location'))

creator.dateOfBirth = data.get('dateOfBirth')
creator.location = location
creator.save()
return creator
return creator
23 changes: 11 additions & 12 deletions zubhub_backend/zubhub/creators/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,34 +6,33 @@
from math import floor



class Location(models.Model):
name = models.CharField(max_length = 100)
slug = models.SlugField(unique = True, max_length = 106)
name = models.CharField(max_length=100)
slug = models.SlugField(unique=True, max_length=106)

def save(self,*args,**kwargs):
def save(self, *args, **kwargs):
if self.slug:
pass
else:
uid = str(uuid.uuid4())
uid = uid[0: floor(len(uid)/6)]
self.slug = slugify(self.name) + "-" + uid
super().save(*args,**kwargs)
super().save(*args, **kwargs)

def __str__(self):
return self.name




class Creator(AbstractUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True)
id = models.UUIDField(
primary_key=True, default=uuid.uuid4, editable=False, unique=True)
avatar = models.URLField(max_length=1000, blank=True, null=True)
phone = models.CharField(unique=True, max_length=17, blank=True, null = True)
phone = models.CharField(unique=True, max_length=17, blank=True, null=True)
dateOfBirth = models.DateField(blank=True, null=True)
location = models.ForeignKey(Location, null=True, on_delete=models.SET_NULL)
location = models.ForeignKey(
Location, null=True, on_delete=models.SET_NULL)
bio = models.CharField(max_length=255, blank=True, null=True)

def save(self,*args,**kwargs):
def save(self, *args, **kwargs):
self.avatar = 'https://robohash.org/{0}'.format(self.username)
super().save(*args,**kwargs)
super().save(*args, **kwargs)
6 changes: 6 additions & 0 deletions zubhub_backend/zubhub/creators/permissions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from rest_framework.permissions import BasePermission

class IsOwner(BasePermission):
message = "You must be the owner of this object to perform this function"
def has_object_permission(self, request, view, objects):
return objects.pk == request.user.pk
14 changes: 10 additions & 4 deletions zubhub_backend/zubhub/creators/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,14 @@

Creator = get_user_model()


class CreatorSerializer(serializers.ModelSerializer):

class Meta:
model = Creator
fields = ('username','email',)
fields = ('username', 'email', 'avatar',
'dateOfBirth', 'location', 'bio',)


class LocationSerializer(serializers.ModelSerializer):
class Meta:
Expand All @@ -23,7 +27,8 @@ class Meta:

class CustomRegisterSerializer(RegisterSerializer):
dateOfBirth = serializers.DateField()
location = serializers.SlugRelatedField(slug_field='name', queryset = Location.objects.all())
location = serializers.SlugRelatedField(
slug_field='name', queryset=Location.objects.all())

# def validate_phone(self, phone):
# if re.search(r'^\+\d{9,15}$', phone) == None:
Expand All @@ -36,7 +41,8 @@ class CustomRegisterSerializer(RegisterSerializer):

def validate_dateOfBirth(self, dateOfBirth):
if((date.today() - dateOfBirth).days < 0):
raise serializers.ValidationError(_("Date of Birth must be less than today's date"))
raise serializers.ValidationError(
_("Date of Birth must be less than today's date"))
return dateOfBirth

def validate_location(self, location):
Expand All @@ -48,5 +54,5 @@ def get_cleaned_data(self):
data_dict = super().get_cleaned_data()
data_dict['dateOfBirth'] = self.validated_data.get('dateOfBirth', '')
data_dict['location'] = self.validated_data.get('location', '')

return data_dict
11 changes: 7 additions & 4 deletions zubhub_backend/zubhub/creators/urls.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from django.urls import path
from .views import auth_user_api_view, LocationListAPIView
from .views import auth_user_api_view, UserProfileAPIView, LocationListAPIView, EditCreatorAPIView

app_name = "creators"

urlpatterns = [
path('authUser/', auth_user_api_view, name = 'auth_user_detail'),
path('locations/', LocationListAPIView.as_view(), name = 'location_list')
]
path('authUser/', auth_user_api_view, name='auth_user_detail'),
path('edit_creator/', EditCreatorAPIView.as_view(), name='edit_creator'),
path('locations/', LocationListAPIView.as_view(), name='location_list'),
path('<str:username>/', UserProfileAPIView.as_view(), name='user_profile')
]

31 changes: 28 additions & 3 deletions zubhub_backend/zubhub/creators/views.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,42 @@
from rest_framework.generics import ListAPIView
from rest_framework.permissions import AllowAny
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import UpdateAPIView, RetrieveAPIView, ListAPIView
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from .serializers import CreatorSerializer, LocationSerializer
from django.contrib.auth import get_user_model
from .permissions import IsOwner
from .models import Location


Creator = get_user_model()


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def auth_user_api_view(request):
return Response(CreatorSerializer(request.user).data)


class UserProfileAPIView(RetrieveAPIView):
queryset = Creator.objects.all()
serializer_class = CreatorSerializer
lookup_field = "username"
permission_classes = [AllowAny]


class EditCreatorAPIView(UpdateAPIView):
queryset = Creator.objects.all()
serializer_class = CreatorSerializer
permission_classes = [IsAuthenticated, IsOwner]

def patch(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)

def get_object(self):
queryset = self.filter_queryset(self.get_queryset())
obj = queryset.get(pk=self.request.user.pk)
self.check_object_permissions(self.request, obj)
return obj

class LocationListAPIView(ListAPIView):
queryset = Location.objects.all()
Expand Down
26 changes: 16 additions & 10 deletions zubhub_frontend/zubhub/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import Login from './components/pages/user_auth/Login';
import PasswordReset from './components/pages/user_auth/PasswordReset';
import PasswordResetConfirm from './components/pages/user_auth/PasswordResetConfirm';
import EmailConfirm from './components/pages/user_auth/EmailConfirm';
import Profile from './components/pages/profile/Profile';

// import Artists from './components/pages/artists/Artists';
// import Artist from './components/pages/artists/Artist';
// import Upcoming from './components/pages/upcoming/Upcoming';
Expand All @@ -26,16 +28,8 @@ import EmailConfirm from './components/pages/user_auth/EmailConfirm';
// import NewsDetails from './components/pages/news/NewsDetails';
// import Cart from './components/pages/cart/Cart';

// import Profile from './components/pages/admin/Profile';

class App extends Component {
constructor(props){
super(props);

}





render(){
let apiProps = this.props;
Expand All @@ -48,7 +42,6 @@ return(
exact={true}
path="/"
render={props=>(
console.log(props),
<PageWrapper >
<Home {...Object.assign({}, props, apiProps)}/>
</PageWrapper>
Expand Down Expand Up @@ -89,6 +82,19 @@ return(
</PageWrapper>
)}/>

<Route path="/profile/:username"
render={props=>(
<PageWrapper>
<Profile {...Object.assign({}, props, apiProps)}/>
</PageWrapper>
)}/>

<Route path="/profile"
render={props=>(
<PageWrapper>
<Profile {...Object.assign({}, props, apiProps)}/>
</PageWrapper>
)}/>
</Switch>
</Router>
);
Expand Down
31 changes: 26 additions & 5 deletions zubhub_frontend/zubhub/src/components/PageWrapper.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,41 @@ import { withAPI } from './api';

import { ToastContainer, toast } from 'react-toastify';

import * as AuthActions from '../store/actions/authActions';
// import * as userActions from '../store/actions/userActions';
import * as AuthActions from '../store/actions/authActions'


import unstructuredLogo from '../assets/images/logos/unstructured-logo.png';
import logo from '../assets/images/logos/logo.png';


class PageWrapper extends Component {

constructor(props){
super(props);

this.state = {
username: null
}
}

componentDidMount(){
if(this.props.auth.token){
this.props.api.get_auth_user(this.props.auth.token)
.then(res=>{
if(!res.username){
throw new Error("an error occured while getting user profile, please try again later")
}
this.props.set_auth_user({...this.props.auth, username: res.username})
})
.catch(error=>toast.warning(error.message))
}
}

logout=(e)=>{
// e.preventDefault();
this.props.api.logout(this.props.auth.token)
.then(res=>{
this.props.set_auth_user({token:null, username: null, email: null})})
this.props.set_auth_user({token:null, username: null})})
.catch(error=>{
toast.warning("An error occured while signing you out. please try again")
})
Expand All @@ -30,7 +51,6 @@ class PageWrapper extends Component {

render(){
return (

<div>
<ToastContainer/>
<header className="App-header">
Expand All @@ -43,7 +63,8 @@ return (
</>
:
<>
<img src={`https://robohash.org/${this.props.auth.username}`} className="profile_image" aria-label="creator profile"/>
<Link to={`/profile/${this.props.auth.username}`}>
<img src={`https://robohash.org/${this.props.auth.username}`} className="profile_image" aria-label="creator profile"/></Link>
<Link className="btn btn-danger" onClick={this.logout}>Logout</Link>
</>
}
Expand Down
Loading