##// END OF EJS Templates
cleanup: replace redirect with WebOb exceptions...
r5543:d9b78d8f default
Show More
my_account.py
277 lines | 10.9 KiB | text/x-python | PythonLexer
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 # -*- coding: utf-8 -*-
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
kallithea.controllers.admin.my_account
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Bradley M. Kuhn
General renaming to Kallithea
r4212 my account controller for Kallithea admin
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187
Bradley M. Kuhn
RhodeCode GmbH is not the sole author of this work
r4211 This file was forked by the Kallithea project in July 2014.
Original author and date, and relevant copyright and licensing information is below:
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 :created_on: August 20, 2013
:author: marcink
Bradley M. Kuhn
RhodeCode GmbH is not the sole author of this work
r4211 :copyright: (c) 2013 RhodeCode GmbH, and others.
Bradley M. Kuhn
Correct licensing information in individual files....
r4208 :license: GPLv3, see LICENSE.md for more details.
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 """
import logging
import traceback
import formencode
Mads Kiilerich
cleanup: remove unused Python imports, found with pyflakes
r4422 from sqlalchemy import func
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 from formencode import htmlfill
from pylons import request, tmpl_context as c, url
from pylons.i18n.translation import _
Søren Løvborg
cleanup: replace redirect with WebOb exceptions...
r5543 from webob.exc import HTTPFound
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187
Bradley M. Kuhn
db: introduce EXTERN_TYPE_INTERNAL for Users.extern_type and .extern_name value for auth type for internal users
r4222 from kallithea import EXTERN_TYPE_INTERNAL
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 from kallithea.lib import helpers as h
Mads Kiilerich
auth: make the auth module decide which fields are editable by admin and user
r5343 from kallithea.lib import auth_modules
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 from kallithea.lib.auth import LoginRequired, NotAnonymous, AuthUser
from kallithea.lib.base import BaseController, render
from kallithea.lib.utils2 import generate_api_key, safe_int
from kallithea.lib.compat import json
Mads Kiilerich
cleanup: remove unused imports...
r5397 from kallithea.model.db import Repository, UserEmailMap, User, UserFollowing
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 from kallithea.model.forms import UserForm, PasswordChangeForm
from kallithea.model.user import UserModel
from kallithea.model.repo import RepoModel
from kallithea.model.api_key import ApiKeyModel
from kallithea.model.meta import Session
log = logging.getLogger(__name__)
class MyAccountController(BaseController):
"""REST Controller styled on the Atom Publishing Protocol"""
# To properly map this controller, ensure your config/routing.py
# file has a resource setup:
# map.resource('setting', 'settings', controller='admin/settings',
# path_prefix='/admin', name_prefix='admin_')
@LoginRequired()
@NotAnonymous()
def __before__(self):
super(MyAccountController, self).__before__()
def __load_data(self):
Bradley M. Kuhn
Rename rhodecode_user to authuser - it is an AuthUser instance
r4197 c.user = User.get(self.authuser.user_id)
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 if c.user.username == User.DEFAULT_USER:
h.flash(_("You can't edit this user since it's"
" crucial for entire application"), category='warning')
Søren Løvborg
cleanup: replace redirect with WebOb exceptions...
r5543 raise HTTPFound(location=url('users'))
Bradley M. Kuhn
db: introduce EXTERN_TYPE_INTERNAL for Users.extern_type and .extern_name value for auth type for internal users
r4222 c.EXTERN_TYPE_INTERNAL = EXTERN_TYPE_INTERNAL
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187
def _load_my_repos_data(self, watched=False):
if watched:
admin = False
repos_list = [x.follows_repository for x in
Session().query(UserFollowing).filter(
UserFollowing.user_id ==
Bradley M. Kuhn
Rename rhodecode_user to authuser - it is an AuthUser instance
r4197 self.authuser.user_id).all()]
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 else:
admin = True
repos_list = Session().query(Repository)\
.filter(Repository.user_id ==
Bradley M. Kuhn
Rename rhodecode_user to authuser - it is an AuthUser instance
r4197 self.authuser.user_id)\
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 .order_by(func.lower(Repository.repo_name)).all()
repos_data = RepoModel().get_repos_as_dict(repos_list=repos_list,
admin=admin)
#json used to render the grid
return json.dumps(repos_data)
def my_account(self):
"""
GET /_admin/my_account Displays info about my account
"""
# url('my_account')
c.active = 'profile'
self.__load_data()
Søren Løvborg
AuthUser: Drop ip_addr field...
r5211 c.perm_user = AuthUser(user_id=self.authuser.user_id)
c.ip_addr = self.ip_addr
Mads Kiilerich
auth: make the auth module decide which fields are editable by admin and user
r5343 managed_fields = auth_modules.get_managed_fields(c.user)
Mads Kiilerich
auth: make sure that users only can manage their own primary data if self registration is enabled...
r5344 def_user_perms = User.get_default_user().AuthUser.permissions['global']
if 'hg.register.none' in def_user_perms:
managed_fields.extend(['username', 'firstname', 'lastname', 'email'])
Mads Kiilerich
auth: make the auth module decide which fields are editable by admin and user
r5343 c.readonly = lambda n: 'readonly' if n in managed_fields else None
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187
defaults = c.user.get_dict()
update = False
if request.POST:
_form = UserForm(edit=True,
Bradley M. Kuhn
Rename rhodecode_user to authuser - it is an AuthUser instance
r4197 old_data={'user_id': self.authuser.user_id,
'email': self.authuser.email})()
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 form_result = {}
try:
post_data = dict(request.POST)
post_data['new_password'] = ''
post_data['password_confirmation'] = ''
form_result = _form.to_python(post_data)
# skip updating those attrs for my account
skip_attrs = ['admin', 'active', 'extern_type', 'extern_name',
Mads Kiilerich
auth: make the auth module decide which fields are editable by admin and user
r5343 'new_password', 'password_confirmation',
] + managed_fields
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187
Bradley M. Kuhn
Rename rhodecode_user to authuser - it is an AuthUser instance
r4197 UserModel().update(self.authuser.user_id, form_result,
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 skip_attrs=skip_attrs)
h.flash(_('Your account was updated successfully'),
category='success')
Session().commit()
update = True
Mads Kiilerich
cleanup: consistently use 'except ... as ...:'...
r5374 except formencode.Invalid as errors:
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 return htmlfill.render(
render('admin/my_account/my_account.html'),
defaults=errors.value,
errors=errors.error_dict or {},
prefix_error=False,
Mads Kiilerich
controllers: consistently use formfill.render with force_defaults=False...
r4941 encoding="UTF-8",
force_defaults=False)
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 except Exception:
log.error(traceback.format_exc())
h.flash(_('Error occurred during update of user %s') \
% form_result.get('username'), category='error')
if update:
Søren Løvborg
cleanup: replace redirect with WebOb exceptions...
r5543 raise HTTPFound(location='my_account')
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 return htmlfill.render(
render('admin/my_account/my_account.html'),
defaults=defaults,
encoding="UTF-8",
Mads Kiilerich
controllers: consistently use formfill.render with force_defaults=False...
r4941 force_defaults=False)
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187
def my_account_password(self):
c.active = 'password'
self.__load_data()
Mads Kiilerich
auth: disable password change when not using internal auth
r5345
managed_fields = auth_modules.get_managed_fields(c.user)
c.can_change_password = 'password' not in managed_fields
if request.POST and c.can_change_password:
Bradley M. Kuhn
Rename rhodecode_user to authuser - it is an AuthUser instance
r4197 _form = PasswordChangeForm(self.authuser.username)()
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 try:
form_result = _form.to_python(request.POST)
Bradley M. Kuhn
Rename rhodecode_user to authuser - it is an AuthUser instance
r4197 UserModel().update(self.authuser.user_id, form_result)
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 Session().commit()
h.flash(_("Successfully updated password"), category='success')
except formencode.Invalid as errors:
return htmlfill.render(
render('admin/my_account/my_account.html'),
defaults=errors.value,
errors=errors.error_dict or {},
prefix_error=False,
Mads Kiilerich
controllers: consistently use formfill.render with force_defaults=False...
r4941 encoding="UTF-8",
force_defaults=False)
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 except Exception:
log.error(traceback.format_exc())
h.flash(_('Error occurred during update of user password'),
category='error')
return render('admin/my_account/my_account.html')
def my_account_repos(self):
c.active = 'repos'
self.__load_data()
#json used to render the grid
c.data = self._load_my_repos_data()
return render('admin/my_account/my_account.html')
def my_account_watched(self):
c.active = 'watched'
self.__load_data()
#json used to render the grid
c.data = self._load_my_repos_data(watched=True)
return render('admin/my_account/my_account.html')
def my_account_perms(self):
c.active = 'perms'
self.__load_data()
Søren Løvborg
AuthUser: Drop ip_addr field...
r5211 c.perm_user = AuthUser(user_id=self.authuser.user_id)
c.ip_addr = self.ip_addr
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187
return render('admin/my_account/my_account.html')
def my_account_emails(self):
c.active = 'emails'
self.__load_data()
c.user_email_map = UserEmailMap.query()\
.filter(UserEmailMap.user == c.user).all()
return render('admin/my_account/my_account.html')
def my_account_emails_add(self):
email = request.POST.get('new_email')
try:
Bradley M. Kuhn
Rename rhodecode_user to authuser - it is an AuthUser instance
r4197 UserModel().add_extra_email(self.authuser.user_id, email)
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 Session().commit()
h.flash(_("Added email %s to user") % email, category='success')
Mads Kiilerich
cleanup: consistently use 'except ... as ...:'...
r5374 except formencode.Invalid as error:
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 msg = error.error_dict['email']
h.flash(msg, category='error')
except Exception:
log.error(traceback.format_exc())
h.flash(_('An error occurred during email saving'),
category='error')
Søren Løvborg
cleanup: replace redirect with WebOb exceptions...
r5543 raise HTTPFound(location=url('my_account_emails'))
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187
def my_account_emails_delete(self):
email_id = request.POST.get('del_email_id')
user_model = UserModel()
Bradley M. Kuhn
Rename rhodecode_user to authuser - it is an AuthUser instance
r4197 user_model.delete_extra_email(self.authuser.user_id, email_id)
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 Session().commit()
h.flash(_("Removed email from user"), category='success')
Søren Løvborg
cleanup: replace redirect with WebOb exceptions...
r5543 raise HTTPFound(location=url('my_account_emails'))
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187
def my_account_api_keys(self):
c.active = 'api_keys'
self.__load_data()
show_expired = True
c.lifetime_values = [
Mads Kiilerich
spelling: fix title casing on various translated strings...
r5127 (str(-1), _('Forever')),
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 (str(5), _('5 minutes')),
(str(60), _('1 hour')),
(str(60 * 24), _('1 day')),
(str(60 * 24 * 30), _('1 month')),
]
c.lifetime_options = [(c.lifetime_values, _("Lifetime"))]
Bradley M. Kuhn
Rename rhodecode_user to authuser - it is an AuthUser instance
r4197 c.user_api_keys = ApiKeyModel().get_api_keys(self.authuser.user_id,
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 show_expired=show_expired)
return render('admin/my_account/my_account.html')
def my_account_api_keys_add(self):
lifetime = safe_int(request.POST.get('lifetime'), -1)
description = request.POST.get('description')
Mads Kiilerich
cleanup: remove unused variables, found with pyflakes
r4423 ApiKeyModel().create(self.authuser.user_id, description, lifetime)
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 Session().commit()
Mads Kiilerich
spelling: more consistent casing of 'API key'
r5124 h.flash(_("API key successfully created"), category='success')
Søren Løvborg
cleanup: replace redirect with WebOb exceptions...
r5543 raise HTTPFound(location=url('my_account_api_keys'))
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187
def my_account_api_keys_delete(self):
api_key = request.POST.get('del_api_key')
Bradley M. Kuhn
Rename rhodecode_user to authuser - it is an AuthUser instance
r4197 user_id = self.authuser.user_id
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 if request.POST.get('del_api_key_builtin'):
user = User.get(user_id)
Mads Kiilerich
cleanup: check for None object identity in cases where that is what the 'contract' says...
r5306 if user is not None:
Mads Kiilerich
utils: make API key generator more random...
r5217 user.api_key = generate_api_key()
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 Session().add(user)
Session().commit()
Mads Kiilerich
spelling: more consistent casing of 'API key'
r5124 h.flash(_("API key successfully reset"), category='success')
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 elif api_key:
Bradley M. Kuhn
Rename rhodecode_user to authuser - it is an AuthUser instance
r4197 ApiKeyModel().delete(api_key, self.authuser.user_id)
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187 Session().commit()
Mads Kiilerich
spelling: more consistent casing of 'API key'
r5124 h.flash(_("API key successfully deleted"), category='success')
Bradley M. Kuhn
Second step in two-part process to rename directories....
r4187
Søren Løvborg
cleanup: replace redirect with WebOb exceptions...
r5543 raise HTTPFound(location=url('my_account_api_keys'))