def get_refresh(self, obj): return str(RefreshToken.for_user(obj))
def tokens(self): refresh = RefreshToken.for_user(self) return {"refresh": str(refresh), "access": str(refresh.access_token)}
def get_token(self, user): return RefreshToken.for_user(user)
def setUp(self): self.first_company = Company.objects.create(trade_name="company one", slug="c1", is_active=True) self.active_user = User.objects.create( email="*****@*****.**", password="******", is_active=True, default_company=self.first_company) self.first_code_group = CodeGroup.objects.create( company=self.first_company, name="group-test", group_type="Stop Code") self.first_stop_code = StopCode.objects.create( company=self.first_company, is_planned=False, name="stop code test", code_group=self.first_code_group) self.first_production_line = ProductionLine.objects.create( company=self.first_company, name="c1", is_active=True, discount_rework=True, discount_waste=True, stop_on_production_absence=True, time_to_consider_absence=True, reset_production_changing_order=True, micro_stop_seconds=10200) self.second_production_line = ProductionLine.objects.create( company=self.first_company, name="pl2", is_active=True, discount_rework=True, discount_waste=True, stop_on_production_absence=True, time_to_consider_absence=True, reset_production_changing_order=True, micro_stop_seconds=20500) self.noise_company = Company.objects.create(trade_name="company two", slug="c2", is_active=False) self.first_company.users.add(self.active_user) active_refresh = RefreshToken.for_user(self.active_user) self.active_token = str(active_refresh.access_token) self.authorization_active_token = f'Bearer {self.active_token}' self.unactivated_user = User.objects.create( email="*****@*****.**", password="******", is_active=False) self.noise_company.users.add(self.unactivated_user) unactivated_refresh = RefreshToken.for_user(self.unactivated_user) self.unactivated_token = str(unactivated_refresh.access_token) self.index_route = f'/v1/companies/{self.first_company.id}/availability/' self.state_events = [ self.create_state_event( self.first_production_line, None, datetime.datetime(2019, 12, 3, 11, 3, 55, 988870, tzinfo=pytz.UTC).strftime( self.test_date_format), choices.ON), self.create_state_event( self.first_production_line, None, datetime.datetime(2019, 12, 3, 12, 3, 54, 988870, tzinfo=pytz.UTC).strftime( self.test_date_format), choices.ON), self.create_state_event( self.second_production_line, None, datetime.datetime(2019, 12, 3, 12, 3, 54, 988870, tzinfo=pytz.UTC).strftime( self.test_date_format), choices.ON), self.create_state_event( self.second_production_line, None, datetime.datetime(2019, 12, 3, 12, 8, 54, 988870, tzinfo=pytz.UTC).strftime( self.test_date_format), choices.ON), self.create_state_event( self.first_production_line, self.first_stop_code, datetime.datetime(2019, 12, 3, 12, 3, 55, 988870, tzinfo=pytz.UTC).strftime( self.test_date_format), choices.OFF), self.create_state_event( self.first_production_line, self.first_stop_code, datetime.datetime(2019, 12, 3, 12, 50, 54, 988870, tzinfo=pytz.UTC).strftime( self.test_date_format), choices.OFF), self.create_state_event( self.first_production_line, self.first_stop_code, datetime.datetime(2019, 12, 3, 13, 30, 54, 988870, tzinfo=pytz.UTC).strftime( self.test_date_format), choices.OFF), self.create_state_event( self.second_production_line, None, datetime.datetime(2019, 12, 3, 12, 3, 55, 988870, tzinfo=pytz.UTC).strftime( self.test_date_format), choices.ON), self.create_state_event( self.second_production_line, None, datetime.datetime(2019, 12, 3, 12, 8, 54, 988870, tzinfo=pytz.UTC).strftime( self.test_date_format), choices.ON) ]
def save(self, **kwargs): try: RefreshToken(self.token).blacklist() except TokenError: self.fail('bad token')
def get_token(user): refresh = RefreshToken.for_user(user) return {"refresh": str(refresh), "access": str(refresh.access_token)}
def refresh_validate(token): newtoken = RefreshToken(token) return str(newtoken.access_token)
def django_saved_schedules_view(request): return render(request, 'saved_schedules.html', { 'access_token': str(RefreshToken.for_user(request.user).access_token) })
def token(self): refresh = RefreshToken.for_user(self) return str(refresh.access_token)
def test_init(self): # Should set token type claim token = RefreshToken() self.assertEqual(token[api_settings.TOKEN_TYPE_CLAIM], 'refresh')
def post(self, request): refresh_token = RefreshToken(token=request.data.get('refresh_token')) return Response({'access_token': str(refresh_token.access_token)})
def tokens(self): tokens = RefreshToken.for_user(self) return { 'refresh': str(tokens), 'access': str(tokens.access_token) }
def api_client(normal_user_a): client = APIClient() refresh = RefreshToken.for_user(normal_user_a) client.credentials(HTTP_AUTHORIZATION=f'Bearer {refresh.access_token}') return client
def post(request): tokenb64 = request.data['token'] token = RefreshToken(tokenb64) token.blacklist() return Response(status=status.HTTP_302_FOUND, headers={'Location': settings.BASE_URL})
def setUp(self): self.user = User.objects.create_user(email="*****@*****.**", password="******") refresh = RefreshToken.for_user(self.user) self.client.credentials( HTTP_AUTHORIZATION=f"Bearer {refresh.access_token}")
def setup(self): user = UserFactory.create(username='******', password='******') self.test_post = PostFactory.create(user=user) self.jwt = str(RefreshToken.for_user(user).access_token)
def login_token(self, user): self.client.force_login(user=user) tokens = RefreshToken.for_user(user) access_token = str(tokens.access_token) return access_token
def setup(self): self.user = UserFactory.create(username='******', password='******') self.post = PostFactory.create() self.jwt = str(RefreshToken.for_user(self.user).access_token) client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.jwt)
def generate_refreshtoken(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), }
def validate(self, attrs): refresh = RefreshToken(attrs["refresh"]) data = {"access": str(refresh.access_token)} data["refresh"] = str(refresh) return data
def logout(self, request): try: request.user.auth_token.delete() except (AttributeError, ObjectDoesNotExist): pass if getattr(settings, 'REST_SESSION_LOGIN', True): django_logout(request) response = Response({"detail": _("Successfully logged out.")}, status=status.HTTP_200_OK) if getattr(settings, 'REST_USE_JWT', False): # NOTE: this import occurs here rather than at the top level # because JWT support is optional, and if `REST_USE_JWT` isn't # True we shouldn't need the dependency from rest_framework_simplejwt.exceptions import TokenError from rest_framework_simplejwt.tokens import RefreshToken cookie_name = getattr(settings, 'JWT_AUTH_COOKIE', None) if cookie_name: response.delete_cookie(cookie_name) elif 'rest_framework_simplejwt.token_blacklist' in settings.INSTALLED_APPS: # add refresh token to blacklist try: token = RefreshToken(request.data['refresh']) token.blacklist() except KeyError: response = Response( { "detail": _("Refresh token was not included in request data." ) }, status=status.HTTP_401_UNAUTHORIZED) except (TokenError, AttributeError, TypeError) as error: if hasattr(error, 'args'): if 'Token is blacklisted' in error.args or 'Token is invalid or expired' in error.args: response = Response( {"detail": _(error.args[0])}, status=status.HTTP_401_UNAUTHORIZED) else: response = Response( {"detail": _("An error has occurred.")}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: response = Response( {"detail": _("An error has occurred.")}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: response = Response( { "detail": _("Neither cookies or blacklist are enabled, so the token has not been deleted server " "side. Please make sure the token is deleted client side." ) }, status=status.HTTP_200_OK) return response
def login(request): try: username = request.POST.get("username") password = request.POST.get("password") fcm_token = request.POST.get('fcm_token') type_device = request.POST.get('type_device') if username is None or password is None: data = { 'status': 'error', 'message': 'Por favor especifique usuario y contraseña', 'code': 400 } else: user = models.User.objects.get(useremail__exact=username) person = models.Person.objects.get(user__userid__exact=user.userid) # .filter(password__exact = password) #user = authenticate(email=username, password=password) # Si el correo electrónico existe # Contexto Passlib pwd_context = CryptContext(schemes=["pbkdf2_sha256"], default="pbkdf2_sha256", pbkdf2_sha256__default_rounds=30000) passwordVerification = pwd_context.verify(password, user.password) if (passwordVerification): # Generación de tokens refresh = RefreshToken.for_user(user) # Almacenando los permisos del usuario en la sesión request.session['permisos'] = [] permisos = models.RolePermissionn.objects.filter( role__role_id__exact=person.role.role_id) for i in permisos: request.session['permisos'].append(str(i.permissionn_id)) # Consultando el nombre del rol del usuario autenticado rol = models.Role.objects.get( person__pers_id__exact=person.pers_id) data = { 'token': str(refresh.access_token), 'user': { 'userid': user.userid, #Para web 'pers_id': user.userid, #Para movil 'userfullname': person.pers_name + " " + person.pers_lastname, 'useremail': user.useremail, 'rol': rol.role_name, #Para web 'role_name': rol.role_name, #Para movil 'puntaje': person.pers_score }, 'code': 200 } if fcm_token is not None and type_device is not None: device = FCMDevice.objects.filter( user_id__exact=user.userid).first() if device is not None: current_fcmtkn = device.registration_id if current_fcmtkn != fcm_token: device.registration_id = fcm_token device.type = type_device device.save() #verificar sesiones activas y cerrarlas else: device = FCMDevice(user=user, registration_id=fcm_token, type=type_device) device.save() else: #login desde la web ROL_SUPER_ADMIN = '8945979e-8ca5-481e-92a2-219dd42ae9fc' ROL_PROYECTISTA = '628acd70-f86f-4449-af06-ab36144d9d6a' print(person.role.role_id) if (str(person.role.role_id) == ROL_SUPER_ADMIN or str(person.role.role_id) == ROL_PROYECTISTA): print("if") pass else: print("else") data = { 'code': 403, 'status': 'error', 'message': 'Acceso no permitido para ese usuario', } # Puntaje esperado para llegar a rol proximo # Voluntario # if str(rol.rolid) == '0be58d4e-6735-481a-8740-739a73c3be86': # data['user']['promocion'] = { # 'rol': "Validador", # 'puntaje': int(settings['umbral-validador']) # } # Proyectista # elif str(rol.rolid) == '53ad3141-56bb-4ee2-adcf-5664ba03ad65': # data['user']['promocion'] = { # 'rol': "Proyectista", # 'puntaje': int(settings['umbral-proyectista']) # } else: data = { 'status': 'error', 'message': 'Usuario y/o contraseña incorrecta', 'code': 404 } except ObjectDoesNotExist: data = { 'status': 'error', 'message': 'Usuario y/o contraseña incorrecta', 'code': 404 } return JsonResponse(data, status=data['code'])
def validating_client_admin(test_validating_reseller): token = RefreshToken.for_user(test_validating_reseller) client = APIClient() client.credentials(HTTP_AUTHORIZATION=f"Bearer {token.access_token}") return client
def post(self, request): outdated_token = request.data.get('token') # print(outdated_token) token = RefreshToken(outdated_token) token.blacklist() return Response(status=status.HTTP_202_ACCEPTED)
def tokens(self): refresh = RefreshToken.for_user(self) return {'refresh': str(refresh), 'access': str(refresh.access_token)}
def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) token = str(refresh.access_token) return token
def get_token(cls, user): return RefreshToken.for_user(user)
def get_tokens_for_user(self, user): refresh = RefreshToken.for_user(user) return str(refresh.access_token)
def get_token(self, obj): print(self, obj) token = RefreshToken.for_user(obj) return str(token.access_token)
def save(self): refresh = self.context['request'].data.get('refresh', '') RefreshToken(refresh).blacklist()