def create_type_lot(dbtype, item_id): """Create new item within the category in the database""" # check login status if 'email' not in login_session: flash('Sorry, the page you tried to access is for members only. ' 'Please sign in first.') return redirect(url_for(dbtype)) # get property names from table, check maximum lot# from ab and cytotoxin table = Table('%s_lot' % dbtype, meta, autoload=True, autoload_with=engine) max_ab_lot = (session.query(AntibodyLot) .order_by(desc(AntibodyLot.id)).first().id) max_cytotoxin_lot = (session.query(CytotoxinLot) .order_by(desc(CytotoxinLot.id)).first().id) origin_id = (session.query(eval(dbtype.capitalize())) .filter_by(id=item_id).one().user_id) user_id = get_user_id(login_session['email']) if request.method == 'POST': # instantiate new object new = eval(dbtype.capitalize()+'Lot')() for field in request.form: # set date attribute of new object with request form data if field == 'date': try: setattr(new, field, (datetime .strptime(request .form[field] .replace('-', ' '), '%Y %m %d'))) # in some cases users can input 6 digit year, catch this error except ValueError as detail: print 'Handling run-time error: ', detail flash('Invalid date detected. Please type the date in ' 'format: MM/DD/YYYY') return redirect(url_for(dbtype)) # set attribute of new object with request form data if hasattr(new, field): setattr(new, field, request.form[field]) setattr(new, dbtype+'_id', item_id) setattr(new, 'user_id', user_id) session.add(new) session.commit() flash('%s Lot Created' % dbtype.capitalize()) return redirect(url_for(dbtype)) else: return render_template('create-type-lot.html', dbtype=dbtype, columns=table.columns, item_id=item_id, max_ab_lot=max_ab_lot, max_cytotoxin_lot=max_cytotoxin_lot, origin_id=origin_id, user_id=get_user_id(login_session['email']))
def create_type_lot(dbtype, item_id): """Create new item within the category in the database""" # check login status if 'email' not in login_session: flash('Sorry, the page you tried to access is for members only. ' 'Please sign in first.') return redirect(url_for(dbtype)) # get property names from table, check maximum lot# from ab and cytotoxin table = Table('%s_lot' % dbtype, meta, autoload=True, autoload_with=engine) max_ab_lot = (session.query(AntibodyLot).order_by(desc( AntibodyLot.id)).first().id) max_cytotoxin_lot = (session.query(CytotoxinLot).order_by( desc(CytotoxinLot.id)).first().id) origin_id = (session.query(eval( dbtype.capitalize())).filter_by(id=item_id).one().user_id) user_id = get_user_id(login_session['email']) if request.method == 'POST': # instantiate new object new = eval(dbtype.capitalize() + 'Lot')() for field in request.form: # set date attribute of new object with request form data if field == 'date': try: setattr(new, field, (datetime.strptime( request.form[field].replace('-', ' '), '%Y %m %d'))) # in some cases users can input 6 digit year, catch this error except ValueError as detail: print 'Handling run-time error: ', detail flash('Invalid date detected. Please type the date in ' 'format: MM/DD/YYYY') return redirect(url_for(dbtype)) # set attribute of new object with request form data if hasattr(new, field): setattr(new, field, request.form[field]) setattr(new, dbtype + '_id', item_id) setattr(new, 'user_id', user_id) session.add(new) session.commit() flash('%s Lot Created' % dbtype.capitalize()) return redirect(url_for(dbtype)) else: return render_template('create-type-lot.html', dbtype=dbtype, columns=table.columns, item_id=item_id, max_ab_lot=max_ab_lot, max_cytotoxin_lot=max_cytotoxin_lot, origin_id=origin_id, user_id=get_user_id(login_session['email']))
def handle_message(message_id): """Returns one message if method is PUT, or deletes one message if method is DELETE.""" if not 'user_id' in session: return NOT_LOGGED_IN user_id = session['user_id'] conn = db_connection() cursor = conn.cursor() cursor.execute(f"SELECT * FROM messages WHERE id='{message_id}'") message = cursor.fetchone() if not message: return MESSAGES_NOT_FOUND sender_id = get_user_id(message['sender'], cursor) receiver_id = get_user_id(message['receiver'], cursor) if user_id != receiver_id and user_id != sender_id: return MESSAGES_NOT_FOUND if request.method == 'PUT': if user_id == receiver_id and message['viewed'] == 0: cursor.execute( f"UPDATE messages SET viewed=1 WHERE id='{message_id}'") conn.commit() del message['viewed'] return jsonify(message), OK else: # method is DELETE deleted = False if user_id == sender_id: deleted = delete_message(user_id, receiver_id, 'outbox', 'inbox', message_id, cursor) elif user_id == receiver_id: deleted = delete_message(user_id, sender_id, 'inbox', 'outbox', message_id, cursor) else: return MESSAGES_NOT_FOUND conn.commit() if deleted: return MESSAGE_DELETED return MESSAGES_NOT_FOUND
def write_message(): """Sends a message to another user. Updates the sender's outbox as well as the receiver's inbox""" conn = db_connection() cursor = conn.cursor() sender, receiver, message, subject = get_form_params_post(request) creation_date = date.today().strftime('%d/%m/%Y') sender_id = get_user_id(sender, cursor) receiver_id = get_user_id(receiver, cursor) # Inserting into messages, inbox and outbox message_id = insert_into_messages(sender, receiver, message, subject, creation_date, cursor) insert_into_mailbox(receiver_id, message_id, cursor, 'inbox') insert_into_mailbox(sender_id, message_id, cursor, 'outbox') conn.commit() return MESSAGE_CREATED
def create_type(dbtype): """ Create new category (within 3 pre-defined type) in the database """ # check login status if 'email' not in login_session: flash('Sorry, the page you tried to access is for members only. ' 'Please sign in first.') return redirect(url_for(dbtype)) # get property names from table table = Table(dbtype, meta, autoload=True, autoload_with=engine) user_id = get_user_id(login_session['email']) if request.method == 'POST': # instantiate new object new = eval(dbtype.capitalize())() for field in request.form: # set attribute of new object with request form data if hasattr(new, field): setattr(new, field, request.form[field]) setattr(new, 'user_id', user_id) session.add(new) session.commit() flash('%s Created' % dbtype.capitalize()) # upload image image = request.files['picture'] if image and allowed_file(image.filename): with store_context(fs_store): new.picture.from_file(image) # prevent user uploading unsupported file type elif image and not allowed_file(image.filename): flash('Unsupported file detected. No image has been uploaded.') return redirect(url_for(dbtype)) else: return render_template('create-type.html', columns=table.columns, dbtype=dbtype)
def google_login(): """Implement Oauth 2.0 login method with user's Google account""" # Validate state token 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 # Obtain authorization code, now compatible with Python3 request.get_data() code = request.data.decode('utf-8') try: # Upgrade the authorization code into a credentials object oauth_flow = flow_from_clientsecrets( os.path.join(app_path, '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 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) # Submit request, parse response - Python3 compatible h = httplib2.Http() response = h.request(url, 'GET')[1] str_response = response.decode('utf-8') result = json.loads(str_response) # 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'] != google_client_secrets['web']['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 stored_access_token = login_session.get('access_token') stored_gplus_id = login_session.get('gplus_id') if stored_access_token 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['access_token'] = access_token login_session['gplus_id'] = gplus_id # Get user info userinfo_url = "https://www.googleapis.com/oauth2/v2/userinfo" params = {'access_token': access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) data = answer.json() login_session['username'] = data['name'] login_session['picture'] = data['picture'] login_session['email'] = data['email'] login_session['provider'] = 'google' # see if user exists, if it 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 = '' output += '<h1>Welcome, ' output += login_session['username'] output += '!</h1>' output += '<img src="' output += login_session['picture'] output += ' " style = "width: 300px; height: 300px;border-radius: 150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;"> ' flash("You are now signed in as %s" % login_session['email']) return output
def facebook_login(): """Implement Oauth 2.0 login method with user's 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 print "access token received %s " % access_token app_id = facebook_client_secrets['web']['app_id'] app_secret = facebook_client_secrets['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.5/me" # strip expire tag from access token token = result.split("&")[0] url = 'https://graph.facebook.com/v2.5/me?%s&fields=name,id,email' % token h = httplib2.Http() result = h.request(url, 'GET')[1] print result # print "url sent for API access:%s"% url # print "API JSON result: %s" % result 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 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 # Get user picture url = 'https://graph.facebook.com/v2.5/me/picture?%s&redirect=0&height=200&width=200' % token h = httplib2.Http() result = h.request(url, 'GET')[1] data = json.loads(result) 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 = '' output += '<h1>Welcome, ' output += login_session['username'] output += '!</h1>' output += '<img src="' output += login_session['picture'] output += ' " style = "width: 300px; height: 300px;border-radius: 150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;"> ' flash("You are now signed in as %s" % login_session['username']) return output
def gconnect(): # Validate state token 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 # Obtain authorization code, now compatible with Python3 request.get_data() code = request.data.decode('utf-8') try: # Upgrade the authorization code into a credentials 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 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) # Submit request, parse response - Python3 compatible h = httplib2.Http() response = h.request(url, 'GET')[1] str_response = response.decode('utf-8') result = json.loads(str_response) # 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) response.headers['Content-Type'] = 'application/json' return response stored_access_token = login_session.get('access_token') stored_gplus_id = login_session.get('gplus_id') if stored_access_token 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['access_token'] = access_token login_session['gplus_id'] = gplus_id # Get user info userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo" params = {'access_token': access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) data = answer.json() login_session['username'] = data['name'] login_session['picture'] = data['picture'] login_session['email'] = data['email'] # see if user exists, if it 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 = '' output += '<h1>Welcome, ' output += login_session['username'] output += '!</h1>' output += '<img src="' output += login_session['picture'] output += ' " style = "width: 300px; height: 300px;border-radius: 150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;"> ' flash("you are now logged in as %s" % login_session['username']) return output
def test_get_user_id(self): """Test get_user_id function""" self.assertEqual(helper.get_user_id('*****@*****.**'), 1)