def test(path, args): username = args['username'] # enforce types if args.has_key('version'): args['version'] = int(args['version']) if args.has_key('mtime_sec'): args['mtime_sec'] = int(args['mtime_sec']) if args.has_key('mtime_nsec'): args['mtime_nsec'] = int(args['mtime_nsec']) if args.has_key('mode'): args['mode'] = int(args['mode']) if args.has_key('size'): args['size'] = int(args['size']) volume_name = args['volume_name'] volume = storage.read_volume(volume_name) if volume == None: raise Exception("No such volume '%s'" % volume_name) user = storage.read_user(username) if user == None: raise Exception("No such user '%s'" % username) # update the entry rc = storage.update_msentry(user, volume, path, **args) if rc != 0: raise Exception("storage.update_msentry rc = %s" % rc) return (200, "OK")
def urlcreate(request, volume_name, g_name, g_password, host, port, read_write): session = request.session username = session['login_email'] user = db.read_user(username) kwargs = {} kwargs['port'] = int(port) kwargs['host'] = host kwargs['ms_username'] = g_name kwargs['ms_password'] = g_password kwargs['read_write'] = read_write vol = db.read_volume(volume_name) if not vol: return HttpResponse("No volume %s exists." % volume_name) if (vol.volume_id not in user.volumes_r) and (vol.volume_id not in user.volumes_rw): return HttpResponse( "Must have read rights to volume %s to create UG for it." % volume_name) try: new_ug = db.create_user_gateway(user, vol, **kwargs) except Exception as E: return HttpResponse("UG creation error: %s" % E) return HttpResponse("UG succesfully created: " + str(new_ug))
def test( path, args ): username = args['username'] # enforce types if args.has_key('version'): args['version'] = int(args['version']) if args.has_key( 'mtime_sec' ): args['mtime_sec'] = int(args['mtime_sec']) if args.has_key( 'mtime_nsec' ): args['mtime_nsec'] = int(args['mtime_nsec']) if args.has_key( 'mode' ): args['mode'] = int(args['mode']) if args.has_key( 'size' ): args['size'] = int(args['size']) volume_name = args['volume_name'] volume = storage.read_volume( volume_name ) if volume == None: raise Exception("No such volume '%s'" % volume_name ) user = storage.read_user( username ) if user == None: raise Exception("No such user '%s'" % username ) # update the entry rc = storage.update_msentry( user, volume, path, **args ) if rc != 0: raise Exception("storage.update_msentry rc = %s" % rc) return (200, "OK")
def wrapper(*args, **kw): session = args[0].session user = db.read_user(session['login_email']) vol = db.read_volume(kw['volume_id']) if not vol: return redirect('django_volume.views.failure') if user.owner_id != vol.owner_id: return redirect('django_volume.views.failure') return f(*args, **kw)
def test( path, args ): username = args['username'] volume_name = args['volume_name'] user = storage.read_user( username ) if user == None: raise Exception("user '%s' does not exist" % username ) volume = storage.read_volume( volume_name ) if volume == None: raise Exception("volume '%s' does not exist" % volume_name ) ents = [] if not path.endswith("/"): # read file ent = storage.read_msentry( user, volume, path ) if ent == None: raise Exception("No such entry: %s" % path ) if type(ent) == types.IntType: raise Exception("storage.read_msentry rc = %d" % ent ) ents.append( ent ) else: # read dir parent = storage.read_msentry( user, volume, path ) if parent == None: raise Exception("No such entry: %s" % path) if type(parent) == types.IntType: raise Exception("storage.read_msentry rc = %d" % parent) ents = storage.read_msentry_children( volume, path, parent.num_children ) ents = [parent] + ents msg = "<table border=\"1\"><tr>" for attr in MSEntry.required_attrs: msg += "<td><b>" + attr + "</b></td>" msg += "</tr>" for ent in ents: msg += "<tr>" for attr in MSEntry.required_attrs: msg += "<td>" + str( getattr(ent, attr) ) + "</td>" msg += "</tr>" msg += "</table>" return (200, msg)
def test(path, args): username = args['username'] volume_name = args['volume_name'] user = storage.read_user(username) if user == None: raise Exception("user '%s' does not exist" % username) volume = storage.read_volume(volume_name) if volume == None: raise Exception("volume '%s' does not exist" % volume_name) ents = [] if not path.endswith("/"): # read file ent = storage.read_msentry(user, volume, path) if ent == None: raise Exception("No such entry: %s" % path) if type(ent) == types.IntType: raise Exception("storage.read_msentry rc = %d" % ent) ents.append(ent) else: # read dir parent = storage.read_msentry(user, volume, path) if parent == None: raise Exception("No such entry: %s" % path) if type(parent) == types.IntType: raise Exception("storage.read_msentry rc = %d" % parent) ents = storage.read_msentry_children(volume, path, parent.num_children) ents = [parent] + ents msg = "<table border=\"1\"><tr>" for attr in MSEntry.required_attrs: msg += "<td><b>" + attr + "</b></td>" msg += "</tr>" for ent in ents: msg += "<tr>" for attr in MSEntry.required_attrs: msg += "<td>" + str(getattr(ent, attr)) + "</td>" msg += "</tr>" msg += "</table>" return (200, msg)
def urldelete(request, g_id, g_password): session = request.session username = session['login_email'] user = db.read_user(username) ug = db.read_user_gateway(g_id) if not ug: return HttpResponse("UG %d does not exist." % g_id) if ug.owner_id != user.owner_id: return HttpResponse("You must own this UG to delete it.") if not UG.authenticate(ug, g_password): return HttpResponse("Incorrect UG password.") db.delete_user_gateway(g_id) return HttpResponse("Gateway succesfully deleted.")
def changepassword(request, g_id): session = request.session username = session['login_email'] user = db.read_user(username) g_id = int(g_id) if request.method != "POST": return redirect('django_ug.views.viewgateway', g_id) g = db.read_user_gateway(g_id) if not g: logging.error("Error reading gateway %d : Gateway does not exist." % g_id) message = "No user gateway by the name of %d exists." % g_id t = loader.get_template("gateway_templates/viewgateway_failure.html") c = Context({'message': message, 'username': username}) return HttpResponse(t.render(c)) form = libforms.ChangePassword(request.POST) if not form.is_valid(): session['message'] = "You must fill out all password fields." return redirect('django_ug.views.viewgateway', g_id) else: # Check password hash if not UG.authenticate(g, form.cleaned_data['oldpassword']): session['message'] = "Incorrect password." return redirect('django_ug.views.viewgateway', g_id) elif form.cleaned_data['newpassword_1'] != form.cleaned_data[ 'newpassword_2']: session['message'] = "Your new passwords did not match each other." return redirect('django_ug.views.viewgateway', g_id) # Ok to change password else: new_hash = UG.generate_password_hash( form.cleaned_data['newpassword_1']) fields = {'ms_password_hash': new_hash} try: db.update_user_gateway(g_id, **fields) except Exception as e: logging.error( "Unable to update user gateway %s. Exception %s" % (g_name, e)) session['message'] = "Unable to update gateway." return redirect('django_ug.views.viewgateway', g_id) session['new_change'] = "We've changed your gateways's password." session['next_url'] = '/syn/UG/viewgateway/' + str(g_id) session['next_message'] = "Click here to go back to your volume." return HttpResponseRedirect('/syn/thanks')
def wrapper(*args, **kw): session = args[0].session if 'authenticated' in session: user = db.read_user(session['login_email']) if user: return f(*args, **kw) else: kwargs = {} kwargs['email'] = session['login_email'] kwargs['openid_url'] = session['openid_url'] user = db.create_user(**kwargs) session['user_key'] = user return f(*args, **kw) else: return redirect('/')
def get( self, user_email ): # get the user try: user = storage.read_user( user_email ) except: response_end( self, 404, "No such user", "text/plain") return if user == None: response_end( self, 404, "No such user", "text/plain") user_cert_dict = user.makeCert() user_cert_txt = jsonrpc.json_stable_serialize( user_cert_dict ) response_end( self, 200, user_cert_txt, "application/json" ) return
def get(self, user_email): # get the user try: user = storage.read_user(user_email) except: response_end(self, 404, "No such user", "text/plain") return if user == None: response_end(self, 404, "No such user", "text/plain") user_cert_dict = user.makeCert() user_cert_txt = jsonrpc.json_stable_serialize(user_cert_dict) response_end(self, 200, user_cert_txt, "application/json") return
def test( path, args ): username = args['username'] volume_name = args['volume_name'] volume = storage.read_volume( volume_name ) if volume == None: raise Exception( "volume %s' does not exist" % volume_name ) user = storage.read_user( username ) if user == None: raise Exception( "user '%s' does not exist" % username ) # create the entry ftype = MSENTRY_TYPE_FILE size = 0 delim = "" if path.endswith("/"): ftype = MSENTRY_TYPE_DIR size = 4096 delim = "/" now_sec, now_nsec = storage.clock_gettime() rc = storage.create_msentry( user, volume, ftype=ftype, fs_path=path, url=os.path.join( "http://localhost:32780/", path.strip('/') ) + delim, version=1, ctime_sec=now_sec, ctime_nsec=now_nsec, mtime_sec=now_sec, mtime_nsec=now_nsec, owner_id=user.owner_id, volume_id=volume.volume_id, mode=0755, size=size ) if rc != 0: raise Exception("storage.create_msentry rc = %s" % rc) return (200, "OK")
def read_user(email_or_user_id): """ Read a user. Positional arguments: email_or_user_id (str or int): The email address or numerical owner ID of the desired user. Returns: A SyndicateUser object on success, or an exception if the user does not exist or if the caller is not allowed to read this user's account. Authorization: The administrator can read any user account. A user can only read itself. """ return storage.read_user(email_or_user_id)
def register_load_objects(gateway_type_str, gateway_name, username): """ Load up a gateway and user object from the datastore, given the type of gateway, the name of the gateway, and the username. Return an HTTP status code, as well, to be sent back to the caller in case of error. """ # get the gateway status, gateway = register_load_gateway(gateway_type_str, gateway_name) if status != 200: return (status, None, None) user = storage.read_user(username) if user == None: logging.error("No such user '%s'" % username) return (401, None, None) return (200, gateway, user)
def register_load_objects( gateway_type_str, gateway_name, username ): """ Load up a gateway and user object from the datastore, given the type of gateway, the name of the gateway, and the username. Return an HTTP status code, as well, to be sent back to the caller in case of error. """ # get the gateway status, gateway = register_load_gateway( gateway_type_str, gateway_name ) if status != 200: return (status, None, None) user = storage.read_user( username ) if user == None: logging.error("No such user '%s'" % username) return (401, None, None) return (200, gateway, user)
def test(path, args): volume_name = args['volume_name'] username = args['username'] user = storage.read_user(username) volume = storage.read_volume(volume_name) if user == None: raise Exception("No such user '%s'" % username) if volume == None: raise Exception("No such volume '%s'" % volume_name) # delete the entry rc = storage.delete_msentry(user, volume, path) if rc != 0: raise Exception("storage.delete_msentry rc = %s" % rc) return (200, "OK")
def test(path, args): volume_name = args["volume_name"] username = args["username"] user = storage.read_user(username) volume = storage.read_volume(volume_name) if user == None: raise Exception("No such user '%s'" % username) if volume == None: raise Exception("No such volume '%s'" % volume_name) # delete the entry rc = storage.delete_msentry(user, volume, path) if rc != 0: raise Exception("storage.delete_msentry rc = %s" % rc) return (200, "OK")
def viewvolume(request, volume_id): session = request.session username = session['login_email'] user = db.read_user(username) vol = db.read_volume(volume_id) if not vol: return redirect('django_volume.views.failure') UserInfo = namedtuple("UserInfo", ["email", "caps_str"]) user_info = [] user_info.append(UserInfo(email=user.email, caps_str="owner")) rw_users = db.list_rw_volume_users(vol.volume_id, sort=True, projection=['email']) ro_users = db.list_ro_volume_users(vol.volume_id, sort=True, projection=['email']) for u in rw_users: user_info.append(UserInfo(email=u.email, caps_str="read/write")) for u in ro_users: user_info.append(UserInfo(email=u.email, caps_str="read-only")) rgs = db.list_replica_gateways_by_volume(vol.volume_id) ags = db.list_acquisition_gateways_by_volume(vol.volume_id) t = loader.get_template('viewvolume.html') c = RequestContext( request, { 'username': username, 'volume': vol, 'ags': ags, 'rgs': rgs, 'user_info': user_info }) return HttpResponse(t.render(c))
def get( self, volume_name ): # get the volume try: volume = storage.read_volume( volume_name ) except: response_end( self, 404, "No such volume", "text/plain") return # get the owner try: user = storage.read_user( volume.owner_id ) except: response_end( self, 404, "No such user", "text/plain") return if user == None: response_end( self, 404, "No such user", "text/plain") user_cert_dict = user.makeCert() user_cert_txt = json.dumps( user_cert_dict ) response_end( self, 200, user_cert_txt, "application/json" ) return
def get(self, volume_name): # get the volume try: volume = storage.read_volume(volume_name) except: response_end(self, 404, "No such volume", "text/plain") return # get the owner try: user = storage.read_user(volume.owner_id) except: response_end(self, 404, "No such user", "text/plain") return if user == None: response_end(self, 404, "No such user", "text/plain") user_cert_dict = user.makeCert() user_cert_txt = json.dumps(user_cert_dict) response_end(self, 200, user_cert_txt, "application/json") return
def test(path, args): username = args['username'] volume_name = args['volume_name'] user = storage.read_user(username) volume = storage.read_volume(volume_name) if user == None: raise Exception("No such user '%s'" % username) if volume == None: raise Exception("No such volume '%s'" % volume_name) # resolve a path reply = Resolve(user, volume, path) # parse the reply reply_struct = ms_pb2.ms_reply() try: reply_struct.ParseFromString(reply) except Exception, e: raise Exception("Invalid Protobuf string")
def test( path, args ): username = args['username'] volume_name = args['volume_name'] user = storage.read_user( username ) volume = storage.read_volume( volume_name ) if user == None: raise Exception("No such user '%s'" % username ) if volume == None: raise Exception("No such volume '%s'" % volume_name) # resolve a path reply = Resolve( user, volume, path ) # parse the reply reply_struct = ms_pb2.ms_reply() try: reply_struct.ParseFromString( reply ) except Exception, e: raise Exception("Invalid Protobuf string")
def myvolumes(request): ''' View that display all of user's owned volumes ''' session = request.session username = session['login_email'] user = db.read_user(username) vols_owned = [] vols_rw = [] vols_ro = [] if user.volumes_o: vols_owned = db.list_volumes({"Volume.volume_id IN": user.volumes_o}) if user.volumes_rw: volumes_rw_without_o = list(set(user.volumes_o) - set(user.volumes_rw)) if volumes_rw_without_o: vols_rw = db.list_volumes( {"Volume.volume_id IN": volumes_rw_without_o}) if user.volumes_r: vols_ro = db.list_Volumes({"Volume.volume_id IN": user.volumes_r}) # filter out volumes that I own that I can also read/write t = loader.get_template('myvolumes.html') c = Context({ 'username': username, 'vols_owned': vols_owned, 'vols_rw': vols_rw, 'vols_ro': vols_ro }) return HttpResponse(t.render(c))
def mygateways(request): ''' Show all of logged in user's UG's ''' session = request.session username = session['login_email'] user = db.read_user(username) try: attrs = {"UserGateway.owner_id ==": user.owner_id} gateways = db.list_user_gateways(attrs) except: gateways = [] vols = [] for g in gateways: vols.append(db.read_volume(g.volume_id)) gateway_vols = zip(gateways, vols) t = loader.get_template('gateway_templates/myusergateways.html') c = RequestContext(request, { 'username': username, 'gateway_vols': gateway_vols }) return HttpResponse(t.render(c))
def handle( self, action ): self.load_query() if action is None: # in a session. Check the session cookie to authenticate. session = self.getSession( expiration_ts=int(time.time() + 60) ) # expire in 1 minute if not session.get("authenticated"): # unauthorized logging.error("Unauthorized session") response_user_error( self, 403 ) return username = session.get("username") if username is None: # no username given logging.error("No username given") response_user_error( self, 403 ) return self.call_method( self.API_AUTH_OPENID, username=username ) return elif action == self.API_AUTH_PUBKEY: self.call_method( action ) elif action == self.API_AUTH_OPENID_BEGIN: # start an API call, using OpenID to authenticate the caller # get the username username = self.query.get( OPENID_POST_USERNAME ) if username is None: logging.error("No username given") response_user_error( self, 401 ) return # get the user user = storage.read_user( username ) if user == None: logging.error("No such user '%s'" % username) response_user_error( self, 401 ) return # start a session session = self.getSession( expiration_ts=int(time.time() + 60) ) # expire in 1 minute # begin the OpenID authentication try: oid_request, rc = self.begin_openid_auth() except consumer.DiscoveryFailure, exc: fetch_error_string = 'Error in discovery: %s' % (cgi.escape(str(exc[0]))) response_server_error( self, 500, fetch_error_string ) return if rc != 0: response_server_error( self, 500, "OpenID error %s" % rc ) return # reply with the redirect URL return_to = self.buildURL( "/API/%s" % (self.API_AUTH_OPENID_COMPLETE) ) data = register_make_openid_reply( oid_request, self.OPENID_RP_REDIRECT_METHOD, return_to, self.query ) # save this for the 'complete' operation session['username'] = username self.setSessionCookie(session) session.save( persist_even_if_using_cookie=True ) response_end( self, 200, data, "application/octet-stream", None ) return
def handle(self, action): self.load_query() if action is None: # in a session. Check the session cookie to authenticate. session = self.getSession( expiration_ts=int(time.time() + 60)) # expire in 1 minute if not session.get("authenticated"): # unauthorized logging.error("Unauthorized session") response_user_error(self, 403) return username = session.get("username") if username is None: # no username given logging.error("No username given") response_user_error(self, 403) return self.call_method(self.API_AUTH_OPENID, username=username) return elif action == self.API_AUTH_PUBKEY: self.call_method(action) elif action == self.API_AUTH_OPENID_BEGIN: # start an API call, using OpenID to authenticate the caller # get the username username = self.query.get(OPENID_POST_USERNAME) if username is None: logging.error("No username given") response_user_error(self, 401) return # get the user user = storage.read_user(username) if user == None: logging.error("No such user '%s'" % username) response_user_error(self, 401) return # start a session session = self.getSession( expiration_ts=int(time.time() + 60)) # expire in 1 minute # begin the OpenID authentication try: oid_request, rc = self.begin_openid_auth() except consumer.DiscoveryFailure, exc: fetch_error_string = 'Error in discovery: %s' % (cgi.escape( str(exc[0]))) response_server_error(self, 500, fetch_error_string) return if rc != 0: response_server_error(self, 500, "OpenID error %s" % rc) return # reply with the redirect URL return_to = self.buildURL("/API/%s" % (self.API_AUTH_OPENID_COMPLETE)) data = register_make_openid_reply(oid_request, self.OPENID_RP_REDIRECT_METHOD, return_to, self.query) # save this for the 'complete' operation session['username'] = username self.setSessionCookie(session) session.save(persist_even_if_using_cookie=True) response_end(self, 200, data, "application/octet-stream", None) return
def changepermissions(request, volume_id): ''' This view handles modification or removal of rights to the volume for users who already had some rights. ''' session = request.session username = session['login_email'] vol = db.read_volume(volume_id) if not vol: return redirect('django_volume.views.viewvolume', volume_id) PermissionFormSet = formset_factory(forms.Permissions, extra=0) if request.method != "POST": return redirect('/syn/volume/' + str(vol.volume_id) + '/permissions') else: passwordform = libforms.Password(request.POST) formset = PermissionFormSet(request.POST) if not passwordform.is_valid(): session['message'] = "Password required." return redirect('django_volume.views.volumepermissions', vol.volume_id) else: # Check password hash if vol.volume_secret_salted_hash != Volume.generate_password_hash( passwordform.cleaned_data['password'], vol.volume_secret_salt): session['message'] = "Incorrect password" return redirect('django_volume.views.volumepermissions', vol.volume_id) if not formset.is_valid(): session['message'] = "Invalid field entries." return redirect('django_volume.views.volumepermissions', vol.volume_id) else: initial_and_forms = zip(session['initial_perms' + str(volume_id)], formset.forms) for data, form in initial_and_forms: check_username = data['user'] check_read = form.cleaned_data['read'] check_write = form.cleaned_data['write'] check_user = db.read_user(check_username) if check_write and not check_read: session[ 'message'] = "Write permissions require read permissions as well." return redirect('django_volume.views.volumepermissions', vol.volume_id) if data['write']: if check_write: continue elif check_read: # Give read, take away write new_volumes_r = check_user.volumes_r + [vol.volume_id] new_volumes_rw = check_user.volumes_rw.remove( vol.volume_id) if not new_volumes_rw: new_volumes_rw = [] fields = { 'volumes_r': new_volumes_r, 'volumes_rw': new_volumes_rw } db.update_user(check_username, **fields) else: # change to no permissions new_volumes_rw = check_user.volumes_rw.remove( vol.volume_id) if not new_volumes_rw: new_volumes_rw = [] fields = {'volumes_rw': new_volumes_rw} db.update_user(check_username, **fields) elif data['read']: if check_write: # Give write, take away read new_volumes_r = check_user.volumes_r.remove( vol.volume_id) new_volumes_rw = check_user.volumes_rw + [ vol.volume_id ] if not new_volumes_r: new_volumes_r = [] fields = { 'volumes_r': new_volumes_r, 'volumes_rw': new_volumes_rw } db.update_user(check_username, **fields) elif check_read: continue else: # change to no permissions new_volumes_r = check_user.volumes_r.remove( vol.volume_id) if not new_volumes_r: new_volumes_r = [] fields = {'volumes_r': new_volumes_r} db.update_user(check_username, **fields) # Clear out stale data. session.pop("initial_perms" + str(volume_id), None) session['new_change'] = "We've saved your new permissions." session['next_url'] = '/syn/volume/' + str( vol.volume_id) + '/permissions' session[ 'next_message'] = "Click here to see your volumes permissions." return redirect('/syn/thanks')
def addpermissions(request, volume_id): ''' This handler allows adding users to volumes so they can have either read access or read and write access. ''' session = request.session username = session['login_email'] if request.method != "POST": return redirect('syn/volume/' + str(vol.volume_id) + '/permissions') else: vol = db.read_volume(volume_id) if not vol: return redirect('django_volume.views.viewvolume', volume_id) addform = forms.AddPermissions(request.POST) passwordform = libforms.Password(request.POST) if not passwordform.is_valid(): session['message'] = "Password required." return redirect('django_volume.views.volumepermissions', vol.volume_id) else: # Check password hash if vol.volume_secret_salted_hash != Volume.generate_password_hash( passwordform.cleaned_data['password'], vol.volume_secret_salt): session['message'] = "Incorrect password" return redirect('django_volume.views.volumepermissions', vol.volume_id) if not addform.is_valid(): session[ 'message'] = "Incorrect entry fields: likely invalid email address." return redirect('django_volume.views.volumepermissions', vol.volume_id) # Ok to update else: new_username = addform.cleaned_data['user'] read = addform.cleaned_data['read'] write = addform.cleaned_data['write'] for data in session['initial_perms' + str(volume_id)]: if data['user'] == new_username: session['message'] = "User already has rights for volume." return redirect('django_volume.views.volumepermissions', vol.volume_id) new_user = db.read_user(new_username) if not new_user: session[ 'message'] = "No Syndicate user with the email {} exists.".format( new_username) return redirect('django_volume.views.volumepermissions', vol.volume_id) if vol.owner_id == new_user.owner_id: session['message'] = "You already own this volume." return redirect('django_volume.views.volumepermissions', vol.volume_id) if write: if read: new_volumes_rw = new_user.volumes_rw + [vol.volume_id] fields = {'volumes_rw': new_volumes_rw} db.update_user(new_username, **fields) else: session[ 'message'] = "Write permissions require read permissions as well." return redirect('django_volume.views.volumepermissions', vol.volume_id) elif read: new_volumes_r = new_user.volumes_r + [vol.volume_id] fields = {'volumes_r': new_volumes_r} db.update_user(new_username, **fields) # Clear out old permissions data. session.pop('initial_perms' + str(volume_id), None) session['new_change'] = "We've saved a new user to your volume." session['next_url'] = '/syn/volume/' + str( vol.volume_id) + '/permissions' session[ 'next_message'] = "Click here to see your volumes permissions." return redirect('/syn/thanks')
def create(request): ''' View to handle creation of AG's ''' session = request.session username = session['login_email'] user = db.read_user(username) # Helper method used to simplify error-handling. When fields are entered incorrectly, # a session message is set and this method is called. def give_create_form(username, session): message = session.pop('message', "") form = gatewayforms.CreateAG() t = loader.get_template( 'gateway_templates/create_acquisition_gateway.html') c = RequestContext(request, { 'username': username, 'form': form, 'message': message }) return HttpResponse(t.render(c)) if request.POST: # Validate input forms form = gatewayforms.CreateAG(request.POST, request.FILES) if form.is_valid(): kwargs = {} # Try and load JSON config file/data, if present. First check uploaded files, then # the text box. if "json_config" in request.FILES: if request.FILES['json_config'].multiple_chunks(): session[ 'message'] = "Uploaded file too large; please make smaller than 2.5M" return give_create_form(username, session) config = request.FILES['json_config'].read() try: kwargs['json_config'] = json.loads(config) except Exception as e: logging.info("Possible JSON load error: %s" % e) try: kwargs['json_config'] = json.loads("\"" + config + "\"") except Exception as e: logging.error("Definite JSON load error %s" % e) session['message'] = "Error parsing given JSON text." return give_create_form(username, session) # No upload, check text box. elif "json_config_text" in form.cleaned_data: try: kwargs['json_config'] = json.loads( form.cleaned_data['json_config_text']) except Exception as e: logging.info("Possible JSON load error: %s" % e) try: kwargs['json_config'] = json.loads( "\"" + str(form.cleaned_data['json_config_text']) + "\"") except Exception as e: logging.error("Definite JSON load error %s" % e) session['message'] = "Error parsing given JSON text." return give_create_form(username, session) try: kwargs['ms_username'] = form.cleaned_data['g_name'] kwargs['port'] = form.cleaned_data['port'] kwargs['host'] = form.cleaned_data['host'] kwargs['ms_password'] = form.cleaned_data['g_password'] new_ag = db.create_acquisition_gateway(user, **kwargs) except Exception as E: session['message'] = "AG creation error: %s" % E return give_create_form(username, session) session['new_change'] = "Your new gateway is ready." session['next_url'] = '/syn/AG/allgateways' session[ 'next_message'] = "Click here to see your acquisition gateways." return redirect('/syn/thanks/') else: # Prep returned form values (so they don't have to re-enter stuff) if 'g_name' in form.errors: oldname = "" else: oldname = request.POST['g_name'] if 'host' in form.errors: oldhost = "" else: oldhost = request.POST['host'] if 'port' in form.errors: oldport = "" else: oldport = request.POST['port'] oldjson = request.POST['json_config_text'] # Prep error message message = "Invalid form entry: " for k, v in form.errors.items(): message = message + "\"" + k + "\"" + " -> " for m in v: message = message + m + " " # Give them the form again form = gatewayforms.CreateAG( initial={ 'g_name': oldname, 'host': oldhost, 'port': oldport, 'json_config_text': oldjson, }) t = loader.get_template( 'gateway_templates/create_acquisition_gateway.html') c = RequestContext(request, { 'username': username, 'form': form, 'message': message }) return HttpResponse(t.render(c)) else: # Not a POST, give them blank form return give_create_form(username, session)
def changevolume(request, g_id): ''' View to enable changing volume attached to UG ''' session = request.session username = session['login_email'] user = db.read_user(username) g_id = int(g_id) g = db.read_user_gateway(g_id) # Isolate DB calls to allow roll-backs via transactions @transactional(xg=True) def update_ug_and_vol(g_id, gfields, vol1_id, vol2_id): db.update_user_gateway(g_id, **gfields) attrs = {"UG_version": 1} # Force update of UG version db.update_volume(vol1_id, **attrs) db.update_volume(vol2_id, **attrs) form = gatewayforms.ChangeVolume(request.POST) if form.is_valid(): attrs = { "Volume.name ==": form.cleaned_data['volume_name'].strip().replace(" ", "_") } vols = db.list_volumes(attrs, limit=1) if vols: new_vol = vols[0] else: session['message'] = "No volume %s exists." % form.cleaned_data[ 'volume_name'] return redirect('django_ug.views.viewgateway', g_id) if (new_vol.volume_id not in user.volumes_r) and (new_vol.volume_id not in user.volumes_rw): session[ 'message'] = "Must have read rights to volume %s to assign UG to it." % form.cleaned_data[ 'volume_name'] return redirect('django_ug.views.viewgateway', g_id) old_vol = g.volume_id #fields = {"volume_id":new_vol.volume_id, "cert_version": True} try: db.update_user_gateway(g_id, volume_id=new_vol.volume_id, cert_version=True) db.update_volume(new_vol.volume_id, version=True, cert_version=True) if g.is_bound_to_volume(): # update the old Volume db.update_volume(old_vol, version=True, cert_version=True) #update_ug_and_vol(g_id, fields, old_vol, new_vol.volume_id) except Exception, e: logging.error("Unable to update UG with ID %s. Error was %s." % (g_id, e)) session['message'] = "Error. Unable to change user gateway." return redirect('django_ug.views.viewgateway', g_id) session['new_change'] = "We've updated your UG." session['next_url'] = '/syn/UG/viewgateway/' + str(g_id) session['next_message'] = "Click here to go back to your gateway." return HttpResponseRedirect('/syn/thanks')
def create(request): ''' View for creating UG's ''' session = request.session username = session['login_email'] user = db.read_user(username) # Helper method that simplifies returning forms after user error. def give_create_form(username, session): message = session.pop('message', "") form = gatewayforms.CreateUG() t = loader.get_template('gateway_templates/create_user_gateway.html') c = RequestContext(request, { 'username': username, 'form': form, 'message': message }) return HttpResponse(t.render(c)) if request.POST: # Validate input forms form = gatewayforms.CreateUG(request.POST) if form.is_valid(): if not form.cleaned_data['volume_name']: logging.info("DLFKJSDF") vol = None else: attrs = { "Volume.name ==": form.cleaned_data['volume_name'].strip().replace(" ", "_") } vols = db.list_volumes(attrs, limit=1) if vols: vol = vols[0] else: session[ 'message'] = "No volume %s exists." % form.cleaned_data[ 'volume_name'] return give_create_form(username, session) if (vol.volume_id not in user.volumes_r) and (vol.volume_id not in user.volumes_rw): session[ 'message'] = "Must have read rights to volume %s to create UG for it." % form.cleaned_data[ 'volume_name'] return give_create_form(username, session) # Force update of UG version attrs = {"UG_version": 1} try: transaction( lambda: db.update_volume(vol.volume_id, **attrs)) except Exception as E: session['message'] = "UG creation error: %s" % E return give_create_form(username, session) try: # Prep kwargs kwargs = {} kwargs['read_write'] = form.cleaned_data['read_write'] kwargs['ms_username'] = form.cleaned_data['g_name'] kwargs['port'] = form.cleaned_data['port'] kwargs['host'] = form.cleaned_data['host'] kwargs['ms_password'] = form.cleaned_data['g_password'] # Create new_ug = db.create_user_gateway(user, vol, **kwargs) except Exception as E: session['message'] = "UG creation error: %s" % E return give_create_form(username, session) session['new_change'] = "Your new gateway is ready." session['next_url'] = '/syn/UG/mygateways' session['next_message'] = "Click here to see your gateways." return HttpResponseRedirect('/syn/thanks/') else: # Prep returned form values (so they don't have to re-enter stuff) if 'g_name' in form.errors: oldname = "" else: oldname = request.POST['g_name'] if 'volume_name' in form.errors: oldvolume_name = "" else: oldvolume_name = request.POST['volume_name'] if 'host' in form.errors: oldhost = "" else: oldhost = request.POST['host'] if 'port' in form.errors: oldport = "" else: oldport = request.POST['port'] # Prep error message message = "Invalid form entry: " for k, v in form.errors.items(): message = message + "\"" + k + "\"" + " -> " for m in v: message = message + m + " " # Give then the form again form = gatewayforms.CreateUG( initial={ 'g_name': oldname, 'volume_name': oldvolume_name, 'host': oldhost, 'port': oldport, }) t = loader.get_template( 'gateway_templates/create_user_gateway.html') c = RequestContext(request, { 'username': username, 'form': form, 'message': message }) return HttpResponse(t.render(c)) else: # Not a POST, give them blank form return give_create_form(username, session)
def create(request): ''' View to handle creation of RG's ''' session = request.session username = session['login_email'] user = db.read_user( username ) # Helper method used to simplify error-handling. When fields are entered incorrectly, # a session message is set and this method is called. def give_create_form(username, session): message = session.pop('message', "") form = gatewayforms.CreateRG() t = loader.get_template('gateway_templates/create_replica_gateway.html') c = RequestContext(request, {'username':username,'form':form, 'message':message}) return HttpResponse(t.render(c)) if request.POST: # Validate input forms form = gatewayforms.CreateRG(request.POST, request.FILES) if form.is_valid(): kwargs = {} # Try and load JSON config file/data, if present. First check uploaded files, then # the text box. if "json_config" in request.FILES: if request.FILES['json_config'].multiple_chunks(): session['message'] = "Uploaded file too large; please make smaller than 2.5M" return give_create_form(username, session) config = request.FILES['json_config'].read() try: kwargs['config'] = json.loads(config) except Exception as e: logging.info("Possible JSON load error: %s" % e) try: kwargs['config'] = json.loads("\"" + config + "\"") except Exception as e: logging.error("Definite JSON load error %s" % e) session['message'] = "Error parsing given JSON text." return give_create_form(username, session) # No upload, check text-box elif "json_config_text" in form.cleaned_data: try: kwargs['config'] = json.loads(form.cleaned_data['json_config_text']) except Exception as e: logging.info("Possible JSON load error: %s" % e) try: kwargs['config'] = json.loads("\"" + str(form.cleaned_data['json_config_text']) + "\"") except Exception as e: logging.error("Definite JSON load error %s" % e) session['message'] = "Error parsing given JSON text." return give_create_form(username, session) try: kwargs['ms_username'] = form.cleaned_data['g_name'] kwargs['port'] = form.cleaned_data['port'] kwargs['host'] = form.cleaned_data['host'] kwargs['ms_password'] = form.cleaned_data['g_password'] kwargs['private'] = form.cleaned_data['private'] new_RG = db.create_replica_gateway(user, **kwargs) except Exception as E: session['message'] = "RG creation error: %s" % E return give_create_form(username, session) session['new_change'] = "Your new gateway is ready." session['next_url'] = '/syn/RG/allgateways/' session['next_message'] = "Click here to see all replica gateways." return redirect('/syn/thanks/') else: # Prep returned form values (so they don't have to re-enter stuff) if 'g_name' in form.errors: oldname = "" else: oldname = request.POST['g_name'] if 'host' in form.errors: oldhost = "" else: oldhost = request.POST['host'] if 'port' in form.errors: oldport = "" else: oldport = request.POST['port'] oldjson = request.POST['json_config_text'] # Prep error message message = "Invalid form entry: " for k, v in form.errors.items(): message = message + "\"" + k + "\"" + " -> " for m in v: message = message + m + " " # Give then the form again form = gatewayforms.CreateRG(initial={'g_name': oldname, 'host': oldhost, 'port': oldport, 'json_config_text':oldjson, }) t = loader.get_template('gateway_templates/create_replica_gateway.html') c = RequestContext(request, {'username':username,'form':form, 'message':message}) return HttpResponse(t.render(c)) else: # Not a POST, give them blank form return give_create_form(username, session)