def authenticate(self, request): api_secret_key = request.META.get('HTTP_API_SECRET_KEY', None) if api_secret_key is None: raise exceptions.NotAuthenticated( 'Api Secret key is missing in request header ') if settings.API_SECRET_KEY != api_secret_key: raise exceptions.NotAuthenticated('Api Secret key is not valid')
def authenticate(self, request): """ Check whether the request provides a valid OAuth2 bearer token. The `user` in `cas_auth_response` is the unique GUID of the user. Please do not use the primary key `id` or the email `username`. :param request: the request :return: the user who owns the bear token and the cas repsonse """ client = cas.get_client() try: auth_header_field = request.META['HTTP_AUTHORIZATION'] auth_token = cas.parse_auth_header(auth_header_field) except (cas.CasTokenError, KeyError): return None try: cas_auth_response = client.profile(auth_token) except cas.CasHTTPError: raise exceptions.NotAuthenticated( _('User provided an invalid OAuth2 access token')) if cas_auth_response.authenticated is False: raise exceptions.NotAuthenticated( _('CAS server failed to authenticate this token')) user = OSFUser.load(cas_auth_response.user) if not user: raise exceptions.AuthenticationFailed( _('Could not find the user associated with this token')) check_user(user) return user, cas_auth_response
def authenticate_credentials(self, key): key = key.strip() model = self.get_model() try: token = model.objects.select_related('user').get(key=key) except model.DoesNotExist: print("invalid token!!") raise exceptions.NotAuthenticated('Invalid token.') if not token.user.is_active: raise exceptions.NotAuthenticated('User inactive or deleted.') utc_now = datetime.utcnow() utc_now = utc_now.replace(tzinfo=pytz.utc) if token.last_activity < utc_now - timedelta( minutes=settings.TOKEN_TIMEOUT): token.delete() print("Token has expired!!") raise exceptions.NotAuthenticated('Token has expired') token.last_activity = utc_now token.save() return token.user, token
def authenticate(self, request=None, **credentials): if request is not None: if "Authorization" in request.headers: hdr = request.headers["Authorization"].split() try: payload = decode_jwt(hdr[1]) except jwt.ExpiredSignatureError: msg = "Signature has expired." raise exceptions.NotAuthenticated(msg) except jwt.DecodeError: msg = "Error decoding signature." raise exceptions.NotAuthenticated(msg) except (jwt.InvalidTokenError, jwt.InvalidSignatureError): raise exceptions.NotAuthenticated() uri, http_method, body, headers = OAuthLibCore._extract_params(request) headers["HTTP_AUTHORIZATION"] = " ".join( [hdr[0], payload["access_token"]] ) headers["Authorization"] = " ".join([hdr[0], payload["access_token"]]) valid, r = OAuthLibCore.server.verify_request( uri, http_method, body, headers, scopes=[] ) if valid: return r.user return None
def validate(self, attrs): email = attrs.get('email') password = attrs.get('password') new_password = attrs.get('new_password') token = attrs.get('token', None) user = None detail = None # Authenticate by one-click-login token if token: user = TokenAuthService.check_token(token, return_user=True) # Authenticate by email and old password if email and password: detail = 'You input wrong current password' try: # Get from model, don't get from cache user = User.objects.get(email=email) except Exception as e: user = None if not user or not user.check_password(password): user = None if user: user.set_password(new_password) user.save() attrs['user'] = user return attrs else: if detail: raise exceptions.NotAuthenticated(detail=detail) else: raise exceptions.NotAuthenticated()
def authenticate(self, request): """ 对客户端提供的token信息进行验证 :param request: :return: HTTP Response """ token = request.headers.get("token") if token is not None: """ 验证 token """ token_obj = Token.objects.filter(token=token).first() if not token_obj: """ 未查询到token信息 """ raise exceptions.NotAuthenticated('用户认证失败') if token_obj.expire_time.strftime('%Y-%m-%d %H:%M:%S') < \ datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'): """ token信息过期""" raise exceptions.NotAuthenticated('token过期') else: """ 验证用户名密码 """ user = request.headers.get("username") pwd = request.headers.get("password") obj = User.objects.filter(username=user, is_delete=0).first() if not obj: """ 未能查询到用户信息,则返回给客户端响应的提示信息 """ raise exceptions.NotAuthenticated('未查询到用户信息!') else: password = User.objects.filter( username=user, is_delete=0).values("password")[0]["password"] res = check_password(pwd, password) if not res: raise exceptions.NotAuthenticated('密码错误!') return
def authenticate(self, request): client = cas.get_client() # Returns a CAS server client try: auth_header_field = request.META["HTTP_AUTHORIZATION"] auth_token = cas.parse_auth_header(auth_header_field) except (cas.CasTokenError, KeyError): return None # If no token in header, then this method is not applicable # Found a token; query CAS for the associated user id try: cas_auth_response = client.profile(auth_token) except cas.CasHTTPError: raise exceptions.NotAuthenticated( _('User provided an invalid OAuth2 access token')) if cas_auth_response.authenticated is False: raise exceptions.NotAuthenticated( _('CAS server failed to authenticate this token')) user_id = cas_auth_response.user user = User.load(user_id) if user is None: raise exceptions.AuthenticationFailed( _('Could not find the user associated with this token')) check_user(user) return user, cas_auth_response
def permission_denied(self, request, message=None): if request.authenticators: if request.user is None: raise exceptions.NotAuthenticated(detail='请输入正确的用户名密码') elif request.user.user_type == 1: raise exceptions.NotAuthenticated(detail='您不是管理员,无法访问') raise exceptions.NotAuthenticated(detail='用户名或密码错误') raise exceptions.PermissionDenied(detail=message)
def validate(self, attrs): try: user = JWT.get_user_from_jwt(attrs['token']) if user is not None: return {'user_id': user.uid} else: raise exceptions.NotAuthenticated('The token was invalid') except: raise exceptions.NotAuthenticated('The token was invalid')
def get_user(decoded_token): if decoded_token[api_settings.USER_ID_CLAIM] is None: raise exceptions.NotAuthenticated() user_id = decoded_token[api_settings.USER_ID_CLAIM] try: return User.objects.get(id=user_id) except User.DoesNotExist: raise exceptions.NotAuthenticated()
def clear_user_info(self, request): user_id = request.query_params.get('id') validate = request.query_params.get('cmd') if not validate == 'clear': raise exceptions.NotAuthenticated('去死吧 !') if not User.objects.filter(id=user_id).exists(): raise exceptions.NotAuthenticated('搞错了 !') from . import tools tools.clear_user_info(user_id) return Response('o_jb_k !')
def authenticate(self, request): token = request.META.get('HTTP_SSCLIENTTOKEN') cacheService = CacheService() if not token: raise exceptions.NotAuthenticated(SSException.AUTH_FAILED) try: client = cacheService.getClientByToken(token) return (client, None) except Client.DoesNotExist: raise exceptions.NotAuthenticated(SSException.AUTH_FAILED)
def info(self, request, pk=None): auth = TokenAuthentication() if not auth.authenticate(request): raise exceptions.NotAuthenticated({'auth_token': "Auth error."}) current_customer = request.user if not current_customer.is_authenticated: raise exceptions.NotAuthenticated("Please provide auth token.") return Response(CustomerSerializer(current_customer).data, status=status.HTTP_200_OK)
def update(self, instance, validated_data): username = instance.username new_username = validated_data.pop('username', None) new_email = validated_data.pop('email', None) profile = validated_data.pop('profile', {}) password = validated_data.pop('password', None) new_password = validated_data.pop('new_password', None) confirm_new_password = validated_data.pop('confirm_new_password', None) for attr, value in validated_data.items(): setattr(instance, attr, value) if new_username and password is not None: user = authenticate(username=username, password=password) if user is None: raise exceptions.NotAuthenticated( 'Your password is incorrect.') instance.username = new_username instance.generate_token_identifier() if new_email and password is not None: user = authenticate(username=username, password=password) if user is None: raise exceptions.NotAuthenticated( 'Your password is incorrect.') instance.email = new_email instance.primary_email.set_unverified() if password and new_password and confirm_new_password is not None: user = authenticate(username=username, password=password) if user is None: raise exceptions.NotAuthenticated( 'Your old password is incorrect.') instance.set_password(confirm_new_password) instance.generate_token_identifier() send_password_changed_email(user) instance.save() for attr, value in profile.items(): setattr(instance.profile, attr, value) instance.profile.save() return instance
def get(self, request, *args, **kwargs): if getattr(request.user, 'is_anonymous') and getattr( request, 'auth') is not None: raise exceptions.NotAuthenticated(detail='User not logged') else: token = request.auth try: AuthToken.objects.get(key=token.key) except Exception as e: raise exceptions.NotAuthenticated(detail=e) else: token.delete() return Response({'message': 'Logout successfully'})
def authenticate(self, request): uuid = request.META.get('HTTP_SSMERCHANTTOKEN') cacheService = CacheService() if not uuid: raise exceptions.NotAuthenticated(SSException.AUTH_FAILED) try: merchant = cacheService.getMerchantByUuid(uuid) if merchant.installed == 1: return (merchant, None) else: raise exceptions.NotAuthenticated(SSException.AUTH_FAILED) except Merchant.DoesNotExist: raise exceptions.NotAuthenticated(SSException.AUTH_FAILED)
def deny_permission(msg, request, own_obj): """ 无法通过权限的返回信息 :param msg: 请求传递的参数-- msg = super().get_parser_context(request) :param request: :param own_obj: 对应的模型类 """ if request.authenticators and not request.successful_authenticator: raise exceptions.NotAuthenticated() try: pk = msg['kwargs'].get('pk') except Exception as e: data = { 'detail': '路径中未包含该条信息的id %s' % e } raise exceptions.PermissionDenied(detail=data) try: obj = own_obj.objects.get(id=pk) owner = obj.owner except own_obj.DoesNotExist: data = { 'detail': '该信息不存在' } raise exceptions.PermissionDenied(detail=data) data = { 'detail': '您目前对该信息无修改权限, 如需修改请联系%s' % owner.email, 'name': owner.email, } raise exceptions.PermissionDenied(detail=data)
def hash(self, request): """ Creates an hash of `version_id` of all accessible assets by the user. Useful to detect changes between each request. :param request: :return: JSON """ user = self.request.user if user.is_anonymous: raise exceptions.NotAuthenticated() else: accessible_assets = get_objects_for_user( user, "view_asset", Asset).filter(asset_type=ASSET_TYPE_SURVEY) \ .order_by("uid") assets_version_ids = [ asset.version_id for asset in accessible_assets if asset.version_id is not None ] # Sort alphabetically assets_version_ids.sort() if len(assets_version_ids) > 0: hash = md5(hashable_str( "".join(assets_version_ids))).hexdigest() else: hash = "" return Response({"hash": hash})
def post(self, request): user = SupportRequest.target_user(request) if user.is_authenticated(): raise exceptions.PermissionDenied( "Another user is already logged in.") serializer = serializers.ClientUserRegistrationSerializer( data=request.data) if not serializer.is_valid(raise_exception=True): logger.error('Error accepting invitation: %s' % serializer.errors['non_field_errors'][0]) return Response({'error': 'invitation not found for this email'}, status=status.HTTP_404_NOT_FOUND) invite = serializer.invite user_params = { 'email': invite.email, 'username': invite.email, 'first_name': invite.first_name, 'middle_name': invite.middle_name, 'last_name': invite.last_name, 'password': serializer.validated_data['password'], } user = User.objects.create_user(**user_params) sa1 = SecurityAnswer( user=user, question=serializer.validated_data['question_one']) sa1.set_answer(serializer.validated_data['question_one_answer']) sa1.save() sa2 = SecurityAnswer( user=user, question=serializer.validated_data['question_two']) sa2.set_answer(serializer.validated_data['question_two_answer']) sa2.save() invite.status = EmailInvite.STATUS_ACCEPTED invite.user = user invite.save() login_params = { 'username': user.email, 'password': serializer.validated_data['password'] } user = authenticate(**login_params) # check if user is authenticated if not user or not user.is_authenticated(): raise exceptions.NotAuthenticated() # Log the user in with a session as well. auth_login(request, user) user_serializer = UserSerializer(instance=user) msg = "Your client %s %s (%s) has accepted your invitation to Betasmartz!" % ( user.first_name, user.last_name, user.email) invite.advisor.user.email_user('Client has accepted your invitation', msg) return Response(user_serializer.data)
def my_flags(self, request: request.Request, **kwargs): if not request.user.is_authenticated: # for mypy raise exceptions.NotAuthenticated() feature_flags = (FeatureFlag.objects.filter( team=self.team, active=True, deleted=False).prefetch_related( Prefetch( "featureflagoverride_set", queryset=FeatureFlagOverride.objects.filter( user=request.user), to_attr="my_overrides", )).order_by("-created_at")) groups = json.loads(request.GET.get("groups", "{}")) flags = [] for feature_flag in feature_flags: my_overrides = feature_flag.my_overrides # type: ignore override = None if len(my_overrides) > 0: override = my_overrides[0] match = feature_flag.matches(request.user.distinct_id, groups) value_for_user_without_override = (match.variant or True) if match else False flags.append({ "feature_flag": FeatureFlagSerializer(feature_flag).data, "value_for_user_without_override": value_for_user_without_override, "override": FeatureFlagOverrideSerializer(override).data if override else None, }) return Response(flags)
def authenticate(self, request, username=None, password=None, **kwargs): data = { "AuthParameters": { "USERNAME": f"{username}", "PASSWORD": f"{password}", }, "AuthFlow": "USER_PASSWORD_AUTH", "ClientId": settings.COGNITO_CLIENT_ID } client = boto3.client('cognito-idp', 'eu-west-1') try: result = client.initiate_auth( ClientId=data['ClientId'], AuthFlow=data['AuthFlow'], AuthParameters=data['AuthParameters']) except (TokenError, client.exceptions.NotAuthorizedException, client.exceptions.UserNotFoundException): raise exceptions.NotAuthenticated() jwt_payload = self._validate_token( result["AuthenticationResult"]["IdToken"]) USER_MODEL = django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) user = USER_MODEL.objects.get_or_create_for_cognito(jwt_payload) return user
def list(self, request, *args, **kwargs): if isinstance(self.request.user, AnonymousUser): raise exceptions.NotAuthenticated(_(u"请先登录!")) try: obj = Resume.objects.filter(user=self.request.user).first() if obj is None: rlt = { "user_uuid": self.request.user.uuid, "first_name": None, "last_name": None, "edu_degree": None, "service_years": None, "tel": None, "email": None, "address": None, "description": None, "work_exp": [], "edu_exp": [], "skills": [], } return Response(rlt) else: serializer = self.get_serializer(obj, many=False) rlt = serializer.data except: return Response(None) return Response(rlt)
def delete(self, request): """ @apiVersion 1.0.0 @api {delete} /auth Logout @apiName Logout @apiGroup VMS_API Account @apiPermission authenticated @apiHeader {number} Type Device type (1: Mobile, 2: Android phone, 3: IOS phone, 4: Window phone, 5: Android tablet, 6: IOS tablet, 7: Mobile web, tablet web, 8: Desktop web) @apiHeader {string} Device Required, Device id, If from browser, please use md5 of useragent. @apiHeader {string} Appid Required @apiHeader {string} Agent Optional @apiHeader {string} Authorization Optional. format: token <token_string> @apiHeaderExample {json} Request Header Authenticated Example: { "Type": 1, "Device": "postman-TEST", "Appid": "1", "Agent": "Samsung A5 2016, Android app, build_number other_info", "Authorization": "token QS7VF3JF29K22U1IY7LAYLNKRW66BNSWF9CH4BND" } @apiSuccess [200] """ if request.user and request.user.is_authenticated(): ApiService.delete_session(token=request.token) return Response(status=status.HTTP_200_OK) else: raise exceptions.NotAuthenticated()
def authenticate(self, request): """ Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`. """ jwt_value = self.get_jwt_value(request) if jwt_value is None: raise exceptions.NotAuthenticated() try: payload = jwt_decode_handler(jwt_value) except jwt.ExpiredSignature: # pragma: no cover msg = 'Signature has expired.' raise exceptions.AuthenticationFailed(msg) except jwt.DecodeError: # pragma: no cover msg = 'Error decoding signature.' raise exceptions.AuthenticationFailed(msg) except jwt.InvalidTokenError: # pragma: no cover raise exceptions.AuthenticationFailed() except Exception as ex: raise exceptions.AuthenticationFailed(ex.message) user = User(**payload) return user, jwt_value
def create(self, request, *args, **kwargs): if self.request.user.is_anonymous(): raise exceptions.NotAuthenticated() itask_data = { 'library': request.POST.get('library') not in ['false', False], # NOTE: 'filename' here comes from 'name' (!) in the POST data 'filename': request.POST.get('name', None), 'destination': request.POST.get('destination', None), } if 'base64Encoded' in request.POST: encoded_str = request.POST['base64Encoded'] encoded_substr = encoded_str[encoded_str.index('base64') + 7:] itask_data['base64Encoded'] = encoded_substr elif 'file' in request.data: encoded_xls = base64.b64encode(request.data['file'].read()) itask_data['base64Encoded'] = encoded_xls if 'filename' not in itask_data: itask_data['filename'] = request.data['file'].name elif 'url' in request.POST: itask_data['single_xls_url'] = request.POST['url'] import_task = ImportTask.objects.create(user=request.user, data=itask_data) # Have Celery run the import in the background import_in_background.delay(import_task_uid=import_task.uid) return Response( { 'uid': import_task.uid, 'url': reverse('importtask-detail', kwargs={'uid': import_task.uid}, request=request), 'status': ImportTask.PROCESSING }, status.HTTP_201_CREATED)
def validate(self, attrs): username = attrs.get('username') password = attrs.get('password') if username and password: user = authenticate(request=self.context.get('request'), username=username, password=password) if not user: raise exceptions.AuthenticationFailed( detail={ "error": self.custom_error['authentication_error'] }) if not user.is_active: raise serializers.ValidationError( {"inactive_user": self.custom_error['inactive_user']}, code=status.HTTP_403_FORBIDDEN) if not hasattr(user, 'writer'): raise serializers.ValidationError({ "invalid_writer_account": _('No writer found associated to this account.') }) else: raise exceptions.NotAuthenticated() attrs['user'] = user return attrs
def dispatch(self, request, *args, **kwargs): try: return super().dispatch(request, *args, **kwargs) except ProgrammingError: if request.user and not request.user.is_authenticated: raise exceptions.NotAuthenticated() raise
def permission_denied(self, request): """ If request is not permitted, determine what kind of exception to raise. """ if not self.request.successful_authenticator: raise exceptions.NotAuthenticated() raise exceptions.PermissionDenied()
def permission_denied(self, request, message=None): """ If request is not permitted, determine what kind of exception to raise. """ if request.authenticators and not request.successful_authenticator: raise exceptions.NotAuthenticated() raise exceptions.PermissionDenied(detail=message)
def match_answer(request, uuid, type): # first, find corresponding match match = Match.objects.filter(uuid=uuid) agree = request.data.get('agree', None) if agree is None: raise exceptions.ValidationError(detail="agree is missing!") if match: match = match.get() else: raise exceptions.NotFound() # check if user is authenticated if type == 'student' and match.student_request.user == request.user: # user is student match.student_agree = agree if not agree: match.delete() else: match.save() return Response({'success': True}) elif type == 'tutor' and match.tutor_request.user == request.user: # user is tutor match.tutor_agree = agree if not agree: match.delete() else: match.save() return Response({'success': True}) else: raise exceptions.NotAuthenticated()