c333f8c43a8d79a84a09d45ee121a9317e93d501
[pharos.git] / tools / pharos-dashboard / 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 jira import JIRA
16 from tlslite.utils import keyfactory
17
18 from django.conf import settings
19
20
21 class SignatureMethod_RSA_SHA1(oauth.SignatureMethod):
22     name = 'RSA-SHA1'
23
24     def signing_base(self, request, consumer, token):
25         if not hasattr(request, 'normalized_url') or request.normalized_url is None:
26             raise ValueError("Base URL for request is not set.")
27
28         sig = (
29             oauth.escape(request.method),
30             oauth.escape(request.normalized_url),
31             oauth.escape(request.get_normalized_parameters()),
32         )
33
34         key = '%s&' % oauth.escape(consumer.secret)
35         if token:
36             key += oauth.escape(token.secret)
37         raw = '&'.join(sig)
38         return key, raw
39
40     def sign(self, request, consumer, token):
41         """Builds the base signature string."""
42         key, raw = self.signing_base(request, consumer, token)
43
44         module_dir = os.path.dirname(__file__)  # get current directory
45         with open(module_dir + '/rsa.pem', 'r') as f:
46             data = f.read()
47         privateKeyString = data.strip()
48         privatekey = keyfactory.parsePrivateKey(privateKeyString)
49         raw = str.encode(raw)
50         signature = privatekey.hashAndSign(raw)
51         return base64.b64encode(signature)
52
53
54 def get_jira(user):
55     module_dir = os.path.dirname(__file__)  # get current directory
56     with open(module_dir + '/rsa.pem', 'r') as f:
57         key_cert = f.read()
58
59     oauth_dict = {
60         'access_token': user.userprofile.oauth_token,
61         'access_token_secret': user.userprofile.oauth_secret,
62         'consumer_key': settings.OAUTH_CONSUMER_KEY,
63         'key_cert': key_cert
64     }
65
66     return JIRA(server=settings.JIRA_URL, oauth=oauth_dict)