def test_get_current(): email = get_random_email() create_user(email, 'pass') token = login_user(email, 'pass') user = get_user(token=token) assert user['email'] == email assert user['balance'] == 2.5
def test_send_sms(): email = get_random_email() create_user(email, 'pass') token = login_user(email, 'pass') verify_user(token) send_sms(token, '+123', 'text', 'god') last_message = query_last_message('+123') assert last_message['text'] == 'text' assert last_message['from'] == 'god'
def post(self): # Create a new user if len(self.request.params) > 0: if helpers.authorized(self.request.params['UUID'], self.request.params['authToken'], self.request.params['action']): helpers.create_user(self.request, self.response, False) else: helpers.report_unauthorized_access(self.response) # Signup a new user else: helpers.create_user(self.request, self.response, True)
def test_balance_sms_send_balance_depleted(): email = get_random_email() create_user(email, 'pass') token = login_user(email, 'pass') verify_user(token) for dummy in xrange(5): send_sms(token, '+123', 'text', 'god') with pytest.raises(requests.HTTPError): send_sms(token, '+123', 'text', 'god')
async def subscribe(self, ctx): hp.create_user(str(ctx.author.id)) arg = " ".join(ctx.message.content.split()[1:]) # parses text after command if arg == "list": await ctx.channel.send(st.SUB_LIST.format('\n'.join(globals.users[str(ctx.author.id)].subscribtions))) else: if arg not in globals.users[str(ctx.author.id)].subscribtions: globals.users[str(ctx.author.id)].subscribtions.append(arg) await ctx.channel.send(st.SUB_RESPONSE.format(arg)) else: await ctx.channel.send(st.SUB_ERROR_EXISTING)
def setUp(self) -> None: self.user = helpers.create_user('alice', 'secret') http_auth_header = f'Token {self.user.auth_token.key}' self.client.credentials(HTTP_AUTHORIZATION=http_auth_header) self.other_user = helpers.create_user('bob', 'secret') helpers.set_exchange_rate(Currency.USD, decimal.Decimal(1.00)) helpers.set_exchange_rate(Currency.CNY, decimal.Decimal(6.94)) helpers.set_exchange_rate(Currency.EUR, decimal.Decimal(0.90)) helpers.set_commission_fee(decimal.Decimal(2))
def signup(request): signup_parameters = json.loads(request.body.decode('utf-8')) email = signup_parameters['email'] school = get_school_by_email(email) if school is not None: try: create_user(email, school) return HttpResponse('Signup OK') except DuplicateEmailError: return HttpResponse(content='Duplicate email', status=409) except ValueError: return HttpResponseBadRequest('Invalid email') return HttpResponseBadRequest('Invalid univesity email')
def test_register(app, db): user = helpers.create_user("test", "testtest") assert do_register(user) is True assert do_login(user.username, user.password) is True another_user = helpers.create_user("test", "otherpassword") assert do_register(another_user) is False user.remove() # try login deleted user assert do_login(user.username, user.password) is False
def signup(): if 'logged_in' in session: return redirect(url_for('home')) if request.method == 'POST': email = request.form['email'].strip().lower() password = request.form['password'] re_password = request.form['password'] if password != re_password: flash("Passwords do not match. Please try again!!") else: session['email'] = email session['logged_in'] = True create_user(email, bcrypt.generate_password_hash(password)) return redirect(url_for('home')) return render_template('signup.html')
async def add_warning(user, reason): if user.id not in globals.users: hp.create_user(str(user.id)) else: globals.users[user.id].warnings["number"] += 1 globals.users[user.id].warnings["reasons"].append(reason) event_log.info(f"{user.name} got warning because of {reason}." f"They have {str(globals.users[user.id].warnings['number'])} warnings.") if globals.users[user.id].warnings["number"] >= cn.WARNINGS_TO_BAN: try: await server.ban(user, reason=", ".join(globals.users[user.id].warnings["reasons"]), delete_message_days=0) await user.dm_channel.send(st.BAN_MSG.format(cn.WARNINGS_TO_BAN)) except Exception: await user.dm_channel.send(st.BAN_ERROR_U) await server.get_channel(cn.ADMIN_CHANNEL).send(st.BAN_ERROR_A.format(user.name)) event_log.exception("Error while issuing ban", exc_info=True) else: await user.dm_channel.send(st.WARNING_MSG.format(str(globals.users[user.id].warnings["number"]), str(cn.WARNINGS_TO_BAN)))
def test_delete_user(client, db): # create one user user = create_user(db) # delete user based on id r = client.delete('/user/{}'.format(user.id)) assert r.status_code == 204 # ensure user is deleted users = db.session.query(User).all() assert len(users) == 0
def signup(request): signup_parameters = json.loads(request.body.decode('utf-8')) email = signup_parameters.get('email') school = get_school_by_email(email) x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') previousDailyRegistrations = User.objects.filter(registrationIP=ip, date_joined__gte=(date.today() - timedelta(1))) if len(previousDailyRegistrations) > 5: return HttpResponse(content='Multiple registrations', status=403) if school is not None: try: create_user(email, school, ip) return HttpResponse('Signup OK') except DuplicateEmailError: return HttpResponse(content='Duplicate email', status=409) except ValueError: return HttpResponseBadRequest('Invalid email') return HttpResponseBadRequest('Invalid univesity email')
def test_get_user(client, db): # create one user user = create_user(db) # get user based on id r = client.get('/user/{}'.format(user.id)) assert r.status_code == 200 # ensure that it returns the same data data = json.loads(r.data) assert data['id'] == user.id assert data['email'] == user.email assert data['name'] == user.name
async def permaloop(): event_log.info("Entering permaloop ...") await globals.bot.wait_until_ready() while not globals.bot.is_closed(): checkpoint = time.time() modification = False for s in globals.seminars: modification = await s.make_request("ulohy") # check tasks for rnd in s.rounds.values(): modification = await s.make_request("vysledky", rnd.id) # check results for each round if modification: db.load(cn.FB_SEMINARS, s.name, s.to_dict()) # load to database if changes management_log.info("Changes loaded to database!") management_log.info(f"permaloop updated in {int((time.time()-checkpoint)*1000)}ms") # users update management_log.info("Creating and uploading {0} users".format(len(globals.server.members)-len(globals.users))) for mem in globals.server.members: hp.create_user(str(mem.id)) for userid in globals.users.keys(): db.load(cn.FB_USERS, str(userid), vars(globals.users[userid])) await asyncio.sleep(cn.MINIMAL_CHECKING_DELAY) event_log.error("Exited infinite loop")
def test_get_all_users(client, db): # create 3 users users = [create_user(db) for _ in xrange(3)] # get all users r = client.get('/user') assert r.status_code == 200 # ensure that it returns the same data (assume that the order of the objects are the same) data = json.loads(r.data) assert len(data['objects']) == 3 for i in xrange(3): assert data['objects'][i]['id'] == users[i].id assert data['objects'][i]['email'] == users[i].email assert data['objects'][i]['name'] == users[i].name
def process_issues(users, issues): ''' Process the issues and award users points. ''' for index, issue in enumerate(issues): if issue['state'] == 'closed': for user in users: if issue['closed_by'] is not None: if set(user['name'].split()).issubset( set(issue['closed_by']['name'].split())): user = update_user_points(user, issue, 'issue') break else: break else: new_user = create_user(issue, 'issue') users.append(new_user) elif issue['state'] == 'opened': for user in users: if issue['author'] is not None: if set(user['name'].split()).issubset( set(issue['author']['name'].split())): user = update_user_points(user, issue, 'issue') break else: break else: new_user = create_user(issue, 'issue') users.append(new_user) return users
def fbconnect(): '''Oauth with Facebook account''' if request.args.get('state') != login_session['state']: response = make_response(json.dumps('Invalid state parameter.'), 401) response.headers['Content-Type'] = 'application/json' return response access_token = request.data # Exchange client token for long-lived server side token with GET /oauth/ # acces_token?grant_type=fb_exchange_token&client_id={app-id} # &client_secret={app-secret}&fb_exchange_token={short-lived-token} app_id = json.loads(open('fb_client_secrets.json', 'r').read())['web'][ 'app_id'] app_secret = json.loads(open('fb_client_secrets.json', 'r').read())['web'][ 'app_secret'] url = 'https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=%s&client_secret=%s&fb_exchange_token=%s' % ( app_id, app_secret, access_token) h = httplib2.Http() result = h.request(url, 'GET')[1] # Use token to get user info from API userinfo_url = 'https://graph.facebook.com/v2.3/me' # strip expire tag from access token token = result.split('&')[0] url = 'https://graph.facebook.com/v2.3/me?%s' % token h = httplib2.Http() result = h.request(url, 'GET')[1] data = json.loads(result) login_session['provider'] = 'facebook' login_session['username'] = data['name'] login_session['email'] = data['email'] login_session['facebook_id'] = data['id'] # The token must be stored in the login_session in order to properly logout, # let's strip out the information before the equals sign in our token stored_token = token.split("=")[1] login_session['access_token'] = stored_token # check if user exists in the db user_id = get_user_id(data['email']) if user_id is None: user_id = create_user(login_session) login_session['user_id'] = user_id output = 'welcome ' + login_session['username'] flash('you are logged in as %s' % login_session['username']) return output
def process_merge_requests(users, merge_requests): ''' Process the merge requests and award users points. ''' for mr in merge_requests: for user in users: if set(user['name'].split()).issubset( set(mr['author']['name'].split())): user = update_user_points(user, mr, 'mr') break else: new_user = create_user(mr, 'mr') users.append(new_user) return users
def process_commits(users, commits): ''' Process the commits and award users points. ''' for commit in commits: for user in users: if set(commit['author_name'].split()).issubset( set(user['name'].split())): user = update_user_points(user, commit, 'commit') break else: new_user = create_user(commit, 'commit') users.append(new_user) return users
def post(self): if not login_using_local(): return self.error(404) email = self.request.get('email') password = self.request.get('password') errors = [] try: self.validate(email, password) logging.info('validated') user = create_user(email, password) logging.info('created user') self.authenticate(user, password) logging.info('authed') return self.redirect('/profile/edit') except Exception, e: logging.error('Error %s' % e) errors.append(str(e))
def get(self): if Profile.gql('WHERE user_email = :1', settings.NEWS_USER).get(): self.response.out.write('Already exist') return news = create_user(settings.NEWS_USER, 'halihalinews').get_user() #user = create_user('*****@*****.**', '1111').get_user() #person = create_user('*****@*****.**', '1111').get_user() #grade = create_user('*****@*****.**', '1111').get_user() #for i in range(1, 21): # ut = create_user('*****@*****.**' % i, '1111').get_user() # Follow.new(ut, user) # Follow.new(person, ut) #Follow.new(user, person) #Follow.new(person, grade) self.response.out.write('OK')
def fbconnect(): if request.args.get('state') != login_session['state']: response = make_response(json.dumps('Invalid state parameter.'), 401) response.headers['Content-Type'] = 'application/json' return response access_token = request.data # Exchanges client token for long-lived server-side token with /GET /oauth/ # access_token?grant_type=fb_exchange_token&client_id={app-id}&client_secret={app-secret}&fb_exchange_token= # {short-lived-token} app_id = json.loads(open('fb_client_secrets.json', 'r').read())['web']['app_id'] app_secret = json.loads(open('fb_client_secrets.json', 'r').read())['web']['app_secret'] url = FB_TOKEN_URL % (app_id, app_secret, access_token) result = request_to_url(url, value=1, to_json=False) # Use token to get user info from API and Strip Expire Tag from Access Token token = get_fb_token(result) userinfo_url = FB_USER_INFO_URL % token data = request_to_url(userinfo_url, value=1) login_session['provider'] = 'facebook' login_session['username'] = data["name"] login_session['email'] = data["email"] login_session['facebook_id'] = data["id"] # Get user picture url = FB_USER_PIC_URL % token data = request_to_url(url, value=1) login_session['picture'] = data['data']['url'] # See if user exists user_id = get_user_id(login_session['email']) if not user_id: user_id = create_user(login_session) login_session['user_id'] = user_id output = LOGIN_OUTPUT % (login_session['username'], login_session['picture']) flash(MESSAGE_LOGIN % login_session['username']) return output
def setUpClass(cls): cls.user = helpers.create_user(db, 'name', 'password', 'email') cls.project = create_project_with_name(PROJECT_NAME) cls.project1 = create_project_with_name(PROJECT_NAME + '2') cls.normal_bam = create_bam_with_name(cls.project['id'], 'normal', uri='/bam/path/normal.bam') cls.tumor_bam = create_bam_with_name(cls.project['id'], 'tumor', uri='/bam/path/tumor.bam') with tables(db.engine, 'vcfs') as (con, runs): res = runs.insert( {'uri': 'file://path/to/something.vcf', 'project_id': cls.project['id'], 'normal_bam_id': cls.normal_bam['id'], 'tumor_bam_id': cls.tumor_bam['id'], 'vcf_header': ''} ).returning(*runs.c).execute() cls.run = dict(res.fetchone()) cls.run2 = create_run_with_uri(cls.project['id'], 'http://someuri.vcf') cls.comment1 = create_comment_with_text(cls.run['id'], 'this is some text') cls.comment2 = create_comment_with_text(cls.run['id'], 'more text')
def test_update_user_full(client, db): # create one user user = create_user(db) user_id = user.id # update user with new data r = client.put('/user/{}'.format(user.id), headers=headers, data=json.dumps({ 'name': 'qwer', 'email': '*****@*****.**', 'password': '******', })) assert r.status_code == 204 # get user again user = User.query.first() # ensure data has been updated in database assert user.id == user_id assert user.email == '*****@*****.**' assert user.name == 'qwer' assert user.check_password('qwer')
def test_update_user_partial(client, db): # create one user user = create_user(db, email='abcd') user_id = user.id user.set_password('abcd') # ensure that partially updating user works r = client.patch('/user/{}'.format(user.id), headers=headers, data=json.dumps({ 'name': 'zxcv', })) assert r.status_code == 204 # get user again user = User.query.first() # ensure name is updated assert user.name == 'zxcv' # ensure other fields are the same as before update assert user.id == user_id assert user.email == 'abcd' assert user.check_password('abcd')
def gconnect(): if request.args.get('state') != login_session['state']: response = make_response(json.dumps('Invalid state parameter'), 401) response.headers['Content-Type'] = 'application/json' return response code = request.data try: # Upgrade the authorization code into a credentials object oauth_flow = flow_from_clientsecrets('client_secret.json', scope='') oauth_flow.redirect_uri = 'postmessage' credentials = oauth_flow.step2_exchange(code) except FlowExchangeError: response = make_response( json.dumps('Failed to upgrade the authorization code.'), 401) response.headers['Content-Type'] = 'application/json' return response # Check that the access token is valid. access_token = credentials.access_token url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % access_token) result = request_to_url(url, value=1) # If there was an error in the access token info, abort. if result.get('error') is not None: response = make_response(json.dumps(result.get('error')), 50) response.headers['Content-Type'] = 'application/json' # Verify that the access token is used for the intended user. gplus_id = credentials.id_token['sub'] if result['user_id'] != gplus_id: response = make_response( json.dumps("Token's user ID doesn't match given user ID."), 401) response.headers['Content-Type'] = 'application/json' return response # Verify that the access token is valid for this app. if result['issued_to'] != CLIENT_ID: response = make_response( json.dumps("Token's client ID does not match app's."), 401) response.headers['Content-Type'] = 'application/json' return response # Check to see if user is already logged in stored_credentials = login_session.get('credentials') stored_gplus_id = login_session.get('gplus_id') if stored_credentials is not None and gplus_id == stored_gplus_id: response = make_response( json.dumps('Current user is already connected.'), 200) response.headers['Content-Type'] = 'application/json' # Store the access token in the session for later use. login_session['provider'] = 'google' login_session['credentials'] = credentials login_session['gplus_id'] = gplus_id response = make_response(json.dumps('Successfully connected user.'), 200) # Get user info userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo" params = {'access_token': credentials.access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) data = json.loads(answer.text) login_session['username'] = data['name'] login_session['picture'] = data['picture'] login_session['email'] = data['email'] # See if user exists, if doesn't make a new one user_id = get_user_id(login_session['email']) if not user_id: user_id = create_user(login_session) login_session['user_id'] = user_id output = LOGIN_OUTPUT % (login_session['username'], login_session['picture']) flash(MESSAGE_LOGIN % login_session['username']) return output
def test_register_user_twice(): email = get_random_email() create_user(email, 'pass') with pytest.raises(requests.HTTPError): create_user(email, 'pass')
def test_login(): email = get_random_email() create_user(email, 'pass') token = login_user(email, 'pass') token = refresh_token(token)
def test_token_guard(): email = get_random_email() create_user(email, 'pass') token = login_user(email, 'pass') with pytest.raises(HTTPError): token = refresh_token(token + '1')
def test_login_with_bad_password(): email = get_random_email() create_user(email, 'pass') with pytest.raises(HTTPError): login_user(email, 'wrong_pass')
def login(): """Handles the whole login process. The GET endpoint displays a page with the google sign in button. The POST endpoint exchanges the client-fetched token with client's credentials. """ if request.method == 'GET': # Generate unique session token and rendering login prompt state_token = ''.join( random.choice(string.ascii_uppercase + string.digits) for i in range(32)) # Keeping a copy for later comparison to ensure no forgery happens login_session['state'] = state_token return render_template('login.html', state=state_token, client_id=CLIENT_ID) else: # Testing the 1-time auth code the user got from Google to login user # Request was forged if request.args.get('state') != login_session['state']: return helpers.build_response('Unauthorized request source.', 401) # This one-time code will be exchanged for an access token from Google one_time_auth = request.data # Exchanging the one-time auth with user's Google credentials try: oauth_flow = flow_from_clientsecrets('client_secret.json', scope='') oauth_flow.redirect_uri = 'postmessage' creds = oauth_flow.step2_exchange(one_time_auth) except FlowExchangeError: return helpers.build_response('Token exchange error.', 401) # Testing exchanged credentials access_token = creds.access_token target_url = ( 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token' '=%s' % access_token) req = httplib2.Http() result = json.loads(req.request(target_url, 'GET')[1]) if result.get('error') is not None: return helpers.build_response(result.get('error'), 500) google_id = creds.id_token['sub'] if result['user_id'] != google_id: return helpers.build_response( result.get('User and token IDs are not matching.'), 401) if result['issued_to'] != CLIENT_ID: return helpers.build_response( result.get( 'Token\'s target client ID doesn\'t match this client.'), 401) # If we got here then the OAuth process is successful valid_access_token = login_session.get('access_token') valid_google_id = login_session.get('gplus_id') # Checking if user is already logged in if valid_access_token and google_id == valid_google_id: return helpers.build_response('User already logged in.', 200) login_session['access_token'] = creds.access_token login_session['gplus_id'] = google_id userinfo_url = 'https://www.googleapis.com/oauth2/v1/userinfo' userinfo_res = requests.get(userinfo_url, params={ 'access_token': creds.access_token, 'alt': 'json' }) user_data = userinfo_res.json() login_session['email'] = user_data['email'] login_session['name'] = user_data['name'] login_session['pic'] = user_data['picture'] # Creating user if hasn't logged in before user_id = helpers.get_uid(user_data['email']) if not user_id: user_id = helpers.create_user(login_session) login_session['user_id'] = user_id flash('Welcome back, %s!' % login_session['name']) return redirect((url_for('home')))
def gconnect(): '''Oauth with Google account''' if request.args.get('state') != login_session['state']: response = make_response(json.dumps('Invalid state'), 401) response.headers['Content-Type'] = 'application/json' return response code = request.data try: # upgrade the authorisation code into a credential object oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='') oauth_flow.redirect_uri = 'postmessage' credentials = oauth_flow.step2_exchange(code) except FlowExchangeError: response = make_response(json.dumps('Failed to upgrade the auth code.'), 401) response.headers['Content-Type'] = 'application/json' return response # check that the access token is valid access_token = credentials.access_token url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % access_token) h = httplib2.Http() result = json.loads(h.request(url, 'GET')[1]) # if there was an error in the access token info, abort. if result.get('error') is not None: response = make_response(json_dumps(result.get('error')), 500) response.headers['Content-Type'] = 'application/json' # verify that the access token is used for the intended user. gplus_id = credentials.id_token['sub'] if result['user_id'] != gplus_id: response = make_response(json.dumps( "Token's user ID doesn't match given user ID"), 401) response.headers['Content-Type'] = 'application/json' return response # verify that the access token is valid for this app. if result['issued_to'] != CLIENT_ID: response = make_response( json.dumps("Token's client ID does not match app's"), 401) print "Token's client ID does not match app's." response.headers['Content-Type'] = 'application/json' return response # check to see if user is already logged in stored_credentials = login_session.get('credentials') stored_gplus_id = login_session.get('gplus_id') if stored_credentials is not None and gplus_id == stored_gplus_id: response = make_response(json.dumps( 'Current user is already connected.'), 200) response.headers['Content-Type'] = 'application/json' return response # store the access token in the session for later use login_session['credentials'] = credentials login_session['gplus_id'] = gplus_id # get user info userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo" params = {'access_token': credentials.access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) data = json.loads(answer.text) login_session['username'] = data['name'] login_session['email'] = data['email'] login_session['picture'] = data['picture'] login_session['provider'] = 'google' # check if user exists in the db user_id = get_user_id(data['email']) if user_id is None: user_id = create_user(login_session) login_session['user_id'] = user_id output = 'Welcome ' + login_session['username'] flash('you are logged in as %s' % login_session['username']) return output
def create_user(): return jsonify(message=helpers.create_user( request.json['username'], request.json['email'], request.json['password'], request.json['user_type']))
def call(self, out): if Profile.gql('WHERE user_email = :1', settings.NEWS_USER).get(): out.write('News user already exist') return news = create_user(settings.NEWS_USER, settings.NEWS_PASSWORD).get_user()
def test_send_sms_without_verify_throws_exception(): email = get_random_email() create_user(email, 'pass') token = login_user(email, 'pass') with pytest.raises(requests.HTTPError): send_sms(token, '+123', 'text', 'god')
def create(self, validated_data): with transaction.atomic(): user = helpers.create_user(validated_data['username'], validated_data['password']) return user
def install_wizard(): """ Runs a command-line series of prompt to gather proper paramaters and then creates the database """ # Check if SQLlite database file already exists if path.isfile('database.db'): overwrite = input( "The database file already exists. Would you like to discard it and start over?\nWARNING: This will delete the entire grant archive.\n(y/n): " ) if overwrite == 'n': # Exit if overwriting denied print("No chages made. Exiting.") exit() elif overwrite == 'y': # Backup old databse file and continue if overwriting accepted timestamp = datetime.now().strftime("%Y-%m-%d_%H:%M:%S") backup = "database_" + timestamp + ".db.bak" rename('database.db', backup) print("Old database backed up to file '" + backup + "'.") else: # Exit on invalid input print("Invalid Input. No Changes were made. Exiting.") exit("Input Error") # Prompt user for council number council = input( "Council Number (e.g. '35' for 35th Undergraduate Council): ") if not council.isdigit() or not int(council) in range(0, 100): print( 'Error: Council Number must be a 1-2 digit positive number.\nNo changes were made. Exiting.' ) exit("Input Error") # Promt user for semester semester = input("Current Semester ('F' for fall or 'S' for spring): ") if semester != 'S' and semester != 'F': print( "Error: Semester input must be either an 'S' or 'F'.\nNo changes were made. Exiting." ) exit("Input Error") # Prompt User for Current Grant Week in Semester week = input( "Grant Week in Semester (e.g. '1' for beginning of semester): ") if not week.isdigit() or not int(week) in range(1, 100): print( 'Error: Grant Week must be a 1-2 digit positive number.\nNo changes were made. Exiting.' ) exit("Input Error") # Prompt User for Weekly Default Budget budget = input("Default Weekly Budget: ") if not week.isdigit() or not int(week) > 0: print( 'Error: Default weekly budget must be a postitive whole number.\nNo changes were made. Exiting.' ) exit("Input Error") # Prompt user for admin email address to create admin user account email = input("Administrator Email: ") if not email: print( 'Error: Must enter an email address.\nNo changes were made. Exiting.' ) exit("Input Error") # Prompt user for admin first name to create admin user account first_name = input("Administrator First Name: ") if not first_name: print( 'Error: Must enter a first name.\nNo changes were made. Exiting.') exit("Input Error") # Prompt user for admin first name to create admin user account last_name = input("Administrator Last Name: ") if not last_name: print('Error: Must enter a last name.\nNo changes were made. Exiting.') exit("Input Error") # Prompt user for admin password to create admin user account password = getpass("Administrator Password: "******"Input Error") password_verify = getpass("Verify Password: "******"Input Error") # Prompt user for email account username print("Note: Application assumes Google as email account host server") grants_email_username = input("Grants Email Account Username: "******"Input Error") # Prompt user for email account password grants_email_password = getpass("Grants Email Account Password: "******"Input Error") # Prompt user for email account username print("Note: Application assumes Google as email account host server") treasurer_email_username = input("Treasurer Email Account Username: "******"Input Error") # Prompt user for email account password treasurer_email_password = getpass("Treasurer Email Account Password: "******"Input Error") # Prompt user for email account password server_name = input( "Server Name for building URLs (exclude 'http://' and '/'): ") if not server_name: print( 'Error: Must enter a server name.\nNo changes were made. Exiting.') exit("Input Error") # Prompt user for treasurer name treasurer_name = input("Treasurer's name: ") if not treasurer_name: print( 'Error: Must enter a treasurer name.\nNo changes were made. Exiting.' ) exit("Input Error") # Set application context for SQLAlchemy db.init_app(app) db.app = app # Create all database with all tables db.create_all() # Add security key configuration sec_key = Config('security_key', 'ZmL1kNBW1i') db.session.add(sec_key) # Add Council Number to config council_semester = Config('council_semester', council + semester) db.session.add(council_semester) # Add Grant Week to config grant_week = Config('grant_week', week) db.session.add(grant_week) # Add Default Weekly Budget default_budget = Config('default_budget', budget) db.session.add(default_budget) # Add Grants Email Account Username grants_email_username_db = Config('grants_email_username', grants_email_username) db.session.add(grants_email_username_db) # Add Grants Email Account Password grants_email_password_db = Config('grants_email_password', grants_email_password) db.session.add(grants_email_password_db) # Add Treasurer Email Account Username treasurer_email_username_db = Config('treasurer_email_username', treasurer_email_username) db.session.add(treasurer_email_username_db) # Add Treasurer Email Account Password treasurer_email_password_db = Config('treasurer_email_password', treasurer_email_password) db.session.add(treasurer_email_password_db) # Add Server Name server_name_db = Config('server_name', server_name) db.session.add(server_name_db) # Default to enabling email without asking user enable_email = Config('enable_email', '1') db.session.add(enable_email) # Add treasurer's name treasurer_name = Config('treasurer_name', treasurer_name) db.session.add(treasurer_name) # Add empty number of Grants for current week grants_week = Grants_Week(council + semester + '-' + week) grants_week.budget = budget db.session.add(grants_week) # Add administrator user account admin = create_user(email, first_name, last_name, password, True) db.session.add(admin) # Commit changes to databse db.session.commit() # Print success message print( "Successfully installed program configuration. Please run flask application to enable the website." )
def test_register(): email = get_random_email() new_user = create_user(email, 'pass') assert new_user['email'] == email
def setUp(self) -> None: self.user = helpers.create_user('john', 'secret') http_auth_header = f'Token {self.user.auth_token.key}' self.client.credentials(HTTP_AUTHORIZATION=http_auth_header)
def test_create_user(self): user = helpers.create_user() self.assertEqual(User.objects.get(username=user.username), user)