API to allow authenticated users to change their password

This commit is contained in:
Kovid Goyal 2017-06-27 11:21:01 +05:30
parent 5b2603b98d
commit eddc49fa44
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
3 changed files with 33 additions and 1 deletions

View File

@ -152,7 +152,7 @@ class Context(object):
return old[1]
SRV_MODULES = ('ajax', 'books', 'cdb', 'code', 'content', 'legacy', 'opds')
SRV_MODULES = ('ajax', 'books', 'cdb', 'code', 'content', 'legacy', 'opds', 'users_api')
class Handler(object):

View File

@ -54,6 +54,8 @@ def validate_username(username):
def validate_password(pw):
if not pw:
return _('Empty passwords are not allowed')
try:
pw = pw.encode('ascii', 'strict')
except ValueError:

View File

@ -0,0 +1,30 @@
#!/usr/bin/env python2
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
from calibre import as_unicode
from calibre.srv.errors import HTTPBadRequest, HTTPForbidden
from calibre.srv.routes import endpoint
from calibre.srv.users import validate_password
@endpoint('/users/change-pw', methods={'POST'})
def change_pw(ctx, rd):
user = rd.username or None
if user is None:
raise HTTPForbidden('Anonymous users are not allowed to change passwords')
try:
pw = rd.request_body_file.read().decode('utf-8')
except Exception:
raise HTTPBadRequest('No decodable password found')
err = validate_password(pw)
if err:
raise HTTPBadRequest(err)
try:
ctx.user_manager.change_password(user, pw)
except Exception as err:
raise HTTPBadRequest(as_unicode(err))
ctx.log.warn('Changed password for user', user)
return 'password for {} changed'.format(user)