def __init__(self, ap: ap.authProvider, basePath, maxZipSize=50e6, tmpFolder=None, tmpFolderDuratioInDays=7, user=None, hiddenItems=None): if hiddenItems is None: hiddenItems = [] self.hiddenItems = set(hiddenItems) self.basePath = os.path.abspath(basePath) self.maxZipSize = maxZipSize self.tmpFolder = tmpFolder.lstrip("/") self.tmpFolderDuration = tmpFolderDuratioInDays * 24 * 60 * 60 self.user = h.getUserID(user) self.ap = ap self.cleanTmpThread = None if self.tmpFolder is not None: tmpPath = h.makePath(self.basePath, self.tmpFolder) if not os.path.exists(tmpPath): h.makeDir(tmpPath) if self.user is not None: h.changeFileOwner(tmpPath, self.user) ap.setListingForbidden(self.tmpFolder) ap.setDownloadForbidden(self.tmpFolder) ap.setShowForbidden(self.tmpFolder) ap.setShareForbidden(self.tmpFolder) ap.setEditAllowed(self.tmpFolder) self.cleanTmpThread = CleanTmp(tmpPath, self.tmpFolderDuration) self.cleanTmpThread.start()
def createTypeLot(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) maxablot = (session.query(AntibodyLot) .order_by(desc(AntibodyLot.id)).first().id) maxtoxinlot = (session.query(CytotoxinLot) .order_by(desc(CytotoxinLot.id)).first().id) originID = (session.query(eval(dbtype.capitalize())) .filter_by(id=item_id).one().user_id) user_id = getUserID(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, maxablot=maxablot, maxtoxinlot=maxtoxinlot, originID=originID, userID=getUserID(login_session['email']))
def __init__(self, sharesPath, user=None, locationEnabled=False, locationAPIKey=""): self.user = h.getUserID(user) self.sharesPath = h.makeDirPath(os.path.abspath(sharesPath)) if self.user is not None: h.changeFileOwner(self.sharesPath, self.user) self.locationEnabled = locationEnabled self.locationAPIKey = locationAPIKey
def __init__(self, basePath, ip: ip.itemsProvider, maxSize=5e5, user=None, locationEnabled=False, locationAPIKey=""): self.ip = ip self.basePath = os.path.abspath(basePath) self.maxSize = maxSize self.user = h.getUserID(user) self.locationEnabled = locationEnabled self.locationAPIKey = locationAPIKey self.trackings = [] # type: List[tracking] self.trackingsSaved = True self.trackingsLock = Lock() self.saveTrackingsThread = SaveTrackings(self, 500) self._loadTrackings() self.saveTrackingsThread.start()
def createType(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 = getUserID(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 gconnect(): """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 = getUserID(login_session['email']) if not user_id: user_id = createUser(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 fbconnect(): """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 "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 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 # 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 = getUserID(login_session['email']) if not user_id: user_id = createUser(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