Flask + GitLab OAuth

Posted by on Mon, September 5, 2016

I’m back. A lot of things have changed since I last wrote and one of that is my go-to language.

Earlier today, I needed to write a simple Flask application using GitLab as the OAuth2 provider.

I immediately turned to Flask-OAuth to do the job, but it keeps on failing with:

SSLHandshakeError: [Errno 1] _ssl.c:510: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

It seems to be a problem with httplib2.

After struggling for quite some time, I found Flask-OAuthlib that claims to be a replacement for the outdated Flask-Oauth. It worked like a charm.

GitLab’s documentation on consuming its OAuth2 is quite basic. Below is a basic implementation that works.

All you need to do is change the gitlab.example.com to your GitLab server, and add the consumer_key and consumer_secret. If successful, the main page will display a JSON with the logged on user’s details.

from flask import Flask, render_template, redirect, url_for, session, request, jsonify
from flask_oauthlib.client import OAuth
 
app = Flask(__name__)
app.debug = True
app.secret_key = 'development'
oauth = OAuth(app)
 
gitlab = oauth.remote_app('gitlab',
    base_url='https://gitlab.example.com/api/v3/',
    request_token_url=None,
    access_token_url='https://gitlab.example.com/oauth/token',
    authorize_url='https://gitlab.example.com/oauth/authorize',
    access_token_method='POST',
    consumer_key='',
    consumer_secret=''
)
 
@app.route('/')
def index():
    if 'gitlab_token' in session:
        me = gitlab.get('user')
        return jsonify(me.data)
    return redirect(url_for('login'))
 
 
@app.route('/login')
def login():
    return gitlab.authorize(callback=url_for('authorized', _external=True, _scheme='https'))
 
 
@app.route('/logout')
def logout():
    del session['gitlab_token']
    return redirect(url_for('index'))
 
@app.route('/login/authorized')
def authorized():
    resp = gitlab.authorized_response()
    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error'],
            request.args['error_description']
        )
    session['gitlab_token'] = (resp['access_token'], '')
    return redirect(url_for('index'))
 
@gitlab.tokengetter
def get_gitlab_oauth_token():
    return session.get('gitlab_token')
 
if __name__ == "__main__":
    app.run()

I hope it saves someone some time.

Previous Articles

Tue, March 24, 2015

CloudWatch INSUFFICIENT_DATA for Linux System Metric

I recently had to recreate images for our production systems on EC2 because they didn’t have ephemeral storage that we require to keep our temporary tcp dumps. Considering that they are EC2 instances, it was quite easy. We use mon-get-instance-stats.pl to monitor system metrics such as memory utilization and disk space. Naturally, I copied alarms […] 
Comments Off on CloudWatch INSUFFICIENT_DATA for Linux System Metric | Full article »

Thu, July 3, 2014

Why I Will Never Buy From Senheng Ever Again

I’m still alive and before I reach the point of one year without writing anything in this blog, I thought that I should write something. Have been busy with life. I’ve been frowning upon the “as long as it works” mentality with Malaysians since I was born. People are providing services without qualifications, and doing […] 
Comments Off on Why I Will Never Buy From Senheng Ever Again | Full article »

Mon, October 14, 2013

DD-WRT: OpenVPN Server Using Certificates

GUI confuses me sometimes, so I prefer to make configurations in text files. For DD-WRT, OpenVPN server is available in OpenVPN, OpenVPN Small, Big, Mega, and Giga builds: K2.6 Build Features. Since I have never used any router with USB storage capabilities, I can’t be sure but I think OpenVPN can be installed using ipkg […] 
Comments Off on DD-WRT: OpenVPN Server Using Certificates | Full article »

Tue, August 13, 2013

WordPress Update: Upgrade package not available (3.5)

I used to upgrade WordPress manually using FTP. I would update a local copy of the website, make sure everything works on my laptop and then upload it to the server. Not that I don’t trust WordPress automatic upgrade but I am paranoid that my custom plugins and changes will break the site. However, starting […] 
Comments Off on WordPress Update: Upgrade package not available (3.5) | Full article »

Mon, May 27, 2013

Happy 10th Anniversary WordPress!

Today marks the 10th anniversary of WordPress which was first released on May 27th, 2003. WordPress now powers countless number of blogs in the Internet via the community driven project WordPress.org and the hosted solutions at WordPress.com. This site has been running on WordPress since the beginning, in 2005. Being sick today, I will not […] 
Comments Off on Happy 10th Anniversary WordPress! | Full article »

Sat, April 20, 2013

CrashPlan 3.5.3 Headless Upgrade

A headless installation of CrashPlan will fail when it tries to update itself. This short post assumes that you already have it setup and successfully running before, and is targeted only to help you save some time by identifying important files to copy. Running the installer again will also work, but we actually spend more […] 
Comments Off on CrashPlan 3.5.3 Headless Upgrade | Full article »

Mon, February 18, 2013

Inbox Zero: Gmail vs. Mailbox

Mailbox is really cool for someone who has a lot of emails like me. It was worth the wait although I didn’t have to wait long (registered in the queue weeks ago). Have you been activated? 
Comments Off on Inbox Zero: Gmail vs. Mailbox | Full article »

Mon, January 21, 2013

CloudFlare: Reliable?

This website and some other websites I maintain had their ups and downs. All of my websites are running via CloudFlare. When you are utilizing CloudFlare and your website is dynamic (not static HTML pages), CloudFlare will still need to contact the server where your website is hosted in order to get the latest contents. […] 
Comments Off on CloudFlare: Reliable? | Full article »

Sat, January 19, 2013

Redirecting WordPress Permalinks in Nginx

I know, it’s been really a long time since I last wrote an article in this blog. But trust me, I’ve done a lot of improvements at the back end. The blog is now in a new server, with new backup infrastructure, and most importantly served by Nginx. I was just casually looking at 404 […] 
Comments Off on Redirecting WordPress Permalinks in Nginx | Full article »

Mon, October 1, 2012

Konvensyen Jutawan Awesome 2012

This year, I am trying to learn as much as possible by joining seminars and conventions related to business and entrepreneurship. I’ve attended seminars by Dr. Azizan Osman and they are superb. As someone who has a day job (salary earner), I still have plans for retirement by having my own business some day. Earlier […] 
Comments Off on Konvensyen Jutawan Awesome 2012 | Full article »

Tue, September 4, 2012

Pink iPhone Cable from Giveaway

I received a surprise in the mail today. It’s the iPhone cable I won in a giveaway organized by LiewCF.com. Thanks LiewCF and I should also thank MudahAlih.my for sponsoring the gifts. I laughed because I expected that he will send me a pink cable, as I commented about pink in the post: Thank you, […] 
Comments Off on Pink iPhone Cable from Giveaway | Full article »

Sat, May 12, 2012

Sluggish iChat, Messages, Terminal, and Others in Mac OS X Lion

After about 60 days using my MacBook Pro running Mac OS X Lion (10.7.3), I saw some sluggishness in some apps. At first, it was Messages (iChat replacement for Mountain Lion). It went unresponsive and displays the rainbow wheel for a few seconds, enough to annoy an impatient user. Then, the same behavior happened in […] 
Comments Off on Sluggish iChat, Messages, Terminal, and Others in Mac OS X Lion | Full article »

Sat, May 5, 2012

Build LFTP on Mac OS X Lion

If you’re a seasoned Linux SysAdmin, you’ll miss LFTP. It’s a really powerful FTP client. Yes, you can also install it using MacPorts or Fink but right now, this is much quicker for me. Here’s how I built LFTP 4.3.6 on my MacBook Pro. For the record, I’m on 10.7.3 Prerequisite: Apple developer tools (Xcode) […] 
1 Comment » | Full article »

Thu, February 23, 2012

UniFi Phone Call Forwarding

If you’re here to look for the way to forward the phone that comes to UniFi to another phone number, I apologize. I don’t know how. I tried asking TM call center but they told me to call UniFi support for UniFi phone. For the record every time I try *61*XXXXXXXXXX# the automated voice response […] 
Comments Off on UniFi Phone Call Forwarding | Full article »