def context(user_claim: UserClaim, experiment_id: str, org: str, workspace: str): url = url_for("workspace_experiment_service.index", org=org, workspace=workspace, experiment_id=experiment_id, _external=True) experiment_id = shortuuid.decode(experiment_id) experiment = Experiment.query.filter( Experiment.id == experiment_id).first() if not experiment: return abort(404) w = DashboardService.get_user_workspace(user_claim, org, workspace) if not w: return abort(404) if "view" not in w["context"]["acls"]: return abort(404) e = experiment.to_public_dict() e["workspace"] = w e["requested_by"] = None e["url"] = url if user_claim: e["requested_by"] = DashboardService.get_user_details( user_claim, shortuuid.decode(w["org"]["id"]), shortuuid.decode(w["id"])) return jsonify(e)
def to_python(self, value): value = super().to_python(value) if value in self.empty_values: return None try: shortuuid.decode(value) except ValueError: raise ValidationError(self.error_messages['invalid'], code='invalid') return value
def store_experiment(user_claim: UserClaim, org: str, workspace: str, payload: Experiment) -> Experiment: experiment = Exp(shared_ref=uuid.uuid4(), account_id=user_claim["id"], org_id=shortuuid.decode(org), workspace_id=shortuuid.decode(workspace), payload=payload) db.session.add(experiment) db.session.commit() return experiment.to_public_dict(with_payload=False)
def get_experiment_in_workspace_for_user(user_claim: UserClaim, org: str, workspace: str, experiment_id: str, include_payload: bool = False) \ -> Optional[Experiment]: experiment = Exp.query.filter( Exp.account_id == user_claim["id"], Exp.org_id == shortuuid.decode(org), Exp.workspace_id == shortuuid.decode(workspace), Exp.id == shortuuid.decode(experiment_id)).first() if not experiment: return None return experiment.to_public_dict(with_payload=include_payload)
def store_execution(user_claim: UserClaim, org: str, workspace: str, experiment: str, payload: Experiment) -> Experiment: execution = Exec(experiment_id=shortuuid.decode(experiment), account_id=user_claim["id"], org_id=shortuuid.decode(org), workspace_id=shortuuid.decode(workspace), payload=payload, status=payload.get('status', 'unknown')) db.session.add(execution) db.session.commit() return execution.to_dict()
def activate(request, suuid): res = HttpResponse(content_type=CONTENT_TYPE_TEXT) logger.error('suuid: %s' % (suuid, )) #FIXME: check if the record is clicked #code = request.GET['c'] code = shortuuid.decode(suuid) try: ur = UserRegistration.objects.get(code=code.hex) except UserRegistration.DoesNotExist: res.status_code = 401 return res if ur.clicked: res.status_code = 203 res.content = 'Already clicked' else: try: ur.activate() except IntegrityError, e: res = status = 400 res.content = e.args[0] return res content = """<!DOCTYPE html> <html> <head> <title>Congratulations!</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> </head> <body> <h3>註冊成功</h3> <p>Welcome to PLATE!</p> <p>leave this page in <span id="remain_seconds">10</span> seconds</p> <script> var count = 9; var countdown = setInterval(function(){ $("#remain_seconds").html(count + ""); if (count == 0) { clearInterval(countdown); window.open('http://plate.tw', "_self"); } count--; }, 1000); </script> </body> </html>""" res = HttpResponse(content) res.status_code = 200 return res
def attendee(request, barcode): prefix = request.build_absolute_uri('/register/badges/qrcode/') qrcode = shortuuid.decode(barcode) ticket = get_object_or_404(Ticket, barcode=qrcode, success=True) if request.method == "POST": checked_in = request.POST.get('checked_in', None) checked_in_bool = checked_in in (True, "true", "True", 1, "1", False, None, "False", "false", "null", 0) p_checked_in = None if checked_in and type(checked_in) in (str, unicode): try: p_checked_in = parser.parse(checked_in) except (AttributeError as ValueError): pass if 'checked_in' not in request.POST or (type(checked_in) in (str, unicode) and not p_checked_in and not checked_in_bool): return HttpResponseBadRequest(json.dumps({'error': 'checked_in parameter required, and must be a datetime, true, false, or null.'}), content_type="application/json") if checked_in in (False, None, "False", "false", "null", 0): ticket.checked_in = None else: if ticket.checked_in is not None: return HttpResponse(json.dumps({'error': 'Already checked in.'}), status=409, content_type="application/json") if checked_in in (True, "true", "True", 1, "1"): ticket.checked_in = timezone.localtime(timezone.now()) elif p_checked_in: if not p_checked_in.tzinfo: p_checked_in = p_checked_in.replace(tzinfo=timezone.get_current_timezone()) ticket.checked_in = p_checked_in ticket.save() return HttpResponse(json.dumps(get_badge(ticket, prefix=prefix, compact=False)), content_type="application/json")
def remove_member_from_org(user_claim: Dict[str, Any], org: Org, user_id: str): if request.headers.get('Accept') != 'application/json': return render_template('index.html') # the user making the request account_id = user_claim["id"] if not org.is_owner(account_id): return abort(400) user_id = shortuuid.decode(user_id) # the user to remove account = UserAccount.query.filter(UserAccount.id == user_id).first() if not account: return "", 204 if org.is_owner(account.id) and org.has_single_owner(): return abort(400) org.remove_member(user_id) db.session.commit() record_activity({ "title": org.name, "account_id": account_id, "kind": "organization", "info": "collaborator removed", "org_id": org.id, "visibility": ActivityVisibility.authenticated }) return "", 204
def remove_collaborator_from_workspace(user_claim: Dict[str, Any], org: Org, workspace: Workspace, user_id: str): if request.headers.get('Accept') != 'application/json': return render_template('index.html') # the user making the request account_id = user_claim["id"] if not workspace.is_owner(account_id): return abort(400) # the user to remove account = UserAccount.query.filter( UserAccount.id == shortuuid.decode(user_id)).first() if not account: return "", 204 if workspace.is_owner(account.id) and workspace.has_single_owner(): return abort(400) workspace.remove_collaborator(user_id) db.session.commit() record_activity({ "title": workspace.name, "account_id": shortuuid.encode(account.id), "type": "workspace", "info": "collaborator deleted", "org_id": shortuuid.encode(org.id), "workspace_id": shortuuid.encode(workspace.id), "visibility": ActivityVisibility.authenticated }) return "", 204
def generate_short_uuid(): short = shortuuid.decode(shortuuid.encode(uuid.uuid4())[:12]) # Check if we already have such uuid, then regenerate if Note.objects.filter(read_id=short).count() > 0: return generate_short_uuid() else: return short
def longid(): MXICPATH= config.get('Locations', 'MXICPATH') files = getfiles(MXICPATH) for file in files: if file[-4:] == '.xml' and file[:5] == 'suid-': # only the XML files f1 = open(MXICPATH + file,'r') lfile = MXICPATH+'lid-'+file f2 = open(lfile,'w') for line in f1.readlines(): if '<mlhim2:pcs-' in line: n1 = line.index('-') n2 = line.index('>') s = line[n1+1:n2] if '-' in s and not 'xmlns:' in s: # this element wasn't a shortuuid print(file," has non-standard characters in element names.") f2.close() os.remove(lfile) # delete the incomplete output file break uid = shortuuid.decode(s) lid = str(uid) newline = line.replace(s,lid) f2.write(newline) else: f2.write(line) f1.close() f2.close()
def note(request, key): read_id = shortuuid.decode(key) n = models.Note.objects.get(read_id=read_id) return render(request, 'notes/note.html', { 'note': n, 'google_analytics_id': settings.GOOGLE_ANALYTICS_ID })
def longid(files=[]): if len(files) == 0: files = getfiles('.') # all files in the current directory for file in files: if file[-4:] == '.xml' and file[:5] == 'suid-': # only the XML files f1 = open(file,'r') lfile = 'lid-'+file f2 = open(lfile,'w') print(lfile) for line in f1.readlines(): if '<ccd:el-' in line: n1 = line.index('-') n2 = line.index('>') s = line[n1+1:n2] if '-' in s and not 'xmlns:' in s: # this element wasn't a shortuuid print(file," has non-standard characters in element names.") f2.close() os.remove(lfile) # delete the incomplete output file break uid = shortuuid.decode(s) lid = str(uid) newline = line.replace(s,lid) f2.write(newline) else: f2.write(line) f1.close() f2.close()
def decode(value): """Decode the value from ShortUUID to UUID. Raises ValueError when the value is not valid. """ if not isinstance(value, str) or len(value) != 22: raise ValueError('badly formed ShortUUID') return shortuuid.decode(value)
def uuid(self, value): if isinstance(value, pyuuid.UUID): self._uuid = value return try: self._uuid = shortuuid.decode(str(value)) except ValueError: self._uuid = pyuuid.UUID(str(value))
def getByShortId(self, id): try: tournamentId = shortuuid.decode(id) return self.getById(tournamentId) except Exception as exception: print(exception) transaction.abort() return None
def get_user_last_experiments(user_claim: UserClaim) -> List[Experiment]: """ Retrieve the last updated experiments. """ experiments = get_last_updated_experiments(user_claim) for e in experiments: w = Workspace.query.filter( Workspace.id == shortuuid.decode(e["workspace"])).first() e["workspace"] = w.to_dict() return experiments
def get_by_id(exp_id: Union[str, uuid.UUID]) -> Optional['Experiment']: if not exp_id: return None if isinstance(exp_id, str): try: exp_id = shortuuid.decode(exp_id) except ValueError: return None return Experiment.query.filter(Experiment.id == exp_id).first()
def get_short_object_id(self): if not shortuuid: return None short_obj_id_name = self.get_short_object_id_name() short_obj_id = self.kwargs.get(short_obj_id_name, None) if short_obj_id is None: return None return shortuuid.decode(short_obj_id).hex
def getGame(response, connection, id, dateId, pitchId, gameId): (tournament, date, pitch) = Game.getPitch(response, connection, id, dateId, pitchId) if pitch: fullGameId = shortuuid.decode(gameId) game = next((x for x in pitch.games if x.id == fullGameId), None) if not game: response.status = '404 Not Found' response.text = '{"message"="Game with id ' + gameId + ' not found."}' else: return (tournament, date, pitch, game) return (None, None, None, None)
def from_dict(activity: Dict[str, Any]) -> 'Activity': visibility = activity["visibility"] if visibility in (1, "anonymous"): visibility = ActivityVisibility.anonymous elif visibility in (2, "authenticated"): visibility = ActivityVisibility.authenticated elif visibility in (3, "collaborator"): visibility = ActivityVisibility.collaborator elif visibility in (4, "owner"): visibility = ActivityVisibility.owner org_id = activity.get("org_id") if org_id: org_id = shortuuid.decode(org_id) workspace_id = activity.get("workspace_id") if workspace_id: workspace_id = shortuuid.decode(workspace_id) experiment_id = activity.get("experiment_id") if experiment_id: experiment_id = shortuuid.decode(experiment_id) execution_id = activity.get("execution_id") if execution_id: execution_id = shortuuid.decode(execution_id) return Activity(account_id=shortuuid.decode( activity.get("account_id")), org_id=org_id, workspace_id=workspace_id, experiment_id=experiment_id, execution_id=execution_id, kind=activity.get("type"), visibility=visibility, title=activity.get("title"), info=activity.get("info"), extra=activity.get("extra"), timestamp=activity.get("timestamp"))
def from_dict(token: Dict[str, Any]) -> 'APIAccessToken': """ Create or update a token from the source access token. On update, only the scope, revoked and dates properties are changed. Others are left as they are. """ access_token = APIAccessToken.get_by_token(token["access_token"]) if not access_token: access_token = APIAccessToken() access_token.id = shortuuid.decode(token["id"]) access_token.account_id = shortuuid.decode(token["account_id"]) access_token.access_token = token["access_token"] access_token.client_id = token["client_id"] access_token.name = token["name"] access_token.refresh_token = token["refresh_token"] access_token.scope = token["scope"] access_token.revoked = token["revoked"] access_token.issued_at = token["issued_at"] access_token.expires_in = token["expires_in"] return access_token
def getPitch(response, connection, id, dateId, pitchId): tournament = connection.tournaments.getByShortId(id) if not tournament: response.status = '404 Not Found' response.text = '{"message"="Tournament with id ' + id + ' not found."}' else: fullDateId = shortuuid.decode(dateId) date = next( (x for x in tournament.gameDates if x.id == fullDateId), None) if not date: response.status = '404 Not Found' response.text = '{"message"="Date with id ' + dateId + ' not found."}' else: fullPitchId = shortuuid.decode(pitchId) pitch = next((x for x in date.pitches if x.id == fullPitchId), None) if not pitch: response.status = '404 Not Found' response.text = '{"message"="Pitch with id ' + pitchId + ' not found."}' else: return (tournament, date, pitch) return (None, None, None)
def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super().get_search_results( request, queryset, search_term) try: search_term_as_uuid = shortuuid.decode(search_term.strip()) except ValueError as e: pass else: for uuid_search_field in self._uuid_search_fields: search_params = { uuid_search_field: search_term_as_uuid, } queryset |= self.model.objects.filter(**search_params) return queryset, use_distinct
def get_redirect_url(self, *args, **kwargs): try: uuid = shortuuid.decode(kwargs['short_uuid']) except ValueError: logger.warning('can not convert %s to uuid with actual decode() method', kwargs['short_uuid']) uuid = shortuuid.decode(kwargs['short_uuid'], legacy=True) receipt = get_object_or_404(Receipt, internal_uuid=uuid) if not receipt.content: logger.warning('access receipt before backend processed receipt, suspicious') raise MissingReceipt() payload = receipt.content['payload'] receipt_dt = parse_receipt_datetime(payload['receipt_datetime']) return settings.RECEIPTS_OFD_URL_TEMPLATE.format( t='{:%Y%m%dT%H%M%S}'.format(receipt_dt), s=payload['total'], fn=payload['fn_number'], fd=payload['fiscal_document_number'], fp=payload['fiscal_document_attribute'], n=payload['fiscal_receipt_number'], )
def revoke_token(token_id: str, user_claim: UserClaim): if request.headers.get('Accept') != 'application/json': return abort(405) token_id = shortuuid.decode(token_id) AuthService.revoke_user_access_token(user_claim, token_id) record_activity({ "title": "Access Token", "account_id": user_claim["short_id"], "type": "token", "info": "revoked", "visibility": ActivityVisibility.owner }) return jsonify(None), 204
def load_experiment(user_claim: UserClaim, experiment_id: str, org: str, workspace: str) -> Experiment: experiment_id = shortuuid.decode(experiment_id) experiment = Experiment.query.filter( Experiment.id == experiment_id).first() if not experiment: raise abort(404) w = DashboardService.get_workspace(user_claim, org, workspace) if not w: raise abort(404) if "view" not in w["context"]["acls"]: raise abort(404) return experiment
def replace(self, column): if not isinstance(column, sa.Column): return try: table = version_table(column.table) except KeyError: reflected_column = column else: reflected_column = table.c[column.name] if (column in self.relationship.local_columns and table == self.parent.__table__): reflected_column = bindparam(column.key, getattr(self.parent, column.key)) with contextlib.suppress(AttributeError, TypeError): reflected_column.value = shortuuid.decode(reflected_column.value) return reflected_column
def attendee(request, barcode): prefix = request.build_absolute_uri('/register/badges/qrcode/') qrcode = shortuuid.decode(barcode) ticket = get_object_or_404(Ticket, barcode=qrcode, success=True) if request.method == "POST": checked_in = request.POST.get('checked_in', None) checked_in_bool = checked_in in (True, "true", "True", 1, "1", False, None, "False", "false", "null", 0) p_checked_in = None if checked_in and type(checked_in) in (str, unicode): try: p_checked_in = parser.parse(checked_in) except (AttributeError, ValueError): pass if 'checked_in' not in request.POST or ( type(checked_in) in (str, unicode) and not p_checked_in and not checked_in_bool): return HttpResponseBadRequest(json.dumps({ 'error': 'checked_in parameter required, and must be a datetime, true, false, or null.' }), content_type="application/json") if checked_in in (False, None, "False", "false", "null", 0): ticket.checked_in = None else: if ticket.checked_in is not None: return HttpResponse(json.dumps( {'error': 'Already checked in.'}), status=409, content_type="application/json") if checked_in in (True, "true", "True", 1, "1"): ticket.checked_in = timezone.localtime(timezone.now()) elif p_checked_in: if not p_checked_in.tzinfo: p_checked_in = p_checked_in.replace( tzinfo=timezone.get_current_timezone()) ticket.checked_in = p_checked_in ticket.save() return HttpResponse(json.dumps( get_badge(ticket, prefix=prefix, compact=False)), content_type="application/json")
def object_hook(self, object): # pylint: disable=E0202 if '_type' not in object: return object type = object['_type'] if type == 'datetime': try: return datetime.strptime(object['value'], '%Y-%m-%dT%H:%M:%S') # DateTime except ValueError: try: return datetime.strptime(object['value'], '%Y-%m-%d') # Date Only except ValueError: return datetime.strptime(object['value']) # Any Format elif type == 'uuid': return shortuuid.decode(object['value']) return object
def patch_membership(user_claim: Dict[str, Any], org: Org, workspace: Workspace, user_id: str): if request.headers.get('Accept') != 'application/json': return render_template('index.html') # the user making the request account_id = user_claim["id"] if not workspace.is_owner(account_id): return abort(400) # the user to amend user = request.json if not user: return abort(400) user_id = user.get("id") if not user_id: return abort(400) account = UserAccount.query.filter( UserAccount.id == shortuuid.decode(user_id)).first() if not account: return "", 204 turn_owner = user.get("workspace_owner", False) if turn_owner and workspace.is_collaborator(account.id): workspace.make_owner(account.id) elif not turn_owner and workspace.is_owner(account.id): if workspace.has_single_owner(): return abort(400) workspace.make_collaborator(account.id) db.session.commit() record_activity({ "title": workspace.name, "account_id": shortuuid.encode(account.id), "type": "workspace", "info": "collaborator updated", "org_id": shortuuid.encode(org.id), "workspace_id": shortuuid.encode(workspace.id), "visibility": ActivityVisibility.authenticated }) return "", 200
def test_generate_access_token(app: Flask): with app.app_context(): claim = {"id": "c1337e77-ccaf-41cf-a68c-d6e2026aef21"} name = "my token" token = generate_access_token(claim, name) token_id = shortuuid.decode(token["id"]) access_token = AccessToken.query.filter( AccessToken.id == token_id).first() assert access_token is not None assert access_token.name == name assert access_token.token_type == "bearer" assert access_token.revoked is False assert str(access_token.account_id) == \ "c1337e77-ccaf-41cf-a68c-d6e2026aef21" db.session.delete(access_token) db.session.commit()
def item_query(q, model, id=None, **kwargs): if id is int: q = q.filter(model.pk == id) elif issubclass(model, TextIdentified): q = q.filter(model.id == id) elif id is not None: item_uuid = shortuuid.decode(id) if item_uuid.version is None: return None else: q = q.filter(model.uuid == item_uuid) for key, val in kwargs.items(): field = getattr(model, key) if field is not None: filter_value = field == val # compute expression q = q.filter(filter_value) return q
def key_is_staff(key): if not key: return False try: ukey = shortuuid.decode(key) except: return False ticket = list(Ticket.objects.filter(barcode=ukey).select_related()) if not ticket: return False ticket = ticket[0] coupon = ticket.sale.coupon_code if coupon and coupon.is_staff: return True else: return False
def clean(self, value): if value is None: # Value is nothing; return it. return value try: try: if self.short: # Attempt to coerce the short UUID. return shortuuid.decode(value) except ValueError: pass # Attempt to coerce the UUID. return uuid.UUID(value) except ValueError: raise ValueError('UUID must be of the form: ' 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx')
def clean(self, value): if value is None: # Value is nothing; return it. return value try: try: if self.short: # Attempt to coerce the short UUID. return shortuuid.decode(value) except ValueError: pass # Attempt to coerce the UUID. return uuid.UUID(value) except ValueError: raise ValueError( 'UUID must be of the form: ' 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx')
def filter(self, *args, **kwargs): if 'short_barcode' in kwargs: kwargs['barcode'] = shortuuid.decode(kwargs['short_barcode']) del kwargs['short_barcode'] return super(TicketQuerySet, self).filter(*args, **kwargs)
def filter(self, qs, value): if value: shortuuid.set_alphabet('23456789abcdefghjkmnpqrstuvwxyz') value = shortuuid.decode(value) return super(ObjectIDFilter, self).filter(qs, value)