XSRF Security Token missing in jira-python - python

I'm using jira-python to loop through all of our users and add them to a specific group. One would think that the 'add_user_to_group' function would have done this, but I ended up having to customize it a bit. At any rate, it mostly worked except for a dozen users that are triggering the 'XSRF Security Token Missing' error. I can't see any common thread in those users that distinguishes them from any body else. If I log into jira I can add the users manually. I'm not really sure where to go from here.
Here's my (slightly modified) add_user_to_group function:
def add_user_to_group(username, group):
url = jira._options['server'] + '/secure/admin/user/EditUserGroups.jspa'
payload = {
'groupsToJoin': group,
'name': username,
'join': 'submit'}
connect = jira._session.post(url, headers=jira._options['headers'], data=payload)
if connect.status_code == 200:
content = connect.content.decode('utf8')
if content.find('class="error">') != -1:
m = re.search('class="error">(.*)</div>', content)
if m:
msg = m.groups()[0]
if msg == 'A user with that username already exists.':
print msg
return True
else:
print "your message is: ", msg
return False
elif 'XSRF Security Token Missing' in content:
print('XSRF Security Token Missing')
return False
else:
return True
return False

Related

Chatting flask projects with pymongo

This is the first time t work with flask and pymongo. Anyone can tell my why and how to fix this problem ?
I had watched this video: https://www.youtube.com/watch?v=7Abxa0q4Vuk and use his code. However, it isn't work when i try to login.
It is a picture I captured when I tried to log in with an account had already register
This is the login_check code:
if(request.method == 'POST'):
req = request.form
req = dict(req)
print(req)
query = user_table.find({'uid', req['uid']})
flag = 0
temp = None
for x in query:
if(x['uid'] == req['uid']):
flag = 1
temp = x
break
if(flag == 1):
if(temp['password'] == req['password']):
return render_template('dashboard.html', uid = req['uid'])
else:
return render_template('invalid.html', message = 'incorrect password')
else:
return render_template('invalid.html', message = "User not registered")
return render_template('login.html')
This is the error:
filter must be an instance of dict, bson.son.SON, or any other type that inherits from collections.Mapping

Discord.py returning user's name when I asked for user's display_name

When I try to get the user's display name it returns their Discord name.
No matter what method I try display_name is never part of the return list.
Just to make sense of it, if the user mentions someone with "no ping" in their display name, it will go through all the channels in the server looking for mentions in the last 10 minutes.
for i in range(len(message.mentions)): # Unimportant, just for clarity
if "no ping" in message.mentions[i].display_name.lower() or \ # Unimportant, just for clarity
"unavailable" in message.mentions[i].display_name.lower() or \ # Unimportant, just for clarity
"unavailable" in message.mentions[i].display_name.lower(): # Unimportant, just for clarity
counter = 0
text_channel_list = []
for TextChannel in message.guild.channels:
if str(TextChannel.type) == 'text':
text_channel_list.append(TextChannel.id)
prev = datetime.datetime.now() - datetime.timedelta(minutes=10)
for i in range(len(text_channel_list)):
channel = client.get_channel(text_channel_list[i])
msg = await channel.history(limit=None, after=prev).flatten()
for message2 in msg:
if message2.author == message.author:
for i in range(len(message2.mentions)):
print(message2.mentions[i].display_name) # This will return the user's Discord name, I want it to return the Server display name.
if "no ping" in message2.mentions[i].display_name.lower():
counter += 1
I just encountered this issue and fixed it by expanding the scope of intents to all:
client = discord.Client(intents=discord.Intents.all())
Hope this helps someone.

My code wont fully run through my dictionary and i cant figure out why

I am new to coding and have been trying to write an automated email formater and sender but am running into trouble trying to get it to realise when it has already sent someone an email.
I tried using a searchable dictionary as shown in the code below however once it sends one email it stops due to something in the code.
This is only a segment of a class for the full code please ask.
def send_email(self):
self.message_format()
if len(self.messages) > 0:
for i in self.messages:
user_email = self.messages[i]["email"]
user_msg = self.messages[i]["message"]
if i in self.sent_to_list:
return False
else:
try:
email_conn = smtplib.SMTP(host,port)
email_conn.ehlo()
email_conn.starttls()
email_conn.login(username, password)
the_msg = MIMEMultipart("alternative")
the_msg["Subject"] = "Hello there!"
the_msg["From"] = from_email
the_msg["To"] = user_email
right_msg = MIMEText(user_msg, "plain")
the_msg.attach(right_msg)
email_conn.sendmail(from_email, [user_email], the_msg.as_string())
email_conn.quit()
self.sent_to_list[str(i)] = self.messages[i]
except smtplib.SMTPException:
print("Error sending message")
except smtplib.SMTPAuthenticationError:
print("An error occured during login")
return True
return False
When your function executes return statement, it immediately stops and returns the value you wrote in return. So in your function it will stop after the first iteration (because of return True in the pre-last line). If you want your function to work more or less correctly, you should:
Replace the first return False with continue. It will skip every bad message. Moreover, because of this you will not need else. You can just have your code to work.
Remove two last lines. return True because you need to iterate through all messages, return False because it has nearly no sense.
Here is the final code:
def send_email(self):
self.message_format()
if len(self.messages) > 0:
for i in self.messages:
user_email = self.messages[i]["email"]
user_msg = self.messages[i]["message"]
if i in self.sent_to_list:
continue
try:
email_conn = smtplib.SMTP(host,port)
email_conn.ehlo()
email_conn.starttls()
email_conn.login(username, password)
the_msg = MIMEMultipart("alternative")
the_msg["Subject"] = "Hello there!"
the_msg["From"] = from_email
the_msg["To"] = user_email
right_msg = MIMEText(user_msg, "plain")
the_msg.attach(right_msg)
email_conn.sendmail(from_email, [user_email], the_msg.as_string())
email_conn.quit()
self.sent_to_list[str(i)] = self.messages[i]
except smtplib.SMTPException:
print("Error sending message")
except smtplib.SMTPAuthenticationError:
print("An error occured during login")
If I understand it correctly you want to send emails to everyone in the dictionary self.messages unless you have already sent it. Currently you call return after one iteration, which terminates the function.
To handle cases where you have already sent an email use continue which simple jumps to the next iteration. You should also remove the return True since it will terminate the function. If you want a boolean return value it should be false only if there are no messages in self.messages, otherwise it doesn't really make sense. The code would then be.
def send_email(self):
self.message_format()
if len(self.messages) > 0:
for i in self.messages:
user_email = self.messages[i]["email"]
user_msg = self.messages[i]["message"]
if i in self.sent_to_list:
continue
try:
email_conn = smtplib.SMTP(host,port)
email_conn.ehlo()
email_conn.starttls()
email_conn.login(username, password)
the_msg = MIMEMultipart("alternative")
the_msg["Subject"] = "Hello there!"
the_msg["From"] = from_email
the_msg["To"] = user_email
right_msg = MIMEText(user_msg, "plain")
the_msg.attach(right_msg)
email_conn.sendmail(from_email, [user_email], the_msg.as_string())
email_conn.quit()
self.sent_to_list[str(i)] = self.messages[i]
except smtplib.SMTPException:
print("Error sending message")
except smtplib.SMTPAuthenticationError:
print("An error occured during login")
return True
return False
I realise now that my error was in the function I iterate at the top of that function.
def message_format(self):
if len (self.user_details) > 0:
for details in self.get_details():
name = details["name"]
date = details["date"]
total = details["total"]
finished_msg = self.base_message.format(
name = name,
date = date,
total = total
)
user_email = details.get("email")
if user_email:
user_data = {"email": user_email,
"message": finished_msg
}
self.messages["customer_" + str(len(self.messages)+1)] = user_data
return self.messages
else:
return ["No user data given"]

i have created a application which contain first page as login page.I want entered emailid to every page in application

I have created a application which contain first page as login page. My question is that, I want to show the entered emailid at the time of login to every page of my application. If I declare emailid as global it throwing error. Please tell me any trick if u have.
Thank u!!!
def loginbmtool(request):
emailid=request.POST["emailid"]
password=request.POST["password"]
if(str(emailid) == "brisatechnology#gmail.com" and str(password) == "hellobrisa123"):
msg ="" +emailid
return render_to_response('admin.html',{'msg':msg})
## if(str(emailid) != "brisatechnology#gmail.com" and str(password) = "brisa123"):
## msg ="" +emailid
## return render_to_response('login.html',{'wrong_user':'wrong emailid or password'})
else:
print "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
db=validate()
flag1=db.ValidateUser_Authentication(emailid,password)
if(flag1=="true"):
msg ="" +emailid
db=Fetch()
list1=db.pendinginvoice()
list2=db.delayedpay()
countofpo=db.NewPOs()
countofinvoice=db.invoicenocount()
countofacc,m,y=db.NewAccounts()
y=" "+y
mon=int(m)
listofmnth=[]
listofmnth=['January','February','March','April','May','June','July','August','September','October','November','December']
month=listofmnth[mon-1]
expiringPO=db.ExpiringPO()
print "\ncountofpo",countofpo
print list2
print list1
print list2
return render_to_response("index.html",{'msg':msg,"month":month,"year":y,"countofacc":countofacc,"expiringPO":expiringPO,"countofinvoice":countofinvoice,"countofpo":countofpo,"list1":list1,"list2":list2,"msg":msg})
else:
return render_to_response('login.html',{'wrong_user':'emailid or password you entered is incorrect?'})
I'm not that familiar with python, but if it is for web, it must have some sort of session variable. Have you tried implementing it?
For further reading: http://webpython.codepoint.net/cgi_session

Skype4py !command with arguments

I currently have a skypebot which replies to commands and pings websites when I use the following code:
if Status == 'SENT' or (Status == 'RECEIVED'):
if Message.Body.lower() == '!ping google':
ping = os.system("ping google.com")
if ping == 0:
Message.Chat.SendMessage("Online!")
else:
Message.Chat.SendMessage('Offline!')
This works and if the website is online it will display Online! in chat. However, it requires me to define the website before hand. I have searched for a good few hours now to try to find how I would make it so I can do !ping [website] and allow for the user at any time to use whatever website they want. Any ideas?
I would do something like this:
body = Message.Body
if body.startswith('!'):
parts = body.split() # ['!ping', 'google.com']
command = parts[0][1:] # 'ping'
result = commands[command](*parts[1:]) # Calls `ping` with 'google.com'
Message.Chat.SendMessage(result) # Prints out the resulting string
Now, you can define simple functions:
def ping(url):
if os.system("ping " + url) == 0:
return 'Online!'
else:
return 'Offline!'
And add them to a commands dictionary:
commands = {
'ping': ping
}
os.system() is insecure if you're expecting arbitrary user input, so I'd use subprocess.Popen instead (or just try connecting to the website with just Python).
I have a SkypeBot I made as well.
I use http://www.downforeveryoneorjustme.com/
I do it this way:
Functions.py
def isUP(url):
try:
source = urllib2.urlopen('http://www.downforeveryoneorjustme.com/' + url).read()
if source.find('It\'s just you.') != -1:
return 'Website Responsive'
elif source.find('It\'s not just you!') != -1:
return 'Tango Down.'
elif source.find('Huh?') != -1:
return 'Invalid Website. Try again'
else:
return 'UNKNOWN'
except:
return 'UNKNOWN ERROR'
And for commands.py
elif msg.startswith('!isup '):
debug.action('!isup command executed.')
send(self.nick + 'Checking website. Please wait...')
url = msg.replace('!isup ', '', 1)
url = functions.getCleanURL(url)
send(self.nick + functions.isUP(url))
Of course with "import functions" in the commands.py file.
I'm sure you can alter this a bit to work to check a website's status for your bot as well.
Good luck :)

Categories

Resources