google app engine: checking if user exists during signup - database

I have a little signup page that I'm trying to get working. Basically you give your username, password, and email, and then if the username that you entered doesn't already exist then it redirects you to a welcome page that says, "welcome (username here)!". If the user DOES exist, then it re-renders the signup page. The problem is, even if the user doesn't exist, it keeps re-rendering the signup page. I get no errors. The function "getByName" that checks if the user exists keeps returning true. Can anybody see the issue?
here's the code that calls the "getByName" function.
if(username and password and verify and email):
if UserInfo.getByName(username) == True:
self.renderSignup()
else:
UserInfo.register(username, password, email)
cookieVal = str(encrypt.makeCookieHash(username))
self.response.headers.add_header("Set-Cookie", "username=%s; Path=/" % (cookieVal))
self.redirect("/welcome")
else:
self.renderSignup(username, email, usernameError, passwordError, verifyError, emailError)
Here's the "UserInfo" data model that contains the "getByName" function, along with others.
class UserInfo(db.Model):
passwordHash = db.StringProperty(required = True)
email = db.StringProperty(required = True)
username = db.StringProperty(required = True)
#classmethod
def register(cls, name, password, email):
encrypt = Encrypt()
pwHash = encrypt.hashUserInfo(name, password)
UserInfo(passwordHash = pwHash, email = email, username = name).put()
#classmethod
def getByName(cls,name):
usersWithName = UserInfo.gql("where username = :1", name)
if usersWithName != None:
return True
return False

The lines
usersWithName = UserInfo.gql("where username = :1", name)
if usersWithName != None:
where you do the comparison is where you are going wrong. userWithName is a query object and your comparison will alwys be true. You need to execute the query with a get, fetch etc.... and then see if the result set has contents.
You should be doing something like
usersWithName = UserInfo.gql("where username = :1", name).get()
if usersWithName != None:
Or you could do a fetch(10), and check for a non empty list. Of course if you found more than 1 item matching, then that would indicate a broader error in your system.

Related

How do I get a list of all members in a discord server, preferably those who aren't bot

I'm attempting checks if a username is in a valid username in the server. The check is done by the following code
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!logan',
intents=intents,
helpCommand=helpCommand)
Users = [# Need help getting users]
async def Fight(ctx, User):
if ctx.author.name != User:
if User in Users:
open_file = open(str(ctx.author.name), "w")
open_file.write(User + "\n300\nTurn")
open_file.close()
open_file = open(User, "w")
open_file.write(str(ctx.author.name) + "\n300\nNot")
open_file.close()
await ctx.author.send("You are now fighting " + User)
#await ctx.User.send("You are now fighting " + ctx.author.name)
else:
await ctx.send("User is not in this server")
else:
await ctx.send("You Cannot Fight Yourself")
I've tried googling, but I haven't found a valid answer
There are other ways to get your guild name, but here's a possible method to get it and get the member list from it.
In member (and user so), there is the ".bot" that is a boolean, 0 if not a bot.
listMembers = []
#bot.command(name="init")
async def FuncInit (ctx) :
global listMembers
guilde = ctx.message.guild
for member in guilde.members :
if not member.bot :
listMembers.append(member.name)

GraphClientService throws exception when calling 'Any'

Given a GUID, I need to know if a user exists in azure active directory.
If I pass the Id of an exisitng user everything is Ok.
If I pass the id for which no user account exists, I get the following exeption:
ServiceException: Code: Request_ResourceNotFound Message: Resource
'02803255-b96e-438a-9123-123' does not exist or one of its queried
reference-property objects are not present.
I know this record doen not exist, as this is what I'm testing, I want false to be returned somehow.
Surely I do not have to catch the exception?
//Simple code:
public bool CheckUserExists(string userId) {
bool exists = false;
//purposefully set this to a string that does not match any user.
userId = "02803255-b96e-438a-9123-123";
var user = _graphServiceClient
.Users
.Request()
.Filter("Id eq '" + userId + "'")
.GetAsync();
//exception thrown on next line.
if (user.Result.Count == 1) {
exists = true;
}
Please try checking if user count is less than or equals 0 condition , instead if count equals 1.
var users = await graphClient.Users.Request().GetAsync();
var exists=true;
try {
var user = _graphServiceClient
.Users
.Request()
.Filter("Id eq '" + userId + "'")
.GetAsync();
if (user.Count <= 0) {
exists = false;
break;
}
}
catch (ServiceException ex) {
exists = false;
}
return exists;
or try with
if (user.Count !=null && user.Count>=0)
Reference:
verify if user account exists in azure active directory -SO
reference
Microsoft.Azure.ActiveDirectory.GraphClient/User

I can't find the correct XPath expression to send the Username and Password Keys to the Instragram Website by selenium webdriver

I want to send automate keys "Username" and "Password" to instagram.com, where I can't locate the correct Xpath expression of "Username" and "Password" to send the "Keys." I got an Xpath location error when I executed the code. For privacy purpose, I do not write the Username and Password.
from selenium import webdriver
from time import sleep
class App:
def __init__(self, username='#', password='#', target_username ='#',
path='C:/Users/ameni/Desktop/instaphoto'):
self.username = username
self.password = password
self.target_username = target_username
self.path = path
self.driver = webdriver.Chrome('C:/chromedriver/chromedriver.exe')
self.main_url = 'https://www.instagram.com/accounts/emailsignup'
self.driver.get(self.main_url)
sleep(3)
self.log_in()
sleep(3)
self.driver.close()
def log_in(self):
login_button = self.driver.find_element_by_xpath("//p[#class='izU2O ']/a[#href]")
login_button.click()
username_input = self.driver.find_element_by_xpath("//input[#aria-label='Phone number, username, or email']")
username_input.send_keys(self.username)
password_input = self.driver.find_element_by_xpath("//input[#aria-label='Password']")
password_input.send_keys(self.password)
input('Stop for Now')
if __name__ == '__main__':
app = App()
The username and password input tags have name attribute. Use the same to locate them.
Was able to send text with these lines.
login_button = driver.find_element_by_xpath("//p[#class='izU2O ']/a[#href]")
login_button.click()
username_input = driver.find_element_by_name("username")
username_input.send_keys("Sample Text")
password_input = driver.find_element_by_name("password")
password_input.send_keys("SampleText")

Unable to Assign Role with member.roles.add (id)

I'm trying to make an assignrole command which takes userID and roleID as arguments.
content = message.content.slice(message.content.indexOf(' ')+1)
args = content.split(', ');
const userID = args[0]
const roleID = args[1]
const desiredUser = message.guild.members.cache.get(userID)
const desiredRole = message.guild.roles.cache.get(roleID)
if (desiredUser != undefined){
if (desiredRole != undefined){
usern = desiredUser.user.username
desiredUser.roles.add(roleID).catch(console.error);
message.channel.send(usern + " has been assigned the "+ desiredRole.name +" role")
console.log("added role")
} else {
message.channel.send("role with ID " + roleID + " does not exist")
}
} else {
message.channel.send("user with ID " + userID + " does not exist")
}
The function succeeds at "getting" the correct user and role, and successfully sends the "USER has been assigned the ROLENAME role" message. However, the role itself isn't actually added to the user!
My console throws a DiscordAPIError: Missing Permissions error, but I don't know how to interpret it. The error does not quit the bot, however.
How do I add the role to the user?
It is likely that you are missing the MANAGE_ROLES permission as it is, like the name would suggest, required to manage rules.
https://discord.com/developers/docs/topics/permissions
Here are other possibilities that may be causing the error:
I found these here
It is trying to execute an action on a guild member with a role higher than or equal to your bots highest role.
It is trying to modify or assign a role that is higher than or equal to its highest role.
It is trying to execute a forbidden action on the server owner.

user_id is not unique

i have a this thing in my views,py
def status_change(request):
if request.method == "POST":
rform = registerForm(data = request.POST)
if rform.is_valid():
register = rform.save(commit=False)
register.user = request.user
register.save()
return render_to_response('home.html')
else:
rform = registerForm()
return render_to_response('status_change.html',{'rform':rform})
when i tried to save the fields for the second time in the model it says
"column user_id is not unique"
actually i want to update it
i tried the rform.save(force_update = True)
but it didnt work
how to solve this thing.
Every time when you save form, django creates new object.
If you need to change(not create new) some object, you need first get object and then create form with instance of this object:
myobject = ...objects.get(....)
mform = MyForm(instance=myobject)
problem is solved
def status_change(request):
instance = get_object_or_404(register,pk=request.user.id)
#rest of the code here

Resources