def get_context_data(self, **kwargs): try: backup_tokens = StaticDevice.objects.get( user=self.request.user.username).token_set.count() except StaticDevice.DoesNotExist: backup_tokens = 0 return { 'default_device': default_device(self.request.user), 'default_device_type': default_device(self.request.user).__class__.__name__, 'backup_tokens': backup_tokens, }
def get(self, request, *args, **kwargs): """ Start the setup wizard. Redirect if already enabled. """ if default_device(self.request.user): return redirect(self.redirect_url) return super(SetupView, self).get(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated() or \ (not request.user.is_verified() and default_device(request.user)): # If the user has not authenticated raise or redirect to the login # page. Also if the user just enabled two-factor authentication and # has not yet logged in since should also have the same result. If # the user receives a 'you need to enable TFA' by now, he gets # confuses as TFA has just been enabled. So we either raise or # redirect to the login page. if self.raise_anonymous: raise PermissionDenied() else: return redirect('%s?%s' % ( self.get_login_url(), urlencode({self.redirect_field_name: request.get_full_path()}) )) if not request.user.is_verified(): if self.raise_unverified: raise PermissionDenied() elif self.get_verification_url(): return redirect('%s?%s' % ( self.verification_url, urlencode({self.redirect_field_name: request.get_full_path()}) )) else: return TemplateResponse( request=request, template='two_factor/core/otp_required.html', status=403, ) return super(OTPRequiredMixin, self).dispatch(request, *args, **kwargs)
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['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) info['has_default_device'] = True if default_device(user) else False info['is_force_2fa'] = UserOptions.objects.is_force_2fa(email) if is_pro_version(): info['role'] = user.role return info
def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated() or \ (not request.user.is_verified() and default_device(request.user)): # If the user has not authenticated raise or redirect to the login # page. Also if the user just enabled two-factor authentication and # has not yet logged in since should also have the same result. If # the user receives a 'you need to enable TFA' by now, he gets # confuses as TFA has just been enabled. So we either raise or # redirect to the login page. if self.raise_anonymous: raise PermissionDenied() else: return redirect( '%s?%s' % (self.get_login_url(), urlencode( {self.redirect_field_name: request.get_full_path()}))) if not request.user.is_verified(): if self.raise_unverified: raise PermissionDenied() elif self.get_verification_url(): return redirect( '%s?%s' % (self.verification_url, urlencode( {self.redirect_field_name: request.get_full_path()}))) else: return TemplateResponse( request=request, template='two_factor/core/otp_required.html', status=403, ) return super(OTPRequiredMixin, self).dispatch(request, *args, **kwargs)
def get(self, request, *args, **kwargs): """ Start the setup wizard. Redirect if already enabled. """ if default_device(self.request.user): return redirect(self.redirect_url) return super(SetupView, self).get(request, *args, **kwargs)
def verify_two_factor_token(user, token): """ This function is called when doing the api authentication. Backup token is not supported, because if the user has the backup token, he can always login the website and re-setup the totp. """ device = default_device(user) if device: return device.verify_token(token)
def handle(self, *args, **options): for username in args: try: user = User.objects.get_by_natural_key(username) except User.DoesNotExist: raise CommandError('User "%s" does not exist' % username) self.stdout.write('%s: %s' % (username, 'enabled' if default_device(user) else self.style.ERROR('disabled')))
def handle(self, *args, **options): for username in args: try: user = User.objects.get_by_natural_key(username) except User.DoesNotExist: raise CommandError('User "%s" does not exist' % username) self.stdout.write('%s: %s' % ( username, 'enabled' if default_device(user) else self.style.ERROR('disabled') ))
def _two_factor_auth(self, request, user): if not has_two_factor_auth() or not two_factor_auth_enabled(user): return if is_device_remembered(request.META.get('HTTP_X_SEAFILE_S2FA', ''), user): return token = request.META.get('HTTP_X_SEAFILE_OTP', '') if not token: # Generate challenge(send sms/call/...) if token is not provided. default_device(user).generate_challenge() self.two_factor_auth_failed = True msg = 'Two factor auth token is missing.' raise serializers.ValidationError(msg) if not verify_two_factor_token(user, token): self.two_factor_auth_failed = True msg = 'Two factor auth token is invalid.' raise serializers.ValidationError(msg)
def get_device(self, step=None): """ Returns the OTP device selected by the user, or his default device. """ if not self.device_cache: if step == 'backup': try: self.device_cache = StaticDevice.objects.get( user=self.user.username, name='backup') except StaticDevice.DoesNotExist: pass if not self.device_cache: self.device_cache = default_device(self.user) return self.device_cache
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 log_user_in(request, user, redirect_to): # Ensure the user-originating redirection url is safe. if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = settings.LOGIN_REDIRECT_URL if request.session.test_cookie_worked(): request.session.delete_test_cookie() clear_login_failed_attempts(request, user.username) if two_factor_auth_enabled(user): if is_device_remembered(request.COOKIES.get('S2FA', ''), user): from seahub.two_factor.models import default_device user.otp_device = default_device(user) else: return handle_two_factor_auth(request, user, redirect_to) # Okay, security checks complete. Log the user in. auth_login(request, user) return HttpResponseRedirect(redirect_to)
def edit_profile(request): """ Show and edit user profile. """ username = request.user.username form_class = DetailedProfileForm if request.method == 'POST': form = form_class(user=request.user, data=request.POST) if form.is_valid(): form.save() messages.success(request, _(u'Successfully edited profile.')) return HttpResponseRedirect(reverse('edit_profile')) else: messages.error(request, _(u'Failed to edit profile')) else: profile = Profile.objects.get_profile_by_user(username) d_profile = DetailedProfile.objects.get_detailed_profile_by_user( username) init_dict = {} if profile: init_dict['nickname'] = profile.nickname init_dict['login_id'] = profile.login_id init_dict['contact_email'] = profile.contact_email init_dict['list_in_address_book'] = profile.list_in_address_book if d_profile: init_dict['department'] = d_profile.department init_dict['telephone'] = d_profile.telephone form = form_class(user=request.user, data=init_dict) # common logic try: server_crypto = UserOptions.objects.is_server_crypto(username) except CryptoOptionNotSetError: # Assume server_crypto is ``False`` if this option is not set. server_crypto = False sub_lib_enabled = UserOptions.objects.is_sub_lib_enabled(username) default_repo_id = UserOptions.objects.get_default_repo(username) if default_repo_id: default_repo = seafile_api.get_repo(default_repo_id) else: default_repo = None owned_repos = get_owned_repo_list(request) owned_repos = filter(lambda r: not r.is_virtual, owned_repos) if settings.ENABLE_WEBDAV_SECRET: decoded = UserOptions.objects.get_webdav_decoded_secret(username) webdav_passwd = decoded if decoded else '' else: webdav_passwd = '' email_inverval = UserOptions.objects.get_file_updates_email_interval( username) email_inverval = email_inverval if email_inverval is not None else 0 if settings.SOCIAL_AUTH_WEIXIN_WORK_KEY: enable_wechat_work = True from social_django.models import UserSocialAuth social_connected = UserSocialAuth.objects.filter( username=request.user.username, provider='weixin-work').count() > 0 else: enable_wechat_work = False social_connected = False resp_dict = { 'form': form, 'server_crypto': server_crypto, "sub_lib_enabled": sub_lib_enabled, 'ENABLE_ADDRESSBOOK_OPT_IN': settings.ENABLE_ADDRESSBOOK_OPT_IN, 'default_repo': default_repo, 'owned_repos': owned_repos, 'is_pro': is_pro_version(), 'is_ldap_user': is_ldap_user(request.user), 'two_factor_auth_enabled': has_two_factor_auth(), 'ENABLE_CHANGE_PASSWORD': settings.ENABLE_CHANGE_PASSWORD, 'ENABLE_WEBDAV_SECRET': settings.ENABLE_WEBDAV_SECRET, 'ENABLE_DELETE_ACCOUNT': ENABLE_DELETE_ACCOUNT, 'ENABLE_UPDATE_USER_INFO': ENABLE_UPDATE_USER_INFO, 'webdav_passwd': webdav_passwd, 'email_notification_interval': email_inverval, 'social_connected': social_connected, 'social_next_page': reverse('edit_profile'), 'enable_wechat_work': enable_wechat_work, 'ENABLE_USER_SET_CONTACT_EMAIL': settings.ENABLE_USER_SET_CONTACT_EMAIL, 'user_unusable_password': request.user.enc_password == UNUSABLE_PASSWORD, } if has_two_factor_auth(): from seahub.two_factor.models import StaticDevice, default_device try: backup_tokens = StaticDevice.objects.get( user=request.user.username).token_set.count() except StaticDevice.DoesNotExist: backup_tokens = 0 resp_dict['default_device'] = default_device(request.user) resp_dict['backup_tokens'] = backup_tokens #template = 'profile/set_profile.html' template = 'profile/set_profile_react.html' return render(request, template, resp_dict)
def edit_profile(request): """ Show and edit user profile. """ username = request.user.username form_class = DetailedProfileForm if request.method == 'POST': form = form_class(request.POST) if form.is_valid(): form.save(username=username) messages.success(request, _(u'Successfully edited profile.')) return HttpResponseRedirect(reverse('edit_profile')) else: messages.error(request, _(u'Failed to edit profile')) else: profile = Profile.objects.get_profile_by_user(username) d_profile = DetailedProfile.objects.get_detailed_profile_by_user( username) init_dict = {} if profile: init_dict['nickname'] = profile.nickname init_dict['login_id'] = profile.login_id init_dict['contact_email'] = profile.contact_email init_dict['list_in_address_book'] = profile.list_in_address_book if d_profile: init_dict['department'] = d_profile.department init_dict['telephone'] = d_profile.telephone form = form_class(init_dict) # common logic try: server_crypto = UserOptions.objects.is_server_crypto(username) except CryptoOptionNotSetError: # Assume server_crypto is ``False`` if this option is not set. server_crypto = False sub_lib_enabled = UserOptions.objects.is_sub_lib_enabled(username) default_repo_id = UserOptions.objects.get_default_repo(username) if default_repo_id: default_repo = seafile_api.get_repo(default_repo_id) else: default_repo = None owned_repos = get_owned_repo_list(request) owned_repos = filter(lambda r: not r.is_virtual, owned_repos) resp_dict = { 'form': form, 'server_crypto': server_crypto, "sub_lib_enabled": sub_lib_enabled, 'ENABLE_ADDRESSBOOK_OPT_IN': settings.ENABLE_ADDRESSBOOK_OPT_IN, 'default_repo': default_repo, 'owned_repos': owned_repos, 'is_pro': is_pro_version(), 'is_ldap_user': is_ldap_user(request.user), 'two_factor_auth_enabled': has_two_factor_auth(), } if has_two_factor_auth(): from seahub.two_factor.models import StaticDevice, default_device try: backup_tokens = StaticDevice.objects.get( user=request.user.username).token_set.count() except StaticDevice.DoesNotExist: backup_tokens = 0 resp_dict['default_device'] = default_device(request.user) resp_dict['backup_tokens'] = backup_tokens return render(request, 'profile/set_profile.html', resp_dict)
def edit_profile(request): """ Show and edit user profile. """ username = request.user.username form_class = DetailedProfileForm if request.method == 'POST': form = form_class(user=request.user, data=request.POST) if form.is_valid(): form.save() messages.success(request, _(u'Successfully edited profile.')) return HttpResponseRedirect(reverse('edit_profile')) else: messages.error(request, _(u'Failed to edit profile')) else: profile = Profile.objects.get_profile_by_user(username) d_profile = DetailedProfile.objects.get_detailed_profile_by_user( username) init_dict = {} if profile: init_dict['nickname'] = profile.nickname init_dict['login_id'] = profile.login_id init_dict['contact_email'] = profile.contact_email init_dict['list_in_address_book'] = profile.list_in_address_book if d_profile: init_dict['department'] = d_profile.department init_dict['telephone'] = d_profile.telephone form = form_class(user=request.user, data=init_dict) # common logic try: server_crypto = UserOptions.objects.is_server_crypto(username) except CryptoOptionNotSetError: # Assume server_crypto is ``False`` if this option is not set. server_crypto = False sub_lib_enabled = UserOptions.objects.is_sub_lib_enabled(username) default_repo_id = UserOptions.objects.get_default_repo(username) if default_repo_id: default_repo = seafile_api.get_repo(default_repo_id) else: default_repo = None owned_repos = get_owned_repo_list(request) owned_repos = filter(lambda r: not r.is_virtual, owned_repos) if settings.ENABLE_WEBDAV_SECRET: decoded = UserOptions.objects.get_webdav_decoded_secret(username) webdav_passwd = decoded if decoded else '' else: webdav_passwd = '' email_inverval = UserOptions.objects.get_file_updates_email_interval(username) email_inverval = email_inverval if email_inverval is not None else 0 if settings.SOCIAL_AUTH_WEIXIN_WORK_KEY: enable_wechat_work = True from social_django.models import UserSocialAuth social_connected = UserSocialAuth.objects.filter( username=request.user.username, provider='weixin-work').count() > 0 else: enable_wechat_work = False social_connected = False resp_dict = { 'form': form, 'server_crypto': server_crypto, "sub_lib_enabled": sub_lib_enabled, 'ENABLE_ADDRESSBOOK_OPT_IN': settings.ENABLE_ADDRESSBOOK_OPT_IN, 'default_repo': default_repo, 'owned_repos': owned_repos, 'is_pro': is_pro_version(), 'is_ldap_user': is_ldap_user(request.user), 'two_factor_auth_enabled': has_two_factor_auth(), 'ENABLE_CHANGE_PASSWORD': settings.ENABLE_CHANGE_PASSWORD, 'ENABLE_WEBDAV_SECRET': settings.ENABLE_WEBDAV_SECRET, 'ENABLE_DELETE_ACCOUNT': ENABLE_DELETE_ACCOUNT, 'ENABLE_UPDATE_USER_INFO': ENABLE_UPDATE_USER_INFO, 'webdav_passwd': webdav_passwd, 'email_notification_interval': email_inverval, 'social_connected': social_connected, 'social_next_page': reverse('edit_profile'), 'enable_wechat_work': enable_wechat_work, 'ENABLE_USER_SET_CONTACT_EMAIL': settings.ENABLE_USER_SET_CONTACT_EMAIL, 'user_unusable_password': request.user.enc_password == UNUSABLE_PASSWORD, } if has_two_factor_auth(): from seahub.two_factor.models import StaticDevice, default_device try: backup_tokens = StaticDevice.objects.get( user=request.user.username).token_set.count() except StaticDevice.DoesNotExist: backup_tokens = 0 resp_dict['default_device'] = default_device(request.user) resp_dict['backup_tokens'] = backup_tokens #template = 'profile/set_profile.html' template = 'profile/set_profile_react.html' return render(request, template, resp_dict)
def has_token_step(self): return default_device(self.get_user_from_request(self.request))