def login(self, params): 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('Girder-Authorization') if not authHeader: 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:]).decode('utf8') if ':' not in credentials: raise TypeError except Exception: raise RestException('Invalid HTTP Authorization header', 401) login, password = credentials.split(':', 1) user = self.model('user').authenticate(login, password) setCurrentUser(user) token = self.sendAuthTokenCookie(user) return { 'user': self.model('user').filter(user, user), 'authToken': { 'token': token['_id'], 'expires': token['expires'], 'scope': token['scope'] }, 'message': 'Login succeeded.' }
def createUser(self, params): self.requireParams( ('firstName', 'lastName', 'login', 'password', 'email'), params) currentUser = self.getCurrentUser() regPolicy = self.model('setting').get(SettingKey.REGISTRATION_POLICY) if currentUser is not None and currentUser['admin']: admin = self.boolParam('admin', params, default=False) else: admin = False if regPolicy == 'closed': raise RestException( 'Registration on this instance is closed. Contact an ' 'administrator to create an account for you.') user = self.model('user').createUser(login=params['login'], password=params['password'], email=params['email'], firstName=params['firstName'], lastName=params['lastName'], admin=admin) outputUser = self.model('user').filter(user, user) if not currentUser and self.model('user').canLogin(user): setCurrentUser(user) token = self.sendAuthTokenCookie(user) outputUser['authToken'] = { 'token': token['_id'], 'expires': token['expires'] } return outputUser
def createUser(self, login, email, firstName, lastName, password, admin): currentUser = self.getCurrentUser() regPolicy = Setting().get(SettingKey.REGISTRATION_POLICY) if not currentUser or not currentUser['admin']: admin = False if regPolicy == 'closed': raise RestException( 'Registration on this instance is closed. Contact an ' 'administrator to create an account for you.') user = self._model.createUser(login=login, password=password, email=email, firstName=firstName, lastName=lastName, admin=admin) if not currentUser and self._model.canLogin(user): setCurrentUser(user) token = self.sendAuthTokenCookie(user) user['authToken'] = { 'token': token['_id'], 'expires': token['expires'] } return user
def verifyEmail(self, user, token): token = Token().load(token, user=user, level=AccessType.ADMIN, objectId=False, exc=True) delta = (token['expires'] - datetime.datetime.utcnow()).total_seconds() hasScope = Token().hasScope(token, TokenScope.EMAIL_VERIFICATION) if token.get('userId') != user['_id'] or delta <= 0 or not hasScope: raise AccessException('The token is invalid or expired.') user['emailVerified'] = True Token().remove(token) user = self._model.save(user) if self._model.canLogin(user): setCurrentUser(user) authToken = self.sendAuthTokenCookie(user) return { 'user': self._model.filter(user, user), 'authToken': { 'token': authToken['_id'], 'expires': authToken['expires'], 'scope': authToken['scope'] }, 'message': 'Email verification succeeded.' } else: return { 'user': self._model.filter(user, user), 'message': 'Email verification succeeded.' }
def verifyEmail(self, user, token): token = Token().load( token, user=user, level=AccessType.ADMIN, objectId=False, exc=True) delta = (token['expires'] - datetime.datetime.utcnow()).total_seconds() hasScope = Token().hasScope(token, TokenScope.EMAIL_VERIFICATION) if token.get('userId') != user['_id'] or delta <= 0 or not hasScope: raise AccessException('The token is invalid or expired.') user['emailVerified'] = True Token().remove(token) user = self._model.save(user) if self._model.canLogin(user): setCurrentUser(user) authToken = self.sendAuthTokenCookie(user) return { 'user': self._model.filter(user, user), 'authToken': { 'token': authToken['_id'], 'expires': authToken['expires'], 'scope': authToken['scope'] }, 'message': 'Email verification succeeded.' } else: return { 'user': self._model.filter(user, user), 'message': 'Email verification succeeded.' }
def _authorizeUploadStep(event): """ Called before any requests dealing with partially completed uploads. Sets the request thread user to the authorized upload token creator if the requested upload is an authorized upload. """ token = getCurrentToken() uploadId = ObjectId(event.info['params'].get('uploadId')) if token and 'authorizedUploadId' in token and token['authorizedUploadId'] == uploadId: user = ModelImporter.model('user').load(token['userId'], force=True) setCurrentUser(user)
def test_genHandlerToRunDockerCLI(admin, folder, file, adminToken, mocker): mocker.patch('girder.api.rest.getCurrentToken').return_value = adminToken mocker.patch('girder.api.rest.getApiUrl').return_value = '/api/v1' from girder.api import rest from slicer_cli_web import docker_resource from slicer_cli_web import rest_slicer_cli from slicer_cli_web.models import CLIItem from girder.models.item import Item rest.setCurrentUser(admin) xmlpath = os.path.join(os.path.dirname(__file__), 'data', 'ExampleSpec.xml') girderCLIItem = Item().createItem('data', admin, folder) Item().setMetadata( girderCLIItem, dict(slicerCLIType='task', type='python', image='dockerImage', digest='dockerImage@sha256:abc', xml=open(xmlpath, 'rb').read())) resource = docker_resource.DockerResource('test') item = CLIItem(girderCLIItem) handlerFunc = rest_slicer_cli.genHandlerToRunDockerCLI(item) assert handlerFunc is not None job = handlerFunc(resource, params={ 'inputImageFile': str(file['_id']), 'secondImageFile': str(file['_id']), 'outputStainImageFile_1_folder': str(folder['_id']), 'outputStainImageFile_1': 'sample1.png', 'outputStainImageFile_2_folder': str(folder['_id']), 'outputStainImageFile_2_name': 'sample2.png', 'stainColor_1': '[0.5, 0.5, 0.5]', 'stainColor_2': '[0.2, 0.3, 0.4]', 'returnparameterfile_folder': str(folder['_id']), 'returnparameterfile': 'output.data', }) kwargs = json.loads(job['kwargs']) assert 'container_args' in kwargs assert 'image' in kwargs assert 'pull_image' in kwargs assert kwargs['image'] == 'dockerImage@sha256:abc' assert kwargs['pull_image'] == 'if-not-present' container_args = kwargs['container_args'] assert container_args[0] == 'data'
def _authorizeInitUpload(event): """ Called when initializing an upload, prior to the default handler. Checks if the user is passing an authorized upload token, and if so, sets the current request-thread user to be whoever created the token. """ token = getCurrentToken() params = event.info['params'] tokenModel = ModelImporter.model('token') parentType = params.get('parentType') parentId = params.get('parentId', '') requiredScopes = {TOKEN_SCOPE_AUTHORIZED_UPLOAD, 'authorized_upload_folder_%s' % parentId} if parentType == 'folder' and tokenModel.hasScope(token=token, scope=requiredScopes): user = ModelImporter.model('user').load(token['userId'], force=True) setCurrentUser(user)
def _authorizeUploadStep(event): """ Called before any requests dealing with partially completed uploads. Sets the request thread user to the authorized upload token creator if the requested upload is an authorized upload. """ token = getCurrentToken() try: uploadId = ObjectId(event.info['params'].get('uploadId', '')) except InvalidId: # Take no action, 'uploadId' will be validated again by the endpoint return if token and 'authorizedUploadId' in token and token[ 'authorizedUploadId'] == uploadId: user = User().load(token['userId'], force=True) setCurrentUser(user)
def anonymousLogin(self, params): """Log in using the "anonymous user".""" user_model = self.model('user') user = user_model.findOne({'login': self.anonuser}) user = user_model.filter(user, user) setCurrentUser(user) token = self.sendAuthTokenCookie(user) return { 'user': self.model('user').filter(user, user), 'authToken': { 'token': token['_id'], 'expires': token['expires'], 'scope': token['scope'] }, 'message': 'Anonymous login succeeded.' }
def login(self): if not Setting().get(SettingKey.ENABLE_PASSWORD_LOGIN): raise RestException('Password login is disabled on this instance.') 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: authHeader = cherrypy.request.headers.get( 'Girder-Authorization') if not authHeader or not authHeader[0:6] == 'Basic ': raise RestException('Use HTTP Basic Authentication', 401) try: credentials = base64.b64decode(authHeader[6:]).decode('utf8') if ':' not in credentials: raise TypeError except Exception: raise RestException('Invalid HTTP Authorization header', 401) login, password = credentials.split(':', 1) otpToken = cherrypy.request.headers.get('Girder-OTP') user = self._model.authenticate(login, password, otpToken) setCurrentUser(user) token = self.sendAuthTokenCookie(user) return { 'user': self._model.filter(user, user), 'authToken': { 'token': token['_id'], 'expires': token['expires'], 'scope': token['scope'] }, 'message': 'Login succeeded.' }
def login(self): if not Setting().get(SettingKey.ENABLE_PASSWORD_LOGIN): raise RestException('Password login is disabled on this instance.') 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('Girder-Authorization') if not authHeader: 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:]).decode('utf8') if ':' not in credentials: raise TypeError except Exception: raise RestException('Invalid HTTP Authorization header', 401) login, password = credentials.split(':', 1) otpToken = cherrypy.request.headers.get('Girder-OTP') user = self._model.authenticate(login, password, otpToken) setCurrentUser(user) token = self.sendAuthTokenCookie(user) return { 'user': self._model.filter(user, user), 'authToken': { 'token': token['_id'], 'expires': token['expires'], 'scope': token['scope'] }, 'message': 'Login succeeded.' }
def setUp(self): import datetime from girder.api import rest from girder.plugins import worker from girder.plugins.worker import utils as worker_utils from girder.models.file import File from girder.models.folder import Folder from girder.models.item import Item from girder.models.user import User base.TestCase.setUp(self) self.admin = User().createUser('admin', 'passwd', 'admin', 'admin', '*****@*****.**') self.folder = Folder().createFolder(self.admin, 'folder', parentType='user') self.item = Item().createItem('item', self.admin, self.folder) self.file = File().createFile(self.admin, self.item, 'file', 7, self.assetstore) # Mock several functions so we can fake creating jobs def getCurrentToken(): return { '_id': str(self.admin['_id']), 'expires': datetime.datetime.utcnow() + datetime.timedelta(hours=1) } def getWorkerApiUrl(): return '/api/v1' self._origRestGetCurrentToken = rest.getCurrentToken self._origRestGetApiUrl = rest.getApiUrl self._origWorkerGetWorkerApiUrl = worker.getWorkerApiUrl rest.getCurrentToken = getCurrentToken rest.getApiUrl = lambda x: '/api/v1' rest.setCurrentUser(self.admin) worker.getWorkerApiUrl = worker_utils.getWorkerApiUrl = getWorkerApiUrl
def createUser(self, login, email, firstName, lastName, password, admin): currentUser = self.getCurrentUser() regPolicy = Setting().get(SettingKey.REGISTRATION_POLICY) if not currentUser or not currentUser['admin']: admin = False if regPolicy == 'closed': raise RestException( 'Registration on this instance is closed. Contact an ' 'administrator to create an account for you.') user = self._model.createUser( login=login, password=password, email=email, firstName=firstName, lastName=lastName, admin=admin) if not currentUser and self._model.canLogin(user): setCurrentUser(user) token = self.sendAuthTokenCookie(user) user['authToken'] = { 'token': token['_id'], 'expires': token['expires'] } return user