Coverage for girder/api/v1/user: 97%

# Coverage for girder/api/v1/user : 97%

## 124 statements 120 run 4 missing 0 excluded

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | #!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright 2013 Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### import base64 import cherrypy import json from ..rest import Resource, RestException, AccessException, loadmodel from ..describe import Description from girder.constants import AccessType, SettingKey from girder.models.token import genToken from girder.utility import mail_utils class User(Resource): """API Endpoint for users in the system.""" def __init__(self): self.resourceName = 'user' self.COOKIE_LIFETIME = int(self.model('setting').get( SettingKey.COOKIE_LIFETIME, default=180)) self.route('DELETE', ('authentication',), self.logout) self.route('DELETE', (':id',), self.deleteUser) self.route('GET', (), self.find) self.route('GET', ('me',), self.getMe) self.route('GET', ('authentication',), self.login) self.route('GET', (':id',), self.getUser) self.route('POST', (), self.createUser) self.route('PUT', (':id',), self.updateUser) self.route('PUT', ('password',), self.changePassword) self.route('DELETE', ('password',), self.resetPassword) def _sendAuthTokenCookie(self, user): """ Helper method to send the authentication cookie """ token = self.model('token').createToken(user, days=self.COOKIE_LIFETIME) cookie = cherrypy.response.cookie cookie['authToken'] = json.dumps({ 'userId': str(user['_id']), 'token': str(token['_id']) }) cookie['authToken']['path'] = '/' cookie['authToken']['expires'] = self.COOKIE_LIFETIME * 3600 * 24 return token def _deleteAuthTokenCookie(self): """ Helper method to kill the authentication cookie """ cookie = cherrypy.response.cookie cookie['authToken'] = '' cookie['authToken']['path'] = '/' cookie['authToken']['expires'] = 0 def find(self, params): """ Get a list of users. You can pass a "text" parameter to filter the users by a full text search string. :param [text]: Full text search. :param limit: The result set size limit, default=50. :param offset: Offset into the results, default=0. :param sort: The field to sort by, default=name. :param sortdir: 1 for ascending, -1 for descending, default=1. """ limit, offset, sort = self.getPagingParameters(params, 'lastName') currentUser = self.getCurrentUser() return [self.model('user').filter(user, currentUser) for user in self.model('user').search( text=params.get('text'), user=currentUser, offset=offset, limit=limit, sort=sort)] find.description = ( Description('List or search for users.') .responseClass('User') .param('text', "Pass this to perform a full text search for items.", required=False) .param('limit', "Result set size limit (default=50).", required=False, dataType='int') .param('offset', "Offset into result set (default=0).", required=False, dataType='int') .param('sort', "Field to sort the user list by (default=lastName)", required=False) .param('sortdir', "1 for ascending, -1 for descending (default=1)", required=False, dataType='int')) @loadmodel(map={'id': 'userToGet'}, model='user', level=AccessType.READ) def getUser(self, userToGet, params): currentUser = self.getCurrentUser() return self.model('user').filter(userToGet, currentUser) getUser.description = ( Description('Get a user by ID.') .responseClass('User') .param('id', 'The ID of the user.', paramType='path') .errorResponse('ID was invalid.') .errorResponse('You do not have permission to see this user.', 403)) def getMe(self, params): currentUser = self.getCurrentUser() return self.model('user').filter(currentUser, currentUser) getMe.description = ( Description('Retrieve the currently logged-in user information.') .responseClass('User')) def login(self, params): """ Login endpoint. Sends an auth cookie in the response on success. The caller is expected to use HTTP Basic Authentication when calling this endpoint. """ user, token = self.getCurrentUser(returnToken=True) # Only create and send new cookie if user isn't already sending # a valid one. if not user: authHeader = cherrypy.request.headers.get('Authorization') if not authHeader or not authHeader[0:6] == 'Basic ': raise RestException('Use HTTP Basic Authentication', 401) try: credentials = base64.b64decode(authHeader[6:]) except: raise RestException('Invalid HTTP Authorization header') login, password = credentials.split(':', 1) login = login.lower().strip() loginField = 'email' if '@' in login else 'login' cursor = self.model('user').find({loginField: login}, limit=1) if cursor.count() == 0: raise RestException('Login failed.', code=403) user = cursor.next() if not self.model('password').authenticate(user, password): raise RestException('Login failed.', code=403) setattr(cherrypy.request, 'girderUser', user) token = self._sendAuthTokenCookie(user) return { 'user': self.model('user').filter(user, user), 'authToken': { 'token': token['_id'], 'expires': token['expires'], 'userId': user['_id'] }, 'message': 'Login succeeded.' } login.description = ( Description('Log in to the system.') .notes('Pass your username and password using HTTP Basic Auth. Sends' ' a cookie that should be passed back in future requests.') .errorResponse('Missing Authorization header.', 401) .errorResponse('Invalid login or password.', 403)) def logout(self, params): self._deleteAuthTokenCookie() return {'message': 'Logged out.'} logout.description = ( Description('Log out of the system.') .responseClass('Token') .notes('Attempts to delete your authentication cookie.')) def createUser(self, params): self.requireParams( ('firstName', 'lastName', 'login', 'password', 'email'), params) user = self.model('user').createUser( login=params['login'], password=params['password'], email=params['email'], firstName=params['firstName'], lastName=params['lastName']) setattr(cherrypy.request, 'girderUser', user) self._sendAuthTokenCookie(user) currentUser = self.getCurrentUser() return self.model('user').filter(user, currentUser) createUser.description = ( Description('Create a new user.') .responseClass('User') .param('login', "The user's requested login.") .param('email', "The user's email address.") .param('firstName', "The user's first name.") .param('lastName', "The user's last name.") .param('password', "The user's requested password") .errorResponse('A parameter was invalid, or the specified login or' ' email already exists in the system.')) @loadmodel(map={'id': 'userToDelete'}, model='user', level=AccessType.ADMIN) def deleteUser(self, userToDelete, params): self.model('user').remove(userToDelete) return {'message': 'Deleted user %s.' % userToDelete['login']} deleteUser.description = ( Description('Delete a user by ID.') .param('id', 'The ID of the user.', paramType='path') .errorResponse('ID was invalid.') .errorResponse('You do not have permission to delete this user.', 403)) @loadmodel(map={'id': 'user'}, model='user', level=AccessType.WRITE) def updateUser(self, user, params): self.requireParams(('firstName', 'lastName', 'email'), params) user['firstName'] = params['firstName'] user['lastName'] = params['lastName'] user['email'] = params['email'] currentUser = self.getCurrentUser() # Only admins can change admin state if 'admin' in params: newAdminState = params['admin'] == 'true' if currentUser['admin']: user['admin'] = newAdminState else: if newAdminState != user['admin']: raise AccessException('Only admins may change admin state.') savedUser = self.model('user').save(user) return self.model('user').filter(savedUser, currentUser) updateUser.description = ( Description("Update a user's information.") .param('id', 'The ID of the user.', paramType='path') .param('firstName', 'First name of the user.') .param('lastName', 'Last name of the user.') .param('email', 'The email of the user.') .param('admin', 'Is the user a site admin (admin access required)', required=False, dataType='boolean') .errorResponse() .errorResponse('You do not have write access for this user.', 403) .errorResponse('Must be an admin to create an admin.', 403)) def changePassword(self, params): self.requireParams(('old', 'new'), params) user = self.getCurrentUser() if user is None: raise RestException('You are not logged in.', code=401) if not self.model('password').authenticate(user, params['old']): raise RestException('Old password is incorrect.', code=403) self.model('user').setPassword(user, params['new']) return {'message': 'Password changed.'} changePassword.description = ( Description('Change your password.') .param('old', 'Your current password.') .param('new', 'Your new password.') .errorResponse('You are not logged in.', 401) .errorResponse('Your old password is incorrect.', 403) .errorResponse('Your new password is invalid.')) def resetPassword(self, params): self.requireParams(('email',), params) email = params['email'].lower().strip() cursor = self.model('user').find({'email': email}, limit=1) if cursor.count() == 0: raise RestException('That email is not registered.') user = cursor.next() randomPass = genToken(length=12) html = mail_utils.renderTemplate('resetPassword.mako', { 'password': randomPass }) mail_utils.sendEmail(to=email, subject='Girder: Password reset', text=html) self.model('user').setPassword(user, randomPass) return {'message': 'Sent password reset email.'} resetPassword.description = ( Description('Reset a forgotten password via email.') .param('email', 'Your email address.') .errorResponse('That email does not exist in the system.'))