Django LDAP Authorization - python
I configure Django with ldap. the authorization in ldap seems to work. but the group membership does'nt work. The user fall back to the login.
here the settings.py and the Debug
------------------- Config ------------------------------
import ldap
from django_auth_ldap.config import LDAPSearch, GroupOfNamesType, NestedActiveDirectoryGroupType
# Baseline configuration.
AUTH_LDAP_SERVER_URI = "ldap://srv.domain.com"
AUTH_LDAP_BIND_DN = "cn=ldapreader,ou=admins,ou=City,dc=domain,dc=com"
AUTH_LDAP_BIND_PASSWORD = "LdapreadeR"
AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=City,dc=domain,dc=com",
ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)")
AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=xgroups,ou=City,dc=domain,dc=com",
ldap.SCOPE_SUBTREE, "(objectClass=group)"
)
AUTH_LDAP_GROUP_TYPE = NestedActiveDirectoryGroupType()
AUTH_LDAP_USER_FLAGS_BY_GROUP = {
"is_active": "cn=django,ou=xgroups,ou=City,dc=domain,dc=com",
"is_staff": "cn=django_staff,ou=xgroups,ou=City,dc=domain,dc=com",
"is_superuser": "cn=django_admin,ou=xgroups,ou=City,dc=domain,dc=com"
}
AUTH_LDAP_FIND_GROUP_PERMS = True
AUTH_LDAP_PROFILE_FLAGS_BY_GROUP = {
"is_awesome": "cn=awesome,ou=django,ou=groups,dc=example,dc=com",
}
AUTH_LDAP_MIRROR_GROUPS = True
------------------ DEBUG ----------------------------------
search_s('ou=City,dc=domain,dc=com', 2, '(sAMAccountName=%(user)s)') returned 1 objects: cn=Farmer Nic,ou=users,ou=City,dc=domain,dc=com
Populating Django user fn000000
search_s('ou=xgroups,ou=City,dc=domain,dc=com', 2, '(& (objectClass=group)(|(member=cn=Farmer Nic,ou=users,ou=City,dc=domain,dc=com)))') returned 4 objects:
cn=django_admin,ou=xgroups,ou=City,dc=domain,dc=com;
cn=django,ou=xgroups,ou=City,dc=domain,dc=com;
cn=pbspot_op,ou=xgroups,ou=City,dc=domain,dc=com;
cn=xxx_super,ou=xgroups,ou=City,dc=domain,dc=com
search_s('ou=xgroups,ou=City,dc=domain,dc=com', 2, '(&(objectClass=group)(|
(member=cn=django_admin,ou=xgroups,ou=City,dc=domain,dc=com)
(member=cn=django,ou=xgroups,ou=City,dc=domain,dc=com)
(member=cn=pbspot_op,ou=xgroups,ou=City,dc=domain,dc=com)
(member=cn=xxx_super,ou=xgroups,ou=City,dc=domain,dc=com)))')
returned 0 objects:
cn=Farmer Nic,ou=users,ou=City,dc=domain,dc=com is a member of cn=django_admin,ou=xgroups,ou=City,dc=domain,dc=com
cn=Farmer Nic,ou=users,ou=City,dc=domain,dc=com is not a member of cn=django_staff,ou=xgroups,ou=City,dc=domain,dc=com
cn=Farmer Nic,ou=users,ou=City,dc=domain,dc=com is a member of cn=django,ou=xgroups,ou=City,dc=domain,dc=com
Django found, that the user Member of django_admin Group is, but he got not the admin-page.
what is wrong?
Thx
I resolve the problem by myself.
User must be member in cn=django_admin.. and cn=django_staff.. group. Now "Farmer Nick" can login. Ich changed the row "is_staff" to "is_staff": "django_admin..." and all things would be ok.
Related
Django role permissions - available_permissions aren't automatically assigned to Group
I'm trying to use django-role-permissions but it doesn't assign available_permissions to Group nor to User. from rolepermissions.roles import AbstractUserRole class PERMISSIONS: CAN_SEE_ALL_INVOICES = 'can_see_all_invoices' CAN_SEE_OWN_INVOICES = 'can_see_own_invoices' class Admin(AbstractUserRole): verbose_name = 'Admin' available_permissions = { PERMISSIONS.CAN_SEE_ALL_INVOICES:True, } class Broker(AbstractUserRole): verbose_name = 'Maklér' available_permissions = { PERMISSIONS.CAN_SEE_ALL_INVOICES: False, PERMISSIONS.CAN_SEE_OWN_INVOICES: True, } After sync_roles I checked the admin and also tried to programmatically check the permission for the user that has Broker role and they doesn't have the permission. How is that possible?
Odoo API: invoice has "paid" status after validation
I am working on a Python script that will import all my existing invoices to an Odoo 12 instance. I am using odoorpc library to simplify RPC calls to my Odoo instance. I achieved to create an invoice using the API, registering it in "draft" state. Then, I want to "validate" it and update its state into "open". Unfortunately, using the "Validate" button in Odoo UI or calling the action from the RPC API do the same: invoice state is changed to "paid". I don't understand this behavior, since I didn't register any payment (it will be my next goal). Here is a simplified version of my script that can be used to reproduce the issue : import odoorpc import settings """settings module contains various constants used to connect with Odoo on my VPS""" if __name__ == "__main__": odoo = odoorpc.ODOO(settings.ODOO_HOST, port=settings.ODOO_PORT, timeout=10) odoo.login(settings.ODOO_DB, settings.ODOO_USER, settings.ODOO_PASSWORD) Partner = odoo.env["res.partner"] # This partner already exists in DB customer = Partner.browse([22]) Invoice = odoo.env["account.invoice"] invoice_id = Invoice.create({ 'partner_id' : customer.id, 'state': 'draft', # This is ID for "Customers Invoices" journal 'journal_id': 1, 'account_id': customer.property_account_receivable_id.id, # This is ID for default bank account, already registered 'partner_bank_id': 1, 'payment_term_id': odoo.env.ref("account.account_payment_term_net").id, }) InvoiceLine = odoo.env["account.invoice.line"] InvoiceLine.create({ "invoice_id": invoice_id, "name": "A basic product", "quantity": 6, "price_unit": 100.0, # Not sure about this one: "uom_id": 1, # No tax "invoice_line_tax_ids": [], 'journal_id': 1, 'account_id': customer.property_account_receivable_id.id, }) inv = Invoice.browse([invoice_id]) print("Before validating:", inv.state) inv.action_invoice_open() inv = Invoice.browse([invoice_id]) print("After validating:", inv.state) result: Before validating: draft After validating: paid I think there is something missing or wrong in my invoice creation, but I didn't find what exactly should be modified to have an invoice created the same way it would be from the UI. Can anybody help me to find what's wrong in my script ?
I found myself a solution. It seems the account_id must be different for invoice and invoice line. To fix the issue, I retrieved the account.journal instance with ID 1 (for "Customers Invoices" journal), then used it to fill invoice line's account_id based on the journal's default_credit_account_id field: cust_invoices_journal = odoo.env["account.journal"].browse([1]) # [...] invoice_id = Invoice.create({ # [...] 'journal_id': cust_invoices_journal.id, 'account_id': customer.property_account_receivable_id.id, # [...] }) # [...] InvoiceLine.create({ # [...] 'account_id': cust_invoices_journal.default_credit_account_id.id, # [...] })
How to assign group after the ldap parameter?
I would like to assign to group after specific ldap parameter. In Django I have other groups then in ldap. I do something in signals.py, but i want do do the same effect in settings.py, because when I create a new groups i want change something in settings.py I do this in signals.py ant it works global group_name if (gidNumber =='201'): goup_name = 'a ' elif (gidNumber == '202'): user.is_staff = True group_name = 'b' else: group_name = 'c' if(user.groups.filter(name=group_name).exists()!= True ): group = Group.objects.get(name=group_name) user.groups.add(gruop) but i would ilke do this like smoething like this what i try do this in my settings.py AUTH_LDAP_USER_FLAGS_BY_GROUP = { "groups.filter(name='a')": "gidNumber=201,uid=%(user)s,ou=People,dc=yy,dc=xx ", }
The simplest answer is to do own dictionary in settings.py LDAP_DICTIONARY = { '201':'a', '202':'b', '203':'c' } AUTH_LDAP_USER_ATTR_MAP = { 'first_name' : 'gecos', 'last_name' : 'gidNumber', } and in signals.py assign property, but I have only first_name and last_name paremeters, so I gidNumber assign to last_name and clean this paremeter gidNumber = user.last_name user.last_name=' ' group_name =LDAP_DICTIONARY[gidNumber] group = Group.objects.get(name=group_name) user.groups.add(group)
Powershell confirm folder existence and sending an email if it does not
I am trying to search a SQL database to confirm if a directory exists. If the directory does not exist the script should send off an email for notification. I have attempted to create something but I am not well versed in PowerShell. I am able to get all of the data from our SQL server. I am running into an error with $($Row.[Last Name]). It states that it is unable to find [Last Name] type, but it finds Account and IsActive just fine. Unable to find type [Last Name]: make sure that the assembly containing this type is loaded. At \cottonwood\users\CB\My Documents\SQLserver-search.ps1:44 char:17 + $Row.[Last Name] <<<< + CategoryInfo : InvalidOperation: (Last Name:String) [], RuntimeException + FullyQualifiedErrorId : TypeNotFound I'm not sure if my question is clear or not. I'm new to Stack Overflow. Any help would be greatly appreciated. Thanks in advance. Param ( $Path = "\\cottonwood\users\Shared\Pool Acquisitions", $SMTPServer = "generic-mailserver", $From = "generic-outbound-email", #The below commented out line is used to test with just one individual. Be sure to comment out the one with all individuals before troubleshooting. #$To = #("generic-email"), $port = "587", $To = #("generic-inbound-email"), $Subject = "Folders Added in", $logname = "\\cottonwood\users\Shared\Loan Documents - Active\logs\New Folders$date.txt", $date = (Get-Date -Format MMddyyyy), $SMTPBody = "`nThe following Pool Acquisitions folders have been added in the last 24 hours:`n`n" ) $SQLServer = "REDWOOD" #use Server\Instance for named SQL instances! $SQLDBName = "MARS" $SqlQuery = "select Account, IsActive, [Last Name] FROM vw_loans WHERE LEFT(Account,1)<>'_' ORDER BY Account" $SqlConnection = New-Object System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True" $SqlCmd = New-Object System.Data.SqlClient.SqlCommand $SqlCmd.CommandText = $SqlQuery $SqlCmd.Connection = $SqlConnection $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $SqlAdapter.SelectCommand = $SqlCmd $DataSet = New-Object System.Data.DataSet $SqlAdapter.Fill($DataSet) $SqlConnection.Close() clear $DataSet.Tables[0] foreach ($Row in $dataset.Tables[0].Rows) { write-Output "$($Row)" write-Output "$($Row.Account)" write-Output "$($Row.IsActive)" write-Output "$($Row.[Last Name])" } if($Row.IsActive -eq $True){ $ChkPath = "U:\Shared\Loan Documents - Active\$Row.Account - $Row.[Last Name]" } else{ $ChkPath = "U:\Shared\Loan Documents - Inactive\$Row.Account - $Row.[Last Name]" } $FileExist = Test-Path $ChkPath $SMTPMessage = #{ To = $To From = $From Subject = "$Subject $Path" Smtpserver = $SMTPServer Port = $port } If($FileExist -eq $True) {Write-Host "Null Response"} else { $SMTPBody = "Loan folder is missing. Please advise." $LastWrite | ForEach { $SMTPBody += "$($_.FullName)`n" } UseSSL = $true }
if($Activity = 'y') should be if($Activity -eq 'y') In PowerShell = always sets a value so this statement is always true. I'm also pretty sure param blocks have to be at the top of a script.
Graphene/Django (GraphQL): How to use a query argument in order to exclude nodes matching a specific filter?
I have some video items in a Django/Graphene backend setup. Each video item is linked to one owner. In a React app, I would like to query via GraphQL all the videos owned by the current user on the one hand and all the videos NOT owned by the current user on the other hand. I could run the following GraphQl query and filter on the client side: query AllScenes { allScenes { edges { node { id, name, owner { name } } } } } I would rather have two queries with filters parameters directly asking relevant data to my backend. Something like: query AllScenes($ownerName : String!, $exclude: Boolean!) { allScenes(owner__name: $ownerName, exclude: $exclude) { edges { node { id, name, owner { name } } } } } I would query with ownerName = currentUserName and exclude = True/False yet I just cannot retrieve my exclude argument on my backend side. Here is the code I have tried in my schema.py file: from project.scene_manager.models import Scene from graphene import ObjectType, relay, Int, String, Field, Boolean, Float from graphene.contrib.django.filter import DjangoFilterConnectionField from graphene.contrib.django.types import DjangoNode from django_filters import FilterSet, CharFilter class SceneNode(DjangoNode): class Meta: model = Scene class SceneFilter(FilterSet): owner__name = CharFilter(lookup_type='exact', exclude=exclude) class Meta: model = Scene fields = ['owner__name'] class Query(ObjectType): scene = relay.NodeField(SceneNode) all_scenes = DjangoFilterConnectionField(SceneNode, filterset_class=SceneFilter, exclude=Boolean()) def resolve_exclude(self, args, info): exclude = args.get('exclude') return exclude class Meta: abstract = True My custom SceneFilter is used but I do not know how to pass the exclude arg to it. (I do not think that I am making a proper use of the resolver). Any help on that matter would be much appreciated!
Switching to graphene-django 1.0, I have been able to do what I wanted with the following query definition: class Query(AbstractType): selected_scenes = DjangoFilterConnectionField(SceneNode, exclude=Boolean()) def resolve_selected_scenes(self, args, context, info): owner__name = args.get('owner__name') exclude = args.get('exclude') if exclude: selected_scenes = Scene.objects.exclude(owner__name=owner__name) else: selected_scenes = Scene.objects.filter(owner__name=owner__name) return selected_scenes BossGrand proposed an other solution on GitHub