Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / commands / astakos.py @ f5ff79d9

History | View | Annotate | Download (6.2 kB)

1
# Copyright 2011-2013 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.command
33

    
34
from kamaki.cli import command
35
from kamaki.clients.astakos import AstakosClient
36
from kamaki.cli.commands import (
37
    _command_init, errors, _optional_json, addLogSettings)
38
from kamaki.cli.command_tree import CommandTree
39
from kamaki.cli.errors import CLIBaseUrlError, CLIError
40
from kamaki.cli.utils import print_dict, ask_user
41

    
42
user_cmds = CommandTree('user', 'Astakos API commands')
43
_commands = [user_cmds]
44

    
45

    
46
class _user_init(_command_init):
47

    
48
    def _write_main_token(self, token):
49
        tokens = self.config.get_cloud(self.cloud, 'token').split()
50
        if token in tokens:
51
            tokens.remove(token)
52
        tokens.insert(0, token)
53
        self.config.set_cloud(self.cloud, 'token', ' '.join(tokens))
54
        self.config.write()
55

    
56
    @errors.generic.all
57
    @errors.user.load
58
    @addLogSettings
59
    def _run(self):
60
        if getattr(self, 'cloud', False):
61
            base_url = self._custom_url('astakos')
62
            if base_url:
63
                token = self._custom_token(
64
                    'astakos') or self.config.get_cloud(self.cloud, 'token')
65
                token = token.split()[0] if ' ' in token else token
66
                self.client = AstakosClient(base_url=base_url, token=token)
67
                return
68
        else:
69
            self.cloud = 'default'
70
        if getattr(self, 'auth_base', False):
71
            self.client = self.auth_base
72
            return
73
        raise CLIBaseUrlError(service='astakos')
74

    
75
    def main(self):
76
        self._run()
77

    
78

    
79
@command(user_cmds)
80
class user_authenticate(_user_init, _optional_json):
81
    """Authenticate a user
82
    Get user information (e.g. unique account name) from token
83
    Token should be set in settings:
84
    *  check if a token is set    /config whoami cloud.default.token
85
    *  permanently set a token    /config set cloud.default.token <token>
86
    Token can also be provided as a parameter
87
    (In case of another named cloud, use its name instead of default)
88
    """
89

    
90
    @staticmethod
91
    def _print_access(r):
92
        print_dict(r['access'])
93

    
94
    @errors.generic.all
95
    @errors.user.authenticate
96
    def _run(self, custom_token=None):
97
        token_bu = self.client.token
98
        try:
99
            r = self.client.authenticate(custom_token)
100
            if (token_bu != self.client.token and
101
                    ask_user('Permanently save token as cloud.%s.token ?' % (
102
                        self.cloud))):
103
                self._write_main_token(self.client.token)
104
        except Exception:
105
            #recover old token
106
            self.client.token = token_bu
107
            raise
108
        self._print(r, self._print_access)
109

    
110
    def main(self, custom_token=None):
111
        super(self.__class__, self)._run()
112
        self._run(custom_token)
113

    
114

    
115
@command(user_cmds)
116
class user_list(_user_init, _optional_json):
117
    """List all authenticated users"""
118

    
119
    @errors.generic.all
120
    def _run(self, custom_token=None):
121
        self._print(self.client.list_users())
122

    
123
    def main(self):
124
        super(self.__class__, self)._run()
125
        self._run()
126

    
127

    
128
@command(user_cmds)
129
class user_whoami(_user_init, _optional_json):
130
    """Get current session user information"""
131

    
132
    @errors.generic.all
133
    def _run(self):
134
        self._print(self.client.user_info(), print_dict)
135

    
136
    def main(self):
137
        super(self.__class__, self)._run()
138
        self._run()
139

    
140

    
141
@command(user_cmds)
142
class user_set(_user_init, _optional_json):
143
    """Set session user by id
144
    To enrich your options, authenticate more users:
145
    /user authenticate <other user token>
146
    To list authenticated users
147
    /user list
148
    To get the current session user
149
    /user whoami
150
    """
151

    
152
    @errors.generic.all
153
    def _run(self, uuid):
154
        for user in self.client.list_users():
155
            if user.get('id', None) in (uuid,):
156
                ntoken = user['auth_token']
157
                if ntoken == self.client.token:
158
                    print('%s (%s) is already the session user' % (
159
                        self.client.user_term('name'),
160
                        self.client.user_term('id')))
161
                    return
162
                self.client.token = user['auth_token']
163
                print('Session user set to %s (%s)' % (
164
                        self.client.user_term('name'),
165
                        self.client.user_term('id')))
166
                if ask_user('Permanently make %s the main user?' % (
167
                        self.client.user_term('name'))):
168
                    self._write_main_token(self.client.token)
169
                return
170
        raise CLIError(
171
            'User with UUID %s not authenticated in current session' % uuid,
172
            details=[
173
                'To authenticate a user', '  /user authenticate <t0k3n>'])
174

    
175
    def main(self, uuid):
176
        super(self.__class__, self)._run()
177
        self._run(uuid)