Added seed code for access-management.
[ta/access-management.git] / src / access_management / rest-plugin / users_keys.py
1 # Copyright 2019 Nokia
2
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 from am_api_base import *
16 from cmframework.apis import cmclient
17
18
19 class UsersKeys(AMApiBase):
20
21     """
22     User add key operations
23
24     .. :quickref: User keys;User add key operations
25
26     .. http:post:: /am/v1/users/keys
27
28     **Start User add key**
29
30     **Example request**:
31
32     .. sourcecode:: http
33
34         POST am/v1/users/keys HTTP/1.1
35         Host: haproxyvip:61200
36         Accept: application/json
37         {
38             "user": <uuid> or <username>
39             "key": <user key>
40         }
41
42     :> json string user: The user's id or name.
43     :> json string key: The user's public key.
44
45     **Example response**:
46
47     .. sourcecode:: http
48
49         HTTP/1.1 200 OK
50         {
51             "code": 0,
52             "description": "User public key uploaded!"
53         }
54
55     :> json int code: the status code
56     :> json string description: the error description, present if code is non zero
57
58     User remove key operations
59
60     .. :quickref: User keys;User remove key operations
61
62     .. http:delete:: /am/v1/users/keys
63
64     **Start User remove key**
65
66     **Example request**:
67
68     .. sourcecode:: http
69
70         DELETE am/v1/users/keys HTTP/1.1
71         Host: haproxyvip:61200
72         Accept: application/json
73         {
74             "user": <uuid> or <username>
75         }
76
77     :> json string user: The user's id or name.
78
79     **Example response**:
80
81     .. sourcecode:: http
82
83         HTTP/1.1 200 OK
84         {
85             "code": 0,
86             "description": "User public key removed!"
87         }
88
89     :> json int code: the status code
90     :> json string description: the error description, present if code is non zero
91     """
92
93     endpoints = ['users/keys']
94     parser_arguments = ['user',
95                         'key']
96
97     def post(self):
98         self.logger.info("Received an add key request!")
99         args = self.parse_args()
100
101         if args["key"] is None:
102             self.logger.error("The public key is missing!")
103             return AMApiBase.embed_data({}, 1, "The public key is missing!")
104
105         state, user_info = self.get_uuid_and_name(args["user"])
106         if state:
107             state, message = self.user_checker(user_info, args["key"])
108             if state:
109                 self.logger.info("User public key uploaded!")
110                 return AMApiBase.embed_data({}, 0, "User public key uploaded!")
111             else:
112                 return AMApiBase.embed_data({}, 1, "Internal error: {0}".format(message))
113         else:
114             self.logger.error(user_info)
115             return AMApiBase.embed_data({}, 1, user_info)
116
117     def delete(self):
118         self.logger.info("Received a remove key request!")
119         args = self.parse_args()
120
121         state, user_info = self.get_uuid_and_name(args["user"])
122         if state:
123             state, message = self.user_checker(user_info, "")
124             if state:
125                 self.logger.info("User public key removed!")
126                 return AMApiBase.embed_data({}, 0, "User public key removed!")
127             else:
128                 return AMApiBase.embed_data({}, 1, "Internal error: {0}".format(message))
129         else:
130             self.logger.error(user_info)
131             return AMApiBase.embed_data({}, 1, user_info)
132
133     def user_checker(self, user_info, key):
134         state_open, message_open = self._open_db()
135         if state_open:
136             try:
137                 roles = self.db.get_user_roles(user_info["id"])
138                 self.logger.debug("Check the chroot role, when setting a user public key!")
139                 for role in roles:
140                     self.logger.debug("Role name: {0}".format(role))
141                     if self.db.is_chroot_role(role):
142                         self.logger.debug("Found a chroot role attached to the {0} user!".format(user_info["name"]))
143                         self.key_handler(user_info["name"], "Chroot", 'cloud.chroot', key)
144
145                     if role == "linux_user":
146                         self.logger.debug("Found a Linux user role attached to the {0} user!".format(user_info["name"]))
147                         self.key_handler(user_info["name"], "Linux", 'cloud.linuxuser', key)
148             except Exception as ex:
149                 self.logger.error("Internal error: {0}".format(ex))
150                 return False, ex
151             finally:
152                 state_close, message_close = self._close_db()
153                 if not state_close:
154                     self._close_db()
155             return True, ""
156         else:
157             return False, message_open
158
159     def key_handler(self, username, user_type, list_name, key):
160         cmc = cmclient.CMClient()
161         user_list = cmc.get_property(list_name)
162         user_list = json.loads(user_list)
163         self.logger.debug("{0} user list before the change: {1}".format(user_type, json.dumps(user_list)))
164         if user_list:
165             self.logger.debug("The {0} user list exists!".format(user_type))
166             for val in user_list:
167                 if val["name"] == username:
168                     val["public_key"] = key
169                     break
170             self.logger.debug("{0} user list after the change: {1}".format(user_type, json.dumps(user_list)))
171             cmc.set_property(list_name, json.dumps(user_list))