def decode_mac_id(self, request, tokenid): """Decode a MACAuth token id into its userid and MAC secret key. This method determines the appropriate secrets to use for the given request, then passes them on to tokenlib to handle the given MAC id token. If the id is invalid then ValueError will be raised. """ # There might be multiple secrets in use, if we're in the # process of transitioning from one to another. Try each # until we find one that works. secrets = self._get_token_secrets(request) for secret in secrets: try: data = tokenlib.parse_token(tokenid, secret=secret) userid = data["uid"] key = tokenlib.get_token_secret(tokenid, secret=secret) break except (ValueError, KeyError): pass else: log_cef("Authentication Failed: invalid MAC id", 5, request.environ, request.registry.settings, "", signature=AUTH_FAILURE) raise ValueError("invalid MAC id") return userid, key
def decode_hawk_id(self, request, tokenid): """Decode a Hawk token id into its userid and secret key. This method determines the appropriate secrets to use for the given request, then passes them on to tokenlib to handle the given Hawk token. If the id is invalid then ValueError will be raised. """ # There might be multiple secrets in use, if we're in the # process of transitioning from one to another. Try each # until we find one that works. node_name = self._get_node_name(request) secrets = self._get_token_secrets(node_name) for secret in secrets: try: data = tokenlib.parse_token(tokenid, secret=secret) userid = data["uid"] token_node_name = data["node"] if token_node_name != node_name: raise ValueError("incorrect node for this token") key = tokenlib.get_derived_secret(tokenid, secret=secret) break except (ValueError, KeyError): pass else: logger.warn("Authentication Failed: invalid hawk id") raise ValueError("invalid Hawk id") return userid, key
def send_message(): token = request.form["token"] print(token) if token is not None: try: parsed_token = tokenlib.parse_token(token, secret=super_duper_secret) if parsed_token['admin'] is None: return json.dumos({ "succress": False, "errors": "User is not an admin" }) message = request.form['message'] user_id = request.form['user_id'] from models.users import Message from models.users import User if user_id is not None: admin = db.session.query(User).filter_by(admin=True).first() new_message = Message(user_id, admin.id, message) db.session.add(new_message) db.session.commit() return json.dumps({"success": True}) except ValueError: pass return json.dumps({"success": False})
def show_profile(username): name, surname = username.split('.') from models.users import Profile profile = db.session.query(Profile).filter_by(name=name, surname=surname).first() if profile is None: abort(404) if len(request.args) == 0: return render_template('index.html', profile=profile) token = request.args["token"] if token != "": try: parsed_token = tokenlib.parse_token(token, secret=super_duper_secret) prof = db.session.query(Profile).filter_by( user_id=parsed_token['id']).first() from models.users import Message msg = db.session.query(Message).filter_by( user_to=parsed_token['id']) if (prof.name == name and prof.surname == surname): res = client.query('weather in Vilnius') return render_template('index.html', profile=profile, admin=True, weather=res.pods, message=msg) else: return render_template('index.html', profile=profile) except ValueError: return render_template('index.html', profile=profile)
def test_convenience_functions(self): token = tokenlib.make_token({"hello": "world"}) self.assertEquals(tokenlib.parse_token(token)["hello"], "world") self.assertRaises(ValueError, tokenlib.parse_token, token, secret="X") self.assertEquals(tokenlib.get_token_secret(token), tokenlib.get_token_secret(token)) self.assertNotEquals(tokenlib.get_token_secret(token), tokenlib.get_token_secret(token, secret="X"))
def check_public_token(context, request): """ Check and parse token for exceptions """ public_token = request.cookies.get(TOKEN_COOKIE_NAME) if public_token is None: return NOTGOOD try: secret = IAnnotations(context)[SECRET_KEY] tokenlib.parse_token(public_token, secret=secret) return OK except ExpiredTokenError: return EXPIRED except Exception: return NOTGOOD return NOTGOOD
def test_purging_of_old_user_records(self): # Make some old user records. service = "sync-1.1" email = "*****@*****.**" user = self.backend.allocate_user(service, email, client_state="aa", generation=123) self.backend.update_user(service, user, client_state="bb", generation=456, keys_changed_at=450) self.backend.update_user(service, user, client_state="cc", generation=789) user_records = list(self.backend.get_user_records(service, email)) self.assertEqual(len(user_records), 3) user = self.backend.get_user(service, email) self.assertEquals(user["client_state"], "cc") self.assertEquals(len(user["old_client_states"]), 2) # The default grace-period should prevent any cleanup. self.assertTrue(purge_old_records(self.ini_file)) user_records = list(self.backend.get_user_records(service, email)) self.assertEqual(len(user_records), 3) self.assertEqual(len(self.service_requests), 0) # With no grace period, we should cleanup two old records. self.assertTrue(purge_old_records(self.ini_file, grace_period=0)) user_records = list(self.backend.get_user_records(service, email)) self.assertEqual(len(user_records), 1) self.assertEqual(len(self.service_requests), 2) # Check that the proper delete requests were made to the service. secrets = self.config.registry.settings["tokenserver.secrets"] node_secret = secrets.get(self.service_node)[-1] expected_kids = ["0000000000450-uw", "0000000000123-qg"] for i, environ in enumerate(self.service_requests): # They must be to the correct path. self.assertEquals(environ["REQUEST_METHOD"], "DELETE") self.assertTrue(re.match("/1.1/[0-9]+", environ["PATH_INFO"])) # They must have a correct request signature. token = hawkauthlib.get_id(environ) secret = tokenlib.get_derived_secret(token, secret=node_secret) self.assertTrue(hawkauthlib.check_signature(environ, secret)) userdata = tokenlib.parse_token(token, secret=node_secret) self.assertTrue("uid" in userdata) self.assertTrue("node" in userdata) self.assertEqual(userdata["fxa_uid"], "test") self.assertEqual(userdata["fxa_kid"], expected_kids[i]) # Check that the user's current state is unaffected user = self.backend.get_user(service, email) self.assertEquals(user["client_state"], "cc") self.assertEquals(len(user["old_client_states"]), 0)
def save_token(token): id = None data = tokenlib.parse_token(token, secret="I_LIKE_UNICORNS") data_token = { "key": token, "expires": data['expires'], "user_id": data['user_id'], "salt": data['salt'] } if tokens_collection.find({"user_id": data['user_id']}).count() == 0: id = tokens_collection.insert_one(data_token).inserted_id return id
def view_user(): user_id = request.form['user_id'] token = request.form['token'] parsed_token = tokenlib.parse_token(token, secret=super_duper_secret) if parsed_token['admin'] == True: from models.users import Profile prof = db.session.query(Profile).filter_by(user_id=user_id).first() return json.dumps({ "success": True, "profile_url": "/profile/{0}.{1}".format(prof.name, prof.surname) })
def decode_mac_id(self, request, id): """Decode MAC id into MAC key and data dict. This method decodes the given MAC id to give the corresponding MAC secret key and dict of user data. By default it uses the tokenlib library, but plugin instances may override this method with another callable from the config file. If the MAC id is invalid then ValueError will be raised. """ secret = tokenlib.get_token_secret(id) data = tokenlib.parse_token(id) return secret, data
def return_token(): token = flask.request.headers.get("Authorization") try: user_id = tokenlib.parse_token( token, secret=flask.current_app.config["security"]["key"])["user_id"] except tokenlib.errors.ExpiredTokenError as exc: abort("Token expired", 400) except tokenlib.errors.InvalidSignatureError as exc: abort("Invalid token", 401) except tokenlib.errors.MalformedTokenError as exc: abort("Invalid token", 401) return flask.jsonify({"user_id": user_id}), 200
def upload_file(): token = request.form['token'] parsed_token = tokenlib.parse_token(token, secret=super_duper_secret) from models.users import Profile profile = db.session.query(Profile).filter_by( user_id=parsed_token['id']).first() file = request.files['newimage'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) image_url = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(image_url) profile.imageurl = filename db.session.commit() return file.filename
def delete_user(): user_id = request.form['user_id'] token = request.form['token'] parsed_token = tokenlib.parse_token(token, secret=super_duper_secret) if parsed_token['admin'] == True: from models.users import Profile profile = db.session.query(Profile).filter_by(user_id=user_id).first() db.session.delete(profile) from models.users import User user = db.session.query(User).filter_by(id=user_id).first() db.session.delete(user) db.session.commit() return json.dumps({"success": True}) return "Error"
def test_purging_of_old_user_records(self): # Make some old user records. service = "test-1.0" email = "*****@*****.**" user = self.backend.allocate_user(service, email, client_state="a") self.backend.update_user(service, user, client_state="b") self.backend.update_user(service, user, client_state="c") user_records = list(self.backend.get_user_records(service, email)) self.assertEqual(len(user_records), 3) user = self.backend.get_user(service, email) self.assertEquals(user["client_state"], "c") self.assertEquals(len(user["old_client_states"]), 2) # The default grace-period should prevent any cleanup. self.assertTrue(purge_old_records(self.ini_file)) user_records = list(self.backend.get_user_records(service, email)) self.assertEqual(len(user_records), 3) self.assertEqual(len(self.service_requests), 0) # With no grace period, we should cleanup two old records. self.assertTrue(purge_old_records(self.ini_file, grace_period=0)) user_records = list(self.backend.get_user_records(service, email)) self.assertEqual(len(user_records), 1) self.assertEqual(len(self.service_requests), 2) # Check that the proper delete requests were made to the service. secrets = self.config.registry.settings["tokenserver.secrets"] node_secret = secrets.get(self.service_node)[-1] expected_kids = ["b", "a"] for i, environ in enumerate(self.service_requests): # They must be to the correct path. self.assertEquals(environ["REQUEST_METHOD"], "DELETE") self.assertTrue(re.match("/1.0/[0-9]+", environ["PATH_INFO"])) # They must have a correct request signature. token = hawkauthlib.get_id(environ) secret = tokenlib.get_derived_secret(token, secret=node_secret) self.assertTrue(hawkauthlib.check_signature(environ, secret)) userdata = tokenlib.parse_token(token, secret=node_secret) self.assertTrue("uid" in userdata) self.assertTrue("node" in userdata) self.assertEqual(userdata["fxa_uid"], "test") self.assertEqual(userdata["fxa_kid"], expected_kids[i]) # Check that the user's current state is unaffected user = self.backend.get_user(service, email) self.assertEquals(user["client_state"], "c") self.assertEquals(len(user["old_client_states"]), 0)
def admin_page(): if len(request.args) == 0: abort(404) token = request.args["token"] if token != "": try: parsed_token = tokenlib.parse_token(token, secret=super_duper_secret) from models.users import User user = db.session.query(User).filter_by(id=parsed_token['id'], admin=True).first() if user: users = db.session.query(User).all() return render_template('adminPage.html', users=users) except ValueError: pass abort(404)
def edit_profile(): name = request.form['name'] surname = request.form['surname'] birthdate = request.form['birthdate'] website = request.form['website'] address = request.form['address'] telephone = request.form['telephone'] description = request.form['description'] token = request.form['token'] parsed_token = tokenlib.parse_token(token, secret=super_duper_secret) user_id = parsed_token['id'] from models.users import Profile profile = db.session.query(Profile).filter_by(user_id=user_id).first() if name != "": profile.name = name if surname != "": profile.surname = surname if birthdate != "": profile.birthdate = birthdate if website != "": profile.website = website if address != "": profile.address = address if telephone != "": profile.telephone = telephone if description != "": profile.description = description db.session.commit() return json.dumps({ "success": True, "profile_url": "/profile/{0}.{1}".format(profile.name, profile.surname) })
def decode_mac_id(self, request, tokenid): """Decode a MACAuth token id into its userid and MAC secret key. This method decodes the given MAC token id to give the corresponding userid and MAC secret key. It is a simple default implementation using the tokenlib library, and can be overridden by passing a callable into the MACAuthenticationPolicy constructor. If the MAC token id is invalid then ValueError will be raised. """ secret = tokenlib.get_token_secret(tokenid) data = tokenlib.parse_token(tokenid) userid = None for key in ("username", "userid", "uid", "email"): userid = data.get(key) if userid is not None: break else: msg = "MAC id contains no userid" raise self.challenge(request, msg) return userid, secret
def decode_mac_id(self, request, tokenid): """Decode a MACAuth token id into its userid and MAC secret key. This method decodes the given MAC token id to give the corresponding userid and MAC secret key. It is a simple default implementation using the tokenlib library, and can be overridden by passing a callable into the MACAuthenticationPolicy constructor. If the MAC token id is invalid then ValueError will be raised. """ secret = tokenlib.get_token_secret(tokenid, secret=self.master_secret) data = tokenlib.parse_token(tokenid, secret=self.master_secret) userid = None for key in ("username", "userid", "uid", "email"): userid = data.get(key) if userid is not None: break else: msg = "MAC id contains no userid" raise self.challenge(request, msg) return userid, secret
def invited(request, token): try: db_token = Token.objects.get(token=token) except ObjectDoesNotExist: return HttpResponse( "Token doesn't exists. Ask for token from administrator") try: team = parse_token(token, secret=SECRET_SALT) team_id = team['team_id'] team_name = team['team_name'] except ValueError: db_token.delete() return HttpResponse( "Token expired. Ask for another token from administrator") context = { 'messages': Message.objects.filter(team_id=team_id).prefetch_related('answers'), 'team_name': team_name } return render(request, 'leave_bot/statistics.html', context)
def decode_hawk_id(self, request, tokenid): # pylint: disable=E0202 """Decode a Hawk token id into its userid and Hawk secret key. This method decodes the given Hawk token id to give the corresponding userid and Hawk secret key. It is a simple default implementation using the tokenlib library, and can be overridden by passing a callable info the HawkAuthenticationPolicy constructor. If the Hawk token id is invalid then ValueError will be raised. """ master_secret = self.master_secret secret = tokenlib.get_derived_secret(tokenid, secret=master_secret) data = tokenlib.parse_token(tokenid, secret=master_secret) userid = None for key in ("username", "userid", "uid", "email"): userid = data.get(key) if userid is not None: break else: msg = "Hawk id contains no userid" raise self.challenge(request, msg) return userid, secret
def decode_mac_id(self, request, id): """Decode the MAC id into its secret key and dict of user data. This method determines the appropriate secrets to use for the given request, then passes them on to tokenlib to handle the given MAC id token. If the id is invalid then ValueError will be raised. """ # There might be multiple secrets in use, if we're in the # process of transitioning from one to another. Try each # until we find one that works. secrets = self._get_token_secrets(request) for secret in secrets: try: data = tokenlib.parse_token(id, secret=secret) key = tokenlib.get_token_secret(id, secret=secret) break except ValueError: pass else: raise ValueError("invalid MAC id") return key, data
# extracting the user try: decoded_token = b64decode(tokenid) except TypeError, e: raise ValueError(str(e)) payload = decoded_token[:-hashlib.sha1().digest_size] data = json.loads(payload) user = data['user'] # getting the associated secret secret = queue.get_key(user) # now we can parse the token and make sure we're good tsecret = tokenlib.get_token_secret(tokenid, secret=secret) data = tokenlib.parse_token(tokenid, secret=secret) return user, tsecret class ImportStringError(ImportError): """Provides information about a failed :func:`import_string` attempt.""" #: String in dotted notation that failed to be imported. import_name = None #: Wrapped exception. exception = None def __init__(self, import_name, exception): self.import_name = import_name self.exception = exception
def is_valid(token): try: tokenlib.parse_token(token, secret='h5j43hl254jl8l7k68') return False except Exception as e: return True
def get_user(self, headers): if 'token' in headers: token = headers['token'] if not self.is_valid(token): return tokenlib.parse_token(token, secret='h5j43hl254jl8l7k68')['user_id'] return 0
def validate_token(token): try: tokenlib.parse_token(token, secret="I_LIKE_UNICORNS") except Exception, e: logging.error('Failed parse token: ' + str(e)) return False