Add test utils and tests for quick booking
[pharos-tools.git] / dashboard / src / account / jira_util.py
1 ##############################################################################
2 # Copyright (c) 2016 Max Breitenfeldt and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10
11 import base64
12 import os
13
14 import oauth2 as oauth
15 from django.conf import settings
16 from jira import JIRA
17 from tlslite.utils import keyfactory
18
19
20 class SignatureMethod_RSA_SHA1(oauth.SignatureMethod):
21     name = 'RSA-SHA1'
22
23     def signing_base(self, request, consumer, token):
24         if not hasattr(request, 'normalized_url') or request.normalized_url is None:
25             raise ValueError("Base URL for request is not set.")
26
27         sig = (
28             oauth.escape(request.method),
29             oauth.escape(request.normalized_url),
30             oauth.escape(request.get_normalized_parameters()),
31         )
32
33         key = '%s&' % oauth.escape(consumer.secret)
34         if token:
35             key += oauth.escape(token.secret)
36         raw = '&'.join(sig)
37         return key, raw
38
39     def sign(self, request, consumer, token):
40         """Builds the base signature string."""
41         key, raw = self.signing_base(request, consumer, token)
42
43         module_dir = os.path.dirname(__file__)  # get current directory
44         with open(module_dir + '/rsa.pem', 'r') as f:
45             data = f.read()
46         privateKeyString = data.strip()
47         privatekey = keyfactory.parsePrivateKey(privateKeyString)
48         raw = str.encode(raw)
49         signature = privatekey.hashAndSign(raw)
50         return base64.b64encode(signature)
51
52
53 def get_jira(user):
54     module_dir = os.path.dirname(__file__)  # get current directory
55     with open(module_dir + '/rsa.pem', 'r') as f:
56         key_cert = f.read()
57
58     oauth_dict = {
59         'access_token': user.userprofile.oauth_token,
60         'access_token_secret': user.userprofile.oauth_secret,
61         'consumer_key': settings.OAUTH_CONSUMER_KEY,
62         'key_cert': key_cert
63     }
64
65     return JIRA(server=settings.JIRA_URL, oauth=oauth_dict)