Added seed code for access-management.
[ta/access-management.git] / src / access_management / rest-plugin / users_passwords.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 import json
16 import crypt
17 import time
18 from am_api_base import *
19 from keystoneauth1 import exceptions
20 from cmframework.apis import cmclient
21
22
23 class UsersPasswords(AMApiBase):
24
25     """
26     User reset password operations
27
28     .. :quickref: User passwords;User reset password operations
29
30     .. http:post:: /am/v1/users/passwords
31
32     **Start User reset password**
33
34     **Example request**:
35
36     .. sourcecode:: http
37
38         POST am/v1/users/passwords HTTP/1.1
39         Host: haproxyvip:61200
40         Accept: application/json
41         {
42             "user": <uuid> or <username>
43             "npassword: "Passwd_1"
44         }
45
46     :> json string user: The user's id or name.
47     :> json string npassword: The user's new password
48
49     **Example response**:
50
51     .. sourcecode:: http
52
53         HTTP/1.1 200 OK
54         {
55             "code": 0,
56             "description": "Users password reset success."
57         }
58
59     :> json int code: the status code
60     :> json string description: the error description, present if code is non zero
61     """
62
63     endpoints = ['users/passwords']
64     parser_arguments = ['user',
65                         'npassword']
66
67     def post(self):
68         self.logger.info("Received a reset password request!")
69         args = self.parse_args()
70
71         passstate = self.passwd_validator(args["npassword"])
72         if passstate is not None:
73             self.logger.error(passstate)
74             return AMApiBase.embed_data({}, 1, passstate)
75
76         state, user_info = self.get_uuid_and_name(args["user"])
77         if state:
78             status, message = self._reset_pass(user_info, args['npassword'])
79
80             if status:
81                 self.logger.info("Password reset successfully!")
82                 return AMApiBase.embed_data({}, 0, "Password reset successfully!")
83             else:
84                 self.logger.error("Internal error: {0}".format(message))
85                 return AMApiBase.embed_data({}, 1, message)
86         else:
87             self.logger.error(user_info)
88             return AMApiBase.embed_data({}, 1, user_info)
89
90     def _reset_pass(self, user_info, passwd):
91         try:
92             reset = self.keystone.users.update(user_info["id"], password=passwd)
93         except exceptions.http.NotFound as ex:
94             self.logger.error("{0}".format(ex))
95             return False, "This user does not exist in the keystone!"
96         except Exception as ex:
97             self.logger.error("{0}".format(ex))
98             return False, "{0}".format(ex)
99
100         self.logger.info(reset)
101         passwd_hash = crypt.crypt(passwd, crypt.mksalt(crypt.METHOD_SHA512))
102
103         state_open, message_open = self._open_db()
104         if state_open:
105             try:
106                 roles = self.db.get_user_roles(user_info["id"])
107                 for role in roles:
108                     if self.db.is_chroot_role(role):
109                         # if the user has a chroot account, change the pwd of that also
110                         for x in range(3):
111                             self.linux_chroot_pass_handling(user_info["name"], "Chroot", "cloud.chroot", passwd_hash)
112                             time.sleep(5)
113                             if self.check_chroot_linux_pass_state(user_info["name"], "cloud.chroot", passwd_hash):
114                                 return True, "Success"
115                         return False, "The user handler is busy, please try again."
116                     if role == "linux_user":
117                         # if the user has a Linux user account, change the pwd of that also
118                         for x in range(3):
119                             self.linux_chroot_pass_handling(user_info["name"], "Linux", "cloud.linuxuser", passwd_hash)
120                             time.sleep(5)
121                             if self.check_chroot_linux_pass_state(user_info["name"], "cloud.linuxuser", passwd_hash):
122                                 return True, "Success"
123                         return False, "The user handler is busy, please try again."
124             except Exception as ex:
125                 self.logger.error("Internal error: {0}".format(ex))
126                 return AMApiBase.embed_data({}, 1, "Internal error: {0}".format(ex))
127             finally:
128                 state_close, message_close = self._close_db()
129                 if not state_close:
130                     self._close_db()
131             return True, reset
132         else:
133             return False, message_open
134
135     def linux_chroot_pass_handling(self, username, user_type, list_name, passwd):
136         cmc = cmclient.CMClient()
137         user_list = cmc.get_property(list_name)
138         user_list = json.loads(user_list)
139         self.logger.debug("{0} user list before the change: {1}".format(user_type, json.dumps(user_list)))
140         if user_list is not None:
141             self.logger.debug("The {0} user list exist!".format(user_type))
142             for val in user_list:
143                 if val["name"] == username:
144                     val["password"] = passwd
145                     break
146             self.logger.debug("{0} user list after the change: {1}".format(user_type, json.dumps(user_list)))
147             cmc.set_property(list_name, json.dumps(user_list))
148
149     def check_chroot_linux_pass_state(self, username, list_name, password):
150         cmc = cmclient.CMClient()
151         user_list = cmc.get_property(list_name)
152         user_list = json.loads(user_list)
153         self.logger.debug("Start the user list check")
154         for val in user_list:
155             if val["name"] == username and val["password"] == password:
156                 self.logger.debug("{0} user's password changed!".format(username))
157                 return True
158         self.logger.debug("{0} user's password is not changed!".format(username))
159         return False