def get(self): """ You can use request.args to get URL arguments from a url. Another name for URL arguments is a query string. What is a URL argument? It"s some data that is appended to the end of a url after a "?" that can give extra context or information. """ AUTHORIZATION_CODE = request.args.get("code") data = { "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "code" : AUTHORIZATION_CODE } url = "https://api.venmo.com/v1/oauth/access_token" response = requests.post(url, data) response_dict = response.json() access_token = response_dict.get("access_token") user = response_dict.get("user") print(user["id"]) user_account = UserAccount(user=user["id"], access_token=access_token, api="venmo") user_account.save() for current_user_account in current_user.user_accounts: if current_user_account.api == "venmo": return redirect("/apps") current_user.user_accounts.append(user_account) current_user.save() session["venmo_token"] = access_token return redirect("/apps")
def join(account, remember=False): # If this is the first user account, then allow to create and make admin users = UserAccount.query().fetch() if not users: logging.info("First user account, creating user as admin", account._User__email) user = UserAccount.create_user(account,make_admin=True) if user and flasklogin.login_user(user, remember): return True # First check domain in whitelist domain = account._User__email[account._User__email.index('@')+1:] logging.info("Checking domain %s for whitelist", domain) whitelistUser = Whitelist.query(Whitelist.domain==domain.lower()).get() if whitelistUser: logging.info("Domain %s is whitelisted, creating user account %s", domain, account._User__email) user = UserAccount.create_user(account) if user and flasklogin.login_user(user, remember): return True else: # Domain not in whitelist, check email address logging.info("Checking email address %s for whitelist", account._User__email) whitelistUser = Whitelist.query(Whitelist.domain==account._User__email.lower()).get() if whitelistUser: logging.info("Email address %s is whitelisted, creating user account", account._User__email) user = UserAccount.create_user(account) if user and flasklogin.login_user(user, remember): return True return False
def decorated(*args, **kwargs): assert not (account and all_accounts), 'Ambiguous arguments' # will raise a 500 error if headers not found #g.platform = request.headers['Platform'] if not getattr(g, 'save_account', False): g.save_account = save_account if hasattr(g, 'user') and \ (not account or hasattr(g, 'account')) and \ (not all_accounts or hasattr(g, 'accounts')) and \ (not main_account or hasattr(g, 'main_account')): return f(*args, **kwargs) g.user_id = userid_from_request() if account: # flask always passes url variables as keyword arguments g.account_id = kwargs[key] #request.headers.get('Account') else: g.account_id = None try: if account: g.user, g.account = UserAccount.from_user_account( g.user_id, g.account_id) elif all_accounts: g.user, g.accounts = UserAccount.from_user(g.user_id) else: g.user = User.select().where(User.id == g.user_id).get() if main_account and not hasattr(g, 'main_account'): # TODO: catch errors if key not found main_account_id = request.headers['Account'] #main_account_service = request.headers['Service'] if account and g.account_id == main_account_id: g.main_account = g.account elif all_accounts: for acct in g.accounts: if str(acct.id) == main_account_id: g.main_account = acct break if not hasattr(g, 'main_account'): _, g.main_account = UserAccount.from_user_account( g.user_id, main_account_id) except (UserAccount.DoesNotExist, User.DoesNotExist), e: logging.warning('User %s, account %s not found: %s' % \ (g.user_id, g.account_id, e)) if not fail_silently: raise abort(401, 'Not logged in')
def create_user(request): if request.method == "POST": body = json.loads(request.body) registered_usr = User.objects.filter(username=body['username']) if len(registered_usr) > 0: return HttpResponseForbidden("User already exists") else: user = User.objects.create_user(body['username'], body['email'], body['password'], is_active=False) user.save() user_acc = UserAccount(name=body['username']) user_acc.save() return JsonResponse({'state': 'ok'}) else: return JsonResponse({'state': 'error', 'reason': 'incorrect request method'})
def initialize_application(app): # create the directory for the database if it does not exist. This might happen if the app is being run for the # first time. if not os.path.exists(DB_DIRECTORY): logger.info('Database directory does not exist. Creating...') os.makedirs(DB_DIRECTORY) # create and initialize the database if it does not exist. if not os.path.isfile(app.config['SQLALCHEMY_DATABASE_URI']): logger.info("Data base file is missing {}".format( app.config['SQLALCHEMY_DATABASE_URI'])) initialize_database(app) # check if there are any uses in the system. If there are none create at least one admin user to be able to access # the system. with app.app_context(): users = UserAccount.query.all() if not users: logger.info( 'There are no users in the database. Creating an admin user account with default settings.' ) new_user_guid = generate_hash_key() admin_user = UserAccount('*****@*****.**', 'Up@8dHgd', new_user_guid, False, datetime.now()) db.session.add(admin_user) db.session.commit()
def get_logged_user(): try: token = get_token_auth_header() payload = verify_decode_jwt(token) oauth_id = payload['sub'] # TODO: search user. If not found add it to DB user = User.query.filter( User.oauth_accounts.any(UserAccount.oauth_id == oauth_id)).first() if not user: user = User(name=oauth_id) user.insert() user_account = UserAccount(user_id=user.id, oauth_id=oauth_id) user_account.insert() return user except AuthError as ex: print(ex) return None
def add_client_account(): if request.data: content = request.json debtor_name = content['debtor_name'] debtor_phone_number = content['debtor_phone_number'] amount = content['amount'] user_id = content['user_id'] try: user_account = UserAccount(debtor_name=debtor_name, debtor_phone_number=debtor_phone_number, amount=amount, user_id=user_id) db.session.add(user_account) db.session.commit() return jsonify(user_account.serialize()), 201 except Exception as e: return jsonify({"Error": str(e)}), 401
async def create_new_user( self, super_acc: Optional[SuperAccount] = None ) -> Tuple[UserAccount, str]: if super_acc is None: super_acc = await self.create_new_super_account() new_acc = UserAccount() password = generate_password() salt, hashed = hash_password(password) new_acc.salt = salt new_acc.pword = hashed new_acc.super_id = super_acc.super_id new_acc.login = generate_uuid4() # handle a minuscule chance that the login already exists in the # database count_user = ("select count(*) " "from user_account u " "where u.login = :login ") while (await self.fetch_one(count_user, login=new_acc.login))['count'] > 0: new_acc.login = generate_uuid4() query = ("insert into user_account (login, salt, pword, super_id)" "values (:login, :salt, :pword, :super_id)") await self.execute(query, login=new_acc.login, salt=new_acc.salt, pword=new_acc.pword, super_id=new_acc.super_id) return new_acc, password
def add_user(username, email, password): #t_bf = int(time.time() * 1000) pw_salt = uuid.uuid4().hex salted_pw = password + pw_salt #t_af = int(time.time() * 1000) #sys.stderr.write("Salting takes: %d\n" % (t_af - t_bf)) hashed_pw = hashlib.sha512(salted_pw.encode('utf-8')).hexdigest() try: #t_bf = int(time.time() * 1000) # Add a user. user = UserAccount(username=username, email=email, password=hashed_pw, password_salt=pw_salt) #t_af = int(time.time() * 1000) #sys.stderr.write("User Object Creation takes: %d\n" % (t_af - t_bf)) #t_bf = int(time.time() * 1000) session.add(user) #t_af = int(time.time() * 1000) #sys.stderr.write("Adding User to Session takes: %d\n" % (t_af - t_bf)) # Add its activation token #t_bf = int(time.time() * 1000) ac_token = toekn_gen() #t_af = int(time.time() * 1000) #sys.stderr.write("Token Generation takes: %d\n" % (t_af - t_bf)) #t_bf = int(time.time() * 1000) user_ac_token = UserActivationToken(user_account=user, activation_token=ac_token) #t_af = int(time.time() * 1000) #sys.stderr.write("Token Object Creation takes: %d\n" % (t_af - t_bf)) #t_bf = int(time.time() * 1000) session.add(user_ac_token) #t_af = int(time.time() * 1000) #t_bf = int(time.time() * 1000) #sys.stderr.write("Adding User Token to Session takes: %d\n" % (t_af - t_bf)) #t_bf = int(time.time() * 1000) session.commit() #t_af = int(time.time() * 1000) #sys.stderr.write("Session Commit takes: %d\n" % (t_af - t_bf)) #t_bf = int(time.time() * 1000) # Async sending emails. send_user_token(email, ac_token) #t_af = int(time.time() * 1000) #sys.stderr.write("AMQP Transfer takes: %d\n" % (t_af - t_bf)) return generate_message(STATUS_OK, SUCCESS_ACCOUNT_CREATED_MESSAGE) except IntegrityError as err: session.rollback() print(err) if err.orig.args[0].startswith(ERROR_ACCOUNT_EXISTED_CODE): return generate_message(STATUS_ERROR, ERROR_ACCOUNT_EXISTED_MESSAGE) return generate_message(STATUS_ERROR, ERROR_UNKNOWN_MESSAGE) except Exception as err: print(err) return generate_message(STATUS_ERROR, ERROR_UNKNOWN_MESSAGE)
async def get_user(self, login: str) -> Optional[UserAccount]: """ Get user with specified UUID. Just send str representation of UUID """ query = ("select u.login, u.salt, u.pword, u.super_id " "from user_account u " "where u.login = :login") result = await self.fetch_one(query=query, login=login) if result is None: return None else: return UserAccount(**result)
async def users_online_in_thread(self, thread_id: int) -> Iterable[UserAccount]: # TODO: thread_id is unused because all users connected to the server # can view all threads hence they are all online query = ( "select u.login, u.salt, u.pword, u.super_id, u.last_request_time " "from user_account u " "where u.last_request_time > now() - (1 * interval '1 minute')") online = await self.fetch_all(query=query) return map(lambda u: UserAccount(**u), online)
def get_users_account(account=None, profile=None): for acct in Account.select(): if not _check(acct.profile, profile): continue if not _check(acct, account): continue break else: raise ValueError('Account not found') return UserAccount.from_account(acct.id)
def regist(email, password): if check(email): raise DuplicateException(u"注册邮箱地址重复") ul = UserLogin(email, password) g.db.add(ul) g.db.flush() up = UserProfile(ul) uc = UserAccount(ul) g.db.add(up) g.db.add(uc) g.db.flush() g.db.commit() return ul.id
def home(path=None): if path: # reloading url paths currently not supported in client javascript return redirect(url_for('home')) try: #assert session['logged_in'] user_id = session['user'] user, accounts = UserAccount.from_user(user_id) except (KeyError, AssertionError, User.DoesNotExist, UserAccount.DoesNotExist): session.clear() return redirect(url_for('index')) user = user.__jsonify__() accounts = [account.__jsonify__() for account in accounts] return render_template('home.html', user=user, accounts=accounts)
def post(self): register_args = { 'userName': fields.Str(required=True), 'password': fields.Str(required=True), 'firstName': fields.Str(required=False), 'lastName': fields.Str(required=False) } request_args = parser.parse(register_args, request) userEmail = request_args['userName'] password = request_args['password'] firstName = request_args['firstName'] lastName = request_args['lastName'] # check if the users already exists user = UserAccount.query.filter_by(user_email=userEmail).first() if user: logger.error("User with email {} already exists. Registration failed.".format(userEmail)) return jsonify(authToken="", isRegistrationSuccessful=False, registrationErrorMessage="User with email {} already exists. Registration failed.".format( userEmail)) else: authToken = generate_hash_key() new_user_guid = generate_hash_key() user_account = UserAccount(userEmail, password, new_user_guid, False, datetime.now()) user_profile = UserProfile(new_user_guid, firstName, lastName) user_auth_token = AuthTokens(new_user_guid, authToken, -1) db.session.add(user_account) db.session.add(user_profile) db.session.add(user_auth_token) db.session.commit() logger.info("New user registered with email {}.".format(userEmail)) return jsonify(authToken=authToken, isRegistrationSuccessful=True, registrationErrorMessage="")
def login(account, remember=False): email = account.email() user = UserAccount.get_by_email(email) if user and flasklogin.login_user(user, remember): return True return False
def delete(user): if UserAccount.can_delete_user(user): return UserAccount.delete_user(user) return None
def create_users(): UserAccount.create(name='Tony') UserAccount.create(name='Bruce')
from models import Users, UserAccount user_account = UserAccount() def register(username, password): user = Users(username, password) user_account.signup(user) print('Successfully registerered!') def login(username, password): for account in user_account.accounts: if password == account['password'] and username == account['username']: return 'You are now logged In!' return "Sorry account does not exist, register if you don't have an account yet." def menu(): choice = input(""" 1.) r - register 2.) l - login 3.) d - display user account data 4.) cp - forgot/change password? 5.) s - save user account data 6.) c - check total count of users 7.) q - quit """) while choice != 'q': if choice == 'r': username1 = input('Enter Username: ')
def join(account, remember=False): user = UserAccount.create_user(account) if user and flasklogin.login_user(user, remember): return True return False