Using Tokens for Your Projects
Let’s say you’re designing an application that uses github3.py. If yourintention is to have users authenticate, you have a few options.
Ask the user to enter their credentials each time they start theapplication. (Or save the username somewhere, and just ask for thepassword.)
Ask the user to supply their credentials once and store them somewhere forlater use.
Ask the user to supply their credentials once, get an authorization tokenand store that for later use.
The first isn’t a bad method at all, it just unfortunately may lead to unhappyusers, this should always be an option though. The second (as I already noted)is a bad idea. Even if you obfuscate the username and password, they can stillbe discovered and no level of obfuscation is clever enough. (May I also takethis moment to remind people that base64 isnot encryption.) The last isprobably the least objectionable of the evils. The token has scopes so thereis only so much someone can do with it and it works well with github3.py.
Requesting a token
If you’re not doing a web application, you are more than welcome to usegithub3.py (otherwise work withredirects). Let’s say your application needsaccess to public and private repositories, and the users but not to gists.Yourscopes should be['user','repo']
. I’m also assuming yourapplication will not be deleting any repositories. The only things left to doare collect the username and password and give a good description for yourapplication.
fromgithub3importauthorizefromgetpassimportgetuser,getpassuser=getuser()password=''whilenotpassword:password=getpass('Password for{0}: '.format(user))note='github3.py example app'note_url='http://example.com'scopes=['user','repo']auth=authorize(user,password,scopes,note,note_url)withopen(CREDENTIALS_FILE,'w')asfd:fd.write(auth.token+'\n')fd.write(str(auth.id))
In the future, you can then read that token in without having to bother youruser. If at some later point in the lifetime of your application you need moreprivileges, you simply do the following:
fromgithub3importlogintoken=id=''withopen(CREDENTIALS_FILE,'r')asfd:token=fd.readline().strip()# Can't hurt to be paranoidid=fd.readline().strip()gh=login(token=token)auth=gh.authorization(id)auth.update(add_scopes=['repo:status','gist'],rm_scopes=['user'])# if you want to be really paranoid, you can then test:# token == auth.token# in case the update changes the token