Exemple #1
0
def get_access_token(request):
	"""
	Generates an access token for valid app users
	@param request:
	@type request: DJANGO WSGIRequest
	@return: An access token and its expiry time or a response code indicating invalid credentials supplied
	@rtype: dict
	"""
	try:
		data = get_request_data(request)
		app_user = AppUserService().get(user__username = data.get('username'))
		if app_user is not None:
			user = check_password(data.get('password'), app_user.user.password)
			if user:
				oauth = OauthService().filter(
					app_user = app_user, expires_at__gt = timezone.now(), state__name = 'Active').first()
				if oauth:
					oauth = OauthService().update(pk = oauth.id, expires_at = token_expiry())
				else:
					oauth = OauthService().create(
						app_user = app_user, token = generate_access_token(),
						state = StateService().get(name = 'Active')
					)
				if not oauth:
					return JsonResponse({'code': '800.400.001'})
				return JsonResponse({
					                    'code': '800.200.001', 'data': {
						'token': str(oauth.token), 'expires_at': calendar.timegm(oauth.expires_at.timetuple())
					}
				                    })
		return JsonResponse({'code': '800.403.001'})
	except Exception as ex:
		lgr.exception("Get Access token Exception %s " % ex)
	return JsonResponse({'code': '800.400.001'})
Exemple #2
0
    def get_logged_in_user_notifications(token, parameters):
        """

		@param token: the given token of a logged in user
		@type: str
		@param parameters:  a dictionary containing parameters used for fetching notification data
		@type: dict
		@return: a dictionary containing response code and data
		@rtype:dict
		"""

        try:
            user = OauthService().filter(token=token).values(
                user=F('app_user__user')).first()
            user_id = user.get('user')
            recipient = User.objects.filter(id=user_id).values(
                'phone_number', 'email').first()
            if not parameters or not token or not user:
                return {
                    "code": "800.400.002",
                    "message": "invalid required parameters"
                }
            row = NotificationService().filter(
                Q(recipient=recipient['email'])
                | Q(recipient=recipient['phone_number']))
            columns = [
                'message', 'recipient', 'state__name',
                'notification_type__name'
            ]
            search_query = build_search_query(
                search_value=parameters.get('search_query'), columns=columns)
            if parameters.get('order_column'):
                row = extract_order(
                    order_column=parameters.get('order_column'),
                    order_dir=parameters.get('order_dir'),
                    data=row)
            if parameters.get('search_query'):
                row = row.filter(search_query)
            row = list(
                row.values('message',
                           'recipient',
                           dateCreated=F('date_created'),
                           status=F('state__name'),
                           Id=F('id'),
                           type=F('notification_type__name')))
            table_data = paginate_data(
                data=row,
                page_size=parameters.get('page_size'),
                page_number=parameters.get('page_number'))
            return {
                'code': '800.200.001',
                'data': table_data,
                'recipient': recipient
            }
        except Exception as ex:
            lgr.exception("Notification Logger exception: %s" % ex)
        return {
            "code": "800.400.001",
            "message": "error in fetching recent user notifications"
        }
Exemple #3
0
    def get_logged_in_user_recent_notifications(token):
        """

		@param token: the given token of a logged in user
		@type: str
		@return: a dictionary containing response code and data
		@rtype:dict
		"""

        try:
            user = OauthService().filter(token=token).values(
                user=F('app_user__user')).first()
            user_id = user.get('user')
            recipient = User.objects.filter(id=user_id).values(
                'phone_number', 'email').first()
            now = timezone.now()
            recently = now - timedelta(hours=6, minutes=0)
            current_hour = timezone.now()
            notifications = list(NotificationService().filter(
                recipient=recipient['email'],
                date_created__lte=current_hour,
                date_created__gte=recently).values())
            sms_notification = list(NotificationService().filter(
                recipient=recipient['phone_number'],
                date_created__lte=current_hour,
                date_created__gte=recently).values())
            for sms in sms_notification:
                notifications.append(sms)
            return {"code": "800.200.001", "data": notifications}
        except Exception as ex:
            lgr.exception("Notification Logger exception: %s" % ex)
        return {
            "code": "800.400.001",
            "message": "error in fetching recent user notifications"
        }
Exemple #4
0
    def verify_token(token, **kwargs):
        """
		Verifies the access token granted to a user
		@param token: The authorization token
		@type token: str
		@param kwargs: Extra key-value arguments that can be passed into the method
		@return: A response code indicating status and the access token
		"""
        try:
            oauth = OauthService().filter(token=token,
                                          expires_at__gte=timezone.now(),
                                          state__name='Active').first()
            if oauth is None:
                return {'code': '800.400.002'}
            if OauthService().update(pk=oauth.id,
                                     expires_at=token_expiry()) is not None:
                updated_oauth = OauthService().filter(pk=oauth.id).first()
                return {
                    'code': '800.200.001',
                    'data': {
                        'token':
                        str(updated_oauth.token),
                        'expires_at':
                        calendar.timegm(updated_oauth.expires_at.timetuple())
                    }
                }
        except Exception as ex:
            lgr.exception('Verify Token Exception %s' % ex)
        return {'code': '800.400.001'}
Exemple #5
0
    def edit_logged_in_user_password(token,
                                     current_password=None,
                                     new_password=None,
                                     **kwargs):
        """
		@param token: the token of the logged in user
		@type: str
		@param current_password: password of the logged in user
		@type:str
		@param new_password:new password of the logged in user
		@type:str
		@return:Response code dictionary indicating if the password update was okay
		"""
        try:
            user_id = OauthService().filter(
                token=token).values('app_user__user__id').first()
            user = User.objects.get(id=user_id.get("app_user__user__id"))
            if user:
                if not user.check_password(current_password):
                    return {
                        "code": "800.400.001",
                        "message": "Current password given is invalid"
                    }
                user.set_password(new_password)
                user.save()
                return {
                    "code": "800.200.001",
                    "message": "Password successfully updated"
                }
        except Exception as ex:
            lgr.exception("Logged in user exception: %s" % ex)
        return {
            "code": "800.400.001",
            "message": "logged in user password update fail"
        }
Exemple #6
0
    def get_logged_in_user_details(token, **kwargs):
        """
		@param token: the generated token of the user
		@type token:char
		@param kwargs: Extra key arguments passed to the method
		@return: Response code dictionary
		"""
        try:
            app_user = OauthService().filter(
                token=token).values('app_user').first()
            user = AppUserService().filter(id=app_user.get('app_user')).values(
                userName=F('user__username'),
                email=F('user__email'),
                superUser=F('user__is_superuser'),
                firstName=F('user__first_name'),
                lastName=F('user__last_name'),
                log=F('user__logentry'),
                staff=F('user__is_staff'),
                phoneNumber=F('user__phone_number'),
                password=F('user__password')).first()
            if user.get('superUser'):
                user.update(role='Admin')
            elif user.get('staff'):
                user.update(role='Staff')
            else:
                user.update(role='User')
            return {'code': '800.200.001', "data": user}
        except Exception as ex:
            lgr.exception("Logged in user exception %s" % ex)
        return {"code": "800.400.001"}
 def test_update(self):
     """
     Test Oauth update service
     """
     oauth = mixer.blend('api.Oauth')
     oauth = OauthService().update(oauth.id, token="12345")
     assert oauth.token == "12345", 'Should have the same token'
 def test_filter(self):
     """
     Test Oauth filter service
     """
     mixer.cycle(3).blend('api.oauth')
     oauths = OauthService().filter()
     assert len(oauths) == 3, 'Should have 3 Oauth objects'
 def test_get(self):
     """
     Test Oauth get service
     """
     mixer.blend('api.Oauth', token="12345")
     oauth = OauthService().get(token="12345")
     assert oauth is not None, 'Should have an oauth object'
Exemple #10
0
 def wrapped_view(*args, **kwargs):
     """This method wraps the decorated method."""
     is_checked = False
     for k in args:
         if isinstance(k, WSGIRequest):
             request_data = get_request_data(k)
             token = request_data.get("token", None)
             if token:
                 is_checked = True
                 oauth = OauthService().filter(
                     token=token,
                     expires_at__gt=timezone.now(),
                     state__name="Active").first()
                 if not oauth:
                     response = HttpResponse(
                         json.dumps({
                             'status': 'failed',
                             'message':
                             'Unauthorized. Invalid credentials.',
                             'code': '800.403.001'
                         }),
                         content_type='application/json',
                         status=401)
                     response['WWW-Authenticate'] = 'Bearer realm=api'
                     return response
                 OauthService().update(oauth.id, expires_at=token_expiry())
                 setattr(k, 'app_user', oauth.app_user)
             else:
                 return JsonResponse(
                     {
                         'status': 'failed',
                         'message':
                         'Unauthorized. Authorization parameters not Found!',
                         'code': '800.403.001'
                     },
                     status=401)
     if not is_checked:
         response = HttpResponse(json.dumps({
             'status': 'failed',
             'message': 'Unauthorized. Credentials not Provided.',
             'code': '800.403.001'
         }),
                                 content_type='application/json',
                                 status=401)
         response['WWW-Authenticate'] = 'Bearer realm=api'
         return response
     return view_func(*args, **kwargs)
 def test_create(self):
     """
     Test Oauth create service
     """
     app_user = mixer.blend('api.AppUser')
     oauth = OauthService().create(token="12345",
                                   app_user=app_user,
                                   state=mixer.blend('base.State'))
     assert oauth is not None, 'Should have an Oauth object'
     assert oauth.token == "12345", "Created Oauth token is equals to 12345"
Exemple #12
0
    def edit_logged_in_user_details(token,
                                    username=None,
                                    first_name=None,
                                    last_name=None,
                                    phone_number=None,
                                    email=None,
                                    **kwargs):
        """
		@param email: Email of the user
		@type token: str
		@param phone_number: phone_number of the user
		@type phone_number: str
		@param last_name: Users last name
		@type last_name: str
		@param first_name:
		@param username:
		@param token: the token of a logged in user
		@type:str
		@param kwargs: Extra key arguments passed to the method
		@return:Response code dictionary indicating if the update was okay
		"""
        try:
            user_id = OauthService().filter(token=token).values(
                userId=F('app_user__user__id')).first()
            user = User.objects.get(id=user_id.get('userId'))
            if user:
                user.username = username if username else user.username
                user.email = email if email else user.email
                user.first_name = first_name if first_name else user.first_name
                user.last_name = last_name if last_name else user.last_name
                user.phone_number = phone_number if phone_number else user.phone_number
                user.save()
                updated_user = User.objects.filter(
                    id=user_id.get('userId')).values().first()
                return {'code': '800.200.001', "data": updated_user}
        except Exception as ex:
            lgr.exception("Logged in user exception: %s" % ex)
        return {"code": "800.400.001", "message": "Logged in user update fail"}