Statistics
| Branch: | Tag: | Revision:

root / ui / userdata / views.py @ c72a830d

History | View | Annotate | Download (1.9 kB)

1
from django import http
2
from django.template import RequestContext, loader
3
from django.utils import simplejson as json
4
from django.conf import settings
5

    
6
from synnefo.ui.userdata import rest
7
from synnefo.ui.userdata.models import PublicKeyPair
8

    
9

    
10
SUPPORT_GENERATE_KEYS = True
11
try:
12
    import M2Crypto as M2C
13
except ImportError, e:
14
    SUPPORT_GENERATE_KEYS = False
15

    
16
import base64
17

    
18
class PublicKeyPairResourceView(rest.UserResourceView):
19
    model = PublicKeyPair
20
    exclude_fields = ["user"]
21

    
22
class PublicKeyPairCollectionView(rest.UserCollectionView):
23
    model = PublicKeyPair
24
    exclude_fields = ["user"]
25

    
26
SSH_KEY_LENGTH = getattr(settings, 'USERDATA_SSH_KEY_LENGTH', 2048)
27
SSH_KEY_EXPONENT = getattr(settings, 'USERDATA_SSH_KEY_EXPONENT', 65537)
28
def generate_key_pair(request):
29
    """
30
    Response to generate private/public RSA key pair
31
    """
32
    if not SUPPORT_GENERATE_KEYS:
33
        raise Exception("Application does not support ssh keys generation")
34

    
35
    if PublicKeyPair.user_limit_exceeded(request.user):
36
        raise http.HttpResponseServerError("SSH keys limit exceeded");
37

    
38

    
39
    # generate RSA key
40
    key = M2C.RSA.gen_key(SSH_KEY_LENGTH, SSH_KEY_EXPONENT, lambda x: "");
41

    
42
    # get PEM string
43
    pem_buffer = M2C.BIO.MemoryBuffer()
44
    M2C.m2.rsa_write_key_no_cipher(key.rsa, pem_buffer._ptr(), lambda : "")
45
    pem = pem_buffer.getvalue()
46

    
47
    # generate public content
48
    public = "ssh-rsa %s" % base64.b64encode('\x00\x00\x00\x07ssh-rsa%s%s' % (key.pub()[0], key.pub()[1]))
49

    
50
    data = {'private': pem, 'public': public}
51
    return http.HttpResponse(json.dumps(data), mimetype="application/json")
52

    
53
def download_private_key(request):
54
    """
55
    Return key contents
56
    """
57
    data = request.POST.get("data")
58
    name = request.POST.get("name", "key")
59

    
60
    response = http.HttpResponse(mimetype='application/x-pem-key')
61
    response['Content-Disposition'] = 'attachment; filename=%s.pem' % name
62
    response.write(data)
63
    return response