Skip to content

Commit

Permalink
Merge pull request madisona#52 from arossoftware/refactoring_tokens
Browse files Browse the repository at this point in the history
refactoring oauth2, permissions, conditions
  • Loading branch information
aruseni authored Oct 15, 2020
2 parents 1e41816 + bdec7f3 commit 681afce
Show file tree
Hide file tree
Showing 17 changed files with 381 additions and 395 deletions.
9 changes: 3 additions & 6 deletions frontend/src-admin/store/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -293,10 +293,9 @@ export default new Vuex.Store({
})
},

[actionTypes.GET_ADMIN_DATA]({ commit, state }) {
[actionTypes.GET_ADMIN_DATA]({ commit }) {
return new Promise((resolve, reject) => {
const name = encodeURIComponent(state.user.name)
getAdmin(`/${name}/`)
getAdmin()
.then((response) => {
commit(mutationTypes.SET_USER_DATA, response.data)
resolve(response.data)
Expand All @@ -307,11 +306,9 @@ export default new Vuex.Store({
})
},

[actionTypes.CHANGE_ADMIN_DATA] ({commit, state}, payloads) {
[actionTypes.CHANGE_ADMIN_DATA] ({commit}, payloads) {
return new Promise((resolve, reject) => {
const name = encodeURIComponent(state.user.name)
updateAdmin({
url: `/${name}/`,
data: payloads
})
.then((response) => {
Expand Down
2 changes: 1 addition & 1 deletion frontend/src-admin/views/CustomersView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
<div class="d-flex justify-content-center">
<b-button
v-if="!data.tbl.item.verified && data.tbl.item.is_active"
v-b-tooltip.hover
v-b-tooltip.hover.left
:title="$t('table.customers.button_resend_email_confirmation')"
size="sm"
class="mr-1"
Expand Down
2 changes: 1 addition & 1 deletion frontend/src-base/locale/da/da.json
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@
"success_feedback_sent": "Din feedback blev modtaget. Vi vil kontakte dig så hurtigt som muligt."
},
"auth": {
"success_restore": "Nulstilling af adgangskode er blevet sendt."
"success_reset_password": "Nulstilling af adgangskode er blevet sendt."
},
"user_settings": {
"warning_verify_email": "E-mail adressen er ændret. Bekræft venligst dette.",
Expand Down
14 changes: 14 additions & 0 deletions frontend/src-base/store/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ const setCsrfToken = (config) => {
config.headers.common['X-CSRFTOKEN'] = csrfToken
}

export const baseRequestInterceptor = (config) => {
setCsrfToken(config)
return config
}

export const adminRequestInterceptor = (config) => {
setCsrfToken(config)
const adminToken = localStorage.getItem('AdminToken')
Expand Down Expand Up @@ -108,6 +113,15 @@ export const customerResponseRejectedInterceptor = error => {
return Promise.reject(error)
}

const axiosInstances = [
refreshToken,
changeLanguage,
]

for (const instance of axiosInstances) {
instance.interceptors.request.use(baseRequestInterceptor)
}

export const baseState = {
showLoader: true,
user: {
Expand Down
7 changes: 3 additions & 4 deletions frontend/src-user/store/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,9 @@ export default new Vuex.Store({
actions: {
...baseActions,

[actionTypes.GET_CUSTOMER_DATA]({ commit, state }) {
[actionTypes.GET_CUSTOMER_DATA]({ commit }) {
return new Promise((resolve, reject) => {
customerGet(`/${state.user.email}/`)
customerGet()
.then((response) => {
commit(mutationTypes.SET_USER_DATA, response.data)
commit(mutationTypes.SET_CUSTOMER_DATA, response.data)
Expand All @@ -99,10 +99,9 @@ export default new Vuex.Store({
})
},

[actionTypes.CHANGE_CUSTOMER_DATA] ({commit, state}, payloads) {
[actionTypes.CHANGE_CUSTOMER_DATA] ({commit}, payloads) {
return new Promise((resolve, reject) => {
updateCustomer({
url: `/${state.user.email}/`,
data: payloads
})
.then((response) => {
Expand Down
47 changes: 29 additions & 18 deletions loppeonline/api/v1/admin/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
IsAuthenticated,
IsMarketSalesAccess,
IsMarketAccess,
IsMarketAdmin,
)
from loppeonline.apps.users.tasks import bulk_create_economic_customers
from loppeonline.utils.api_filters import (
Expand Down Expand Up @@ -68,7 +69,7 @@ class AdminMarketViewSet(viewsets.ModelViewSet):
Admin POS view for market operations
"""

permission_classes = [IsAuthenticated, IsMarketAccess]
permission_classes = [IsAuthenticated, IsMarketAccess, IsMarketAdmin]
serializer_class = AdminMarketModelSerializer
lookup_field = "market_id"

Expand All @@ -89,7 +90,7 @@ class AdminMarketImagesViewSet(
"""

parser_classes = (MultiPartParser, FormParser, JSONParser)
permission_classes = [IsAuthenticated, IsMarketAccess]
permission_classes = [IsAuthenticated, IsMarketAccess, IsMarketAdmin]
serializer_class = MarketImageModelSerializer

def get_queryset(self):
Expand All @@ -104,7 +105,7 @@ class AdminCustomerViewSet(viewsets.ModelViewSet):
Admin POS view for customer operations
"""

permission_classes = [IsAuthenticated, IsMarketAccess]
permission_classes = [IsAuthenticated, IsMarketAccess, IsMarketAdmin]
pagination_class = ViewSetPagination
filterset_class = AdminCustomerFilter
filter_backends = (
Expand Down Expand Up @@ -177,7 +178,7 @@ class AdminMarketShelfViewSet(viewsets.ModelViewSet):
Admin view for market shelf operations
"""

permission_classes = [IsAuthenticated, IsMarketAccess]
permission_classes = [IsAuthenticated, IsMarketAccess, IsMarketAdmin]
filter_backends = (SearchFilter,)
search_fields = [
'name',
Expand Down Expand Up @@ -213,14 +214,14 @@ def get_queryset(self):
date_start = self.request.query_params.get('date_start')
date_end = self.request.query_params.get('date_end')
if date_start and date_end:
qs = MarketShelf.objects.select_related(
'market'
).filter(
market=self.request.user.market_inst
).exclude(
qs = (
MarketShelf.objects.select_related('market')
.filter(market=self.request.user.market_inst)
.exclude(
bookings__date_start__lte=date_end,
bookings__date_end__gte=date_start,
)
)
elif date_start or date_end:
raise ValidationError(
_('Date start and date end should be together.')
Expand All @@ -237,7 +238,7 @@ class AdminShelfBookingViewSet(viewsets.ModelViewSet):
Admin view for shelf booking operations
"""

permission_classes = [IsAuthenticated, IsMarketAccess]
permission_classes = [IsAuthenticated, IsMarketAccess, IsMarketAdmin]
filterset_class = AdminShelfBookingsFilter
serializer_class = AdminShelfBookingModelSerializer

Expand All @@ -256,7 +257,7 @@ class AdminCustomerBookingsViewSet(generics.ListAPIView):
"""

pagination_class = ViewSetPagination
permission_classes = [IsAuthenticated, IsMarketAccess]
permission_classes = [IsAuthenticated, IsMarketAccess, IsMarketAdmin]
serializer_class = AdminShelfBookingModelSerializer

def get_queryset(self):
Expand All @@ -276,7 +277,7 @@ class AdminGetCustomerViewSet(
Admin POS view for customer operations
"""

permission_classes = [IsAuthenticated, IsMarketAccess]
permission_classes = [IsAuthenticated, IsMarketAccess, IsMarketAdmin]
serializer_class = AdminGetCustomerModelSerializer
lookup_field = 'user_number'

Expand All @@ -292,7 +293,7 @@ class AdminCustomersSummaryView(generics.ListAPIView):
Admin view for getting all customers
"""

permission_classes = [IsAuthenticated, IsMarketAccess]
permission_classes = [IsAuthenticated, IsMarketAccess, IsMarketAdmin]
serializer_class = AdminCustomersSummarySerializer

def get_queryset(self):
Expand All @@ -305,7 +306,7 @@ def get_queryset(self):


class AdminSendEmailConfirmationApiView(generics.GenericAPIView):
permission_classes = [IsAuthenticated, IsMarketAccess]
permission_classes = [IsAuthenticated, IsMarketAccess, IsMarketAdmin]
serializer_class = AdminSendEmailConfirmationSerializer

def post(self, request, *args, **kwargs):
Expand All @@ -326,7 +327,12 @@ class AdminResetCustomerPasswordViewSet(
View for updating customer password
"""

permission_classes = [IsAuthenticated, IsMarketSalesAccess, IsMarketAccess]
permission_classes = [
IsAuthenticated,
IsMarketSalesAccess,
IsMarketAccess,
IsMarketAdmin,
]
lookup_field = 'user_number'

def get_queryset(self):
Expand Down Expand Up @@ -357,7 +363,12 @@ class AdminVerifyCustomerViewSet(
View for updating customer password
"""

permission_classes = [IsAuthenticated, IsMarketSalesAccess, IsMarketAccess]
permission_classes = [
IsAuthenticated,
IsMarketSalesAccess,
IsMarketAccess,
IsMarketAdmin,
]
lookup_field = 'user_number'

def get_queryset(self):
Expand Down Expand Up @@ -385,7 +396,7 @@ def update(self, request, *args, **kwargs):


class AdminGetPaymentsInfoView(APIView):
permission_classes = [IsAuthenticated, IsMarketAccess]
permission_classes = [IsAuthenticated, IsMarketAccess, IsMarketAdmin]

def get(self, request, export=None, format=None):
serializer = AdminGetPaymentsInfoViewSerializer(
Expand All @@ -411,7 +422,7 @@ class AdminPaymentsInfoSalesPeriodViewSet(
mixins.DestroyModelMixin,
viewsets.GenericViewSet,
):
permission_classes = [IsAuthenticated, IsMarketAccess]
permission_classes = [IsAuthenticated, IsMarketAccess, IsMarketAdmin]
serializer_class = AdminPaymentsInfoSalesPeriodModelSerializer

def create(self, request, *args, **kwargs):
Expand Down
4 changes: 3 additions & 1 deletion loppeonline/api/v1/user/api.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from oauth2_provider.contrib.rest_framework import OAuth2Authentication
from rest_framework import viewsets, mixins

from loppeonline.apps.markets.models import Market
Expand All @@ -8,6 +7,7 @@
IsMarketApiValid,
IsMarketSalesAccess,
IsMarketAccess,
IsMarketCustomer,
)
from loppeonline.utils.api_filters import UserSaleLinesFilter

Expand All @@ -27,6 +27,7 @@ class UserGetMarketViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
IsMarketApiValid,
IsMarketSalesAccess,
IsMarketAccess,
IsMarketCustomer,
]
serializer_class = UserGetMarketModelSerializer
lookup_field = 'market_id'
Expand All @@ -48,6 +49,7 @@ class UserGetSaleLines(mixins.ListModelMixin, viewsets.GenericViewSet):
IsMarketApiValid,
IsMarketSalesAccess,
IsMarketAccess,
IsMarketCustomer,
]
serializer_class = UserGetSaleLinesModelSerializer
filterset_class = UserSaleLinesFilter
Expand Down
7 changes: 5 additions & 2 deletions loppeonline/apps/markets/tasks.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import datetime
import logging

from celery import shared_task

Expand All @@ -9,6 +10,8 @@
create_sale_lines,
)

logger = logging.getLogger(__name__)


@shared_task
def collect_initial_sale_data(market_id):
Expand Down Expand Up @@ -42,6 +45,6 @@ def collect_initial_sale_data(market_id):
data = get_sale_data(token, data['NextPageUrl'])
create_sale_lines(data, market_inst)
else:
print("Something went wrong while collecting sale data")
logger.warning("Something went wrong while collecting sale data")

print(f"Sale data for market {market_id} successfully collected!")
logger.info(f"Sale data for market {market_id} successfully collected!")
12 changes: 8 additions & 4 deletions loppeonline/apps/users/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,16 @@ class Meta:
def is_admin(self):
return self.user_type == self.ADMIN

@property
def is_customer(self):
return self.user_type == self.CUSTOMER

@property
def market_inst(self):
if self.user_type == CustomUser.ADMIN and hasattr(self, 'market'):
if self.is_admin and hasattr(self, 'market'):
return self.market
if (
self.user_type == CustomUser.CUSTOMER
self.is_customer
and hasattr(self, 'customer')
and self.customer.market
):
Expand All @@ -74,13 +78,13 @@ def market_inst(self):
def __str__(self):
if self.get_username():
return self.get_username()
if self.user_type == CustomUser.CUSTOMER:
if self.is_customer:
if hasattr(self, 'customer') and self.customer.market:
return gettext('Customer {} for {}').format(
self.customer.user_number, self.customer.market.market_id,
)
return gettext('Customer')
if self.user_type == CustomUser.ADMIN:
if self.is_admin:
return gettext('Admin for market {}').format(self.market.market_id)


Expand Down
Loading

0 comments on commit 681afce

Please sign in to comment.