def delete_account(uuid: UUID, db: Session): acct_to_delete = db.query(Account).filter_by(uuid=uuid).first() if acct_to_delete is None: raise HTTPException(status_code=400, detail=f"Account with UUID {uuid} not found") db.delete(acct_to_delete) db.commit()
def delete_settings(uuid: UUID, db: Session): settings_to_delete = db.query(AccountSettings).filter_by(uuid=uuid).first() if settings_to_delete is None: raise HTTPException(status_code=400, detail=f"Settings with UUID {uuid} not found") db.delete(settings_to_delete) db.commit()
def setup(db, response_converter, airtable_loader): db = Session() RunAirtableSync(airtable_loader, db, response_converter) yield # this is where the testing happens db.rollback() cleanup(db)
def list_messages(): """Return list of recieved mail messages""" session = Session() messages = session.query(Message).all() msg_lst = [] for message in messages: msg_lst.append(create_message(message)) return msg_lst
def isValidUser(username, password, cookie): session = Session() user_query = session.query(User).filter_by(Username=username) if user_query.count() != 0 and (user_query.first().Password == password): user_query.update({"Cookie": (cookie)}) session.commit() return True return False
def show_message(id): """ Return message selected by id """ session = Session() message = session.query(Message).filter_by(id=id).one() msg_dct = create_message(message) msg_dct["size"] = message.size msg_dct["recipients"] = create_recipients(message.recipients) return msg_dct
def update_settings(uuid, settings: AccountSettingsSchema, Authorize: AuthJWT = Depends(), db: Session = Depends(get_db)): Authorize.jwt_required() check_matching_user(uuid, Authorize) updated_settings = AccountSettings(**settings.dict()) db.merge(updated_settings) db.commit() return updated_settings
def update_account(uuid, account: AccountBaseSchema, Authorize: AuthJWT = Depends(), db: Session = Depends(get_db)): Authorize.jwt_required() check_matching_user(uuid, Authorize) check_for_diff_user_with_same_username(uuid, account, db) updated_acct = Account(uuid=uuid, **account.dict()) db.merge(updated_acct) db.commit() return updated_acct
def create_account(account: AccountCreateRequestSchema, Authorize: AuthJWT = Depends(), db: Session = Depends(get_db)): check_for_existing_username_or_email(account, db) if account.password is not None: check_valid_password(account.password) account.password = encrypt_password(account.password) account = Account(**account.dict()) db.add(account) db.commit() create_account_settings(account.uuid, db) create_access_and_refresh_tokens(str(account.uuid), Authorize) return account
def check_for_existing_username_or_email(account: AccountBaseSchema, db: Session): existing_acct = db.query(Account).filter_by(email=account.email).first() errors = {} if existing_acct is not None: errors[ 'email'] = f"An account with the email address {account.email} already exists" existing_acct = db.query(Account).filter_by( username=account.username).first() if existing_acct is not None: errors[ 'username'] = f"An account with the username {account.username} already exists" if len(errors) > 0: raise HTTPException(status_code=400, detail=errors)
def connected(self): root_switch = rootDPID pol = Filter(SwitchEq(root_switch) & IP4DstEq("100.0.0.102")) >> SetPort(2) pol = pol | Filter(SwitchEq(root_switch) & IP4DstEq("100.0.0.103")) >> SetPort(1) pol = pol | Filter(SwitchEq(root_switch) & IP4DstEq("100.0.0.104")) >> SetPort(1) pol = pol | Filter(SwitchEq(root_switch) & IP4DstEq("100.0.0.105")) >> SetPort(1) slave_switch_1 = slaveDPID pol = pol | Filter(SwitchEq(slave_switch_1) & IP4DstEq("100.0.0.105")) >> SetPort(4) pol = pol | Filter(SwitchEq(slave_switch_1) & IP4DstEq("100.0.0.103")) >> SetPort(2) pol = pol | Filter(SwitchEq(slave_switch_1) & IP4DstEq("100.0.0.104")) >> SetPort(3) pol = pol | Filter(SwitchEq(slave_switch_1) & IP4DstEq("100.0.0.102")) >> SetPort(1) session = Session() policies = session.query(Policies).filter_by(loaded=1) for p in policies: pol = pol | Filter( SwitchEq(slave_switch_1) & IP4SrcEq("100.0.0.103")) >> SetIP4Dst("100.0.0.104") pol = pol | Filter( SwitchEq(slave_switch_1) & EthSrcEq("62:99:69:d7:ef:49")) >> SetIP4Dst("100.0.0.104") pol = pol | Filter( SwitchEq(slave_switch_1) & IP4SrcEq("100.0.0.103")) >> SetEthDst("d2:33:20:b8:08:40") pol = pol | Filter( SwitchEq(slave_switch_1) & EthSrcEq("62:99:69:d7:ef:49") ) >> SetEthDst("d2:33:20:b8:08:40") pol = pol | Filter( SwitchEq(slave_switch_1) & IP4SrcEq("100.0.0.103")) >> SetPort(3) pol = pol | Filter( SwitchEq(slave_switch_1) & EthSrcEq("62:99:69:d7:ef:49")) >> SetPort(3) app.update(pol)
def create_notification(notification_payload: AccountNotificationSchema, db: Session = Depends(get_db)): existing_acct = None if notification_payload.email is not None: existing_acct = db.query(Account).filter_by( email=notification_payload.email).first() or db.query( Account).filter_by( email=sanitize_email(notification_payload.email)).first() elif notification_payload.username is not None: existing_acct = db.query(Account).filter_by( username=notification_payload.username.strip()).first() else: raise HTTPException(status_code=400, detail=f"Invalid username or e-mail!") create_and_send_email(notification_payload, existing_acct, db)
def modifyBalance(cookie, amount, spins): session = Session() user_query = session.query(User).filter_by(Cookie=cookie) queried_user = user_query.first() spinsLeft = int(queried_user.Spinsleft); if(spinsLeft > 0): bal = float(queried_user.Balance) spinsLeft = spinsLeft - 1 + spins bal += amount user_query.update({'Spinsleft' : spinsLeft}) user_query.update({'Balance' : bal}) if spinsLeft == 0: user_query.update({'TimeLeft' : (datetime.now() + timedelta(hours=2))}) session.commit()
def validateCookie(cookie): session = Session() user_query = session.query(User).filter_by(Cookie=cookie) if user_query.count() > 0: user = user_query.first() spinsLeft = user.Spinsleft if spinsLeft == 0: refreshTime = user.TimeLeft present = datetime.now() if refreshTime is not None and present > refreshTime: user_query.update({"Spinsleft": 3}) user_query.update({"TimeLeft": None}) session.commit() return user_query.first() return False
def populate_initiative_map(db: Session = Depends(get_db)) -> Dict: initiatives = db.query(Initiative).options(lazyload( Initiative.roles_rel)).all() result = {} if initiatives is not None: for item in initiatives: result[item] = False return result
async def authorize_google(request: Request, Authorize: AuthJWT = Depends(), db: Session = Depends(get_db)): try: token = await oauth.google.authorize_access_token(request) except OAuthError as error: return HTMLResponse(f'<h1>{error.error}</h1>') user = await oauth.google.parse_id_token(request, token) account = db.query(Account).filter_by(email=user.email).first() if account is None: logging.warning('Creating a new user object for first-time login') new_account = Account( email=user.email, username=user.email.split('@')[0], first_name=user.given_name, last_name=user.family_name, oauth='google', profile_pic=user.picture, is_verified=True, ) db.add(new_account) db.commit() db.refresh(new_account) create_account_settings(new_account.uuid, db) account = new_account return create_token_for_user(Authorize, str(account.uuid))
async def authorize_github(request: Request, Authorize: AuthJWT = Depends(), db: Session = Depends(get_db)): try: token = await oauth.github.authorize_access_token(request) except OAuthError as error: return HTMLResponse(f'<h1>{error.error}</h1>') resp = await oauth.github.get('user', token=token) user = resp.json() email_to_use = user['email'] or user['login'] + '@fakegithubemail.com' account = db.query(Account).filter_by(email=email_to_use).first() if account is None: new_account = Account(email=email_to_use, username=user['login'], first_name=user['name'], last_name='no last name', oauth='github', profile_pic=user['avatar_url'], city=None if user['location'] is None else user['location'].split(', ')[0], state=None if user['location'] is None else user['location'].split(', ')[1], is_verified=True) db.add(new_account) db.commit() db.refresh(new_account) create_account_settings(new_account.uuid, db) account = new_account return create_token_for_user(Authorize, str(account.uuid))
def connected(self): root_switch = 196040413341508 pol = Filter(SwitchEq(root_switch) & IP4DstEq("10.0.0.102")) >> SetPort(2) pol = pol | Filter(SwitchEq(root_switch) & IP4DstEq("10.0.0.103")) >> SetPort(3) pol = pol | Filter(SwitchEq(root_switch) & IP4DstEq("10.0.0.104")) >> SetPort(4) pol = pol | Filter(SwitchEq(root_switch) & IP4DstEq("10.0.0.105")) >> SetPort(1) pol = pol | Filter(SwitchEq(root_switch) & IP4DstEq("10.0.0.106")) >> SetPort(1) pol = pol | Filter(SwitchEq(root_switch) & IP4DstEq("10.0.0.107")) >> SetPort(1) pol = pol | Filter(SwitchEq(root_switch) & IP4DstEq("10.0.0.108")) >> SetPort(1) pol = pol | Filter(SwitchEq(root_switch) & IP4DstEq("10.0.0.109")) >> SetPort(1) pol = pol | Filter(SwitchEq(root_switch) & IP4DstEq("10.0.0.110")) >> SetPort(1) slave_switch_1 = 77043891114308 pol = pol | Filter(SwitchEq(slave_switch_1) & IP4DstEq("10.0.0.105")) >> SetPort(5) pol = pol | Filter(SwitchEq(slave_switch_1) & IP4DstEq("10.0.0.106")) >> SetPort(6) pol = pol | Filter(SwitchEq(slave_switch_1) & IP4DstEq("10.0.0.107")) >> SetPort(7) pol = pol | Filter(SwitchEq(slave_switch_1) & IP4DstEq("10.0.0.108")) >> SetPort(3) pol = pol | Filter(SwitchEq(slave_switch_1) & IP4DstEq("10.0.0.109")) >> SetPort(4) pol = pol | Filter(SwitchEq(slave_switch_1) & IP4DstEq("10.0.0.110")) >> SetPort(2) pol = pol | Filter(SwitchEq(slave_switch_1) & IP4DstEq("10.0.0.102")) >> SetPort(1) pol = pol | Filter(SwitchEq(slave_switch_1) & IP4DstEq("10.0.0.103")) >> SetPort(1) pol = pol | Filter(SwitchEq(slave_switch_1) & IP4DstEq("10.0.0.104")) >> SetPort(1) session = Session() policies = session.query(Policies).filter_by(loaded=1) for p in policies: pol = pol | Filter(SwitchEq(p.switch1) & IP4SrcEq(p.src_ip)) >> SetIP4Dst(QVM_IP) app.update(pol)
def check_for_diff_user_with_same_username(uuid, account: AccountCreateRequestSchema, db: Session): existing_acct = db.query(Account).filter_by( username=account.username).first() if existing_acct is not None and str(uuid) != str(existing_acct.uuid): raise HTTPException( status_code=400, detail= f"Account with username {existing_acct.username} already exists!")
def cancel_account_registration(cancel_hash: str, db: Session = Depends(get_db)): settings_to_delete = db.query(AccountSettings).filter_by( cancel_registration_hash=cancel_hash).first() if settings_to_delete is None: raise HTTPException( status_code=400, detail=f"Account settings with hash {cancel_hash} not found") acct_uuid = settings_to_delete.uuid delete_user(acct_uuid, db)
def verify_password(payload: AccountPasswordSchema, Authorize: AuthJWT = Depends(), db: Session = Depends(get_db)): Authorize.jwt_required() existing_acct = db.query(Account).filter_by(uuid=payload.uuid).first() password_valid = check_encrypted_password(payload.old_password, existing_acct.password) if password_valid is True: return True else: raise HTTPException(status_code=403, detail=f"Password is incorrect")
def get_settings_from_hash(pw_reset_hash: str, Authorize: AuthJWT = Depends(), db: Session = Depends(get_db)): existing_settings = db.query(AccountSettings).filter_by( password_reset_hash=pw_reset_hash).first() if existing_settings is not None: time_diff = minutes_difference(existing_settings.password_reset_time) if time_diff >= 15: existing_settings.password_reset_hash = None existing_settings.password_reset_time = None db.merge(existing_settings) db.commit() raise HTTPException( status_code=400, detail=f"Invalid or expired password reset URL!") else: create_access_and_refresh_tokens(str(existing_settings.uuid), Authorize) return existing_settings else: raise HTTPException(status_code=400, detail=f"Invalid or expired password reset URL!")
def complete_account_registration(verify_hash: str, Authorize: AuthJWT = Depends(), db: Session = Depends(get_db)): settings = db.query(AccountSettings).filter_by( verify_account_hash=verify_hash).first() if settings is not None: acct_uuid = settings.uuid settings.verify_account_hash = None settings.cancel_registration_hash = None db.merge(settings) db.commit() account = db.query(Account).filter_by(uuid=acct_uuid).first() if account is not None: account.is_verified = True db.merge(account) db.commit() create_access_and_refresh_tokens(str(acct_uuid), Authorize) user = row2dict(account) user.update(row2dict(settings)) return user else: raise HTTPException(status_code=400, detail=f"invalid hash or account does not exist")
def authorize_basic(account: AccountBasicLoginSchema, Authorize: AuthJWT = Depends(), db: Session = Depends(get_db)): existing_acct = db.query(Account).filter_by(email=account.email).first() if existing_acct is None: raise HTTPException(status_code=403, detail=f"E-mail or password is invalid!") verified_pw = check_encrypted_password(account.password, existing_acct.password) if verified_pw is False: raise HTTPException(status_code=403, detail=f"E-mail or password is invalid!") if existing_acct.is_verified is False: raise HTTPException( status_code=403, detail=f"Account has not been verified. Please check your e-mail.") create_access_and_refresh_tokens(str(existing_acct.uuid), Authorize) return existing_acct
def registerUser(username, password, firstName, lastName, address, email, cookie, referral): session = Session() user_query = session.query(User).filter_by(Username=username) email_query = session.query(User).filter_by(Email=email) if(user_query.count() > 0 or email_query.count() > 0): return False spinsLeft = 3 if len(referral) > 0: ref_user = session.query(User).filter_by(Username=referral) if ref_user.count > 0: ref_spins = ref_user.first().Spinsleft ref_spins += 10 ref_user.update({'Spinsleft' : ref_spins}) spinsLeft += 10 new_user = User(Username=username, Email = email, Password=password, firstName = firstName, lastName = lastName, AdIndex = 0, Spinsleft = spinsLeft, Balance = 0.0, Cookie = cookie) session.add(new_user) session.commit() return True
def update_password(uuid, partial_account: AccountNewPasswordSchema, Authorize: AuthJWT = Depends(), db: Session = Depends(get_db)): try: Authorize.jwt_required() check_matching_user(uuid, Authorize) account = db.query(Account).filter_by(uuid=uuid).first() if partial_account.password is None: raise HTTPException(status_code=400, detail=f"Password is missing") else: check_valid_password(partial_account.password) account.password = encrypt_password(partial_account.password) db.merge(account) db.commit() db.refresh(account) except Exception as e: logging.warning(e) raise e return account
def send_notification(recipient: str, message: str, channel: NotificationChannel, scheduled_send_date: datetime = None, subject=None): notification = Notification(recipient=recipient, subject=subject, message=message, channel=channel, scheduled_send_date=scheduled_send_date) db = Session() db.add(notification) if notification.channel is NotificationChannel.EMAIL: send_email_notification(notification) elif notification.channel is NotificationChannel.SMS: send_sms_notification(notification) elif notification.channel is NotificationChannel.SLACK: send_slack_notification(notification) else: raise ValueError() db.commit()
def home(request): if "css" in request.path or "jss" in request.path or "images" in request.path: return print "Requesting new page %s" % request.path cookie = request.COOKIES.get('csrftoken') cachedUserData = validateCookie(cookie) randNum = randint(0,3) if cachedUserData is not False: randNum = cachedUserData.AdIndex updateValueForUser(cachedUserData.Username, "AdIndex", (randNum + 1) % 4) if request.path == "/withdraw" and request.method == "POST": method = request.POST.get("method") message = "Username : "******"\n" + "Method : " + method; send_email(message, "Withdrawal Request : " + cachedUserData.Username, cachedUserData.Email) content = { 'username' : cachedUserData.Username, 'Balance' : cachedUserData.Balance, 'spinsLeft' : cachedUserData.Spinsleft, 'email' : cachedUserData.Email, 'disabled' : "disabled", 'ads' : ad[randNum] } return render(request, 'withdrawal_success.html', content) if request.path == "/contact" and request.method == "POST": message = request.POST.get("message") email = request.POST.get("email") name = request.POST.get("name") send_email(message, name + " - contact us", email) if cachedUserData == False: content = { 'visib' : "hidden", 'ads' : ad[randNum] } else: content = { 'username' : cachedUserData.Username, 'Balance' : cachedUserData.Balance, 'spinsLeft' : cachedUserData.Spinsleft, 'visib' : "", 'ads' : ad[randNum] } return render(request, 'contact_success.html', content) if request.path == "/advertiser" and request.method == "POST": message = request.POST.get("message") email = request.POST.get("email") name = request.POST.get("name") send_email(message, name + " - advertiser", email) if cachedUserData == False: content = { 'visib' : "hidden", 'ads' : ad[randNum] } else: content = { 'username' : cachedUserData.Username, 'Balance' : cachedUserData.Balance, 'spinsLeft' : cachedUserData.Spinsleft, 'visib' : "", 'ads' : ad[randNum] } return render(request, 'contact_success.html', content) if request.path == "/": if cachedUserData == False: content = { 'visib' : "hidden", 'ads' : ad[randNum] } else: content = { 'username' : cachedUserData.Username, 'Balance' : cachedUserData.Balance, 'spinsLeft' : cachedUserData.Spinsleft, 'visib' : "", 'ads' : ad[randNum] } return render(request, 'index.html', content) if request.method == "POST" and request.path == "/spinRes": res = float(request.POST.get('res')) winner_balance = res % 2 winner_spins = int(res)/10 modifyBalance(cookie, winner_balance, winner_spins) return HttpResponse("Success") if request.path == "/game_wi_spin": return HttpResponse(isWinner()) if request.path == "/faqs": if cachedUserData == False: content = { 'visib' : "hidden", 'ads' : ad[randNum] } else: content = { 'username' : cachedUserData.Username, 'Balance' : cachedUserData.Balance, 'spinsLeft' : cachedUserData.Spinsleft, 'visib' : "", 'ads' : ad[randNum] } return render(request, 'faqs.html', content) if request.path == "/login": if request.method == "GET": cachedUserData = validateCookie(cookie) if cachedUserData == False: return render(request, 'login.html') else: content = { 'username' : cachedUserData.Username, 'Balance' : cachedUserData.Balance, 'spinsLeft' : cachedUserData.Spinsleft, 'ang' : isWinner(), 'ads' : ad[randNum] } return render(request, 'game.html', content) if(request.method == "POST"): username = request.POST.get('username') password = request.POST.get('password') if request.POST.has_key('email'): firstName = request.POST.get('firstName') lastName = request.POST.get('lastName') username = request.POST.get('username') address = request.POST.get('address') email = request.POST.get('email') referral = request.POST.get('referral') flag = registerUser(username, password, firstName, lastName, address, email, cookie, referral) if(flag == False): return render(request, 'invalid_login.html') return render(request, 'account_created.html') else: if isValidUser(username, password, cookie): session = Session() user_query = session.query(User).filter_by(Username=username) content = { 'username' : username, 'Balance' : user_query.first().Balance, 'spinsLeft' : user_query.first().Spinsleft, 'ang' : isWinner(), 'ads' : ad[randNum] } return render(request, 'game.html', content) else: return render(request, 'invalid_login.html') return render(request, 'login.html') if request.path == "/logout": logUserOut(cookie) content = { 'visib' : "hidden", 'ads' : ad[randNum] } return render(request, 'index.html', content) if request.path == "/withdraw": session = Session() user_query = session.query(User).filter_by(Cookie=cookie) disabled = '' if(user_query.first().Balance < 2): disabled = 'disabled', content = { 'username' : user_query.first().Username, 'Balance' : user_query.first().Balance, 'spinsLeft' : user_query.first().Spinsleft, 'email' : user_query.first().Email, 'disabled' : disabled, 'ads' : ad[randNum] } return render(request, 'withdraw.html', content) # if request.path == "/" and request.method == "POST": # username = request.POST.get("username") # password = request.POST.get("password") # if len(username) <= 0 or len(password) <= 0: # return render(request, 'invalid_login.html') # # Register new account # if request.POST.has_key('email'): # firstName = request.POST.get("firstName") # lastName = request.POST.get("lastName") # address = request.POST.get("address") # email = request.POST.get("email") # registerUser(username, password, firstName, lastName, address, email, cookie) # content = { # 'username' : username # } # return render(request, 'game.html', content) # else: # if isValidUser(username, password, cookie): # content = { # 'username' : username # } # return render(request, 'game.html', content) # else: # return render(request, 'invalid_login.html') content = { 'path' : request.path } if request.path == '/contact': if cachedUserData == False: content = { 'visib' : "hidden", 'ads' : ad[randNum] } else: content = { 'username' : cachedUserData.Username, 'Balance' : cachedUserData.Balance, 'spinsLeft' : cachedUserData.Spinsleft, 'visib' : "", 'ads' : ad[randNum] } return render(request, 'contact_us.html', content) elif request.path == '/advertiser': if cachedUserData == False: content = { 'visib' : "hidden" } else: content = { 'username' : cachedUserData.Username, 'Balance' : cachedUserData.Balance, 'spinsLeft' : cachedUserData.Spinsleft, 'visib' : "" } return render(request, 'advertiser.html', content) return render(request, 'index.html')
#!/usr/bin/env python import sys from settings import Session, engine, Base from calcSSByTime import calculateSSByTime from calcSS import calculateSS from models import SuspiciousnessScores, Devices session = Session() lastrecord = session.query(SuspiciousnessScores).order_by(SuspiciousnessScores.traceID.desc()).first() if lastrecord is None: trace_id = 1 else: trace_id = lastrecord.traceID +1 records = session.query(Devices).all() lastssID = session.query(SuspiciousnessScores).order_by(SuspiciousnessScores.SSID.desc()).first() if lastssID is None: row_count=0 else: row_count = lastssID.SSID for rec in records: device_id = rec.deviceID row_count = row_count+1 calculateSS(row_count,trace_id,device_id) #calculateSSByTime(trace_id, device_id) print('executed')
def posts(): session = Session() topics = session.query(Topic).all() a = [{'title': t.title, 'posts': [{'body': p.body} for p in t.posts]} for t in topics] return json.dumps(a)
def setup(db): db = Session() yield # this is where the testing happens db.rollback()
def logUserOut(cookie): session = Session() user_query = session.query(User).filter_by(Cookie=cookie) if user_query.count() > 0: user_query.update({"Cookie": ""}) session.commit()
def updateValueForUser(username, columnName, columnValue): session = Session() user_query = session.query(User).filter_by(Username=username) user_query.update({columnName : columnValue}) session.commit()
from settings import Session __author__ = 'jb' from orm_example import * b = TabB() sess = Session()
def db(): return Session()
def get_all_volunteer_events(db: Session = Depends( get_db)) -> List[VolunteerEventSchema]: return db.query(VolunteerEvent).order_by( VolunteerEvent.start_datetime.asc()).all()
class UserMigration(Base): __tablename__ = 'usermigration' userMigrationUID = Column('userMigrationUID', String(100), nullable=False, primary_key=True) userIP = Column('userIP', String(45), nullable=True) originalServerIP = Column('originalServerIP', String(45), default=None) migratedServerIP = Column('migratedServerIP', String(45), default=None) migrationStartTime = Column('migrationStartTime', DateTime, default=None) migrationStopTime = Column('migrationStopTime', DateTime, default=None) class Users(Base): __tablename__ = 'users' userUID = Column('userID', String(100), nullable=False, primary_key=True) username = Column('username', String(100), default=None) ipAddressuserIP = Column('ipAddress', String(20), default=None) connectionStartTime = Column('connectionStartTime', DateTime, default=None) connectionStopTime = Column('connectionStopTime', DateTime, default=None) class Whitelist(Base): __tablename__ = 'whitelist' ipv4 = Column('ipv4', String(15), nullable=False, primary_key=True) session = Session() Base.metadata.create_all(engine) session.commit()
def get_volunteer_event_by_external_id( external_id, db: Session = Depends(get_db)) -> Optional[VolunteerEventSchema]: return db.query(VolunteerEvent).filter_by(external_id=external_id).first()