def handle(self, *args, **options): force_exec = options.get('force_exec') target_address = options.get('target_address') client_id = None client_secret = None if check_ogc_backend(geoserver.BACKEND_PACKAGE): from geonode.geoserver.helpers import ogc_server_settings redirect_uris = f'{ogc_server_settings.LOCATION}\n{ogc_server_settings.public_url}\n{target_address}/geoserver/' # noqa if Application.objects.filter(name='GeoServer').exists(): Application.objects.filter(name='GeoServer').update(redirect_uris=redirect_uris) if force_exec: Application.objects.filter(name='GeoServer').update( client_id=generate_client_id(), client_secret=generate_client_secret() ) app = Application.objects.filter(name='GeoServer')[0] client_id = app.client_id client_secret = app.client_secret else: client_id = generate_client_id() client_secret = generate_client_secret() Application.objects.create( skip_authorization=True, redirect_uris=redirect_uris, name='GeoServer', authorization_grant_type='authorization-code', client_type='confidential', client_id=client_id, client_secret=client_secret, user=get_user_model().objects.filter(is_superuser=True)[0] ) return f'{client_id},{client_secret}'
def handle(self, *args, **options): from django.conf import settings client_id = None client_secret = None if 'geonode.geoserver' in settings.INSTALLED_APPS: from geonode.geoserver.helpers import ogc_server_settings if Application.objects.filter(name='GeoServer').exists(): Application.objects.filter(name='GeoServer').update( redirect_uris=ogc_server_settings.public_url) app = Application.objects.filter(name='GeoServer')[0] client_id = app.client_id client_secret = app.client_secret else: client_id = generate_client_id() client_secret = generate_client_secret() Application.objects.create( skip_authorization=True, redirect_uris=ogc_server_settings.public_url, name='GeoServer', authorization_grant_type='authorization-code', client_type='confidential', client_id=client_id, client_secret=client_secret, user=Profile.objects.filter(is_superuser=True)[0]) return '%s,%s' % (client_id, client_secret)
def handle(self, *args, **options): from django.conf import settings client_id = None client_secret = None if check_ogc_backend(geoserver.BACKEND_PACKAGE): from geonode.geoserver.helpers import ogc_server_settings redirect_uris = '%s\n%s' % (ogc_server_settings.LOCATION, ogc_server_settings.public_url) if Application.objects.filter(name='GeoServer').exists(): Application.objects.filter(name='GeoServer').update(redirect_uris=redirect_uris) app = Application.objects.filter(name='GeoServer')[0] client_id = app.client_id client_secret = app.client_secret else: client_id = generate_client_id() client_secret = generate_client_secret() Application.objects.create( skip_authorization=True, redirect_uris=redirect_uris, name='GeoServer', authorization_grant_type='authorization-code', client_type='confidential', client_id=client_id, client_secret=client_secret, user=Profile.objects.filter(is_superuser=True)[0] ) return '%s,%s' % (client_id, client_secret)
def handle(self, application): application.client_secret = generate_client_secret() if application.livemode: application.client_secret = "sk_live_" + application.client_secret else: application.client_secret = "sk_test_" + application.client_secret application.save()
def update(request, user_app_id): """Update record""" data = request.DATA user = helpers.get_user(request) data = helpers.set_null_values_if_not_exist(data, get_fields()) try: item = get_application_model().objects.get(pk=user_app_id) except get_application_model().DoesNotExist: return {'code': 'user_app/not_found', 'values': [user_app_id]}, 404, False data['client_type'] = AbstractApplication.CLIENT_CONFIDENTIAL data['authorization_grant_type'] = AbstractApplication.GRANT_PASSWORD data['skip_authorization'] = True data['client_id'] = generate_client_id() data['client_secret'] = generate_client_secret() helpers.json_to_objects(item, data) item.user = user item.save() return {'code': 'ok', 'data': helpers.objects_to_json(request, [item])}, 200, item
def update(self, instance, validated_data): client_secret = instance.client_secret had_oidc_enabled = instance.algorithm == "RS256" will_enable_oidc = (not had_oidc_enabled and validated_data.get("scopes") and "openid" in validated_data.get("scopes")) algorithm = "RS256" if had_oidc_enabled or will_enable_oidc else "" redirect_uris = validated_data.get("redirect_uris") print("Redirect uris: ", redirect_uris) if (validated_data.get("client_type") == "confidential" and not instance.client_secret): client_secret = generate_client_secret() elif validated_data.get( "client_type") == "public" and instance.client_secret: client_secret = "" data = { **validated_data, "client_secret": client_secret, "algorithm": algorithm, } for key, value in data.items(): setattr(instance, key, value) instance.save() return instance
def post(self, request, *args, **kwargs): self.object = self.get_object() messages.success( request, _('A new client secret has been generated and is now effective.')) self.object.client_secret = generate_client_secret() self.object.save() return HttpResponseRedirect(self.object.get_absolute_url())
def post(self, request, format=None): # Store the registration information the developer gave us. serialized = OAuth2RegistrationSerializer(data=request.data) if not serialized.is_valid(): return Response(status=400, data=serialized.errors) else: serialized.save() # Produce a client ID, client secret, and authorize the application in # the OAuth2 backend. client_secret = generate_client_secret() new_application = ThrottledApplication( name=serialized.validated_data["name"], skip_authorization=False, client_type="Confidential", authorization_grant_type="client-credentials", verified=False, client_secret=client_secret, ) new_application.save() # Send a verification email. verification = OAuth2Verification( email=serialized.validated_data["email"], code=secrets.token_urlsafe(64), associated_application=new_application, ) verification.save() token = verification.code link = request.build_absolute_uri(reverse("verify-email", [token])) verification_msg = f""" To verify your Openverse API credentials, click on the following link: {link} If you believe you received this message in error, please disregard it. """ try: send_mail( subject="Verify your API credentials", message=verification_msg, from_email=settings.EMAIL_SENDER, recipient_list=[verification.email], fail_silently=False, ) except smtplib.SMTPException as e: log.error("Failed to send API verification email!") log.error(e) # Give the user their newly created credentials. return Response( status=201, data={ "client_id": new_application.client_id, "client_secret": client_secret, "name": new_application.name, "msg": "Check your email for a verification link.", }, )
def update(self, instance, validated_data): instance.redirect_uris = validated_data.get('redirect_uris', instance.redirect_uris) instance.name = validated_data.get('name', instance.name) instance.web_hook = validated_data.get('web_hook', instance.web_hook) if validated_data.get('reset_credentials', False) is True: instance.client_id = generate_client_id() instance.client_secret = generate_client_secret() instance.save() return instance
def handle(self, *args, **options): new_application = Application( user=User.objects.filter(is_superuser=True)[0], client_type="confidential", authorization_grant_type="password", name=options["name"] or "socialauth_application", client_id=options["client_id"] or generate_client_id(), client_secret=options["client_secret"] or generate_client_secret(), ) new_application.save()
def create(self, validated_data): client_secret = "" if validated_data.get("client_type") == "confidential": client_secret = generate_client_secret() data = { **validated_data, "client_secret": client_secret, } client = get_application_model().objects.create(**data) client.save() return client
def add_application(username, application_name): user = User.objects.get(username=username) if not user: return application = MyApplication(name=application_name, client_id=generate_client_id(), client_secret=generate_client_secret(), client_type="confidential", authorization_grant_type="password", user=user) application.save()
def get_form(self, form_class=None): form = super(ApiRequestStatusView, self).get_form(form_class) # Copy the data, since it's an immutable QueryDict. copied_data = form.data.copy() # Now set the fields that were removed earlier. We give them # confidential client credentials, and generate their client # ID and secret. copied_data.update({ 'authorization_grant_type': Application.GRANT_CLIENT_CREDENTIALS, 'client_type': Application.CLIENT_CONFIDENTIAL, 'client_secret': generate_client_secret(), 'client_id': generate_client_id(), }) form.data = copied_data return form
def Application_Update_Secret(request, pk): """ Replace client_id and client_secret :param request: :param pk: :return: """ if request.method == 'POST': a = BBApplication.objects.get(pk=pk) form = Application_Secret(request.POST) if form.is_valid(): if form.cleaned_data['confirm'] == '1': a.client_id = generate_client_id() a.client_secret = generate_client_secret() a.save() messages.success(request, "Client Id and Secret updated") if settings.DEBUG: print("Confirm:", form.cleaned_data['confirm']) print("Id:", a.client_id) print("Secret:", a.client_secret) return HttpResponseRedirect( reverse_lazy('appmgmt:manage_applications')) else: if settings.DEBUG: print("form has a problem") else: a = BBApplication.objects.get(pk=pk) if settings.DEBUG: print("BBApplication:", a) form = Application_Secret(initial={'confirm': '0'}) return render_to_response( 'appmgmt/application_secret_form.html', RequestContext(request, { 'form': form, 'application': a, }))
def create_sentry_application(sentry_instance): if not sentry_instance: return name = sentry_instance["InstanceName"] client_id = generators.generate_client_id() client_secret = generators.generate_client_secret() authorization_grant_type = Application.GRANT_AUTHORIZATION_CODE client_type = Application.CLIENT_PUBLIC redirect_url = "http://%s/oauth/consumer/exchange/" % (sentry_instance["sentry_ipaddress"],) if not MyApplication.objects.filter(name=name): MyApplication.objects.create( name=name, client_id=client_id, client_secret=client_secret, authorization_grant_type=authorization_grant_type, client_type=client_type, redirect_uris=redirect_url, user_id=1, ) return client_id, client_secret
def handle(self, *args, **options): name = ''.join( random.choices(string.ascii_uppercase + string.digits, k=8)) client_id = generate_client_id() client_secret = generate_client_secret() client_type = 'public' authorization_grant_type = 'password' redirect_uris = '' skip_authorization = False # Save application application = get_application_model().objects.create( name=name, client_id=client_id, client_secret=client_secret, client_type=client_type, authorization_grant_type=authorization_grant_type, redirect_uris=redirect_uris, skip_authorization=skip_authorization) # Print application data print(json.dumps(model_to_dict(application), indent=4))
def Application_Update_Secret(request, pk): """ Replace client_id and client_secret :param request: :param pk: :return: """ if request.method == "POST": a = BBApplication.objects.get(pk=pk) form = Application_Secret(request.POST) if form.is_valid(): if form.cleaned_data["confirm"] == "1": a.client_id = generate_client_id() a.client_secret = generate_client_secret() a.save() messages.success(request, "Client Id and Secret updated") if settings.DEBUG: print("Confirm:", form.cleaned_data["confirm"]) print("Id:", a.client_id) print("Secret:", a.client_secret) return HttpResponseRedirect(reverse_lazy("appmgmt:application_view")) else: if settings.DEBUG: print("form has a problem") else: a = BBApplication.objects.get(pk=pk) if settings.DEBUG: print("BBApplication:", a) form = Application_Secret(initial={"confirm": "0"}) return render_to_response( "appmgmt/application_secret_form.html", RequestContext(request, {"form": form, "application": a}) )
def save(self, commit=True): """Save the form. This method will generate the ``client_id`` and ``client_secret`` fields. Args: commit (bool, optional): Whether or not the Application should be saved to the database. Returns: reviewboard.oauth.models.Application: The created Application. """ instance = super(ApplicationCreationForm, self).save(commit=False) instance.client_id = generate_client_id() instance.client_secret = generate_client_secret() if commit: instance.save() return instance
def Application_Update_Secret(request, pk): """ Replace client_id and client_secret :param request: :param pk: :return: """ if request.method == 'POST': a=BBApplication.objects.get(pk=pk) form = Application_Secret(request.POST) if form.is_valid(): if form.cleaned_data['confirm'] == '1': a.client_id = generate_client_id() a.client_secret = generate_client_secret() a.save() messages.success(request,"Client Id and Secret updated") if settings.DEBUG: print("Confirm:", form.cleaned_data['confirm']) print("Id:", a.client_id) print("Secret:", a.client_secret) return HttpResponseRedirect(reverse_lazy('appmgmt:manage_applications')) else: if settings.DEBUG: print("form has a problem") else: a=BBApplication.objects.get(pk=pk) if settings.DEBUG: print("BBApplication:", a) form = Application_Secret(initial={'confirm': '0'}) return render_to_response('appmgmt/application_secret_form.html', RequestContext(request,{'form': form, 'application': a,}))
def create(request): data = request.DATA user = helpers.get_user(request) data = helpers.set_null_values_if_not_exist(data, get_fields()) data['client_type'] = AbstractApplication.CLIENT_CONFIDENTIAL data['authorization_grant_type'] = AbstractApplication.GRANT_PASSWORD data['skip_authorization'] = True data['client_id'] = generate_client_id() data['client_secret'] = generate_client_secret() item, created = get_application_model().objects.get_or_create(client_id=data['client_id'], user=user, redirect_uris=data['redirect_uris'], client_type=data['client_type'], authorization_grant_type=data[ 'authorization_grant_type'], client_secret=data['client_secret'], name=data['name'], skip_authorization=data['skip_authorization']) return {'code': 'ok', 'data': helpers.objects_to_json(request, [item])}, 200, item
def post(self, request, **kwargs): app = get_object_or_404(self.get_queryset(), pk=kwargs["pk"]) app.client_secret = generate_client_secret() app.save() return redirect(app)
def create(self, validated_data): validated_data["client_id"] = generate_client_id() validated_data["client_secret"] = generate_client_secret() return SBApplication.objects.create(**validated_data)
def post(self, request, *args, **kwargs): self.object = self.get_object() messages.success(request, _('A new client secret has been generated and is now effective.')) self.object.client_secret = generate_client_secret() self.object.save() return HttpResponseRedirect(self.object.get_absolute_url())
def test_generate_secret_id(self): g = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS() self.assertEqual(len(g.hash()), 128) oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS = MockHashGenerator self.assertEqual(generate_client_secret(), 42)
def _create_or_update(self, request, parsed_request_fields, extra_fields, instance, local_site, regenerate_secret=False): """Create or update an application. Args: request (django.http.HttpRequest): The current HTTP request. parsed_request_fields (dict): The parsed request fields. extra_fields (dict): Extra data fields. instance (reviewboard.oauth.models.Application): The current application to update or ``None`` if we are creating a new application. local_site (reviewboard.site.models.LocalSite): The LocalSite the API is being accessed through. regenerate_secret (bool, optional): Whether or not the secret on the Returns: tuple: A 2-tuple of: * The HTTP status (:py:class:`int` or :py:class:`djblets.webapi.error.WebAPIError`). * The response body to encode (:py:class:`dict`). """ try: username = parsed_request_fields.pop('user') except KeyError: username = None skip_authorization = parsed_request_fields.get('skip_authorization', False) change_owner = (username is not None and username != request.user.username) errors = defaultdict(list) user_pk = None if skip_authorization or change_owner: # These fields are only available to administrators. We must check # for adequate permissions. if not (request.user.is_authenticated() and (request.user.is_superuser or (request.local_site is not None and request.local_site.is_mutable_by(request.user)))): # The user does not have adequate permission to modify these # fields. We will return an error message for each field they # attempted to modify. err_msg = 'You do not have permission to set this field.' if skip_authorization: errors['skip_authorization'].append(err_msg) if change_owner: errors['user'].append(err_msg) elif change_owner: try: if request.local_site: qs = local_site.users else: qs = User.objects user_pk = (qs.values_list( 'pk', flat=True).get(username=username)) except User.DoesNotExist: errors['user'].append('The user "%s" does not exist.' % username) if errors: return INVALID_FORM_DATA, { 'fields': errors, } form_data = parsed_request_fields.copy() # When creating the application, if a user is not provided, set it to # the user making the request. # # Do not update the user field during an update when it is not # explicitly provided. if user_pk is None and instance is None: assert not change_owner user_pk = request.user.pk if user_pk is not None: form_data['user'] = user_pk if not instance: form_data.setdefault('enabled', True) if local_site: form_data['local_site'] = local_site.pk elif regenerate_secret: # We are setting these directly on the instance because the form # does not support updating the client_secret field. instance.client_secret = generate_client_secret() # Setting instance.original_user to be blank will make # instance.is_disabled_for_security False so that the form will # validate. instance.original_user = None form = self.create_form(form_data, request, instance) if form.is_valid(): if instance is None: status_code = 201 else: status_code = 200 instance = self.save_form(form, extra_fields) return status_code, { self.item_result_key: instance, } else: return INVALID_FORM_DATA, {'fields': self._get_form_errors(form)}
def _create_or_update(self, request, parsed_request_fields, extra_fields, instance, local_site, regenerate_secret=False): """Create or update an application. Args: request (django.http.HttpRequest): The current HTTP request. parsed_request_fields (dict): The parsed request fields. extra_fields (dict): Extra data fields. instance (reviewboard.oauth.models.Application): The current application to update or ``None`` if we are creating a new application. local_site (reviewboard.site.models.LocalSite): The LocalSite the API is being accessed through. regenerate_secret (bool, optional): Whether or not the secret on the Returns: tuple: A 2-tuple of: * The HTTP status (:py:class:`int` or :py:class:`djblets.webapi.error.WebAPIError`). * The response body to encode (:py:class:`dict`). """ try: username = parsed_request_fields.pop('user') except KeyError: username = None skip_authorization = parsed_request_fields.get('skip_authorization', False) change_owner = (username is not None and username != request.user.username) errors = defaultdict(list) user_pk = None if skip_authorization or change_owner: # These fields are only available to administrators. We must check # for adequate permissions. if not (request.user.is_authenticated() and (request.user.is_superuser or (request.local_site is not None and request.local_site.is_mutable_by(request.user)))): # The user does not have adequate permission to modify these # fields. We will return an error message for each field they # attempted to modify. err_msg = 'You do not have permission to set this field.' if skip_authorization: errors['skip_authorization'].append(err_msg) if change_owner: errors['user'].append(err_msg) elif change_owner: try: if request.local_site: qs = local_site.users else: qs = User.objects user_pk = ( qs .values_list('pk', flat=True) .get(username=username) ) except User.DoesNotExist: errors['user'].append('The user "%s" does not exist.' % username) if errors: return INVALID_FORM_DATA, { 'fields': errors, } form_data = parsed_request_fields.copy() # When creating the application, if a user is not provided, set it to # the user making the request. # # Do not update the user field during an update when it is not # explicitly provided. if user_pk is None and instance is None: assert not change_owner user_pk = request.user.pk if user_pk is not None: form_data['user'] = user_pk if not instance: form_data.setdefault('enabled', True) if local_site: form_data['local_site'] = local_site.pk elif regenerate_secret: # We are setting these directly on the instance because the form # does not support updating the client_secret field. instance.client_secret = generate_client_secret() # Setting instance.original_user to be blank will make # instance.is_disabled_for_security False so that the form will # validate. instance.original_user = None form = self.create_form(form_data, request, instance) if form.is_valid(): if instance is None: status_code = 201 else: status_code = 200 try: instance = self.save_form(form, extra_fields) except ImportExtraDataError as e: return e.error_payload return status_code, { self.item_result_key: instance, } else: return INVALID_FORM_DATA, { 'fields': self._get_form_errors(form) }