def _set_quota(user, quota): """Set the quota of the user to the given value, and restore the old value when exit""" oldquota = seafilerpc.get_user_quota(user) if seafilerpc.set_user_quota(user, quota) < 0: raise RuntimeError('failed to change user quota') assert seafilerpc.get_user_quota(user) == quota try: yield finally: seafilerpc.set_user_quota(user, oldquota)
def user_search(request): """Search a user. """ email = request.GET.get('email', '') email_patt = email.replace('*', '%') users = ccnet_threaded_rpc.search_emailusers(email_patt, -1, -1) last_logins = UserLastLogin.objects.filter( username__in=[x.email for x in users]) for user in users: try: user.self_usage = seafile_api.get_user_self_usage(user.email) user.share_usage = seafile_api.get_user_share_usage(user.email) user.quota = seafile_api.get_user_quota(user.email) except: user.self_usage = -1 user.share_usage = -1 user.quota = -1 # populate user last login time user.last_login = None for last_login in last_logins: if last_login.username == user.email: user.last_login = last_login.last_login return render_to_response('sysadmin/user_search.html', { 'users': users, 'email': email, }, context_instance=RequestContext(request))
def _populate_user_quota_usage(user): """Populate space/share quota to user. Arguments: - `user`: """ orgs = ccnet_threaded_rpc.get_orgs_by_user(user.email) try: if orgs: user.org = orgs[0] org_id = user.org.org_id user.space_usage = seafserv_threaded_rpc.get_org_user_quota_usage( org_id, user.email) user.space_quota = seafserv_threaded_rpc.get_org_user_quota( org_id, user.email) user.share_usage = user.share_quota = 0 else: user.space_usage = seafile_api.get_user_self_usage(user.email) user.space_quota = seafile_api.get_user_quota(user.email) if CALC_SHARE_USAGE: user.share_quota = seafile_api.get_user_share_quota(user.email) user.share_usage = seafile_api.get_user_share_usage(user.email) else: user.share_usage = user.share_quota = 0 except SearpcError as e: logger.error(e) user.space_usage = user.space_quota = user.share_usage = user.share_quota = -1
def get_user_info(email): user = User.objects.get(email=email) d_profile = DetailedProfile.objects.get_detailed_profile_by_user(email) profile = Profile.objects.get_profile_by_user(email) info = {} info['email'] = email info['name'] = email2nickname(email) info['contact_email'] = email2contact_email(email) info['login_id'] = profile.login_id if profile and profile.login_id else '' info['is_staff'] = user.is_staff info['is_active'] = user.is_active info['create_time'] = user.ctime info['reference_id'] = user.reference_id if user.reference_id else '' info['department'] = d_profile.department if d_profile else '' info['quota_total'] = seafile_api.get_user_quota(email) info['quota_usage'] = seafile_api.get_user_self_usage(email) info['create_time'] = timestamp_to_isoformat_timestr(user.ctime) if is_pro_version(): info['role'] = user.role return info
def check_user_share_quota(username, repo, users=[], groups=[]): """Check whether user has enough quota when share repo to users/groups. """ if not users and not groups: return True if not seaserv.CALC_SHARE_USAGE: return True check_pass = False quota = seafile_api.get_user_quota(username) self_usage = seafile_api.get_user_self_usage(username) current_share_usage = seafile_api.get_user_share_usage(username) share_usage = 0 if users: share_usage += seafile_api.get_repo_size(repo.id) * (len(users)) if groups: grp_members = [] for group in groups: grp_members += [ e.user_name for e in seaserv.get_group_members(group.id)] grp_members = set(grp_members) share_usage += seafile_api.get_repo_size(repo.id) * (len(grp_members) -1) if share_usage + self_usage + current_share_usage < quota: check_pass = True return check_pass
def _populate_user_quota_usage(user): """Populate space/share quota to user. Arguments: - `user`: """ orgs = ccnet_threaded_rpc.get_orgs_by_user(user.email) try: if orgs: user.org = orgs[0] org_id = user.org.org_id user.space_usage = seafserv_threaded_rpc.get_org_user_quota_usage(org_id, user.email) user.space_quota = seafserv_threaded_rpc.get_org_user_quota(org_id, user.email) user.share_usage = user.share_quota = 0 else: user.space_usage = seafile_api.get_user_self_usage(user.email) user.space_quota = seafile_api.get_user_quota(user.email) if CALC_SHARE_USAGE: user.share_quota = seafile_api.get_user_share_quota(user.email) user.share_usage = seafile_api.get_user_share_usage(user.email) else: user.share_usage = user.share_quota = 0 except SearpcError as e: logger.error(e) user.space_usage = user.space_quota = user.share_usage = user.share_quota = -1
def get_user_info(email): user = User.objects.get(email=email) d_profile = DetailedProfile.objects.get_detailed_profile_by_user(email) profile = Profile.objects.get_profile_by_user(email) info = {} info['email'] = email info['name'] = email2nickname(email) info['contact_email'] = profile.contact_email if profile and profile.contact_email else '' info['login_id'] = profile.login_id if profile and profile.login_id else '' info['is_staff'] = user.is_staff info['is_active'] = user.is_active info['create_time'] = user.ctime info['reference_id'] = user.reference_id if user.reference_id else '' info['department'] = d_profile.department if d_profile else '' info['quota_total'] = seafile_api.get_user_quota(email) info['quota_usage'] = seafile_api.get_user_self_usage(email) info['create_time'] = timestamp_to_isoformat_timestr(user.ctime) if is_pro_version(): info['role'] = user.role return info
def check_repo_owner_quota(self, isnewfile=True, contentlength=-1): """Check if the upload would cause the user quota be exceeded `contentlength` is only positive when the client does not use "transfer-encode: chunking" Return True if the quota would not be exceeded, otherwise return False. """ if contentlength <= 0: # When client use "transfer-encode: chunking", the content length # is not included in the request headers if isnewfile: return check_repo_quota(self.repo.id) >= 0 else: return True if not self.owner: self.owner = seafile_api.get_repo_owner(self.repo.id) quota = seafile_api.get_user_quota(self.owner) if quota == INFINITE_QUOTA: return True self_usage = seafile_api.get_user_self_usage(self.owner) share_usage = seafile_api.get_user_share_usage(self.owner) if CALC_SHARE_USAGE else 0 remain = quota - self_usage - share_usage if not isnewfile: remain -= self.obj.size return contentlength <= remain
def check_user_share_quota(username, repo, users=[], groups=[]): """Check whether user has enough quota when share repo to users/groups. """ if not users and not groups: return True if not seaserv.CALC_SHARE_USAGE: return True check_pass = False quota = seafile_api.get_user_quota(username) self_usage = seafile_api.get_user_self_usage(username) current_share_usage = seafile_api.get_user_share_usage(username) share_usage = 0 if users: share_usage += seafile_api.get_repo_size(repo.id) * (len(users)) if groups: grp_members = [] for group in groups: grp_members += [ e.user_name for e in seaserv.get_group_members(group.id) ] grp_members = set(grp_members) share_usage += seafile_api.get_repo_size( repo.id) * (len(grp_members) - 1) if share_usage + self_usage + current_share_usage < quota: check_pass = True return check_pass
def user_search(request): """Search a user. """ email = request.GET.get('email', '') email_patt = email.replace('*', '%') users = ccnet_threaded_rpc.search_emailusers(email_patt, -1, -1) last_logins = UserLastLogin.objects.filter(username__in=[x.email for x in users]) for user in users: try: user.self_usage = seafile_api.get_user_self_usage(user.email) user.share_usage = seafile_api.get_user_share_usage(user.email) user.quota = seafile_api.get_user_quota(user.email) except: user.self_usage = -1 user.share_usage = -1 user.quota = -1 # populate user last login time user.last_login = None for last_login in last_logins: if last_login.username == user.email: user.last_login = last_login.last_login return render_to_response('sysadmin/user_search.html', { 'users': users, 'email': email, }, context_instance=RequestContext(request))
def send_email(self, email): # save current language cur_language = translation.get_language() # get and active user language user_language = self.get_user_language(email) translation.activate(user_language) orgs = ccnet_api.get_orgs_by_user(email) if orgs: org_id = orgs[0].org_id quota_usage = seafile_api.get_org_user_quota_usage(org_id, email) quota_total = seafile_api.get_org_user_quota(org_id, email) else: quota_usage = seafile_api.get_user_self_usage(email) quota_total = seafile_api.get_user_quota(email) if IS_EMAIL_CONFIGURED and quota_total > 0 and quota_usage/quota_total > 0.9: data = {'email': email, 'quota_total': quota_total, 'quota_usage': quota_usage} contact_email = Profile.objects.get_contact_email_by_user(email) print('Send email to %s(%s)' % (contact_email, email)) send_html_email(_(u'Your quota is almost full on %s') % get_site_name(), 'user_quota_full.html', data, None, [contact_email]) # restore current language translation.activate(cur_language)
def get(self, request): """List all admins from database and ldap imported """ if not request.user.admin_permissions.can_manage_user(): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') try: admin_users = ccnet_api.get_superusers() except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) admin_users_info = [] for user in admin_users: user_info = {} profile = Profile.objects.get_profile_by_user(user.email) user_info['email'] = user.email user_info['name'] = email2nickname(user.email) user_info['contact_email'] = email2contact_email(user.email) user_info['login_id'] = profile.login_id if profile and profile.login_id else '' user_info['is_staff'] = user.is_staff user_info['is_active'] = user.is_active orgs = ccnet_api.get_orgs_by_user(user.email) try: if orgs: org_id = orgs[0].org_id user_info['org_id'] = org_id user_info['org_name'] = orgs[0].org_name user_info['quota_usage'] = seafile_api.get_org_user_quota_usage(org_id, user.email) user_info['quota_total'] = seafile_api.get_org_user_quota(org_id, user.email) else: user_info['quota_usage'] = seafile_api.get_user_self_usage(user.email) user_info['quota_total'] = seafile_api.get_user_quota(user.email) except Exception as e: logger.error(e) user_info['quota_usage'] = -1 user_info['quota_total'] = -1 user_info['create_time'] = timestamp_to_isoformat_timestr(user.ctime) last_login_obj = UserLastLogin.objects.get_by_username(user.email) user_info['last_login'] = datetime_to_isoformat_timestr(last_login_obj.last_login) if last_login_obj else '' try: admin_role = AdminRole.objects.get_admin_role(user.email) user_info['admin_role'] = admin_role.role except AdminRole.DoesNotExist: user_info['admin_role'] = DEFAULT_ADMIN admin_users_info.append(user_info) result = { 'admin_user_list': admin_users_info, } return Response(result)
def get_info_of_users_order_by_quota_usage(self, source, direction, page, per_page): # get user's quota usage info user_usage_dict = {} users_with_usage = seafile_api.list_user_quota_usage() for user in users_with_usage: email = user.user if email not in user_usage_dict: user_usage_dict[email] = user.usage # get all users and map quota usage to user if source == 'db': users = ccnet_api.get_emailusers('DB', -1, -1) else: users = ccnet_api.get_emailusers('LDAPImport', -1, -1) for user in users: email = user.email user.quota_usage = user_usage_dict.get(email, -1) # sort users.sort(key=lambda item: item.quota_usage, reverse=direction == 'desc') data = [] MULTI_INSTITUTION = getattr(settings, 'MULTI_INSTITUTION', False) for user in users[(page - 1) * per_page:page * per_page]: info = {} info['email'] = user.email info['name'] = email2nickname(user.email) info['contact_email'] = email2contact_email(user.email) profile = Profile.objects.get_profile_by_user(user.email) info[ 'login_id'] = profile.login_id if profile and profile.login_id else '' info['is_staff'] = user.is_staff info['is_active'] = user.is_active info['create_time'] = timestamp_to_isoformat_timestr(user.ctime) info['quota_usage'] = user.quota_usage info['quota_total'] = seafile_api.get_user_quota(user.email) last_login_obj = UserLastLogin.objects.get_by_username(user.email) info['last_login'] = datetime_to_isoformat_timestr( last_login_obj.last_login) if last_login_obj else '' info['role'] = get_user_role(user) if MULTI_INSTITUTION: info['institution'] = profile.institution if profile else '' data.append(info) return data
def post(self, request): """ Add admin in batch """ emails = request.data.get('emails', None) if not emails: error_msg = 'emails invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) emails = string2list(emails) new_admin_info = [] for email in emails: if not is_valid_username(email): error_msg = 'email %s invalid.' % email return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: user = User.objects.get(email=email) except User.DoesNotExist: error_msg = 'email %s invalid.' % email return api_error(status.HTTP_400_BAD_REQUEST, error_msg) user.is_staff = True user.save() profile = Profile.objects.get_profile_by_user(user.email) user_info = {} user_info['email'] = user.email user_info['name'] = email2nickname(user.email) user_info[ 'contact_email'] = profile.contact_email if profile and profile.contact_email else '' user_info[ 'login_id'] = profile.login_id if profile and profile.login_id else '' user_info['is_staff'] = user.is_staff user_info['is_active'] = user.is_active user_info['quota_total'] = seafile_api.get_user_quota(user.email) user_info['quota_usage'] = seafile_api.get_user_self_usage( user.email) user_info['create_time'] = timestamp_to_isoformat_timestr( user.ctime) user_info['last_login'] = UserLastLogin.objects.get_by_username( user.email ).last_login if UserLastLogin.objects.get_by_username( user.email) else '' try: admin_role = AdminRole.objects.get_admin_role(user.email) user_info['admin_role'] = admin_role.role except AdminRole.DoesNotExist: user_info['admin_role'] = DEFAULT_ADMIN new_admin_info.append(user_info) return Response({'new_admin_user_list': new_admin_info})
def sys_user_admin(request): """List all users from database. """ # Make sure page request is an int. If not, deliver first page. try: current_page = int(request.GET.get('page', '1')) per_page = int(request.GET.get('per_page', '25')) except ValueError: current_page = 1 per_page = 25 users_plus_one = get_emailusers('DB', per_page * (current_page - 1), per_page + 1) if len(users_plus_one) == per_page + 1: page_next = True else: page_next = False users = users_plus_one[:per_page] last_logins = UserLastLogin.objects.filter( username__in=[x.email for x in users]) for user in users: if user.props.id == request.user.id: user.is_self = True try: user.self_usage = seafile_api.get_user_self_usage(user.email) user.share_usage = seafile_api.get_user_share_usage(user.email) user.quota = seafile_api.get_user_quota(user.email) except: user.self_usage = -1 user.share_usage = -1 user.quota = -1 # populate user last login time user.last_login = None for last_login in last_logins: if last_login.username == user.email: user.last_login = last_login.last_login have_ldap = True if len(get_emailusers('LDAP', 0, 1)) > 0 else False platform = get_platform_name() server_id = get_server_id() return render_to_response('sysadmin/sys_useradmin.html', { 'users': users, 'current_page': current_page, 'prev_page': current_page - 1, 'next_page': current_page + 1, 'per_page': per_page, 'page_next': page_next, 'CALC_SHARE_USAGE': CALC_SHARE_USAGE, 'have_ldap': have_ldap, 'platform': platform, 'server_id': server_id[:8], }, context_instance=RequestContext(request))
def get_quota_usage(username): # https://github.com/haiwen/seahub/blob/master/seahub/api2/views.py#L310 used = seafile_api.get_user_self_usage(username) + seafile_api.get_user_share_usage(username) total = seafile_api.get_user_quota(username) if used > 0: used = float(used) if total == -2: total = float(2) elif total > 0: total = float(total) return used, total
def get_institution_available_quota(inst): inst_quota = InstitutionQuota.objects.get_or_none(institution=inst) if inst_quota is None: return None usernames = [x.user for x in Profile.objects.filter(institution=inst.name)] allocated = 0 for user in usernames: allocated += seafile_api.get_user_quota(user) return 0 if allocated >= inst_quota else inst_quota - allocated
def sys_user_admin(request): """List all users from database. """ # Make sure page request is an int. If not, deliver first page. try: current_page = int(request.GET.get('page', '1')) per_page = int(request.GET.get('per_page', '25')) except ValueError: current_page = 1 per_page = 25 users_plus_one = get_emailusers('DB', per_page * (current_page - 1), per_page + 1) if len(users_plus_one) == per_page + 1: page_next = True else: page_next = False users = users_plus_one[:per_page] last_logins = UserLastLogin.objects.filter(username__in=[x.email for x in users]) for user in users: if user.props.id == request.user.id: user.is_self = True try: user.self_usage = seafile_api.get_user_self_usage(user.email) user.share_usage = seafile_api.get_user_share_usage(user.email) user.quota = seafile_api.get_user_quota(user.email) except: user.self_usage = -1 user.share_usage = -1 user.quota = -1 # populate user last login time user.last_login = None for last_login in last_logins: if last_login.username == user.email: user.last_login = last_login.last_login have_ldap = True if len(get_emailusers('LDAP', 0, 1)) > 0 else False platform = get_platform_name() server_id = get_server_id() return render_to_response( 'sysadmin/sys_useradmin.html', { 'users': users, 'current_page': current_page, 'prev_page': current_page-1, 'next_page': current_page+1, 'per_page': per_page, 'page_next': page_next, 'CALC_SHARE_USAGE': CALC_SHARE_USAGE, 'have_ldap': have_ldap, 'platform': platform, 'server_id': server_id[:8], }, context_instance=RequestContext(request))
def _populate_user_quota_usage(user): """Populate space/share quota to user. Arguments: - `user`: """ try: user.space_usage = seafile_api.get_user_self_usage(user.email) user.space_quota = seafile_api.get_user_quota(user.email) except SearpcError as e: logger.error(e) user.space_usage = -1 user.space_quota = -1
def test_update_quota_total(self): self.login_as(self.admin) # change user name quota_total = 1232 data = {"email": self.tmp_email, "quota_total": quota_total} resp = self.client.put(self.url, json.dumps(data), 'application/json') json_resp = json.loads(resp.content) self.assertEqual(200, resp.status_code) quota_total_mb = quota_total * get_file_size_unit('mb') assert json_resp['quota_total'] == quota_total_mb assert seafile_api.get_user_quota(self.tmp_email) == quota_total_mb
def user_search(request): """Search a user. """ email = request.GET.get('email', '') users = ccnet_threaded_rpc.search_emailusers(email, -1, -1) last_logins = UserLastLogin.objects.filter( username__in=[x.email for x in users]) for user in users: org = ccnet_threaded_rpc.get_orgs_by_user(user.email) try: if not org: user.self_usage = seafile_api.get_user_self_usage(user.email) user.share_usage = seafile_api.get_user_share_usage(user.email) user.quota = seafile_api.get_user_quota(user.email) else: user.org = org[0] org_id = user.org.org_id user.self_usage = seafserv_threaded_rpc.get_org_user_quota_usage( org_id, user.email) user.share_usage = 0 user.quota = seafserv_threaded_rpc.get_org_user_quota( org_id, user.email) except SearpcError as e: logger.error(e) user.self_usage = -1 user.share_usage = -1 user.quota = -1 # check user's role if user.role == GUEST_USER: user.is_guest = True else: user.is_guest = False # populate user last login time user.last_login = None for last_login in last_logins: if last_login.username == user.email: user.last_login = last_login.last_login return render_to_response('sysadmin/user_search.html', { 'users': users, 'email': email, 'default_user': DEFAULT_USER, 'guest_user': GUEST_USER, 'enable_guest': ENABLE_GUEST, }, context_instance=RequestContext(request))
def sys_user_admin_admins(request): """List all admins from database. """ users = get_emailusers('DB', -1, -1) admin_users = [] not_admin_users = [] for user in users: if user.is_staff is True: admin_users.append(user) else: not_admin_users.append(user) last_logins = UserLastLogin.objects.filter( username__in=[x.email for x in admin_users]) for user in admin_users: if user.props.id == request.user.id: user.is_self = True try: user.self_usage = seafile_api.get_user_self_usage(user.email) user.share_usage = seafile_api.get_user_share_usage(user.email) user.quota = seafile_api.get_user_quota(user.email) except: user.self_usage = -1 user.share_usage = -1 user.quota = -1 # check user's role if user.role == GUEST_USER: user.is_guest = True else: user.is_guest = False # populate user last login time user.last_login = None for last_login in last_logins: if last_login.username == user.email: user.last_login = last_login.last_login have_ldap = True if len(get_emailusers('LDAP', 0, 1)) > 0 else False return render_to_response('sysadmin/sys_useradmin_admins.html', { 'admin_users': admin_users, 'not_admin_users': not_admin_users, 'CALC_SHARE_USAGE': CALC_SHARE_USAGE, 'have_ldap': have_ldap, 'default_user': DEFAULT_USER, 'guest_user': GUEST_USER, }, context_instance=RequestContext(request))
def test_update(self): self.login_as(self.admin) resp = self._do_update() self.assertEqual(200, resp.status_code) self.assertTrue( User.objects.get(self.user1.username).check_password('654321')) self.assertTrue(User.objects.get(self.user1.username).is_staff) self.assertFalse(User.objects.get(self.user1.username).is_active) self.assertEqual( Profile.objects.get_profile_by_user(self.user1.username).nickname, 'user1') self.assertEqual(seafile_api.get_user_quota(self.user1.username), 102400000000)
def sys_user_admin_admins(request): """List all admins from database. """ users = get_emailusers('DB', -1, -1) admin_users = [] not_admin_users = [] for user in users: if user.is_staff is True: admin_users.append(user) else: not_admin_users.append(user) last_logins = UserLastLogin.objects.filter(username__in=[x.email for x in admin_users]) for user in admin_users: if user.props.id == request.user.id: user.is_self = True try: user.self_usage = seafile_api.get_user_self_usage(user.email) user.share_usage = seafile_api.get_user_share_usage(user.email) user.quota = seafile_api.get_user_quota(user.email) except: user.self_usage = -1 user.share_usage = -1 user.quota = -1 # check user's role if user.role == GUEST_USER: user.is_guest = True else: user.is_guest = False # populate user last login time user.last_login = None for last_login in last_logins: if last_login.username == user.email: user.last_login = last_login.last_login have_ldap = True if len(get_emailusers('LDAP', 0, 1)) > 0 else False return render_to_response( 'sysadmin/sys_useradmin_admins.html', { 'admin_users': admin_users, 'not_admin_users': not_admin_users, 'CALC_SHARE_USAGE': CALC_SHARE_USAGE, 'have_ldap': have_ldap, 'default_user': DEFAULT_USER, 'guest_user': GUEST_USER, }, context_instance=RequestContext(request))
def user_info(request, email): owned_repos = seafile_api.get_owned_repo_list(email) quota = seafile_api.get_user_quota(email) quota_usage = 0 share_usage = 0 my_usage = 0 my_usage = seafile_api.get_user_self_usage(email) if CALC_SHARE_USAGE: try: share_usage = seafile_api.get_user_share_usage(email) except SearpcError, e: logger.error(e) share_usage = 0 quota_usage = my_usage + share_usage
def get_quota_usage(username): # https://github.com/haiwen/seahub/blob/master/seahub/api2/views.py#L310 used = seafile_api.get_user_self_usage(username) + seafile_api.get_user_share_usage(username) total = seafile_api.get_user_quota(username) if used > 0: used = float(used) else: used = 0 if total > 0: total = float(total) else: total = float(2) return used, total # print get_quota_usage('*****@*****.**') # print get_quota_usage('*****@*****.**')
def test_update(self): self.login_as(self.admin) resp = self._do_update() self.assertEqual(200, resp.status_code) self.assertTrue(User.objects.get(self.user1.username).check_password( '654321')) self.assertTrue(User.objects.get(self.user1.username).is_staff) self.assertFalse(User.objects.get(self.user1.username).is_active) self.assertEqual(Profile.objects.get_profile_by_user( self.user1.username).nickname, 'user1') self.assertEqual(Profile.objects.get_profile_by_user( self.user1.username).intro, 'this_is_user1') self.assertEqual(seafile_api.get_user_quota( self.user1.username), 102400)
def get_account_info(user): email = user.username d_profile = DetailedProfile.objects.get_detailed_profile_by_user(email) info = {} info['email'] = email info['name'] = email2nickname(email) info['department'] = d_profile.department if d_profile else '' info['id'] = user.id info['is_staff'] = user.is_staff info['is_active'] = user.is_active info['create_time'] = user.ctime info['total'] = seafile_api.get_user_quota(email) info['usage'] = seafile_api.get_user_self_usage(email) return info
def get_user_info(email): user = User.objects.get(email=email) profile = Profile.objects.get_profile_by_user(email) info = {} info['email'] = email info['name'] = email2nickname(email) info[ 'contact_email'] = profile.contact_email if profile and profile.contact_email else '' info['login_id'] = profile.login_id if profile and profile.login_id else '' info['is_staff'] = user.is_staff info['is_active'] = user.is_active info['reference_id'] = user.reference_id if user.reference_id else '' orgs = ccnet_api.get_orgs_by_user(email) try: if orgs: org_id = orgs[0].org_id info['org_id'] = org_id info['org_name'] = orgs[0].org_name info['quota_usage'] = seafile_api.get_org_user_quota_usage( org_id, user.email) info['quota_total'] = seafile_api.get_org_user_quota( org_id, user.email) else: info['quota_usage'] = seafile_api.get_user_self_usage(user.email) info['quota_total'] = seafile_api.get_user_quota(user.email) except Exception as e: logger.error(e) info['quota_usage'] = -1 info['quota_total'] = -1 info['create_time'] = timestamp_to_isoformat_timestr(user.ctime) info['has_default_device'] = True if default_device(user) else False info['is_force_2fa'] = UserOptions.objects.is_force_2fa(email) if getattr(settings, 'MULTI_INSTITUTION', False): info['institution'] = profile.institution if profile else '' info['role'] = get_user_role(user) return info
def get(self, request): """List all admins from database and ldap imported """ try: db_users = ccnet_api.get_emailusers('DB', -1, -1) ldap_imported_users = ccnet_api.get_emailusers('LDAPImport', -1, -1) except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) admin_users = [] for user in db_users + ldap_imported_users: if user.is_staff is True: admin_users.append(user) admin_users_info = [] for user in admin_users: user_info = {} profile = Profile.objects.get_profile_by_user(user.email) user_info['email'] = user.email user_info['name'] = email2nickname(user.email) user_info['contact_email'] = profile.contact_email if profile and profile.contact_email else '' user_info['login_id'] = profile.login_id if profile and profile.login_id else '' user_info['is_staff'] = user.is_staff user_info['is_active'] = user.is_active user_info['quota_total'] = seafile_api.get_user_quota(user.email) user_info['quota_usage'] = seafile_api.get_user_self_usage(user.email) user_info['create_time'] = timestamp_to_isoformat_timestr(user.ctime) user_info['last_login'] = UserLastLogin.objects.get_by_username(user.email).last_login if UserLastLogin.objects.get_by_username(user.email) else '' try: admin_role = AdminRole.objects.get_admin_role(user.email) user_info['admin_role'] = admin_role.role except AdminRole.DoesNotExist: user_info['admin_role'] = DEFAULT_ADMIN admin_users_info.append(user_info) result = { 'admin_user_list': admin_users_info, } return Response(result)
def user_search(request): """Search a user. """ email = request.GET.get('email', '') users = ccnet_threaded_rpc.search_emailusers(email, -1, -1) last_logins = UserLastLogin.objects.filter(username__in=[x.email for x in users]) for user in users: org = ccnet_threaded_rpc.get_orgs_by_user(user.email) try: if not org: user.self_usage = seafile_api.get_user_self_usage(user.email) user.share_usage = seafile_api.get_user_share_usage(user.email) user.quota = seafile_api.get_user_quota(user.email) else: user.org = org[0] org_id = user.org.org_id user.self_usage = seafserv_threaded_rpc.get_org_user_quota_usage(org_id, user.email) user.share_usage = 0 user.quota = seafserv_threaded_rpc.get_org_user_quota(org_id, user.email) except SearpcError as e: logger.error(e) user.self_usage = -1 user.share_usage = -1 user.quota = -1 # check user's role if user.role == GUEST_USER: user.is_guest = True else: user.is_guest = False # populate user last login time user.last_login = None for last_login in last_logins: if last_login.username == user.email: user.last_login = last_login.last_login return render_to_response('sysadmin/user_search.html', { 'users': users, 'email': email, 'default_user': DEFAULT_USER, 'guest_user': GUEST_USER, 'enable_guest': ENABLE_GUEST, }, context_instance=RequestContext(request))
def get_account_info(user): email = user.username profile = Profile.objects.get_profile_by_user(email) info = {} info['email'] = email info['name'] = email2nickname(email) info['institution'] = profile.institution if profile else '' info['id'] = user.id info['is_staff'] = user.is_staff info['is_active'] = user.is_active info['create_time'] = user.ctime info['login_id'] = profile.login_id if profile else '' info['list_in_address_book'] = profile.list_in_address_book if profile else False info['total'] = seafile_api.get_user_quota(email) info['usage'] = seafile_api.get_user_self_usage(email) return info
def get_quota_usage(username): # https://github.com/haiwen/seahub/blob/master/seahub/api2/views.py#L310 used = seafile_api.get_user_self_usage( username) + seafile_api.get_user_share_usage(username) total = seafile_api.get_user_quota(username) if used > 0: used = float(used) else: used = 0 if total > 0: total = float(total) else: total = float(2) return used, total # print get_quota_usage('*****@*****.**') # print get_quota_usage('*****@*****.**')
def get_user_quota_usage_and_total(email, org_id=''): try: if org_id: quota_usage = seafile_api.get_org_user_quota_usage(org_id, email) quota_total = seafile_api.get_org_user_quota(org_id, email) else: orgs = ccnet_api.get_orgs_by_user(email) if orgs: org_id = orgs[0].org_id quota_usage = seafile_api.get_org_user_quota_usage( org_id, email) quota_total = seafile_api.get_org_user_quota(org_id, email) else: quota_usage = seafile_api.get_user_self_usage(email) quota_total = seafile_api.get_user_quota(email) except Exception as e: logger.error(e) quota_usage = -1 quota_total = -1 return quota_usage, quota_total
def get_account_info(user): email = user.username d_profile = DetailedProfile.objects.get_detailed_profile_by_user(email) profile = Profile.objects.get_profile_by_user(email) info = {} info['email'] = email info['name'] = email2nickname(email) info['department'] = d_profile.department if d_profile else '' info['institution'] = profile.institution if profile else '' info['id'] = user.id info['is_staff'] = user.is_staff info['is_active'] = user.is_active info['create_time'] = user.ctime info['login_id'] = profile.login_id if profile else '' info['list_in_address_book'] = profile.list_in_address_book if profile else False info['total'] = seafile_api.get_user_quota(email) info['usage'] = seafile_api.get_user_self_usage(email) return info
def _populate_user_quota_usage(user): """Populate space/share quota to user. Arguments: - `user`: """ orgs = ccnet_api.get_orgs_by_user(user.email) try: if orgs: user.org = orgs[0] org_id = user.org.org_id user.space_usage = seafile_api.get_org_user_quota_usage(org_id, user.email) user.space_quota = seafile_api.get_org_user_quota(org_id, user.email) else: user.space_usage = seafile_api.get_user_self_usage(user.email) user.space_quota = seafile_api.get_user_quota(user.email) except SearpcError as e: logger.error(e) user.space_usage = -1 user.space_quota = -1
def get(self, request, email, format=None): if not is_valid_username(email): return api_error(status.HTTP_400_BAD_REQUEST, 'Email %s invalid.' % email) # query account info try: user = User.objects.get(email=email) except User.DoesNotExist: return api_error(status.HTTP_404_NOT_FOUND, 'User %s not found.' % email) info = {} info['email'] = user.email info['id'] = user.id info['is_staff'] = user.is_staff info['is_active'] = user.is_active info['create_time'] = user.ctime info['total'] = seafile_api.get_user_quota(email) info['usage'] = seafile_api.get_user_self_usage(email) return Response(info)
def get(self, request, email, format=None): if not is_valid_username(email): return api_error(status.HTTP_404_NOT_FOUND, 'User not found.') # query account info try: user = User.objects.get(email=email) except User.DoesNotExist: return api_error(status.HTTP_404_NOT_FOUND, 'User not found.') info = {} info['email'] = user.email info['id'] = user.id info['is_staff'] = user.is_staff info['is_active'] = user.is_active info['create_time'] = user.ctime info['total'] = seafile_api.get_user_quota(email) info['usage'] = seafile_api.get_user_self_usage(email) return Response(info)
def get(self, request, email, format=None): if not is_valid_username(email): return api_error(status.HTTP_404_NOT_FOUND, "User not found.") # query account info try: user = User.objects.get(email=email) except User.DoesNotExist: return api_error(status.HTTP_404_NOT_FOUND, "User not found.") info = {} info["email"] = user.email info["id"] = user.id info["is_staff"] = user.is_staff info["is_active"] = user.is_active info["create_time"] = user.ctime info["total"] = seafile_api.get_user_quota(email) info["usage"] = seafile_api.get_user_self_usage(email) return Response(info)
def get(self, request): try: page = int(request.GET.get('page', '1')) per_page = int(request.GET.get('per_page', '25')) except ValueError: page = 1 per_page = 25 start = (page - 1) * per_page end = start + per_page users = ccnet_api.get_emailusers('DB', start, end) total_count = ccnet_api.count_emailusers('DB') + \ ccnet_api.count_inactive_emailusers('DB') data = [] for user in users: profile = Profile.objects.get_profile_by_user(user.email) info = {} info['email'] = user.email info['name'] = email2nickname(user.email) info['contact_email'] = profile.contact_email if profile and profile.contact_email else '' info['login_id'] = profile.login_id if profile and profile.login_id else '' info['is_staff'] = user.is_staff info['is_active'] = user.is_active info['quota_total'] = seafile_api.get_user_quota(user.email) info['quota_usage'] = seafile_api.get_user_self_usage(user.email) info['create_time'] = timestamp_to_isoformat_timestr(user.ctime) info['last_login'] = UserLastLogin.objects.get_by_username(user.email).last_login if UserLastLogin.objects.get_by_username(user.email) else '' if is_pro_version(): info['role'] = user.role data.append(info) result = {'data': data, 'total_count': total_count} return Response(result)
def get(self, request): """List all users from LDAP server Permission checking: 1. only admin can perform this action. """ if not request.user.admin_permissions.can_manage_user(): return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.') try: page = int(request.GET.get('page', '1')) per_page = int(request.GET.get('per_page', '25')) except ValueError: page = 1 per_page = 25 start = (page - 1) * per_page end = page * per_page + 1 users = ccnet_api.get_emailusers('LDAP', start, end) if len(users) == end - start: users = users[:per_page] has_next_page = True else: has_next_page = False data = [] for user in users: info = {} info['email'] = user.email info['quota_total'] = seafile_api.get_user_quota(user.email) info['quota_usage'] = seafile_api.get_user_self_usage(user.email) info['create_time'] = timestamp_to_isoformat_timestr(user.ctime) last_login_obj = UserLastLogin.objects.get_by_username(user.email) info['last_login'] = datetime_to_isoformat_timestr( last_login_obj.last_login) if last_login_obj else '' data.append(info) result = {'ldap_user_list': data, 'has_next_page': has_next_page} return Response(result)
def user_info(request, email): owned_repos = seafile_api.get_owned_repo_list(email) org = ccnet_threaded_rpc.get_orgs_by_user(email) if not org: my_usage = seafile_api.get_user_self_usage(email) quota = seafile_api.get_user_quota(email) else: org_id = org[0].org_id my_usage =seafserv_threaded_rpc. \ get_org_user_quota_usage(org_id, email) quota = seafserv_threaded_rpc. \ get_org_user_quota(org_id, email) if CALC_SHARE_USAGE: try: share_usage = seafile_api.get_user_share_usage(email) except SearpcError, e: logger.error(e) share_usage = 0 quota_usage = my_usage + share_usage
def user_info(request, email): if request.method == 'POST': result = {} content_type = 'application/json; charset=utf-8' f = SetUserQuotaForm(request.POST) if f.is_valid(): email = f.cleaned_data['email'] quota_mb = f.cleaned_data['quota'] quota = quota_mb * (1 << 20) try: seafile_api.set_user_quota(email, quota) except: result['error'] = _(u'Failed to set quota: internal error') return HttpResponse(json.dumps(result), content_type=content_type) result['success'] = True return HttpResponse(json.dumps(result), content_type=content_type) else: result['error'] = str(f.errors.values()[0]) return HttpResponse(json.dumps(result), content_type=content_type) owned_repos = [] owned_repos = seafile_api.get_owned_repo_list(email) quota = seafile_api.get_user_quota(email) quota_usage = 0 share_usage = 0 my_usage = 0 my_usage = seafile_api.get_user_self_usage(email) if CALC_SHARE_USAGE: try: share_usage = seafile_api.get_user_share_usage(email) except SearpcError, e: logger.error(e) share_usage = 0 quota_usage = my_usage + share_usage
def sys_user_admin(request): # Make sure page request is an int. If not, deliver first page. try: current_page = int(request.GET.get('page', '1')) per_page= int(request.GET.get('per_page', '25')) except ValueError: current_page = 1 per_page = 25 users_plus_one = get_emailusers(per_page * (current_page - 1), per_page + 1) if len(users_plus_one) == per_page + 1: page_next = True else: page_next = False users = users_plus_one[:per_page] for user in users: if user.props.id == request.user.id: user.is_self = True try: user.self_usage = seafile_api.get_user_self_usage(user.email) user.share_usage = seafile_api.get_user_share_usage(user.email) user.quota = seafile_api.get_user_quota(user.email) except: user.self_usage = -1 user.share_usage = -1 user.quota = -1 return render_to_response( 'sysadmin/sys_useradmin.html', { 'users': users, 'current_page': current_page, 'prev_page': current_page-1, 'next_page': current_page+1, 'per_page': per_page, 'page_next': page_next, 'CALC_SHARE_USAGE': CALC_SHARE_USAGE, }, context_instance=RequestContext(request))
def user_search(request): """Search a user. """ email = request.GET.get('email', '') email_patt = email.replace('*', '%') users = ccnet_threaded_rpc.search_emailusers(email_patt, -1, -1) last_logins = UserLastLogin.objects.filter(username__in=[x.email for x in users]) for user in users: try: user.self_usage = seafile_api.get_user_self_usage(user.email) user.share_usage = seafile_api.get_user_share_usage(user.email) user.quota = seafile_api.get_user_quota(user.email) except: user.self_usage = -1 user.share_usage = -1 user.quota = -1 # check user's role if user.role == GUEST_USER: user.is_guest = True else: user.is_guest = False # populate user last login time user.last_login = None for last_login in last_logins: if last_login.username == user.email: user.last_login = last_login.last_login return render_to_response('sysadmin/user_search.html', { 'users': users, 'email': email, 'default_user': DEFAULT_USER, 'guest_user': GUEST_USER, 'enable_guest': ENABLE_GUEST, }, context_instance=RequestContext(request))
def post(self, request): """ Set user quota, set user institution, delete users, in batch. Permission checking: 1. admin user. """ # argument check emails = request.POST.getlist('email', None) if not emails: error_msg = 'email invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) operation = request.POST.get('operation', None) if operation not in ('set-quota', 'delete-user', 'set-institution'): error_msg = "operation can only be 'set-quota', 'delete-user', or 'set-institution'." return api_error(status.HTTP_400_BAD_REQUEST, error_msg) result = {} result['failed'] = [] result['success'] = [] existed_users = [] for email in emails: try: user = User.objects.get(email=email) existed_users.append(user) except User.DoesNotExist: result['failed'].append({ 'email': email, 'error_msg': 'User %s not found.' % email }) continue if operation == 'set-quota': quota_total_mb = request.POST.get('quota_total', None) if not quota_total_mb: error_msg = 'quota_total invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: quota_total_mb = int(quota_total_mb) except ValueError: error_msg = _('must be an integer that is greater than or equal to 0.') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if quota_total_mb < 0: error_msg = _('Space quota is too low (minimum value is 0)') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) quota_total_byte = quota_total_mb * get_file_size_unit('MB') for user in existed_users: email = user.email try: seafile_api.set_user_quota(email, quota_total_byte) except Exception as e: logger.error(e) result['failed'].append({ 'email': email, 'error_msg': 'Internal Server Error' }) continue result['success'].append({ 'email': email, 'quota_total': seafile_api.get_user_quota(email), }) if operation == 'delete-user': for user in existed_users: email = user.email try: user.delete() except Exception as e: logger.error(e) result['failed'].append({ 'email': email, 'error_msg': 'Internal Server Error' }) continue result['success'].append({ 'email': email, }) # send admin operation log signal admin_op_detail = { "email": email, } admin_operation.send(sender=None, admin_name=request.user.username, operation=USER_DELETE, detail=admin_op_detail) if operation == 'set-institution': institution = request.POST.get('institution', None) if institution is None: error_msg = 'Institution can not be blank.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if institution != '': try: obj_insti = Institution.objects.get(name=institution) except Institution.DoesNotExist: error_msg = 'Institution %s does not exist' % institution return api_error(status.HTTP_400_BAD_REQUEST, error_msg) for user in existed_users: email = user.email profile = Profile.objects.get_profile_by_user(email) if profile is None: profile = Profile(user=email) profile.institution = institution profile.save() result['success'].append({ 'email': email, 'institution': institution }) return Response(result)
def user_info(request, email): owned_repos = seafile_api.get_owned_repo_list(email) org = ccnet_threaded_rpc.get_orgs_by_user(email) org_name = None if not org: space_usage = seafile_api.get_user_self_usage(email) space_quota = seafile_api.get_user_quota(email) if CALC_SHARE_USAGE: share_usage = seafile_api.get_user_share_usage(email) share_quota = seafile_api.get_user_share_quota(email) else: share_quota = share_usage = 0 else: org_id = org[0].org_id org_name = org[0].org_name space_usage = seafserv_threaded_rpc.get_org_user_quota_usage(org_id, email) space_quota = seafserv_threaded_rpc.get_org_user_quota(org_id, email) share_usage = share_quota = 0 # Repos that are share to user in_repos = seafile_api.get_share_in_repo_list(email, -1, -1) # get user profile profile = Profile.objects.get_profile_by_user(email) d_profile = DetailedProfile.objects.get_detailed_profile_by_user(email) user_shared_links = [] # download links p_fileshares = [] fileshares = list(FileShare.objects.filter(username=email)) for fs in fileshares: r = seafile_api.get_repo(fs.repo_id) if not r: fs.delete() continue if fs.is_file_share_link(): if seafile_api.get_file_id_by_path(r.id, fs.path) is None: fs.delete() continue fs.filename = os.path.basename(fs.path) path = fs.path.rstrip('/') # Normalize file path obj_id = seafile_api.get_file_id_by_path(r.id, path) fs.file_size = seafile_api.get_file_size(r.store_id, r.version, obj_id) else: if seafile_api.get_dir_id_by_path(r.id, fs.path) is None: fs.delete() continue fs.filename = os.path.basename(fs.path.rstrip('/')) path = fs.path if path[-1] != '/': # Normalize dir path path += '/' # get dir size dir_id = seafserv_threaded_rpc.get_dirid_by_path(r.id, r.head_cmmt_id, path) fs.dir_size = seafserv_threaded_rpc.get_dir_size(r.store_id, r.version, dir_id) fs.is_download = True p_fileshares.append(fs) p_fileshares.sort(key=lambda x: x.view_cnt, reverse=True) user_shared_links += p_fileshares # upload links uploadlinks = list(UploadLinkShare.objects.filter(username=email)) p_uploadlinks = [] for link in uploadlinks: r = seafile_api.get_repo(link.repo_id) if not r: link.delete() continue if seafile_api.get_dir_id_by_path(r.id, link.path) is None: link.delete() continue link.dir_name = os.path.basename(link.path.rstrip('/')) link.is_upload = True p_uploadlinks.append(link) p_uploadlinks.sort(key=lambda x: x.view_cnt, reverse=True) user_shared_links += p_uploadlinks return render_to_response( 'sysadmin/userinfo.html', { 'owned_repos': owned_repos, 'space_quota': space_quota, 'space_usage': space_usage, 'share_quota': share_quota, 'share_usage': share_usage, 'CALC_SHARE_USAGE': CALC_SHARE_USAGE, 'in_repos': in_repos, 'email': email, 'profile': profile, 'd_profile': d_profile, 'org_name': org_name, 'user_shared_links': user_shared_links, }, context_instance=RequestContext(request))
def handle(self, *args, **options): self.stdout.write("Export users to '../users.xlsx'.") try: users = ccnet_api.get_emailusers('DB', -1, -1) + \ ccnet_api.get_emailusers('LDAPImport', -1, -1) except Exception as e: self.stdout.write('Error: ' + str(e)) return if is_pro_version(): is_pro = True else: is_pro = False if is_pro: head = [_("Email"), _("Name"), _("Contact Email"), _("Status"), _("Role"), _("Space Usage") + "(MB)", _("Space Quota") + "(MB)", _("Create At"), _("Last Login"), _("Admin"), _("LDAP(imported)"),] else: head = [_("Email"), _("Name"), _("Contact Email"), _("Status"), _("Space Usage") + "(MB)", _("Space Quota") + "(MB)", _("Create At"), _("Last Login"), _("Admin"), _("LDAP(imported)"),] # only operate 100 users for every `for` loop looped = 0 limit = 100 data_list = [] while looped < len(users): current_users = users[looped:looped+limit] last_logins = UserLastLogin.objects.filter(username__in=[x.email \ for x in current_users]) user_profiles = Profile.objects.filter(user__in=[x.email \ for x in current_users]) for user in current_users: # populate name and contact email user.contact_email = '' user.name = '' for profile in user_profiles: if profile.user == user.email: user.contact_email = profile.contact_email user.name = profile.nickname # populate space usage and quota MB = get_file_size_unit('MB') # populate user quota usage orgs = ccnet_api.get_orgs_by_user(user.email) try: if orgs: user.org = orgs[0] org_id = user.org.org_id user.space_usage = seafile_api.get_org_user_quota_usage(org_id, user.email) user.space_quota = seafile_api.get_org_user_quota(org_id, user.email) else: user.space_usage = seafile_api.get_user_self_usage(user.email) user.space_quota = seafile_api.get_user_quota(user.email) except Exception as e: self.stdout.write('Debug: ' + str(e)) user.space_usage = -1 user.space_quota = -1 if user.space_usage > 0: try: space_usage_MB = round(float(user.space_usage) / MB, 2) except Exception as e: self.stdout.write('Debug: ' + str(e)) space_usage_MB = '--' else: space_usage_MB = '' if user.space_quota > 0: try: space_quota_MB = round(float(user.space_quota) / MB, 2) except Exception as e: self.stdout.write('Debug: ' + str(e)) space_quota_MB = '--' else: space_quota_MB = '' # populate user last login time user.last_login = None for last_login in last_logins: if last_login.username == user.email: user.last_login = last_login.last_login if user.is_active: status = _('Active') else: status = _('Inactive') create_at = tsstr_sec(user.ctime) if user.ctime else '' last_login = user.last_login.strftime("%Y-%m-%d %H:%M:%S") if \ user.last_login else '' is_admin = _('Yes') if user.is_staff else '' ldap_import = _('Yes') if user.source == 'LDAPImport' else '' if is_pro: if user.role: if user.role == GUEST_USER: role = _('Guest') elif user.role == DEFAULT_USER: role = _('Default') else: role = user.role else: role = _('Default') row = [user.email, user.name, user.contact_email, status, role, space_usage_MB, space_quota_MB, create_at, last_login, is_admin, ldap_import] else: row = [user.email, user.name, user.contact_email, status, space_usage_MB, space_quota_MB, create_at, last_login, is_admin, ldap_import] data_list.append(row) # update `looped` value when `for` loop finished looped += limit wb = write_xls('users', head, data_list) if not wb: self.stdout.write('Error: please check the log.') return wb.save('../users.xlsx') self.stdout.write('Done.\n')