Make already existing Django-user model case-insensitve - django-models

So right now I have
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('E-mail'), unique=True)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
wants_email = models.BooleanField(_("Send mig emails"),default=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __str__(self):
return self.email
which works great by using email as login. The issue is that the e-mail is case sensitive i.e myuser#app.com is can not login as MyUser#app.com.
I have seen several ways of creating case insensitive username in models (some suggest just cast the user-name to lower when entered where some suggest its a bad idea), but I don't know if I can do that now, since I have users in my database with like MyUser#app.com.

Related

Either paramter #objname is ambiguos or the claimed #objtype is wrong

I am trying to switch from the default Django user model to a custom user model. when I try to migrate the changes I get the error:
Either the parameter #objname is ambiguous or the claimed #objtype (COLUMN) is wrong.
I am using driver 13 from pyodbc. The migration works if I fake it, but throws the above error when I try to actually run the migration.
class OUser(AbstractBaseUser):
"""
Our custom user model which may be extended later.
"""
email = models.EmailField(verbose_name='email address', max_length=255, unique=True)
username = models.CharField(max_length=150, unique=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False) # a superuser
first_name = models.CharField(max_length=100, blank=True, default='')
last_name = models.CharField(max_length=100, blank=True, default='')
date_joined = models.DateField(auto_now=True)
password = models.CharField(max_length=100)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = [] # Email & Password are required by default.
def __str__(self):
return self.username
#property
def is_staff(self):
"""Is the user a member of staff?"""
return self.is_staff
#property
def is_admin(self):
return self.is_superuser
#property
def is_active(self):
return self.is_active
objects = UserManager()
I have no Idea what this error could be from. Does anybody have any idea?

LINQ retrieve statement didn't return latest updated result

I have a table called Organization and a table called Staff.
Inside the Staff table I've got 2 fields which are
StaffStatus to indicate whether he/she is available for the organization and
ParentStatus to inidicate whether the organization of the user is still available or not (I didn't link them due to several reasons).
I allow the owner to recover the staff (update the StaffStatus to "Available") if the ParentStatus of the staff is "Available".
There was a weird situation in my system. I first remove the staff (update StaffStatus to "Unavailable"), then I remove the organization (update staff.ParentStatus to "Unavailable"). In this condition, the owner is not allowed to recover the user. However, the ParentStatus I retrieve is "Available" (so it's still allow to recover the user), but in the database the ParentStatus is already changed to "Unavailable".
The code I used to removeUser:
Friend Sub removeUser(strInput As String)
Try
objUser = (From userDB In db.Staffs Where userDB.UserID = strInput).FirstOrDefault()
objUser.UserStatus = "Unavailable"
db.SubmitChanges(ConflictMode.ContinueOnConflict)
Catch ex As Exception
For Each occ As ObjectChangeConflict In db.ChangeConflicts
occ.Resolve(RefreshMode.KeepChanges)
Next
db.SubmitChanges()
End Try
End Sub
The code I used to removeOrganization:
Friend Sub removeOrganization(strInput As String)
Try
objOrganization = (From organizationDB In db.Organizations
Where organizationDB.OrganizationID = strInput).FirstOrDefault()
objOrganization.OrganizationStatus = "Unavailable"
Dim objCompany = From companyDB In db.Companies
Where companyDB.OrganizationID = strInput
For Each mem In objCompany
mem.ParentStatus = "Unavailable"
Dim objDepartment = From DepartmentDB In db.Departments
Where DepartmentDB.CompanyID = mem.CompanyID
For Each record In objDepartment
record.ParentStatus = "Unavailable"
Next
Next
Dim objUser = From UserDB In db.Staffs
Where UserDB.OrganizationID = strInput
For Each mem In objUser
mem.ParentStatus = "Unavailable"
Next
db.SubmitChanges(ConflictMode.ContinueOnConflict)
Catch ex As Exception
For Each occ As ObjectChangeConflict In db.ChangeConflicts
occ.Resolve(RefreshMode.KeepChanges)
Next
db.SubmitChanges()
End Try
End Sub
How I called the recoverUser (I used a MsgBox() to test the ParentStatus I retrieve):
Private Sub btnViewUserRecover_Click(sender As Object, e As EventArgs) Handles btnViewUserRecover.Click
MsgBox(helperUserCKJ.getUserByID(strUserID).ParentStatus)
If dgvUser.RowCount > 0 Then
strUserID = dgvUser.SelectedRows.Item(0).Cells(0).Value
If (helperUserCKJ.getUserByID(strUserID).ParentStatus.Equals("Unavailable")) Then
MessageBox.Show("The Organization or Company or Department of the User is unavailable now." & vbNewLine & "You need to recover the Organization or Company or Department of the User first before you can recover the User.", "User Recovery Error", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
Dim respond = MessageBox.Show("Are you sure want to recover the user?", "User Recovery Comfirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If respond = DialogResult.Yes Then
helperUserCKJ.recoverUser(strUserID)
End If
End If
End If
End Sub
The query I used to retrieve user:
Friend Function getUserByID(strInput As String) As Staff
getUserByID = (From userDB In db.Staffs
Where userDB.UserID = strInput).FirstOrDefault()
End Function
I can verify that the ParentStatus field in the database is already changed.
If I didn't remove the user and directly remove the organization only, then it become normal(disallow to recover user). If I remove the user and then remove the organization, when I click to recover the user, the parentStatus is "Available".
It's a weird situation. I'm using LINQ, vb.net and Microsoft Azure database.
So I find the solution to refresh my database with the current value.
Friend Function getUserByID(strInput As String) As Staff
objUser = (From userDB In db.Staffs
Where userDB.UserID = strInput).FirstOrDefault()
db.Refresh(RefreshMode.OverwriteCurrentValues, objUser)
getUserByID = objUser
End Function

self-join query on global catalog

I need to retrieve information about an employee (strUser variable stores their sAMAccountName )ID and their manager by querying the global catalog, using classic ASP. This works:
'=========Account and connection string information for LDAP=======
Set objDomain = GetObject ("GC://RootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.provider ="ADsDSOObject"
objConn.Properties("User ID") = "..." 'domain account with read access to LDAP
objConn.Properties("Password") = "..." 'domain account password
objConn.Properties("Encrypt Password") = True
objConn.open "Active Directory Provider"
Set objCom = CreateObject("ADODB.Command")
Set objCom.ActiveConnection = objConn
objCom.CommandText ="select name, givenName, sn, distinguishedName, manager, telephonenumber, mobile, mail, company, title, department, sAMAccountName,userAccountControl, msexchhidefromaddresslists FROM 'GC://"+objADsPath+"' where sAMAccountname='"+strUser+"'"
'=======Executre query on LDAP for all accounts=========
Set objRS = objCom.Execute
Now if I'm trying to use an alias for GC e.g.:
FROM 'GC://"+objADsPath+"' AS e
I get into an infinite loop.
What I need is a way to self-join query on global catalog (as e for employee, and m for manager) where e.manager = m.distinguishedName, in other words the relationship for the self-join in that the employee's manager is the manager's distinguished name.
How to do this?
I would also appreciate any hint to documentation.
Many thanks!
Another approach that works is to embed a second query for manager details within the outer query for employee details.
objCom2.CommandText ="select sAMAccountName, name, givenName, sn, distinguishedName, manager FROM 'GC://"+objADsPath+"' where distinguishedName='" + manager + "'"
I would still like to know if GC self-join query is possible or not.

how to add other columns to the joinTable in a Many To Many relationship in hibernate JPA?

I have two entities User and File . a File can be shared with many users and a user can receive many files . So it's a Many To Many relationship between the two entities .
in the User class :
#ManyToMany
#JoinTable(name = "receiver_shared",
joinColumns = #JoinColumn(name = "user_id",
insertable =false, updatable = false),
inverseJoinColumns = #JoinColumn(name ="file_id",
insertable = false, updatable = false))
private List<File> receivedfiles;
in the File class :
#ManyToMany(mappedBy = "receivedfiles")
private List<User> receivers;
My problem is that I want to save the shareTime and to assign permissions when a file is shared with a user . I mean file 1 can be shared with user 1 with permissions read and write and it's shared with user 2 with permission read Only .
I'm new to JPA . What I was thinking about is that the receiver_shared Table must contain a permission column and shareTime column .
how to do this ?
Update :
as JB Nizet suggested I've created a new Share entity .
I've added this to my File Class
#OneToMany (mappedBy = "sharedFile",fetch=FetchType.LAZY)
private List<Share> shares = new ArrayList<Share>();
I've added this to my User Class
#OneToMany (mappedBy = "receiver",fetch=FetchType.LAZY)
private List<Share> receivedfiles = new ArrayList<Share>();
In my Share Class I have added a column shareTime , a column permission and :
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "receiver_id")
private User receiver;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "file_id")
private File sharedFile;
I tested my configuration with JUnit
User receiver=userRepository.findOne((long)2);
File toshare=fileRepository.findOne((long)2);
Share s=new Share(toshare,receiver,1,new Timestamp(newDate().getTime()));
shareRepository.save(s);
If the join table contains additional functional information, it's not a join table anymore, and it must be mapped as an entity.
So you'll have a one-to-many between User and Share, and a one-to-many between File and Share.

Update Only one field in MS SQL Using Classic ASP

I have been banging my head with this script and need to assistance. I am trying to create a registration form that connects to the following sql fields: Acct_ID, Username, Password, FirstName, LastName, Confirmation, RegistrationDate and AccountNum.
What I have been able to do so far is get the form inserted into the database and have a cdosys email sent out to the email address(username) with a querystring attached to a link embedded in the email. The querystring is the AccountNum field from the registration form.
What I want to try to do is update the confirmation field only in the database when the user clicks on the link which looks like this:
http://www.domainname.com/Presenter_Account_Confirm_Registration.asp?AccountNum=2152012319101300766363428210152260.
I verified that the Account Number is transferred to the confirmation page, but I am stumped as to how to update just the confirmation field in the database. Any help would be greatly appreciated. Thank you!
Making some assumptions here, that Acct_ID is an INT, is the same as AccountNum, and that you want to set Confirmation to 1:
<%
Acct_ID = Request.QueryString("AccountNum")
set cmd = CreateObject("ADODB.Command")
cmd.ActiveConnection = conn ' assume ADODB.Connection has been set up
cmd.CommandType = adCmdText
sql = "UPDATE dbo.tablename SET Confirmation = 1 WHERE Acct_ID = ?"
cmd.Parameters(0).value = Acct_ID
cmd.CommandText = sql
cmd.Execute
%>

Resources