Python3.6 Ldap3 modify_dn ( Renaming + Moving User to another OU) - python-3.x

I'm trying to rename AD user Test_2 to testing using python LDAP3 as well as moving user to another OU too.
NOTE: instead of domain name i am using IP and rest is same.
i am successfully able to fetching user details using the same manner (Mentioned in NOTE), but during renaming and moving user one OU to other OU, i am getting negative result; the funny thing is code doesn't showing any error it is showing only FALSE result.
import ldap3
from ldap3 import Server, Connection, ALL
server=Server(host='IP',port=389,get_info=ALL)
conn=Connection(server,user='adtest\admin',password='admin#123') conn.bind()
print (conn.modify_dn('cn=Test_2,OU=Test,OU=adtest','cn=Testing'))

Check conn.result to get the reason of the failure.

Related

Issue faced during Flask-login authorizing per enter

I using flask-login for authorizing in my site.
If I login once, flask do not offer login again, but I want users to be logged in every time they log on to the site.
P.S.: I try to use remember=False in login_user() function, but it didn't help.
What can be the correction that need to be done?
I now see case for fresh loging like password change etc It is provided for by the use of fresh_login_required
flask_login.login_fresh()
This returns True if the current login is fresh. So your views protected with login required you can do something like
if not login_fresh():
#redirect to your login page with a request to reauthenticate
or (and am using change-password just as an example you can use it on any and all views that require fresh login everytime)
from flask.ext.login import fresh_login_required
#app.route("/change-password")
#fresh_login_required
def change_password():
#do stuff here
If the user is not authenticated, LoginManager.unauthorized() is called as normal. If they are authenticated, but their session is not fresh, it will call LoginManager.needs_refresh() instead. (In that case, you will need to provide a LoginManager.refresh_view.) which you can do as below as per the docs
login_manager.refresh_view = "accounts.reauthenticate"
login_manager.needs_refresh_message = (
u"To protect your account, please reauthenticate to access this page."
)
login_manager.needs_refresh_message_category = "info"
If what you are looking at is logging someone out after lets say 5 minutes of inactivity for which this question and this question gives you a very good answer, so you would do it like this
from datetime import timedelta
from flask import session, app
#make the session permanent and set expiry period
session.permanent = True
app.permanent_session_lifetime = timedelta(minutes=5)
#everytime a user visits, modify the session so that you know they are still active
#app.before_request
def func():
session.modified = True
You can make the lifetime very small for a start for testing purposes

How to access a shared folder using python imaplib?

How do you access a shared folder ? This is a shared folder which is visible to other users too. I am currently using outlook where the shared folder is visible along with my personal emails
Following back on my question. After reading enough this seems to work.
While using imaplib and connecting to exchange in python 3
use this,
result, data=mail.login('personal#domain.com\shared#domain.com','personalPassword')
If you have access to this shared mailbox in outlook then you will be able to connect using this. Print the result if it says 'OK' then the code did work.
I believe this is an answer.
Posting a link here for those who are working on similar problem with a python solution.
https://medium.com/#theamazingexposure/accessing-shared-mailbox-using-exchangelib-python-f020e71a96ab
Here is the snippet:
from exchangelib import Credentials, Account
credentials = Credentials('Firstname.Lastname#someenterprise.com', 'Your_Password_Here')
account = Account('**shared_mail_box_name#someenterprise.com**', credentials=credentials, autodiscover=True)
for item in account.inbox.all().order_by('-datetime_received')[:100]:
print(item.subject, item.sender, item.datetime_received)

Spotipy - Cannot log in to authenticate (Authorization Code Flow)

I am working with the Spotipy Python library to connect to the Spotify web API. I want to get access to my Spotify's user account via Authorization Code Flow. I am using Python 3.5, Spotipy 2.4.4, Google Chrome 55.0.2883.95 (64-bit) and Mac OS Sierra 10.12.2
First, I went to the Spotify Developer website to register the program to get a Client ID, a Client Secret key and enter a redirect URI (https://www.google.com) on my white-list.
Second, I set the environment variables from terminal:
export SPOTIPY_CLIENT_ID='my_spotify_client_id'
export SPOTIPY_CLIENT_SECRET='my_spotify_client_secret'
export SPOTIPY_REDIRECT_URI='https://www.google.com'
Then I try to run the example code typing 'python3.5 script.py my_username' from terminal. Here is the script:
import sys
import spotipy
import spotipy.util as util
scope = 'user-library-read'
if len(sys.argv) > 1:
username = sys.argv[1]
else:
print "Usage: %s username" % (sys.argv[0],)
sys.exit()
token = util.prompt_for_user_token(username, scope)
if token:
sp = spotipy.Spotify(auth=token)
results = sp.current_user_saved_tracks()
for item in results['items']:
track = item['track']
print track['name'] + ' - ' + track['artists'][0]['name']
else:
print "Can't get token for", username
When running this code, it takes me to a log in screen on my browser. I enter my Spotify's credential to grant access to my app. But when I finally click on 'log in' (or 'Iniciar sesiĆ³n' in Spanish) nothing happens. I tried to log in with my Facebook account but it does not work either. It seems that I get a Bad Request every time that I click on 'log in'. Here is a capture of Chrome:
The process is incomplete because when trying to enter the redirect URI back on terminal I get another Bad Request:
raise SpotifyOauthError(response.reason)
spotipy.oauth2.SpotifyOauthError: Bad Request
I tried to restart my computer, clean my browser cookies, use another different browser but did not work. It seems that I am not the only one having this problem. Is it maybe a bug? Please, avoid answers like "read the documentation of the API going here". Thank you.
Solved it. In order to run the Authorization Code Flow example code provided in the Spotipy's documentation correctly, I specified the redirect URI in line 13 of the example script when calling util.prompt_for_user_token, even when I had done this previously when setting environment variables:
token = util.prompt_for_user_token(username, scope, redirect_uri = 'https://example.com/callback/')
Likewise, do not use https://www.google.com or similar web address as your redirect URI. Instead, try 'https://example.com/callback/' or 'http://localhost/' as suggested here. Do not forget that the redirected URL once you are logged in must have the word code included.
Cheers,

Create a google contact with python3

I would like to create a contact with the google api and python3
but gdata seemsnot to be compatible with python3.
Like :
AttributeError: 'function' object has no attribute 'func_name'
Does anyone have any sample that works on how to create contact with google api in python3 ?
thanks
First, have you installed the gdata python client with pip, or with pip3? According to Google's repository, which says,
Python 3.3+ is also now supported! However, this library has not yet been > used as thoroughly with Python 3, so we'd recommend testing before
deploying with Python 3 in production,
you can use pip3, like pip3 install google-api-python-client, to reinstall it. Once that's cleared up, see the below modified sample code-block for how to create a contact by just their Name, E-mail and Phone number with Python 3:
import atom.data
import gdata.data
import gdata.contacts.client
import gdata.contacts.data
gd_client = gdata.contacts.client.ContactsClient(source='YOUR_APPLICATION_NAME')
def create_contact(gd_client):
new_contact = gdata.contacts.data.ContactEntry()
# Set the contact's name.
new_contact.name = gdata.data.Name(
given_name=gdata.data.GivenName(text='First'),
family_name=gdata.data.FamilyName(text='Last'),
full_name=gdata.data.FullName(text='Full'))
new_contact.content = atom.data.Content(text='Notes')
# Set the contact's email addresses.
new_contact.email.append(gdata.data.Email(address='handle#gmail.com',\
primary='true', rel=gdata.data.WORK_REL, display_name='E. Bennet'))
new_contact.email.append(gdata.data.Email(address='liz#example.com',\
rel=gdata.data.HOME_REL))
# Set the contact's phone numbers.
new_contact.phone_number.append(gdata.data.PhoneNumber(text='(206)555-1212',
rel=gdata.data.WORK_REL, primary='true'))
new_contact.phone_number.append(gdata.data.PhoneNumber(text='(206)555-1213',
rel=gdata.data.HOME_REL))
# Send the contact data to the server.
contact_entry = gd_client.CreateContact(new_contact)
print ("Contact's ID: {}".format(contact_entry.id.text))
return contact_entry
For read-only access to Contacts, Google has built the new People API, which works just fine with Python3 in the google-api-python-client. However, for write access you'll need to use the older GData format.
The short answer to your question is that you won't be able to get GData to work with Python3 because the gdata-python-client is no longer maintained and never had Python3 support built in (see https://github.com/google/gdata-python-client/issues/29)
However, not all hope is lost! You can still query directly to Google's REST API. Specifically, to create a contact you need to work with the https://www.google.com/m8/feeds/contacts/{userEmail}/full route (see the Contacts API documentation for more information)
The appropriate way to work with the API directly is to submit a web request using something like Python's Requests module.
CREATE_ROUTE = 'https://www.google.com/m8/feeds/contacts/default/full'
FULL_PATH = CREATE_ROUTE + '?access_token=' + ACCESS_TOKEN
import requests
r = requests.get(FULL_PATH)
print(r.text)
Where ACCESS_TOKEN is the access token you got back from Google when you authorized your access (this can still be done using google-api-python-client)

Using SSL with the python-instagram and localhost on sample-app.py

I plan on using the sample-app.py as a baseline of what I am building out and then expanding it from there. Just want to get comfortable with the instagram API and build out from there.
I am trying to use the sample-app.py provided with python-instagram. I have registered an application on instagrams website. I set it up using the default redirect uri from sample-app.py:
http://localhost:8515/oauth_callback .
I was able to authorize my instagram account to use the app, but when I click on any of the links, I get an error about the acccess-token.
When you look at the python command-line window that stays open, I get the following error:
"check_hostname needs a SSL context with either CERT_OPTIONAL or CERT_REQUIRED"
It appears that when the sample app is processing the lines below, it is trying to connect to instagram, but is not able to because SSL in local host is not set up properly. How do I set up SSL so i do not get the above error?
access_token, user_info = unauthenticated_api.exchange_code_for_access_token(code)
if not access_token:
return 'Could not get access token'
api = client.InstagramAPI(access_token=access_token)
request.session['access_token'] = access_token
print ("access token="+access_token)
There are a few steps to solve this problem (it appears that it is actually several problems in aggregate causing this issue):
use openssl to create a ssl certificate and save cert to the same location as your python script. Download open ssl here: http://slproweb.com/products/Win32OpenSSL.html
You need to tweak bottle so that it will support ssl. Do so by adding the following lines in run in class WSGIRefServer(ServerAdapter):
import ssl
srv.socket = ssl.wrap_socket (
srv.socket,
certfile='server.pem', # path to certificate
server_side=True)
There is a bug in python 3 and above(https://github.com/jcgregorio/httplib2/issues/173). I am using 3.4, so the bug could be fixed in 3.5. In the instagram/oauth2.py file, change all disable_ssl_certificate_validation=False to True.

Resources