1
0
mirror of https://github.com/haiwen/seahub.git synced 2025-09-05 08:53:14 +00:00

Webdav secret (#5357)

* not show webdav password on user profile setting page

* hash webdav password

* show webdav url and username on user profile setting page

* update test

* update

* update

Co-authored-by: lian <lian@seafile.com>
This commit is contained in:
lian
2023-01-18 09:59:53 +08:00
committed by GitHub
parent d2aa07da63
commit ff9a0e92f9
10 changed files with 305 additions and 66 deletions

View File

@@ -0,0 +1,53 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Modal, ModalHeader, ModalBody, ModalFooter, Alert, Button, Input, InputGroup, InputGroupAddon } from 'reactstrap';
import { gettext } from '../../utils/constants';
import { Utils } from '../../utils/utils';
const propTypes = {
removePassword: PropTypes.func.isRequired,
toggle: PropTypes.func.isRequired
};
class RemoveWebdavPassword extends Component {
constructor(props) {
super(props);
this.state = {
btnDisabled: false,
errMsg: ''
};
}
submit = () => {
this.setState({
btnDisabled: true
});
this.props.removePassword();
}
render() {
const { toggle } = this.props;
let dialogMsg = gettext('Are you sure you want to remove {placeholder} ?').replace('{placeholder}', 'WebDAV password');
return (
<Modal centered={true} isOpen={true} toggle={toggle}>
<ModalHeader toggle={toggle}>{gettext('Remove WebDAV Password')}</ModalHeader>
<ModalBody>
<p>{dialogMsg}</p>
</ModalBody>
{this.state.errMsg && <Alert color="danger" className="m-0 mt-2">{gettext(this.state.errMsg)}</Alert>}
<ModalFooter>
<Button color="secondary" onClick={toggle}>{gettext('Cancel')}</Button>
<Button color="primary" onClick={this.submit} disabled={this.state.btnDisabled}>{gettext('Submit')}</Button>
</ModalFooter>
</Modal>
);
}
}
RemoveWebdavPassword.propTypes = propTypes;
export default RemoveWebdavPassword;

View File

@@ -5,19 +5,18 @@ import { gettext } from '../../utils/constants';
import { Utils } from '../../utils/utils';
const propTypes = {
password: PropTypes.string.isRequired,
updatePassword: PropTypes.func.isRequired,
resetPassword: PropTypes.func.isRequired,
toggle: PropTypes.func.isRequired
};
const { webdavSecretMinLength, webdavSecretStrengthLevel } = window.app.pageOptions;
class UpdateWebdavPassword extends Component {
class ResetWebdavPassword extends Component {
constructor(props) {
super(props);
this.state = {
password: this.props.password,
password: '',
isPasswordVisible: false,
btnDisabled: false,
errMsg: ''
@@ -44,7 +43,7 @@ class UpdateWebdavPassword extends Component {
btnDisabled: true
});
this.props.updatePassword(this.state.password.trim());
this.props.resetPassword(this.state.password.trim());
}
handleInputChange = (e) => {
@@ -71,7 +70,7 @@ class UpdateWebdavPassword extends Component {
return (
<Modal centered={true} isOpen={true} toggle={toggle}>
<ModalHeader toggle={toggle}>{gettext('WebDav Password')}</ModalHeader>
<ModalHeader toggle={toggle}>{gettext('Reset WebDAV Password')}</ModalHeader>
<ModalBody>
<InputGroup>
<Input type={this.state.isPasswordVisible ? 'text' : 'password'} value={this.state.password} onChange={this.handleInputChange} autoComplete="new-password"/>
@@ -92,6 +91,6 @@ class UpdateWebdavPassword extends Component {
}
}
UpdateWebdavPassword.propTypes = propTypes;
ResetWebdavPassword.propTypes = propTypes;
export default UpdateWebdavPassword;
export default ResetWebdavPassword;

View File

@@ -0,0 +1,96 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Modal, ModalHeader, ModalBody, ModalFooter, Alert, Button, Input, InputGroup, InputGroupAddon } from 'reactstrap';
import { gettext } from '../../utils/constants';
import { Utils } from '../../utils/utils';
const propTypes = {
setPassword: PropTypes.func.isRequired,
toggle: PropTypes.func.isRequired
};
const { webdavSecretMinLength, webdavSecretStrengthLevel } = window.app.pageOptions;
class SetWebdavPassword extends Component {
constructor(props) {
super(props);
this.state = {
password: '',
isPasswordVisible: false,
btnDisabled: false,
errMsg: ''
};
}
submit = () => {
if (this.state.password.length === 0) {
this.setState({errMsg: gettext('Please enter a password.')});
return false;
}
if (this.state.password.length < webdavSecretMinLength) {
this.setState({errMsg: gettext('The password is too short.')});
return false;
}
if (Utils.getStrengthLevel(this.state.password) < webdavSecretStrengthLevel) {
this.setState({errMsg: gettext('The password is too weak. It should include at least {passwordStrengthLevel} of the following: number, upper letter, lower letter and other symbols.').replace('{passwordStrengthLevel}', webdavSecretStrengthLevel)});
return false;
}
this.setState({
btnDisabled: true
});
this.props.setPassword(this.state.password.trim());
}
handleInputChange = (e) => {
this.setState({password: e.target.value});
}
togglePasswordVisible = () => {
this.setState({
isPasswordVisible: !this.state.isPasswordVisible
});
}
generatePassword = () => {
let randomPassword = Utils.generatePassword(webdavSecretMinLength);
this.setState({
password: randomPassword,
isPasswordVisible: true
});
}
render() {
const { toggle } = this.props;
const passwordTip = gettext('(at least {passwordMinLength} characters and includes {passwordStrengthLevel} of the following: number, upper letter, lower letter and other symbols)').replace('{passwordMinLength}', webdavSecretMinLength).replace('{passwordStrengthLevel}', webdavSecretStrengthLevel);
return (
<Modal centered={true} isOpen={true} toggle={toggle}>
<ModalHeader toggle={toggle}>{gettext('Set WebDAV Password')}</ModalHeader>
<ModalBody>
<InputGroup>
<Input type={this.state.isPasswordVisible ? 'text' : 'password'} value={this.state.password} onChange={this.handleInputChange} autoComplete="new-password"/>
<InputGroupAddon addonType="append">
<Button onClick={this.togglePasswordVisible}><i className={`fas ${this.state.isPasswordVisible ? 'fa-eye': 'fa-eye-slash'}`}></i></Button>
<Button onClick={this.generatePassword}><i className="fas fa-magic"></i></Button>
</InputGroupAddon>
</InputGroup>
<p className="form-text text-muted m-0">{passwordTip}</p>
{this.state.errMsg && <Alert color="danger" className="m-0 mt-2">{gettext(this.state.errMsg)}</Alert>}
</ModalBody>
<ModalFooter>
<Button color="secondary" onClick={toggle}>{gettext('Cancel')}</Button>
<Button color="primary" onClick={this.submit} disabled={this.state.btnDisabled}>{gettext('Submit')}</Button>
</ModalFooter>
</Modal>
);
}
}
SetWebdavPassword.propTypes = propTypes;
export default SetWebdavPassword;

View File

@@ -4,44 +4,78 @@ import { gettext } from '../../utils/constants';
import { seafileAPI } from '../../utils/seafile-api';
import { Utils } from '../../utils/utils';
import toaster from '../toast';
import UpdateWebdavPassword from '../dialog/update-webdav-password';
import SetWebdavPassword from '../dialog/set-webdav-password';
import ResetWebdavPassword from '../dialog/reset-webdav-password';
import RemoveWebdavPassword from '../dialog/remove-webdav-password';
const { webdavPasswd } = window.app.pageOptions;
const { username, webdavUrl, webdavPasswordSetted } = window.app.pageOptions;
class WebdavPassword extends React.Component {
constructor(props) {
super(props);
this.state = {
password: webdavPasswd,
isPasswordVisible: false,
isDialogOpen: false
isWebdavPasswordSetted: webdavPasswordSetted,
isSetPasserdDialogOpen: false,
isResetPasserdDialogOpen: false,
isRemovePasserdDialogOpen: false,
};
}
togglePasswordVisible = () => {
toggleSetPasswordDialog = () => {
this.setState({
isPasswordVisible: !this.state.isPasswordVisible
isSetPasserdDialogOpen: !this.state.isSetPasserdDialogOpen,
});
}
updatePassword = (password) => {
setPassword = (password) => {
seafileAPI.updateWebdavSecret(password).then((res) => {
this.toggleDialog();
this.toggleSetPasswordDialog();
this.setState({
password: password
isWebdavPasswordSetted: !this.state.isWebdavPasswordSetted,
});
toaster.success(gettext('Success'));
}).catch((error) => {
let errorMsg = Utils.getErrorMsg(error);
this.toggleDialog();
this.toggleSetPasswordDialog();
toaster.danger(errorMsg);
});
}
toggleDialog = () => {
toggleResetPasswordDialog = () => {
this.setState({
isDialogOpen: !this.state.isDialogOpen
isResetPasswordDialogOpen: !this.state.isResetPasswordDialogOpen,
});
}
resetPassword = (password) => {
seafileAPI.updateWebdavSecret(password).then((res) => {
this.toggleResetPasswordDialog();
toaster.success(gettext('Success'));
}).catch((error) => {
let errorMsg = Utils.getErrorMsg(error);
this.toggleResetPasswordDialog();
toaster.danger(errorMsg);
});
}
toggleRemovePasswordDialog = () => {
this.setState({
isRemovePasswordDialogOpen: !this.state.isRemovePasswordDialogOpen,
});
}
removePassword = () => {
seafileAPI.updateWebdavSecret().then((res) => {
this.toggleRemovePasswordDialog();
this.setState({
isWebdavPasswordSetted: !this.state.isWebdavPasswordSetted,
});
toaster.success(gettext('Success'));
}).catch((error) => {
let errorMsg = Utils.getErrorMsg(error);
this.toggleRemovePasswordDialog();
toaster.danger(errorMsg);
});
}
@@ -52,30 +86,47 @@ class WebdavPassword extends React.Component {
}
render() {
const { password, isPasswordVisible } = this.state;
const { isWebdavPasswordSetted } = this.state;
return (
<React.Fragment>
<div id="update-webdav-passwd" className="setting-item">
<h3 className="setting-item-heading">{gettext('WebDav Password')}</h3>
{password ? (
<h3 className="setting-item-heading">{gettext('WebDAV Password')}</h3>
<p>{gettext('WebDAV URL:')}<a href={webdavUrl}> {webdavUrl}</a></p>
<p>{gettext('WebDAV username:')} {username}</p>
{!isWebdavPasswordSetted ?
<React.Fragment>
<div className="d-flex align-items-center">
<label className="m-0 mr-2" htmlFor="passwd">{gettext('Password:')}</label>
<input id="passwd" className="border-0 mr-1" type="text" value={isPasswordVisible ? password : '**********'} readOnly={true} size={Math.max(password.length, 10)} />
<span tabIndex="0" role="button" aria-label={isPasswordVisible? gettext('Hide') : gettext('Show')} onClick={this.togglePasswordVisible} onKeyDown={this.onIconKeyDown} className={`eye-icon fas ${this.state.isPasswordVisible ? 'fa-eye': 'fa-eye-slash'}`}></span>
</div>
<button className="btn btn-outline-primary mt-2" onClick={this.toggleDialog}>{gettext('Update')}</button>
<p>{gettext('WebDAV password:')} {gettext('not set')}</p>
<button className="btn btn-outline-primary" onClick={this.toggleSetPasswordDialog}>{gettext('Set Password')}</button>
</React.Fragment>
) : (
<button className="btn btn-outline-primary" onClick={this.toggleDialog}>{gettext('Set Password')}</button>
)}
:
<React.Fragment>
<p>{gettext('WebDAV password:')} ***</p>
<button className="btn btn-outline-primary mr-2" onClick={this.toggleResetPasswordDialog}>{gettext('Reset Password')}</button>
<button className="btn btn-outline-primary" onClick={this.toggleRemovePasswordDialog}>{gettext('Remove Password')}</button>
</React.Fragment>
}
</div>
{this.state.isDialogOpen && (
{this.state.isSetPasserdDialogOpen && (
<ModalPortal>
<UpdateWebdavPassword
password={this.state.password}
updatePassword={this.updatePassword}
toggle={this.toggleDialog}
<SetWebdavPassword
setPassword={this.setPassword}
toggle={this.toggleSetPasswordDialog}
/>
</ModalPortal>
)}
{this.state.isResetPasswordDialogOpen && (
<ModalPortal>
<ResetWebdavPassword
resetPassword={this.resetPassword}
toggle={this.toggleResetPasswordDialog}
/>
</ModalPortal>
)}
{this.state.isRemovePasswordDialogOpen && (
<ModalPortal>
<RemoveWebdavPassword
removePassword={this.removePassword}
toggle={this.toggleRemovePasswordDialog}
/>
</ModalPortal>
)}

View File

@@ -13,8 +13,8 @@ from seahub.api2.authentication import TokenAuthentication
from seahub.api2.throttling import UserRateThrottle
from seahub.api2.utils import api_error
from seahub.options.models import UserOptions
from seahub.utils.hasher import AESPasswordHasher
from seahub.utils import get_password_strength_level
from seahub.utils import get_password_strength_level, \
is_valid_password, hash_password
# Get an instance of a logger
logger = logging.getLogger(__name__)
@@ -43,12 +43,15 @@ class WebdavSecretView(APIView):
return api_error(status.HTTP_403_FORBIDDEN,
'Feature is not enabled.')
aes = AESPasswordHasher()
username = request.user.username
secret = request.data.get("secret", None)
if secret:
if not is_valid_password(secret):
error_msg = _('Password can only contain number, upper letter, lower letter and other symbols.')
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
if len(secret) >= 30:
error_msg = _('Length of WebDav password should be less than 30.')
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
@@ -61,9 +64,9 @@ class WebdavSecretView(APIView):
error_msg = _('Password is too weak.')
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
encoded = aes.encode(secret)
UserOptions.objects.set_webdav_secret(username, encoded)
hashed_password = hash_password(secret)
UserOptions.objects.set_webdav_secret(username, hashed_password)
else:
UserOptions.objects.unset_webdav_secret(username)
return self.get(request, format)
return Response({'success': True})

View File

@@ -267,7 +267,7 @@ class UserOptionsManager(models.Manager):
from seahub.utils.hasher import AESPasswordHasher
secret = UserOptions.objects.get_webdav_secret(username)
if secret:
if secret and secret.startswith(AESPasswordHasher.algorithm):
aes = AESPasswordHasher()
decoded = aes.decode(secret)
else:

View File

@@ -12,6 +12,7 @@
<script type="text/javascript">
// overwrite the one in base_for_react.html
window.app.pageOptions = {
username: "{{request.user.username|escapejs}}",
avatarURL: '{% avatar_url request.user 160 %}',
csrfToken: '{{ csrf_token }}',
@@ -28,7 +29,8 @@ window.app.pageOptions = {
enableWebdavSecret: {% if ENABLE_WEBDAV_SECRET %} true {% else %} false {% endif %},
{% if ENABLE_WEBDAV_SECRET %}
webdavPasswd: '{{ webdav_passwd|escapejs }}',
webdavUrl: "{{ WEBDAV_URL }}",
webdavPasswordSetted: {% if WEBDAV_SECRET_SETTED %} true {% else %} false {% endif %},
webdavSecretMinLength: {{ WEBDAV_SECRET_MIN_LENGTH }},
webdavSecretStrengthLevel: {{ WEBDAV_SECRET_STRENGTH_LEVEL }},
{% endif %}

View File

@@ -19,7 +19,7 @@ from seahub.base.accounts import User, UNUSABLE_PASSWORD
from seahub.base.templatetags.seahub_tags import email2nickname
from seahub.contacts.models import Contact
from seahub.options.models import UserOptions, CryptoOptionNotSetError, DEFAULT_COLLABORATE_EMAIL_INTERVAL
from seahub.utils import is_ldap_user
from seahub.utils import is_ldap_user, get_webdav_url
from seahub.utils.two_factor_auth import has_two_factor_auth
from seahub.views import get_owned_repo_list
from seahub.work_weixin.utils import work_weixin_oauth_check
@@ -79,12 +79,6 @@ def edit_profile(request):
owned_repos = get_owned_repo_list(request)
owned_repos = [r for r in owned_repos if not r.is_virtual]
if settings.ENABLE_WEBDAV_SECRET:
decoded = UserOptions.objects.get_webdav_decoded_secret(username)
webdav_passwd = decoded if decoded else ''
else:
webdav_passwd = ''
file_updates_email_interval = UserOptions.objects.get_file_updates_email_interval(username)
file_updates_email_interval = file_updates_email_interval if file_updates_email_interval is not None else 0
collaborate_email_interval = UserOptions.objects.get_collaborate_email_interval(username)
@@ -110,6 +104,11 @@ def edit_profile(request):
enable_dingtalk = False
social_connected_dingtalk = False
WEBDAV_SECRET_SETTED = False
if settings.ENABLE_WEBDAV_SECRET and \
UserOptions.objects.get_webdav_secret(username):
WEBDAV_SECRET_SETTED = True
resp_dict = {
'form': form,
'server_crypto': server_crypto,
@@ -123,11 +122,12 @@ def edit_profile(request):
'ENABLE_CHANGE_PASSWORD': settings.ENABLE_CHANGE_PASSWORD,
'ENABLE_GET_AUTH_TOKEN_BY_SESSION': settings.ENABLE_GET_AUTH_TOKEN_BY_SESSION,
'ENABLE_WEBDAV_SECRET': settings.ENABLE_WEBDAV_SECRET,
'WEBDAV_SECRET_SETTED': WEBDAV_SECRET_SETTED,
'WEBDAV_URL': get_webdav_url(),
'WEBDAV_SECRET_MIN_LENGTH': settings.WEBDAV_SECRET_MIN_LENGTH,
'WEBDAV_SECRET_STRENGTH_LEVEL': settings.WEBDAV_SECRET_STRENGTH_LEVEL,
'ENABLE_DELETE_ACCOUNT': ENABLE_DELETE_ACCOUNT,
'ENABLE_UPDATE_USER_INFO': ENABLE_UPDATE_USER_INFO,
'webdav_passwd': webdav_passwd,
'file_updates_email_interval': file_updates_email_interval,
'collaborate_email_interval': collaborate_email_interval,
'social_next_page': reverse('edit_profile'),

View File

@@ -29,7 +29,7 @@ from django.http import HttpResponseRedirect, HttpResponse
from django.utils.http import urlquote
from django.utils.html import escape
from django.utils.timezone import make_naive, is_aware
from django.views.static import serve as django_static_serve
from django.utils.crypto import get_random_string
from seahub.auth import REDIRECT_FIELD_NAME
from seahub.api2.models import Token, TokenV2
@@ -958,6 +958,33 @@ def get_service_url():
"""
return config.SERVICE_URL
def get_webdav_url():
"""Get webdav url.
"""
if 'SEAFILE_CENTRAL_CONF_DIR' in os.environ:
conf_dir = os.environ['SEAFILE_CENTRAL_CONF_DIR']
else:
conf_dir = os.environ['SEAFILE_CONF_DIR']
conf_file = os.path.join(conf_dir, 'seafdav.conf')
if not os.path.exists(conf_file):
return ""
config = configparser.ConfigParser()
config.read(conf_file)
if not config.has_option("WEBDAV", "share_name"):
return ""
share_name = config.get("WEBDAV", "share_name")
share_name = share_name.strip('/')
service_url = get_service_url()
service_url = service_url.rstrip('/')
return "{}/{}/".format(service_url, share_name)
def get_server_id():
"""Get server id from seaserv.
"""
@@ -1409,9 +1436,23 @@ def is_valid_org_id(org_id):
return False
def encrypt_with_sha1(origin_str):
def hash_password(password, algorithm='sha1', salt=get_random_string(4)):
return hashlib.sha1(origin_str.encode()).hexdigest()
digest = hashlib.pbkdf2_hmac(algorithm,
password.encode(),
salt.encode(),
10000)
hex_hash = digest.hex()
# sha1$QRle$5511a4e2efb7d12e1f64647f64c0c6e105d150ff
return "{}${}${}".format(algorithm, salt, hex_hash)
def check_hashed_password(password, hashed_password):
algorithm, salt, hex_hash = hashed_password.split('$')
return hashed_password == hash_password(password, algorithm, salt)
ASCII_RE = re.compile(r'[^\x00-\x7f]')

View File

@@ -24,14 +24,8 @@ class WebdavSecretTest(BaseTestCase):
)
self.assertEqual(200, resp.status_code)
json_resp = json.loads(resp.content)
assert json_resp['secret'] == '123456'
resp = self.client.put(
reverse('api-v2.1-webdav-secret'), 'secret=',
'application/x-www-form-urlencoded',
)
self.assertEqual(200, resp.status_code)
json_resp = json.loads(resp.content)
assert json_resp['secret'] is None