def update_jwt(): """Gets a new JWT from the server""" password = get_private_setting('password') devicename = get_setting('device', 'devicename') if devicename == None or devicename == "": print("Can't get JWT as no devicename is saved. Will register again.") return register(util.rand_str(12)) if password == None or password == "": print("Can't get JWT as no password is saved. Will register again.") return register(util.rand_str(12)) serverUrl = get_setting('server', 'url') url = serverUrl + '/authenticate_device' try: payload = {'password': get_private_setting('password'), 'devicename': get_setting('device', 'devicename') } print("Getting new JWT") r = requests.post(url, data = payload) if r.status_code == 200: j = json.loads(r.text) print("New jwt from server.") set_private_setting('jwt', j['token']) return True elif r.status_code == 401: print("401 when authenticating, will re-register.") return register(util.rand_str(12)) else: print("Error with device authenticating device request.") return False except: print("Error with connecting to server") return False
def test_save_user(self): u = self.uk.users.create_user(email=rand_email(), password=rand_str(14), name="Name") new_name = "Test Name {}".format(rand_str()) user = self.uk.users.get_user(u.id) user.name = new_name user.save() self.assertEqual(user.name, new_name)
def test_update_user(self): extras = {'score': 200} u = self.uk.users.create_user(email=rand_email(), password=rand_str(14), name="Name", extras=extras) new_name = "Test Name {}".format(rand_str()) user = self.uk.users.update_user(u.id, name=new_name) self.assertEqual(user.name, new_name) self.assertEqual(user.extras['score'], extras['score'])
def test_get_current_user(self): email, password = rand_email(), rand_str(14) u = self.uk.users.create_user(email=email, password=password) session = self.uk.users.login_user(email, password) user = self.uk.users.get_current_user(session.token) self.assertEqual(user.id, u.id)
def test_refresh_session(self): email, password = rand_email(), rand_str(14) u = self.uk.users.create_user(email=email, password=password) session1 = self.uk.users.login_user(email, password) session2 = self.uk.users.refresh_session(session1.token) self.assertTrue(hasattr(session2, 'token')) self.assertTrue(hasattr(session2, 'expires_in_secs'))
def test_request_password_reset(self): u = self.uk.users.create_user(email=rand_email(), password=rand_str(14)) try: self.uk.users.request_password_reset(u.email) except Exception as e: self.fail(e)
def store(self, stanza, network, delayed=False, reuseId=None, expire=None): receipt = xmlstream2.extract_receipt(stanza, 'request') if not receipt: if reuseId is not None: _id = reuseId else: _id = util.rand_str(30, util.CHARSBOX_AZN_LOWERCASE) else: _id = receipt['id'] # cancel any previous delayed call self._cancel_pending(_id) # WARNING using deepcopy is not safe if delayed: # delay our call self._pending_offline[_id] = (reactor.callLater( self.OFFLINE_STORE_DELAY, self._store, stanza=deepcopy(stanza), network=network, _id=_id, expire=expire), stanza, (network, _id, expire)) return _id else: return self._store(deepcopy(stanza), network, _id, expire)
def test_custom_audit_log_invalid_actor(self): # create a test user email = rand_email() user = self.uk.users.create_user(email=email, password=rand_str(14)) self.assertRaises(error.InvalidRequestError, self.uk.logs.log_event, actor='NOT_A_VAlID_USER_ID', actor_ip='::1', actor_useragent='TestLogs', actee=user.id, action='test.custom_audit_log', details='Testing custom audit logs')
def store(self, stanza, network, delayed=False, reuseId=None, expire=None): receipt = xmlstream2.extract_receipt(stanza, "request") if not receipt: if reuseId is not None: _id = reuseId else: _id = util.rand_str(30, util.CHARSBOX_AZN_LOWERCASE) else: _id = receipt["id"] # cancel any previous delayed call self._cancel_pending(_id) if delayed: # delay our call self._pending_offline[_id] = ( reactor.callLater( self.OFFLINE_STORE_DELAY, self._store, stanza=stanza, network=network, _id=_id, expire=expire ), stanza, (network, _id, expire), ) return _id else: return self._store(stanza, network, _id, expire)
def test_accept_invite(self): email = rand_email() invite = self.uk.invites.create_invite(to_email=email) user = self.uk.users.create_user(email=rand_email(), password=rand_str(14)) invite = self.uk.invites.accept_invite(user.id, invite.token_raw) self.assertTrue(invite.accepted)
def test_create_user(self): email = rand_email() extras = {'score': 100} user = self.uk.users.create_user(email=email, password=rand_str(14), extras=extras) self.assertEqual(user.email, email.lower()) self.assertEqual(user.extras['score'], extras['score'])
def buildAvatar(self, avatarId): # The hostname will be overwritten by the SASLReceivingInitializer # We put in example.com to keep the JID constructor from complaining if isinstance(avatarId, jid.JID): _jid = avatarId # generate random resource _jid.resource = util.rand_str(8, util.CHARSBOX_AZN_UPPERCASE) else: userid, resource = util.split_userid(avatarId) _jid = jid.JID(tuple=(userid, "example.com", resource)) return xmlstream2.XMPPUser(_jid)
def _store(self, stanza, network, _id, expire): # remove ourselves from pending if not self._exiting: try: del self._pending_offline[_id] except: pass # WARNING using deepcopy is not safe from copy import deepcopy stanza = deepcopy(stanza) # if no receipt request is found, generate a unique id for the message receipt = xmlstream2.extract_receipt(stanza, "request") if not receipt: if _id: stanza["id"] = _id else: stanza["id"] = util.rand_str(30, util.CHARSBOX_AZN_LOWERCASE) # store message for bare network JID jid_to = jid.JID(stanza["to"]) # WARNING this is actually useless jid_to.host = network stanza["to"] = jid_to.userhost() # sender JID should be a network JID jid_from = jid.JID(stanza["from"]) # WARNING this is actually useless jid_from.host = network stanza["from"] = jid_from.full() try: del stanza["origin"] except KeyError: pass # safe uri for persistance stanza.uri = stanza.defaultUri = sm.C2SManager.namespace log.debug("storing offline message for %s" % (stanza["to"],)) try: d = self._do_store(stanza, expire) if self._exiting: return d except: # TODO log this import traceback traceback.print_exc() return stanza["id"]
def test_disable_user(self): u = self.uk.users.create_user(email=rand_email(), password=rand_str(14)) # Test the disable_user() function disabled = True user = self.uk.users.disable_user(u.id, disabled) self.assertEqual(user.disabled, disabled) # Return to original value (and test the user.disable() method) disabled = False user.disable(disabled) self.assertEqual(user.disabled, disabled)
def test_login_and_logout_user(self): email, password = rand_email(), rand_str(14) u = self.uk.users.create_user(email=email, password=password) # Test login session = self.uk.users.login_user(email, password) self.assertTrue(hasattr(session, 'token')) # Test logout try: self.uk.users.logout_user(session.token) except Exception as e: self.fail(e)
def test_custom_audit_log(self): # create a test user email = rand_email() user = self.uk.users.create_user(email=email, password=rand_str(14)) # create a test audit log log = self.uk.logs.log_event(actor=user.id, actor_ip='::1', actor_useragent='TestLogs', actee=user.id, action='test.custom_audit_log', details='Testing custom audit logs') self.assertEqual(log.actor, user.id) self.assertEqual(log.actor_ip, '::1') self.assertEqual(log.actor_useragent, 'TestLogs') self.assertEqual(log.actee, user.id) self.assertEqual(log.action, 'test.custom_audit_log') self.assertEqual(log.details, 'Testing custom audit logs')
def _store(self, stanza, network, _id, expire): # remove ourselves from pending if not self._exiting: try: del self._pending_offline[_id] except: pass # WARNING using deepcopy is not safe from copy import deepcopy stanza = deepcopy(stanza) # if no receipt request is found, generate a unique id for the message receipt = xmlstream2.extract_receipt(stanza, 'request') if not receipt: if _id: stanza['id'] = _id else: stanza['id'] = util.rand_str(30, util.CHARSBOX_AZN_LOWERCASE) # store message for bare network JID jid_to = jid.JID(stanza['to']) # WARNING this is actually useless jid_to.host = network stanza['to'] = jid_to.userhost() # sender JID should be a network JID jid_from = jid.JID(stanza['from']) # WARNING this is actually useless jid_from.host = network stanza['from'] = jid_from.full() try: del stanza['origin'] except KeyError: pass # safe uri for persistance stanza.uri = stanza.defaultUri = sm.C2SManager.namespace log.debug("storing offline message for %s" % (stanza['to'], )) try: d = self._do_store(stanza, expire) if self._exiting: return d except: # TODO log this import traceback traceback.print_exc() return stanza['id']
def register(devicename = None): """Register device using given device name, if none is givne then creates a random one. password is saved to private config file.""" if devicename == None or devicename == "": devicename = util.rand_str(12) group = get_setting('device', 'group') if group == None or group == "": print("No group is set. Set group in device section in config file.") return False password = util.rand_str(20) serverUrl = get_setting('server', 'url') url = serverUrl + '/api/v1/devices' try: payload = {'password': password, 'devicename': devicename, 'group': group} r = requests.post(url, data=payload) if r.status_code == 200: j = json.loads(r.text) set_private_setting('password', password) set_private_setting('jwt', j['token']) set_setting('device', 'devicename', devicename) return True elif r.status_code == 400: j = json.loads(r.text) print('Error with register') print(j['messages']) return False else: print("Error with register.") return False except Exception as e: print("Error with register") print(e) return False
def register(self, key, code=None): global dbpool if not code: code = util.rand_str(self.VALIDATION_CODE_LENGTH, util.CHARSBOX_NUMBERS) def _callback(result, callback, code): callback.callback(code) def _errback(failure, callback): callback.errback(failure) callback = defer.Deferred() d = dbpool.runOperation('INSERT INTO validations VALUES (?, ?, sysdate())', (key, code, )) d.addCallback(_callback, callback, code) d.addErrback(_errback, callback) return callback
def setUp(self): super(TestUsers, self).setUp() # Create a user for use with various tests user_data = { 'email': rand_email(), 'password': rand_str(14), 'extras': { 'score': 100 }, } body = widget_body('post', 'users', user_data) resp = self.uk.widget.proxy(body) self.user1 = resp.response_dict['data']['user'] self.user1_password = user_data['password'] self.user1_token = resp.response_dict['data']['session']['token'] self.user1_token_private = resp.token_private
def test_wprox_create_user(self): user_data = { 'email': rand_email(), 'password': rand_str(14), 'extras': { 'score': 100 }, } body = widget_body('post', 'users', user_data) resp = self.uk.widget.proxy(body) user = resp.response_dict['data']['user'] # Should create and return the new user self.assertEqual(user['email'], user_data['email'].lower()) self.assertEqual(user['extras']['score'], user_data['extras']['score']) # Should contain correct JSON string in resp.response response_str = json.dumps(resp.response_dict) self.assertEqual(resp.response, response_str)
def run(self): # Craete folder to save images in imagesFolder = os.path.join(allImagesFolder, (str(int(time.time())))+util.rand_str()) os.makedirs(imagesFolder) # Save images imageIndex = 0 for i in self.images: imageName = str(imageIndex).zfill(6) + '.jpg' imageIndex += 1 cv2.imwrite(os.path.join(imagesFolder, imageName), np.uint8(i)) # Render into avi inputF = os.path.join(imagesFolder, "%06d.jpg") outputF = os.path.join(imagesFolder, "file.avi") command = "/usr/local/bin/ffmpeg -r 5 -i {i} {o}".format( i = inputF, o = outputF) print(command) os.system(command) util.save_data(self.data, outputF) shutil.rmtree(imagesFolder)
def render_POST(self, request): #log.debug("request from %s: %s" % (self.userid, request.requestHeaders)) # check mime type mime = request.getHeader('content-type') if mime not in self.config['upload']['accept_content']: return self._quick_response(request, 406, 'unacceptable content type') # check length length = request.getHeader('content-length') if length != None: length = long(length) if length <= self.config['upload']['max_size']: # store file to storage # TODO convert to file-object management for less memory consumption data = request.content.read() if len(data) == length: fileid = util.rand_str(40) filename = self.fileserver.storage.store_data(fileid, mime, data) if filename: log.debug("file stored to disk (filename=%s, fileid=%s)" % (filename, fileid)) request.setHeader('content-type', 'text/url') return str(self.config['upload']['url']) % (fileid, ) else: log.error("error storing file") return self._quick_response(request, 500, 'unable to store file') else: log.warn("file length not matching content-length header (%d/%d)" % (len(data), length)) return self._quick_response(request, 400, 'bad request') else: log.warn("file too big (%d bytes)" % length) return self._quick_response(request, 413, 'request too large') else: log.warn("content-length header not found") return self._quick_response(request, 411, 'content length not declared')
def resolve_output_map(tmp_dir,resource_map): m={} print rand_str() for r in resource_map: m[resource_map[r]['mapsTo']] = os.path.join(tmp_dir,resource_map[r]['name']+rand_str()+'.'+resource_map[r]['type']) return m
def _rand_name_in_dir(dir): '''returns a str not found in a dir''' fname = rand_str(8) while fname in os.listdir(dir): fname = rand_str(8) return fname
def test_get_user(self): u = self.uk.users.create_user(email=rand_email(), password=rand_str(14)) user = self.uk.users.get_user(u.id) self.assertEqual(user.id, u.id)