def userlogin(request): from django.contrib.auth import login if request.method == "GET": return render(request, 'users/login.html', {}) errors = "" username = request.POST.get('username') password = request.POST.get('password') invalid = "Username/Password not valid" if not username or not password: errors = "Username and password are required" if not errors: user = User.find(username) if not user: errors = invalid else: if not user.authenticate(password) and not ldapAuthenticate( username, password): errors = invalid if not errors: request.session['user'] = unicode(user.name) return redirect("/") ctx = {} if errors: ctx = {'errors': errors} return render(request, 'users/login.html', ctx)
def mod_user(self, args): """Modify a user. Ask in the terminal if the value isn't provided""" name = unicode(args['<name>'], "utf-8") user = User.find(name) if not user: self.print_error("User {} doesn't exist".format(name)) return value = unicode(args['<value>'], "utf-8") if not value: if args['password']: while not value: value = getpass("Please enter the new password: "******"Please enter the new value: ") value = unicode(args['<value>'], "utf-8") if args['email']: user.update(email=value) elif args['administrator']: user.update(administrator=value.lower() in ["true", "y", "yes"]) elif args['active']: user.update(active=value.lower() in ["true", "y", "yes"]) elif args['password']: user.update(password=value) print u"User {} has been modified".format(name)
def list_users(self, args): """List all users or a specific user if the name is specified""" if args['<name>']: name = unicode(args['<name>'], "utf-8") user = User.find(name) if user: user_info = user.to_dict() groups = u", ".join([el['name'] for el in user_info.get("groups", [])]) print u"{0.bold}User name{0.normal}: {1}".format( self.terminal, user_info.get("username", name)) print u"{0.bold}Email{0.normal}: {1}".format( self.terminal, user_info.get("email", "")) print u"{0.bold}User id{0.normal}: {1}".format( self.terminal, user_info.get("uuid", "")) print u"{0.bold}Administrator{0.normal}: {1}".format( self.terminal, user_info.get("administrator", False)) print u"{0.bold}Active{0.normal}: {1}".format( self.terminal, user_info.get("active", False)) print u"{0.bold}Groups{0.normal}: {1}".format( self.terminal, groups) else: self.print_error(u"User {} not found".format(name)) else: for user in User.objects.all(): print user.name
def do_ingest(self, args): """Ingest a local collection""" group_name = unicode(args['<group>'], "utf-8") group = Group.find(group_name) if not group: self.print_error(u"Group {} not found".format(group_name)) return user_name = unicode(args['<user>'], "utf-8") user = User.find(user_name) if not user: self.print_error(u"User {} not found".format(user_name)) return path_name = unicode(args['<path>'], "utf-8") path = os.path.abspath(path_name) if not os.path.exists(path): self.print_error(u"Could not find path {}".format(path_name)) return include_pattern = args['--include'] local_ip = args['--localip'] is_reference = args['--reference'] compress = not args['--no-compress'] do_ingest(user, group, path)
def authenticate(self, username=None, password=None): user = User.find(username) if not user: print "User not found" return None if not user.authenticate(password): print "User not authenticated" return None return user
def authenticate_credentials(self, username, password): """ Authenticate the username and password against username and password. """ user = User.find(username) if user is None or not user.is_active(): raise exceptions.AuthenticationFailed(_('User inactive or deleted.')) if not user.authenticate(password) and not ldapAuthenticate(username, password): raise exceptions.AuthenticationFailed(_('Invalid username/password.')) return (user, None)
def user_view(request, name): # argument is the login name, not the uuid in Cassandra user = User.find(name) if not user: return redirect('users:home') #raise Http404 ctx = { "req_user": request.user, "user_obj": user, "groups": [Group.find(gname) for gname in user.groups] } return render(request, 'users/view.html', ctx)
def rm_user(self, args): """Remove a user.""" if not args['<name>']: username = raw_input("Please enter the user's username: "******"utf-8") user = User.find(username) if not user: self.print_error("User {} doesn't exist".format(username)) return user.delete() print u"User {} has been deleted".format(username)
def process_request(self, request): from indigo.models import User username = request.session.get('user') if not username: return None # Cache the user rather than hitting the database for # each request. We can also invalidate the entry if the # user is marked as inactive. user = cache.get('user_{}'.format(username), None) if not user: user = User.find(username) request.user = user cache.set('user_{}'.format(username), user, 60) return None
def rm_user(request, name, uname): group = Group.find(name) user = User.find(uname) if not request.user.administrator: raise PermissionDenied if user and group: removed, not_there, not_exist = group.rm_user(uname) if removed: msg = "'{}' has been removed from the group '{}'".format( uname, name) elif not_there: msg = "'{}' isn't in the group '{}'".format(uname, name) elif not_exist: msg = "'{}' doesn't exist".format(uname) messages.add_message(request, messages.INFO, msg) else: raise Http404 return redirect('groups:view', name=name)
def delete_user(request, name): user = User.find(name) if not user: raise Http404 if not request.user.administrator: raise PermissionDenied if request.method == "POST": user.delete(username=request.user.name) messages.add_message( request, messages.INFO, "The user '{}' has been deleted".format(user.name)) return redirect('users:home') # Requires delete on user ctx = { "user": user, } return render(request, 'users/delete.html', ctx)
def add_users(self, ls_users): """Add a list of users to a group Return 3 lists: - added for the username which were added - already_there for username already in the group - not_added for username not found""" from indigo.models import User added = [] not_added = [] already_there = [] for username in ls_users: user = User.find(username) if user: if self.name not in user.get_groups(): user.add_group(self.name) added.append(username) else: already_there.append(username) else: not_added.append(username) return added, not_added, already_there
def rm_users(self, ls_users): """Remove a list of users from the group Return 3 lists: removed for the username who were removed not_there for the username who weren't in the group not_exist for the usernames who doesn't exist""" from indigo.models import User not_exist = [] removed = [] not_there = [] for username in ls_users: user = User.find(username) if user: if self.name in user.get_groups(): user.rm_group(self.name) removed.append(username) else: not_there.append(username) else: not_exist.append(username) return removed, not_there, not_exist
def mk_user(self, args): """Create a new user. Ask in the terminal for mandatory fields""" if not args['<name>']: username = raw_input("Please enter the user's username: "******"utf-8") if User.find(username): self.print_error(u"Username {} already exists".format(username)) return admin = raw_input("Is this an administrator? [y/N] ") email = "" while not email: email = raw_input("Please enter the user's email address: ") password = "" while not password: password = getpass("Please enter the user's password: "******"User {} has been created".format(username)
def edit_user(request, name): # Requires edit on user user = User.find(name) if not user: raise Http404() if not request.user.administrator: raise PermissionDenied if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): data = form.cleaned_data user.update(email=data['email'], administrator=data['administrator'], active=data['active'], username=request.user.name) if data["password"] != user.password: user.update(password=data["password"], username=request.user.name) return redirect('users:home') else: initial_data = { 'username': user.name, 'email': user.email, 'administrator': user.administrator, "active": user.active, "password": user.password } form = UserForm(initial=initial_data) ctx = { "form": form, "user": user, } return render(request, 'users/edit.html', ctx)
def get_user(self, id): return User.find(username)
def home(request): notifications = Notification.recent(10) activities = [] for notif in notifications: t = template.Template(notif['tmpl']) obj_uuid = notif['object_uuid'] object = None if notif['object_type'] == OBJ_RESOURCE: object = Resource.find(obj_uuid) if object: object_dict = object.to_dict() else: object_dict = {'name': obj_uuid} elif notif['object_type'] == OBJ_COLLECTION: object = Collection.find(obj_uuid) if object: object_dict = object.to_dict() else: object_dict = {'name': obj_uuid} elif notif['object_type'] == OBJ_USER: object = User.find(obj_uuid) if object: object_dict = object.to_dict() else: # User has been deleted it can't be find by uuid # look in payload of the message to get the name if notif['operation'] in [OP_CREATE, OP_UPDATE]: name = notif['payload']['post']['name'] else: # OP_DELETE name = notif['payload']['pre']['name'] object_dict = {'name': name} elif notif['object_type'] == OBJ_GROUP: object = Group.find(obj_uuid) if object: object_dict = object.to_dict() else: # User has been deleted it can't be find by uuid # look in payload of the message to get the name if notif['operation'] in [OP_CREATE, OP_UPDATE]: name = notif['payload']['post']['name'] else: # OP_DELETE name = notif['payload']['pre']['name'] object_dict = {'uuid': obj_uuid, 'name': name} user_dict = {} if notif['username']: user = User.find(notif['username']) if user: user_dict = user.to_dict() variables = { 'user': user_dict, 'when': notif['when'], 'object': object_dict } ctx = template.Context(variables) activities.append({'html': t.render(ctx)}) return render(request, 'activity/index.html', {'activities': activities})
def create(cls, container, name, uuid=None, metadata=None, url=None, mimetype=None, username=None, size=None): """Create a new resource in the tree_entry table""" from indigo.models import Collection from indigo.models import Notification # Check if parent collection exists parent = Collection.find(container) if parent is None: raise NoSuchCollectionError(container) if uuid is None: uuid = default_cdmi_id() create_ts = datetime.now() modified_ts = create_ts path = merge(container, name) if metadata: metadata_cass = meta_cdmi_to_cassandra(metadata) # Check the container exists collection = Collection.find(container) if not collection: raise NoSuchCollectionError(container) # Make sure parent/name are not in use. existing = cls.find(path) if existing: raise ResourceConflictError(path) kwargs = { "container": container, "name": name, "url": url, "uuid": uuid, } if is_reference(url): kwargs["create_ts"] = create_ts kwargs["modified_ts"] = modified_ts kwargs["mimetype"] = mimetype if metadata: kwargs["metadata"] = metadata_cass else: obj_id = url.replace("cassandra://", "") data_obj = DataObject.find(obj_id) if metadata: data_obj.update(mimetype=mimetype, metadata=metadata_cass) else: if mimetype: data_obj.update(mimetype=mimetype) if size: data_obj.update(size=size) data_entry = TreeEntry.create(**kwargs) new = Resource(data_entry) session = get_graph_session() add_user_edge = "" if username: user = User.find(username) if user: add_user_edge = """v_user = {}.next(); v_user.addEdge('owns', v_new); """.format(gq_get_vertex_user(user)) else: add_user_edge = "" session.execute_graph("""v_parent = {}.next(); v_new = {}; v_parent.addEdge('son', v_new); {} """.format(gq_get_vertex_collection(parent), gq_add_vertex_resource(new), add_user_edge)) if metadata: new.update_graph(metadata) state = new.mqtt_get_state() payload = new.mqtt_payload({}, state) Notification.create_resource(username, path, payload) # Index the resource new.index() return new
def create(cls, name, container='/', metadata=None, username=None): """Create a new collection""" from indigo.models import Notification from indigo.models import Resource path = merge(container, name) # Check if parent collection exists parent = Collection.find(container) if parent is None: raise NoSuchCollectionError(container) resource = Resource.find(merge(container, name)) if resource is not None: raise ResourceConflictError(container) collection = Collection.find(path) if collection is not None: raise CollectionConflictError(container) now = datetime.now() # If we try to create a tree entry with no metadata, cassandra-driver # will fail as it tries to delete a static column if metadata: metadata_cass = meta_cdmi_to_cassandra(metadata) coll_entry = TreeEntry.create(container=path, name='.', container_create_ts=now, container_modified_ts=now, container_metadata=metadata_cass) else: coll_entry = TreeEntry.create(container=path, name='.', container_create_ts=now, container_modified_ts=now) coll_entry.update(uuid=coll_entry.container_uuid) child_entry = TreeEntry.create(container=container, name=name + '/', uuid=coll_entry.container_uuid) new = Collection.find(path) add_user_edge = "" if username: user = User.find(username) if user: add_user_edge = """v_user = {}.next(); v_user.addEdge('owns', v_new); """.format(gq_get_vertex_user(user)) else: add_user_edge = "" session = get_graph_session() session.execute_graph("""v_parent = {}.next(); v_new = {}; v_parent.addEdge('son', v_new); {} """.format(gq_get_vertex_collection(parent), gq_add_vertex_collection(new), add_user_edge)) if metadata: new.update_graph(metadata) state = new.mqtt_get_state() payload = new.mqtt_payload({}, state) Notification.create_collection(username, path, payload) # Index the collection new.index() return new