def login (): body = request.json # Validations if not type_check (body, 'dict'): return 'body must be an object', 400 if not object_check (body, 'username', 'str'): return 'username must be a string', 400 if not object_check (body, 'password', 'str'): return 'password must be a string', 400 # If username has an @-sign, then it's an email if '@' in body ['username']: user = db_get ('users', {'email': body ['username'].strip ().lower ()}, True) else: user = db_get ('users', {'username': body ['username'].strip ().lower ()}) if not user: return 'invalid username/password', 403 if not check_password (body ['password'], user ['password']): return 'invalid username/password', 403 cookie = make_salt () db_set ('tokens', {'id': cookie, 'username': user ['username'], 'ttl': times () + session_length}) db_set ('users', {'username': user ['username'], 'last_login': timems ()}) resp = make_response ({}) resp.set_cookie (cookie_name, value=cookie, httponly=True, path='/') return resp
def recover (): body = request.json # Validations if not type_check (body, 'dict'): return 'body must be an object', 400 if not object_check (body, 'username', 'str'): return 'body.username must be a string', 400 # If username has an @-sign, then it's an email if '@' in body ['username']: user = db_get ('users', {'email': body ['username'].strip ().lower ()}, True) else: user = db_get ('users', {'username': body ['username'].strip ().lower ()}) if not user: return 'invalid username', 403 token = make_salt () hashed = hash (token, make_salt ()) db_set ('tokens', {'id': user ['username'], 'token': hashed, 'ttl': times () + session_length}) if not env: # If on local environment, we return email verification token directly instead of emailing it, for test purposes. return jsonify ({'username': user ['username'], 'token': token}), 200 else: send_email_template ('recover_password', user ['email'], requested_lang (), os.getenv ('BASE_URL') + '/reset?username='******'username']) + '&token=' + urllib.parse.quote_plus (token)) return '', 200
def login(): body = request.json # Validations if not type_check(body, 'dict'): return 'body must be an object', 400 if not object_check(body, 'username', 'str'): return 'username must be a string', 400 if not object_check(body, 'password', 'str'): return 'password must be a string', 400 # If username has an @-sign, then it's an email if '@' in body['username']: user = db_get('users', {'email': body['username'].strip().lower()}, True) else: user = db_get('users', {'username': body['username'].strip().lower()}) if not user: return 'invalid username/password', 403 if not check_password(body['password'], user['password']): return 'invalid username/password', 403 # If the number of bcrypt rounds has changed, create a new hash. new_hash = None if config['bcrypt_rounds'] != extract_bcrypt_rounds(user['password']): new_hash = hash(body['password'], make_salt()) cookie = make_salt() db_set( 'tokens', { 'id': cookie, 'username': user['username'], 'ttl': times() + session_length }) if new_hash: db_set( 'users', { 'username': user['username'], 'password': new_hash, 'last_login': timems() }) else: db_set('users', { 'username': user['username'], 'last_login': timems() }) resp = make_response({}) # We set the cookie to expire in a year, just so that the browser won't invalidate it if the same cookie gets renewed by constant use. # The server will decide whether the cookie expires. resp.set_cookie(cookie_name, value=cookie, httponly=True, secure=True, samesite='Lax', path='/', max_age=365 * 24 * 60 * 60) return resp
def current_user(): now = times() user = session.get('user', {'username': '', 'email': ''}) ttl = session.get('user-ttl', None) if ttl == None or now >= ttl: username = user['username'] if username: db_user = DATABASE.user_by_username(username) remember_current_user(db_user) return user
def login(): body = request.json # Validations if not isinstance(body, dict): return 'body must be an object', 400 if not isinstance(body.get('username'), str): return 'username must be a string', 400 if not isinstance(body.get('password'), str): return 'password must be a string', 400 # If username has an @-sign, then it's an email if '@' in body['username']: user = DATABASE.user_by_email(body['username']) else: user = DATABASE.user_by_username(body['username']) if not user: return 'invalid username/password', 403 if not check_password(body['password'], user['password']): return 'invalid username/password', 403 # If the number of bcrypt rounds has changed, create a new hash. new_hash = None if config['bcrypt_rounds'] != extract_bcrypt_rounds(user['password']): new_hash = hash(body['password'], make_salt()) cookie = make_salt() DATABASE.store_token({ 'id': cookie, 'username': user['username'], 'ttl': times() + session_length }) if new_hash: DATABASE.record_login(user['username'], new_hash) else: DATABASE.record_login(user['username']) resp = make_response({}) # We set the cookie to expire in a year, just so that the browser won't invalidate it if the same cookie gets renewed by constant use. # The server will decide whether the cookie expires. resp.set_cookie(TOKEN_COOKIE_NAME, value=cookie, httponly=True, secure=is_heroku(), samesite='Lax', path='/', max_age=365 * 24 * 60 * 60) # Remember the current user on the session. This is "new style" logins, which should ultimately # replace "old style" logins (with the cookie above), as it requires fewer database calls. remember_current_user(user) return resp
def record_quiz_answer(self, attempt_id, username, level, question_number, answer, is_correct): """Update the current quiz record with a new answer. Uses a DynamoDB update to add to the exising record. """ key = { "user": username, "levelAttempt": str(level).zfill(4) + '_' + attempt_id, } updates = { "attemptId": attempt_id, "level": level, "date": times(), "q" + str(question_number): dynamo.DynamoAddToList(answer), } if is_correct: updates['correct'] = dynamo.DynamoAddToNumberSet( int(question_number)) return QUIZ_ANSWERS.update(key, updates)
def recover(): body = request.json # Validations if not isinstance(body, dict): return 'body must be an object', 400 if not isinstance(body.get('username'), str): return 'body.username must be a string', 400 # If username has an @-sign, then it's an email if '@' in body['username']: user = DATABASE.user_by_email(body['username'].strip().lower()) else: user = DATABASE.user_by_username(body['username'].strip().lower()) if not user: return 'invalid username', 403 token = make_salt() hashed = hash(token, make_salt()) DATABASE.store_token({ 'id': user['username'], 'token': hashed, 'ttl': times() + session_length }) if is_testing_request(request): # If this is an e2e test, we return the email verification token directly instead of emailing it. return jsonify({'username': user['username'], 'token': token}), 200 else: send_email_template( 'recover_password', user['email'], requested_lang(), os.getenv('BASE_URL') + '/reset?username='******'username']) + '&token=' + urllib.parse.quote_plus(token)) return '', 200
if isinstance(module, list): modules += module else: modules.append(module) if commandArgs.type == 'none': #from motor.motor import Motor #modules.append(Motor()) pass elif commandArgs.type == "dummy": from motor.motor import DummyMotor add(DummyMotor()) elif commandArgs.type == 'motor_hat': from motor.motorhat import MotorHat forward = json.loads(commandArgs.forward) backward = times(forward, -1) left = json.loads(commandArgs.left) right = times(left, -1) straightDelay = commandArgs.straight_delay turnDelay = commandArgs.turn_delay add(MotorHat(commandArgs.driving_speed, commandArgs.day_speed, commandArgs.night_speed, forward, backward, left, right, straightDelay, turnDelay)) elif commandArgs.type == 'gopigo2': from motor.gopigo2 import GoPiGo2 add(GoPiGo2()) elif commandArgs.type == 'gopigo3': from motor.gopigo3 import GoPiGo3 add(GoPiGo3()) elif commandArgs.type == 'l298n': from motor.l298n import L298N add(L298N()) elif commandArgs.type == 'motozero':
def signup(): body = request.json # Validations, mandatory fields if not type_check(body, 'dict'): return 'body must be an object', 400 if not object_check(body, 'username', 'str'): return 'username must be a string', 400 if '@' in body['username']: return 'username cannot contain an @-sign', 400 if ':' in body['username']: return 'username cannot contain a colon', 400 if len(body['username'].strip()) < 3: return 'username must be at least three characters long', 400 if not object_check(body, 'password', 'str'): return 'password must be a string', 400 if len(body['password']) < 6: return 'password must be at least six characters long', 400 if not object_check(body, 'email', 'str'): return 'email must be a string', 400 if not re.match( '^(([a-zA-Z0-9_\.\-]+)@([\da-zA-Z\.\-]+)\.([a-zA-Z\.]{2,6})\s*)$', body['email']): return 'email must be a valid email', 400 # Validations, optional fields if 'country' in body: if not body['country'] in countries: return 'country must be a valid country', 400 if 'birth_year' in body: if not object_check( body, 'birth_year', 'int') or body['birth_year'] <= 1900 or body[ 'birth_year'] > datetime.datetime.now().year: return 'birth_year must be a year between 1900 and ' + datetime.datetime.now( ).year, 400 if 'gender' in body: if body['gender'] != 'm' and body['gender'] != 'f' and body[ 'gender'] != 'o': return 'gender must be m/f/o', 400 user = db_get('users', {'username': body['username'].strip().lower()}) if user: return 'username exists', 403 email = db_get('users', {'email': body['email'].strip().lower()}, True) if email: return 'email exists', 403 hashed = hash(body['password'], make_salt()) token = make_salt() hashed_token = hash(token, make_salt()) username = body['username'].strip().lower() email = body['email'].strip().lower() if env and 'subscribe' in body and body['subscribe'] == True: # If we have a Mailchimp API key, we use it to add the subscriber through the API if os.getenv('MAILCHIMP_API_KEY') and os.getenv( 'MAILCHIMP_AUDIENCE_ID'): # The first domain in the path is the server name, which is contained in the Mailchimp API key request_path = 'https://' + os.getenv( 'MAILCHIMP_API_KEY').split( '-')[1] + '.api.mailchimp.com/3.0/lists/' + os.getenv( 'MAILCHIMP_AUDIENCE_ID') + '/members' request_headers = { 'Content-Type': 'application/json', 'Authorization': 'apikey ' + os.getenv('MAILCHIMP_API_KEY') } request_body = {'email_address': email, 'status': 'subscribed'} r = requests.post(request_path, headers=request_headers, data=json.dumps(request_body)) subscription_error = None if r.status_code != 200 and r.status_code != 400: subscription_error = True # We can get a 400 if the email is already subscribed to the list. We should ignore this error. if r.status_code == 400 and not re.match( '.*already a list member', r.text): subscription_error = True # If there's an error in subscription through the API, we report it to the main email address if subscription_error: send_email( config['email']['sender'], 'ERROR - Subscription to Hedy newsletter on signup', email, '<p>' + email + '</p><pre>Status:' + str(r.status_code) + ' Body:' + r.text + '</pre>') # Otherwise, we send an email to notify about this to the main email address else: send_email(config['email']['sender'], 'Subscription to Hedy newsletter on signup', email, '<p>' + email + '</p>') user = { 'username': username, 'password': hashed, 'email': email, 'created': timems(), 'verification_pending': hashed_token } if 'country' in body: user['country'] = body['country'] if 'birth_year' in body: user['birth_year'] = body['birth_year'] if 'gender' in body: user['gender'] = body['gender'] db_set('users', user) # We automatically login the user cookie = make_salt() db_set( 'tokens', { 'id': cookie, 'username': user['username'], 'ttl': times() + session_length }) db_set('users', {'username': user['username'], 'last_login': timems()}) # If on local environment, we return email verification token directly instead of emailing it, for test purposes. if not env: resp = make_response({'username': username, 'token': hashed_token}) # Otherwise, we send an email with a verification link and we return an empty body else: send_email_template( 'welcome_verify', email, requested_lang(), os.getenv('BASE_URL') + '/auth/verify?username='******'&token=' + urllib.parse.quote_plus(hashed_token)) resp = make_response({}) # We set the cookie to expire in a year, just so that the browser won't invalidate it if the same cookie gets renewed by constant use. # The server will decide whether the cookie expires. resp.set_cookie(cookie_name, value=cookie, httponly=True, secure=True, samesite='Lax', path='/', max_age=365 * 24 * 60 * 60) return resp
#coding:utf-8 #引入函数 from utils import times #调用函数 a = "itsource " b = 10 s = times(a, b) print "The multiplication of {0} and {1} is: \n{2}".format(a, b, s)
def signup(): body = request.json # Validations, mandatory fields if not isinstance(body, dict): return 'body must be an object', 400 if not isinstance(body.get('username'), str): return 'username must be a string', 400 if '@' in body['username']: return 'username cannot contain an @-sign', 400 if ':' in body['username']: return 'username cannot contain a colon', 400 if len(body['username'].strip()) < 3: return 'username must be at least three characters long', 400 if not isinstance(body.get('password'), str): return 'password must be a string', 400 if len(body['password']) < 6: return 'password must be at least six characters long', 400 if not isinstance(body.get('email'), str): return 'email must be a string', 400 if not valid_email(body['email']): return 'email must be a valid email', 400 # Validations, optional fields if 'country' in body: if not body['country'] in countries: return 'country must be a valid country', 400 if 'birth_year' in body: if not isinstance(body.get('birth_year'), int) or body['birth_year'] <= 1900 or body[ 'birth_year'] > datetime.datetime.now().year: return 'birth_year must be a year between 1900 and ' + datetime.datetime.now( ).year, 400 if 'gender' in body: if body['gender'] != 'm' and body['gender'] != 'f' and body[ 'gender'] != 'o': return 'gender must be m/f/o', 400 if 'prog_experience' in body and body['prog_experience'] not in [ 'yes', 'no' ]: return 'If present, prog_experience must be "yes" or "no"', 400 if 'experience_languages' in body: if not isinstance(body['experience_languages'], list): return 'If present, experience_languages must be an array', 400 for language in body['experience_languages']: if language not in [ 'scratch', 'other_block', 'python', 'other_text' ]: return 'Invalid language: ' + str(language), 400 user = DATABASE.user_by_username(body['username'].strip().lower()) if user: return 'username exists', 403 email = DATABASE.user_by_email(body['email'].strip().lower()) if email: return 'email exists', 403 hashed = hash(body['password'], make_salt()) token = make_salt() hashed_token = hash(token, make_salt()) username = body['username'].strip().lower() email = body['email'].strip().lower() if not is_testing_request( request) and 'subscribe' in body and body['subscribe'] == True: # If we have a Mailchimp API key, we use it to add the subscriber through the API if os.getenv('MAILCHIMP_API_KEY') and os.getenv( 'MAILCHIMP_AUDIENCE_ID'): # The first domain in the path is the server name, which is contained in the Mailchimp API key request_path = 'https://' + os.getenv( 'MAILCHIMP_API_KEY').split( '-')[1] + '.api.mailchimp.com/3.0/lists/' + os.getenv( 'MAILCHIMP_AUDIENCE_ID') + '/members' request_headers = { 'Content-Type': 'application/json', 'Authorization': 'apikey ' + os.getenv('MAILCHIMP_API_KEY') } request_body = {'email_address': email, 'status': 'subscribed'} r = requests.post(request_path, headers=request_headers, data=json.dumps(request_body)) subscription_error = None if r.status_code != 200 and r.status_code != 400: subscription_error = True # We can get a 400 if the email is already subscribed to the list. We should ignore this error. if r.status_code == 400 and not re.match( '.*already a list member', r.text): subscription_error = True # If there's an error in subscription through the API, we report it to the main email address if subscription_error: send_email( config['email']['sender'], 'ERROR - Subscription to Hedy newsletter on signup', email, '<p>' + email + '</p><pre>Status:' + str(r.status_code) + ' Body:' + r.text + '</pre>') # Otherwise, we send an email to notify about this to the main email address else: send_email(config['email']['sender'], 'Subscription to Hedy newsletter on signup', email, '<p>' + email + '</p>') user = { 'username': username, 'password': hashed, 'email': email, 'created': timems(), 'verification_pending': hashed_token, 'last_login': timems() } for field in [ 'country', 'birth_year', 'gender', 'prog_experience', 'experience_languages' ]: if field in body: if field == 'experience_languages' and len(body[field]) == 0: continue user[field] = body[field] DATABASE.store_user(user) print(user) # We automatically login the user cookie = make_salt() DATABASE.store_token({ 'id': cookie, 'username': user['username'], 'ttl': times() + session_length }) # If this is an e2e test, we return the email verification token directly instead of emailing it. if is_testing_request(request): resp = make_response({'username': username, 'token': hashed_token}) # Otherwise, we send an email with a verification link and we return an empty body else: send_email_template( 'welcome_verify', email, requested_lang(), os.getenv('BASE_URL', 'http://localhost') + '/auth/verify?username='******'&token=' + urllib.parse.quote_plus(hashed_token)) resp = make_response({}) # We set the cookie to expire in a year, just so that the browser won't invalidate it if the same cookie gets renewed by constant use. # The server will decide whether the cookie expires. resp.set_cookie(cookie_name, value=cookie, httponly=True, secure=is_heroku(), samesite='Lax', path='/', max_age=365 * 24 * 60 * 60) return resp
def signup(): body = request.json # Validations, mandatory fields if not type_check(body, 'dict'): return 'body must be an object', 400 if not object_check(body, 'username', 'str'): return 'username must be a string', 400 if '@' in body['username']: return 'username cannot contain an @-sign', 400 if ':' in body['username']: return 'username cannot contain a colon', 400 if len(body['username'].strip()) < 3: return 'username must be at least three characters long', 400 if not object_check(body, 'password', 'str'): return 'password must be a string', 400 if len(body['password']) < 6: return 'password must be at least six characters long', 400 if not object_check(body, 'email', 'str'): return 'email must be a string', 400 if not re.match( '^(([a-zA-Z0-9_\.\-]+)@([\da-zA-Z\.\-]+)\.([a-zA-Z\.]{2,6})\s*)$', body['email']): return 'email must be a valid email', 400 # Validations, optional fields if 'country' in body: if not body['country'] in countries: return 'country must be a valid country', 400 if 'birth_year' in body: if not object_check( body, 'birth_year', 'int') or body['birth_year'] <= 1900 or body[ 'birth_year'] > datetime.datetime.now().year: return 'birth_year must be a year between 1900 and ' + datetime.datetime.now( ).year, 400 if 'gender' in body: if body['gender'] != 'm' and body['gender'] != 'f' and body[ 'gender'] != 'o': return 'gender must be m/f/o', 400 user = db_get('users', {'username': body['username'].strip().lower()}) if user: return 'username exists', 403 email = db_get('users', {'email': body['email'].strip().lower()}, True) if email: return 'email exists', 403 hashed = hash(body['password'], make_salt()) token = make_salt() hashed_token = hash(token, make_salt()) username = body['username'].strip().lower() email = body['email'].strip().lower() if env and 'subscribe' in body and body['subscribe'] == True: send_email(config['email']['sender'], 'Subscription to Hedy newsletter on signup', email, '<p>' + email + '</p>') user = { 'username': username, 'password': hashed, 'email': email, 'created': timems(), 'verification_pending': hashed_token } if 'country' in body: user['country'] = body['country'] if 'birth_year' in body: user['birth_year'] = body['birth_year'] if 'gender' in body: user['gender'] = body['gender'] db_set('users', user) # We automatically login the user cookie = make_salt() db_set( 'tokens', { 'id': cookie, 'username': user['username'], 'ttl': times() + session_length }) db_set('users', {'username': user['username'], 'last_login': timems()}) # If on local environment, we return email verification token directly instead of emailing it, for test purposes. if not env: resp = make_response({'username': username, 'token': hashed_token}) # Otherwise, we send an email with a verification link and we return an empty body else: send_email_template( 'welcome_verify', email, requested_lang(), os.getenv('BASE_URL') + '/auth/verify?username='******'&token=' + urllib.parse.quote_plus(hashed_token)) resp = make_response({}) resp.set_cookie(cookie_name, value=cookie, httponly=True, path='/') return resp
def remember_current_user(db_user): session['user-ttl'] = times() + 5 * 60 session['user'] = pick(db_user, 'username', 'email', 'is_teacher')