##// END OF EJS Templates
model: always import the whole db module - drop "from" imports
Mads Kiilerich -
r8453:5e46f73f default
parent child Browse files
Show More
@@ -29,7 +29,7 b' depends_on = None'
29 from alembic import op
29 from alembic import op
30 from sqlalchemy import MetaData, Table
30 from sqlalchemy import MetaData, Table
31
31
32 from kallithea.model.db import Ui
32 from kallithea.model import db
33
33
34
34
35 meta = MetaData()
35 meta = MetaData()
@@ -37,7 +37,7 b' meta = MetaData()'
37
37
38 def upgrade():
38 def upgrade():
39 meta.bind = op.get_bind()
39 meta.bind = op.get_bind()
40 ui = Table(Ui.__tablename__, meta, autoload=True)
40 ui = Table(db.Ui.__tablename__, meta, autoload=True)
41
41
42 ui.update(values={
42 ui.update(values={
43 'ui_key': 'prechangegroup.push_lock_handling',
43 'ui_key': 'prechangegroup.push_lock_handling',
@@ -51,7 +51,7 b' def upgrade():'
51
51
52 def downgrade():
52 def downgrade():
53 meta.bind = op.get_bind()
53 meta.bind = op.get_bind()
54 ui = Table(Ui.__tablename__, meta, autoload=True)
54 ui = Table(db.Ui.__tablename__, meta, autoload=True)
55
55
56 ui.update(values={
56 ui.update(values={
57 'ui_key': 'prechangegroup.pre_push',
57 'ui_key': 'prechangegroup.pre_push',
@@ -30,7 +30,7 b' import sqlalchemy as sa'
30 from alembic import op
30 from alembic import op
31 from sqlalchemy import MetaData, Table
31 from sqlalchemy import MetaData, Table
32
32
33 from kallithea.model.db import Ui
33 from kallithea.model import db
34
34
35
35
36 meta = MetaData()
36 meta = MetaData()
@@ -45,7 +45,7 b' def upgrade():'
45 batch_op.drop_column('enable_locking')
45 batch_op.drop_column('enable_locking')
46
46
47 meta.bind = op.get_bind()
47 meta.bind = op.get_bind()
48 ui = Table(Ui.__tablename__, meta, autoload=True)
48 ui = Table(db.Ui.__tablename__, meta, autoload=True)
49 ui.delete().where(ui.c.ui_key == 'prechangegroup.push_lock_handling').execute()
49 ui.delete().where(ui.c.ui_key == 'prechangegroup.push_lock_handling').execute()
50 ui.delete().where(ui.c.ui_key == 'preoutgoing.pull_lock_handling').execute()
50 ui.delete().where(ui.c.ui_key == 'preoutgoing.pull_lock_handling').execute()
51
51
@@ -29,7 +29,7 b' depends_on = None'
29 import sqlalchemy as sa
29 import sqlalchemy as sa
30 from alembic import op
30 from alembic import op
31
31
32 from kallithea.model.db import PullRequestReviewer
32 from kallithea.model import db
33
33
34
34
35 def upgrade():
35 def upgrade():
@@ -41,9 +41,9 b' def upgrade():'
41 # duplicate_values contains one copy of each duplicated pair
41 # duplicate_values contains one copy of each duplicated pair
42 duplicate_values = (
42 duplicate_values = (
43 session
43 session
44 .query(PullRequestReviewer.pull_request_id, PullRequestReviewer.user_id)
44 .query(db.PullRequestReviewer.pull_request_id, db.PullRequestReviewer.user_id)
45 .group_by(PullRequestReviewer.pull_request_id, PullRequestReviewer.user_id)
45 .group_by(db.PullRequestReviewer.pull_request_id, db.PullRequestReviewer.user_id)
46 .having(sa.func.count(PullRequestReviewer.pull_request_reviewers_id) > 1)
46 .having(sa.func.count(db.PullRequestReviewer.pull_request_reviewers_id) > 1)
47 )
47 )
48
48
49 for pull_request_id, user_id in duplicate_values:
49 for pull_request_id, user_id in duplicate_values:
@@ -51,9 +51,9 b' def upgrade():'
51 # currently being processed
51 # currently being processed
52 duplicate_occurrences = (
52 duplicate_occurrences = (
53 session
53 session
54 .query(PullRequestReviewer)
54 .query(db.PullRequestReviewer)
55 .filter(PullRequestReviewer.pull_request_id == pull_request_id)
55 .filter(db.PullRequestReviewer.pull_request_id == pull_request_id)
56 .filter(PullRequestReviewer.user_id == user_id)
56 .filter(db.PullRequestReviewer.user_id == user_id)
57 )
57 )
58 for prr in duplicate_occurrences:
58 for prr in duplicate_occurrences:
59 if (pull_request_id, user_id) in seen:
59 if (pull_request_id, user_id) in seen:
@@ -30,8 +30,7 b' import kallithea'
30 import kallithea.bin.kallithea_cli_base as cli_base
30 import kallithea.bin.kallithea_cli_base as cli_base
31 from kallithea.lib.utils import REMOVED_REPO_PAT, repo2db_mapper
31 from kallithea.lib.utils import REMOVED_REPO_PAT, repo2db_mapper
32 from kallithea.lib.utils2 import ask_ok
32 from kallithea.lib.utils2 import ask_ok
33 from kallithea.model import meta
33 from kallithea.model import db, meta
34 from kallithea.model.db import Repository
35 from kallithea.model.scm import ScmModel
34 from kallithea.model.scm import ScmModel
36
35
37
36
@@ -73,11 +72,11 b' def repo_update_metadata(repositories):'
73 updated.
72 updated.
74 """
73 """
75 if not repositories:
74 if not repositories:
76 repo_list = Repository.query().all()
75 repo_list = db.Repository.query().all()
77 else:
76 else:
78 repo_names = [n.strip() for n in repositories]
77 repo_names = [n.strip() for n in repositories]
79 repo_list = list(Repository.query()
78 repo_list = list(db.Repository.query()
80 .filter(Repository.repo_name.in_(repo_names)))
79 .filter(db.Repository.repo_name.in_(repo_names)))
81
80
82 for repo in repo_list:
81 for repo in repo_list:
83 # update latest revision metadata in database
82 # update latest revision metadata in database
@@ -35,7 +35,7 b' from kallithea.config.middleware.pygrack'
35 from kallithea.lib.base import BaseVCSController, get_path_info
35 from kallithea.lib.base import BaseVCSController, get_path_info
36 from kallithea.lib.hooks import log_pull_action
36 from kallithea.lib.hooks import log_pull_action
37 from kallithea.lib.utils import make_ui
37 from kallithea.lib.utils import make_ui
38 from kallithea.model.db import Repository
38 from kallithea.model import db
39
39
40
40
41 log = logging.getLogger(__name__)
41 log = logging.getLogger(__name__)
@@ -87,7 +87,7 b' class SimpleGit(BaseVCSController):'
87 parsed_request.service == 'git-upload-pack'
87 parsed_request.service == 'git-upload-pack'
88 ):
88 ):
89 baseui = make_ui()
89 baseui = make_ui()
90 repo = Repository.get_by_repo_name(parsed_request.repo_name)
90 repo = db.Repository.get_by_repo_name(parsed_request.repo_name)
91 scm_repo = repo.scm_instance
91 scm_repo = repo.scm_instance
92 # Run hooks, like Mercurial outgoing.pull_logger does
92 # Run hooks, like Mercurial outgoing.pull_logger does
93 log_pull_action(ui=baseui, repo=scm_repo._repo)
93 log_pull_action(ui=baseui, repo=scm_repo._repo)
@@ -41,7 +41,7 b' from kallithea.lib.base import BaseContr'
41 from kallithea.lib.indexers import JOURNAL_SCHEMA
41 from kallithea.lib.indexers import JOURNAL_SCHEMA
42 from kallithea.lib.page import Page
42 from kallithea.lib.page import Page
43 from kallithea.lib.utils2 import remove_prefix, remove_suffix, safe_int
43 from kallithea.lib.utils2 import remove_prefix, remove_suffix, safe_int
44 from kallithea.model.db import UserLog
44 from kallithea.model import db
45
45
46
46
47 log = logging.getLogger(__name__)
47 log = logging.getLogger(__name__)
@@ -77,15 +77,15 b' def _journal_filter(user_log, search_ter'
77 def get_filterion(field, val, term):
77 def get_filterion(field, val, term):
78
78
79 if field == 'repository':
79 if field == 'repository':
80 field = getattr(UserLog, 'repository_name')
80 field = getattr(db.UserLog, 'repository_name')
81 elif field == 'ip':
81 elif field == 'ip':
82 field = getattr(UserLog, 'user_ip')
82 field = getattr(db.UserLog, 'user_ip')
83 elif field == 'date':
83 elif field == 'date':
84 field = getattr(UserLog, 'action_date')
84 field = getattr(db.UserLog, 'action_date')
85 elif field == 'username':
85 elif field == 'username':
86 field = getattr(UserLog, 'username')
86 field = getattr(db.UserLog, 'username')
87 else:
87 else:
88 field = getattr(UserLog, field)
88 field = getattr(db.UserLog, field)
89 log.debug('filter field: %s val=>%s', field, val)
89 log.debug('filter field: %s val=>%s', field, val)
90
90
91 # sql filtering
91 # sql filtering
@@ -126,15 +126,15 b' class AdminController(BaseController):'
126
126
127 @HasPermissionAnyDecorator('hg.admin')
127 @HasPermissionAnyDecorator('hg.admin')
128 def index(self):
128 def index(self):
129 users_log = UserLog.query() \
129 users_log = db.UserLog.query() \
130 .options(joinedload(UserLog.user)) \
130 .options(joinedload(db.UserLog.user)) \
131 .options(joinedload(UserLog.repository))
131 .options(joinedload(db.UserLog.repository))
132
132
133 # FILTERING
133 # FILTERING
134 c.search_term = request.GET.get('filter')
134 c.search_term = request.GET.get('filter')
135 users_log = _journal_filter(users_log, c.search_term)
135 users_log = _journal_filter(users_log, c.search_term)
136
136
137 users_log = users_log.order_by(UserLog.action_date.desc())
137 users_log = users_log.order_by(db.UserLog.action_date.desc())
138
138
139 p = safe_int(request.GET.get('page'), 1)
139 p = safe_int(request.GET.get('page'), 1)
140
140
@@ -36,9 +36,8 b' from kallithea.lib import auth_modules'
36 from kallithea.lib import helpers as h
36 from kallithea.lib import helpers as h
37 from kallithea.lib.auth import HasPermissionAnyDecorator, LoginRequired
37 from kallithea.lib.auth import HasPermissionAnyDecorator, LoginRequired
38 from kallithea.lib.base import BaseController, render
38 from kallithea.lib.base import BaseController, render
39 from kallithea.lib.webutils import url
39 from kallithea.lib.utils3 import url
40 from kallithea.model import meta
40 from kallithea.model import db, meta
41 from kallithea.model.db import Setting
42 from kallithea.model.forms import AuthSettingsForm
41 from kallithea.model.forms import AuthSettingsForm
43
42
44
43
@@ -77,7 +76,7 b' class AuthSettingsController(BaseControl'
77 if "default" in v:
76 if "default" in v:
78 c.defaults[fullname] = v["default"]
77 c.defaults[fullname] = v["default"]
79 # Current values will be the default on the form, if there are any
78 # Current values will be the default on the form, if there are any
80 setting = Setting.get_by_name(fullname)
79 setting = db.Setting.get_by_name(fullname)
81 if setting is not None:
80 if setting is not None:
82 c.defaults[fullname] = setting.app_settings_value
81 c.defaults[fullname] = setting.app_settings_value
83 if defaults:
82 if defaults:
@@ -131,7 +130,7 b' class AuthSettingsController(BaseControl'
131 # we want to store it comma separated inside our settings
130 # we want to store it comma separated inside our settings
132 v = ','.join(v)
131 v = ','.join(v)
133 log.debug("%s = %s", k, str(v))
132 log.debug("%s = %s", k, str(v))
134 setting = Setting.create_or_update(k, v)
133 setting = db.Setting.create_or_update(k, v)
135 meta.Session().commit()
134 meta.Session().commit()
136 h.flash(_('Auth settings updated successfully'),
135 h.flash(_('Auth settings updated successfully'),
137 category='success')
136 category='success')
@@ -37,9 +37,8 b' from webob.exc import HTTPFound'
37 from kallithea.lib import helpers as h
37 from kallithea.lib import helpers as h
38 from kallithea.lib.auth import HasPermissionAnyDecorator, LoginRequired
38 from kallithea.lib.auth import HasPermissionAnyDecorator, LoginRequired
39 from kallithea.lib.base import BaseController, render
39 from kallithea.lib.base import BaseController, render
40 from kallithea.lib.webutils import url
40 from kallithea.lib.utils3 import url
41 from kallithea.model import meta
41 from kallithea.model import db, meta
42 from kallithea.model.db import Setting
43 from kallithea.model.forms import DefaultsForm
42 from kallithea.model.forms import DefaultsForm
44
43
45
44
@@ -54,7 +53,7 b' class DefaultsController(BaseController)'
54 super(DefaultsController, self)._before(*args, **kwargs)
53 super(DefaultsController, self)._before(*args, **kwargs)
55
54
56 def index(self, format='html'):
55 def index(self, format='html'):
57 defaults = Setting.get_default_repo_settings()
56 defaults = db.Setting.get_default_repo_settings()
58
57
59 return htmlfill.render(
58 return htmlfill.render(
60 render('admin/defaults/defaults.html'),
59 render('admin/defaults/defaults.html'),
@@ -69,7 +68,7 b' class DefaultsController(BaseController)'
69 try:
68 try:
70 form_result = _form.to_python(dict(request.POST))
69 form_result = _form.to_python(dict(request.POST))
71 for k, v in form_result.items():
70 for k, v in form_result.items():
72 setting = Setting.create_or_update(k, v)
71 setting = db.Setting.create_or_update(k, v)
73 meta.Session().commit()
72 meta.Session().commit()
74 h.flash(_('Default settings updated successfully'),
73 h.flash(_('Default settings updated successfully'),
75 category='success')
74 category='success')
@@ -42,8 +42,7 b' from kallithea.lib.page import Page'
42 from kallithea.lib.utils2 import safe_int, safe_str, time_to_datetime
42 from kallithea.lib.utils2 import safe_int, safe_str, time_to_datetime
43 from kallithea.lib.vcs.exceptions import NodeNotChangedError, VCSError
43 from kallithea.lib.vcs.exceptions import NodeNotChangedError, VCSError
44 from kallithea.lib.webutils import url
44 from kallithea.lib.webutils import url
45 from kallithea.model import meta
45 from kallithea.model import db, meta
46 from kallithea.model.db import Gist
47 from kallithea.model.forms import GistForm
46 from kallithea.model.forms import GistForm
48 from kallithea.model.gist import GistModel
47 from kallithea.model.gist import GistModel
49
48
@@ -76,28 +75,28 b' class GistsController(BaseController):'
76 elif c.show_private:
75 elif c.show_private:
77 url_params['private'] = 1
76 url_params['private'] = 1
78
77
79 gists = Gist().query() \
78 gists = db.Gist().query() \
80 .filter_by(is_expired=False) \
79 .filter_by(is_expired=False) \
81 .order_by(Gist.created_on.desc())
80 .order_by(db.Gist.created_on.desc())
82
81
83 # MY private
82 # MY private
84 if c.show_private and not c.show_public:
83 if c.show_private and not c.show_public:
85 gists = gists.filter(Gist.gist_type == Gist.GIST_PRIVATE) \
84 gists = gists.filter(db.Gist.gist_type == db.Gist.GIST_PRIVATE) \
86 .filter(Gist.owner_id == request.authuser.user_id)
85 .filter(db.Gist.owner_id == request.authuser.user_id)
87 # MY public
86 # MY public
88 elif c.show_public and not c.show_private:
87 elif c.show_public and not c.show_private:
89 gists = gists.filter(Gist.gist_type == Gist.GIST_PUBLIC) \
88 gists = gists.filter(db.Gist.gist_type == db.Gist.GIST_PUBLIC) \
90 .filter(Gist.owner_id == request.authuser.user_id)
89 .filter(db.Gist.owner_id == request.authuser.user_id)
91
90
92 # MY public+private
91 # MY public+private
93 elif c.show_private and c.show_public:
92 elif c.show_private and c.show_public:
94 gists = gists.filter(or_(Gist.gist_type == Gist.GIST_PUBLIC,
93 gists = gists.filter(or_(db.Gist.gist_type == db.Gist.GIST_PUBLIC,
95 Gist.gist_type == Gist.GIST_PRIVATE)) \
94 db.Gist.gist_type == db.Gist.GIST_PRIVATE)) \
96 .filter(Gist.owner_id == request.authuser.user_id)
95 .filter(db.Gist.owner_id == request.authuser.user_id)
97
96
98 # default show ALL public gists
97 # default show ALL public gists
99 if not c.show_public and not c.show_private:
98 if not c.show_public and not c.show_private:
100 gists = gists.filter(Gist.gist_type == Gist.GIST_PUBLIC)
99 gists = gists.filter(db.Gist.gist_type == db.Gist.GIST_PUBLIC)
101
100
102 c.gists = gists
101 c.gists = gists
103 p = safe_int(request.GET.get('page'), 1)
102 p = safe_int(request.GET.get('page'), 1)
@@ -112,7 +111,7 b' class GistsController(BaseController):'
112 try:
111 try:
113 form_result = gist_form.to_python(dict(request.POST))
112 form_result = gist_form.to_python(dict(request.POST))
114 # TODO: multiple files support, from the form
113 # TODO: multiple files support, from the form
115 filename = form_result['filename'] or Gist.DEFAULT_FILENAME
114 filename = form_result['filename'] or db.Gist.DEFAULT_FILENAME
116 nodes = {
115 nodes = {
117 filename: {
116 filename: {
118 'content': form_result['content'],
117 'content': form_result['content'],
@@ -120,7 +119,7 b' class GistsController(BaseController):'
120 }
119 }
121 }
120 }
122 _public = form_result['public']
121 _public = form_result['public']
123 gist_type = Gist.GIST_PUBLIC if _public else Gist.GIST_PRIVATE
122 gist_type = db.Gist.GIST_PUBLIC if _public else db.Gist.GIST_PRIVATE
124 gist = GistModel().create(
123 gist = GistModel().create(
125 description=form_result['description'],
124 description=form_result['description'],
126 owner=request.authuser.user_id,
125 owner=request.authuser.user_id,
@@ -168,7 +167,7 b' class GistsController(BaseController):'
168
167
169 @LoginRequired(allow_default_user=True)
168 @LoginRequired(allow_default_user=True)
170 def show(self, gist_id, revision='tip', format='html', f_path=None):
169 def show(self, gist_id, revision='tip', format='html', f_path=None):
171 c.gist = Gist.get_or_404(gist_id)
170 c.gist = db.Gist.get_or_404(gist_id)
172
171
173 if c.gist.is_expired:
172 if c.gist.is_expired:
174 log.error('Gist expired at %s',
173 log.error('Gist expired at %s',
@@ -191,7 +190,7 b' class GistsController(BaseController):'
191
190
192 @LoginRequired()
191 @LoginRequired()
193 def edit(self, gist_id, format='html'):
192 def edit(self, gist_id, format='html'):
194 c.gist = Gist.get_or_404(gist_id)
193 c.gist = db.Gist.get_or_404(gist_id)
195
194
196 if c.gist.is_expired:
195 if c.gist.is_expired:
197 log.error('Gist expired at %s',
196 log.error('Gist expired at %s',
@@ -251,7 +250,7 b' class GistsController(BaseController):'
251 @LoginRequired()
250 @LoginRequired()
252 @jsonify
251 @jsonify
253 def check_revision(self, gist_id):
252 def check_revision(self, gist_id):
254 c.gist = Gist.get_or_404(gist_id)
253 c.gist = db.Gist.get_or_404(gist_id)
255 last_rev = c.gist.scm_instance.get_changeset()
254 last_rev = c.gist.scm_instance.get_changeset()
256 success = True
255 success = True
257 revision = request.POST.get('revision')
256 revision = request.POST.get('revision')
@@ -40,10 +40,9 b' from kallithea.lib import helpers as h'
40 from kallithea.lib.auth import AuthUser, LoginRequired
40 from kallithea.lib.auth import AuthUser, LoginRequired
41 from kallithea.lib.base import BaseController, IfSshEnabled, render
41 from kallithea.lib.base import BaseController, IfSshEnabled, render
42 from kallithea.lib.utils2 import generate_api_key, safe_int
42 from kallithea.lib.utils2 import generate_api_key, safe_int
43 from kallithea.lib.webutils import url
43 from kallithea.lib.utils3 import url
44 from kallithea.model import meta
44 from kallithea.model import db, meta
45 from kallithea.model.api_key import ApiKeyModel
45 from kallithea.model.api_key import ApiKeyModel
46 from kallithea.model.db import Repository, User, UserEmailMap, UserFollowing
47 from kallithea.model.forms import PasswordChangeForm, UserForm
46 from kallithea.model.forms import PasswordChangeForm, UserForm
48 from kallithea.model.repo import RepoModel
47 from kallithea.model.repo import RepoModel
49 from kallithea.model.ssh_key import SshKeyModel, SshKeyModelException
48 from kallithea.model.ssh_key import SshKeyModel, SshKeyModelException
@@ -60,7 +59,7 b' class MyAccountController(BaseController'
60 super(MyAccountController, self)._before(*args, **kwargs)
59 super(MyAccountController, self)._before(*args, **kwargs)
61
60
62 def __load_data(self):
61 def __load_data(self):
63 c.user = User.get(request.authuser.user_id)
62 c.user = db.User.get(request.authuser.user_id)
64 if c.user.is_default_user:
63 if c.user.is_default_user:
65 h.flash(_("You can't edit this user since it's"
64 h.flash(_("You can't edit this user since it's"
66 " crucial for entire application"), category='warning')
65 " crucial for entire application"), category='warning')
@@ -69,14 +68,14 b' class MyAccountController(BaseController'
69 def _load_my_repos_data(self, watched=False):
68 def _load_my_repos_data(self, watched=False):
70 if watched:
69 if watched:
71 admin = False
70 admin = False
72 repos_list = meta.Session().query(Repository) \
71 repos_list = meta.Session().query(db.Repository) \
73 .join(UserFollowing) \
72 .join(db.UserFollowing) \
74 .filter(UserFollowing.user_id ==
73 .filter(db.UserFollowing.user_id ==
75 request.authuser.user_id).all()
74 request.authuser.user_id).all()
76 else:
75 else:
77 admin = True
76 admin = True
78 repos_list = meta.Session().query(Repository) \
77 repos_list = meta.Session().query(db.Repository) \
79 .filter(Repository.owner_id ==
78 .filter(db.Repository.owner_id ==
80 request.authuser.user_id).all()
79 request.authuser.user_id).all()
81
80
82 return RepoModel().get_repos_as_dict(repos_list, admin=admin)
81 return RepoModel().get_repos_as_dict(repos_list, admin=admin)
@@ -86,7 +85,7 b' class MyAccountController(BaseController'
86 self.__load_data()
85 self.__load_data()
87 c.perm_user = AuthUser(user_id=request.authuser.user_id)
86 c.perm_user = AuthUser(user_id=request.authuser.user_id)
88 managed_fields = auth_modules.get_managed_fields(c.user)
87 managed_fields = auth_modules.get_managed_fields(c.user)
89 def_user_perms = AuthUser(dbuser=User.get_default_user()).global_permissions
88 def_user_perms = AuthUser(dbuser=db.User.get_default_user()).global_permissions
90 if 'hg.register.none' in def_user_perms:
89 if 'hg.register.none' in def_user_perms:
91 managed_fields.extend(['username', 'firstname', 'lastname', 'email'])
90 managed_fields.extend(['username', 'firstname', 'lastname', 'email'])
92
91
@@ -191,8 +190,8 b' class MyAccountController(BaseController'
191 c.active = 'emails'
190 c.active = 'emails'
192 self.__load_data()
191 self.__load_data()
193
192
194 c.user_email_map = UserEmailMap.query() \
193 c.user_email_map = db.UserEmailMap.query() \
195 .filter(UserEmailMap.user == c.user).all()
194 .filter(db.UserEmailMap.user == c.user).all()
196 return render('admin/my_account/my_account.html')
195 return render('admin/my_account/my_account.html')
197
196
198 def my_account_emails_add(self):
197 def my_account_emails_add(self):
@@ -246,7 +245,7 b' class MyAccountController(BaseController'
246 def my_account_api_keys_delete(self):
245 def my_account_api_keys_delete(self):
247 api_key = request.POST.get('del_api_key')
246 api_key = request.POST.get('del_api_key')
248 if request.POST.get('del_api_key_builtin'):
247 if request.POST.get('del_api_key_builtin'):
249 user = User.get(request.authuser.user_id)
248 user = db.User.get(request.authuser.user_id)
250 user.api_key = generate_api_key()
249 user.api_key = generate_api_key()
251 meta.Session().commit()
250 meta.Session().commit()
252 h.flash(_("API key successfully reset"), category='success')
251 h.flash(_("API key successfully reset"), category='success')
@@ -39,9 +39,8 b' from webob.exc import HTTPFound'
39 from kallithea.lib import helpers as h
39 from kallithea.lib import helpers as h
40 from kallithea.lib.auth import AuthUser, HasPermissionAnyDecorator, LoginRequired
40 from kallithea.lib.auth import AuthUser, HasPermissionAnyDecorator, LoginRequired
41 from kallithea.lib.base import BaseController, render
41 from kallithea.lib.base import BaseController, render
42 from kallithea.lib.webutils import url
42 from kallithea.lib.utils3 import url
43 from kallithea.model import meta
43 from kallithea.model import db, meta
44 from kallithea.model.db import User, UserIpMap
45 from kallithea.model.forms import DefaultPermissionsForm
44 from kallithea.model.forms import DefaultPermissionsForm
46 from kallithea.model.permission import PermissionModel
45 from kallithea.model.permission import PermissionModel
47
46
@@ -134,7 +133,7 b' class PermissionsController(BaseControll'
134
133
135 raise HTTPFound(location=url('admin_permissions'))
134 raise HTTPFound(location=url('admin_permissions'))
136
135
137 c.user = User.get_default_user()
136 c.user = db.User.get_default_user()
138 defaults = {'anonymous': c.user.active}
137 defaults = {'anonymous': c.user.active}
139
138
140 for p in c.user.user_perms:
139 for p in c.user.user_perms:
@@ -170,14 +169,14 b' class PermissionsController(BaseControll'
170
169
171 def permission_ips(self):
170 def permission_ips(self):
172 c.active = 'ips'
171 c.active = 'ips'
173 c.user = User.get_default_user()
172 c.user = db.User.get_default_user()
174 c.user_ip_map = UserIpMap.query() \
173 c.user_ip_map = db.UserIpMap.query() \
175 .filter(UserIpMap.user == c.user).all()
174 .filter(db.UserIpMap.user == c.user).all()
176
175
177 return render('admin/permissions/permissions.html')
176 return render('admin/permissions/permissions.html')
178
177
179 def permission_perms(self):
178 def permission_perms(self):
180 c.active = 'perms'
179 c.active = 'perms'
181 c.user = User.get_default_user()
180 c.user = db.User.get_default_user()
182 c.perm_user = AuthUser(dbuser=c.user)
181 c.perm_user = AuthUser(dbuser=c.user)
183 return render('admin/permissions/permissions.html')
182 return render('admin/permissions/permissions.html')
@@ -40,9 +40,8 b' from kallithea.lib import helpers as h'
40 from kallithea.lib.auth import HasPermissionAny, HasRepoGroupPermissionLevel, HasRepoGroupPermissionLevelDecorator, LoginRequired
40 from kallithea.lib.auth import HasPermissionAny, HasRepoGroupPermissionLevel, HasRepoGroupPermissionLevelDecorator, LoginRequired
41 from kallithea.lib.base import BaseController, render
41 from kallithea.lib.base import BaseController, render
42 from kallithea.lib.utils2 import safe_int
42 from kallithea.lib.utils2 import safe_int
43 from kallithea.lib.webutils import url
43 from kallithea.lib.utils3 import url
44 from kallithea.model import meta
44 from kallithea.model import db, meta
45 from kallithea.model.db import RepoGroup, Repository
46 from kallithea.model.forms import RepoGroupForm, RepoGroupPermsForm
45 from kallithea.model.forms import RepoGroupForm, RepoGroupPermsForm
47 from kallithea.model.repo import RepoModel
46 from kallithea.model.repo import RepoModel
48 from kallithea.model.repo_group import RepoGroupModel
47 from kallithea.model.repo_group import RepoGroupModel
@@ -74,7 +73,7 b' class RepoGroupsController(BaseControlle'
74
73
75 :param group_id:
74 :param group_id:
76 """
75 """
77 repo_group = RepoGroup.get_or_404(group_id)
76 repo_group = db.RepoGroup.get_or_404(group_id)
78 data = repo_group.get_dict()
77 data = repo_group.get_dict()
79 data['group_name'] = repo_group.name
78 data['group_name'] = repo_group.name
80
79
@@ -98,7 +97,7 b' class RepoGroupsController(BaseControlle'
98 return False
97 return False
99
98
100 def index(self, format='html'):
99 def index(self, format='html'):
101 _list = RepoGroup.query(sorted=True).all()
100 _list = db.RepoGroup.query(sorted=True).all()
102 group_iter = RepoGroupList(_list, perm_level='admin')
101 group_iter = RepoGroupList(_list, perm_level='admin')
103 repo_groups_data = []
102 repo_groups_data = []
104 _tmpl_lookup = app_globals.mako_lookup
103 _tmpl_lookup = app_globals.mako_lookup
@@ -181,7 +180,7 b' class RepoGroupsController(BaseControlle'
181 # we pass in parent group into creation form, thus we know
180 # we pass in parent group into creation form, thus we know
182 # what would be the group, we can check perms here !
181 # what would be the group, we can check perms here !
183 group_id = safe_int(request.GET.get('parent_group'))
182 group_id = safe_int(request.GET.get('parent_group'))
184 group = RepoGroup.get(group_id) if group_id else None
183 group = db.RepoGroup.get(group_id) if group_id else None
185 group_name = group.group_name if group else None
184 group_name = group.group_name if group else None
186 if HasRepoGroupPermissionLevel('admin')(group_name, 'group create'):
185 if HasRepoGroupPermissionLevel('admin')(group_name, 'group create'):
187 pass
186 pass
@@ -193,7 +192,7 b' class RepoGroupsController(BaseControlle'
193
192
194 @HasRepoGroupPermissionLevelDecorator('admin')
193 @HasRepoGroupPermissionLevelDecorator('admin')
195 def update(self, group_name):
194 def update(self, group_name):
196 c.repo_group = RepoGroup.guess_instance(group_name)
195 c.repo_group = db.RepoGroup.guess_instance(group_name)
197 self.__load_defaults(extras=[c.repo_group.parent_group],
196 self.__load_defaults(extras=[c.repo_group.parent_group],
198 exclude=[c.repo_group])
197 exclude=[c.repo_group])
199
198
@@ -239,7 +238,7 b' class RepoGroupsController(BaseControlle'
239
238
240 @HasRepoGroupPermissionLevelDecorator('admin')
239 @HasRepoGroupPermissionLevelDecorator('admin')
241 def delete(self, group_name):
240 def delete(self, group_name):
242 gr = c.repo_group = RepoGroup.guess_instance(group_name)
241 gr = c.repo_group = db.RepoGroup.guess_instance(group_name)
243 repos = gr.repositories.all()
242 repos = gr.repositories.all()
244 if repos:
243 if repos:
245 h.flash(_('This group contains %s repositories and cannot be '
244 h.flash(_('This group contains %s repositories and cannot be '
@@ -273,7 +272,7 b' class RepoGroupsController(BaseControlle'
273 the group by id view instead
272 the group by id view instead
274 """
273 """
275 group_name = group_name.rstrip('/')
274 group_name = group_name.rstrip('/')
276 id_ = RepoGroup.get_by_group_name(group_name)
275 id_ = db.RepoGroup.get_by_group_name(group_name)
277 if id_:
276 if id_:
278 return self.show(group_name)
277 return self.show(group_name)
279 raise HTTPNotFound
278 raise HTTPNotFound
@@ -282,12 +281,12 b' class RepoGroupsController(BaseControlle'
282 def show(self, group_name):
281 def show(self, group_name):
283 c.active = 'settings'
282 c.active = 'settings'
284
283
285 c.group = c.repo_group = RepoGroup.guess_instance(group_name)
284 c.group = c.repo_group = db.RepoGroup.guess_instance(group_name)
286
285
287 groups = RepoGroup.query(sorted=True).filter_by(parent_group=c.group).all()
286 groups = db.RepoGroup.query(sorted=True).filter_by(parent_group=c.group).all()
288 repo_groups_list = self.scm_model.get_repo_groups(groups)
287 repo_groups_list = self.scm_model.get_repo_groups(groups)
289
288
290 repos_list = Repository.query(sorted=True).filter_by(group=c.group).all()
289 repos_list = db.Repository.query(sorted=True).filter_by(group=c.group).all()
291 c.data = RepoModel().get_repos_as_dict(repos_list,
290 c.data = RepoModel().get_repos_as_dict(repos_list,
292 repo_groups_list=repo_groups_list,
291 repo_groups_list=repo_groups_list,
293 short_name=True)
292 short_name=True)
@@ -298,7 +297,7 b' class RepoGroupsController(BaseControlle'
298 def edit(self, group_name):
297 def edit(self, group_name):
299 c.active = 'settings'
298 c.active = 'settings'
300
299
301 c.repo_group = RepoGroup.guess_instance(group_name)
300 c.repo_group = db.RepoGroup.guess_instance(group_name)
302 self.__load_defaults(extras=[c.repo_group.parent_group],
301 self.__load_defaults(extras=[c.repo_group.parent_group],
303 exclude=[c.repo_group])
302 exclude=[c.repo_group])
304 defaults = self.__load_data(c.repo_group.group_id)
303 defaults = self.__load_data(c.repo_group.group_id)
@@ -313,14 +312,14 b' class RepoGroupsController(BaseControlle'
313 @HasRepoGroupPermissionLevelDecorator('admin')
312 @HasRepoGroupPermissionLevelDecorator('admin')
314 def edit_repo_group_advanced(self, group_name):
313 def edit_repo_group_advanced(self, group_name):
315 c.active = 'advanced'
314 c.active = 'advanced'
316 c.repo_group = RepoGroup.guess_instance(group_name)
315 c.repo_group = db.RepoGroup.guess_instance(group_name)
317
316
318 return render('admin/repo_groups/repo_group_edit.html')
317 return render('admin/repo_groups/repo_group_edit.html')
319
318
320 @HasRepoGroupPermissionLevelDecorator('admin')
319 @HasRepoGroupPermissionLevelDecorator('admin')
321 def edit_repo_group_perms(self, group_name):
320 def edit_repo_group_perms(self, group_name):
322 c.active = 'perms'
321 c.active = 'perms'
323 c.repo_group = RepoGroup.guess_instance(group_name)
322 c.repo_group = db.RepoGroup.guess_instance(group_name)
324 self.__load_defaults()
323 self.__load_defaults()
325 defaults = self.__load_data(c.repo_group.group_id)
324 defaults = self.__load_data(c.repo_group.group_id)
326
325
@@ -339,7 +338,7 b' class RepoGroupsController(BaseControlle'
339 :param group_name:
338 :param group_name:
340 """
339 """
341
340
342 c.repo_group = RepoGroup.guess_instance(group_name)
341 c.repo_group = db.RepoGroup.guess_instance(group_name)
343 valid_recursive_choices = ['none', 'repos', 'groups', 'all']
342 valid_recursive_choices = ['none', 'repos', 'groups', 'all']
344 form_result = RepoGroupPermsForm(valid_recursive_choices)().to_python(request.POST)
343 form_result = RepoGroupPermsForm(valid_recursive_choices)().to_python(request.POST)
345 if not request.authuser.is_admin:
344 if not request.authuser.is_admin:
@@ -45,8 +45,7 b' from kallithea.lib.utils import action_l'
45 from kallithea.lib.utils2 import safe_int
45 from kallithea.lib.utils2 import safe_int
46 from kallithea.lib.vcs import RepositoryError
46 from kallithea.lib.vcs import RepositoryError
47 from kallithea.lib.webutils import url
47 from kallithea.lib.webutils import url
48 from kallithea.model import meta
48 from kallithea.model import db, meta
49 from kallithea.model.db import RepoGroup, Repository, RepositoryField, Setting, UserFollowing
50 from kallithea.model.forms import RepoFieldForm, RepoForm, RepoPermsForm
49 from kallithea.model.forms import RepoFieldForm, RepoForm, RepoPermsForm
51 from kallithea.model.repo import RepoModel
50 from kallithea.model.repo import RepoModel
52 from kallithea.model.scm import AvailableRepoGroupChoices, RepoList, ScmModel
51 from kallithea.model.scm import AvailableRepoGroupChoices, RepoList, ScmModel
@@ -91,7 +90,7 b' class ReposController(BaseRepoController'
91 return defaults
90 return defaults
92
91
93 def index(self, format='html'):
92 def index(self, format='html'):
94 repos_list = RepoList(Repository.query(sorted=True).all(), perm_level='admin')
93 repos_list = RepoList(db.Repository.query(sorted=True).all(), perm_level='admin')
95 # the repo list will be filtered to only show repos where the user has read permissions
94 # the repo list will be filtered to only show repos where the user has read permissions
96 repos_data = RepoModel().get_repos_as_dict(repos_list, admin=True)
95 repos_data = RepoModel().get_repos_as_dict(repos_list, admin=True)
97 # data used to render the grid
96 # data used to render the grid
@@ -141,9 +140,9 b' class ReposController(BaseRepoController'
141 parent_group = request.GET.get('parent_group')
140 parent_group = request.GET.get('parent_group')
142
141
143 ## apply the defaults from defaults page
142 ## apply the defaults from defaults page
144 defaults = Setting.get_default_repo_settings(strip_prefix=True)
143 defaults = db.Setting.get_default_repo_settings(strip_prefix=True)
145 if parent_group:
144 if parent_group:
146 prg = RepoGroup.get(parent_group)
145 prg = db.RepoGroup.get(parent_group)
147 if prg is None or not any(rgc[0] == prg.group_id
146 if prg is None or not any(rgc[0] == prg.group_id
148 for rgc in c.repo_groups):
147 for rgc in c.repo_groups):
149 raise HTTPForbidden
148 raise HTTPForbidden
@@ -177,8 +176,8 b' class ReposController(BaseRepoController'
177 if task_result.failed():
176 if task_result.failed():
178 raise HTTPInternalServerError(task_result.traceback)
177 raise HTTPInternalServerError(task_result.traceback)
179
178
180 repo = Repository.get_by_repo_name(repo_name)
179 repo = db.Repository.get_by_repo_name(repo_name)
181 if repo and repo.repo_state == Repository.STATE_CREATED:
180 if repo and repo.repo_state == db.Repository.STATE_CREATED:
182 if repo.clone_uri:
181 if repo.clone_uri:
183 h.flash(_('Created repository %s from %s')
182 h.flash(_('Created repository %s from %s')
184 % (repo.repo_name, repo.clone_uri_hidden), category='success')
183 % (repo.repo_name, repo.clone_uri_hidden), category='success')
@@ -202,12 +201,12 b' class ReposController(BaseRepoController'
202 c.repo_info = self._load_repo()
201 c.repo_info = self._load_repo()
203 self.__load_defaults(c.repo_info)
202 self.__load_defaults(c.repo_info)
204 c.active = 'settings'
203 c.active = 'settings'
205 c.repo_fields = RepositoryField.query() \
204 c.repo_fields = db.RepositoryField.query() \
206 .filter(RepositoryField.repository == c.repo_info).all()
205 .filter(db.RepositoryField.repository == c.repo_info).all()
207
206
208 repo_model = RepoModel()
207 repo_model = RepoModel()
209 changed_name = repo_name
208 changed_name = repo_name
210 repo = Repository.get_by_repo_name(repo_name)
209 repo = db.Repository.get_by_repo_name(repo_name)
211 old_data = {
210 old_data = {
212 'repo_name': repo_name,
211 'repo_name': repo_name,
213 'repo_group': repo.group.get_dict() if repo.group else {},
212 'repo_group': repo.group.get_dict() if repo.group else {},
@@ -285,8 +284,8 b' class ReposController(BaseRepoController'
285 @HasRepoPermissionLevelDecorator('admin')
284 @HasRepoPermissionLevelDecorator('admin')
286 def edit(self, repo_name):
285 def edit(self, repo_name):
287 defaults = self.__load_data()
286 defaults = self.__load_data()
288 c.repo_fields = RepositoryField.query() \
287 c.repo_fields = db.RepositoryField.query() \
289 .filter(RepositoryField.repository == c.repo_info).all()
288 .filter(db.RepositoryField.repository == c.repo_info).all()
290 c.active = 'settings'
289 c.active = 'settings'
291 return htmlfill.render(
290 return htmlfill.render(
292 render('admin/repos/repo_edit.html'),
291 render('admin/repos/repo_edit.html'),
@@ -352,8 +351,8 b' class ReposController(BaseRepoController'
352 @HasRepoPermissionLevelDecorator('admin')
351 @HasRepoPermissionLevelDecorator('admin')
353 def edit_fields(self, repo_name):
352 def edit_fields(self, repo_name):
354 c.repo_info = self._load_repo()
353 c.repo_info = self._load_repo()
355 c.repo_fields = RepositoryField.query() \
354 c.repo_fields = db.RepositoryField.query() \
356 .filter(RepositoryField.repository == c.repo_info).all()
355 .filter(db.RepositoryField.repository == c.repo_info).all()
357 c.active = 'fields'
356 c.active = 'fields'
358 if request.POST:
357 if request.POST:
359
358
@@ -364,8 +363,8 b' class ReposController(BaseRepoController'
364 def create_repo_field(self, repo_name):
363 def create_repo_field(self, repo_name):
365 try:
364 try:
366 form_result = RepoFieldForm()().to_python(dict(request.POST))
365 form_result = RepoFieldForm()().to_python(dict(request.POST))
367 new_field = RepositoryField()
366 new_field = db.RepositoryField()
368 new_field.repository = Repository.get_by_repo_name(repo_name)
367 new_field.repository = db.Repository.get_by_repo_name(repo_name)
369 new_field.field_key = form_result['new_field_key']
368 new_field.field_key = form_result['new_field_key']
370 new_field.field_type = form_result['new_field_type'] # python type
369 new_field.field_type = form_result['new_field_type'] # python type
371 new_field.field_value = form_result['new_field_value'] # set initial blank value
370 new_field.field_value = form_result['new_field_value'] # set initial blank value
@@ -382,7 +381,7 b' class ReposController(BaseRepoController'
382
381
383 @HasRepoPermissionLevelDecorator('admin')
382 @HasRepoPermissionLevelDecorator('admin')
384 def delete_repo_field(self, repo_name, field_id):
383 def delete_repo_field(self, repo_name, field_id):
385 field = RepositoryField.get_or_404(field_id)
384 field = db.RepositoryField.get_or_404(field_id)
386 try:
385 try:
387 meta.Session().delete(field)
386 meta.Session().delete(field)
388 meta.Session().commit()
387 meta.Session().commit()
@@ -396,11 +395,11 b' class ReposController(BaseRepoController'
396 def edit_advanced(self, repo_name):
395 def edit_advanced(self, repo_name):
397 c.repo_info = self._load_repo()
396 c.repo_info = self._load_repo()
398 c.default_user_id = kallithea.DEFAULT_USER_ID
397 c.default_user_id = kallithea.DEFAULT_USER_ID
399 c.in_public_journal = UserFollowing.query() \
398 c.in_public_journal = db.UserFollowing.query() \
400 .filter(UserFollowing.user_id == c.default_user_id) \
399 .filter(db.UserFollowing.user_id == c.default_user_id) \
401 .filter(UserFollowing.follows_repository == c.repo_info).scalar()
400 .filter(db.UserFollowing.follows_repository == c.repo_info).scalar()
402
401
403 _repos = Repository.query(sorted=True).all()
402 _repos = db.Repository.query(sorted=True).all()
404 read_access_repos = RepoList(_repos, perm_level='read')
403 read_access_repos = RepoList(_repos, perm_level='read')
405 c.repos_list = [(None, _('-- Not a fork --'))]
404 c.repos_list = [(None, _('-- Not a fork --'))]
406 c.repos_list += [(x.repo_id, x.repo_name)
405 c.repos_list += [(x.repo_id, x.repo_name)
@@ -431,7 +430,7 b' class ReposController(BaseRepoController'
431 """
430 """
432
431
433 try:
432 try:
434 repo_id = Repository.get_by_repo_name(repo_name).repo_id
433 repo_id = db.Repository.get_by_repo_name(repo_name).repo_id
435 user_id = kallithea.DEFAULT_USER_ID
434 user_id = kallithea.DEFAULT_USER_ID
436 self.scm_model.toggle_following_repo(repo_id, user_id)
435 self.scm_model.toggle_following_repo(repo_id, user_id)
437 h.flash(_('Updated repository visibility in public journal'),
436 h.flash(_('Updated repository visibility in public journal'),
@@ -43,8 +43,7 b' from kallithea.lib.utils import repo2db_'
43 from kallithea.lib.utils2 import safe_str
43 from kallithea.lib.utils2 import safe_str
44 from kallithea.lib.vcs import VCSError
44 from kallithea.lib.vcs import VCSError
45 from kallithea.lib.webutils import url
45 from kallithea.lib.webutils import url
46 from kallithea.model import meta
46 from kallithea.model import db, meta
47 from kallithea.model.db import Repository, Setting, Ui
48 from kallithea.model.forms import ApplicationSettingsForm, ApplicationUiSettingsForm, ApplicationVisualisationForm
47 from kallithea.model.forms import ApplicationSettingsForm, ApplicationUiSettingsForm, ApplicationVisualisationForm
49 from kallithea.model.notification import EmailNotificationModel
48 from kallithea.model.notification import EmailNotificationModel
50 from kallithea.model.scm import ScmModel
49 from kallithea.model.scm import ScmModel
@@ -60,7 +59,7 b' class SettingsController(BaseController)'
60 super(SettingsController, self)._before(*args, **kwargs)
59 super(SettingsController, self)._before(*args, **kwargs)
61
60
62 def _get_hg_ui_settings(self):
61 def _get_hg_ui_settings(self):
63 ret = Ui.query().all()
62 ret = db.Ui.query().all()
64
63
65 settings = {}
64 settings = {}
66 for each in ret:
65 for each in ret:
@@ -95,21 +94,21 b' class SettingsController(BaseController)'
95
94
96 try:
95 try:
97 if c.visual.allow_repo_location_change:
96 if c.visual.allow_repo_location_change:
98 sett = Ui.get_by_key('paths', '/')
97 sett = db.Ui.get_by_key('paths', '/')
99 sett.ui_value = form_result['paths_root_path']
98 sett.ui_value = form_result['paths_root_path']
100
99
101 # HOOKS
100 # HOOKS
102 sett = Ui.get_by_key('hooks', Ui.HOOK_UPDATE)
101 sett = db.Ui.get_by_key('hooks', db.Ui.HOOK_UPDATE)
103 sett.ui_active = form_result['hooks_changegroup_update']
102 sett.ui_active = form_result['hooks_changegroup_update']
104
103
105 sett = Ui.get_by_key('hooks', Ui.HOOK_REPO_SIZE)
104 sett = db.Ui.get_by_key('hooks', db.Ui.HOOK_REPO_SIZE)
106 sett.ui_active = form_result['hooks_changegroup_repo_size']
105 sett.ui_active = form_result['hooks_changegroup_repo_size']
107
106
108 ## EXTENSIONS
107 ## EXTENSIONS
109 sett = Ui.get_or_create('extensions', 'largefiles')
108 sett = db.Ui.get_or_create('extensions', 'largefiles')
110 sett.ui_active = form_result['extensions_largefiles']
109 sett.ui_active = form_result['extensions_largefiles']
111
110
112 # sett = Ui.get_or_create('extensions', 'hggit')
111 # sett = db.Ui.get_or_create('extensions', 'hggit')
113 # sett.ui_active = form_result['extensions_hggit']
112 # sett.ui_active = form_result['extensions_hggit']
114
113
115 meta.Session().commit()
114 meta.Session().commit()
@@ -121,7 +120,7 b' class SettingsController(BaseController)'
121 h.flash(_('Error occurred while updating '
120 h.flash(_('Error occurred while updating '
122 'application settings'), category='error')
121 'application settings'), category='error')
123
122
124 defaults = Setting.get_app_settings()
123 defaults = db.Setting.get_app_settings()
125 defaults.update(self._get_hg_ui_settings())
124 defaults.update(self._get_hg_ui_settings())
126
125
127 return htmlfill.render(
126 return htmlfill.render(
@@ -159,7 +158,7 b' class SettingsController(BaseController)'
159 if invalidate_cache:
158 if invalidate_cache:
160 log.debug('invalidating all repositories cache')
159 log.debug('invalidating all repositories cache')
161 i = 0
160 i = 0
162 for repo in Repository.query():
161 for repo in db.Repository.query():
163 try:
162 try:
164 ScmModel().mark_for_invalidation(repo.repo_name)
163 ScmModel().mark_for_invalidation(repo.repo_name)
165 i += 1
164 i += 1
@@ -169,7 +168,7 b' class SettingsController(BaseController)'
169
168
170 raise HTTPFound(location=url('admin_settings_mapping'))
169 raise HTTPFound(location=url('admin_settings_mapping'))
171
170
172 defaults = Setting.get_app_settings()
171 defaults = db.Setting.get_app_settings()
173 defaults.update(self._get_hg_ui_settings())
172 defaults.update(self._get_hg_ui_settings())
174
173
175 return htmlfill.render(
174 return htmlfill.render(
@@ -202,7 +201,7 b' class SettingsController(BaseController)'
202 'captcha_public_key',
201 'captcha_public_key',
203 'captcha_private_key',
202 'captcha_private_key',
204 ):
203 ):
205 Setting.create_or_update(setting, form_result[setting])
204 db.Setting.create_or_update(setting, form_result[setting])
206
205
207 meta.Session().commit()
206 meta.Session().commit()
208 set_app_settings(config)
207 set_app_settings(config)
@@ -216,7 +215,7 b' class SettingsController(BaseController)'
216
215
217 raise HTTPFound(location=url('admin_settings_global'))
216 raise HTTPFound(location=url('admin_settings_global'))
218
217
219 defaults = Setting.get_app_settings()
218 defaults = db.Setting.get_app_settings()
220 defaults.update(self._get_hg_ui_settings())
219 defaults.update(self._get_hg_ui_settings())
221
220
222 return htmlfill.render(
221 return htmlfill.render(
@@ -256,7 +255,7 b' class SettingsController(BaseController)'
256 ('clone_ssh_tmpl', 'clone_ssh_tmpl', 'unicode'),
255 ('clone_ssh_tmpl', 'clone_ssh_tmpl', 'unicode'),
257 ]
256 ]
258 for setting, form_key, type_ in settings:
257 for setting, form_key, type_ in settings:
259 Setting.create_or_update(setting, form_result[form_key], type_)
258 db.Setting.create_or_update(setting, form_result[form_key], type_)
260
259
261 meta.Session().commit()
260 meta.Session().commit()
262 set_app_settings(config)
261 set_app_settings(config)
@@ -271,7 +270,7 b' class SettingsController(BaseController)'
271
270
272 raise HTTPFound(location=url('admin_settings_visual'))
271 raise HTTPFound(location=url('admin_settings_visual'))
273
272
274 defaults = Setting.get_app_settings()
273 defaults = db.Setting.get_app_settings()
275 defaults.update(self._get_hg_ui_settings())
274 defaults.update(self._get_hg_ui_settings())
276
275
277 return htmlfill.render(
276 return htmlfill.render(
@@ -307,7 +306,7 b' class SettingsController(BaseController)'
307 h.flash(_('Send email task created'), category='success')
306 h.flash(_('Send email task created'), category='success')
308 raise HTTPFound(location=url('admin_settings_email'))
307 raise HTTPFound(location=url('admin_settings_email'))
309
308
310 defaults = Setting.get_app_settings()
309 defaults = db.Setting.get_app_settings()
311 defaults.update(self._get_hg_ui_settings())
310 defaults.update(self._get_hg_ui_settings())
312
311
313 import kallithea
312 import kallithea
@@ -331,15 +330,15 b' class SettingsController(BaseController)'
331
330
332 try:
331 try:
333 ui_key = ui_key and ui_key.strip()
332 ui_key = ui_key and ui_key.strip()
334 if ui_key in (x.ui_key for x in Ui.get_custom_hooks()):
333 if ui_key in (x.ui_key for x in db.Ui.get_custom_hooks()):
335 h.flash(_('Hook already exists'), category='error')
334 h.flash(_('Hook already exists'), category='error')
336 elif ui_key in (x.ui_key for x in Ui.get_builtin_hooks()):
335 elif ui_key in (x.ui_key for x in db.Ui.get_builtin_hooks()):
337 h.flash(_('Builtin hooks are read-only. Please use another hook name.'), category='error')
336 h.flash(_('Builtin hooks are read-only. Please use another hook name.'), category='error')
338 elif ui_value and ui_key:
337 elif ui_value and ui_key:
339 Ui.create_or_update_hook(ui_key, ui_value)
338 db.Ui.create_or_update_hook(ui_key, ui_value)
340 h.flash(_('Added new hook'), category='success')
339 h.flash(_('Added new hook'), category='success')
341 elif hook_id:
340 elif hook_id:
342 Ui.delete(hook_id)
341 db.Ui.delete(hook_id)
343 meta.Session().commit()
342 meta.Session().commit()
344
343
345 # check for edits
344 # check for edits
@@ -349,7 +348,7 b' class SettingsController(BaseController)'
349 _d.get('hook_ui_value_new', []),
348 _d.get('hook_ui_value_new', []),
350 _d.get('hook_ui_value', [])):
349 _d.get('hook_ui_value', [])):
351 if v != ov:
350 if v != ov:
352 Ui.create_or_update_hook(k, v)
351 db.Ui.create_or_update_hook(k, v)
353 update = True
352 update = True
354
353
355 if update:
354 if update:
@@ -362,11 +361,11 b' class SettingsController(BaseController)'
362
361
363 raise HTTPFound(location=url('admin_settings_hooks'))
362 raise HTTPFound(location=url('admin_settings_hooks'))
364
363
365 defaults = Setting.get_app_settings()
364 defaults = db.Setting.get_app_settings()
366 defaults.update(self._get_hg_ui_settings())
365 defaults.update(self._get_hg_ui_settings())
367
366
368 c.hooks = Ui.get_builtin_hooks()
367 c.hooks = db.Ui.get_builtin_hooks()
369 c.custom_hooks = Ui.get_custom_hooks()
368 c.custom_hooks = db.Ui.get_custom_hooks()
370
369
371 return htmlfill.render(
370 return htmlfill.render(
372 render('admin/settings/settings.html'),
371 render('admin/settings/settings.html'),
@@ -384,7 +383,7 b' class SettingsController(BaseController)'
384 h.flash(_('Whoosh reindex task scheduled'), category='success')
383 h.flash(_('Whoosh reindex task scheduled'), category='success')
385 raise HTTPFound(location=url('admin_settings_search'))
384 raise HTTPFound(location=url('admin_settings_search'))
386
385
387 defaults = Setting.get_app_settings()
386 defaults = db.Setting.get_app_settings()
388 defaults.update(self._get_hg_ui_settings())
387 defaults.update(self._get_hg_ui_settings())
389
388
390 return htmlfill.render(
389 return htmlfill.render(
@@ -397,12 +396,12 b' class SettingsController(BaseController)'
397 def settings_system(self):
396 def settings_system(self):
398 c.active = 'system'
397 c.active = 'system'
399
398
400 defaults = Setting.get_app_settings()
399 defaults = db.Setting.get_app_settings()
401 defaults.update(self._get_hg_ui_settings())
400 defaults.update(self._get_hg_ui_settings())
402
401
403 import kallithea
402 import kallithea
404 c.ini = kallithea.CONFIG
403 c.ini = kallithea.CONFIG
405 server_info = Setting.get_server_info()
404 server_info = db.Setting.get_server_info()
406 for key, val in server_info.items():
405 for key, val in server_info.items():
407 setattr(c, key, val)
406 setattr(c, key, val)
408
407
@@ -43,9 +43,8 b' from kallithea.lib.base import BaseContr'
43 from kallithea.lib.exceptions import RepoGroupAssignmentError, UserGroupsAssignedException
43 from kallithea.lib.exceptions import RepoGroupAssignmentError, UserGroupsAssignedException
44 from kallithea.lib.utils import action_logger
44 from kallithea.lib.utils import action_logger
45 from kallithea.lib.utils2 import safe_int, safe_str
45 from kallithea.lib.utils2 import safe_int, safe_str
46 from kallithea.lib.webutils import url
46 from kallithea.lib.utils3 import url
47 from kallithea.model import meta
47 from kallithea.model import db, meta
48 from kallithea.model.db import User, UserGroup, UserGroupRepoGroupToPerm, UserGroupRepoToPerm, UserGroupToPerm
49 from kallithea.model.forms import CustomDefaultPermissionsForm, UserGroupForm, UserGroupPermsForm
48 from kallithea.model.forms import CustomDefaultPermissionsForm, UserGroupForm, UserGroupPermsForm
50 from kallithea.model.scm import UserGroupList
49 from kallithea.model.scm import UserGroupList
51 from kallithea.model.user_group import UserGroupModel
50 from kallithea.model.user_group import UserGroupModel
@@ -66,7 +65,7 b' class UserGroupsController(BaseControlle'
66
65
67 c.group_members = [(x.user_id, x.username) for x in c.group_members_obj]
66 c.group_members = [(x.user_id, x.username) for x in c.group_members_obj]
68 c.available_members = sorted(((x.user_id, x.username) for x in
67 c.available_members = sorted(((x.user_id, x.username) for x in
69 User.query().all()),
68 db.User.query().all()),
70 key=lambda u: u[1].lower())
69 key=lambda u: u[1].lower())
71
70
72 def __load_defaults(self, user_group_id):
71 def __load_defaults(self, user_group_id):
@@ -75,13 +74,13 b' class UserGroupsController(BaseControlle'
75
74
76 :param user_group_id:
75 :param user_group_id:
77 """
76 """
78 user_group = UserGroup.get_or_404(user_group_id)
77 user_group = db.UserGroup.get_or_404(user_group_id)
79 data = user_group.get_dict()
78 data = user_group.get_dict()
80 return data
79 return data
81
80
82 def index(self, format='html'):
81 def index(self, format='html'):
83 _list = UserGroup.query() \
82 _list = db.UserGroup.query() \
84 .order_by(func.lower(UserGroup.users_group_name)) \
83 .order_by(func.lower(db.UserGroup.users_group_name)) \
85 .all()
84 .all()
86 group_iter = UserGroupList(_list, perm_level='admin')
85 group_iter = UserGroupList(_list, perm_level='admin')
87 user_groups_data = []
86 user_groups_data = []
@@ -154,7 +153,7 b' class UserGroupsController(BaseControlle'
154
153
155 @HasUserGroupPermissionLevelDecorator('admin')
154 @HasUserGroupPermissionLevelDecorator('admin')
156 def update(self, id):
155 def update(self, id):
157 c.user_group = UserGroup.get_or_404(id)
156 c.user_group = db.UserGroup.get_or_404(id)
158 c.active = 'settings'
157 c.active = 'settings'
159 self.__load_data(id)
158 self.__load_data(id)
160
159
@@ -200,7 +199,7 b' class UserGroupsController(BaseControlle'
200
199
201 @HasUserGroupPermissionLevelDecorator('admin')
200 @HasUserGroupPermissionLevelDecorator('admin')
202 def delete(self, id):
201 def delete(self, id):
203 usr_gr = UserGroup.get_or_404(id)
202 usr_gr = db.UserGroup.get_or_404(id)
204 try:
203 try:
205 UserGroupModel().delete(usr_gr)
204 UserGroupModel().delete(usr_gr)
206 meta.Session().commit()
205 meta.Session().commit()
@@ -215,7 +214,7 b' class UserGroupsController(BaseControlle'
215
214
216 @HasUserGroupPermissionLevelDecorator('admin')
215 @HasUserGroupPermissionLevelDecorator('admin')
217 def edit(self, id, format='html'):
216 def edit(self, id, format='html'):
218 c.user_group = UserGroup.get_or_404(id)
217 c.user_group = db.UserGroup.get_or_404(id)
219 c.active = 'settings'
218 c.active = 'settings'
220 self.__load_data(id)
219 self.__load_data(id)
221
220
@@ -230,7 +229,7 b' class UserGroupsController(BaseControlle'
230
229
231 @HasUserGroupPermissionLevelDecorator('admin')
230 @HasUserGroupPermissionLevelDecorator('admin')
232 def edit_perms(self, id):
231 def edit_perms(self, id):
233 c.user_group = UserGroup.get_or_404(id)
232 c.user_group = db.UserGroup.get_or_404(id)
234 c.active = 'perms'
233 c.active = 'perms'
235
234
236 defaults = {}
235 defaults = {}
@@ -257,7 +256,7 b' class UserGroupsController(BaseControlle'
257
256
258 :param id:
257 :param id:
259 """
258 """
260 user_group = UserGroup.get_or_404(id)
259 user_group = db.UserGroup.get_or_404(id)
261 form = UserGroupPermsForm()().to_python(request.POST)
260 form = UserGroupPermsForm()().to_python(request.POST)
262
261
263 # set the permissions !
262 # set the permissions !
@@ -304,27 +303,27 b' class UserGroupsController(BaseControlle'
304
303
305 @HasUserGroupPermissionLevelDecorator('admin')
304 @HasUserGroupPermissionLevelDecorator('admin')
306 def edit_default_perms(self, id):
305 def edit_default_perms(self, id):
307 c.user_group = UserGroup.get_or_404(id)
306 c.user_group = db.UserGroup.get_or_404(id)
308 c.active = 'default_perms'
307 c.active = 'default_perms'
309
308
310 permissions = {
309 permissions = {
311 'repositories': {},
310 'repositories': {},
312 'repositories_groups': {}
311 'repositories_groups': {}
313 }
312 }
314 ugroup_repo_perms = UserGroupRepoToPerm.query() \
313 ugroup_repo_perms = db.UserGroupRepoToPerm.query() \
315 .options(joinedload(UserGroupRepoToPerm.permission)) \
314 .options(joinedload(db.UserGroupRepoToPerm.permission)) \
316 .options(joinedload(UserGroupRepoToPerm.repository)) \
315 .options(joinedload(db.UserGroupRepoToPerm.repository)) \
317 .filter(UserGroupRepoToPerm.users_group_id == id) \
316 .filter(db.UserGroupRepoToPerm.users_group_id == id) \
318 .all()
317 .all()
319
318
320 for gr in ugroup_repo_perms:
319 for gr in ugroup_repo_perms:
321 permissions['repositories'][gr.repository.repo_name] \
320 permissions['repositories'][gr.repository.repo_name] \
322 = gr.permission.permission_name
321 = gr.permission.permission_name
323
322
324 ugroup_group_perms = UserGroupRepoGroupToPerm.query() \
323 ugroup_group_perms = db.UserGroupRepoGroupToPerm.query() \
325 .options(joinedload(UserGroupRepoGroupToPerm.permission)) \
324 .options(joinedload(db.UserGroupRepoGroupToPerm.permission)) \
326 .options(joinedload(UserGroupRepoGroupToPerm.group)) \
325 .options(joinedload(db.UserGroupRepoGroupToPerm.group)) \
327 .filter(UserGroupRepoGroupToPerm.users_group_id == id) \
326 .filter(db.UserGroupRepoGroupToPerm.users_group_id == id) \
328 .all()
327 .all()
329
328
330 for gr in ugroup_group_perms:
329 for gr in ugroup_group_perms:
@@ -353,7 +352,7 b' class UserGroupsController(BaseControlle'
353
352
354 @HasUserGroupPermissionLevelDecorator('admin')
353 @HasUserGroupPermissionLevelDecorator('admin')
355 def update_default_perms(self, id):
354 def update_default_perms(self, id):
356 user_group = UserGroup.get_or_404(id)
355 user_group = db.UserGroup.get_or_404(id)
357
356
358 try:
357 try:
359 form = CustomDefaultPermissionsForm()()
358 form = CustomDefaultPermissionsForm()()
@@ -361,8 +360,8 b' class UserGroupsController(BaseControlle'
361
360
362 usergroup_model = UserGroupModel()
361 usergroup_model = UserGroupModel()
363
362
364 defs = UserGroupToPerm.query() \
363 defs = db.UserGroupToPerm.query() \
365 .filter(UserGroupToPerm.users_group == user_group) \
364 .filter(db.UserGroupToPerm.users_group == user_group) \
366 .all()
365 .all()
367 for ug in defs:
366 for ug in defs:
368 meta.Session().delete(ug)
367 meta.Session().delete(ug)
@@ -391,7 +390,7 b' class UserGroupsController(BaseControlle'
391
390
392 @HasUserGroupPermissionLevelDecorator('admin')
391 @HasUserGroupPermissionLevelDecorator('admin')
393 def edit_advanced(self, id):
392 def edit_advanced(self, id):
394 c.user_group = UserGroup.get_or_404(id)
393 c.user_group = db.UserGroup.get_or_404(id)
395 c.active = 'advanced'
394 c.active = 'advanced'
396 c.group_members_obj = sorted((x.user for x in c.user_group.members),
395 c.group_members_obj = sorted((x.user for x in c.user_group.members),
397 key=lambda u: u.username.lower())
396 key=lambda u: u.username.lower())
@@ -399,7 +398,7 b' class UserGroupsController(BaseControlle'
399
398
400 @HasUserGroupPermissionLevelDecorator('admin')
399 @HasUserGroupPermissionLevelDecorator('admin')
401 def edit_members(self, id):
400 def edit_members(self, id):
402 c.user_group = UserGroup.get_or_404(id)
401 c.user_group = db.UserGroup.get_or_404(id)
403 c.active = 'members'
402 c.active = 'members'
404 c.group_members_obj = sorted((x.user for x in c.user_group.members),
403 c.group_members_obj = sorted((x.user for x in c.user_group.members),
405 key=lambda u: u.username.lower())
404 key=lambda u: u.username.lower())
@@ -44,10 +44,9 b' from kallithea.lib.base import BaseContr'
44 from kallithea.lib.exceptions import DefaultUserException, UserCreationError, UserOwnsReposException
44 from kallithea.lib.exceptions import DefaultUserException, UserCreationError, UserOwnsReposException
45 from kallithea.lib.utils import action_logger
45 from kallithea.lib.utils import action_logger
46 from kallithea.lib.utils2 import datetime_to_time, generate_api_key, safe_int
46 from kallithea.lib.utils2 import datetime_to_time, generate_api_key, safe_int
47 from kallithea.lib.webutils import url
47 from kallithea.lib.utils3 import url
48 from kallithea.model import meta
48 from kallithea.model import db, meta
49 from kallithea.model.api_key import ApiKeyModel
49 from kallithea.model.api_key import ApiKeyModel
50 from kallithea.model.db import User, UserEmailMap, UserIpMap, UserToPerm
51 from kallithea.model.forms import CustomDefaultPermissionsForm, UserForm
50 from kallithea.model.forms import CustomDefaultPermissionsForm, UserForm
52 from kallithea.model.ssh_key import SshKeyModel, SshKeyModelException
51 from kallithea.model.ssh_key import SshKeyModel, SshKeyModelException
53 from kallithea.model.user import UserModel
52 from kallithea.model.user import UserModel
@@ -64,9 +63,9 b' class UsersController(BaseController):'
64 super(UsersController, self)._before(*args, **kwargs)
63 super(UsersController, self)._before(*args, **kwargs)
65
64
66 def index(self, format='html'):
65 def index(self, format='html'):
67 c.users_list = User.query().order_by(User.username) \
66 c.users_list = db.User.query().order_by(db.User.username) \
68 .filter_by(is_default_user=False) \
67 .filter_by(is_default_user=False) \
69 .order_by(func.lower(User.username)) \
68 .order_by(func.lower(db.User.username)) \
70 .all()
69 .all()
71
70
72 users_data = []
71 users_data = []
@@ -108,7 +107,7 b' class UsersController(BaseController):'
108 return render('admin/users/users.html')
107 return render('admin/users/users.html')
109
108
110 def create(self):
109 def create(self):
111 c.default_extern_type = User.DEFAULT_AUTH_TYPE
110 c.default_extern_type = db.User.DEFAULT_AUTH_TYPE
112 c.default_extern_name = ''
111 c.default_extern_name = ''
113 user_model = UserModel()
112 user_model = UserModel()
114 user_form = UserForm()()
113 user_form = UserForm()()
@@ -137,7 +136,7 b' class UsersController(BaseController):'
137 raise HTTPFound(location=url('edit_user', id=user.user_id))
136 raise HTTPFound(location=url('edit_user', id=user.user_id))
138
137
139 def new(self, format='html'):
138 def new(self, format='html'):
140 c.default_extern_type = User.DEFAULT_AUTH_TYPE
139 c.default_extern_type = db.User.DEFAULT_AUTH_TYPE
141 c.default_extern_name = ''
140 c.default_extern_name = ''
142 return render('admin/users/user_add.html')
141 return render('admin/users/user_add.html')
143
142
@@ -180,7 +179,7 b' class UsersController(BaseController):'
180 raise HTTPFound(location=url('edit_user', id=id))
179 raise HTTPFound(location=url('edit_user', id=id))
181
180
182 def delete(self, id):
181 def delete(self, id):
183 usr = User.get_or_404(id)
182 usr = db.User.get_or_404(id)
184 has_ssh_keys = bool(usr.ssh_keys)
183 has_ssh_keys = bool(usr.ssh_keys)
185 try:
184 try:
186 UserModel().delete(usr)
185 UserModel().delete(usr)
@@ -199,7 +198,7 b' class UsersController(BaseController):'
199
198
200 def _get_user_or_raise_if_default(self, id):
199 def _get_user_or_raise_if_default(self, id):
201 try:
200 try:
202 return User.get_or_404(id, allow_default=False)
201 return db.User.get_or_404(id, allow_default=False)
203 except DefaultUserException:
202 except DefaultUserException:
204 h.flash(_("The default user cannot be edited"), category='warning')
203 h.flash(_("The default user cannot be edited"), category='warning')
205 raise HTTPNotFound
204 raise HTTPNotFound
@@ -318,8 +317,8 b' class UsersController(BaseController):'
318
317
319 user_model = UserModel()
318 user_model = UserModel()
320
319
321 defs = UserToPerm.query() \
320 defs = db.UserToPerm.query() \
322 .filter(UserToPerm.user == user) \
321 .filter(db.UserToPerm.user == user) \
323 .all()
322 .all()
324 for ug in defs:
323 for ug in defs:
325 meta.Session().delete(ug)
324 meta.Session().delete(ug)
@@ -347,8 +346,8 b' class UsersController(BaseController):'
347 def edit_emails(self, id):
346 def edit_emails(self, id):
348 c.user = self._get_user_or_raise_if_default(id)
347 c.user = self._get_user_or_raise_if_default(id)
349 c.active = 'emails'
348 c.active = 'emails'
350 c.user_email_map = UserEmailMap.query() \
349 c.user_email_map = db.UserEmailMap.query() \
351 .filter(UserEmailMap.user == c.user).all()
350 .filter(db.UserEmailMap.user == c.user).all()
352
351
353 defaults = c.user.get_dict()
352 defaults = c.user.get_dict()
354 return htmlfill.render(
353 return htmlfill.render(
@@ -387,11 +386,11 b' class UsersController(BaseController):'
387 def edit_ips(self, id):
386 def edit_ips(self, id):
388 c.user = self._get_user_or_raise_if_default(id)
387 c.user = self._get_user_or_raise_if_default(id)
389 c.active = 'ips'
388 c.active = 'ips'
390 c.user_ip_map = UserIpMap.query() \
389 c.user_ip_map = db.UserIpMap.query() \
391 .filter(UserIpMap.user == c.user).all()
390 .filter(db.UserIpMap.user == c.user).all()
392
391
393 c.default_user_ip_map = UserIpMap.query() \
392 c.default_user_ip_map = db.UserIpMap.query() \
394 .filter(UserIpMap.user_id == kallithea.DEFAULT_USER_ID).all()
393 .filter(db.UserIpMap.user_id == kallithea.DEFAULT_USER_ID).all()
395
394
396 defaults = c.user.get_dict()
395 defaults = c.user.get_dict()
397 return htmlfill.render(
396 return htmlfill.render(
@@ -40,7 +40,7 b' from kallithea.lib.auth import AuthUser'
40 from kallithea.lib.base import _get_ip_addr as _get_ip
40 from kallithea.lib.base import _get_ip_addr as _get_ip
41 from kallithea.lib.base import get_path_info
41 from kallithea.lib.base import get_path_info
42 from kallithea.lib.utils2 import ascii_bytes
42 from kallithea.lib.utils2 import ascii_bytes
43 from kallithea.model.db import User
43 from kallithea.model import db
44
44
45
45
46 log = logging.getLogger('JSONRPC')
46 log = logging.getLogger('JSONRPC')
@@ -145,7 +145,7 b' class JSONRPCController(TGController):'
145
145
146 # check if we can find this session using api_key
146 # check if we can find this session using api_key
147 try:
147 try:
148 u = User.get_by_api_key(self._req_api_key)
148 u = db.User.get_by_api_key(self._req_api_key)
149 auth_user = AuthUser.make(dbuser=u, ip_addr=ip_addr)
149 auth_user = AuthUser.make(dbuser=u, ip_addr=ip_addr)
150 if auth_user is None:
150 if auth_user is None:
151 raise JSONRPCErrorResponse(retid=self._req_id,
151 raise JSONRPCErrorResponse(retid=self._req_id,
@@ -38,10 +38,9 b' from kallithea.lib.exceptions import Def'
38 from kallithea.lib.utils import action_logger, repo2db_mapper
38 from kallithea.lib.utils import action_logger, repo2db_mapper
39 from kallithea.lib.vcs.backends.base import EmptyChangeset
39 from kallithea.lib.vcs.backends.base import EmptyChangeset
40 from kallithea.lib.vcs.exceptions import EmptyRepositoryError
40 from kallithea.lib.vcs.exceptions import EmptyRepositoryError
41 from kallithea.model import meta
41 from kallithea.model import db, meta
42 from kallithea.model.changeset_status import ChangesetStatusModel
42 from kallithea.model.changeset_status import ChangesetStatusModel
43 from kallithea.model.comment import ChangesetCommentsModel
43 from kallithea.model.comment import ChangesetCommentsModel
44 from kallithea.model.db import ChangesetStatus, Gist, Permission, PullRequest, RepoGroup, Repository, Setting, User, UserGroup, UserIpMap
45 from kallithea.model.gist import GistModel
44 from kallithea.model.gist import GistModel
46 from kallithea.model.pull_request import PullRequestModel
45 from kallithea.model.pull_request import PullRequestModel
47 from kallithea.model.repo import RepoModel
46 from kallithea.model.repo import RepoModel
@@ -93,7 +92,7 b' def get_repo_group_or_error(repogroupid)'
93
92
94 :param repogroupid:
93 :param repogroupid:
95 """
94 """
96 repo_group = RepoGroup.guess_instance(repogroupid)
95 repo_group = db.RepoGroup.guess_instance(repogroupid)
97 if repo_group is None:
96 if repo_group is None:
98 raise JSONRPCError(
97 raise JSONRPCError(
99 'repository group `%s` does not exist' % (repogroupid,))
98 'repository group `%s` does not exist' % (repogroupid,))
@@ -118,7 +117,7 b' def get_perm_or_error(permid, prefix=Non'
118
117
119 :param permid:
118 :param permid:
120 """
119 """
121 perm = Permission.get_by_key(permid)
120 perm = db.Permission.get_by_key(permid)
122 if perm is None:
121 if perm is None:
123 raise JSONRPCError('permission `%s` does not exist' % (permid,))
122 raise JSONRPCError('permission `%s` does not exist' % (permid,))
124 if prefix:
123 if prefix:
@@ -323,7 +322,7 b' class ApiController(JSONRPCController):'
323 if userid is None:
322 if userid is None:
324 userid = request.authuser.user_id
323 userid = request.authuser.user_id
325 user = get_user_or_error(userid)
324 user = get_user_or_error(userid)
326 ips = UserIpMap.query().filter(UserIpMap.user == user).all()
325 ips = db.UserIpMap.query().filter(db.UserIpMap.user == user).all()
327 return dict(
326 return dict(
328 server_ip_addr=request.ip_addr,
327 server_ip_addr=request.ip_addr,
329 user_ips=ips
328 user_ips=ips
@@ -349,7 +348,7 b' class ApiController(JSONRPCController):'
349 }
348 }
350 error : null
349 error : null
351 """
350 """
352 return Setting.get_server_info()
351 return db.Setting.get_server_info()
353
352
354 def get_user(self, userid=None):
353 def get_user(self, userid=None):
355 """
354 """
@@ -425,8 +424,8 b' class ApiController(JSONRPCController):'
425
424
426 return [
425 return [
427 user.get_api_data()
426 user.get_api_data()
428 for user in User.query()
427 for user in db.User.query()
429 .order_by(User.username)
428 .order_by(db.User.username)
430 .filter_by(is_default_user=False)
429 .filter_by(is_default_user=False)
431 ]
430 ]
432
431
@@ -434,7 +433,7 b' class ApiController(JSONRPCController):'
434 def create_user(self, username, email, password='',
433 def create_user(self, username, email, password='',
435 firstname='', lastname='',
434 firstname='', lastname='',
436 active=True, admin=False,
435 active=True, admin=False,
437 extern_type=User.DEFAULT_AUTH_TYPE,
436 extern_type=db.User.DEFAULT_AUTH_TYPE,
438 extern_name=''):
437 extern_name=''):
439 """
438 """
440 Creates new user. Returns new user object. This command can
439 Creates new user. Returns new user object. This command can
@@ -483,10 +482,10 b' class ApiController(JSONRPCController):'
483
482
484 """
483 """
485
484
486 if User.get_by_username(username):
485 if db.User.get_by_username(username):
487 raise JSONRPCError("user `%s` already exist" % (username,))
486 raise JSONRPCError("user `%s` already exist" % (username,))
488
487
489 if User.get_by_email(email):
488 if db.User.get_by_email(email):
490 raise JSONRPCError("email `%s` already exist" % (email,))
489 raise JSONRPCError("email `%s` already exist" % (email,))
491
490
492 try:
491 try:
@@ -681,7 +680,7 b' class ApiController(JSONRPCController):'
681
680
682 return [
681 return [
683 user_group.get_api_data()
682 user_group.get_api_data()
684 for user_group in UserGroupList(UserGroup.query().all(), perm_level='read')
683 for user_group in UserGroupList(db.UserGroup.query().all(), perm_level='read')
685 ]
684 ]
686
685
687 @HasPermissionAnyDecorator('hg.admin', 'hg.usergroup.create.true')
686 @HasPermissionAnyDecorator('hg.admin', 'hg.usergroup.create.true')
@@ -1100,7 +1099,7 b' class ApiController(JSONRPCController):'
1100 if not HasPermissionAny('hg.admin')():
1099 if not HasPermissionAny('hg.admin')():
1101 repos = RepoModel().get_all_user_repos(user=request.authuser.user_id)
1100 repos = RepoModel().get_all_user_repos(user=request.authuser.user_id)
1102 else:
1101 else:
1103 repos = Repository.query()
1102 repos = db.Repository.query()
1104
1103
1105 return [
1104 return [
1106 repo.get_api_data()
1105 repo.get_api_data()
@@ -1235,7 +1234,7 b' class ApiController(JSONRPCController):'
1235 if RepoModel().get_by_repo_name(repo_name):
1234 if RepoModel().get_by_repo_name(repo_name):
1236 raise JSONRPCError("repo `%s` already exist" % repo_name)
1235 raise JSONRPCError("repo `%s` already exist" % repo_name)
1237
1236
1238 defs = Setting.get_default_repo_settings(strip_prefix=True)
1237 defs = db.Setting.get_default_repo_settings(strip_prefix=True)
1239 if private is None:
1238 if private is None:
1240 private = defs.get('repo_private') or False
1239 private = defs.get('repo_private') or False
1241 if repo_type is None:
1240 if repo_type is None:
@@ -1250,7 +1249,7 b' class ApiController(JSONRPCController):'
1250 repo_group = None
1249 repo_group = None
1251 if len(repo_name_parts) > 1:
1250 if len(repo_name_parts) > 1:
1252 group_name = '/'.join(repo_name_parts[:-1])
1251 group_name = '/'.join(repo_name_parts[:-1])
1253 repo_group = RepoGroup.get_by_group_name(group_name)
1252 repo_group = db.RepoGroup.get_by_group_name(group_name)
1254 if repo_group is None:
1253 if repo_group is None:
1255 raise JSONRPCError("repo group `%s` not found" % group_name)
1254 raise JSONRPCError("repo group `%s` not found" % group_name)
1256 data = dict(
1255 data = dict(
@@ -1426,7 +1425,7 b' class ApiController(JSONRPCController):'
1426 repo_group = None
1425 repo_group = None
1427 if len(fork_name_parts) > 1:
1426 if len(fork_name_parts) > 1:
1428 group_name = '/'.join(fork_name_parts[:-1])
1427 group_name = '/'.join(fork_name_parts[:-1])
1429 repo_group = RepoGroup.get_by_group_name(group_name)
1428 repo_group = db.RepoGroup.get_by_group_name(group_name)
1430 if repo_group is None:
1429 if repo_group is None:
1431 raise JSONRPCError("repo group `%s` not found" % group_name)
1430 raise JSONRPCError("repo group `%s` not found" % group_name)
1432
1431
@@ -1756,7 +1755,7 b' class ApiController(JSONRPCController):'
1756 """
1755 """
1757 return [
1756 return [
1758 repo_group.get_api_data()
1757 repo_group.get_api_data()
1759 for repo_group in RepoGroup.query()
1758 for repo_group in db.RepoGroup.query()
1760 ]
1759 ]
1761
1760
1762 @HasPermissionAnyDecorator('hg.admin')
1761 @HasPermissionAnyDecorator('hg.admin')
@@ -1797,7 +1796,7 b' class ApiController(JSONRPCController):'
1797 }
1796 }
1798
1797
1799 """
1798 """
1800 if RepoGroup.get_by_group_name(group_name):
1799 if db.RepoGroup.get_by_group_name(group_name):
1801 raise JSONRPCError("repo group `%s` already exist" % (group_name,))
1800 raise JSONRPCError("repo group `%s` already exist" % (group_name,))
1802
1801
1803 if owner is None:
1802 if owner is None:
@@ -2190,14 +2189,14 b' class ApiController(JSONRPCController):'
2190
2189
2191 return [
2190 return [
2192 gist.get_api_data()
2191 gist.get_api_data()
2193 for gist in Gist().query()
2192 for gist in db.Gist().query()
2194 .filter_by(is_expired=False)
2193 .filter_by(is_expired=False)
2195 .filter(Gist.owner_id == user_id)
2194 .filter(db.Gist.owner_id == user_id)
2196 .order_by(Gist.created_on.desc())
2195 .order_by(db.Gist.created_on.desc())
2197 ]
2196 ]
2198
2197
2199 def create_gist(self, files, owner=None,
2198 def create_gist(self, files, owner=None,
2200 gist_type=Gist.GIST_PUBLIC, lifetime=-1,
2199 gist_type=db.Gist.GIST_PUBLIC, lifetime=-1,
2201 description=''):
2200 description=''):
2202
2201
2203 """
2202 """
@@ -2340,7 +2339,7 b' class ApiController(JSONRPCController):'
2340 """
2339 """
2341 Get given pull request by id
2340 Get given pull request by id
2342 """
2341 """
2343 pull_request = PullRequest.get(pullrequest_id)
2342 pull_request = db.PullRequest.get(pullrequest_id)
2344 if pull_request is None:
2343 if pull_request is None:
2345 raise JSONRPCError('pull request `%s` does not exist' % (pullrequest_id,))
2344 raise JSONRPCError('pull request `%s` does not exist' % (pullrequest_id,))
2346 if not HasRepoPermissionLevel('read')(pull_request.org_repo.repo_name):
2345 if not HasRepoPermissionLevel('read')(pull_request.org_repo.repo_name):
@@ -2353,7 +2352,7 b' class ApiController(JSONRPCController):'
2353 Add comment, close and change status of pull request.
2352 Add comment, close and change status of pull request.
2354 """
2353 """
2355 apiuser = get_user_or_error(request.authuser.user_id)
2354 apiuser = get_user_or_error(request.authuser.user_id)
2356 pull_request = PullRequest.get(pull_request_id)
2355 pull_request = db.PullRequest.get(pull_request_id)
2357 if pull_request is None:
2356 if pull_request is None:
2358 raise JSONRPCError('pull request `%s` does not exist' % (pull_request_id,))
2357 raise JSONRPCError('pull request `%s` does not exist' % (pull_request_id,))
2359 if (not HasRepoPermissionLevel('read')(pull_request.org_repo.repo_name)):
2358 if (not HasRepoPermissionLevel('read')(pull_request.org_repo.repo_name)):
@@ -2375,7 +2374,7 b' class ApiController(JSONRPCController):'
2375 pull_request=pull_request.pull_request_id,
2374 pull_request=pull_request.pull_request_id,
2376 f_path=None,
2375 f_path=None,
2377 line_no=None,
2376 line_no=None,
2378 status_change=ChangesetStatus.get_status_lbl(status),
2377 status_change=db.ChangesetStatus.get_status_lbl(status),
2379 closing_pr=close_pr
2378 closing_pr=close_pr
2380 )
2379 )
2381 action_logger(apiuser,
2380 action_logger(apiuser,
@@ -2407,7 +2406,7 b' class ApiController(JSONRPCController):'
2407 if add is None and remove is None:
2406 if add is None and remove is None:
2408 raise JSONRPCError('''Invalid request. Neither 'add' nor 'remove' is specified.''')
2407 raise JSONRPCError('''Invalid request. Neither 'add' nor 'remove' is specified.''')
2409
2408
2410 pull_request = PullRequest.get(pull_request_id)
2409 pull_request = db.PullRequest.get(pull_request_id)
2411 if pull_request is None:
2410 if pull_request is None:
2412 raise JSONRPCError('pull request `%s` does not exist' % (pull_request_id,))
2411 raise JSONRPCError('pull request `%s` does not exist' % (pull_request_id,))
2413
2412
@@ -44,10 +44,9 b' from kallithea.lib.utils import action_l'
44 from kallithea.lib.utils2 import ascii_str, safe_str
44 from kallithea.lib.utils2 import ascii_str, safe_str
45 from kallithea.lib.vcs.backends.base import EmptyChangeset
45 from kallithea.lib.vcs.backends.base import EmptyChangeset
46 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError, EmptyRepositoryError, RepositoryError
46 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError, EmptyRepositoryError, RepositoryError
47 from kallithea.model import meta
47 from kallithea.model import db, meta
48 from kallithea.model.changeset_status import ChangesetStatusModel
48 from kallithea.model.changeset_status import ChangesetStatusModel
49 from kallithea.model.comment import ChangesetCommentsModel
49 from kallithea.model.comment import ChangesetCommentsModel
50 from kallithea.model.db import ChangesetComment, ChangesetStatus
51 from kallithea.model.pull_request import PullRequestModel
50 from kallithea.model.pull_request import PullRequestModel
52
51
53
52
@@ -115,7 +114,7 b' def create_cs_pr_comment(repo_name, revi'
115 pull_request=pull_request_id,
114 pull_request=pull_request_id,
116 f_path=f_path or None,
115 f_path=f_path or None,
117 line_no=line_no or None,
116 line_no=line_no or None,
118 status_change=ChangesetStatus.get_status_lbl(status) if status else None,
117 status_change=db.ChangesetStatus.get_status_lbl(status) if status else None,
119 closing_pr=close_pr,
118 closing_pr=close_pr,
120 )
119 )
121
120
@@ -156,7 +155,7 b' def create_cs_pr_comment(repo_name, revi'
156
155
157 def delete_cs_pr_comment(repo_name, comment_id):
156 def delete_cs_pr_comment(repo_name, comment_id):
158 """Delete a comment from a changeset or pull request"""
157 """Delete a comment from a changeset or pull request"""
159 co = ChangesetComment.get_or_404(comment_id)
158 co = db.ChangesetComment.get_or_404(comment_id)
160 if co.repo.repo_name != repo_name:
159 if co.repo.repo_name != repo_name:
161 raise HTTPNotFound()
160 raise HTTPNotFound()
162 if co.pull_request and co.pull_request.is_closed():
161 if co.pull_request and co.pull_request.is_closed():
@@ -210,7 +209,7 b' class ChangesetController(BaseRepoContro'
210 c.lines_added = 0 # count of lines added
209 c.lines_added = 0 # count of lines added
211 c.lines_deleted = 0 # count of lines removes
210 c.lines_deleted = 0 # count of lines removes
212
211
213 c.changeset_statuses = ChangesetStatus.STATUSES
212 c.changeset_statuses = db.ChangesetStatus.STATUSES
214 comments = dict()
213 comments = dict()
215 c.statuses = []
214 c.statuses = []
216 c.inline_comments = []
215 c.inline_comments = []
@@ -39,8 +39,8 b' from kallithea.lib import helpers as h'
39 from kallithea.lib.auth import HasRepoPermissionLevelDecorator, LoginRequired
39 from kallithea.lib.auth import HasRepoPermissionLevelDecorator, LoginRequired
40 from kallithea.lib.base import BaseRepoController, render
40 from kallithea.lib.base import BaseRepoController, render
41 from kallithea.lib.graphmod import graph_data
41 from kallithea.lib.graphmod import graph_data
42 from kallithea.lib.webutils import url
42 from kallithea.lib.utils3 import url
43 from kallithea.model.db import Repository
43 from kallithea.model import db
44
44
45
45
46 log = logging.getLogger(__name__)
46 log = logging.getLogger(__name__)
@@ -59,7 +59,7 b' class CompareController(BaseRepoControll'
59 if other_repo is None:
59 if other_repo is None:
60 c.cs_repo = c.a_repo
60 c.cs_repo = c.a_repo
61 else:
61 else:
62 c.cs_repo = Repository.get_by_repo_name(other_repo)
62 c.cs_repo = db.Repository.get_by_repo_name(other_repo)
63 if c.cs_repo is None:
63 if c.cs_repo is None:
64 msg = _('Could not find other repository %s') % other_repo
64 msg = _('Could not find other repository %s') % other_repo
65 h.flash(msg, category='error')
65 h.flash(msg, category='error')
@@ -34,7 +34,7 b' from kallithea.lib.auth import HasRepoPe'
34 from kallithea.lib.base import BaseRepoController, render
34 from kallithea.lib.base import BaseRepoController, render
35 from kallithea.lib.page import Page
35 from kallithea.lib.page import Page
36 from kallithea.lib.utils2 import safe_int
36 from kallithea.lib.utils2 import safe_int
37 from kallithea.model.db import UserFollowing
37 from kallithea.model import db
38
38
39
39
40 log = logging.getLogger(__name__)
40 log = logging.getLogger(__name__)
@@ -47,8 +47,8 b' class FollowersController(BaseRepoContro'
47 def followers(self, repo_name):
47 def followers(self, repo_name):
48 p = safe_int(request.GET.get('page'), 1)
48 p = safe_int(request.GET.get('page'), 1)
49 repo_id = c.db_repo.repo_id
49 repo_id = c.db_repo.repo_id
50 d = UserFollowing.get_repo_followers(repo_id) \
50 d = db.UserFollowing.get_repo_followers(repo_id) \
51 .order_by(UserFollowing.follows_from)
51 .order_by(db.UserFollowing.follows_from)
52 c.followers_pager = Page(d, page=p, items_per_page=20)
52 c.followers_pager = Page(d, page=p, items_per_page=20)
53
53
54 if request.environ.get('HTTP_X_PARTIAL_XHR'):
54 if request.environ.get('HTTP_X_PARTIAL_XHR'):
@@ -41,8 +41,8 b' from kallithea.lib.auth import HasPermis'
41 from kallithea.lib.base import BaseRepoController, render
41 from kallithea.lib.base import BaseRepoController, render
42 from kallithea.lib.page import Page
42 from kallithea.lib.page import Page
43 from kallithea.lib.utils2 import safe_int
43 from kallithea.lib.utils2 import safe_int
44 from kallithea.lib.webutils import url
44 from kallithea.lib.utils3 import url
45 from kallithea.model.db import Repository, Ui, UserFollowing
45 from kallithea.model import db
46 from kallithea.model.forms import RepoForkForm
46 from kallithea.model.forms import RepoForkForm
47 from kallithea.model.repo import RepoModel
47 from kallithea.model.repo import RepoModel
48 from kallithea.model.scm import AvailableRepoGroupChoices, ScmModel
48 from kallithea.model.scm import AvailableRepoGroupChoices, ScmModel
@@ -58,7 +58,7 b' class ForksController(BaseRepoController'
58
58
59 c.landing_revs_choices, c.landing_revs = ScmModel().get_repo_landing_revs()
59 c.landing_revs_choices, c.landing_revs = ScmModel().get_repo_landing_revs()
60
60
61 c.can_update = Ui.get_by_key('hooks', Ui.HOOK_UPDATE).ui_active
61 c.can_update = db.Ui.get_by_key('hooks', db.Ui.HOOK_UPDATE).ui_active
62
62
63 def __load_data(self):
63 def __load_data(self):
64 """
64 """
@@ -74,9 +74,9 b' class ForksController(BaseRepoController'
74 raise HTTPFound(location=url('repos'))
74 raise HTTPFound(location=url('repos'))
75
75
76 c.default_user_id = kallithea.DEFAULT_USER_ID
76 c.default_user_id = kallithea.DEFAULT_USER_ID
77 c.in_public_journal = UserFollowing.query() \
77 c.in_public_journal = db.UserFollowing.query() \
78 .filter(UserFollowing.user_id == c.default_user_id) \
78 .filter(db.UserFollowing.user_id == c.default_user_id) \
79 .filter(UserFollowing.follows_repository == c.repo_info).scalar()
79 .filter(db.UserFollowing.follows_repository == c.repo_info).scalar()
80
80
81 if c.repo_info.stats:
81 if c.repo_info.stats:
82 last_rev = c.repo_info.stats.stat_on_revision + 1
82 last_rev = c.repo_info.stats.stat_on_revision + 1
@@ -108,7 +108,7 b' class ForksController(BaseRepoController'
108 p = safe_int(request.GET.get('page'), 1)
108 p = safe_int(request.GET.get('page'), 1)
109 repo_id = c.db_repo.repo_id
109 repo_id = c.db_repo.repo_id
110 d = []
110 d = []
111 for r in Repository.get_repo_forks(repo_id):
111 for r in db.Repository.get_repo_forks(repo_id):
112 if not HasRepoPermissionLevel('read')(r.repo_name, 'get forks check'):
112 if not HasRepoPermissionLevel('read')(r.repo_name, 'get forks check'):
113 continue
113 continue
114 d.append(r)
114 d.append(r)
@@ -123,7 +123,7 b' class ForksController(BaseRepoController'
123 @HasPermissionAnyDecorator('hg.admin', 'hg.fork.repository')
123 @HasPermissionAnyDecorator('hg.admin', 'hg.fork.repository')
124 @HasRepoPermissionLevelDecorator('read')
124 @HasRepoPermissionLevelDecorator('read')
125 def fork(self, repo_name):
125 def fork(self, repo_name):
126 c.repo_info = Repository.get_by_repo_name(repo_name)
126 c.repo_info = db.Repository.get_by_repo_name(repo_name)
127 if not c.repo_info:
127 if not c.repo_info:
128 h.not_mapped_error(repo_name)
128 h.not_mapped_error(repo_name)
129 raise HTTPFound(location=url('home'))
129 raise HTTPFound(location=url('home'))
@@ -141,7 +141,7 b' class ForksController(BaseRepoController'
141 @HasRepoPermissionLevelDecorator('read')
141 @HasRepoPermissionLevelDecorator('read')
142 def fork_create(self, repo_name):
142 def fork_create(self, repo_name):
143 self.__load_defaults()
143 self.__load_defaults()
144 c.repo_info = Repository.get_by_repo_name(repo_name)
144 c.repo_info = db.Repository.get_by_repo_name(repo_name)
145 _form = RepoForkForm(old_data={'repo_type': c.repo_info.repo_type},
145 _form = RepoForkForm(old_data={'repo_type': c.repo_info.repo_type},
146 repo_groups=c.repo_groups,
146 repo_groups=c.repo_groups,
147 landing_revs=c.landing_revs_choices)()
147 landing_revs=c.landing_revs_choices)()
@@ -151,7 +151,7 b' class ForksController(BaseRepoController'
151 form_result = _form.to_python(dict(request.POST))
151 form_result = _form.to_python(dict(request.POST))
152
152
153 # an approximation that is better than nothing
153 # an approximation that is better than nothing
154 if not Ui.get_by_key('hooks', Ui.HOOK_UPDATE).ui_active:
154 if not db.Ui.get_by_key('hooks', db.Ui.HOOK_UPDATE).ui_active:
155 form_result['update_after_clone'] = False
155 form_result['update_after_clone'] = False
156
156
157 # create fork is done sometimes async on celery, db transaction
157 # create fork is done sometimes async on celery, db transaction
@@ -38,7 +38,7 b' from kallithea.lib import helpers as h'
38 from kallithea.lib.auth import HasRepoPermissionLevelDecorator, LoginRequired
38 from kallithea.lib.auth import HasRepoPermissionLevelDecorator, LoginRequired
39 from kallithea.lib.base import BaseController, jsonify, render
39 from kallithea.lib.base import BaseController, jsonify, render
40 from kallithea.lib.utils2 import safe_str
40 from kallithea.lib.utils2 import safe_str
41 from kallithea.model.db import RepoGroup, Repository, User, UserGroup
41 from kallithea.model import db
42 from kallithea.model.repo import RepoModel
42 from kallithea.model.repo import RepoModel
43 from kallithea.model.scm import UserGroupList
43 from kallithea.model.scm import UserGroupList
44
44
@@ -56,7 +56,7 b' class HomeController(BaseController):'
56 c.group = None
56 c.group = None
57
57
58 repo_groups_list = self.scm_model.get_repo_groups()
58 repo_groups_list = self.scm_model.get_repo_groups()
59 repos_list = Repository.query(sorted=True).filter_by(group=None).all()
59 repos_list = db.Repository.query(sorted=True).filter_by(group=None).all()
60
60
61 c.data = RepoModel().get_repos_as_dict(repos_list,
61 c.data = RepoModel().get_repos_as_dict(repos_list,
62 repo_groups_list=repo_groups_list,
62 repo_groups_list=repo_groups_list,
@@ -68,9 +68,9 b' class HomeController(BaseController):'
68 @jsonify
68 @jsonify
69 def repo_switcher_data(self):
69 def repo_switcher_data(self):
70 if request.is_xhr:
70 if request.is_xhr:
71 all_repos = Repository.query(sorted=True).all()
71 all_repos = db.Repository.query(sorted=True).all()
72 repo_iter = self.scm_model.get_repos(all_repos)
72 repo_iter = self.scm_model.get_repos(all_repos)
73 all_groups = RepoGroup.query(sorted=True).all()
73 all_groups = db.RepoGroup.query(sorted=True).all()
74 repo_groups_iter = self.scm_model.get_repo_groups(all_groups)
74 repo_groups_iter = self.scm_model.get_repo_groups(all_groups)
75
75
76 res = [{
76 res = [{
@@ -111,7 +111,7 b' class HomeController(BaseController):'
111 @HasRepoPermissionLevelDecorator('read')
111 @HasRepoPermissionLevelDecorator('read')
112 @jsonify
112 @jsonify
113 def repo_refs_data(self, repo_name):
113 def repo_refs_data(self, repo_name):
114 repo = Repository.get_by_repo_name(repo_name).scm_instance
114 repo = db.Repository.get_by_repo_name(repo_name).scm_instance
115 res = []
115 res = []
116 _branches = repo.branches.items()
116 _branches = repo.branches.items()
117 if _branches:
117 if _branches:
@@ -163,20 +163,20 b' class HomeController(BaseController):'
163 if 'users' in types:
163 if 'users' in types:
164 user_list = []
164 user_list = []
165 if key:
165 if key:
166 u = User.get_by_username(key)
166 u = db.User.get_by_username(key)
167 if u:
167 if u:
168 user_list = [u]
168 user_list = [u]
169 elif query:
169 elif query:
170 user_list = User.query() \
170 user_list = db.User.query() \
171 .filter(User.is_default_user == False) \
171 .filter(db.User.is_default_user == False) \
172 .filter(User.active == True) \
172 .filter(db.User.active == True) \
173 .filter(or_(
173 .filter(or_(
174 User.username.ilike("%%" + query + "%%"),
174 db.User.username.ilike("%%" + query + "%%"),
175 User.name.concat(' ').concat(User.lastname).ilike("%%" + query + "%%"),
175 db.User.name.concat(' ').concat(db.User.lastname).ilike("%%" + query + "%%"),
176 User.lastname.concat(' ').concat(User.name).ilike("%%" + query + "%%"),
176 db.User.lastname.concat(' ').concat(db.User.name).ilike("%%" + query + "%%"),
177 User.email.ilike("%%" + query + "%%"),
177 db.User.email.ilike("%%" + query + "%%"),
178 )) \
178 )) \
179 .order_by(User.username) \
179 .order_by(db.User.username) \
180 .limit(500) \
180 .limit(500) \
181 .all()
181 .all()
182 for u in user_list:
182 for u in user_list:
@@ -192,14 +192,14 b' class HomeController(BaseController):'
192 if 'groups' in types:
192 if 'groups' in types:
193 grp_list = []
193 grp_list = []
194 if key:
194 if key:
195 grp = UserGroup.get_by_group_name(key)
195 grp = db.UserGroup.get_by_group_name(key)
196 if grp:
196 if grp:
197 grp_list = [grp]
197 grp_list = [grp]
198 elif query:
198 elif query:
199 grp_list = UserGroup.query() \
199 grp_list = db.UserGroup.query() \
200 .filter(UserGroup.users_group_name.ilike("%%" + query + "%%")) \
200 .filter(db.UserGroup.users_group_name.ilike("%%" + query + "%%")) \
201 .filter(UserGroup.users_group_active == True) \
201 .filter(db.UserGroup.users_group_active == True) \
202 .order_by(UserGroup.users_group_name) \
202 .order_by(db.UserGroup.users_group_name) \
203 .limit(500) \
203 .limit(500) \
204 .all()
204 .all()
205 for g in UserGroupList(grp_list, perm_level='read'):
205 for g in UserGroupList(grp_list, perm_level='read'):
@@ -43,8 +43,7 b' from kallithea.lib.auth import LoginRequ'
43 from kallithea.lib.base import BaseController, render
43 from kallithea.lib.base import BaseController, render
44 from kallithea.lib.page import Page
44 from kallithea.lib.page import Page
45 from kallithea.lib.utils2 import AttributeDict, safe_int
45 from kallithea.lib.utils2 import AttributeDict, safe_int
46 from kallithea.model import meta
46 from kallithea.model import db, meta
47 from kallithea.model.db import Repository, User, UserFollowing, UserLog
48 from kallithea.model.repo import RepoModel
47 from kallithea.model.repo import RepoModel
49
48
50
49
@@ -84,20 +83,20 b' class JournalController(BaseController):'
84 filtering_criterion = None
83 filtering_criterion = None
85
84
86 if repo_ids and user_ids:
85 if repo_ids and user_ids:
87 filtering_criterion = or_(UserLog.repository_id.in_(repo_ids),
86 filtering_criterion = or_(db.UserLog.repository_id.in_(repo_ids),
88 UserLog.user_id.in_(user_ids))
87 db.UserLog.user_id.in_(user_ids))
89 if repo_ids and not user_ids:
88 if repo_ids and not user_ids:
90 filtering_criterion = UserLog.repository_id.in_(repo_ids)
89 filtering_criterion = db.UserLog.repository_id.in_(repo_ids)
91 if not repo_ids and user_ids:
90 if not repo_ids and user_ids:
92 filtering_criterion = UserLog.user_id.in_(user_ids)
91 filtering_criterion = db.UserLog.user_id.in_(user_ids)
93 if filtering_criterion is not None:
92 if filtering_criterion is not None:
94 journal = UserLog.query() \
93 journal = db.UserLog.query() \
95 .options(joinedload(UserLog.user)) \
94 .options(joinedload(db.UserLog.user)) \
96 .options(joinedload(UserLog.repository))
95 .options(joinedload(db.UserLog.repository))
97 # filter
96 # filter
98 journal = _journal_filter(journal, c.search_term)
97 journal = _journal_filter(journal, c.search_term)
99 journal = journal.filter(filtering_criterion) \
98 journal = journal.filter(filtering_criterion) \
100 .order_by(UserLog.action_date.desc())
99 .order_by(db.UserLog.action_date.desc())
101 else:
100 else:
102 journal = []
101 journal = []
103
102
@@ -166,10 +165,10 b' class JournalController(BaseController):'
166 def index(self):
165 def index(self):
167 # Return a rendered template
166 # Return a rendered template
168 p = safe_int(request.GET.get('page'), 1)
167 p = safe_int(request.GET.get('page'), 1)
169 c.user = User.get(request.authuser.user_id)
168 c.user = db.User.get(request.authuser.user_id)
170 c.following = UserFollowing.query() \
169 c.following = db.UserFollowing.query() \
171 .filter(UserFollowing.user_id == request.authuser.user_id) \
170 .filter(db.UserFollowing.user_id == request.authuser.user_id) \
172 .options(joinedload(UserFollowing.follows_repository)) \
171 .options(joinedload(db.UserFollowing.follows_repository)) \
173 .all()
172 .all()
174
173
175 journal = self._get_journal_data(c.following)
174 journal = self._get_journal_data(c.following)
@@ -181,7 +180,7 b' class JournalController(BaseController):'
181 if request.environ.get('HTTP_X_PARTIAL_XHR'):
180 if request.environ.get('HTTP_X_PARTIAL_XHR'):
182 return render('journal/journal_data.html')
181 return render('journal/journal_data.html')
183
182
184 repos_list = Repository.query(sorted=True) \
183 repos_list = db.Repository.query(sorted=True) \
185 .filter_by(owner_id=request.authuser.user_id).all()
184 .filter_by(owner_id=request.authuser.user_id).all()
186
185
187 repos_data = RepoModel().get_repos_as_dict(repos_list, admin=True)
186 repos_data = RepoModel().get_repos_as_dict(repos_list, admin=True)
@@ -193,18 +192,18 b' class JournalController(BaseController):'
193 @LoginRequired()
192 @LoginRequired()
194 def journal_atom(self):
193 def journal_atom(self):
195 """Produce a simple atom-1.0 feed"""
194 """Produce a simple atom-1.0 feed"""
196 following = UserFollowing.query() \
195 following = db.UserFollowing.query() \
197 .filter(UserFollowing.user_id == request.authuser.user_id) \
196 .filter(db.UserFollowing.user_id == request.authuser.user_id) \
198 .options(joinedload(UserFollowing.follows_repository)) \
197 .options(joinedload(db.UserFollowing.follows_repository)) \
199 .all()
198 .all()
200 return self._atom_feed(following, public=False)
199 return self._atom_feed(following, public=False)
201
200
202 @LoginRequired()
201 @LoginRequired()
203 def journal_rss(self):
202 def journal_rss(self):
204 """Produce a simple rss2 feed"""
203 """Produce a simple rss2 feed"""
205 following = UserFollowing.query() \
204 following = db.UserFollowing.query() \
206 .filter(UserFollowing.user_id == request.authuser.user_id) \
205 .filter(db.UserFollowing.user_id == request.authuser.user_id) \
207 .options(joinedload(UserFollowing.follows_repository)) \
206 .options(joinedload(db.UserFollowing.follows_repository)) \
208 .all()
207 .all()
209 return self._rss_feed(following, public=False)
208 return self._rss_feed(following, public=False)
210
209
@@ -239,9 +238,9 b' class JournalController(BaseController):'
239 # Return a rendered template
238 # Return a rendered template
240 p = safe_int(request.GET.get('page'), 1)
239 p = safe_int(request.GET.get('page'), 1)
241
240
242 c.following = UserFollowing.query() \
241 c.following = db.UserFollowing.query() \
243 .filter(UserFollowing.user_id == request.authuser.user_id) \
242 .filter(db.UserFollowing.user_id == request.authuser.user_id) \
244 .options(joinedload(UserFollowing.follows_repository)) \
243 .options(joinedload(db.UserFollowing.follows_repository)) \
245 .all()
244 .all()
246
245
247 journal = self._get_journal_data(c.following)
246 journal = self._get_journal_data(c.following)
@@ -258,9 +257,9 b' class JournalController(BaseController):'
258 @LoginRequired(allow_default_user=True)
257 @LoginRequired(allow_default_user=True)
259 def public_journal_atom(self):
258 def public_journal_atom(self):
260 """Produce a simple atom-1.0 feed"""
259 """Produce a simple atom-1.0 feed"""
261 c.following = UserFollowing.query() \
260 c.following = db.UserFollowing.query() \
262 .filter(UserFollowing.user_id == request.authuser.user_id) \
261 .filter(db.UserFollowing.user_id == request.authuser.user_id) \
263 .options(joinedload(UserFollowing.follows_repository)) \
262 .options(joinedload(db.UserFollowing.follows_repository)) \
264 .all()
263 .all()
265
264
266 return self._atom_feed(c.following)
265 return self._atom_feed(c.following)
@@ -268,9 +267,9 b' class JournalController(BaseController):'
268 @LoginRequired(allow_default_user=True)
267 @LoginRequired(allow_default_user=True)
269 def public_journal_rss(self):
268 def public_journal_rss(self):
270 """Produce a simple rss2 feed"""
269 """Produce a simple rss2 feed"""
271 c.following = UserFollowing.query() \
270 c.following = db.UserFollowing.query() \
272 .filter(UserFollowing.user_id == request.authuser.user_id) \
271 .filter(db.UserFollowing.user_id == request.authuser.user_id) \
273 .options(joinedload(UserFollowing.follows_repository)) \
272 .options(joinedload(db.UserFollowing.follows_repository)) \
274 .all()
273 .all()
275
274
276 return self._rss_feed(c.following)
275 return self._rss_feed(c.following)
@@ -40,9 +40,8 b' import kallithea.lib.helpers as h'
40 from kallithea.lib.auth import AuthUser, HasPermissionAnyDecorator
40 from kallithea.lib.auth import AuthUser, HasPermissionAnyDecorator
41 from kallithea.lib.base import BaseController, log_in_user, render
41 from kallithea.lib.base import BaseController, log_in_user, render
42 from kallithea.lib.exceptions import UserCreationError
42 from kallithea.lib.exceptions import UserCreationError
43 from kallithea.lib.webutils import url
43 from kallithea.lib.utils3 import url
44 from kallithea.model import meta
44 from kallithea.model import db, meta
45 from kallithea.model.db import Setting, User
46 from kallithea.model.forms import LoginForm, PasswordResetConfirmationForm, PasswordResetRequestForm, RegisterForm
45 from kallithea.model.forms import LoginForm, PasswordResetConfirmationForm, PasswordResetRequestForm, RegisterForm
47 from kallithea.model.user import UserModel
46 from kallithea.model.user import UserModel
48
47
@@ -82,7 +81,7 b' class LoginController(BaseController):'
82 # login_form will check username/password using ValidAuth and report failure to the user
81 # login_form will check username/password using ValidAuth and report failure to the user
83 c.form_result = login_form.to_python(dict(request.POST))
82 c.form_result = login_form.to_python(dict(request.POST))
84 username = c.form_result['username']
83 username = c.form_result['username']
85 user = User.get_by_username_or_email(username)
84 user = db.User.get_by_username_or_email(username)
86 assert user is not None # the same user get just passed in the form validation
85 assert user is not None # the same user get just passed in the form validation
87 except formencode.Invalid as errors:
86 except formencode.Invalid as errors:
88 defaults = errors.value
87 defaults = errors.value
@@ -118,10 +117,10 b' class LoginController(BaseController):'
118 @HasPermissionAnyDecorator('hg.admin', 'hg.register.auto_activate',
117 @HasPermissionAnyDecorator('hg.admin', 'hg.register.auto_activate',
119 'hg.register.manual_activate')
118 'hg.register.manual_activate')
120 def register(self):
119 def register(self):
121 def_user_perms = AuthUser(dbuser=User.get_default_user()).global_permissions
120 def_user_perms = AuthUser(dbuser=db.User.get_default_user()).global_permissions
122 c.auto_active = 'hg.register.auto_activate' in def_user_perms
121 c.auto_active = 'hg.register.auto_activate' in def_user_perms
123
122
124 settings = Setting.get_app_settings()
123 settings = db.Setting.get_app_settings()
125 captcha_private_key = settings.get('captcha_private_key')
124 captcha_private_key = settings.get('captcha_private_key')
126 c.captcha_active = bool(captcha_private_key)
125 c.captcha_active = bool(captcha_private_key)
127 c.captcha_public_key = settings.get('captcha_public_key')
126 c.captcha_public_key = settings.get('captcha_public_key')
@@ -168,7 +167,7 b' class LoginController(BaseController):'
168 return render('/register.html')
167 return render('/register.html')
169
168
170 def password_reset(self):
169 def password_reset(self):
171 settings = Setting.get_app_settings()
170 settings = db.Setting.get_app_settings()
172 captcha_private_key = settings.get('captcha_private_key')
171 captcha_private_key = settings.get('captcha_private_key')
173 c.captcha_active = bool(captcha_private_key)
172 c.captcha_active = bool(captcha_private_key)
174 c.captcha_public_key = settings.get('captcha_public_key')
173 c.captcha_public_key = settings.get('captcha_public_key')
@@ -45,10 +45,9 b' from kallithea.lib.page import Page'
45 from kallithea.lib.utils2 import ascii_bytes, safe_bytes, safe_int
45 from kallithea.lib.utils2 import ascii_bytes, safe_bytes, safe_int
46 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError, EmptyRepositoryError
46 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError, EmptyRepositoryError
47 from kallithea.lib.webutils import url
47 from kallithea.lib.webutils import url
48 from kallithea.model import meta
48 from kallithea.model import db, meta
49 from kallithea.model.changeset_status import ChangesetStatusModel
49 from kallithea.model.changeset_status import ChangesetStatusModel
50 from kallithea.model.comment import ChangesetCommentsModel
50 from kallithea.model.comment import ChangesetCommentsModel
51 from kallithea.model.db import ChangesetStatus, PullRequest, PullRequestReviewer, Repository, User
52 from kallithea.model.forms import PullRequestForm, PullRequestPostForm
51 from kallithea.model.forms import PullRequestForm, PullRequestPostForm
53 from kallithea.model.pull_request import CreatePullRequestAction, CreatePullRequestIterationAction, PullRequestModel
52 from kallithea.model.pull_request import CreatePullRequestAction, CreatePullRequestIterationAction, PullRequestModel
54
53
@@ -59,7 +58,7 b' log = logging.getLogger(__name__)'
59 def _get_reviewer(user_id):
58 def _get_reviewer(user_id):
60 """Look up user by ID and validate it as a potential reviewer."""
59 """Look up user by ID and validate it as a potential reviewer."""
61 try:
60 try:
62 user = User.get(int(user_id))
61 user = db.User.get(int(user_id))
63 except ValueError:
62 except ValueError:
64 user = None
63 user = None
65
64
@@ -183,9 +182,9 b' class PullrequestsController(BaseRepoCon'
183 return False
182 return False
184
183
185 owner = request.authuser.user_id == pull_request.owner_id
184 owner = request.authuser.user_id == pull_request.owner_id
186 reviewer = PullRequestReviewer.query() \
185 reviewer = db.PullRequestReviewer.query() \
187 .filter(PullRequestReviewer.pull_request == pull_request) \
186 .filter(db.PullRequestReviewer.pull_request == pull_request) \
188 .filter(PullRequestReviewer.user_id == request.authuser.user_id) \
187 .filter(db.PullRequestReviewer.user_id == request.authuser.user_id) \
189 .count() != 0
188 .count() != 0
190
189
191 return request.authuser.admin or owner or reviewer
190 return request.authuser.admin or owner or reviewer
@@ -202,7 +201,7 b' class PullrequestsController(BaseRepoCon'
202 url_params['closed'] = 1
201 url_params['closed'] = 1
203 p = safe_int(request.GET.get('page'), 1)
202 p = safe_int(request.GET.get('page'), 1)
204
203
205 q = PullRequest.query(include_closed=c.closed, sorted=True)
204 q = db.PullRequest.query(include_closed=c.closed, sorted=True)
206 if c.from_:
205 if c.from_:
207 q = q.filter_by(org_repo=c.db_repo)
206 q = q.filter_by(org_repo=c.db_repo)
208 else:
207 else:
@@ -217,15 +216,15 b' class PullrequestsController(BaseRepoCon'
217 def show_my(self):
216 def show_my(self):
218 c.closed = request.GET.get('closed') or ''
217 c.closed = request.GET.get('closed') or ''
219
218
220 c.my_pull_requests = PullRequest.query(
219 c.my_pull_requests = db.PullRequest.query(
221 include_closed=c.closed,
220 include_closed=c.closed,
222 sorted=True,
221 sorted=True,
223 ).filter_by(owner_id=request.authuser.user_id).all()
222 ).filter_by(owner_id=request.authuser.user_id).all()
224
223
225 c.participate_in_pull_requests = []
224 c.participate_in_pull_requests = []
226 c.participate_in_pull_requests_todo = []
225 c.participate_in_pull_requests_todo = []
227 done_status = set([ChangesetStatus.STATUS_APPROVED, ChangesetStatus.STATUS_REJECTED])
226 done_status = set([db.ChangesetStatus.STATUS_APPROVED, db.ChangesetStatus.STATUS_REJECTED])
228 for pr in PullRequest.query(
227 for pr in db.PullRequest.query(
229 include_closed=c.closed,
228 include_closed=c.closed,
230 reviewer_id=request.authuser.user_id,
229 reviewer_id=request.authuser.user_id,
231 sorted=True,
230 sorted=True,
@@ -320,16 +319,16 b' class PullrequestsController(BaseRepoCon'
320
319
321 # heads up: org and other might seem backward here ...
320 # heads up: org and other might seem backward here ...
322 org_ref = _form['org_ref'] # will have merge_rev as rev but symbolic name
321 org_ref = _form['org_ref'] # will have merge_rev as rev but symbolic name
323 org_repo = Repository.guess_instance(_form['org_repo'])
322 org_repo = db.Repository.guess_instance(_form['org_repo'])
324
323
325 other_ref = _form['other_ref'] # will have symbolic name and head revision
324 other_ref = _form['other_ref'] # will have symbolic name and head revision
326 other_repo = Repository.guess_instance(_form['other_repo'])
325 other_repo = db.Repository.guess_instance(_form['other_repo'])
327
326
328 reviewers = []
327 reviewers = []
329
328
330 title = _form['pullrequest_title']
329 title = _form['pullrequest_title']
331 description = _form['pullrequest_desc'].strip()
330 description = _form['pullrequest_desc'].strip()
332 owner = User.get(request.authuser.user_id)
331 owner = db.User.get(request.authuser.user_id)
333
332
334 try:
333 try:
335 cmd = CreatePullRequestAction(org_repo, other_repo, org_ref, other_ref, title, description, owner, reviewers)
334 cmd = CreatePullRequestAction(org_repo, other_repo, org_ref, other_ref, title, description, owner, reviewers)
@@ -351,7 +350,7 b' class PullrequestsController(BaseRepoCon'
351 raise HTTPFound(location=pull_request.url())
350 raise HTTPFound(location=pull_request.url())
352
351
353 def create_new_iteration(self, old_pull_request, new_rev, title, description, reviewers):
352 def create_new_iteration(self, old_pull_request, new_rev, title, description, reviewers):
354 owner = User.get(request.authuser.user_id)
353 owner = db.User.get(request.authuser.user_id)
355 new_org_rev = self._get_ref_rev(old_pull_request.org_repo, 'rev', new_rev)
354 new_org_rev = self._get_ref_rev(old_pull_request.org_repo, 'rev', new_rev)
356 new_other_rev = self._get_ref_rev(old_pull_request.other_repo, old_pull_request.other_ref_parts[0], old_pull_request.other_ref_parts[1])
355 new_other_rev = self._get_ref_rev(old_pull_request.other_repo, old_pull_request.other_ref_parts[0], old_pull_request.other_ref_parts[1])
357 try:
356 try:
@@ -377,7 +376,7 b' class PullrequestsController(BaseRepoCon'
377 @LoginRequired()
376 @LoginRequired()
378 @HasRepoPermissionLevelDecorator('read')
377 @HasRepoPermissionLevelDecorator('read')
379 def post(self, repo_name, pull_request_id):
378 def post(self, repo_name, pull_request_id):
380 pull_request = PullRequest.get_or_404(pull_request_id)
379 pull_request = db.PullRequest.get_or_404(pull_request_id)
381 if pull_request.is_closed():
380 if pull_request.is_closed():
382 raise HTTPForbidden()
381 raise HTTPForbidden()
383 assert pull_request.other_repo.repo_name == repo_name
382 assert pull_request.other_repo.repo_name == repo_name
@@ -418,8 +417,8 b' class PullrequestsController(BaseRepoCon'
418 old_description = pull_request.description
417 old_description = pull_request.description
419 pull_request.title = _form['pullrequest_title']
418 pull_request.title = _form['pullrequest_title']
420 pull_request.description = _form['pullrequest_desc'].strip() or _('No description')
419 pull_request.description = _form['pullrequest_desc'].strip() or _('No description')
421 pull_request.owner = User.get_by_username(_form['owner'])
420 pull_request.owner = db.User.get_by_username(_form['owner'])
422 user = User.get(request.authuser.user_id)
421 user = db.User.get(request.authuser.user_id)
423
422
424 PullRequestModel().mention_from_description(user, pull_request, old_description)
423 PullRequestModel().mention_from_description(user, pull_request, old_description)
425 PullRequestModel().add_reviewers(user, pull_request, added_reviewers)
424 PullRequestModel().add_reviewers(user, pull_request, added_reviewers)
@@ -434,7 +433,7 b' class PullrequestsController(BaseRepoCon'
434 @HasRepoPermissionLevelDecorator('read')
433 @HasRepoPermissionLevelDecorator('read')
435 @jsonify
434 @jsonify
436 def delete(self, repo_name, pull_request_id):
435 def delete(self, repo_name, pull_request_id):
437 pull_request = PullRequest.get_or_404(pull_request_id)
436 pull_request = db.PullRequest.get_or_404(pull_request_id)
438 # only owner can delete it !
437 # only owner can delete it !
439 if pull_request.owner_id == request.authuser.user_id:
438 if pull_request.owner_id == request.authuser.user_id:
440 PullRequestModel().delete(pull_request)
439 PullRequestModel().delete(pull_request)
@@ -447,7 +446,7 b' class PullrequestsController(BaseRepoCon'
447 @LoginRequired(allow_default_user=True)
446 @LoginRequired(allow_default_user=True)
448 @HasRepoPermissionLevelDecorator('read')
447 @HasRepoPermissionLevelDecorator('read')
449 def show(self, repo_name, pull_request_id, extra=None):
448 def show(self, repo_name, pull_request_id, extra=None):
450 c.pull_request = PullRequest.get_or_404(pull_request_id)
449 c.pull_request = db.PullRequest.get_or_404(pull_request_id)
451 c.allowed_to_change_status = self._is_allowed_to_change_status(c.pull_request)
450 c.allowed_to_change_status = self._is_allowed_to_change_status(c.pull_request)
452 cc_model = ChangesetCommentsModel()
451 cc_model = ChangesetCommentsModel()
453 cs_model = ChangesetStatusModel()
452 cs_model = ChangesetStatusModel()
@@ -616,7 +615,7 b' class PullrequestsController(BaseRepoCon'
616 c.pull_request_pending_reviewers,
615 c.pull_request_pending_reviewers,
617 c.current_voting_result,
616 c.current_voting_result,
618 ) = cs_model.calculate_pull_request_result(c.pull_request)
617 ) = cs_model.calculate_pull_request_result(c.pull_request)
619 c.changeset_statuses = ChangesetStatus.STATUSES
618 c.changeset_statuses = db.ChangesetStatus.STATUSES
620
619
621 c.is_ajax_preview = False
620 c.is_ajax_preview = False
622 c.ancestors = None # [c.a_rev] ... but that is shown in an other way
621 c.ancestors = None # [c.a_rev] ... but that is shown in an other way
@@ -626,7 +625,7 b' class PullrequestsController(BaseRepoCon'
626 @HasRepoPermissionLevelDecorator('read')
625 @HasRepoPermissionLevelDecorator('read')
627 @jsonify
626 @jsonify
628 def comment(self, repo_name, pull_request_id):
627 def comment(self, repo_name, pull_request_id):
629 pull_request = PullRequest.get_or_404(pull_request_id)
628 pull_request = db.PullRequest.get_or_404(pull_request_id)
630 allowed_to_change_status = self._is_allowed_to_change_status(pull_request)
629 allowed_to_change_status = self._is_allowed_to_change_status(pull_request)
631 return create_cs_pr_comment(repo_name, pull_request=pull_request,
630 return create_cs_pr_comment(repo_name, pull_request=pull_request,
632 allowed_to_change_status=allowed_to_change_status)
631 allowed_to_change_status=allowed_to_change_status)
@@ -50,7 +50,7 b' from kallithea.lib.utils2 import safe_in'
50 from kallithea.lib.vcs.backends.base import EmptyChangeset
50 from kallithea.lib.vcs.backends.base import EmptyChangeset
51 from kallithea.lib.vcs.exceptions import ChangesetError, EmptyRepositoryError, NodeDoesNotExistError
51 from kallithea.lib.vcs.exceptions import ChangesetError, EmptyRepositoryError, NodeDoesNotExistError
52 from kallithea.lib.vcs.nodes import FileNode
52 from kallithea.lib.vcs.nodes import FileNode
53 from kallithea.model.db import Statistics
53 from kallithea.model import db
54
54
55
55
56 log = logging.getLogger(__name__)
56 log = logging.getLogger(__name__)
@@ -131,8 +131,8 b' class SummaryController(BaseRepoControll'
131 else:
131 else:
132 c.show_stats = False
132 c.show_stats = False
133
133
134 stats = Statistics.query() \
134 stats = db.Statistics.query() \
135 .filter(Statistics.repository == c.db_repo) \
135 .filter(db.Statistics.repository == c.db_repo) \
136 .scalar()
136 .scalar()
137
137
138 c.stats_percentage = 0
138 c.stats_percentage = 0
@@ -181,8 +181,8 b' class SummaryController(BaseRepoControll'
181 c.ts_min = ts_min_m
181 c.ts_min = ts_min_m
182 c.ts_max = ts_max_y
182 c.ts_max = ts_max_y
183
183
184 stats = Statistics.query() \
184 stats = db.Statistics.query() \
185 .filter(Statistics.repository == c.db_repo) \
185 .filter(db.Statistics.repository == c.db_repo) \
186 .scalar()
186 .scalar()
187 c.stats_percentage = 0
187 c.stats_percentage = 0
188 if stats and stats.languages:
188 if stats and stats.languages:
@@ -44,9 +44,7 b' from kallithea.lib.utils import get_repo'
44 from kallithea.lib.utils2 import ascii_bytes, ascii_str, safe_bytes
44 from kallithea.lib.utils2 import ascii_bytes, ascii_str, safe_bytes
45 from kallithea.lib.vcs.utils.lazy import LazyProperty
45 from kallithea.lib.vcs.utils.lazy import LazyProperty
46 from kallithea.lib.webutils import url
46 from kallithea.lib.webutils import url
47 from kallithea.model import meta
47 from kallithea.model import db, meta
48 from kallithea.model.db import (Permission, UserApiKeys, UserGroup, UserGroupMember, UserGroupRepoGroupToPerm, UserGroupRepoToPerm, UserGroupToPerm,
49 UserGroupUserGroupToPerm, UserIpMap, UserToPerm)
50 from kallithea.model.user import UserModel
48 from kallithea.model.user import UserModel
51
49
52
50
@@ -117,7 +115,7 b' def check_password(password, hashed):'
117 return False
115 return False
118
116
119
117
120 PERM_WEIGHTS = Permission.PERM_WEIGHTS
118 PERM_WEIGHTS = db.Permission.PERM_WEIGHTS
121
119
122 def bump_permission(permissions, key, new_perm):
120 def bump_permission(permissions, key, new_perm):
123 """Add a new permission for key to permissions.
121 """Add a new permission for key to permissions.
@@ -225,22 +223,22 b' class AuthUser(object):'
225 global_permissions = set()
223 global_permissions = set()
226
224
227 # default global permissions from the default user
225 # default global permissions from the default user
228 default_global_perms = UserToPerm.query() \
226 default_global_perms = db.UserToPerm.query() \
229 .filter(UserToPerm.user_id == kallithea.DEFAULT_USER_ID) \
227 .filter(db.UserToPerm.user_id == kallithea.DEFAULT_USER_ID) \
230 .options(joinedload(UserToPerm.permission))
228 .options(joinedload(db.UserToPerm.permission))
231 for perm in default_global_perms:
229 for perm in default_global_perms:
232 global_permissions.add(perm.permission.permission_name)
230 global_permissions.add(perm.permission.permission_name)
233
231
234 # user group global permissions
232 # user group global permissions
235 user_perms_from_users_groups = meta.Session().query(UserGroupToPerm) \
233 user_perms_from_users_groups = meta.Session().query(db.UserGroupToPerm) \
236 .options(joinedload(UserGroupToPerm.permission)) \
234 .options(joinedload(db.UserGroupToPerm.permission)) \
237 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
235 .join((db.UserGroupMember, db.UserGroupToPerm.users_group_id ==
238 UserGroupMember.users_group_id)) \
236 db.UserGroupMember.users_group_id)) \
239 .filter(UserGroupMember.user_id == self.user_id) \
237 .filter(db.UserGroupMember.user_id == self.user_id) \
240 .join((UserGroup, UserGroupMember.users_group_id ==
238 .join((db.UserGroup, db.UserGroupMember.users_group_id ==
241 UserGroup.users_group_id)) \
239 db.UserGroup.users_group_id)) \
242 .filter(UserGroup.users_group_active == True) \
240 .filter(db.UserGroup.users_group_active == True) \
243 .order_by(UserGroupToPerm.users_group_id) \
241 .order_by(db.UserGroupToPerm.users_group_id) \
244 .all()
242 .all()
245 # need to group here by groups since user can be in more than
243 # need to group here by groups since user can be in more than
246 # one group
244 # one group
@@ -252,9 +250,9 b' class AuthUser(object):'
252 global_permissions.add(perm.permission.permission_name)
250 global_permissions.add(perm.permission.permission_name)
253
251
254 # user specific global permissions
252 # user specific global permissions
255 user_perms = meta.Session().query(UserToPerm) \
253 user_perms = meta.Session().query(db.UserToPerm) \
256 .options(joinedload(UserToPerm.permission)) \
254 .options(joinedload(db.UserToPerm.permission)) \
257 .filter(UserToPerm.user_id == self.user_id).all()
255 .filter(db.UserToPerm.user_id == self.user_id).all()
258 for perm in user_perms:
256 for perm in user_perms:
259 global_permissions.add(perm.permission.permission_name)
257 global_permissions.add(perm.permission.permission_name)
260
258
@@ -269,7 +267,7 b' class AuthUser(object):'
269 def repository_permissions(self):
267 def repository_permissions(self):
270 log.debug('Getting repository permissions for %s', self)
268 log.debug('Getting repository permissions for %s', self)
271 repository_permissions = {}
269 repository_permissions = {}
272 default_repo_perms = Permission.get_default_perms(kallithea.DEFAULT_USER_ID)
270 default_repo_perms = db.Permission.get_default_perms(kallithea.DEFAULT_USER_ID)
273
271
274 if self.is_admin:
272 if self.is_admin:
275 for perm in default_repo_perms:
273 for perm in default_repo_perms:
@@ -291,15 +289,15 b' class AuthUser(object):'
291
289
292 # user group repository permissions
290 # user group repository permissions
293 user_repo_perms_from_users_groups = \
291 user_repo_perms_from_users_groups = \
294 meta.Session().query(UserGroupRepoToPerm) \
292 meta.Session().query(db.UserGroupRepoToPerm) \
295 .join((UserGroup, UserGroupRepoToPerm.users_group_id ==
293 .join((db.UserGroup, db.UserGroupRepoToPerm.users_group_id ==
296 UserGroup.users_group_id)) \
294 db.UserGroup.users_group_id)) \
297 .filter(UserGroup.users_group_active == True) \
295 .filter(db.UserGroup.users_group_active == True) \
298 .join((UserGroupMember, UserGroupRepoToPerm.users_group_id ==
296 .join((db.UserGroupMember, db.UserGroupRepoToPerm.users_group_id ==
299 UserGroupMember.users_group_id)) \
297 db.UserGroupMember.users_group_id)) \
300 .filter(UserGroupMember.user_id == self.user_id) \
298 .filter(db.UserGroupMember.user_id == self.user_id) \
301 .options(joinedload(UserGroupRepoToPerm.repository)) \
299 .options(joinedload(db.UserGroupRepoToPerm.repository)) \
302 .options(joinedload(UserGroupRepoToPerm.permission)) \
300 .options(joinedload(db.UserGroupRepoToPerm.permission)) \
303 .all()
301 .all()
304 for perm in user_repo_perms_from_users_groups:
302 for perm in user_repo_perms_from_users_groups:
305 bump_permission(repository_permissions,
303 bump_permission(repository_permissions,
@@ -307,7 +305,7 b' class AuthUser(object):'
307 perm.permission.permission_name)
305 perm.permission.permission_name)
308
306
309 # user permissions for repositories
307 # user permissions for repositories
310 user_repo_perms = Permission.get_default_perms(self.user_id)
308 user_repo_perms = db.Permission.get_default_perms(self.user_id)
311 for perm in user_repo_perms:
309 for perm in user_repo_perms:
312 bump_permission(repository_permissions,
310 bump_permission(repository_permissions,
313 perm.repository.repo_name,
311 perm.repository.repo_name,
@@ -319,7 +317,7 b' class AuthUser(object):'
319 def repository_group_permissions(self):
317 def repository_group_permissions(self):
320 log.debug('Getting repository group permissions for %s', self)
318 log.debug('Getting repository group permissions for %s', self)
321 repository_group_permissions = {}
319 repository_group_permissions = {}
322 default_repo_groups_perms = Permission.get_default_group_perms(kallithea.DEFAULT_USER_ID)
320 default_repo_groups_perms = db.Permission.get_default_group_perms(kallithea.DEFAULT_USER_ID)
323
321
324 if self.is_admin:
322 if self.is_admin:
325 for perm in default_repo_groups_perms:
323 for perm in default_repo_groups_perms:
@@ -337,14 +335,14 b' class AuthUser(object):'
337
335
338 # user group for repo groups permissions
336 # user group for repo groups permissions
339 user_repo_group_perms_from_users_groups = \
337 user_repo_group_perms_from_users_groups = \
340 meta.Session().query(UserGroupRepoGroupToPerm) \
338 meta.Session().query(db.UserGroupRepoGroupToPerm) \
341 .join((UserGroup, UserGroupRepoGroupToPerm.users_group_id ==
339 .join((db.UserGroup, db.UserGroupRepoGroupToPerm.users_group_id ==
342 UserGroup.users_group_id)) \
340 db.UserGroup.users_group_id)) \
343 .filter(UserGroup.users_group_active == True) \
341 .filter(db.UserGroup.users_group_active == True) \
344 .join((UserGroupMember, UserGroupRepoGroupToPerm.users_group_id
342 .join((db.UserGroupMember, db.UserGroupRepoGroupToPerm.users_group_id
345 == UserGroupMember.users_group_id)) \
343 == db.UserGroupMember.users_group_id)) \
346 .filter(UserGroupMember.user_id == self.user_id) \
344 .filter(db.UserGroupMember.user_id == self.user_id) \
347 .options(joinedload(UserGroupRepoGroupToPerm.permission)) \
345 .options(joinedload(db.UserGroupRepoGroupToPerm.permission)) \
348 .all()
346 .all()
349 for perm in user_repo_group_perms_from_users_groups:
347 for perm in user_repo_group_perms_from_users_groups:
350 bump_permission(repository_group_permissions,
348 bump_permission(repository_group_permissions,
@@ -352,7 +350,7 b' class AuthUser(object):'
352 perm.permission.permission_name)
350 perm.permission.permission_name)
353
351
354 # user explicit permissions for repository groups
352 # user explicit permissions for repository groups
355 user_repo_groups_perms = Permission.get_default_group_perms(self.user_id)
353 user_repo_groups_perms = db.Permission.get_default_group_perms(self.user_id)
356 for perm in user_repo_groups_perms:
354 for perm in user_repo_groups_perms:
357 bump_permission(repository_group_permissions,
355 bump_permission(repository_group_permissions,
358 perm.group.group_name,
356 perm.group.group_name,
@@ -364,7 +362,7 b' class AuthUser(object):'
364 def user_group_permissions(self):
362 def user_group_permissions(self):
365 log.debug('Getting user group permissions for %s', self)
363 log.debug('Getting user group permissions for %s', self)
366 user_group_permissions = {}
364 user_group_permissions = {}
367 default_user_group_perms = Permission.get_default_user_group_perms(kallithea.DEFAULT_USER_ID)
365 default_user_group_perms = db.Permission.get_default_user_group_perms(kallithea.DEFAULT_USER_ID)
368
366
369 if self.is_admin:
367 if self.is_admin:
370 for perm in default_user_group_perms:
368 for perm in default_user_group_perms:
@@ -382,16 +380,16 b' class AuthUser(object):'
382
380
383 # user group for user group permissions
381 # user group for user group permissions
384 user_group_user_groups_perms = \
382 user_group_user_groups_perms = \
385 meta.Session().query(UserGroupUserGroupToPerm) \
383 meta.Session().query(db.UserGroupUserGroupToPerm) \
386 .join((UserGroup, UserGroupUserGroupToPerm.target_user_group_id
384 .join((db.UserGroup, db.UserGroupUserGroupToPerm.target_user_group_id
387 == UserGroup.users_group_id)) \
385 == db.UserGroup.users_group_id)) \
388 .join((UserGroupMember, UserGroupUserGroupToPerm.user_group_id
386 .join((db.UserGroupMember, db.UserGroupUserGroupToPerm.user_group_id
389 == UserGroupMember.users_group_id)) \
387 == db.UserGroupMember.users_group_id)) \
390 .filter(UserGroupMember.user_id == self.user_id) \
388 .filter(db.UserGroupMember.user_id == self.user_id) \
391 .join((UserGroup, UserGroupMember.users_group_id ==
389 .join((db.UserGroup, db.UserGroupMember.users_group_id ==
392 UserGroup.users_group_id), aliased=True, from_joinpoint=True) \
390 db.UserGroup.users_group_id), aliased=True, from_joinpoint=True) \
393 .filter(UserGroup.users_group_active == True) \
391 .filter(db.UserGroup.users_group_active == True) \
394 .options(joinedload(UserGroupUserGroupToPerm.permission)) \
392 .options(joinedload(db.UserGroupUserGroupToPerm.permission)) \
395 .all()
393 .all()
396 for perm in user_group_user_groups_perms:
394 for perm in user_group_user_groups_perms:
397 bump_permission(user_group_permissions,
395 bump_permission(user_group_permissions,
@@ -399,7 +397,7 b' class AuthUser(object):'
399 perm.permission.permission_name)
397 perm.permission.permission_name)
400
398
401 # user explicit permission for user groups
399 # user explicit permission for user groups
402 user_user_groups_perms = Permission.get_default_user_group_perms(self.user_id)
400 user_user_groups_perms = db.Permission.get_default_user_group_perms(self.user_id)
403 for perm in user_user_groups_perms:
401 for perm in user_user_groups_perms:
404 bump_permission(user_group_permissions,
402 bump_permission(user_group_permissions,
405 perm.user_group.users_group_name,
403 perm.user_group.users_group_name,
@@ -459,7 +457,7 b' class AuthUser(object):'
459
457
460 def _get_api_keys(self):
458 def _get_api_keys(self):
461 api_keys = [self.api_key]
459 api_keys = [self.api_key]
462 for api_key in UserApiKeys.query() \
460 for api_key in db.UserApiKeys.query() \
463 .filter_by(user_id=self.user_id, is_expired=False):
461 .filter_by(user_id=self.user_id, is_expired=False):
464 api_keys.append(api_key.api_key)
462 api_keys.append(api_key.api_key)
465
463
@@ -518,7 +516,7 b' class AuthUser(object):'
518 def get_allowed_ips(cls, user_id):
516 def get_allowed_ips(cls, user_id):
519 _set = set()
517 _set = set()
520
518
521 default_ips = UserIpMap.query().filter(UserIpMap.user_id == kallithea.DEFAULT_USER_ID)
519 default_ips = db.UserIpMap.query().filter(db.UserIpMap.user_id == kallithea.DEFAULT_USER_ID)
522 for ip in default_ips:
520 for ip in default_ips:
523 try:
521 try:
524 _set.add(ip.ip_addr)
522 _set.add(ip.ip_addr)
@@ -527,7 +525,7 b' class AuthUser(object):'
527 # deleted objects here, we just skip them
525 # deleted objects here, we just skip them
528 pass
526 pass
529
527
530 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
528 user_ips = db.UserIpMap.query().filter(db.UserIpMap.user_id == user_id)
531 for ip in user_ips:
529 for ip in user_ips:
532 try:
530 try:
533 _set.add(ip.ip_addr)
531 _set.add(ip.ip_addr)
@@ -23,8 +23,7 b' from inspect import isfunction'
23 from kallithea.lib.auth import AuthUser, PasswordGenerator
23 from kallithea.lib.auth import AuthUser, PasswordGenerator
24 from kallithea.lib.compat import hybrid_property
24 from kallithea.lib.compat import hybrid_property
25 from kallithea.lib.utils2 import asbool
25 from kallithea.lib.utils2 import asbool
26 from kallithea.model import meta, validators
26 from kallithea.model import db, meta, validators
27 from kallithea.model.db import Setting, User
28 from kallithea.model.user import UserModel
27 from kallithea.model.user import UserModel
29 from kallithea.model.user_group import UserGroupModel
28 from kallithea.model.user_group import UserGroupModel
30
29
@@ -134,7 +133,7 b' class KallitheaAuthPluginBase(object):'
134 log.debug('Trying to fetch user `%s` from Kallithea database',
133 log.debug('Trying to fetch user `%s` from Kallithea database',
135 username)
134 username)
136 if username:
135 if username:
137 user = User.get_by_username_or_email(username)
136 user = db.User.get_by_username_or_email(username)
138 else:
137 else:
139 log.debug('provided username:`%s` is empty skipping...', username)
138 log.debug('provided username:`%s` is empty skipping...', username)
140 return user
139 return user
@@ -239,7 +238,7 b' class KallitheaExternalAuthPlugin(Kallit'
239 userobj, username, passwd, settings, **kwargs)
238 userobj, username, passwd, settings, **kwargs)
240 if user_data is not None:
239 if user_data is not None:
241 if userobj is None: # external authentication of unknown user that will be created soon
240 if userobj is None: # external authentication of unknown user that will be created soon
242 def_user_perms = AuthUser(dbuser=User.get_default_user()).global_permissions
241 def_user_perms = AuthUser(dbuser=db.User.get_default_user()).global_permissions
243 active = 'hg.extern_activate.auto' in def_user_perms
242 active = 'hg.extern_activate.auto' in def_user_perms
244 else:
243 else:
245 active = userobj.active
244 active = userobj.active
@@ -315,7 +314,7 b' def loadplugin(plugin):'
315 def get_auth_plugins():
314 def get_auth_plugins():
316 """Return a list of instances of plugins that are available and enabled"""
315 """Return a list of instances of plugins that are available and enabled"""
317 auth_plugins = []
316 auth_plugins = []
318 for plugin_name in Setting.get_by_name("auth_plugins").app_settings_value:
317 for plugin_name in db.Setting.get_by_name("auth_plugins").app_settings_value:
319 try:
318 try:
320 plugin = loadplugin(plugin_name)
319 plugin = loadplugin(plugin_name)
321 except Exception:
320 except Exception:
@@ -345,7 +344,7 b' def authenticate(username, password, env'
345 plugin_settings = {}
344 plugin_settings = {}
346 for v in plugin.plugin_settings():
345 for v in plugin.plugin_settings():
347 conf_key = "auth_%s_%s" % (plugin_name, v["name"])
346 conf_key = "auth_%s_%s" % (plugin_name, v["name"])
348 setting = Setting.get_by_name(conf_key)
347 setting = db.Setting.get_by_name(conf_key)
349 plugin_settings[v["name"]] = setting.app_settings_value if setting else None
348 plugin_settings[v["name"]] = setting.app_settings_value if setting else None
350 log.debug('Settings for auth plugin %s: %s', plugin_name, plugin_settings)
349 log.debug('Settings for auth plugin %s: %s', plugin_name, plugin_settings)
351
350
@@ -30,7 +30,7 b' import logging'
30 from kallithea.lib import auth_modules
30 from kallithea.lib import auth_modules
31 from kallithea.lib.compat import hybrid_property
31 from kallithea.lib.compat import hybrid_property
32 from kallithea.lib.utils2 import asbool
32 from kallithea.lib.utils2 import asbool
33 from kallithea.model.db import Setting
33 from kallithea.model import db
34
34
35
35
36 log = logging.getLogger(__name__)
36 log = logging.getLogger(__name__)
@@ -212,10 +212,10 b' class KallitheaAuthPlugin(auth_modules.K'
212
212
213 def get_managed_fields(self):
213 def get_managed_fields(self):
214 fields = ['username', 'password']
214 fields = ['username', 'password']
215 if(Setting.get_by_name('auth_container_email_header').app_settings_value):
215 if(db.Setting.get_by_name('auth_container_email_header').app_settings_value):
216 fields.append('email')
216 fields.append('email')
217 if(Setting.get_by_name('auth_container_firstname_header').app_settings_value):
217 if(db.Setting.get_by_name('auth_container_firstname_header').app_settings_value):
218 fields.append('firstname')
218 fields.append('firstname')
219 if(Setting.get_by_name('auth_container_lastname_header').app_settings_value):
219 if(db.Setting.get_by_name('auth_container_lastname_header').app_settings_value):
220 fields.append('lastname')
220 fields.append('lastname')
221 return fields
221 return fields
@@ -51,8 +51,7 b' from kallithea.lib.utils import get_repo'
51 from kallithea.lib.utils2 import AttributeDict, asbool, ascii_bytes, safe_int, safe_str, set_hook_environment
51 from kallithea.lib.utils2 import AttributeDict, asbool, ascii_bytes, safe_int, safe_str, set_hook_environment
52 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError, EmptyRepositoryError, RepositoryError
52 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError, EmptyRepositoryError, RepositoryError
53 from kallithea.lib.webutils import url
53 from kallithea.lib.webutils import url
54 from kallithea.model import meta
54 from kallithea.model import db, meta
55 from kallithea.model.db import PullRequest, Repository, Setting, User
56 from kallithea.model.scm import ScmModel
55 from kallithea.model.scm import ScmModel
57
56
58
57
@@ -223,7 +222,7 b' class BaseVCSController(object):'
223 Returns (None, wsgi_app) to send the wsgi_app response to the client.
222 Returns (None, wsgi_app) to send the wsgi_app response to the client.
224 """
223 """
225 # Use anonymous access if allowed for action on repo.
224 # Use anonymous access if allowed for action on repo.
226 default_user = User.get_default_user()
225 default_user = db.User.get_default_user()
227 default_authuser = AuthUser.make(dbuser=default_user, ip_addr=ip_addr)
226 default_authuser = AuthUser.make(dbuser=default_user, ip_addr=ip_addr)
228 if default_authuser is None:
227 if default_authuser is None:
229 log.debug('No anonymous access at all') # move on to proper user auth
228 log.debug('No anonymous access at all') # move on to proper user auth
@@ -260,7 +259,7 b' class BaseVCSController(object):'
260 # CHECK PERMISSIONS FOR THIS REQUEST USING GIVEN USERNAME
259 # CHECK PERMISSIONS FOR THIS REQUEST USING GIVEN USERNAME
261 #==============================================================
260 #==============================================================
262 try:
261 try:
263 user = User.get_by_username_or_email(username)
262 user = db.User.get_by_username_or_email(username)
264 except Exception:
263 except Exception:
265 log.error(traceback.format_exc())
264 log.error(traceback.format_exc())
266 return None, webob.exc.HTTPInternalServerError()
265 return None, webob.exc.HTTPInternalServerError()
@@ -369,7 +368,7 b' class BaseController(TGController):'
369 raise webob.exc.HTTPForbidden()
368 raise webob.exc.HTTPForbidden()
370
369
371 c.kallithea_version = kallithea.__version__
370 c.kallithea_version = kallithea.__version__
372 rc_config = Setting.get_app_settings()
371 rc_config = db.Setting.get_app_settings()
373
372
374 # Visual options
373 # Visual options
375 c.visual = AttributeDict({})
374 c.visual = AttributeDict({})
@@ -400,8 +399,8 b' class BaseController(TGController):'
400 })();
399 })();
401 </script>''' % c.ga_code
400 </script>''' % c.ga_code
402 c.site_name = rc_config.get('title')
401 c.site_name = rc_config.get('title')
403 c.clone_uri_tmpl = rc_config.get('clone_uri_tmpl') or Repository.DEFAULT_CLONE_URI
402 c.clone_uri_tmpl = rc_config.get('clone_uri_tmpl') or db.Repository.DEFAULT_CLONE_URI
404 c.clone_ssh_tmpl = rc_config.get('clone_ssh_tmpl') or Repository.DEFAULT_CLONE_SSH
403 c.clone_ssh_tmpl = rc_config.get('clone_ssh_tmpl') or db.Repository.DEFAULT_CLONE_SSH
405
404
406 ## INI stored
405 ## INI stored
407 c.visual.allow_repo_location_change = asbool(config.get('allow_repo_location_change', True))
406 c.visual.allow_repo_location_change = asbool(config.get('allow_repo_location_change', True))
@@ -417,7 +416,7 b' class BaseController(TGController):'
417
416
418 self.cut_off_limit = safe_int(config.get('cut_off_limit'))
417 self.cut_off_limit = safe_int(config.get('cut_off_limit'))
419
418
420 c.my_pr_count = PullRequest.query(reviewer_id=request.authuser.user_id, include_closed=False).count()
419 c.my_pr_count = db.PullRequest.query(reviewer_id=request.authuser.user_id, include_closed=False).count()
421
420
422 self.scm_model = ScmModel()
421 self.scm_model = ScmModel()
423
422
@@ -450,11 +449,11 b' class BaseController(TGController):'
450 else:
449 else:
451 if user_info is not None:
450 if user_info is not None:
452 username = user_info['username']
451 username = user_info['username']
453 user = User.get_by_username(username, case_insensitive=True)
452 user = db.User.get_by_username(username, case_insensitive=True)
454 return log_in_user(user, remember=False, is_external_auth=True, ip_addr=ip_addr)
453 return log_in_user(user, remember=False, is_external_auth=True, ip_addr=ip_addr)
455
454
456 # User is default user (if active) or anonymous
455 # User is default user (if active) or anonymous
457 default_user = User.get_default_user()
456 default_user = db.User.get_default_user()
458 authuser = AuthUser.make(dbuser=default_user, ip_addr=ip_addr)
457 authuser = AuthUser.make(dbuser=default_user, ip_addr=ip_addr)
459 if authuser is None: # fall back to anonymous
458 if authuser is None: # fall back to anonymous
460 authuser = AuthUser(dbuser=default_user) # TODO: somehow use .make?
459 authuser = AuthUser(dbuser=default_user) # TODO: somehow use .make?
@@ -513,7 +512,7 b' class BaseController(TGController):'
513 needs_csrf_check = request.method not in ['GET', 'HEAD']
512 needs_csrf_check = request.method not in ['GET', 'HEAD']
514
513
515 else:
514 else:
516 dbuser = User.get_by_api_key(api_key)
515 dbuser = db.User.get_by_api_key(api_key)
517 if dbuser is None:
516 if dbuser is None:
518 log.info('No db user found for authentication with API key ****%s from %s',
517 log.info('No db user found for authentication with API key ****%s from %s',
519 api_key[-4:], ip_addr)
518 api_key[-4:], ip_addr)
@@ -553,7 +552,7 b' class BaseRepoController(BaseController)'
553 def _before(self, *args, **kwargs):
552 def _before(self, *args, **kwargs):
554 super(BaseRepoController, self)._before(*args, **kwargs)
553 super(BaseRepoController, self)._before(*args, **kwargs)
555 if c.repo_name: # extracted from request by base-base BaseController._before
554 if c.repo_name: # extracted from request by base-base BaseController._before
556 _dbr = Repository.get_by_repo_name(c.repo_name)
555 _dbr = db.Repository.get_by_repo_name(c.repo_name)
557 if not _dbr:
556 if not _dbr:
558 return
557 return
559
558
@@ -565,7 +564,7 b' class BaseRepoController(BaseController)'
565 if route in ['delete_repo']:
564 if route in ['delete_repo']:
566 return
565 return
567
566
568 if _dbr.repo_state in [Repository.STATE_PENDING]:
567 if _dbr.repo_state in [db.Repository.STATE_PENDING]:
569 if route in ['repo_creating_home']:
568 if route in ['repo_creating_home']:
570 return
569 return
571 check_url = url('repo_creating_home', repo_name=c.repo_name)
570 check_url = url('repo_creating_home', repo_name=c.repo_name)
@@ -45,7 +45,7 b' from kallithea.lib.rcmail.smtp_mailer im'
45 from kallithea.lib.utils import action_logger
45 from kallithea.lib.utils import action_logger
46 from kallithea.lib.utils2 import asbool, ascii_bytes
46 from kallithea.lib.utils2 import asbool, ascii_bytes
47 from kallithea.lib.vcs.utils import author_email
47 from kallithea.lib.vcs.utils import author_email
48 from kallithea.model.db import RepoGroup, Repository, Setting, Statistics, User
48 from kallithea.model import db
49 from kallithea.model.repo import RepoModel
49 from kallithea.model.repo import RepoModel
50
50
51
51
@@ -87,7 +87,7 b' def get_commits_stats(repo_name, ts_min_'
87
87
88 co_day_auth_aggr = {}
88 co_day_auth_aggr = {}
89 commits_by_day_aggregate = {}
89 commits_by_day_aggregate = {}
90 repo = Repository.get_by_repo_name(repo_name)
90 repo = db.Repository.get_by_repo_name(repo_name)
91 if repo is None:
91 if repo is None:
92 return True
92 return True
93
93
@@ -104,10 +104,10 b' def get_commits_stats(repo_name, ts_min_'
104 last_cs = None
104 last_cs = None
105 timegetter = itemgetter('time')
105 timegetter = itemgetter('time')
106
106
107 dbrepo = DBS.query(Repository) \
107 dbrepo = DBS.query(db.Repository) \
108 .filter(Repository.repo_name == repo_name).scalar()
108 .filter(db.Repository.repo_name == repo_name).scalar()
109 cur_stats = DBS.query(Statistics) \
109 cur_stats = DBS.query(db.Statistics) \
110 .filter(Statistics.repository == dbrepo).scalar()
110 .filter(db.Statistics.repository == dbrepo).scalar()
111
111
112 if cur_stats is not None:
112 if cur_stats is not None:
113 last_rev = cur_stats.stat_on_revision
113 last_rev = cur_stats.stat_on_revision
@@ -194,7 +194,7 b' def get_commits_stats(repo_name, ts_min_'
194 "schema": ["commits"],
194 "schema": ["commits"],
195 }
195 }
196
196
197 stats = cur_stats if cur_stats else Statistics()
197 stats = cur_stats if cur_stats else db.Statistics()
198 stats.commit_activity = ascii_bytes(ext_json.dumps(co_day_auth_aggr))
198 stats.commit_activity = ascii_bytes(ext_json.dumps(co_day_auth_aggr))
199 stats.commit_activity_combined = ascii_bytes(ext_json.dumps(overview_data))
199 stats.commit_activity_combined = ascii_bytes(ext_json.dumps(overview_data))
200
200
@@ -261,8 +261,8 b' def send_email(recipients, subject, body'
261
261
262 if not recipients:
262 if not recipients:
263 # if recipients are not defined we send to email_config + all admins
263 # if recipients are not defined we send to email_config + all admins
264 recipients = [u.email for u in User.query()
264 recipients = [u.email for u in db.User.query()
265 .filter(User.admin == True).all()]
265 .filter(db.User.admin == True).all()]
266 if email_config.get('email_to') is not None:
266 if email_config.get('email_to') is not None:
267 recipients += email_config.get('email_to').split(',')
267 recipients += email_config.get('email_to').split(',')
268
268
@@ -326,7 +326,7 b' def send_email(recipients, subject, body'
326 def create_repo(form_data, cur_user):
326 def create_repo(form_data, cur_user):
327 DBS = celerylib.get_session()
327 DBS = celerylib.get_session()
328
328
329 cur_user = User.guess_instance(cur_user)
329 cur_user = db.User.guess_instance(cur_user)
330
330
331 owner = cur_user
331 owner = cur_user
332 repo_name = form_data['repo_name']
332 repo_name = form_data['repo_name']
@@ -340,10 +340,10 b' def create_repo(form_data, cur_user):'
340 copy_fork_permissions = form_data.get('copy_permissions')
340 copy_fork_permissions = form_data.get('copy_permissions')
341 copy_group_permissions = form_data.get('repo_copy_permissions')
341 copy_group_permissions = form_data.get('repo_copy_permissions')
342 fork_of = form_data.get('fork_parent_id')
342 fork_of = form_data.get('fork_parent_id')
343 state = form_data.get('repo_state', Repository.STATE_PENDING)
343 state = form_data.get('repo_state', db.Repository.STATE_PENDING)
344
344
345 # repo creation defaults, private and repo_type are filled in form
345 # repo creation defaults, private and repo_type are filled in form
346 defs = Setting.get_default_repo_settings(strip_prefix=True)
346 defs = db.Setting.get_default_repo_settings(strip_prefix=True)
347 enable_statistics = defs.get('repo_enable_statistics')
347 enable_statistics = defs.get('repo_enable_statistics')
348 enable_downloads = defs.get('repo_enable_downloads')
348 enable_downloads = defs.get('repo_enable_downloads')
349
349
@@ -373,25 +373,25 b' def create_repo(form_data, cur_user):'
373 RepoModel()._create_filesystem_repo(
373 RepoModel()._create_filesystem_repo(
374 repo_name=repo_name,
374 repo_name=repo_name,
375 repo_type=repo_type,
375 repo_type=repo_type,
376 repo_group=RepoGroup.guess_instance(repo_group),
376 repo_group=db.RepoGroup.guess_instance(repo_group),
377 clone_uri=clone_uri,
377 clone_uri=clone_uri,
378 )
378 )
379 repo = Repository.get_by_repo_name(repo_name_full)
379 repo = db.Repository.get_by_repo_name(repo_name_full)
380 log_create_repository(repo.get_dict(), created_by=owner.username)
380 log_create_repository(repo.get_dict(), created_by=owner.username)
381
381
382 # update repo changeset caches initially
382 # update repo changeset caches initially
383 repo.update_changeset_cache()
383 repo.update_changeset_cache()
384
384
385 # set new created state
385 # set new created state
386 repo.set_state(Repository.STATE_CREATED)
386 repo.set_state(db.Repository.STATE_CREATED)
387 DBS.commit()
387 DBS.commit()
388 except Exception as e:
388 except Exception as e:
389 log.warning('Exception %s occurred when forking repository, '
389 log.warning('Exception %s occurred when forking repository, '
390 'doing cleanup...' % e)
390 'doing cleanup...' % e)
391 # rollback things manually !
391 # rollback things manually !
392 repo = Repository.get_by_repo_name(repo_name_full)
392 repo = db.Repository.get_by_repo_name(repo_name_full)
393 if repo:
393 if repo:
394 Repository.delete(repo.repo_id)
394 db.Repository.delete(repo.repo_id)
395 DBS.commit()
395 DBS.commit()
396 RepoModel()._delete_filesystem_repo(repo)
396 RepoModel()._delete_filesystem_repo(repo)
397 raise
397 raise
@@ -411,7 +411,7 b' def create_repo_fork(form_data, cur_user'
411 DBS = celerylib.get_session()
411 DBS = celerylib.get_session()
412
412
413 base_path = kallithea.CONFIG['base_path']
413 base_path = kallithea.CONFIG['base_path']
414 cur_user = User.guess_instance(cur_user)
414 cur_user = db.User.guess_instance(cur_user)
415
415
416 repo_name = form_data['repo_name'] # fork in this case
416 repo_name = form_data['repo_name'] # fork in this case
417 repo_name_full = form_data['repo_name_full']
417 repo_name_full = form_data['repo_name_full']
@@ -425,7 +425,7 b' def create_repo_fork(form_data, cur_user'
425 copy_fork_permissions = form_data.get('copy_permissions')
425 copy_fork_permissions = form_data.get('copy_permissions')
426
426
427 try:
427 try:
428 fork_of = Repository.guess_instance(form_data.get('fork_parent_id'))
428 fork_of = db.Repository.guess_instance(form_data.get('fork_parent_id'))
429
429
430 RepoModel()._create_repo(
430 RepoModel()._create_repo(
431 repo_name=repo_name_full,
431 repo_name=repo_name_full,
@@ -449,25 +449,25 b' def create_repo_fork(form_data, cur_user'
449 RepoModel()._create_filesystem_repo(
449 RepoModel()._create_filesystem_repo(
450 repo_name=repo_name,
450 repo_name=repo_name,
451 repo_type=repo_type,
451 repo_type=repo_type,
452 repo_group=RepoGroup.guess_instance(repo_group),
452 repo_group=db.RepoGroup.guess_instance(repo_group),
453 clone_uri=source_repo_path,
453 clone_uri=source_repo_path,
454 )
454 )
455 repo = Repository.get_by_repo_name(repo_name_full)
455 repo = db.Repository.get_by_repo_name(repo_name_full)
456 log_create_repository(repo.get_dict(), created_by=owner.username)
456 log_create_repository(repo.get_dict(), created_by=owner.username)
457
457
458 # update repo changeset caches initially
458 # update repo changeset caches initially
459 repo.update_changeset_cache()
459 repo.update_changeset_cache()
460
460
461 # set new created state
461 # set new created state
462 repo.set_state(Repository.STATE_CREATED)
462 repo.set_state(db.Repository.STATE_CREATED)
463 DBS.commit()
463 DBS.commit()
464 except Exception as e:
464 except Exception as e:
465 log.warning('Exception %s occurred when forking repository, '
465 log.warning('Exception %s occurred when forking repository, '
466 'doing cleanup...' % e)
466 'doing cleanup...' % e)
467 # rollback things manually !
467 # rollback things manually !
468 repo = Repository.get_by_repo_name(repo_name_full)
468 repo = db.Repository.get_by_repo_name(repo_name_full)
469 if repo:
469 if repo:
470 Repository.delete(repo.repo_id)
470 db.Repository.delete(repo.repo_id)
471 DBS.commit()
471 DBS.commit()
472 RepoModel()._delete_filesystem_repo(repo)
472 RepoModel()._delete_filesystem_repo(repo)
473 raise
473 raise
@@ -476,7 +476,7 b' def create_repo_fork(form_data, cur_user'
476
476
477
477
478 def __get_codes_stats(repo_name):
478 def __get_codes_stats(repo_name):
479 repo = Repository.get_by_repo_name(repo_name).scm_instance
479 repo = db.Repository.get_by_repo_name(repo_name).scm_instance
480
480
481 tip = repo.get_changeset()
481 tip = repo.get_changeset()
482 code_stats = {}
482 code_stats = {}
@@ -38,9 +38,8 b' import sqlalchemy'
38 from sqlalchemy.engine import create_engine
38 from sqlalchemy.engine import create_engine
39
39
40 from kallithea.lib.utils2 import ask_ok
40 from kallithea.lib.utils2 import ask_ok
41 from kallithea.model import meta
41 from kallithea.model import db, meta
42 from kallithea.model.base import init_model
42 from kallithea.model.base import init_model
43 from kallithea.model.db import Repository, Setting, Ui, User
44 from kallithea.model.permission import PermissionModel
43 from kallithea.model.permission import PermissionModel
45 from kallithea.model.user import UserModel
44 from kallithea.model.user import UserModel
46
45
@@ -167,10 +166,10 b' class DbManage(object):'
167
166
168 for k, v, t in [('auth_plugins', 'kallithea.lib.auth_modules.auth_internal', 'list'),
167 for k, v, t in [('auth_plugins', 'kallithea.lib.auth_modules.auth_internal', 'list'),
169 ('auth_internal_enabled', 'True', 'bool')]:
168 ('auth_internal_enabled', 'True', 'bool')]:
170 if skip_existing and Setting.get_by_name(k) is not None:
169 if skip_existing and db.Setting.get_by_name(k) is not None:
171 log.debug('Skipping option %s', k)
170 log.debug('Skipping option %s', k)
172 continue
171 continue
173 setting = Setting(k, v, t)
172 setting = db.Setting(k, v, t)
174 self.sa.add(setting)
173 self.sa.add(setting)
175
174
176 def create_default_options(self, skip_existing=False):
175 def create_default_options(self, skip_existing=False):
@@ -182,10 +181,10 b' class DbManage(object):'
182 ('default_repo_private', False, 'bool'),
181 ('default_repo_private', False, 'bool'),
183 ('default_repo_type', 'hg', 'unicode')
182 ('default_repo_type', 'hg', 'unicode')
184 ]:
183 ]:
185 if skip_existing and Setting.get_by_name(k) is not None:
184 if skip_existing and db.Setting.get_by_name(k) is not None:
186 log.debug('Skipping option %s', k)
185 log.debug('Skipping option %s', k)
187 continue
186 continue
188 setting = Setting(k, v, t)
187 setting = db.Setting(k, v, t)
189 self.sa.add(setting)
188 self.sa.add(setting)
190
189
191 def prompt_repo_root_path(self, test_repo_path='', retries=3):
190 def prompt_repo_root_path(self, test_repo_path='', retries=3):
@@ -245,14 +244,14 b' class DbManage(object):'
245 ui_config = [
244 ui_config = [
246 ('paths', '/', repo_root_path, True),
245 ('paths', '/', repo_root_path, True),
247 #('phases', 'publish', 'false', False)
246 #('phases', 'publish', 'false', False)
248 ('hooks', Ui.HOOK_UPDATE, 'hg update >&2', False),
247 ('hooks', db.Ui.HOOK_UPDATE, 'hg update >&2', False),
249 ('hooks', Ui.HOOK_REPO_SIZE, 'python:kallithea.lib.hooks.repo_size', True),
248 ('hooks', db.Ui.HOOK_REPO_SIZE, 'python:kallithea.lib.hooks.repo_size', True),
250 ('extensions', 'largefiles', '', True),
249 ('extensions', 'largefiles', '', True),
251 ('largefiles', 'usercache', os.path.join(repo_root_path, '.cache', 'largefiles'), True),
250 ('largefiles', 'usercache', os.path.join(repo_root_path, '.cache', 'largefiles'), True),
252 ('extensions', 'hggit', '', False),
251 ('extensions', 'hggit', '', False),
253 ]
252 ]
254 for ui_section, ui_key, ui_value, ui_active in ui_config:
253 for ui_section, ui_key, ui_value, ui_active in ui_config:
255 ui_conf = Ui(
254 ui_conf = db.Ui(
256 ui_section=ui_section,
255 ui_section=ui_section,
257 ui_key=ui_key,
256 ui_key=ui_key,
258 ui_value=ui_value,
257 ui_value=ui_value,
@@ -270,12 +269,12 b' class DbManage(object):'
270 ('admin_grid_items', 25, 'int'),
269 ('admin_grid_items', 25, 'int'),
271 ('show_version', True, 'bool'),
270 ('show_version', True, 'bool'),
272 ('use_gravatar', True, 'bool'),
271 ('use_gravatar', True, 'bool'),
273 ('gravatar_url', User.DEFAULT_GRAVATAR_URL, 'unicode'),
272 ('gravatar_url', db.User.DEFAULT_GRAVATAR_URL, 'unicode'),
274 ('clone_uri_tmpl', Repository.DEFAULT_CLONE_URI, 'unicode'),
273 ('clone_uri_tmpl', db.Repository.DEFAULT_CLONE_URI, 'unicode'),
275 ('clone_ssh_tmpl', Repository.DEFAULT_CLONE_SSH, 'unicode'),
274 ('clone_ssh_tmpl', db.Repository.DEFAULT_CLONE_SSH, 'unicode'),
276 ]
275 ]
277 for key, val, type_ in settings:
276 for key, val, type_ in settings:
278 sett = Setting(key, val, type_)
277 sett = db.Setting(key, val, type_)
279 self.sa.add(sett)
278 self.sa.add(sett)
280
279
281 self.create_auth_plugin_options()
280 self.create_auth_plugin_options()
@@ -288,12 +287,12 b' class DbManage(object):'
288 UserModel().create_or_update(username, password, email,
287 UserModel().create_or_update(username, password, email,
289 firstname='Kallithea', lastname='Admin',
288 firstname='Kallithea', lastname='Admin',
290 active=True, admin=admin,
289 active=True, admin=admin,
291 extern_type=User.DEFAULT_AUTH_TYPE)
290 extern_type=db.User.DEFAULT_AUTH_TYPE)
292
291
293 def create_default_user(self):
292 def create_default_user(self):
294 log.info('creating default user')
293 log.info('creating default user')
295 # create default user for handling default permissions.
294 # create default user for handling default permissions.
296 user = UserModel().create_or_update(username=User.DEFAULT_USER_NAME,
295 user = UserModel().create_or_update(username=db.User.DEFAULT_USER_NAME,
297 password=str(uuid.uuid1())[:20],
296 password=str(uuid.uuid1())[:20],
298 email='anonymous@kallithea-scm.org',
297 email='anonymous@kallithea-scm.org',
299 firstname='Anonymous',
298 firstname='Anonymous',
@@ -320,4 +319,4 b' class DbManage(object):'
320 permissions that are missing, and not alter already defined ones
319 permissions that are missing, and not alter already defined ones
321 """
320 """
322 log.info('creating default user permissions')
321 log.info('creating default user permissions')
323 PermissionModel().create_default_permissions(user=User.DEFAULT_USER_NAME)
322 PermissionModel().create_default_permissions(user=db.User.DEFAULT_USER_NAME)
@@ -56,8 +56,8 b' from kallithea.lib.vcs.exceptions import'
56 #==============================================================================
56 #==============================================================================
57 from kallithea.lib.vcs.utils import author_email, author_name
57 from kallithea.lib.vcs.utils import author_email, author_name
58 from kallithea.lib.webutils import url
58 from kallithea.lib.webutils import url
59 from kallithea.model import db
59 from kallithea.model.changeset_status import ChangesetStatusModel
60 from kallithea.model.changeset_status import ChangesetStatusModel
60 from kallithea.model.db import ChangesetStatus, Permission, PullRequest, User, UserIpMap
61
61
62
62
63 # mute pyflakes "imported but unused"
63 # mute pyflakes "imported but unused"
@@ -600,7 +600,7 b' def user_attr_or_none(author, show_attr)'
600 - or return None if user not found"""
600 - or return None if user not found"""
601 email = author_email(author)
601 email = author_email(author)
602 if email:
602 if email:
603 user = User.get_by_email(email)
603 user = db.User.get_by_email(email)
604 if user is not None:
604 if user is not None:
605 return getattr(user, show_attr)
605 return getattr(user, show_attr)
606 return None
606 return None
@@ -628,7 +628,7 b' def person(author, show_attr="username")'
628 """Find the user identified by 'author', return one of the users attributes,
628 """Find the user identified by 'author', return one of the users attributes,
629 default to the username attribute, None if there is no user"""
629 default to the username attribute, None if there is no user"""
630 # if author is already an instance use it for extraction
630 # if author is already an instance use it for extraction
631 if isinstance(author, User):
631 if isinstance(author, db.User):
632 return getattr(author, show_attr)
632 return getattr(author, show_attr)
633
633
634 value = user_attr_or_none(author, show_attr)
634 value = user_attr_or_none(author, show_attr)
@@ -643,7 +643,7 b' def person_by_id(id_, show_attr="usernam'
643 # maybe it's an ID ?
643 # maybe it's an ID ?
644 if str(id_).isdigit() or isinstance(id_, int):
644 if str(id_).isdigit() or isinstance(id_, int):
645 id_ = int(id_)
645 id_ = int(id_)
646 user = User.get(id_)
646 user = db.User.get(id_)
647 if user is not None:
647 if user is not None:
648 return getattr(user, show_attr)
648 return getattr(user, show_attr)
649 return id_
649 return id_
@@ -822,7 +822,7 b' def action_parser(user_log, feed=False, '
822
822
823 def get_pull_request():
823 def get_pull_request():
824 pull_request_id = action_params
824 pull_request_id = action_params
825 nice_id = PullRequest.make_nice_id(pull_request_id)
825 nice_id = db.PullRequest.make_nice_id(pull_request_id)
826
826
827 deleted = user_log.repository is None
827 deleted = user_log.repository is None
828 if deleted:
828 if deleted:
@@ -979,7 +979,7 b' def gravatar_url(email_address, size=30,'
979 return default
979 return default
980
980
981 parsed_url = urllib.parse.urlparse(url.current(qualified=True))
981 parsed_url = urllib.parse.urlparse(url.current(qualified=True))
982 return (c.visual.gravatar_url or User.DEFAULT_GRAVATAR_URL) \
982 return (c.visual.gravatar_url or db.User.DEFAULT_GRAVATAR_URL) \
983 .replace('{email}', email_address) \
983 .replace('{email}', email_address) \
984 .replace('{md5email}', hashlib.md5(safe_bytes(email_address).lower()).hexdigest()) \
984 .replace('{md5email}', hashlib.md5(safe_bytes(email_address).lower()).hexdigest()) \
985 .replace('{netloc}', parsed_url.netloc) \
985 .replace('{netloc}', parsed_url.netloc) \
@@ -1310,11 +1310,11 b' def changeset_status(repo, revision):'
1310
1310
1311
1311
1312 def changeset_status_lbl(changeset_status):
1312 def changeset_status_lbl(changeset_status):
1313 return ChangesetStatus.get_status_lbl(changeset_status)
1313 return db.ChangesetStatus.get_status_lbl(changeset_status)
1314
1314
1315
1315
1316 def get_permission_name(key):
1316 def get_permission_name(key):
1317 return dict(Permission.PERMS).get(key)
1317 return dict(db.Permission.PERMS).get(key)
1318
1318
1319
1319
1320 def journal_filter_help():
1320 def journal_filter_help():
@@ -1345,7 +1345,7 b' def not_mapped_error(repo_name):'
1345
1345
1346
1346
1347 def ip_range(ip_addr):
1347 def ip_range(ip_addr):
1348 s, e = UserIpMap._get_ip_range(ip_addr)
1348 s, e = db.UserIpMap._get_ip_range(ip_addr)
1349 return '%s - %s' % (s, e)
1349 return '%s - %s' % (s, e)
1350
1350
1351
1351
@@ -37,7 +37,7 b' from kallithea.lib.exceptions import Use'
37 from kallithea.lib.utils import action_logger, make_ui
37 from kallithea.lib.utils import action_logger, make_ui
38 from kallithea.lib.utils2 import HookEnvironmentError, ascii_str, get_hook_environment, safe_bytes, safe_str
38 from kallithea.lib.utils2 import HookEnvironmentError, ascii_str, get_hook_environment, safe_bytes, safe_str
39 from kallithea.lib.vcs.backends.base import EmptyChangeset
39 from kallithea.lib.vcs.backends.base import EmptyChangeset
40 from kallithea.model.db import Repository, User
40 from kallithea.model import db
41
41
42
42
43 def _get_scm_size(alias, root_path):
43 def _get_scm_size(alias, root_path):
@@ -91,7 +91,7 b' def log_pull_action(ui, repo, **kwargs):'
91 """
91 """
92 ex = get_hook_environment()
92 ex = get_hook_environment()
93
93
94 user = User.get_by_username(ex.username)
94 user = db.User.get_by_username(ex.username)
95 action = 'pull'
95 action = 'pull'
96 action_logger(user, action, ex.repository, ex.ip, commit=True)
96 action_logger(user, action, ex.repository, ex.ip, commit=True)
97 # extension hook call
97 # extension hook call
@@ -316,7 +316,7 b' def _hook_environment(repo_path):'
316 if repo_path.endswith(os.sep + '.git'):
316 if repo_path.endswith(os.sep + '.git'):
317 repo_path = repo_path[:-5]
317 repo_path = repo_path[:-5]
318
318
319 repo = Repository.get_by_full_path(repo_path)
319 repo = db.Repository.get_by_full_path(repo_path)
320 if not repo:
320 if not repo:
321 raise OSError('Repository %s not found in database' % repo_path)
321 raise OSError('Repository %s not found in database' % repo_path)
322
322
@@ -41,7 +41,7 b' from kallithea.lib.conf import INDEX_EXT'
41 from kallithea.lib.indexers import CHGSET_IDX_NAME, CHGSETS_SCHEMA, IDX_NAME, SCHEMA
41 from kallithea.lib.indexers import CHGSET_IDX_NAME, CHGSETS_SCHEMA, IDX_NAME, SCHEMA
42 from kallithea.lib.utils2 import safe_str
42 from kallithea.lib.utils2 import safe_str
43 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError, ChangesetError, NodeDoesNotExistError, RepositoryError
43 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError, ChangesetError, NodeDoesNotExistError, RepositoryError
44 from kallithea.model.db import Repository
44 from kallithea.model import db
45 from kallithea.model.scm import ScmModel
45 from kallithea.model.scm import ScmModel
46
46
47
47
@@ -109,7 +109,7 b' class WhooshIndexingDaemon(object):'
109 self.initial = False
109 self.initial = False
110
110
111 def _get_index_revision(self, repo):
111 def _get_index_revision(self, repo):
112 db_repo = Repository.get_by_repo_name(repo.name)
112 db_repo = db.Repository.get_by_repo_name(repo.name)
113 landing_rev = 'tip'
113 landing_rev = 'tip'
114 if db_repo:
114 if db_repo:
115 _rev_type, _rev = db_repo.landing_rev
115 _rev_type, _rev = db_repo.landing_rev
@@ -156,9 +156,9 b' def authorized_keys_line(kallithea_cli_p'
156 Return a line as it would appear in .authorized_keys
156 Return a line as it would appear in .authorized_keys
157
157
158 >>> getfixture('doctest_mock_ugettext')
158 >>> getfixture('doctest_mock_ugettext')
159 >>> from kallithea.model.db import UserSshKeys, User
159 >>> from kallithea.model import db
160 >>> user = User(user_id=7, username='uu')
160 >>> user = db.User(user_id=7, username='uu')
161 >>> key = UserSshKeys(user_ssh_key_id=17, user=user, description='test key')
161 >>> key = db.UserSshKeys(user_ssh_key_id=17, user=user, description='test key')
162 >>> key.public_key='''ssh-rsa AAAAB3NzaC1yc2EAAAANVGhpcyBpcyBmYWtlIQAAAANieWU= and a comment'''
162 >>> key.public_key='''ssh-rsa AAAAB3NzaC1yc2EAAAANVGhpcyBpcyBmYWtlIQAAAANieWU= and a comment'''
163 >>> authorized_keys_line('/srv/kallithea/venv/bin/kallithea-cli', '/srv/kallithea/my.ini', key)
163 >>> authorized_keys_line('/srv/kallithea/venv/bin/kallithea-cli', '/srv/kallithea/my.ini', key)
164 'no-pty,no-port-forwarding,no-X11-forwarding,no-agent-forwarding,command="/srv/kallithea/venv/bin/kallithea-cli ssh-serve -c /srv/kallithea/my.ini 7 17" ssh-rsa AAAAB3NzaC1yc2EAAAANVGhpcyBpcyBmYWtlIQAAAANieWU=\n'
164 'no-pty,no-port-forwarding,no-X11-forwarding,no-agent-forwarding,command="/srv/kallithea/venv/bin/kallithea-cli ssh-serve -c /srv/kallithea/my.ini 7 17" ssh-rsa AAAAB3NzaC1yc2EAAAANVGhpcyBpcyBmYWtlIQAAAANieWU=\n'
@@ -47,8 +47,7 b' from kallithea.lib.vcs.conf import setti'
47 from kallithea.lib.vcs.exceptions import RepositoryError, VCSError
47 from kallithea.lib.vcs.exceptions import RepositoryError, VCSError
48 from kallithea.lib.vcs.utils.fakemod import create_module
48 from kallithea.lib.vcs.utils.fakemod import create_module
49 from kallithea.lib.vcs.utils.helpers import get_scm
49 from kallithea.lib.vcs.utils.helpers import get_scm
50 from kallithea.model import meta
50 from kallithea.model import db, meta
51 from kallithea.model.db import RepoGroup, Repository, Setting, Ui, User, UserGroup, UserLog
52
51
53
52
54 log = logging.getLogger(__name__)
53 log = logging.getLogger(__name__)
@@ -75,7 +74,7 b' def get_repo_group_slug(request):'
75
74
76 def get_user_group_slug(request):
75 def get_user_group_slug(request):
77 _group = request.environ['pylons.routes_dict'].get('id')
76 _group = request.environ['pylons.routes_dict'].get('id')
78 _group = UserGroup.get(_group)
77 _group = db.UserGroup.get(_group)
79 if _group:
78 if _group:
80 return _group.users_group_name
79 return _group.users_group_name
81 return None
80 return None
@@ -105,7 +104,7 b' def fix_repo_id_name(path):'
105 rest = '/' + rest_
104 rest = '/' + rest_
106 repo_id = _get_permanent_id(first)
105 repo_id = _get_permanent_id(first)
107 if repo_id is not None:
106 if repo_id is not None:
108 repo = Repository.get(repo_id)
107 repo = db.Repository.get(repo_id)
109 if repo is not None:
108 if repo is not None:
110 return repo.repo_name + rest
109 return repo.repo_name + rest
111 return path
110 return path
@@ -131,23 +130,23 b' def action_logger(user, action, repo, ip'
131 ipaddr = getattr(get_current_authuser(), 'ip_addr', '')
130 ipaddr = getattr(get_current_authuser(), 'ip_addr', '')
132
131
133 if getattr(user, 'user_id', None):
132 if getattr(user, 'user_id', None):
134 user_obj = User.get(user.user_id)
133 user_obj = db.User.get(user.user_id)
135 elif isinstance(user, str):
134 elif isinstance(user, str):
136 user_obj = User.get_by_username(user)
135 user_obj = db.User.get_by_username(user)
137 else:
136 else:
138 raise Exception('You have to provide a user object or a username')
137 raise Exception('You have to provide a user object or a username')
139
138
140 if getattr(repo, 'repo_id', None):
139 if getattr(repo, 'repo_id', None):
141 repo_obj = Repository.get(repo.repo_id)
140 repo_obj = db.Repository.get(repo.repo_id)
142 repo_name = repo_obj.repo_name
141 repo_name = repo_obj.repo_name
143 elif isinstance(repo, str):
142 elif isinstance(repo, str):
144 repo_name = repo.lstrip('/')
143 repo_name = repo.lstrip('/')
145 repo_obj = Repository.get_by_repo_name(repo_name)
144 repo_obj = db.Repository.get_by_repo_name(repo_name)
146 else:
145 else:
147 repo_obj = None
146 repo_obj = None
148 repo_name = ''
147 repo_name = ''
149
148
150 user_log = UserLog()
149 user_log = db.UserLog()
151 user_log.user_id = user_obj.user_id
150 user_log.user_id = user_obj.user_id
152 user_log.username = user_obj.username
151 user_log.username = user_obj.username
153 user_log.action = action
152 user_log.action = action
@@ -322,7 +321,7 b' def make_ui(repo_path=None):'
322 baseui._tcfg = mercurial.config.config()
321 baseui._tcfg = mercurial.config.config()
323
322
324 sa = meta.Session()
323 sa = meta.Session()
325 for ui_ in sa.query(Ui).order_by(Ui.ui_section, Ui.ui_key):
324 for ui_ in sa.query(db.Ui).order_by(db.Ui.ui_section, db.Ui.ui_key):
326 if ui_.ui_active:
325 if ui_.ui_active:
327 log.debug('config from db: [%s] %s=%r', ui_.ui_section,
326 log.debug('config from db: [%s] %s=%r', ui_.ui_section,
328 ui_.ui_key, ui_.ui_value)
327 ui_.ui_key, ui_.ui_value)
@@ -353,10 +352,10 b' def set_app_settings(config):'
353
352
354 :param config:
353 :param config:
355 """
354 """
356 hgsettings = Setting.get_app_settings()
355 hgsettings = db.Setting.get_app_settings()
357 for k, v in hgsettings.items():
356 for k, v in hgsettings.items():
358 config[k] = v
357 config[k] = v
359 config['base_path'] = Ui.get_repos_location()
358 config['base_path'] = db.Ui.get_repos_location()
360
359
361
360
362 def set_vcs_config(config):
361 def set_vcs_config(config):
@@ -406,10 +405,10 b' def map_groups(path):'
406 # last element is repo in nested groups structure
405 # last element is repo in nested groups structure
407 groups = groups[:-1]
406 groups = groups[:-1]
408 rgm = RepoGroupModel()
407 rgm = RepoGroupModel()
409 owner = User.get_first_admin()
408 owner = db.User.get_first_admin()
410 for lvl, group_name in enumerate(groups):
409 for lvl, group_name in enumerate(groups):
411 group_name = '/'.join(groups[:lvl] + [group_name])
410 group_name = '/'.join(groups[:lvl] + [group_name])
412 group = RepoGroup.get_by_group_name(group_name)
411 group = db.RepoGroup.get_by_group_name(group_name)
413 desc = '%s group' % group_name
412 desc = '%s group' % group_name
414
413
415 # skip folders that are now removed repos
414 # skip folders that are now removed repos
@@ -419,7 +418,7 b' def map_groups(path):'
419 if group is None:
418 if group is None:
420 log.debug('creating group level: %s group_name: %s',
419 log.debug('creating group level: %s group_name: %s',
421 lvl, group_name)
420 lvl, group_name)
422 group = RepoGroup(group_name, parent)
421 group = db.RepoGroup(group_name, parent)
423 group.group_description = desc
422 group.group_description = desc
424 group.owner = owner
423 group.owner = owner
425 sa.add(group)
424 sa.add(group)
@@ -449,11 +448,11 b' def repo2db_mapper(initial_repo_dict, re'
449 sa = meta.Session()
448 sa = meta.Session()
450 repo_model = RepoModel()
449 repo_model = RepoModel()
451 if user is None:
450 if user is None:
452 user = User.get_first_admin()
451 user = db.User.get_first_admin()
453 added = []
452 added = []
454
453
455 # creation defaults
454 # creation defaults
456 defs = Setting.get_default_repo_settings(strip_prefix=True)
455 defs = db.Setting.get_default_repo_settings(strip_prefix=True)
457 enable_statistics = defs.get('repo_enable_statistics')
456 enable_statistics = defs.get('repo_enable_statistics')
458 enable_downloads = defs.get('repo_enable_downloads')
457 enable_downloads = defs.get('repo_enable_downloads')
459 private = defs.get('repo_private')
458 private = defs.get('repo_private')
@@ -478,7 +477,7 b' def repo2db_mapper(initial_repo_dict, re'
478 enable_downloads=enable_downloads,
477 enable_downloads=enable_downloads,
479 enable_statistics=enable_statistics,
478 enable_statistics=enable_statistics,
480 private=private,
479 private=private,
481 state=Repository.STATE_CREATED
480 state=db.Repository.STATE_CREATED
482 )
481 )
483 sa.commit()
482 sa.commit()
484 # we added that repo just now, and make sure it has githook
483 # we added that repo just now, and make sure it has githook
@@ -496,7 +495,7 b' def repo2db_mapper(initial_repo_dict, re'
496
495
497 removed = []
496 removed = []
498 # remove from database those repositories that are not in the filesystem
497 # remove from database those repositories that are not in the filesystem
499 for repo in sa.query(Repository).all():
498 for repo in sa.query(db.Repository).all():
500 if repo.repo_name not in initial_repo_dict:
499 if repo.repo_name not in initial_repo_dict:
501 if remove_obsolete:
500 if remove_obsolete:
502 log.debug("Removing non-existing repository found in db `%s`",
501 log.debug("Removing non-existing repository found in db `%s`",
@@ -597,7 +596,7 b' def extract_mentioned_users(text):'
597 """ Returns set of actual database Users @mentioned in given text. """
596 """ Returns set of actual database Users @mentioned in given text. """
598 result = set()
597 result = set()
599 for name in extract_mentioned_usernames(text):
598 for name in extract_mentioned_usernames(text):
600 user = User.get_by_username(name, case_insensitive=True)
599 user = db.User.get_by_username(name, case_insensitive=True)
601 if user is not None and not user.is_default_user:
600 if user is not None and not user.is_default_user:
602 result.add(user)
601 result.add(user)
603 return result
602 return result
@@ -25,8 +25,7 b' import sys'
25
25
26 from kallithea.lib.auth import AuthUser, HasPermissionAnyMiddleware
26 from kallithea.lib.auth import AuthUser, HasPermissionAnyMiddleware
27 from kallithea.lib.utils2 import set_hook_environment
27 from kallithea.lib.utils2 import set_hook_environment
28 from kallithea.model import meta
28 from kallithea.model import db, meta
29 from kallithea.model.db import Repository, User, UserSshKeys
30
29
31
30
32 log = logging.getLogger(__name__)
31 log = logging.getLogger(__name__)
@@ -62,7 +61,7 b' class BaseSshHandler(object):'
62 """Verify basic sanity of the repository, and that the user is
61 """Verify basic sanity of the repository, and that the user is
63 valid and has access - then serve the native VCS protocol for
62 valid and has access - then serve the native VCS protocol for
64 repository access."""
63 repository access."""
65 dbuser = User.get(user_id)
64 dbuser = db.User.get(user_id)
66 if dbuser is None:
65 if dbuser is None:
67 self.exit('User %r not found' % user_id)
66 self.exit('User %r not found' % user_id)
68 self.authuser = AuthUser.make(dbuser=dbuser, ip_addr=client_ip)
67 self.authuser = AuthUser.make(dbuser=dbuser, ip_addr=client_ip)
@@ -70,7 +69,7 b' class BaseSshHandler(object):'
70 if self.authuser is None: # not ok ... but already kind of authenticated by SSH ... but not really not authorized ...
69 if self.authuser is None: # not ok ... but already kind of authenticated by SSH ... but not really not authorized ...
71 self.exit('User %s from %s cannot be authorized' % (dbuser.username, client_ip))
70 self.exit('User %s from %s cannot be authorized' % (dbuser.username, client_ip))
72
71
73 ssh_key = UserSshKeys.get(key_id)
72 ssh_key = db.UserSshKeys.get(key_id)
74 if ssh_key is None:
73 if ssh_key is None:
75 self.exit('SSH key %r not found' % key_id)
74 self.exit('SSH key %r not found' % key_id)
76 ssh_key.last_seen = datetime.datetime.now()
75 ssh_key.last_seen = datetime.datetime.now()
@@ -84,7 +83,7 b' class BaseSshHandler(object):'
84 else:
83 else:
85 self.exit('Access to %r denied' % self.repo_name)
84 self.exit('Access to %r denied' % self.repo_name)
86
85
87 self.db_repo = Repository.get_by_repo_name(self.repo_name)
86 self.db_repo = db.Repository.get_by_repo_name(self.repo_name)
88 if self.db_repo is None:
87 if self.db_repo is None:
89 self.exit("Repository '%s' not found" % self.repo_name)
88 self.exit("Repository '%s' not found" % self.repo_name)
90 assert self.db_repo.repo_name == self.repo_name
89 assert self.db_repo.repo_name == self.repo_name
@@ -29,8 +29,7 b' import logging'
29 import time
29 import time
30
30
31 from kallithea.lib.utils2 import generate_api_key
31 from kallithea.lib.utils2 import generate_api_key
32 from kallithea.model import meta
32 from kallithea.model import db, meta
33 from kallithea.model.db import User, UserApiKeys
34
33
35
34
36 log = logging.getLogger(__name__)
35 log = logging.getLogger(__name__)
@@ -44,9 +43,9 b' class ApiKeyModel(object):'
44 :param description: description of ApiKey
43 :param description: description of ApiKey
45 :param lifetime: expiration time in seconds
44 :param lifetime: expiration time in seconds
46 """
45 """
47 user = User.guess_instance(user)
46 user = db.User.guess_instance(user)
48
47
49 new_api_key = UserApiKeys()
48 new_api_key = db.UserApiKeys()
50 new_api_key.api_key = generate_api_key()
49 new_api_key.api_key = generate_api_key()
51 new_api_key.user_id = user.user_id
50 new_api_key.user_id = user.user_id
52 new_api_key.description = description
51 new_api_key.description = description
@@ -60,19 +59,19 b' class ApiKeyModel(object):'
60 Deletes given api_key, if user is set it also filters the object for
59 Deletes given api_key, if user is set it also filters the object for
61 deletion by given user.
60 deletion by given user.
62 """
61 """
63 api_key = UserApiKeys.query().filter(UserApiKeys.api_key == api_key)
62 api_key = db.UserApiKeys.query().filter(db.UserApiKeys.api_key == api_key)
64
63
65 if user is not None:
64 if user is not None:
66 user = User.guess_instance(user)
65 user = db.User.guess_instance(user)
67 api_key = api_key.filter(UserApiKeys.user_id == user.user_id)
66 api_key = api_key.filter(db.UserApiKeys.user_id == user.user_id)
68
67
69 api_key = api_key.scalar()
68 api_key = api_key.scalar()
70 meta.Session().delete(api_key)
69 meta.Session().delete(api_key)
71
70
72 def get_api_keys(self, user, show_expired=True):
71 def get_api_keys(self, user, show_expired=True):
73 user = User.guess_instance(user)
72 user = db.User.guess_instance(user)
74 user_api_keys = UserApiKeys.query() \
73 user_api_keys = db.UserApiKeys.query() \
75 .filter(UserApiKeys.user_id == user.user_id)
74 .filter(db.UserApiKeys.user_id == user.user_id)
76 if not show_expired:
75 if not show_expired:
77 user_api_keys = user_api_keys.filter_by(is_expired=False)
76 user_api_keys = user_api_keys.filter_by(is_expired=False)
78 return user_api_keys
77 return user_api_keys
@@ -29,8 +29,7 b' import logging'
29
29
30 from sqlalchemy.orm import joinedload
30 from sqlalchemy.orm import joinedload
31
31
32 from kallithea.model import meta
32 from kallithea.model import db, meta
33 from kallithea.model.db import ChangesetStatus, PullRequest, Repository, User
34
33
35
34
36 log = logging.getLogger(__name__)
35 log = logging.getLogger(__name__)
@@ -40,22 +39,22 b' class ChangesetStatusModel(object):'
40
39
41 def _get_status_query(self, repo, revision, pull_request,
40 def _get_status_query(self, repo, revision, pull_request,
42 with_revisions=False):
41 with_revisions=False):
43 repo = Repository.guess_instance(repo)
42 repo = db.Repository.guess_instance(repo)
44
43
45 q = ChangesetStatus.query() \
44 q = db.ChangesetStatus.query() \
46 .filter(ChangesetStatus.repo == repo)
45 .filter(db.ChangesetStatus.repo == repo)
47 if not with_revisions:
46 if not with_revisions:
48 # only report the latest vote across all users! TODO: be smarter!
47 # only report the latest vote across all users! TODO: be smarter!
49 q = q.filter(ChangesetStatus.version == 0)
48 q = q.filter(db.ChangesetStatus.version == 0)
50
49
51 if revision:
50 if revision:
52 q = q.filter(ChangesetStatus.revision == revision)
51 q = q.filter(db.ChangesetStatus.revision == revision)
53 elif pull_request:
52 elif pull_request:
54 pull_request = PullRequest.guess_instance(pull_request)
53 pull_request = db.PullRequest.guess_instance(pull_request)
55 q = q.filter(ChangesetStatus.pull_request == pull_request)
54 q = q.filter(db.ChangesetStatus.pull_request == pull_request)
56 else:
55 else:
57 raise Exception('Please specify revision or pull_request')
56 raise Exception('Please specify revision or pull_request')
58 q = q.order_by(ChangesetStatus.version.asc())
57 q = q.order_by(db.ChangesetStatus.version.asc())
59 return q
58 return q
60
59
61 def _calculate_status(self, statuses):
60 def _calculate_status(self, statuses):
@@ -65,15 +64,15 b' class ChangesetStatusModel(object):'
65 """
64 """
66
65
67 if not statuses:
66 if not statuses:
68 return ChangesetStatus.STATUS_UNDER_REVIEW
67 return db.ChangesetStatus.STATUS_UNDER_REVIEW
69
68
70 if all(st and st.status == ChangesetStatus.STATUS_APPROVED for st in statuses):
69 if all(st and st.status == db.ChangesetStatus.STATUS_APPROVED for st in statuses):
71 return ChangesetStatus.STATUS_APPROVED
70 return db.ChangesetStatus.STATUS_APPROVED
72
71
73 if any(st and st.status == ChangesetStatus.STATUS_REJECTED for st in statuses):
72 if any(st and st.status == db.ChangesetStatus.STATUS_REJECTED for st in statuses):
74 return ChangesetStatus.STATUS_REJECTED
73 return db.ChangesetStatus.STATUS_REJECTED
75
74
76 return ChangesetStatus.STATUS_UNDER_REVIEW
75 return db.ChangesetStatus.STATUS_UNDER_REVIEW
77
76
78 def calculate_pull_request_result(self, pull_request):
77 def calculate_pull_request_result(self, pull_request):
79 """
78 """
@@ -95,9 +94,9 b' class ChangesetStatusModel(object):'
95 for user in pull_request.get_reviewer_users():
94 for user in pull_request.get_reviewer_users():
96 st = cs_statuses.get(user.username)
95 st = cs_statuses.get(user.username)
97 relevant_statuses.append(st)
96 relevant_statuses.append(st)
98 status = ChangesetStatus.STATUS_NOT_REVIEWED if st is None else st.status
97 status = db.ChangesetStatus.STATUS_NOT_REVIEWED if st is None else st.status
99 if status in (ChangesetStatus.STATUS_NOT_REVIEWED,
98 if status in (db.ChangesetStatus.STATUS_NOT_REVIEWED,
100 ChangesetStatus.STATUS_UNDER_REVIEW):
99 db.ChangesetStatus.STATUS_UNDER_REVIEW):
101 pull_request_pending_reviewers.append(user)
100 pull_request_pending_reviewers.append(user)
102 pull_request_reviewers.append((user, status))
101 pull_request_reviewers.append((user, status))
103
102
@@ -131,7 +130,7 b' class ChangesetStatusModel(object):'
131 # returned from pull_request
130 # returned from pull_request
132 status = q.first()
131 status = q.first()
133 if as_str:
132 if as_str:
134 return str(status.status) if status else ChangesetStatus.DEFAULT
133 return str(status.status) if status else db.ChangesetStatus.DEFAULT
135 return status
134 return status
136
135
137 def set_status(self, repo, status, user, comment, revision=None,
136 def set_status(self, repo, status, user, comment, revision=None,
@@ -147,20 +146,20 b' class ChangesetStatusModel(object):'
147 :param revision:
146 :param revision:
148 :param pull_request:
147 :param pull_request:
149 """
148 """
150 repo = Repository.guess_instance(repo)
149 repo = db.Repository.guess_instance(repo)
151
150
152 q = ChangesetStatus.query()
151 q = db.ChangesetStatus.query()
153 if revision is not None:
152 if revision is not None:
154 assert pull_request is None
153 assert pull_request is None
155 q = q.filter(ChangesetStatus.repo == repo)
154 q = q.filter(db.ChangesetStatus.repo == repo)
156 q = q.filter(ChangesetStatus.revision == revision)
155 q = q.filter(db.ChangesetStatus.revision == revision)
157 revisions = [revision]
156 revisions = [revision]
158 else:
157 else:
159 assert pull_request is not None
158 assert pull_request is not None
160 pull_request = PullRequest.guess_instance(pull_request)
159 pull_request = db.PullRequest.guess_instance(pull_request)
161 repo = pull_request.org_repo
160 repo = pull_request.org_repo
162 q = q.filter(ChangesetStatus.repo == repo)
161 q = q.filter(db.ChangesetStatus.repo == repo)
163 q = q.filter(ChangesetStatus.revision.in_(pull_request.revisions))
162 q = q.filter(db.ChangesetStatus.revision.in_(pull_request.revisions))
164 revisions = pull_request.revisions
163 revisions = pull_request.revisions
165 cur_statuses = q.all()
164 cur_statuses = q.all()
166
165
@@ -170,10 +169,10 b' class ChangesetStatusModel(object):'
170
169
171 new_statuses = []
170 new_statuses = []
172 for rev in revisions:
171 for rev in revisions:
173 new_status = ChangesetStatus()
172 new_status = db.ChangesetStatus()
174 new_status.version = 0 # default
173 new_status.version = 0 # default
175 new_status.author = User.guess_instance(user)
174 new_status.author = db.User.guess_instance(user)
176 new_status.repo = Repository.guess_instance(repo)
175 new_status.repo = db.Repository.guess_instance(repo)
177 new_status.status = status
176 new_status.status = status
178 new_status.comment = comment
177 new_status.comment = comment
179 new_status.revision = rev
178 new_status.revision = rev
@@ -32,8 +32,7 b' from tg.i18n import ugettext as _'
32
32
33 from kallithea.lib import helpers as h
33 from kallithea.lib import helpers as h
34 from kallithea.lib.utils import extract_mentioned_users
34 from kallithea.lib.utils import extract_mentioned_users
35 from kallithea.model import meta
35 from kallithea.model import db, meta
36 from kallithea.model.db import ChangesetComment, PullRequest, Repository, User
37 from kallithea.model.notification import NotificationModel
36 from kallithea.model.notification import NotificationModel
38
37
39
38
@@ -41,15 +40,15 b' log = logging.getLogger(__name__)'
41
40
42
41
43 def _list_changeset_commenters(revision):
42 def _list_changeset_commenters(revision):
44 return (meta.Session().query(User)
43 return (meta.Session().query(db.User)
45 .join(ChangesetComment.author)
44 .join(db.ChangesetComment.author)
46 .filter(ChangesetComment.revision == revision)
45 .filter(db.ChangesetComment.revision == revision)
47 .all())
46 .all())
48
47
49 def _list_pull_request_commenters(pull_request):
48 def _list_pull_request_commenters(pull_request):
50 return (meta.Session().query(User)
49 return (meta.Session().query(db.User)
51 .join(ChangesetComment.author)
50 .join(db.ChangesetComment.author)
52 .filter(ChangesetComment.pull_request_id == pull_request.pull_request_id)
51 .filter(db.ChangesetComment.pull_request_id == pull_request.pull_request_id)
53 .all())
52 .all())
54
53
55
54
@@ -88,7 +87,7 b' class ChangesetCommentsModel(object):'
88 # get the current participants of this changeset
87 # get the current participants of this changeset
89 recipients = _list_changeset_commenters(revision)
88 recipients = _list_changeset_commenters(revision)
90 # add changeset author if it's known locally
89 # add changeset author if it's known locally
91 cs_author = User.get_from_cs_author(cs.author)
90 cs_author = db.User.get_from_cs_author(cs.author)
92 if not cs_author:
91 if not cs_author:
93 # use repo owner if we cannot extract the author correctly
92 # use repo owner if we cannot extract the author correctly
94 # FIXME: just use committer name even if not a user
93 # FIXME: just use committer name even if not a user
@@ -176,9 +175,9 b' class ChangesetCommentsModel(object):'
176 log.warning('Missing text for comment, skipping...')
175 log.warning('Missing text for comment, skipping...')
177 return None
176 return None
178
177
179 repo = Repository.guess_instance(repo)
178 repo = db.Repository.guess_instance(repo)
180 author = User.guess_instance(author)
179 author = db.User.guess_instance(author)
181 comment = ChangesetComment()
180 comment = db.ChangesetComment()
182 comment.repo = repo
181 comment.repo = repo
183 comment.author = author
182 comment.author = author
184 comment.text = text
183 comment.text = text
@@ -188,7 +187,7 b' class ChangesetCommentsModel(object):'
188 if revision is not None:
187 if revision is not None:
189 comment.revision = revision
188 comment.revision = revision
190 elif pull_request is not None:
189 elif pull_request is not None:
191 pull_request = PullRequest.guess_instance(pull_request)
190 pull_request = db.PullRequest.guess_instance(pull_request)
192 comment.pull_request = pull_request
191 comment.pull_request = pull_request
193 else:
192 else:
194 raise Exception('Please specify revision or pull_request_id')
193 raise Exception('Please specify revision or pull_request_id')
@@ -229,7 +228,7 b' class ChangesetCommentsModel(object):'
229 return comment
228 return comment
230
229
231 def delete(self, comment):
230 def delete(self, comment):
232 comment = ChangesetComment.guess_instance(comment)
231 comment = db.ChangesetComment.guess_instance(comment)
233 meta.Session().delete(comment)
232 meta.Session().delete(comment)
234
233
235 return comment
234 return comment
@@ -270,34 +269,34 b' class ChangesetCommentsModel(object):'
270 if inline is None and f_path is not None:
269 if inline is None and f_path is not None:
271 raise Exception("f_path only makes sense for inline comments.")
270 raise Exception("f_path only makes sense for inline comments.")
272
271
273 q = meta.Session().query(ChangesetComment)
272 q = meta.Session().query(db.ChangesetComment)
274
273
275 if inline:
274 if inline:
276 if f_path is not None:
275 if f_path is not None:
277 # inline comments for a given file...
276 # inline comments for a given file...
278 q = q.filter(ChangesetComment.f_path == f_path)
277 q = q.filter(db.ChangesetComment.f_path == f_path)
279 if line_no is None:
278 if line_no is None:
280 # ... on any line
279 # ... on any line
281 q = q.filter(ChangesetComment.line_no != None)
280 q = q.filter(db.ChangesetComment.line_no != None)
282 else:
281 else:
283 # ... on specific line
282 # ... on specific line
284 q = q.filter(ChangesetComment.line_no == line_no)
283 q = q.filter(db.ChangesetComment.line_no == line_no)
285 else:
284 else:
286 # all inline comments
285 # all inline comments
287 q = q.filter(ChangesetComment.line_no != None) \
286 q = q.filter(db.ChangesetComment.line_no != None) \
288 .filter(ChangesetComment.f_path != None)
287 .filter(db.ChangesetComment.f_path != None)
289 else:
288 else:
290 # all general comments
289 # all general comments
291 q = q.filter(ChangesetComment.line_no == None) \
290 q = q.filter(db.ChangesetComment.line_no == None) \
292 .filter(ChangesetComment.f_path == None)
291 .filter(db.ChangesetComment.f_path == None)
293
292
294 if revision is not None:
293 if revision is not None:
295 q = q.filter(ChangesetComment.revision == revision) \
294 q = q.filter(db.ChangesetComment.revision == revision) \
296 .filter(ChangesetComment.repo_id == repo_id)
295 .filter(db.ChangesetComment.repo_id == repo_id)
297 elif pull_request is not None:
296 elif pull_request is not None:
298 pull_request = PullRequest.guess_instance(pull_request)
297 pull_request = db.PullRequest.guess_instance(pull_request)
299 q = q.filter(ChangesetComment.pull_request == pull_request)
298 q = q.filter(db.ChangesetComment.pull_request == pull_request)
300 else:
299 else:
301 raise Exception('Please specify either revision or pull_request')
300 raise Exception('Please specify either revision or pull_request')
302
301
303 return q.order_by(ChangesetComment.created_on).all()
302 return q.order_by(db.ChangesetComment.created_on).all()
@@ -34,8 +34,7 b' import traceback'
34
34
35 from kallithea.lib import ext_json
35 from kallithea.lib import ext_json
36 from kallithea.lib.utils2 import AttributeDict, ascii_bytes, safe_int, time_to_datetime
36 from kallithea.lib.utils2 import AttributeDict, ascii_bytes, safe_int, time_to_datetime
37 from kallithea.model import meta
37 from kallithea.model import db, meta
38 from kallithea.model.db import Gist, User
39 from kallithea.model.repo import RepoModel
38 from kallithea.model.repo import RepoModel
40 from kallithea.model.scm import ScmModel
39 from kallithea.model.scm import ScmModel
41
40
@@ -86,7 +85,7 b' class GistModel(object):'
86 f.write(ascii_bytes(ext_json.dumps(metadata)))
85 f.write(ascii_bytes(ext_json.dumps(metadata)))
87
86
88 def get_gist(self, gist):
87 def get_gist(self, gist):
89 return Gist.guess_instance(gist)
88 return db.Gist.guess_instance(gist)
90
89
91 def get_gist_files(self, gist_access_id, revision=None):
90 def get_gist_files(self, gist_access_id, revision=None):
92 """
91 """
@@ -94,12 +93,12 b' class GistModel(object):'
94
93
95 :param gist_access_id:
94 :param gist_access_id:
96 """
95 """
97 repo = Gist.get_by_access_id(gist_access_id)
96 repo = db.Gist.get_by_access_id(gist_access_id)
98 cs = repo.scm_instance.get_changeset(revision)
97 cs = repo.scm_instance.get_changeset(revision)
99 return cs, [n for n in cs.get_node('/')]
98 return cs, [n for n in cs.get_node('/')]
100
99
101 def create(self, description, owner, ip_addr, gist_mapping,
100 def create(self, description, owner, ip_addr, gist_mapping,
102 gist_type=Gist.GIST_PUBLIC, lifetime=-1):
101 gist_type=db.Gist.GIST_PUBLIC, lifetime=-1):
103 """
102 """
104
103
105 :param description: description of the gist
104 :param description: description of the gist
@@ -108,7 +107,7 b' class GistModel(object):'
108 :param gist_type: type of gist private/public
107 :param gist_type: type of gist private/public
109 :param lifetime: in minutes, -1 == forever
108 :param lifetime: in minutes, -1 == forever
110 """
109 """
111 owner = User.guess_instance(owner)
110 owner = db.User.guess_instance(owner)
112 gist_access_id = make_gist_access_id()
111 gist_access_id = make_gist_access_id()
113 lifetime = safe_int(lifetime, -1)
112 lifetime = safe_int(lifetime, -1)
114 gist_expires = time.time() + (lifetime * 60) if lifetime != -1 else -1
113 gist_expires = time.time() + (lifetime * 60) if lifetime != -1 else -1
@@ -116,7 +115,7 b' class GistModel(object):'
116 time_to_datetime(gist_expires)
115 time_to_datetime(gist_expires)
117 if gist_expires != -1 else 'forever')
116 if gist_expires != -1 else 'forever')
118 # create the Database version
117 # create the Database version
119 gist = Gist()
118 gist = db.Gist()
120 gist.gist_description = description
119 gist.gist_description = description
121 gist.gist_access_id = gist_access_id
120 gist.gist_access_id = gist_access_id
122 gist.owner_id = owner.user_id
121 gist.owner_id = owner.user_id
@@ -124,7 +123,7 b' class GistModel(object):'
124 gist.gist_type = gist_type
123 gist.gist_type = gist_type
125 meta.Session().add(gist)
124 meta.Session().add(gist)
126 meta.Session().flush() # make database assign gist.gist_id
125 meta.Session().flush() # make database assign gist.gist_id
127 if gist_type == Gist.GIST_PUBLIC:
126 if gist_type == db.Gist.GIST_PUBLIC:
128 # use DB ID for easy to use GIST ID
127 # use DB ID for easy to use GIST ID
129 gist.gist_access_id = str(gist.gist_id)
128 gist.gist_access_id = str(gist.gist_id)
130
129
@@ -171,7 +170,7 b' class GistModel(object):'
171 return gist
170 return gist
172
171
173 def delete(self, gist, fs_remove=True):
172 def delete(self, gist, fs_remove=True):
174 gist = Gist.guess_instance(gist)
173 gist = db.Gist.guess_instance(gist)
175 try:
174 try:
176 meta.Session().delete(gist)
175 meta.Session().delete(gist)
177 if fs_remove:
176 if fs_remove:
@@ -184,7 +183,7 b' class GistModel(object):'
184
183
185 def update(self, gist, description, owner, ip_addr, gist_mapping, gist_type,
184 def update(self, gist, description, owner, ip_addr, gist_mapping, gist_type,
186 lifetime):
185 lifetime):
187 gist = Gist.guess_instance(gist)
186 gist = db.Gist.guess_instance(gist)
188 gist_repo = gist.scm_instance
187 gist_repo = gist.scm_instance
189
188
190 lifetime = safe_int(lifetime, -1)
189 lifetime = safe_int(lifetime, -1)
@@ -34,7 +34,7 b' from tg import tmpl_context as c'
34 from tg.i18n import ugettext as _
34 from tg.i18n import ugettext as _
35
35
36 from kallithea.lib import helpers as h
36 from kallithea.lib import helpers as h
37 from kallithea.model.db import User
37 from kallithea.model import db
38
38
39
39
40 log = logging.getLogger(__name__)
40 log = logging.getLogger(__name__)
@@ -71,12 +71,12 b' class NotificationModel(object):'
71 if recipients and not getattr(recipients, '__iter__', False):
71 if recipients and not getattr(recipients, '__iter__', False):
72 raise Exception('recipients must be a list or iterable')
72 raise Exception('recipients must be a list or iterable')
73
73
74 created_by_obj = User.guess_instance(created_by)
74 created_by_obj = db.User.guess_instance(created_by)
75
75
76 recipients_objs = set()
76 recipients_objs = set()
77 if recipients:
77 if recipients:
78 for u in recipients:
78 for u in recipients:
79 obj = User.guess_instance(u)
79 obj = db.User.guess_instance(u)
80 if obj is not None:
80 if obj is not None:
81 recipients_objs.add(obj)
81 recipients_objs.add(obj)
82 else:
82 else:
@@ -87,7 +87,7 b' class NotificationModel(object):'
87 )
87 )
88 elif recipients is None:
88 elif recipients is None:
89 # empty recipients means to all admins
89 # empty recipients means to all admins
90 recipients_objs = User.query().filter(User.admin == True).all()
90 recipients_objs = db.User.query().filter(db.User.admin == True).all()
91 log.debug('sending notifications %s to admins: %s',
91 log.debug('sending notifications %s to admins: %s',
92 type_, recipients_objs
92 type_, recipients_objs
93 )
93 )
@@ -32,8 +32,7 b' import traceback'
32 from sqlalchemy.exc import DatabaseError
32 from sqlalchemy.exc import DatabaseError
33
33
34 from kallithea.lib.utils2 import asbool
34 from kallithea.lib.utils2 import asbool
35 from kallithea.model import meta
35 from kallithea.model import db, meta
36 from kallithea.model.db import Permission, User, UserRepoGroupToPerm, UserRepoToPerm, UserToPerm, UserUserGroupToPerm
37
36
38
37
39 log = logging.getLogger(__name__)
38 log = logging.getLogger(__name__)
@@ -48,9 +47,9 b' class PermissionModel(object):'
48 """
47 """
49 Create permissions for whole system
48 Create permissions for whole system
50 """
49 """
51 for p in Permission.PERMS:
50 for p in db.Permission.PERMS:
52 if not Permission.get_by_key(p[0]):
51 if not db.Permission.get_by_key(p[0]):
53 new_perm = Permission()
52 new_perm = db.Permission()
54 new_perm.permission_name = p[0]
53 new_perm.permission_name = p[0]
55 meta.Session().add(new_perm)
54 meta.Session().add(new_perm)
56
55
@@ -62,18 +61,18 b' class PermissionModel(object):'
62
61
63 :param user:
62 :param user:
64 """
63 """
65 user = User.guess_instance(user)
64 user = db.User.guess_instance(user)
66
65
67 def _make_perm(perm):
66 def _make_perm(perm):
68 new_perm = UserToPerm()
67 new_perm = db.UserToPerm()
69 new_perm.user = user
68 new_perm.user = user
70 new_perm.permission = Permission.get_by_key(perm)
69 new_perm.permission = db.Permission.get_by_key(perm)
71 return new_perm
70 return new_perm
72
71
73 def _get_group(perm_name):
72 def _get_group(perm_name):
74 return '.'.join(perm_name.split('.')[:1])
73 return '.'.join(perm_name.split('.')[:1])
75
74
76 perms = UserToPerm.query().filter(UserToPerm.user == user).all()
75 perms = db.UserToPerm.query().filter(db.UserToPerm.user == user).all()
77 defined_perms_groups = set(_get_group(x.permission.permission_name) for x in perms)
76 defined_perms_groups = set(_get_group(x.permission.permission_name) for x in perms)
78 log.debug('GOT ALREADY DEFINED:%s', perms)
77 log.debug('GOT ALREADY DEFINED:%s', perms)
79
78
@@ -84,7 +83,7 b' class PermissionModel(object):'
84 defined_perms_groups = []
83 defined_perms_groups = []
85 # For every default permission that needs to be created, we check if
84 # For every default permission that needs to be created, we check if
86 # its group is already defined. If it's not, we create default permission.
85 # its group is already defined. If it's not, we create default permission.
87 for perm_name in Permission.DEFAULT_USER_PERMISSIONS:
86 for perm_name in db.Permission.DEFAULT_USER_PERMISSIONS:
88 gr = _get_group(perm_name)
87 gr = _get_group(perm_name)
89 if gr not in defined_perms_groups:
88 if gr not in defined_perms_groups:
90 log.debug('GR:%s not found, creating permission %s',
89 log.debug('GR:%s not found, creating permission %s',
@@ -93,7 +92,7 b' class PermissionModel(object):'
93 meta.Session().add(new_perm)
92 meta.Session().add(new_perm)
94
93
95 def update(self, form_result):
94 def update(self, form_result):
96 perm_user = User.get_by_username(username=form_result['perm_user_name'])
95 perm_user = db.User.get_by_username(username=form_result['perm_user_name'])
97
96
98 try:
97 try:
99 # stage 1 set anonymous access
98 # stage 1 set anonymous access
@@ -103,15 +102,15 b' class PermissionModel(object):'
103 # stage 2 reset defaults and set them from form data
102 # stage 2 reset defaults and set them from form data
104 def _make_new(usr, perm_name):
103 def _make_new(usr, perm_name):
105 log.debug('Creating new permission:%s', perm_name)
104 log.debug('Creating new permission:%s', perm_name)
106 new = UserToPerm()
105 new = db.UserToPerm()
107 new.user = usr
106 new.user = usr
108 new.permission = Permission.get_by_key(perm_name)
107 new.permission = db.Permission.get_by_key(perm_name)
109 return new
108 return new
110 # clear current entries, to make this function idempotent
109 # clear current entries, to make this function idempotent
111 # it will fix even if we define more permissions or permissions
110 # it will fix even if we define more permissions or permissions
112 # are somehow missing
111 # are somehow missing
113 u2p = UserToPerm.query() \
112 u2p = db.UserToPerm.query() \
114 .filter(UserToPerm.user == perm_user) \
113 .filter(db.UserToPerm.user == perm_user) \
115 .all()
114 .all()
116 for p in u2p:
115 for p in u2p:
117 meta.Session().delete(p)
116 meta.Session().delete(p)
@@ -130,10 +129,10 b' class PermissionModel(object):'
130 # stage 3 update all default permissions for repos if checked
129 # stage 3 update all default permissions for repos if checked
131 if form_result['overwrite_default_repo']:
130 if form_result['overwrite_default_repo']:
132 _def_name = form_result['default_repo_perm'].split('repository.')[-1]
131 _def_name = form_result['default_repo_perm'].split('repository.')[-1]
133 _def = Permission.get_by_key('repository.' + _def_name)
132 _def = db.Permission.get_by_key('repository.' + _def_name)
134 # repos
133 # repos
135 for r2p in UserRepoToPerm.query() \
134 for r2p in db.UserRepoToPerm.query() \
136 .filter(UserRepoToPerm.user == perm_user) \
135 .filter(db.UserRepoToPerm.user == perm_user) \
137 .all():
136 .all():
138
137
139 # don't reset PRIVATE repositories
138 # don't reset PRIVATE repositories
@@ -143,18 +142,18 b' class PermissionModel(object):'
143 if form_result['overwrite_default_group']:
142 if form_result['overwrite_default_group']:
144 _def_name = form_result['default_group_perm'].split('group.')[-1]
143 _def_name = form_result['default_group_perm'].split('group.')[-1]
145 # groups
144 # groups
146 _def = Permission.get_by_key('group.' + _def_name)
145 _def = db.Permission.get_by_key('group.' + _def_name)
147 for g2p in UserRepoGroupToPerm.query() \
146 for g2p in db.UserRepoGroupToPerm.query() \
148 .filter(UserRepoGroupToPerm.user == perm_user) \
147 .filter(db.UserRepoGroupToPerm.user == perm_user) \
149 .all():
148 .all():
150 g2p.permission = _def
149 g2p.permission = _def
151
150
152 if form_result['overwrite_default_user_group']:
151 if form_result['overwrite_default_user_group']:
153 _def_name = form_result['default_user_group_perm'].split('usergroup.')[-1]
152 _def_name = form_result['default_user_group_perm'].split('usergroup.')[-1]
154 # groups
153 # groups
155 _def = Permission.get_by_key('usergroup.' + _def_name)
154 _def = db.Permission.get_by_key('usergroup.' + _def_name)
156 for g2p in UserUserGroupToPerm.query() \
155 for g2p in db.UserUserGroupToPerm.query() \
157 .filter(UserUserGroupToPerm.user == perm_user) \
156 .filter(db.UserUserGroupToPerm.user == perm_user) \
158 .all():
157 .all():
159 g2p.permission = _def
158 g2p.permission = _def
160
159
@@ -36,8 +36,7 b' from kallithea.lib import helpers as h'
36 from kallithea.lib.hooks import log_create_pullrequest
36 from kallithea.lib.hooks import log_create_pullrequest
37 from kallithea.lib.utils import extract_mentioned_users
37 from kallithea.lib.utils import extract_mentioned_users
38 from kallithea.lib.utils2 import ascii_bytes
38 from kallithea.lib.utils2 import ascii_bytes
39 from kallithea.model import meta
39 from kallithea.model import db, meta
40 from kallithea.model.db import ChangesetStatus, PullRequest, PullRequestReviewer, User
41 from kallithea.model.notification import NotificationModel
40 from kallithea.model.notification import NotificationModel
42
41
43
42
@@ -60,10 +59,10 b' class PullRequestModel(object):'
60 mention_recipients = set(mention_recipients) - reviewers
59 mention_recipients = set(mention_recipients) - reviewers
61 _assert_valid_reviewers(mention_recipients)
60 _assert_valid_reviewers(mention_recipients)
62
61
63 redundant_reviewers = set(User.query() \
62 redundant_reviewers = set(db.User.query() \
64 .join(PullRequestReviewer) \
63 .join(db.PullRequestReviewer) \
65 .filter(PullRequestReviewer.pull_request == pr) \
64 .filter(db.PullRequestReviewer.pull_request == pr) \
66 .filter(PullRequestReviewer.user_id.in_(r.user_id for r in reviewers))
65 .filter(db.PullRequestReviewer.user_id.in_(r.user_id for r in reviewers))
67 .all())
66 .all())
68
67
69 if redundant_reviewers:
68 if redundant_reviewers:
@@ -73,7 +72,7 b' class PullRequestModel(object):'
73
72
74 log.debug('Adding reviewers to pull request %s: %s', pr.pull_request_id, reviewers)
73 log.debug('Adding reviewers to pull request %s: %s', pr.pull_request_id, reviewers)
75 for reviewer in reviewers:
74 for reviewer in reviewers:
76 prr = PullRequestReviewer(reviewer, pr)
75 prr = db.PullRequestReviewer(reviewer, pr)
77 meta.Session().add(prr)
76 meta.Session().add(prr)
78
77
79 # notification to reviewers
78 # notification to reviewers
@@ -143,13 +142,13 b' class PullRequestModel(object):'
143 if not reviewers:
142 if not reviewers:
144 return # avoid SQLAlchemy warning about empty sequence for IN-predicate
143 return # avoid SQLAlchemy warning about empty sequence for IN-predicate
145
144
146 PullRequestReviewer.query() \
145 db.PullRequestReviewer.query() \
147 .filter_by(pull_request=pull_request) \
146 .filter_by(pull_request=pull_request) \
148 .filter(PullRequestReviewer.user_id.in_(r.user_id for r in reviewers)) \
147 .filter(db.PullRequestReviewer.user_id.in_(r.user_id for r in reviewers)) \
149 .delete(synchronize_session='fetch') # the default of 'evaluate' is not available
148 .delete(synchronize_session='fetch') # the default of 'evaluate' is not available
150
149
151 def delete(self, pull_request):
150 def delete(self, pull_request):
152 pull_request = PullRequest.guess_instance(pull_request)
151 pull_request = db.PullRequest.guess_instance(pull_request)
153 meta.Session().delete(pull_request)
152 meta.Session().delete(pull_request)
154 if pull_request.org_repo.scm_instance.alias == 'git':
153 if pull_request.org_repo.scm_instance.alias == 'git':
155 # remove a ref under refs/pull/ so that commits can be garbage-collected
154 # remove a ref under refs/pull/ so that commits can be garbage-collected
@@ -159,8 +158,8 b' class PullRequestModel(object):'
159 pass
158 pass
160
159
161 def close_pull_request(self, pull_request):
160 def close_pull_request(self, pull_request):
162 pull_request = PullRequest.guess_instance(pull_request)
161 pull_request = db.PullRequest.guess_instance(pull_request)
163 pull_request.status = PullRequest.STATUS_CLOSED
162 pull_request.status = db.PullRequest.STATUS_CLOSED
164 pull_request.updated_on = datetime.datetime.now()
163 pull_request.updated_on = datetime.datetime.now()
165
164
166
165
@@ -254,9 +253,9 b' class CreatePullRequestAction(object):'
254 raise self.Unauthorized(_('You are not authorized to create the pull request'))
253 raise self.Unauthorized(_('You are not authorized to create the pull request'))
255
254
256 def execute(self):
255 def execute(self):
257 created_by = User.get(request.authuser.user_id)
256 created_by = db.User.get(request.authuser.user_id)
258
257
259 pr = PullRequest()
258 pr = db.PullRequest()
260 pr.org_repo = self.org_repo
259 pr.org_repo = self.org_repo
261 pr.org_ref = self.org_ref
260 pr.org_ref = self.org_ref
262 pr.other_repo = self.other_repo
261 pr.other_repo = self.other_repo
@@ -281,11 +280,11 b' class CreatePullRequestAction(object):'
281 author=created_by,
280 author=created_by,
282 pull_request=pr,
281 pull_request=pr,
283 send_email=False,
282 send_email=False,
284 status_change=ChangesetStatus.STATUS_UNDER_REVIEW,
283 status_change=db.ChangesetStatus.STATUS_UNDER_REVIEW,
285 )
284 )
286 ChangesetStatusModel().set_status(
285 ChangesetStatusModel().set_status(
287 self.org_repo,
286 self.org_repo,
288 ChangesetStatus.STATUS_UNDER_REVIEW,
287 db.ChangesetStatus.STATUS_UNDER_REVIEW,
289 created_by,
288 created_by,
290 comment,
289 comment,
291 pull_request=pr,
290 pull_request=pr,
@@ -40,9 +40,7 b' from kallithea.lib.hooks import log_dele'
40 from kallithea.lib.utils import is_valid_repo_uri, make_ui
40 from kallithea.lib.utils import is_valid_repo_uri, make_ui
41 from kallithea.lib.utils2 import LazyProperty, get_current_authuser, obfuscate_url_pw, remove_prefix
41 from kallithea.lib.utils2 import LazyProperty, get_current_authuser, obfuscate_url_pw, remove_prefix
42 from kallithea.lib.vcs.backends import get_backend
42 from kallithea.lib.vcs.backends import get_backend
43 from kallithea.model import meta
43 from kallithea.model import db, meta
44 from kallithea.model.db import (Permission, RepoGroup, Repository, RepositoryField, Statistics, Ui, User, UserGroup, UserGroupRepoGroupToPerm,
45 UserGroupRepoToPerm, UserRepoGroupToPerm, UserRepoToPerm)
46
44
47
45
48 log = logging.getLogger(__name__)
46 log = logging.getLogger(__name__)
@@ -53,7 +51,7 b' class RepoModel(object):'
53 def _create_default_perms(self, repository, private):
51 def _create_default_perms(self, repository, private):
54 # create default permission
52 # create default permission
55 default = 'repository.read'
53 default = 'repository.read'
56 def_user = User.get_default_user()
54 def_user = db.User.get_default_user()
57 for p in def_user.user_perms:
55 for p in def_user.user_perms:
58 if p.permission.permission_name.startswith('repository.'):
56 if p.permission.permission_name.startswith('repository.'):
59 default = p.permission.permission_name
57 default = p.permission.permission_name
@@ -61,8 +59,8 b' class RepoModel(object):'
61
59
62 default_perm = 'repository.none' if private else default
60 default_perm = 'repository.none' if private else default
63
61
64 repo_to_perm = UserRepoToPerm()
62 repo_to_perm = db.UserRepoToPerm()
65 repo_to_perm.permission = Permission.get_by_key(default_perm)
63 repo_to_perm.permission = db.Permission.get_by_key(default_perm)
66
64
67 repo_to_perm.repository = repository
65 repo_to_perm.repository = repository
68 repo_to_perm.user_id = def_user.user_id
66 repo_to_perm.user_id = def_user.user_id
@@ -76,20 +74,20 b' class RepoModel(object):'
76 Gets the repositories root path from database
74 Gets the repositories root path from database
77 """
75 """
78
76
79 q = Ui.query().filter(Ui.ui_key == '/').one()
77 q = db.Ui.query().filter(db.Ui.ui_key == '/').one()
80 return q.ui_value
78 return q.ui_value
81
79
82 def get(self, repo_id):
80 def get(self, repo_id):
83 repo = Repository.query() \
81 repo = db.Repository.query() \
84 .filter(Repository.repo_id == repo_id)
82 .filter(db.Repository.repo_id == repo_id)
85 return repo.scalar()
83 return repo.scalar()
86
84
87 def get_repo(self, repository):
85 def get_repo(self, repository):
88 return Repository.guess_instance(repository)
86 return db.Repository.guess_instance(repository)
89
87
90 def get_by_repo_name(self, repo_name):
88 def get_by_repo_name(self, repo_name):
91 repo = Repository.query() \
89 repo = db.Repository.query() \
92 .filter(Repository.repo_name == repo_name)
90 .filter(db.Repository.repo_name == repo_name)
93 return repo.scalar()
91 return repo.scalar()
94
92
95 def get_all_user_repos(self, user):
93 def get_all_user_repos(self, user):
@@ -99,12 +97,12 b' class RepoModel(object):'
99 :param user:
97 :param user:
100 """
98 """
101 from kallithea.lib.auth import AuthUser
99 from kallithea.lib.auth import AuthUser
102 auth_user = AuthUser(dbuser=User.guess_instance(user))
100 auth_user = AuthUser(dbuser=db.User.guess_instance(user))
103 repos = [repo_name
101 repos = [repo_name
104 for repo_name, perm in auth_user.repository_permissions.items()
102 for repo_name, perm in auth_user.repository_permissions.items()
105 if perm in ['repository.read', 'repository.write', 'repository.admin']
103 if perm in ['repository.read', 'repository.write', 'repository.admin']
106 ]
104 ]
107 return Repository.query().filter(Repository.repo_name.in_(repos))
105 return db.Repository.query().filter(db.Repository.repo_name.in_(repos))
108
106
109 @classmethod
107 @classmethod
110 def _render_datatable(cls, tmpl, *args, **kwargs):
108 def _render_datatable(cls, tmpl, *args, **kwargs):
@@ -220,7 +218,7 b' class RepoModel(object):'
220 :param repo_name:
218 :param repo_name:
221 """
219 """
222
220
223 repo_info = Repository.get_by_repo_name(repo_name)
221 repo_info = db.Repository.get_by_repo_name(repo_name)
224
222
225 if repo_info is None:
223 if repo_info is None:
226 return None
224 return None
@@ -248,7 +246,7 b' class RepoModel(object):'
248 if repo_info.owner:
246 if repo_info.owner:
249 defaults.update({'owner': repo_info.owner.username})
247 defaults.update({'owner': repo_info.owner.username})
250 else:
248 else:
251 replacement_user = User.query().filter(User.admin ==
249 replacement_user = db.User.query().filter(db.User.admin ==
252 True).first().username
250 True).first().username
253 defaults.update({'owner': replacement_user})
251 defaults.update({'owner': replacement_user})
254
252
@@ -266,14 +264,14 b' class RepoModel(object):'
266
264
267 def update(self, repo, **kwargs):
265 def update(self, repo, **kwargs):
268 try:
266 try:
269 cur_repo = Repository.guess_instance(repo)
267 cur_repo = db.Repository.guess_instance(repo)
270 org_repo_name = cur_repo.repo_name
268 org_repo_name = cur_repo.repo_name
271 if 'owner' in kwargs:
269 if 'owner' in kwargs:
272 cur_repo.owner = User.get_by_username(kwargs['owner'])
270 cur_repo.owner = db.User.get_by_username(kwargs['owner'])
273
271
274 if 'repo_group' in kwargs:
272 if 'repo_group' in kwargs:
275 assert kwargs['repo_group'] != '-1', kwargs # RepoForm should have converted to None
273 assert kwargs['repo_group'] != '-1', kwargs # RepoForm should have converted to None
276 cur_repo.group = RepoGroup.get(kwargs['repo_group'])
274 cur_repo.group = db.RepoGroup.get(kwargs['repo_group'])
277 cur_repo.repo_name = cur_repo.get_new_name(cur_repo.just_name)
275 cur_repo.repo_name = cur_repo.get_new_name(cur_repo.just_name)
278 log.debug('Updating repo %s with params:%s', cur_repo, kwargs)
276 log.debug('Updating repo %s with params:%s', cur_repo, kwargs)
279 for k in ['repo_enable_downloads',
277 for k in ['repo_enable_downloads',
@@ -305,9 +303,9 b' class RepoModel(object):'
305 repo=cur_repo, user='default', perm=EMPTY_PERM
303 repo=cur_repo, user='default', perm=EMPTY_PERM
306 )
304 )
307 # handle extra fields
305 # handle extra fields
308 for field in [k for k in kwargs if k.startswith(RepositoryField.PREFIX)]:
306 for field in [k for k in kwargs if k.startswith(db.RepositoryField.PREFIX)]:
309 k = RepositoryField.un_prefix_key(field)
307 k = db.RepositoryField.un_prefix_key(field)
310 ex_field = RepositoryField.get_by_key_name(key=k, repo=cur_repo)
308 ex_field = db.RepositoryField.get_by_key_name(key=k, repo=cur_repo)
311 if ex_field:
309 if ex_field:
312 ex_field.field_value = kwargs[field]
310 ex_field.field_value = kwargs[field]
313
311
@@ -325,7 +323,7 b' class RepoModel(object):'
325 landing_rev='rev:tip', fork_of=None,
323 landing_rev='rev:tip', fork_of=None,
326 copy_fork_permissions=False, enable_statistics=False,
324 copy_fork_permissions=False, enable_statistics=False,
327 enable_downloads=False,
325 enable_downloads=False,
328 copy_group_permissions=False, state=Repository.STATE_PENDING):
326 copy_group_permissions=False, state=db.Repository.STATE_PENDING):
329 """
327 """
330 Create repository inside database with PENDING state. This should only be
328 Create repository inside database with PENDING state. This should only be
331 executed by create() repo, with exception of importing existing repos.
329 executed by create() repo, with exception of importing existing repos.
@@ -333,9 +331,9 b' class RepoModel(object):'
333 """
331 """
334 from kallithea.model.scm import ScmModel
332 from kallithea.model.scm import ScmModel
335
333
336 owner = User.guess_instance(owner)
334 owner = db.User.guess_instance(owner)
337 fork_of = Repository.guess_instance(fork_of)
335 fork_of = db.Repository.guess_instance(fork_of)
338 repo_group = RepoGroup.guess_instance(repo_group)
336 repo_group = db.RepoGroup.guess_instance(repo_group)
339 try:
337 try:
340 repo_name = repo_name
338 repo_name = repo_name
341 description = description
339 description = description
@@ -347,7 +345,7 b' class RepoModel(object):'
347 if kallithea.lib.utils2.repo_name_slug(repo_name) != repo_name:
345 if kallithea.lib.utils2.repo_name_slug(repo_name) != repo_name:
348 raise Exception('invalid repo name %s' % repo_name)
346 raise Exception('invalid repo name %s' % repo_name)
349
347
350 new_repo = Repository()
348 new_repo = db.Repository()
351 new_repo.repo_state = state
349 new_repo.repo_state = state
352 new_repo.enable_statistics = False
350 new_repo.enable_statistics = False
353 new_repo.repo_name = repo_name_full
351 new_repo.repo_name = repo_name_full
@@ -373,35 +371,35 b' class RepoModel(object):'
373
371
374 if fork_of and copy_fork_permissions:
372 if fork_of and copy_fork_permissions:
375 repo = fork_of
373 repo = fork_of
376 user_perms = UserRepoToPerm.query() \
374 user_perms = db.UserRepoToPerm.query() \
377 .filter(UserRepoToPerm.repository == repo).all()
375 .filter(db.UserRepoToPerm.repository == repo).all()
378 group_perms = UserGroupRepoToPerm.query() \
376 group_perms = db.UserGroupRepoToPerm.query() \
379 .filter(UserGroupRepoToPerm.repository == repo).all()
377 .filter(db.UserGroupRepoToPerm.repository == repo).all()
380
378
381 for perm in user_perms:
379 for perm in user_perms:
382 UserRepoToPerm.create(perm.user, new_repo, perm.permission)
380 db.UserRepoToPerm.create(perm.user, new_repo, perm.permission)
383
381
384 for perm in group_perms:
382 for perm in group_perms:
385 UserGroupRepoToPerm.create(perm.users_group, new_repo,
383 db.UserGroupRepoToPerm.create(perm.users_group, new_repo,
386 perm.permission)
384 perm.permission)
387
385
388 elif repo_group and copy_group_permissions:
386 elif repo_group and copy_group_permissions:
389
387
390 user_perms = UserRepoGroupToPerm.query() \
388 user_perms = db.UserRepoGroupToPerm.query() \
391 .filter(UserRepoGroupToPerm.group == repo_group).all()
389 .filter(db.UserRepoGroupToPerm.group == repo_group).all()
392
390
393 group_perms = UserGroupRepoGroupToPerm.query() \
391 group_perms = db.UserGroupRepoGroupToPerm.query() \
394 .filter(UserGroupRepoGroupToPerm.group == repo_group).all()
392 .filter(db.UserGroupRepoGroupToPerm.group == repo_group).all()
395
393
396 for perm in user_perms:
394 for perm in user_perms:
397 perm_name = perm.permission.permission_name.replace('group.', 'repository.')
395 perm_name = perm.permission.permission_name.replace('group.', 'repository.')
398 perm_obj = Permission.get_by_key(perm_name)
396 perm_obj = db.Permission.get_by_key(perm_name)
399 UserRepoToPerm.create(perm.user, new_repo, perm_obj)
397 db.UserRepoToPerm.create(perm.user, new_repo, perm_obj)
400
398
401 for perm in group_perms:
399 for perm in group_perms:
402 perm_name = perm.permission.permission_name.replace('group.', 'repository.')
400 perm_name = perm.permission.permission_name.replace('group.', 'repository.')
403 perm_obj = Permission.get_by_key(perm_name)
401 perm_obj = db.Permission.get_by_key(perm_name)
404 UserGroupRepoToPerm.create(perm.users_group, new_repo, perm_obj)
402 db.UserGroupRepoToPerm.create(perm.users_group, new_repo, perm_obj)
405
403
406 else:
404 else:
407 self._create_default_perms(new_repo, private)
405 self._create_default_perms(new_repo, private)
@@ -481,7 +479,7 b' class RepoModel(object):'
481 """
479 """
482 if not cur_user:
480 if not cur_user:
483 cur_user = getattr(get_current_authuser(), 'username', None)
481 cur_user = getattr(get_current_authuser(), 'username', None)
484 repo = Repository.guess_instance(repo)
482 repo = db.Repository.guess_instance(repo)
485 if repo is not None:
483 if repo is not None:
486 if forks == 'detach':
484 if forks == 'detach':
487 for r in repo.forks:
485 for r in repo.forks:
@@ -514,18 +512,18 b' class RepoModel(object):'
514 :param user: Instance of User, user_id or username
512 :param user: Instance of User, user_id or username
515 :param perm: Instance of Permission, or permission_name
513 :param perm: Instance of Permission, or permission_name
516 """
514 """
517 user = User.guess_instance(user)
515 user = db.User.guess_instance(user)
518 repo = Repository.guess_instance(repo)
516 repo = db.Repository.guess_instance(repo)
519 permission = Permission.guess_instance(perm)
517 permission = db.Permission.guess_instance(perm)
520
518
521 # check if we have that permission already
519 # check if we have that permission already
522 obj = UserRepoToPerm.query() \
520 obj = db.UserRepoToPerm.query() \
523 .filter(UserRepoToPerm.user == user) \
521 .filter(db.UserRepoToPerm.user == user) \
524 .filter(UserRepoToPerm.repository == repo) \
522 .filter(db.UserRepoToPerm.repository == repo) \
525 .scalar()
523 .scalar()
526 if obj is None:
524 if obj is None:
527 # create new !
525 # create new !
528 obj = UserRepoToPerm()
526 obj = db.UserRepoToPerm()
529 meta.Session().add(obj)
527 meta.Session().add(obj)
530 obj.repository = repo
528 obj.repository = repo
531 obj.user = user
529 obj.user = user
@@ -541,12 +539,12 b' class RepoModel(object):'
541 :param user: Instance of User, user_id or username
539 :param user: Instance of User, user_id or username
542 """
540 """
543
541
544 user = User.guess_instance(user)
542 user = db.User.guess_instance(user)
545 repo = Repository.guess_instance(repo)
543 repo = db.Repository.guess_instance(repo)
546
544
547 obj = UserRepoToPerm.query() \
545 obj = db.UserRepoToPerm.query() \
548 .filter(UserRepoToPerm.repository == repo) \
546 .filter(db.UserRepoToPerm.repository == repo) \
549 .filter(UserRepoToPerm.user == user) \
547 .filter(db.UserRepoToPerm.user == user) \
550 .scalar()
548 .scalar()
551 if obj is not None:
549 if obj is not None:
552 meta.Session().delete(obj)
550 meta.Session().delete(obj)
@@ -562,19 +560,19 b' class RepoModel(object):'
562 or user group name
560 or user group name
563 :param perm: Instance of Permission, or permission_name
561 :param perm: Instance of Permission, or permission_name
564 """
562 """
565 repo = Repository.guess_instance(repo)
563 repo = db.Repository.guess_instance(repo)
566 group_name = UserGroup.guess_instance(group_name)
564 group_name = db.UserGroup.guess_instance(group_name)
567 permission = Permission.guess_instance(perm)
565 permission = db.Permission.guess_instance(perm)
568
566
569 # check if we have that permission already
567 # check if we have that permission already
570 obj = UserGroupRepoToPerm.query() \
568 obj = db.UserGroupRepoToPerm.query() \
571 .filter(UserGroupRepoToPerm.users_group == group_name) \
569 .filter(db.UserGroupRepoToPerm.users_group == group_name) \
572 .filter(UserGroupRepoToPerm.repository == repo) \
570 .filter(db.UserGroupRepoToPerm.repository == repo) \
573 .scalar()
571 .scalar()
574
572
575 if obj is None:
573 if obj is None:
576 # create new
574 # create new
577 obj = UserGroupRepoToPerm()
575 obj = db.UserGroupRepoToPerm()
578 meta.Session().add(obj)
576 meta.Session().add(obj)
579
577
580 obj.repository = repo
578 obj.repository = repo
@@ -591,12 +589,12 b' class RepoModel(object):'
591 :param group_name: Instance of UserGroup, users_group_id,
589 :param group_name: Instance of UserGroup, users_group_id,
592 or user group name
590 or user group name
593 """
591 """
594 repo = Repository.guess_instance(repo)
592 repo = db.Repository.guess_instance(repo)
595 group_name = UserGroup.guess_instance(group_name)
593 group_name = db.UserGroup.guess_instance(group_name)
596
594
597 obj = UserGroupRepoToPerm.query() \
595 obj = db.UserGroupRepoToPerm.query() \
598 .filter(UserGroupRepoToPerm.repository == repo) \
596 .filter(db.UserGroupRepoToPerm.repository == repo) \
599 .filter(UserGroupRepoToPerm.users_group == group_name) \
597 .filter(db.UserGroupRepoToPerm.users_group == group_name) \
600 .scalar()
598 .scalar()
601 if obj is not None:
599 if obj is not None:
602 meta.Session().delete(obj)
600 meta.Session().delete(obj)
@@ -608,10 +606,10 b' class RepoModel(object):'
608
606
609 :param repo_name:
607 :param repo_name:
610 """
608 """
611 repo = Repository.guess_instance(repo_name)
609 repo = db.Repository.guess_instance(repo_name)
612 try:
610 try:
613 obj = Statistics.query() \
611 obj = db.Statistics.query() \
614 .filter(Statistics.repository == repo).scalar()
612 .filter(db.Statistics.repository == repo).scalar()
615 if obj is not None:
613 if obj is not None:
616 meta.Session().delete(obj)
614 meta.Session().delete(obj)
617 except Exception:
615 except Exception:
@@ -632,7 +630,7 b' class RepoModel(object):'
632 if '/' in repo_name:
630 if '/' in repo_name:
633 raise ValueError('repo_name must not contain groups got `%s`' % repo_name)
631 raise ValueError('repo_name must not contain groups got `%s`' % repo_name)
634
632
635 if isinstance(repo_group, RepoGroup):
633 if isinstance(repo_group, db.RepoGroup):
636 new_parent_path = os.sep.join(repo_group.full_path_splitted)
634 new_parent_path = os.sep.join(repo_group.full_path_splitted)
637 else:
635 else:
638 new_parent_path = repo_group or ''
636 new_parent_path = repo_group or ''
@@ -34,8 +34,7 b' import traceback'
34
34
35 import kallithea.lib.utils2
35 import kallithea.lib.utils2
36 from kallithea.lib.utils2 import LazyProperty
36 from kallithea.lib.utils2 import LazyProperty
37 from kallithea.model import meta
37 from kallithea.model import db, meta
38 from kallithea.model.db import Permission, RepoGroup, Repository, Ui, User, UserGroup, UserGroupRepoGroupToPerm, UserRepoGroupToPerm
39
38
40
39
41 log = logging.getLogger(__name__)
40 log = logging.getLogger(__name__)
@@ -49,20 +48,20 b' class RepoGroupModel(object):'
49 Gets the repositories root path from database
48 Gets the repositories root path from database
50 """
49 """
51
50
52 q = Ui.get_by_key('paths', '/')
51 q = db.Ui.get_by_key('paths', '/')
53 return q.ui_value
52 return q.ui_value
54
53
55 def _create_default_perms(self, new_group):
54 def _create_default_perms(self, new_group):
56 # create default permission
55 # create default permission
57 default_perm = 'group.read'
56 default_perm = 'group.read'
58 def_user = User.get_default_user()
57 def_user = db.User.get_default_user()
59 for p in def_user.user_perms:
58 for p in def_user.user_perms:
60 if p.permission.permission_name.startswith('group.'):
59 if p.permission.permission_name.startswith('group.'):
61 default_perm = p.permission.permission_name
60 default_perm = p.permission.permission_name
62 break
61 break
63
62
64 repo_group_to_perm = UserRepoGroupToPerm()
63 repo_group_to_perm = db.UserRepoGroupToPerm()
65 repo_group_to_perm.permission = Permission.get_by_key(default_perm)
64 repo_group_to_perm.permission = db.Permission.get_by_key(default_perm)
66
65
67 repo_group_to_perm.group = new_group
66 repo_group_to_perm.group = new_group
68 repo_group_to_perm.user_id = def_user.user_id
67 repo_group_to_perm.user_id = def_user.user_id
@@ -139,9 +138,9 b' class RepoGroupModel(object):'
139 if kallithea.lib.utils2.repo_name_slug(group_name) != group_name:
138 if kallithea.lib.utils2.repo_name_slug(group_name) != group_name:
140 raise Exception('invalid repo group name %s' % group_name)
139 raise Exception('invalid repo group name %s' % group_name)
141
140
142 owner = User.guess_instance(owner)
141 owner = db.User.guess_instance(owner)
143 parent_group = RepoGroup.guess_instance(parent)
142 parent_group = db.RepoGroup.guess_instance(parent)
144 new_repo_group = RepoGroup()
143 new_repo_group = db.RepoGroup()
145 new_repo_group.owner = owner
144 new_repo_group.owner = owner
146 new_repo_group.group_description = group_description or group_name
145 new_repo_group.group_description = group_description or group_name
147 new_repo_group.parent_group = parent_group
146 new_repo_group.parent_group = parent_group
@@ -157,21 +156,21 b' class RepoGroupModel(object):'
157
156
158 if parent_group and copy_permissions:
157 if parent_group and copy_permissions:
159 # copy permissions from parent
158 # copy permissions from parent
160 user_perms = UserRepoGroupToPerm.query() \
159 user_perms = db.UserRepoGroupToPerm.query() \
161 .filter(UserRepoGroupToPerm.group == parent_group).all()
160 .filter(db.UserRepoGroupToPerm.group == parent_group).all()
162
161
163 group_perms = UserGroupRepoGroupToPerm.query() \
162 group_perms = db.UserGroupRepoGroupToPerm.query() \
164 .filter(UserGroupRepoGroupToPerm.group == parent_group).all()
163 .filter(db.UserGroupRepoGroupToPerm.group == parent_group).all()
165
164
166 for perm in user_perms:
165 for perm in user_perms:
167 # don't copy over the permission for user who is creating
166 # don't copy over the permission for user who is creating
168 # this group, if he is not super admin he get's admin
167 # this group, if he is not super admin he get's admin
169 # permission set above
168 # permission set above
170 if perm.user != owner or owner.is_admin:
169 if perm.user != owner or owner.is_admin:
171 UserRepoGroupToPerm.create(perm.user, new_repo_group, perm.permission)
170 db.UserRepoGroupToPerm.create(perm.user, new_repo_group, perm.permission)
172
171
173 for perm in group_perms:
172 for perm in group_perms:
174 UserGroupRepoGroupToPerm.create(perm.users_group, new_repo_group, perm.permission)
173 db.UserGroupRepoGroupToPerm.create(perm.users_group, new_repo_group, perm.permission)
175 else:
174 else:
176 self._create_default_perms(new_repo_group)
175 self._create_default_perms(new_repo_group)
177
176
@@ -198,10 +197,10 b' class RepoGroupModel(object):'
198 perms_updates = []
197 perms_updates = []
199
198
200 def _set_perm_user(obj, user, perm):
199 def _set_perm_user(obj, user, perm):
201 if isinstance(obj, RepoGroup):
200 if isinstance(obj, db.RepoGroup):
202 self.grant_user_permission(repo_group=obj, user=user, perm=perm)
201 self.grant_user_permission(repo_group=obj, user=user, perm=perm)
203 elif isinstance(obj, Repository):
202 elif isinstance(obj, db.Repository):
204 user = User.guess_instance(user)
203 user = db.User.guess_instance(user)
205
204
206 # private repos will not allow to change the default permissions
205 # private repos will not allow to change the default permissions
207 # using recursive mode
206 # using recursive mode
@@ -216,11 +215,11 b' class RepoGroupModel(object):'
216 )
215 )
217
216
218 def _set_perm_group(obj, users_group, perm):
217 def _set_perm_group(obj, users_group, perm):
219 if isinstance(obj, RepoGroup):
218 if isinstance(obj, db.RepoGroup):
220 self.grant_user_group_permission(repo_group=obj,
219 self.grant_user_group_permission(repo_group=obj,
221 group_name=users_group,
220 group_name=users_group,
222 perm=perm)
221 perm=perm)
223 elif isinstance(obj, Repository):
222 elif isinstance(obj, db.Repository):
224 # we set group permission but we have to switch to repo
223 # we set group permission but we have to switch to repo
225 # permission
224 # permission
226 perm = perm.replace('group.', 'repository.')
225 perm = perm.replace('group.', 'repository.')
@@ -240,11 +239,11 b' class RepoGroupModel(object):'
240 pass
239 pass
241 elif recursive == 'repos':
240 elif recursive == 'repos':
242 # skip groups, other than this one
241 # skip groups, other than this one
243 if isinstance(obj, RepoGroup) and not obj == repo_group:
242 if isinstance(obj, db.RepoGroup) and not obj == repo_group:
244 continue
243 continue
245 elif recursive == 'groups':
244 elif recursive == 'groups':
246 # skip repos
245 # skip repos
247 if isinstance(obj, Repository):
246 if isinstance(obj, db.Repository):
248 continue
247 continue
249 else: # recursive == 'none': # DEFAULT don't apply to iterated objects
248 else: # recursive == 'none': # DEFAULT don't apply to iterated objects
250 obj = repo_group
249 obj = repo_group
@@ -279,7 +278,7 b' class RepoGroupModel(object):'
279
278
280 def update(self, repo_group, repo_group_args):
279 def update(self, repo_group, repo_group_args):
281 try:
280 try:
282 repo_group = RepoGroup.guess_instance(repo_group)
281 repo_group = db.RepoGroup.guess_instance(repo_group)
283 old_path = repo_group.full_path
282 old_path = repo_group.full_path
284
283
285 # change properties
284 # change properties
@@ -290,7 +289,7 b' class RepoGroupModel(object):'
290
289
291 if 'parent_group_id' in repo_group_args:
290 if 'parent_group_id' in repo_group_args:
292 assert repo_group_args['parent_group_id'] != '-1', repo_group_args # RepoGroupForm should have converted to None
291 assert repo_group_args['parent_group_id'] != '-1', repo_group_args # RepoGroupForm should have converted to None
293 repo_group.parent_group = RepoGroup.get(repo_group_args['parent_group_id'])
292 repo_group.parent_group = db.RepoGroup.get(repo_group_args['parent_group_id'])
294 if 'group_name' in repo_group_args:
293 if 'group_name' in repo_group_args:
295 group_name = repo_group_args['group_name']
294 group_name = repo_group_args['group_name']
296 if kallithea.lib.utils2.repo_name_slug(group_name) != group_name:
295 if kallithea.lib.utils2.repo_name_slug(group_name) != group_name:
@@ -306,12 +305,12 b' class RepoGroupModel(object):'
306 # this can be potentially heavy operation
305 # this can be potentially heavy operation
307 for obj in repo_group.recursive_groups_and_repos():
306 for obj in repo_group.recursive_groups_and_repos():
308 # set the value from it's parent
307 # set the value from it's parent
309 if isinstance(obj, RepoGroup):
308 if isinstance(obj, db.RepoGroup):
310 new_name = obj.get_new_name(obj.name)
309 new_name = obj.get_new_name(obj.name)
311 log.debug('Fixing group %s to new name %s'
310 log.debug('Fixing group %s to new name %s'
312 % (obj.group_name, new_name))
311 % (obj.group_name, new_name))
313 obj.group_name = new_name
312 obj.group_name = new_name
314 elif isinstance(obj, Repository):
313 elif isinstance(obj, db.Repository):
315 # we need to get all repositories from this new group and
314 # we need to get all repositories from this new group and
316 # rename them accordingly to new group path
315 # rename them accordingly to new group path
317 new_name = obj.get_new_name(obj.just_name)
316 new_name = obj.get_new_name(obj.just_name)
@@ -327,7 +326,7 b' class RepoGroupModel(object):'
327 raise
326 raise
328
327
329 def delete(self, repo_group, force_delete=False):
328 def delete(self, repo_group, force_delete=False):
330 repo_group = RepoGroup.guess_instance(repo_group)
329 repo_group = db.RepoGroup.guess_instance(repo_group)
331 try:
330 try:
332 meta.Session().delete(repo_group)
331 meta.Session().delete(repo_group)
333 self._delete_group(repo_group, force_delete)
332 self._delete_group(repo_group, force_delete)
@@ -337,8 +336,8 b' class RepoGroupModel(object):'
337
336
338 def add_permission(self, repo_group, obj, obj_type, perm, recursive):
337 def add_permission(self, repo_group, obj, obj_type, perm, recursive):
339 from kallithea.model.repo import RepoModel
338 from kallithea.model.repo import RepoModel
340 repo_group = RepoGroup.guess_instance(repo_group)
339 repo_group = db.RepoGroup.guess_instance(repo_group)
341 perm = Permission.guess_instance(perm)
340 perm = db.Permission.guess_instance(perm)
342
341
343 for el in repo_group.recursive_groups_and_repos():
342 for el in repo_group.recursive_groups_and_repos():
344 # iterated obj is an instance of a repos group or repository in
343 # iterated obj is an instance of a repos group or repository in
@@ -347,24 +346,24 b' class RepoGroupModel(object):'
347 pass
346 pass
348 elif recursive == 'repos':
347 elif recursive == 'repos':
349 # skip groups, other than this one
348 # skip groups, other than this one
350 if isinstance(el, RepoGroup) and not el == repo_group:
349 if isinstance(el, db.RepoGroup) and not el == repo_group:
351 continue
350 continue
352 elif recursive == 'groups':
351 elif recursive == 'groups':
353 # skip repos
352 # skip repos
354 if isinstance(el, Repository):
353 if isinstance(el, db.Repository):
355 continue
354 continue
356 else: # recursive == 'none': # DEFAULT don't apply to iterated objects
355 else: # recursive == 'none': # DEFAULT don't apply to iterated objects
357 el = repo_group
356 el = repo_group
358 # also we do a break at the end of this loop.
357 # also we do a break at the end of this loop.
359
358
360 if isinstance(el, RepoGroup):
359 if isinstance(el, db.RepoGroup):
361 if obj_type == 'user':
360 if obj_type == 'user':
362 RepoGroupModel().grant_user_permission(el, user=obj, perm=perm)
361 RepoGroupModel().grant_user_permission(el, user=obj, perm=perm)
363 elif obj_type == 'user_group':
362 elif obj_type == 'user_group':
364 RepoGroupModel().grant_user_group_permission(el, group_name=obj, perm=perm)
363 RepoGroupModel().grant_user_group_permission(el, group_name=obj, perm=perm)
365 else:
364 else:
366 raise Exception('undefined object type %s' % obj_type)
365 raise Exception('undefined object type %s' % obj_type)
367 elif isinstance(el, Repository):
366 elif isinstance(el, db.Repository):
368 # for repos we need to hotfix the name of permission
367 # for repos we need to hotfix the name of permission
369 _perm = perm.permission_name.replace('group.', 'repository.')
368 _perm = perm.permission_name.replace('group.', 'repository.')
370 if obj_type == 'user':
369 if obj_type == 'user':
@@ -393,7 +392,7 b' class RepoGroupModel(object):'
393 :param recursive: recurse to all children of group
392 :param recursive: recurse to all children of group
394 """
393 """
395 from kallithea.model.repo import RepoModel
394 from kallithea.model.repo import RepoModel
396 repo_group = RepoGroup.guess_instance(repo_group)
395 repo_group = db.RepoGroup.guess_instance(repo_group)
397
396
398 for el in repo_group.recursive_groups_and_repos():
397 for el in repo_group.recursive_groups_and_repos():
399 # iterated obj is an instance of a repos group or repository in
398 # iterated obj is an instance of a repos group or repository in
@@ -402,24 +401,24 b' class RepoGroupModel(object):'
402 pass
401 pass
403 elif recursive == 'repos':
402 elif recursive == 'repos':
404 # skip groups, other than this one
403 # skip groups, other than this one
405 if isinstance(el, RepoGroup) and not el == repo_group:
404 if isinstance(el, db.RepoGroup) and not el == repo_group:
406 continue
405 continue
407 elif recursive == 'groups':
406 elif recursive == 'groups':
408 # skip repos
407 # skip repos
409 if isinstance(el, Repository):
408 if isinstance(el, db.Repository):
410 continue
409 continue
411 else: # recursive == 'none': # DEFAULT don't apply to iterated objects
410 else: # recursive == 'none': # DEFAULT don't apply to iterated objects
412 el = repo_group
411 el = repo_group
413 # also we do a break at the end of this loop.
412 # also we do a break at the end of this loop.
414
413
415 if isinstance(el, RepoGroup):
414 if isinstance(el, db.RepoGroup):
416 if obj_type == 'user':
415 if obj_type == 'user':
417 RepoGroupModel().revoke_user_permission(el, user=obj)
416 RepoGroupModel().revoke_user_permission(el, user=obj)
418 elif obj_type == 'user_group':
417 elif obj_type == 'user_group':
419 RepoGroupModel().revoke_user_group_permission(el, group_name=obj)
418 RepoGroupModel().revoke_user_group_permission(el, group_name=obj)
420 else:
419 else:
421 raise Exception('undefined object type %s' % obj_type)
420 raise Exception('undefined object type %s' % obj_type)
422 elif isinstance(el, Repository):
421 elif isinstance(el, db.Repository):
423 if obj_type == 'user':
422 if obj_type == 'user':
424 RepoModel().revoke_user_permission(el, user=obj)
423 RepoModel().revoke_user_permission(el, user=obj)
425 elif obj_type == 'user_group':
424 elif obj_type == 'user_group':
@@ -446,18 +445,18 b' class RepoGroupModel(object):'
446 :param perm: Instance of Permission, or permission_name
445 :param perm: Instance of Permission, or permission_name
447 """
446 """
448
447
449 repo_group = RepoGroup.guess_instance(repo_group)
448 repo_group = db.RepoGroup.guess_instance(repo_group)
450 user = User.guess_instance(user)
449 user = db.User.guess_instance(user)
451 permission = Permission.guess_instance(perm)
450 permission = db.Permission.guess_instance(perm)
452
451
453 # check if we have that permission already
452 # check if we have that permission already
454 obj = UserRepoGroupToPerm.query() \
453 obj = db.UserRepoGroupToPerm.query() \
455 .filter(UserRepoGroupToPerm.user == user) \
454 .filter(db.UserRepoGroupToPerm.user == user) \
456 .filter(UserRepoGroupToPerm.group == repo_group) \
455 .filter(db.UserRepoGroupToPerm.group == repo_group) \
457 .scalar()
456 .scalar()
458 if obj is None:
457 if obj is None:
459 # create new !
458 # create new !
460 obj = UserRepoGroupToPerm()
459 obj = db.UserRepoGroupToPerm()
461 meta.Session().add(obj)
460 meta.Session().add(obj)
462 obj.group = repo_group
461 obj.group = repo_group
463 obj.user = user
462 obj.user = user
@@ -474,12 +473,12 b' class RepoGroupModel(object):'
474 :param user: Instance of User, user_id or username
473 :param user: Instance of User, user_id or username
475 """
474 """
476
475
477 repo_group = RepoGroup.guess_instance(repo_group)
476 repo_group = db.RepoGroup.guess_instance(repo_group)
478 user = User.guess_instance(user)
477 user = db.User.guess_instance(user)
479
478
480 obj = UserRepoGroupToPerm.query() \
479 obj = db.UserRepoGroupToPerm.query() \
481 .filter(UserRepoGroupToPerm.user == user) \
480 .filter(db.UserRepoGroupToPerm.user == user) \
482 .filter(UserRepoGroupToPerm.group == repo_group) \
481 .filter(db.UserRepoGroupToPerm.group == repo_group) \
483 .scalar()
482 .scalar()
484 if obj is not None:
483 if obj is not None:
485 meta.Session().delete(obj)
484 meta.Session().delete(obj)
@@ -496,19 +495,19 b' class RepoGroupModel(object):'
496 or user group name
495 or user group name
497 :param perm: Instance of Permission, or permission_name
496 :param perm: Instance of Permission, or permission_name
498 """
497 """
499 repo_group = RepoGroup.guess_instance(repo_group)
498 repo_group = db.RepoGroup.guess_instance(repo_group)
500 group_name = UserGroup.guess_instance(group_name)
499 group_name = db.UserGroup.guess_instance(group_name)
501 permission = Permission.guess_instance(perm)
500 permission = db.Permission.guess_instance(perm)
502
501
503 # check if we have that permission already
502 # check if we have that permission already
504 obj = UserGroupRepoGroupToPerm.query() \
503 obj = db.UserGroupRepoGroupToPerm.query() \
505 .filter(UserGroupRepoGroupToPerm.group == repo_group) \
504 .filter(db.UserGroupRepoGroupToPerm.group == repo_group) \
506 .filter(UserGroupRepoGroupToPerm.users_group == group_name) \
505 .filter(db.UserGroupRepoGroupToPerm.users_group == group_name) \
507 .scalar()
506 .scalar()
508
507
509 if obj is None:
508 if obj is None:
510 # create new
509 # create new
511 obj = UserGroupRepoGroupToPerm()
510 obj = db.UserGroupRepoGroupToPerm()
512 meta.Session().add(obj)
511 meta.Session().add(obj)
513
512
514 obj.group = repo_group
513 obj.group = repo_group
@@ -526,12 +525,12 b' class RepoGroupModel(object):'
526 :param group_name: Instance of UserGroup, users_group_id,
525 :param group_name: Instance of UserGroup, users_group_id,
527 or user group name
526 or user group name
528 """
527 """
529 repo_group = RepoGroup.guess_instance(repo_group)
528 repo_group = db.RepoGroup.guess_instance(repo_group)
530 group_name = UserGroup.guess_instance(group_name)
529 group_name = db.UserGroup.guess_instance(group_name)
531
530
532 obj = UserGroupRepoGroupToPerm.query() \
531 obj = db.UserGroupRepoGroupToPerm.query() \
533 .filter(UserGroupRepoGroupToPerm.group == repo_group) \
532 .filter(db.UserGroupRepoGroupToPerm.group == repo_group) \
534 .filter(UserGroupRepoGroupToPerm.users_group == group_name) \
533 .filter(db.UserGroupRepoGroupToPerm.users_group == group_name) \
535 .scalar()
534 .scalar()
536 if obj is not None:
535 if obj is not None:
537 meta.Session().delete(obj)
536 meta.Session().delete(obj)
@@ -46,8 +46,7 b' from kallithea.lib.vcs.backends.base imp'
46 from kallithea.lib.vcs.exceptions import RepositoryError
46 from kallithea.lib.vcs.exceptions import RepositoryError
47 from kallithea.lib.vcs.nodes import FileNode
47 from kallithea.lib.vcs.nodes import FileNode
48 from kallithea.lib.vcs.utils.lazy import LazyProperty
48 from kallithea.lib.vcs.utils.lazy import LazyProperty
49 from kallithea.model import meta
49 from kallithea.model import db, meta
50 from kallithea.model.db import PullRequest, RepoGroup, Repository, Ui, User, UserFollowing, UserLog
51
50
52
51
53 log = logging.getLogger(__name__)
52 log = logging.getLogger(__name__)
@@ -136,7 +135,7 b' class ScmModel(object):'
136 """
135 """
137
136
138 def __get_repo(self, instance):
137 def __get_repo(self, instance):
139 cls = Repository
138 cls = db.Repository
140 if isinstance(instance, cls):
139 if isinstance(instance, cls):
141 return instance
140 return instance
142 elif isinstance(instance, int):
141 elif isinstance(instance, int):
@@ -154,7 +153,7 b' class ScmModel(object):'
154 Gets the repositories root path from database
153 Gets the repositories root path from database
155 """
154 """
156
155
157 q = Ui.query().filter(Ui.ui_key == '/').one()
156 q = db.Ui.query().filter(db.Ui.ui_key == '/').one()
158
157
159 return q.ui_value
158 return q.ui_value
160
159
@@ -178,7 +177,7 b' class ScmModel(object):'
178 for name, path in get_filesystem_repos(repos_path):
177 for name, path in get_filesystem_repos(repos_path):
179 # name need to be decomposed and put back together using the /
178 # name need to be decomposed and put back together using the /
180 # since this is internal storage separator for kallithea
179 # since this is internal storage separator for kallithea
181 name = Repository.normalize_repo_name(name)
180 name = db.Repository.normalize_repo_name(name)
182
181
183 try:
182 try:
184 if name in repos:
183 if name in repos:
@@ -207,8 +206,8 b' class ScmModel(object):'
207 If no groups are specified, use top level groups.
206 If no groups are specified, use top level groups.
208 """
207 """
209 if groups is None:
208 if groups is None:
210 groups = RepoGroup.query() \
209 groups = db.RepoGroup.query() \
211 .filter(RepoGroup.parent_group_id == None).all()
210 .filter(db.RepoGroup.parent_group_id == None).all()
212 return RepoGroupList(groups, perm_level='read')
211 return RepoGroupList(groups, perm_level='read')
213
212
214 def mark_for_invalidation(self, repo_name):
213 def mark_for_invalidation(self, repo_name):
@@ -218,16 +217,16 b' class ScmModel(object):'
218 :param repo_name: the repo for which caches should be marked invalid
217 :param repo_name: the repo for which caches should be marked invalid
219 """
218 """
220 log.debug("Marking %s as invalidated and update cache", repo_name)
219 log.debug("Marking %s as invalidated and update cache", repo_name)
221 repo = Repository.get_by_repo_name(repo_name)
220 repo = db.Repository.get_by_repo_name(repo_name)
222 if repo is not None:
221 if repo is not None:
223 repo.set_invalidate()
222 repo.set_invalidate()
224 repo.update_changeset_cache()
223 repo.update_changeset_cache()
225
224
226 def toggle_following_repo(self, follow_repo_id, user_id):
225 def toggle_following_repo(self, follow_repo_id, user_id):
227
226
228 f = UserFollowing.query() \
227 f = db.UserFollowing.query() \
229 .filter(UserFollowing.follows_repository_id == follow_repo_id) \
228 .filter(db.UserFollowing.follows_repository_id == follow_repo_id) \
230 .filter(UserFollowing.user_id == user_id).scalar()
229 .filter(db.UserFollowing.user_id == user_id).scalar()
231
230
232 if f is not None:
231 if f is not None:
233 try:
232 try:
@@ -241,7 +240,7 b' class ScmModel(object):'
241 raise
240 raise
242
241
243 try:
242 try:
244 f = UserFollowing()
243 f = db.UserFollowing()
245 f.user_id = user_id
244 f.user_id = user_id
246 f.follows_repository_id = follow_repo_id
245 f.follows_repository_id = follow_repo_id
247 meta.Session().add(f)
246 meta.Session().add(f)
@@ -254,9 +253,9 b' class ScmModel(object):'
254 raise
253 raise
255
254
256 def toggle_following_user(self, follow_user_id, user_id):
255 def toggle_following_user(self, follow_user_id, user_id):
257 f = UserFollowing.query() \
256 f = db.UserFollowing.query() \
258 .filter(UserFollowing.follows_user_id == follow_user_id) \
257 .filter(db.UserFollowing.follows_user_id == follow_user_id) \
259 .filter(UserFollowing.user_id == user_id).scalar()
258 .filter(db.UserFollowing.user_id == user_id).scalar()
260
259
261 if f is not None:
260 if f is not None:
262 try:
261 try:
@@ -267,7 +266,7 b' class ScmModel(object):'
267 raise
266 raise
268
267
269 try:
268 try:
270 f = UserFollowing()
269 f = db.UserFollowing()
271 f.user_id = user_id
270 f.user_id = user_id
272 f.follows_user_id = follow_user_id
271 f.follows_user_id = follow_user_id
273 meta.Session().add(f)
272 meta.Session().add(f)
@@ -276,40 +275,40 b' class ScmModel(object):'
276 raise
275 raise
277
276
278 def is_following_repo(self, repo_name, user_id):
277 def is_following_repo(self, repo_name, user_id):
279 r = Repository.query() \
278 r = db.Repository.query() \
280 .filter(Repository.repo_name == repo_name).scalar()
279 .filter(db.Repository.repo_name == repo_name).scalar()
281
280
282 f = UserFollowing.query() \
281 f = db.UserFollowing.query() \
283 .filter(UserFollowing.follows_repository == r) \
282 .filter(db.UserFollowing.follows_repository == r) \
284 .filter(UserFollowing.user_id == user_id).scalar()
283 .filter(db.UserFollowing.user_id == user_id).scalar()
285
284
286 return f is not None
285 return f is not None
287
286
288 def is_following_user(self, username, user_id):
287 def is_following_user(self, username, user_id):
289 u = User.get_by_username(username)
288 u = db.User.get_by_username(username)
290
289
291 f = UserFollowing.query() \
290 f = db.UserFollowing.query() \
292 .filter(UserFollowing.follows_user == u) \
291 .filter(db.UserFollowing.follows_user == u) \
293 .filter(UserFollowing.user_id == user_id).scalar()
292 .filter(db.UserFollowing.user_id == user_id).scalar()
294
293
295 return f is not None
294 return f is not None
296
295
297 def get_followers(self, repo):
296 def get_followers(self, repo):
298 repo = Repository.guess_instance(repo)
297 repo = db.Repository.guess_instance(repo)
299
298
300 return UserFollowing.query() \
299 return db.UserFollowing.query() \
301 .filter(UserFollowing.follows_repository == repo).count()
300 .filter(db.UserFollowing.follows_repository == repo).count()
302
301
303 def get_forks(self, repo):
302 def get_forks(self, repo):
304 repo = Repository.guess_instance(repo)
303 repo = db.Repository.guess_instance(repo)
305 return Repository.query() \
304 return db.Repository.query() \
306 .filter(Repository.fork == repo).count()
305 .filter(db.Repository.fork == repo).count()
307
306
308 def get_pull_requests(self, repo):
307 def get_pull_requests(self, repo):
309 repo = Repository.guess_instance(repo)
308 repo = db.Repository.guess_instance(repo)
310 return PullRequest.query() \
309 return db.PullRequest.query() \
311 .filter(PullRequest.other_repo == repo) \
310 .filter(db.PullRequest.other_repo == repo) \
312 .filter(PullRequest.status != PullRequest.STATUS_CLOSED).count()
311 .filter(db.PullRequest.status != db.PullRequest.STATUS_CLOSED).count()
313
312
314 def mark_as_fork(self, repo, fork, user):
313 def mark_as_fork(self, repo, fork, user):
315 repo = self.__get_repo(repo)
314 repo = self.__get_repo(repo)
@@ -393,7 +392,7 b' class ScmModel(object):'
393
392
394 :param repo: a db_repo.scm_instance
393 :param repo: a db_repo.scm_instance
395 """
394 """
396 user = User.guess_instance(user)
395 user = db.User.guess_instance(user)
397 IMC = self._get_IMC_module(repo.alias)
396 IMC = self._get_IMC_module(repo.alias)
398 imc = IMC(repo)
397 imc = IMC(repo)
399 imc.change(FileNode(f_path, content, mode=cs.get_file_mode(f_path)))
398 imc.change(FileNode(f_path, content, mode=cs.get_file_mode(f_path)))
@@ -465,7 +464,7 b' class ScmModel(object):'
465 :returns: new committed changeset
464 :returns: new committed changeset
466 """
465 """
467
466
468 user = User.guess_instance(user)
467 user = db.User.guess_instance(user)
469 scm_instance = repo.scm_instance_no_cache()
468 scm_instance = repo.scm_instance_no_cache()
470
469
471 processed_nodes = []
470 processed_nodes = []
@@ -517,7 +516,7 b' class ScmModel(object):'
517 """
516 """
518 Commits specified nodes to repo. Again.
517 Commits specified nodes to repo. Again.
519 """
518 """
520 user = User.guess_instance(user)
519 user = db.User.guess_instance(user)
521 scm_instance = repo.scm_instance_no_cache()
520 scm_instance = repo.scm_instance_no_cache()
522
521
523 message = message
522 message = message
@@ -590,7 +589,7 b' class ScmModel(object):'
590 :returns: new committed changeset after deletion
589 :returns: new committed changeset after deletion
591 """
590 """
592
591
593 user = User.guess_instance(user)
592 user = db.User.guess_instance(user)
594 scm_instance = repo.scm_instance_no_cache()
593 scm_instance = repo.scm_instance_no_cache()
595
594
596 processed_nodes = []
595 processed_nodes = []
@@ -638,7 +637,7 b' class ScmModel(object):'
638 return tip
637 return tip
639
638
640 def get_unread_journal(self):
639 def get_unread_journal(self):
641 return UserLog.query().count()
640 return db.UserLog.query().count()
642
641
643 def get_repo_landing_revs(self, repo=None):
642 def get_repo_landing_revs(self, repo=None):
644 """
643 """
@@ -749,7 +748,7 b' def AvailableRepoGroupChoices(repo_group'
749
748
750 Top level is -1.
749 Top level is -1.
751 """
750 """
752 groups = RepoGroup.query().all()
751 groups = db.RepoGroup.query().all()
753 if HasPermissionAny('hg.admin')('available repo groups'):
752 if HasPermissionAny('hg.admin')('available repo groups'):
754 groups.append(None)
753 groups.append(None)
755 else:
754 else:
@@ -759,4 +758,4 b' def AvailableRepoGroupChoices(repo_group'
759 for extra in extras:
758 for extra in extras:
760 if not any(rg == extra for rg in groups):
759 if not any(rg == extra for rg in groups):
761 groups.append(extra)
760 groups.append(extra)
762 return RepoGroup.groups_choices(groups=groups)
761 return db.RepoGroup.groups_choices(groups=groups)
@@ -31,8 +31,7 b' from tg.i18n import ugettext as _'
31 from kallithea.lib import ssh
31 from kallithea.lib import ssh
32 from kallithea.lib.utils2 import asbool
32 from kallithea.lib.utils2 import asbool
33 from kallithea.lib.vcs.exceptions import RepositoryError
33 from kallithea.lib.vcs.exceptions import RepositoryError
34 from kallithea.model import meta
34 from kallithea.model import db, meta
35 from kallithea.model.db import User, UserSshKeys
36
35
37
36
38 log = logging.getLogger(__name__)
37 log = logging.getLogger(__name__)
@@ -58,14 +57,14 b' class SshKeyModel(object):'
58 if not description.strip():
57 if not description.strip():
59 description = comment.strip()
58 description = comment.strip()
60
59
61 user = User.guess_instance(user)
60 user = db.User.guess_instance(user)
62
61
63 new_ssh_key = UserSshKeys()
62 new_ssh_key = db.UserSshKeys()
64 new_ssh_key.user_id = user.user_id
63 new_ssh_key.user_id = user.user_id
65 new_ssh_key.description = description
64 new_ssh_key.description = description
66 new_ssh_key.public_key = public_key
65 new_ssh_key.public_key = public_key
67
66
68 for ssh_key in UserSshKeys.query().filter(UserSshKeys.fingerprint == new_ssh_key.fingerprint).all():
67 for ssh_key in db.UserSshKeys.query().filter(db.UserSshKeys.fingerprint == new_ssh_key.fingerprint).all():
69 raise SshKeyModelException(_('SSH key %s is already used by %s') %
68 raise SshKeyModelException(_('SSH key %s is already used by %s') %
70 (new_ssh_key.fingerprint, ssh_key.user.username))
69 (new_ssh_key.fingerprint, ssh_key.user.username))
71
70
@@ -78,10 +77,10 b' class SshKeyModel(object):'
78 Deletes ssh key with given fingerprint for the given user.
77 Deletes ssh key with given fingerprint for the given user.
79 Will raise SshKeyModelException on errors
78 Will raise SshKeyModelException on errors
80 """
79 """
81 ssh_key = UserSshKeys.query().filter(UserSshKeys.fingerprint == fingerprint)
80 ssh_key = db.UserSshKeys.query().filter(db.UserSshKeys.fingerprint == fingerprint)
82
81
83 user = User.guess_instance(user)
82 user = db.User.guess_instance(user)
84 ssh_key = ssh_key.filter(UserSshKeys.user_id == user.user_id)
83 ssh_key = ssh_key.filter(db.UserSshKeys.user_id == user.user_id)
85
84
86 ssh_key = ssh_key.scalar()
85 ssh_key = ssh_key.scalar()
87 if ssh_key is None:
86 if ssh_key is None:
@@ -89,9 +88,9 b' class SshKeyModel(object):'
89 meta.Session().delete(ssh_key)
88 meta.Session().delete(ssh_key)
90
89
91 def get_ssh_keys(self, user):
90 def get_ssh_keys(self, user):
92 user = User.guess_instance(user)
91 user = db.User.guess_instance(user)
93 user_ssh_keys = UserSshKeys.query() \
92 user_ssh_keys = db.UserSshKeys.query() \
94 .filter(UserSshKeys.user_id == user.user_id).all()
93 .filter(db.UserSshKeys.user_id == user.user_id).all()
95 return user_ssh_keys
94 return user_ssh_keys
96
95
97 def write_authorized_keys(self):
96 def write_authorized_keys(self):
@@ -131,7 +130,7 b' class SshKeyModel(object):'
131 fh, tmp_authorized_keys = tempfile.mkstemp('.authorized_keys', dir=os.path.dirname(authorized_keys))
130 fh, tmp_authorized_keys = tempfile.mkstemp('.authorized_keys', dir=os.path.dirname(authorized_keys))
132 with os.fdopen(fh, 'w') as f:
131 with os.fdopen(fh, 'w') as f:
133 f.write("# WARNING: This .ssh/authorized_keys file is managed by Kallithea. Manual editing or adding new entries will make Kallithea back off.\n")
132 f.write("# WARNING: This .ssh/authorized_keys file is managed by Kallithea. Manual editing or adding new entries will make Kallithea back off.\n")
134 for key in UserSshKeys.query().join(UserSshKeys.user).filter(User.active == True):
133 for key in db.UserSshKeys.query().join(db.UserSshKeys.user).filter(db.User.active == True):
135 f.write(ssh.authorized_keys_line(kallithea_cli_path, config['__file__'], key))
134 f.write(ssh.authorized_keys_line(kallithea_cli_path, config['__file__'], key))
136 os.chmod(tmp_authorized_keys, stat.S_IRUSR | stat.S_IWUSR)
135 os.chmod(tmp_authorized_keys, stat.S_IRUSR | stat.S_IWUSR)
137 # Note: simple overwrite / rename isn't enough to replace the file on Windows
136 # Note: simple overwrite / rename isn't enough to replace the file on Windows
@@ -38,8 +38,7 b' from tg.i18n import ugettext as _'
38
38
39 from kallithea.lib.exceptions import DefaultUserException, UserOwnsReposException
39 from kallithea.lib.exceptions import DefaultUserException, UserOwnsReposException
40 from kallithea.lib.utils2 import generate_api_key, get_current_authuser
40 from kallithea.lib.utils2 import generate_api_key, get_current_authuser
41 from kallithea.model import meta
41 from kallithea.model import db, meta
42 from kallithea.model.db import Permission, User, UserEmailMap, UserIpMap, UserToPerm
43
42
44
43
45 log = logging.getLogger(__name__)
44 log = logging.getLogger(__name__)
@@ -49,11 +48,11 b' class UserModel(object):'
49 password_reset_token_lifetime = 86400 # 24 hours
48 password_reset_token_lifetime = 86400 # 24 hours
50
49
51 def get(self, user_id):
50 def get(self, user_id):
52 user = User.query()
51 user = db.User.query()
53 return user.get(user_id)
52 return user.get(user_id)
54
53
55 def get_user(self, user):
54 def get_user(self, user):
56 return User.guess_instance(user)
55 return db.User.guess_instance(user)
57
56
58 def create(self, form_data, cur_user=None):
57 def create(self, form_data, cur_user=None):
59 if not cur_user:
58 if not cur_user:
@@ -74,7 +73,7 b' class UserModel(object):'
74 check_allowed_create_user(user_data, cur_user)
73 check_allowed_create_user(user_data, cur_user)
75 from kallithea.lib.auth import get_crypt_password
74 from kallithea.lib.auth import get_crypt_password
76
75
77 new_user = User()
76 new_user = db.User()
78 for k, v in form_data.items():
77 for k, v in form_data.items():
79 if k == 'password':
78 if k == 'password':
80 v = get_crypt_password(v)
79 v = get_crypt_password(v)
@@ -121,10 +120,10 b' class UserModel(object):'
121 check_allowed_create_user(user_data, cur_user)
120 check_allowed_create_user(user_data, cur_user)
122
121
123 log.debug('Checking for %s account in Kallithea database', username)
122 log.debug('Checking for %s account in Kallithea database', username)
124 user = User.get_by_username(username, case_insensitive=True)
123 user = db.User.get_by_username(username, case_insensitive=True)
125 if user is None:
124 if user is None:
126 log.debug('creating new user %s', username)
125 log.debug('creating new user %s', username)
127 new_user = User()
126 new_user = db.User()
128 edit = False
127 edit = False
129 else:
128 else:
130 log.debug('updating user %s', username)
129 log.debug('updating user %s', username)
@@ -170,7 +169,7 b' class UserModel(object):'
170 from kallithea.model.notification import NotificationModel
169 from kallithea.model.notification import NotificationModel
171
170
172 form_data['admin'] = False
171 form_data['admin'] = False
173 form_data['extern_type'] = User.DEFAULT_AUTH_TYPE
172 form_data['extern_type'] = db.User.DEFAULT_AUTH_TYPE
174 form_data['extern_name'] = ''
173 form_data['extern_name'] = ''
175 new_user = self.create(form_data)
174 new_user = self.create(form_data)
176
175
@@ -218,7 +217,7 b' class UserModel(object):'
218 def update_user(self, user, **kwargs):
217 def update_user(self, user, **kwargs):
219 from kallithea.lib.auth import get_crypt_password
218 from kallithea.lib.auth import get_crypt_password
220
219
221 user = User.guess_instance(user)
220 user = db.User.guess_instance(user)
222 if user.is_default_user:
221 if user.is_default_user:
223 raise DefaultUserException(
222 raise DefaultUserException(
224 _("You can't edit this user since it's"
223 _("You can't edit this user since it's"
@@ -235,7 +234,7 b' class UserModel(object):'
235 def delete(self, user, cur_user=None):
234 def delete(self, user, cur_user=None):
236 if cur_user is None:
235 if cur_user is None:
237 cur_user = getattr(get_current_authuser(), 'username', None)
236 cur_user = getattr(get_current_authuser(), 'username', None)
238 user = User.guess_instance(user)
237 user = db.User.guess_instance(user)
239
238
240 if user.is_default_user:
239 if user.is_default_user:
241 raise DefaultUserException(
240 raise DefaultUserException(
@@ -320,7 +319,7 b' class UserModel(object):'
320 from kallithea.model.notification import EmailNotificationModel
319 from kallithea.model.notification import EmailNotificationModel
321
320
322 user_email = data['email']
321 user_email = data['email']
323 user = User.get_by_email(user_email)
322 user = db.User.get_by_email(user_email)
324 timestamp = int(time.time())
323 timestamp = int(time.time())
325 if user is not None:
324 if user is not None:
326 if self.can_change_password(user):
325 if self.can_change_password(user):
@@ -361,7 +360,7 b' class UserModel(object):'
361
360
362 def verify_reset_password_token(self, email, timestamp, token):
361 def verify_reset_password_token(self, email, timestamp, token):
363 import kallithea.lib.helpers as h
362 import kallithea.lib.helpers as h
364 user = User.get_by_email(email)
363 user = db.User.get_by_email(email)
365 if user is None:
364 if user is None:
366 log.debug("user with email %s not found", email)
365 log.debug("user with email %s not found", email)
367 return False
366 return False
@@ -386,7 +385,7 b' class UserModel(object):'
386 def reset_password(self, user_email, new_passwd):
385 def reset_password(self, user_email, new_passwd):
387 from kallithea.lib import auth
386 from kallithea.lib import auth
388 from kallithea.lib.celerylib import tasks
387 from kallithea.lib.celerylib import tasks
389 user = User.get_by_email(user_email)
388 user = db.User.get_by_email(user_email)
390 if user is not None:
389 if user is not None:
391 if not self.can_change_password(user):
390 if not self.can_change_password(user):
392 raise Exception('trying to change password for external user')
391 raise Exception('trying to change password for external user')
@@ -404,11 +403,11 b' class UserModel(object):'
404 return True
403 return True
405
404
406 def has_perm(self, user, perm):
405 def has_perm(self, user, perm):
407 perm = Permission.guess_instance(perm)
406 perm = db.Permission.guess_instance(perm)
408 user = User.guess_instance(user)
407 user = db.User.guess_instance(user)
409
408
410 return UserToPerm.query().filter(UserToPerm.user == user) \
409 return db.UserToPerm.query().filter(db.UserToPerm.user == user) \
411 .filter(UserToPerm.permission == perm).scalar() is not None
410 .filter(db.UserToPerm.permission == perm).scalar() is not None
412
411
413 def grant_perm(self, user, perm):
412 def grant_perm(self, user, perm):
414 """
413 """
@@ -417,16 +416,16 b' class UserModel(object):'
417 :param user:
416 :param user:
418 :param perm:
417 :param perm:
419 """
418 """
420 user = User.guess_instance(user)
419 user = db.User.guess_instance(user)
421 perm = Permission.guess_instance(perm)
420 perm = db.Permission.guess_instance(perm)
422 # if this permission is already granted skip it
421 # if this permission is already granted skip it
423 _perm = UserToPerm.query() \
422 _perm = db.UserToPerm.query() \
424 .filter(UserToPerm.user == user) \
423 .filter(db.UserToPerm.user == user) \
425 .filter(UserToPerm.permission == perm) \
424 .filter(db.UserToPerm.permission == perm) \
426 .scalar()
425 .scalar()
427 if _perm:
426 if _perm:
428 return
427 return
429 new = UserToPerm()
428 new = db.UserToPerm()
430 new.user = user
429 new.user = user
431 new.permission = perm
430 new.permission = perm
432 meta.Session().add(new)
431 meta.Session().add(new)
@@ -439,12 +438,12 b' class UserModel(object):'
439 :param user:
438 :param user:
440 :param perm:
439 :param perm:
441 """
440 """
442 user = User.guess_instance(user)
441 user = db.User.guess_instance(user)
443 perm = Permission.guess_instance(perm)
442 perm = db.Permission.guess_instance(perm)
444
443
445 UserToPerm.query().filter(
444 db.UserToPerm.query().filter(
446 UserToPerm.user == user,
445 db.UserToPerm.user == user,
447 UserToPerm.permission == perm,
446 db.UserToPerm.permission == perm,
448 ).delete()
447 ).delete()
449
448
450 def add_extra_email(self, user, email):
449 def add_extra_email(self, user, email):
@@ -457,9 +456,9 b' class UserModel(object):'
457 from kallithea.model import forms
456 from kallithea.model import forms
458 form = forms.UserExtraEmailForm()()
457 form = forms.UserExtraEmailForm()()
459 data = form.to_python(dict(email=email))
458 data = form.to_python(dict(email=email))
460 user = User.guess_instance(user)
459 user = db.User.guess_instance(user)
461
460
462 obj = UserEmailMap()
461 obj = db.UserEmailMap()
463 obj.user = user
462 obj.user = user
464 obj.email = data['email']
463 obj.email = data['email']
465 meta.Session().add(obj)
464 meta.Session().add(obj)
@@ -472,8 +471,8 b' class UserModel(object):'
472 :param user:
471 :param user:
473 :param email_id:
472 :param email_id:
474 """
473 """
475 user = User.guess_instance(user)
474 user = db.User.guess_instance(user)
476 obj = UserEmailMap.query().get(email_id)
475 obj = db.UserEmailMap.query().get(email_id)
477 if obj is not None:
476 if obj is not None:
478 meta.Session().delete(obj)
477 meta.Session().delete(obj)
479
478
@@ -487,9 +486,9 b' class UserModel(object):'
487 from kallithea.model import forms
486 from kallithea.model import forms
488 form = forms.UserExtraIpForm()()
487 form = forms.UserExtraIpForm()()
489 data = form.to_python(dict(ip=ip))
488 data = form.to_python(dict(ip=ip))
490 user = User.guess_instance(user)
489 user = db.User.guess_instance(user)
491
490
492 obj = UserIpMap()
491 obj = db.UserIpMap()
493 obj.user = user
492 obj.user = user
494 obj.ip_addr = data['ip']
493 obj.ip_addr = data['ip']
495 meta.Session().add(obj)
494 meta.Session().add(obj)
@@ -502,7 +501,7 b' class UserModel(object):'
502 :param user:
501 :param user:
503 :param ip_id:
502 :param ip_id:
504 """
503 """
505 user = User.guess_instance(user)
504 user = db.User.guess_instance(user)
506 obj = UserIpMap.query().get(ip_id)
505 obj = db.UserIpMap.query().get(ip_id)
507 if obj:
506 if obj:
508 meta.Session().delete(obj)
507 meta.Session().delete(obj)
@@ -28,8 +28,7 b' import logging'
28 import traceback
28 import traceback
29
29
30 from kallithea.lib.exceptions import RepoGroupAssignmentError, UserGroupsAssignedException
30 from kallithea.lib.exceptions import RepoGroupAssignmentError, UserGroupsAssignedException
31 from kallithea.model import meta
31 from kallithea.model import db, meta
32 from kallithea.model.db import Permission, User, UserGroup, UserGroupMember, UserGroupRepoToPerm, UserGroupToPerm, UserGroupUserGroupToPerm, UserUserGroupToPerm
33
32
34
33
35 log = logging.getLogger(__name__)
34 log = logging.getLogger(__name__)
@@ -40,14 +39,14 b' class UserGroupModel(object):'
40 def _create_default_perms(self, user_group):
39 def _create_default_perms(self, user_group):
41 # create default permission
40 # create default permission
42 default_perm = 'usergroup.read'
41 default_perm = 'usergroup.read'
43 def_user = User.get_default_user()
42 def_user = db.User.get_default_user()
44 for p in def_user.user_perms:
43 for p in def_user.user_perms:
45 if p.permission.permission_name.startswith('usergroup.'):
44 if p.permission.permission_name.startswith('usergroup.'):
46 default_perm = p.permission.permission_name
45 default_perm = p.permission.permission_name
47 break
46 break
48
47
49 user_group_to_perm = UserUserGroupToPerm()
48 user_group_to_perm = db.UserUserGroupToPerm()
50 user_group_to_perm.permission = Permission.get_by_key(default_perm)
49 user_group_to_perm.permission = db.Permission.get_by_key(default_perm)
51
50
52 user_group_to_perm.user_group = user_group
51 user_group_to_perm.user_group = user_group
53 user_group_to_perm.user_id = def_user.user_id
52 user_group_to_perm.user_id = def_user.user_id
@@ -89,18 +88,18 b' class UserGroupModel(object):'
89 )
88 )
90
89
91 def get(self, user_group_id):
90 def get(self, user_group_id):
92 return UserGroup.get(user_group_id)
91 return db.UserGroup.get(user_group_id)
93
92
94 def get_group(self, user_group):
93 def get_group(self, user_group):
95 return UserGroup.guess_instance(user_group)
94 return db.UserGroup.guess_instance(user_group)
96
95
97 def get_by_name(self, name, case_insensitive=False):
96 def get_by_name(self, name, case_insensitive=False):
98 return UserGroup.get_by_group_name(name, case_insensitive=case_insensitive)
97 return db.UserGroup.get_by_group_name(name, case_insensitive=case_insensitive)
99
98
100 def create(self, name, description, owner, active=True, group_data=None):
99 def create(self, name, description, owner, active=True, group_data=None):
101 try:
100 try:
102 new_user_group = UserGroup()
101 new_user_group = db.UserGroup()
103 new_user_group.owner = User.guess_instance(owner)
102 new_user_group.owner = db.User.guess_instance(owner)
104 new_user_group.users_group_name = name
103 new_user_group.users_group_name = name
105 new_user_group.user_group_description = description
104 new_user_group.user_group_description = description
106 new_user_group.users_group_active = active
105 new_user_group.users_group_active = active
@@ -120,7 +119,7 b' class UserGroupModel(object):'
120 def update(self, user_group, form_data):
119 def update(self, user_group, form_data):
121
120
122 try:
121 try:
123 user_group = UserGroup.guess_instance(user_group)
122 user_group = db.UserGroup.guess_instance(user_group)
124
123
125 for k, v in form_data.items():
124 for k, v in form_data.items():
126 if k == 'users_group_members':
125 if k == 'users_group_members':
@@ -128,7 +127,7 b' class UserGroupModel(object):'
128 if v:
127 if v:
129 v = [v] if isinstance(v, str) else v
128 v = [v] if isinstance(v, str) else v
130 for u_id in set(v):
129 for u_id in set(v):
131 member = UserGroupMember(user_group.users_group_id, u_id)
130 member = db.UserGroupMember(user_group.users_group_id, u_id)
132 members_list.append(member)
131 members_list.append(member)
133 meta.Session().add(member)
132 meta.Session().add(member)
134 user_group.members = members_list
133 user_group.members = members_list
@@ -150,11 +149,11 b' class UserGroupModel(object):'
150 :param user_group:
149 :param user_group:
151 :param force:
150 :param force:
152 """
151 """
153 user_group = UserGroup.guess_instance(user_group)
152 user_group = db.UserGroup.guess_instance(user_group)
154 try:
153 try:
155 # check if this group is not assigned to repo
154 # check if this group is not assigned to repo
156 assigned_groups = UserGroupRepoToPerm.query() \
155 assigned_groups = db.UserGroupRepoToPerm.query() \
157 .filter(UserGroupRepoToPerm.users_group == user_group).all()
156 .filter(db.UserGroupRepoToPerm.users_group == user_group).all()
158 assigned_groups = [x.repository.repo_name for x in assigned_groups]
157 assigned_groups = [x.repository.repo_name for x in assigned_groups]
159
158
160 if assigned_groups and not force:
159 if assigned_groups and not force:
@@ -167,8 +166,8 b' class UserGroupModel(object):'
167
166
168 def add_user_to_group(self, user_group, user):
167 def add_user_to_group(self, user_group, user):
169 """Return True if user already is in the group - else return the new UserGroupMember"""
168 """Return True if user already is in the group - else return the new UserGroupMember"""
170 user_group = UserGroup.guess_instance(user_group)
169 user_group = db.UserGroup.guess_instance(user_group)
171 user = User.guess_instance(user)
170 user = db.User.guess_instance(user)
172
171
173 for m in user_group.members:
172 for m in user_group.members:
174 u = m.user
173 u = m.user
@@ -177,7 +176,7 b' class UserGroupModel(object):'
177 return True
176 return True
178
177
179 try:
178 try:
180 user_group_member = UserGroupMember()
179 user_group_member = db.UserGroupMember()
181 user_group_member.user = user
180 user_group_member.user = user
182 user_group_member.users_group = user_group
181 user_group_member.users_group = user_group
183
182
@@ -191,8 +190,8 b' class UserGroupModel(object):'
191 raise
190 raise
192
191
193 def remove_user_from_group(self, user_group, user):
192 def remove_user_from_group(self, user_group, user):
194 user_group = UserGroup.guess_instance(user_group)
193 user_group = db.UserGroup.guess_instance(user_group)
195 user = User.guess_instance(user)
194 user = db.User.guess_instance(user)
196
195
197 user_group_member = None
196 user_group_member = None
198 for m in user_group.members:
197 for m in user_group.members:
@@ -213,38 +212,38 b' class UserGroupModel(object):'
213 return False
212 return False
214
213
215 def has_perm(self, user_group, perm):
214 def has_perm(self, user_group, perm):
216 user_group = UserGroup.guess_instance(user_group)
215 user_group = db.UserGroup.guess_instance(user_group)
217 perm = Permission.guess_instance(perm)
216 perm = db.Permission.guess_instance(perm)
218
217
219 return UserGroupToPerm.query() \
218 return db.UserGroupToPerm.query() \
220 .filter(UserGroupToPerm.users_group == user_group) \
219 .filter(db.UserGroupToPerm.users_group == user_group) \
221 .filter(UserGroupToPerm.permission == perm).scalar() is not None
220 .filter(db.UserGroupToPerm.permission == perm).scalar() is not None
222
221
223 def grant_perm(self, user_group, perm):
222 def grant_perm(self, user_group, perm):
224 user_group = UserGroup.guess_instance(user_group)
223 user_group = db.UserGroup.guess_instance(user_group)
225 perm = Permission.guess_instance(perm)
224 perm = db.Permission.guess_instance(perm)
226
225
227 # if this permission is already granted skip it
226 # if this permission is already granted skip it
228 _perm = UserGroupToPerm.query() \
227 _perm = db.UserGroupToPerm.query() \
229 .filter(UserGroupToPerm.users_group == user_group) \
228 .filter(db.UserGroupToPerm.users_group == user_group) \
230 .filter(UserGroupToPerm.permission == perm) \
229 .filter(db.UserGroupToPerm.permission == perm) \
231 .scalar()
230 .scalar()
232 if _perm:
231 if _perm:
233 return
232 return
234
233
235 new = UserGroupToPerm()
234 new = db.UserGroupToPerm()
236 new.users_group = user_group
235 new.users_group = user_group
237 new.permission = perm
236 new.permission = perm
238 meta.Session().add(new)
237 meta.Session().add(new)
239 return new
238 return new
240
239
241 def revoke_perm(self, user_group, perm):
240 def revoke_perm(self, user_group, perm):
242 user_group = UserGroup.guess_instance(user_group)
241 user_group = db.UserGroup.guess_instance(user_group)
243 perm = Permission.guess_instance(perm)
242 perm = db.Permission.guess_instance(perm)
244
243
245 obj = UserGroupToPerm.query() \
244 obj = db.UserGroupToPerm.query() \
246 .filter(UserGroupToPerm.users_group == user_group) \
245 .filter(db.UserGroupToPerm.users_group == user_group) \
247 .filter(UserGroupToPerm.permission == perm).scalar()
246 .filter(db.UserGroupToPerm.permission == perm).scalar()
248 if obj is not None:
247 if obj is not None:
249 meta.Session().delete(obj)
248 meta.Session().delete(obj)
250
249
@@ -259,18 +258,18 b' class UserGroupModel(object):'
259 :param perm: Instance of Permission, or permission_name
258 :param perm: Instance of Permission, or permission_name
260 """
259 """
261
260
262 user_group = UserGroup.guess_instance(user_group)
261 user_group = db.UserGroup.guess_instance(user_group)
263 user = User.guess_instance(user)
262 user = db.User.guess_instance(user)
264 permission = Permission.guess_instance(perm)
263 permission = db.Permission.guess_instance(perm)
265
264
266 # check if we have that permission already
265 # check if we have that permission already
267 obj = UserUserGroupToPerm.query() \
266 obj = db.UserUserGroupToPerm.query() \
268 .filter(UserUserGroupToPerm.user == user) \
267 .filter(db.UserUserGroupToPerm.user == user) \
269 .filter(UserUserGroupToPerm.user_group == user_group) \
268 .filter(db.UserUserGroupToPerm.user_group == user_group) \
270 .scalar()
269 .scalar()
271 if obj is None:
270 if obj is None:
272 # create new !
271 # create new !
273 obj = UserUserGroupToPerm()
272 obj = db.UserUserGroupToPerm()
274 meta.Session().add(obj)
273 meta.Session().add(obj)
275 obj.user_group = user_group
274 obj.user_group = user_group
276 obj.user = user
275 obj.user = user
@@ -287,12 +286,12 b' class UserGroupModel(object):'
287 :param user: Instance of User, user_id or username
286 :param user: Instance of User, user_id or username
288 """
287 """
289
288
290 user_group = UserGroup.guess_instance(user_group)
289 user_group = db.UserGroup.guess_instance(user_group)
291 user = User.guess_instance(user)
290 user = db.User.guess_instance(user)
292
291
293 obj = UserUserGroupToPerm.query() \
292 obj = db.UserUserGroupToPerm.query() \
294 .filter(UserUserGroupToPerm.user == user) \
293 .filter(db.UserUserGroupToPerm.user == user) \
295 .filter(UserUserGroupToPerm.user_group == user_group) \
294 .filter(db.UserUserGroupToPerm.user_group == user_group) \
296 .scalar()
295 .scalar()
297 if obj is not None:
296 if obj is not None:
298 meta.Session().delete(obj)
297 meta.Session().delete(obj)
@@ -306,22 +305,22 b' class UserGroupModel(object):'
306 :param user_group:
305 :param user_group:
307 :param perm:
306 :param perm:
308 """
307 """
309 target_user_group = UserGroup.guess_instance(target_user_group)
308 target_user_group = db.UserGroup.guess_instance(target_user_group)
310 user_group = UserGroup.guess_instance(user_group)
309 user_group = db.UserGroup.guess_instance(user_group)
311 permission = Permission.guess_instance(perm)
310 permission = db.Permission.guess_instance(perm)
312 # forbid assigning same user group to itself
311 # forbid assigning same user group to itself
313 if target_user_group == user_group:
312 if target_user_group == user_group:
314 raise RepoGroupAssignmentError('target repo:%s cannot be '
313 raise RepoGroupAssignmentError('target repo:%s cannot be '
315 'assigned to itself' % target_user_group)
314 'assigned to itself' % target_user_group)
316
315
317 # check if we have that permission already
316 # check if we have that permission already
318 obj = UserGroupUserGroupToPerm.query() \
317 obj = db.UserGroupUserGroupToPerm.query() \
319 .filter(UserGroupUserGroupToPerm.target_user_group == target_user_group) \
318 .filter(db.UserGroupUserGroupToPerm.target_user_group == target_user_group) \
320 .filter(UserGroupUserGroupToPerm.user_group == user_group) \
319 .filter(db.UserGroupUserGroupToPerm.user_group == user_group) \
321 .scalar()
320 .scalar()
322 if obj is None:
321 if obj is None:
323 # create new !
322 # create new !
324 obj = UserGroupUserGroupToPerm()
323 obj = db.UserGroupUserGroupToPerm()
325 meta.Session().add(obj)
324 meta.Session().add(obj)
326 obj.user_group = user_group
325 obj.user_group = user_group
327 obj.target_user_group = target_user_group
326 obj.target_user_group = target_user_group
@@ -336,19 +335,19 b' class UserGroupModel(object):'
336 :param target_user_group:
335 :param target_user_group:
337 :param user_group:
336 :param user_group:
338 """
337 """
339 target_user_group = UserGroup.guess_instance(target_user_group)
338 target_user_group = db.UserGroup.guess_instance(target_user_group)
340 user_group = UserGroup.guess_instance(user_group)
339 user_group = db.UserGroup.guess_instance(user_group)
341
340
342 obj = UserGroupUserGroupToPerm.query() \
341 obj = db.UserGroupUserGroupToPerm.query() \
343 .filter(UserGroupUserGroupToPerm.target_user_group == target_user_group) \
342 .filter(db.UserGroupUserGroupToPerm.target_user_group == target_user_group) \
344 .filter(UserGroupUserGroupToPerm.user_group == user_group) \
343 .filter(db.UserGroupUserGroupToPerm.user_group == user_group) \
345 .scalar()
344 .scalar()
346 if obj is not None:
345 if obj is not None:
347 meta.Session().delete(obj)
346 meta.Session().delete(obj)
348 log.debug('Revoked perm on %s on %s', target_user_group, user_group)
347 log.debug('Revoked perm on %s on %s', target_user_group, user_group)
349
348
350 def enforce_groups(self, user, groups, extern_type=None):
349 def enforce_groups(self, user, groups, extern_type=None):
351 user = User.guess_instance(user)
350 user = db.User.guess_instance(user)
352 log.debug('Enforcing groups %s on user %s', user, groups)
351 log.debug('Enforcing groups %s on user %s', user, groups)
353 current_groups = user.group_member
352 current_groups = user.group_member
354 # find the external created groups
353 # find the external created groups
@@ -363,9 +362,9 b' class UserGroupModel(object):'
363 self.remove_user_from_group(gr, user)
362 self.remove_user_from_group(gr, user)
364
363
365 # now we calculate in which groups user should be == groups params
364 # now we calculate in which groups user should be == groups params
366 owner = User.get_first_admin().username
365 owner = db.User.get_first_admin().username
367 for gr in set(groups):
366 for gr in set(groups):
368 existing_group = UserGroup.get_by_group_name(gr)
367 existing_group = db.UserGroup.get_by_group_name(gr)
369 if not existing_group:
368 if not existing_group:
370 desc = 'Automatically created from plugin:%s' % extern_type
369 desc = 'Automatically created from plugin:%s' % extern_type
371 # we use first admin account to set the owner of the group
370 # we use first admin account to set the owner of the group
@@ -33,7 +33,7 b' from kallithea.lib.compat import Ordered'
33 from kallithea.lib.exceptions import InvalidCloneUriException, LdapImportError
33 from kallithea.lib.exceptions import InvalidCloneUriException, LdapImportError
34 from kallithea.lib.utils import is_valid_repo_uri
34 from kallithea.lib.utils import is_valid_repo_uri
35 from kallithea.lib.utils2 import asbool, aslist, repo_name_slug
35 from kallithea.lib.utils2 import asbool, aslist, repo_name_slug
36 from kallithea.model.db import RepoGroup, Repository, User, UserGroup
36 from kallithea.model import db
37
37
38
38
39 # silence warnings and pylint
39 # silence warnings and pylint
@@ -85,10 +85,10 b' def ValidUsername(edit=False, old_data=N'
85 # check if user is unique
85 # check if user is unique
86 old_un = None
86 old_un = None
87 if edit:
87 if edit:
88 old_un = User.get(old_data.get('user_id')).username
88 old_un = db.User.get(old_data.get('user_id')).username
89
89
90 if old_un != value or not edit:
90 if old_un != value or not edit:
91 if User.get_by_username(value, case_insensitive=True):
91 if db.User.get_by_username(value, case_insensitive=True):
92 msg = self.message('username_exists', state, username=value)
92 msg = self.message('username_exists', state, username=value)
93 raise formencode.Invalid(msg, value, state)
93 raise formencode.Invalid(msg, value, state)
94
94
@@ -112,8 +112,8 b' def ValidRepoUser():'
112
112
113 def _validate_python(self, value, state):
113 def _validate_python(self, value, state):
114 try:
114 try:
115 User.query().filter(User.active == True) \
115 db.User.query().filter(db.User.active == True) \
116 .filter(User.username == value).one()
116 .filter(db.User.username == value).one()
117 except sqlalchemy.exc.InvalidRequestError: # NoResultFound/MultipleResultsFound
117 except sqlalchemy.exc.InvalidRequestError: # NoResultFound/MultipleResultsFound
118 msg = self.message('invalid_username', state, username=value)
118 msg = self.message('invalid_username', state, username=value)
119 raise formencode.Invalid(msg, value, state,
119 raise formencode.Invalid(msg, value, state,
@@ -146,10 +146,10 b' def ValidUserGroup(edit=False, old_data='
146 old_ugname = None
146 old_ugname = None
147 if edit:
147 if edit:
148 old_id = old_data.get('users_group_id')
148 old_id = old_data.get('users_group_id')
149 old_ugname = UserGroup.get(old_id).users_group_name
149 old_ugname = db.UserGroup.get(old_id).users_group_name
150
150
151 if old_ugname != value or not edit:
151 if old_ugname != value or not edit:
152 is_existing_group = UserGroup.get_by_group_name(value,
152 is_existing_group = db.UserGroup.get_by_group_name(value,
153 case_insensitive=True)
153 case_insensitive=True)
154 if is_existing_group:
154 if is_existing_group:
155 msg = self.message('group_exist', state, usergroup=value)
155 msg = self.message('group_exist', state, usergroup=value)
@@ -194,14 +194,14 b' def ValidRepoGroup(edit=False, old_data='
194
194
195 old_gname = None
195 old_gname = None
196 if edit:
196 if edit:
197 old_gname = RepoGroup.get(old_data.get('group_id')).group_name
197 old_gname = db.RepoGroup.get(old_data.get('group_id')).group_name
198
198
199 if old_gname != group_name or not edit:
199 if old_gname != group_name or not edit:
200
200
201 # check group
201 # check group
202 gr = RepoGroup.query() \
202 gr = db.RepoGroup.query() \
203 .filter(func.lower(RepoGroup.group_name) == func.lower(slug)) \
203 .filter(func.lower(db.RepoGroup.group_name) == func.lower(slug)) \
204 .filter(RepoGroup.parent_group_id == parent_group_id) \
204 .filter(db.RepoGroup.parent_group_id == parent_group_id) \
205 .scalar()
205 .scalar()
206 if gr is not None:
206 if gr is not None:
207 msg = self.message('group_exists', state, group_name=slug)
207 msg = self.message('group_exists', state, group_name=slug)
@@ -210,8 +210,8 b' def ValidRepoGroup(edit=False, old_data='
210 )
210 )
211
211
212 # check for same repo
212 # check for same repo
213 repo = Repository.query() \
213 repo = db.Repository.query() \
214 .filter(func.lower(Repository.repo_name) == func.lower(slug)) \
214 .filter(func.lower(db.Repository.repo_name) == func.lower(slug)) \
215 .scalar()
215 .scalar()
216 if repo is not None:
216 if repo is not None:
217 msg = self.message('repo_exists', state, group_name=slug)
217 msg = self.message('repo_exists', state, group_name=slug)
@@ -284,7 +284,7 b' def ValidAuth():'
284 # authenticate returns unused dict but has called
284 # authenticate returns unused dict but has called
285 # plugin._authenticate which has create_or_update'ed the username user in db
285 # plugin._authenticate which has create_or_update'ed the username user in db
286 if auth_modules.authenticate(username, password) is None:
286 if auth_modules.authenticate(username, password) is None:
287 user = User.get_by_username_or_email(username)
287 user = db.User.get_by_username_or_email(username)
288 if user and not user.active:
288 if user and not user.active:
289 log.warning('user %s is disabled', username)
289 log.warning('user %s is disabled', username)
290 msg = self.message('invalid_auth', state)
290 msg = self.message('invalid_auth', state)
@@ -319,7 +319,7 b' def ValidRepoName(edit=False, old_data=N'
319 repo_name = repo_name_slug(value.get('repo_name', ''))
319 repo_name = repo_name_slug(value.get('repo_name', ''))
320 repo_group = value.get('repo_group')
320 repo_group = value.get('repo_group')
321 if repo_group:
321 if repo_group:
322 gr = RepoGroup.get(repo_group)
322 gr = db.RepoGroup.get(repo_group)
323 group_path = gr.full_path
323 group_path = gr.full_path
324 group_name = gr.group_name
324 group_name = gr.group_name
325 # value needs to be aware of group name in order to check
325 # value needs to be aware of group name in order to check
@@ -351,8 +351,8 b' def ValidRepoName(edit=False, old_data=N'
351 rename = old_data.get('repo_name') != repo_name_full
351 rename = old_data.get('repo_name') != repo_name_full
352 create = not edit
352 create = not edit
353 if rename or create:
353 if rename or create:
354 repo = Repository.get_by_repo_name(repo_name_full, case_insensitive=True)
354 repo = db.Repository.get_by_repo_name(repo_name_full, case_insensitive=True)
355 repo_group = RepoGroup.get_by_group_name(repo_name_full, case_insensitive=True)
355 repo_group = db.RepoGroup.get_by_group_name(repo_name_full, case_insensitive=True)
356 if group_path != '':
356 if group_path != '':
357 if repo is not None:
357 if repo is not None:
358 msg = self.message('repository_in_group_exists', state,
358 msg = self.message('repository_in_group_exists', state,
@@ -451,7 +451,7 b' def CanWriteGroup(old_data=None):'
451 return value
451 return value
452
452
453 def _validate_python(self, value, state):
453 def _validate_python(self, value, state):
454 gr = RepoGroup.get(value)
454 gr = db.RepoGroup.get(value)
455 gr_name = gr.group_name if gr is not None else None # None means ROOT location
455 gr_name = gr.group_name if gr is not None else None # None means ROOT location
456
456
457 # create repositories with write permission on group is set to true
457 # create repositories with write permission on group is set to true
@@ -500,7 +500,7 b' def CanCreateGroup(can_create_in_root=Fa'
500 return value
500 return value
501
501
502 def _validate_python(self, value, state):
502 def _validate_python(self, value, state):
503 gr = RepoGroup.get(value)
503 gr = db.RepoGroup.get(value)
504 gr_name = gr.group_name if gr is not None else None # None means ROOT location
504 gr_name = gr.group_name if gr is not None else None # None means ROOT location
505
505
506 if can_create_in_root and gr is None:
506 if can_create_in_root and gr is None:
@@ -565,7 +565,7 b" def ValidPerms(type_='repo'):"
565 t = {'u': 'user',
565 t = {'u': 'user',
566 'g': 'users_group'
566 'g': 'users_group'
567 }[k[0]]
567 }[k[0]]
568 if member_name == User.DEFAULT_USER_NAME:
568 if member_name == db.User.DEFAULT_USER_NAME:
569 if asbool(value.get('repo_private')):
569 if asbool(value.get('repo_private')):
570 # set none for default when updating to
570 # set none for default when updating to
571 # private repo protects against form manipulation
571 # private repo protects against form manipulation
@@ -579,13 +579,13 b" def ValidPerms(type_='repo'):"
579 for k, v, t in perms_new:
579 for k, v, t in perms_new:
580 try:
580 try:
581 if t == 'user':
581 if t == 'user':
582 _user_db = User.query() \
582 _user_db = db.User.query() \
583 .filter(User.active == True) \
583 .filter(db.User.active == True) \
584 .filter(User.username == k).one()
584 .filter(db.User.username == k).one()
585 if t == 'users_group':
585 if t == 'users_group':
586 _user_db = UserGroup.query() \
586 _user_db = db.UserGroup.query() \
587 .filter(UserGroup.users_group_active == True) \
587 .filter(db.UserGroup.users_group_active == True) \
588 .filter(UserGroup.users_group_name == k).one()
588 .filter(db.UserGroup.users_group_name == k).one()
589
589
590 except Exception as e:
590 except Exception as e:
591 log.warning('Error validating %s permission %s', t, k)
591 log.warning('Error validating %s permission %s', t, k)
@@ -647,7 +647,7 b' def UniqSystemEmail(old_data=None):'
647
647
648 def _validate_python(self, value, state):
648 def _validate_python(self, value, state):
649 if (old_data.get('email') or '').lower() != value:
649 if (old_data.get('email') or '').lower() != value:
650 user = User.get_by_email(value)
650 user = db.User.get_by_email(value)
651 if user is not None:
651 if user is not None:
652 msg = self.message('email_taken', state)
652 msg = self.message('email_taken', state)
653 raise formencode.Invalid(msg, value, state,
653 raise formencode.Invalid(msg, value, state,
@@ -666,7 +666,7 b' def ValidSystemEmail():'
666 return value.lower()
666 return value.lower()
667
667
668 def _validate_python(self, value, state):
668 def _validate_python(self, value, state):
669 user = User.get_by_email(value)
669 user = db.User.get_by_email(value)
670 if user is None:
670 if user is None:
671 msg = self.message('non_existing_email', state, email=value)
671 msg = self.message('non_existing_email', state, email=value)
672 raise formencode.Invalid(msg, value, state,
672 raise formencode.Invalid(msg, value, state,
@@ -26,9 +26,8 b' import pytest'
26 from kallithea.lib import ext_json
26 from kallithea.lib import ext_json
27 from kallithea.lib.auth import AuthUser
27 from kallithea.lib.auth import AuthUser
28 from kallithea.lib.utils2 import ascii_bytes
28 from kallithea.lib.utils2 import ascii_bytes
29 from kallithea.model import meta
29 from kallithea.model import db, meta
30 from kallithea.model.changeset_status import ChangesetStatusModel
30 from kallithea.model.changeset_status import ChangesetStatusModel
31 from kallithea.model.db import ChangesetStatus, PullRequest, PullRequestReviewer, RepoGroup, Repository, Setting, Ui, User
32 from kallithea.model.gist import GistModel
31 from kallithea.model.gist import GistModel
33 from kallithea.model.pull_request import PullRequestModel
32 from kallithea.model.pull_request import PullRequestModel
34 from kallithea.model.repo import RepoModel
33 from kallithea.model.repo import RepoModel
@@ -91,7 +90,7 b' class _BaseTestApi(object):'
91
90
92 @classmethod
91 @classmethod
93 def setup_class(cls):
92 def setup_class(cls):
94 cls.usr = User.get_by_username(base.TEST_USER_ADMIN_LOGIN)
93 cls.usr = db.User.get_by_username(base.TEST_USER_ADMIN_LOGIN)
95 cls.apikey = cls.usr.api_key
94 cls.apikey = cls.usr.api_key
96 cls.test_user = UserModel().create_or_update(
95 cls.test_user = UserModel().create_or_update(
97 username='test-api',
96 username='test-api',
@@ -193,8 +192,8 b' class _BaseTestApi(object):'
193 id_, params = _build_data(self.apikey, 'get_users', )
192 id_, params = _build_data(self.apikey, 'get_users', )
194 response = api_call(self, params)
193 response = api_call(self, params)
195 ret_all = []
194 ret_all = []
196 _users = User.query().filter_by(is_default_user=False) \
195 _users = db.User.query().filter_by(is_default_user=False) \
197 .order_by(User.username).all()
196 .order_by(db.User.username).all()
198 for usr in _users:
197 for usr in _users:
199 ret = usr.get_api_data()
198 ret = usr.get_api_data()
200 ret_all.append(jsonify(ret))
199 ret_all.append(jsonify(ret))
@@ -206,7 +205,7 b' class _BaseTestApi(object):'
206 userid=base.TEST_USER_ADMIN_LOGIN)
205 userid=base.TEST_USER_ADMIN_LOGIN)
207 response = api_call(self, params)
206 response = api_call(self, params)
208
207
209 usr = User.get_by_username(base.TEST_USER_ADMIN_LOGIN)
208 usr = db.User.get_by_username(base.TEST_USER_ADMIN_LOGIN)
210 ret = usr.get_api_data()
209 ret = usr.get_api_data()
211 ret['permissions'] = AuthUser(dbuser=usr).permissions
210 ret['permissions'] = AuthUser(dbuser=usr).permissions
212
211
@@ -225,7 +224,7 b' class _BaseTestApi(object):'
225 id_, params = _build_data(self.apikey, 'get_user')
224 id_, params = _build_data(self.apikey, 'get_user')
226 response = api_call(self, params)
225 response = api_call(self, params)
227
226
228 usr = User.get_by_username(base.TEST_USER_ADMIN_LOGIN)
227 usr = db.User.get_by_username(base.TEST_USER_ADMIN_LOGIN)
229 ret = usr.get_api_data()
228 ret = usr.get_api_data()
230 ret['permissions'] = AuthUser(dbuser=usr).permissions
229 ret['permissions'] = AuthUser(dbuser=usr).permissions
231
230
@@ -236,7 +235,7 b' class _BaseTestApi(object):'
236 id_, params = _build_data(self.apikey_regular, 'get_user')
235 id_, params = _build_data(self.apikey_regular, 'get_user')
237 response = api_call(self, params)
236 response = api_call(self, params)
238
237
239 usr = User.get_by_username(self.TEST_USER_LOGIN)
238 usr = db.User.get_by_username(self.TEST_USER_LOGIN)
240 ret = usr.get_api_data()
239 ret = usr.get_api_data()
241 ret['permissions'] = AuthUser(dbuser=usr).permissions
240 ret['permissions'] = AuthUser(dbuser=usr).permissions
242
241
@@ -258,10 +257,10 b' class _BaseTestApi(object):'
258 r = fixture.create_repo(repo_name, repo_type=self.REPO_TYPE)
257 r = fixture.create_repo(repo_name, repo_type=self.REPO_TYPE)
259 # hack around that clone_uri can't be set to to a local path
258 # hack around that clone_uri can't be set to to a local path
260 # (as shown by test_api_create_repo_clone_uri_local)
259 # (as shown by test_api_create_repo_clone_uri_local)
261 r.clone_uri = os.path.join(Ui.get_by_key('paths', '/').ui_value, self.REPO)
260 r.clone_uri = os.path.join(db.Ui.get_by_key('paths', '/').ui_value, self.REPO)
262 meta.Session().commit()
261 meta.Session().commit()
263
262
264 pre_cached_tip = [repo.get_api_data()['last_changeset']['short_id'] for repo in Repository.query().filter(Repository.repo_name == repo_name)]
263 pre_cached_tip = [repo.get_api_data()['last_changeset']['short_id'] for repo in db.Repository.query().filter(db.Repository.repo_name == repo_name)]
265
264
266 id_, params = _build_data(self.apikey, 'pull',
265 id_, params = _build_data(self.apikey, 'pull',
267 repoid=repo_name,)
266 repoid=repo_name,)
@@ -271,7 +270,7 b' class _BaseTestApi(object):'
271 'repository': repo_name}
270 'repository': repo_name}
272 self._compare_ok(id_, expected, given=response.body)
271 self._compare_ok(id_, expected, given=response.body)
273
272
274 post_cached_tip = [repo.get_api_data()['last_changeset']['short_id'] for repo in Repository.query().filter(Repository.repo_name == repo_name)]
273 post_cached_tip = [repo.get_api_data()['last_changeset']['short_id'] for repo in db.Repository.query().filter(db.Repository.repo_name == repo_name)]
275
274
276 fixture.destroy_repo(repo_name)
275 fixture.destroy_repo(repo_name)
277
276
@@ -303,7 +302,7 b' class _BaseTestApi(object):'
303 repo_name = 'test_pull_custom_remote'
302 repo_name = 'test_pull_custom_remote'
304 fixture.create_repo(repo_name, repo_type=self.REPO_TYPE)
303 fixture.create_repo(repo_name, repo_type=self.REPO_TYPE)
305
304
306 custom_remote_path = os.path.join(Ui.get_by_key('paths', '/').ui_value, self.REPO)
305 custom_remote_path = os.path.join(db.Ui.get_by_key('paths', '/').ui_value, self.REPO)
307
306
308 id_, params = _build_data(self.apikey, 'pull',
307 id_, params = _build_data(self.apikey, 'pull',
309 repoid=repo_name,
308 repoid=repo_name,
@@ -361,7 +360,7 b' class _BaseTestApi(object):'
361 password='trololo')
360 password='trololo')
362 response = api_call(self, params)
361 response = api_call(self, params)
363
362
364 usr = User.get_by_username(username)
363 usr = db.User.get_by_username(username)
365 ret = dict(
364 ret = dict(
366 msg='created new user `%s`' % username,
365 msg='created new user `%s`' % username,
367 user=jsonify(usr.get_api_data())
366 user=jsonify(usr.get_api_data())
@@ -382,7 +381,7 b' class _BaseTestApi(object):'
382 email=email)
381 email=email)
383 response = api_call(self, params)
382 response = api_call(self, params)
384
383
385 usr = User.get_by_username(username)
384 usr = db.User.get_by_username(username)
386 ret = dict(
385 ret = dict(
387 msg='created new user `%s`' % username,
386 msg='created new user `%s`' % username,
388 user=jsonify(usr.get_api_data())
387 user=jsonify(usr.get_api_data())
@@ -402,7 +401,7 b' class _BaseTestApi(object):'
402 email=email, extern_name='internal')
401 email=email, extern_name='internal')
403 response = api_call(self, params)
402 response = api_call(self, params)
404
403
405 usr = User.get_by_username(username)
404 usr = db.User.get_by_username(username)
406 ret = dict(
405 ret = dict(
407 msg='created new user `%s`' % username,
406 msg='created new user `%s`' % username,
408 user=jsonify(usr.get_api_data())
407 user=jsonify(usr.get_api_data())
@@ -479,7 +478,7 b' class _BaseTestApi(object):'
479 ('password', 'newpass'),
478 ('password', 'newpass'),
480 ])
479 ])
481 def test_api_update_user(self, name, expected):
480 def test_api_update_user(self, name, expected):
482 usr = User.get_by_username(self.TEST_USER_LOGIN)
481 usr = db.User.get_by_username(self.TEST_USER_LOGIN)
483 kw = {name: expected,
482 kw = {name: expected,
484 'userid': usr.user_id}
483 'userid': usr.user_id}
485 id_, params = _build_data(self.apikey, 'update_user', **kw)
484 id_, params = _build_data(self.apikey, 'update_user', **kw)
@@ -488,7 +487,7 b' class _BaseTestApi(object):'
488 ret = {
487 ret = {
489 'msg': 'updated user ID:%s %s' % (
488 'msg': 'updated user ID:%s %s' % (
490 usr.user_id, self.TEST_USER_LOGIN),
489 usr.user_id, self.TEST_USER_LOGIN),
491 'user': jsonify(User \
490 'user': jsonify(db.User \
492 .get_by_username(self.TEST_USER_LOGIN) \
491 .get_by_username(self.TEST_USER_LOGIN) \
493 .get_api_data())
492 .get_api_data())
494 }
493 }
@@ -497,7 +496,7 b' class _BaseTestApi(object):'
497 self._compare_ok(id_, expected, given=response.body)
496 self._compare_ok(id_, expected, given=response.body)
498
497
499 def test_api_update_user_no_changed_params(self):
498 def test_api_update_user_no_changed_params(self):
500 usr = User.get_by_username(base.TEST_USER_ADMIN_LOGIN)
499 usr = db.User.get_by_username(base.TEST_USER_ADMIN_LOGIN)
501 ret = jsonify(usr.get_api_data())
500 ret = jsonify(usr.get_api_data())
502 id_, params = _build_data(self.apikey, 'update_user',
501 id_, params = _build_data(self.apikey, 'update_user',
503 userid=base.TEST_USER_ADMIN_LOGIN)
502 userid=base.TEST_USER_ADMIN_LOGIN)
@@ -512,7 +511,7 b' class _BaseTestApi(object):'
512 self._compare_ok(id_, expected, given=response.body)
511 self._compare_ok(id_, expected, given=response.body)
513
512
514 def test_api_update_user_by_user_id(self):
513 def test_api_update_user_by_user_id(self):
515 usr = User.get_by_username(base.TEST_USER_ADMIN_LOGIN)
514 usr = db.User.get_by_username(base.TEST_USER_ADMIN_LOGIN)
516 ret = jsonify(usr.get_api_data())
515 ret = jsonify(usr.get_api_data())
517 id_, params = _build_data(self.apikey, 'update_user',
516 id_, params = _build_data(self.apikey, 'update_user',
518 userid=usr.user_id)
517 userid=usr.user_id)
@@ -527,7 +526,7 b' class _BaseTestApi(object):'
527 self._compare_ok(id_, expected, given=response.body)
526 self._compare_ok(id_, expected, given=response.body)
528
527
529 def test_api_update_user_default_user(self):
528 def test_api_update_user_default_user(self):
530 usr = User.get_default_user()
529 usr = db.User.get_default_user()
531 id_, params = _build_data(self.apikey, 'update_user',
530 id_, params = _build_data(self.apikey, 'update_user',
532 userid=usr.user_id)
531 userid=usr.user_id)
533
532
@@ -537,7 +536,7 b' class _BaseTestApi(object):'
537
536
538 @mock.patch.object(UserModel, 'update_user', raise_exception)
537 @mock.patch.object(UserModel, 'update_user', raise_exception)
539 def test_api_update_user_when_exception_happens(self):
538 def test_api_update_user_when_exception_happens(self):
540 usr = User.get_by_username(base.TEST_USER_ADMIN_LOGIN)
539 usr = db.User.get_by_username(base.TEST_USER_ADMIN_LOGIN)
541 ret = jsonify(usr.get_api_data())
540 ret = jsonify(usr.get_api_data())
542 id_, params = _build_data(self.apikey, 'update_user',
541 id_, params = _build_data(self.apikey, 'update_user',
543 userid=usr.user_id)
542 userid=usr.user_id)
@@ -645,7 +644,7 b' class _BaseTestApi(object):'
645
644
646 def test_api_get_repo_by_non_admin_no_permission_to_repo(self):
645 def test_api_get_repo_by_non_admin_no_permission_to_repo(self):
647 RepoModel().grant_user_permission(repo=self.REPO,
646 RepoModel().grant_user_permission(repo=self.REPO,
648 user=User.DEFAULT_USER_NAME,
647 user=db.User.DEFAULT_USER_NAME,
649 perm='repository.none')
648 perm='repository.none')
650 try:
649 try:
651 RepoModel().grant_user_permission(repo=self.REPO,
650 RepoModel().grant_user_permission(repo=self.REPO,
@@ -660,7 +659,7 b' class _BaseTestApi(object):'
660 self._compare_error(id_, expected, given=response.body)
659 self._compare_error(id_, expected, given=response.body)
661 finally:
660 finally:
662 RepoModel().grant_user_permission(repo=self.REPO,
661 RepoModel().grant_user_permission(repo=self.REPO,
663 user=User.DEFAULT_USER_NAME,
662 user=db.User.DEFAULT_USER_NAME,
664 perm='repository.read')
663 perm='repository.read')
665
664
666 def test_api_get_repo_that_doesn_not_exist(self):
665 def test_api_get_repo_that_doesn_not_exist(self):
@@ -678,7 +677,7 b' class _BaseTestApi(object):'
678
677
679 expected = jsonify([
678 expected = jsonify([
680 repo.get_api_data()
679 repo.get_api_data()
681 for repo in Repository.query()
680 for repo in db.Repository.query()
682 ])
681 ])
683
682
684 self._compare_ok(id_, expected, given=response.body)
683 self._compare_ok(id_, expected, given=response.body)
@@ -875,7 +874,7 b' class _BaseTestApi(object):'
875 repo_group_name = '%s/%s' % (TEST_REPO_GROUP, repo_group_basename)
874 repo_group_name = '%s/%s' % (TEST_REPO_GROUP, repo_group_basename)
876 repo_name = '%s/api-repo' % repo_group_name
875 repo_name = '%s/api-repo' % repo_group_name
877
876
878 top_group = RepoGroup.get_by_group_name(TEST_REPO_GROUP)
877 top_group = db.RepoGroup.get_by_group_name(TEST_REPO_GROUP)
879 assert top_group
878 assert top_group
880 rg = fixture.create_repo_group(repo_group_basename, parent_group_id=top_group)
879 rg = fixture.create_repo_group(repo_group_basename, parent_group_id=top_group)
881 meta.Session().commit()
880 meta.Session().commit()
@@ -1302,7 +1301,7 b' class _BaseTestApi(object):'
1302
1301
1303 def test_api_fork_repo_non_admin_no_permission_to_fork(self):
1302 def test_api_fork_repo_non_admin_no_permission_to_fork(self):
1304 RepoModel().grant_user_permission(repo=self.REPO,
1303 RepoModel().grant_user_permission(repo=self.REPO,
1305 user=User.DEFAULT_USER_NAME,
1304 user=db.User.DEFAULT_USER_NAME,
1306 perm='repository.none')
1305 perm='repository.none')
1307 try:
1306 try:
1308 fork_name = 'api-repo-fork'
1307 fork_name = 'api-repo-fork'
@@ -1315,7 +1314,7 b' class _BaseTestApi(object):'
1315 self._compare_error(id_, expected, given=response.body)
1314 self._compare_error(id_, expected, given=response.body)
1316 finally:
1315 finally:
1317 RepoModel().grant_user_permission(repo=self.REPO,
1316 RepoModel().grant_user_permission(repo=self.REPO,
1318 user=User.DEFAULT_USER_NAME,
1317 user=db.User.DEFAULT_USER_NAME,
1319 perm='repository.read')
1318 perm='repository.read')
1320 fixture.destroy_repo(fork_name)
1319 fixture.destroy_repo(fork_name)
1321
1320
@@ -2328,7 +2327,7 b' class _BaseTestApi(object):'
2328 def test_api_get_server_info(self):
2327 def test_api_get_server_info(self):
2329 id_, params = _build_data(self.apikey, 'get_server_info')
2328 id_, params = _build_data(self.apikey, 'get_server_info')
2330 response = api_call(self, params)
2329 response = api_call(self, params)
2331 expected = Setting.get_server_info()
2330 expected = db.Setting.get_server_info()
2332 self._compare_ok(id_, expected, given=response.body)
2331 self._compare_ok(id_, expected, given=response.body)
2333
2332
2334 def test_api_get_changesets(self):
2333 def test_api_get_changesets(self):
@@ -2429,7 +2428,7 b' class _BaseTestApi(object):'
2429 "args": {"pullrequest_id": pull_request_id},
2428 "args": {"pullrequest_id": pull_request_id},
2430 }))
2429 }))
2431 response = api_call(self, params)
2430 response = api_call(self, params)
2432 pullrequest = PullRequest().get(pull_request_id)
2431 pullrequest = db.PullRequest().get(pull_request_id)
2433 expected = {
2432 expected = {
2434 "status": "new",
2433 "status": "new",
2435 "pull_request_id": pull_request_id,
2434 "pull_request_id": pull_request_id,
@@ -2463,9 +2462,9 b' class _BaseTestApi(object):'
2463 }))
2462 }))
2464 response = api_call(self, params)
2463 response = api_call(self, params)
2465 self._compare_ok(random_id, True, given=response.body)
2464 self._compare_ok(random_id, True, given=response.body)
2466 pullrequest = PullRequest().get(pull_request_id)
2465 pullrequest = db.PullRequest().get(pull_request_id)
2467 assert pullrequest.comments[-1].text == ''
2466 assert pullrequest.comments[-1].text == ''
2468 assert pullrequest.status == PullRequest.STATUS_CLOSED
2467 assert pullrequest.status == db.PullRequest.STATUS_CLOSED
2469 assert pullrequest.is_closed() == True
2468 assert pullrequest.is_closed() == True
2470
2469
2471 def test_api_status_pullrequest(self):
2470 def test_api_status_pullrequest(self):
@@ -2474,24 +2473,24 b' class _BaseTestApi(object):'
2474 random_id = random.randrange(1, 9999)
2473 random_id = random.randrange(1, 9999)
2475 params = ascii_bytes(ext_json.dumps({
2474 params = ascii_bytes(ext_json.dumps({
2476 "id": random_id,
2475 "id": random_id,
2477 "api_key": User.get_by_username(base.TEST_USER_REGULAR2_LOGIN).api_key,
2476 "api_key": db.User.get_by_username(base.TEST_USER_REGULAR2_LOGIN).api_key,
2478 "method": "comment_pullrequest",
2477 "method": "comment_pullrequest",
2479 "args": {"pull_request_id": pull_request_id, "status": ChangesetStatus.STATUS_APPROVED},
2478 "args": {"pull_request_id": pull_request_id, "status": db.ChangesetStatus.STATUS_APPROVED},
2480 }))
2479 }))
2481 response = api_call(self, params)
2480 response = api_call(self, params)
2482 pullrequest = PullRequest().get(pull_request_id)
2481 pullrequest = db.PullRequest().get(pull_request_id)
2483 self._compare_error(random_id, "No permission to change pull request status. User needs to be admin, owner or reviewer.", given=response.body)
2482 self._compare_error(random_id, "No permission to change pull request status. User needs to be admin, owner or reviewer.", given=response.body)
2484 assert ChangesetStatus.STATUS_UNDER_REVIEW == ChangesetStatusModel().calculate_pull_request_result(pullrequest)[2]
2483 assert db.ChangesetStatus.STATUS_UNDER_REVIEW == ChangesetStatusModel().calculate_pull_request_result(pullrequest)[2]
2485 params = ascii_bytes(ext_json.dumps({
2484 params = ascii_bytes(ext_json.dumps({
2486 "id": random_id,
2485 "id": random_id,
2487 "api_key": User.get_by_username(base.TEST_USER_REGULAR_LOGIN).api_key,
2486 "api_key": db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN).api_key,
2488 "method": "comment_pullrequest",
2487 "method": "comment_pullrequest",
2489 "args": {"pull_request_id": pull_request_id, "status": ChangesetStatus.STATUS_APPROVED},
2488 "args": {"pull_request_id": pull_request_id, "status": db.ChangesetStatus.STATUS_APPROVED},
2490 }))
2489 }))
2491 response = api_call(self, params)
2490 response = api_call(self, params)
2492 self._compare_ok(random_id, True, given=response.body)
2491 self._compare_ok(random_id, True, given=response.body)
2493 pullrequest = PullRequest().get(pull_request_id)
2492 pullrequest = db.PullRequest().get(pull_request_id)
2494 assert ChangesetStatus.STATUS_APPROVED == ChangesetStatusModel().calculate_pull_request_result(pullrequest)[2]
2493 assert db.ChangesetStatus.STATUS_APPROVED == ChangesetStatusModel().calculate_pull_request_result(pullrequest)[2]
2495
2494
2496 def test_api_comment_pullrequest(self):
2495 def test_api_comment_pullrequest(self):
2497 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, "comment test")
2496 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, "comment test")
@@ -2504,12 +2503,12 b' class _BaseTestApi(object):'
2504 }))
2503 }))
2505 response = api_call(self, params)
2504 response = api_call(self, params)
2506 self._compare_ok(random_id, True, given=response.body)
2505 self._compare_ok(random_id, True, given=response.body)
2507 pullrequest = PullRequest().get(pull_request_id)
2506 pullrequest = db.PullRequest().get(pull_request_id)
2508 assert pullrequest.comments[-1].text == 'Looks good to me'
2507 assert pullrequest.comments[-1].text == 'Looks good to me'
2509
2508
2510 def test_api_edit_reviewers_add_single(self):
2509 def test_api_edit_reviewers_add_single(self):
2511 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2510 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2512 pullrequest = PullRequest().get(pull_request_id)
2511 pullrequest = db.PullRequest().get(pull_request_id)
2513 pullrequest.owner = self.test_user
2512 pullrequest.owner = self.test_user
2514 random_id = random.randrange(1, 9999)
2513 random_id = random.randrange(1, 9999)
2515 params = ascii_bytes(ext_json.dumps({
2514 params = ascii_bytes(ext_json.dumps({
@@ -2522,11 +2521,11 b' class _BaseTestApi(object):'
2522 expected = { 'added': [base.TEST_USER_REGULAR2_LOGIN], 'already_present': [], 'removed': [] }
2521 expected = { 'added': [base.TEST_USER_REGULAR2_LOGIN], 'already_present': [], 'removed': [] }
2523
2522
2524 self._compare_ok(random_id, expected, given=response.body)
2523 self._compare_ok(random_id, expected, given=response.body)
2525 assert User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) in pullrequest.get_reviewer_users()
2524 assert db.User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) in pullrequest.get_reviewer_users()
2526
2525
2527 def test_api_edit_reviewers_add_nonexistent(self):
2526 def test_api_edit_reviewers_add_nonexistent(self):
2528 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2527 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2529 pullrequest = PullRequest().get(pull_request_id)
2528 pullrequest = db.PullRequest().get(pull_request_id)
2530 pullrequest.owner = self.test_user
2529 pullrequest.owner = self.test_user
2531 random_id = random.randrange(1, 9999)
2530 random_id = random.randrange(1, 9999)
2532 params = ascii_bytes(ext_json.dumps({
2531 params = ascii_bytes(ext_json.dumps({
@@ -2541,7 +2540,7 b' class _BaseTestApi(object):'
2541
2540
2542 def test_api_edit_reviewers_add_multiple(self):
2541 def test_api_edit_reviewers_add_multiple(self):
2543 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2542 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2544 pullrequest = PullRequest().get(pull_request_id)
2543 pullrequest = db.PullRequest().get(pull_request_id)
2545 pullrequest.owner = self.test_user
2544 pullrequest.owner = self.test_user
2546 random_id = random.randrange(1, 9999)
2545 random_id = random.randrange(1, 9999)
2547 params = ascii_bytes(ext_json.dumps({
2546 params = ascii_bytes(ext_json.dumps({
@@ -2559,12 +2558,12 b' class _BaseTestApi(object):'
2559 assert set(ext_json.loads(response.body)['result']['already_present']) == set()
2558 assert set(ext_json.loads(response.body)['result']['already_present']) == set()
2560 assert set(ext_json.loads(response.body)['result']['removed']) == set()
2559 assert set(ext_json.loads(response.body)['result']['removed']) == set()
2561
2560
2562 assert User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) in pullrequest.get_reviewer_users()
2561 assert db.User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) in pullrequest.get_reviewer_users()
2563 assert User.get_by_username(self.TEST_USER_LOGIN) in pullrequest.get_reviewer_users()
2562 assert db.User.get_by_username(self.TEST_USER_LOGIN) in pullrequest.get_reviewer_users()
2564
2563
2565 def test_api_edit_reviewers_add_already_present(self):
2564 def test_api_edit_reviewers_add_already_present(self):
2566 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2565 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2567 pullrequest = PullRequest().get(pull_request_id)
2566 pullrequest = db.PullRequest().get(pull_request_id)
2568 pullrequest.owner = self.test_user
2567 pullrequest.owner = self.test_user
2569 random_id = random.randrange(1, 9999)
2568 random_id = random.randrange(1, 9999)
2570 params = ascii_bytes(ext_json.dumps({
2569 params = ascii_bytes(ext_json.dumps({
@@ -2583,12 +2582,12 b' class _BaseTestApi(object):'
2583 }
2582 }
2584
2583
2585 self._compare_ok(random_id, expected, given=response.body)
2584 self._compare_ok(random_id, expected, given=response.body)
2586 assert User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2585 assert db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2587 assert User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) in pullrequest.get_reviewer_users()
2586 assert db.User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) in pullrequest.get_reviewer_users()
2588
2587
2589 def test_api_edit_reviewers_add_closed(self):
2588 def test_api_edit_reviewers_add_closed(self):
2590 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2589 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2591 pullrequest = PullRequest().get(pull_request_id)
2590 pullrequest = db.PullRequest().get(pull_request_id)
2592 pullrequest.owner = self.test_user
2591 pullrequest.owner = self.test_user
2593 PullRequestModel().close_pull_request(pull_request_id)
2592 PullRequestModel().close_pull_request(pull_request_id)
2594 random_id = random.randrange(1, 9999)
2593 random_id = random.randrange(1, 9999)
@@ -2603,8 +2602,8 b' class _BaseTestApi(object):'
2603
2602
2604 def test_api_edit_reviewers_add_not_owner(self):
2603 def test_api_edit_reviewers_add_not_owner(self):
2605 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2604 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2606 pullrequest = PullRequest().get(pull_request_id)
2605 pullrequest = db.PullRequest().get(pull_request_id)
2607 pullrequest.owner = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
2606 pullrequest.owner = db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
2608 random_id = random.randrange(1, 9999)
2607 random_id = random.randrange(1, 9999)
2609 params = ascii_bytes(ext_json.dumps({
2608 params = ascii_bytes(ext_json.dumps({
2610 "id": random_id,
2609 "id": random_id,
@@ -2618,8 +2617,8 b' class _BaseTestApi(object):'
2618
2617
2619 def test_api_edit_reviewers_remove_single(self):
2618 def test_api_edit_reviewers_remove_single(self):
2620 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2619 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2621 pullrequest = PullRequest().get(pull_request_id)
2620 pullrequest = db.PullRequest().get(pull_request_id)
2622 assert User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2621 assert db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2623
2622
2624 pullrequest.owner = self.test_user
2623 pullrequest.owner = self.test_user
2625 random_id = random.randrange(1, 9999)
2624 random_id = random.randrange(1, 9999)
@@ -2636,12 +2635,12 b' class _BaseTestApi(object):'
2636 'removed': [base.TEST_USER_REGULAR_LOGIN],
2635 'removed': [base.TEST_USER_REGULAR_LOGIN],
2637 }
2636 }
2638 self._compare_ok(random_id, expected, given=response.body)
2637 self._compare_ok(random_id, expected, given=response.body)
2639 assert User.get_by_username(base.TEST_USER_REGULAR_LOGIN) not in pullrequest.get_reviewer_users()
2638 assert db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN) not in pullrequest.get_reviewer_users()
2640
2639
2641 def test_api_edit_reviewers_remove_nonexistent(self):
2640 def test_api_edit_reviewers_remove_nonexistent(self):
2642 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2641 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2643 pullrequest = PullRequest().get(pull_request_id)
2642 pullrequest = db.PullRequest().get(pull_request_id)
2644 assert User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2643 assert db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2645
2644
2646 pullrequest.owner = self.test_user
2645 pullrequest.owner = self.test_user
2647 random_id = random.randrange(1, 9999)
2646 random_id = random.randrange(1, 9999)
@@ -2654,13 +2653,13 b' class _BaseTestApi(object):'
2654 response = api_call(self, params)
2653 response = api_call(self, params)
2655
2654
2656 self._compare_error(random_id, "user `999` does not exist", given=response.body)
2655 self._compare_error(random_id, "user `999` does not exist", given=response.body)
2657 assert User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2656 assert db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2658
2657
2659 def test_api_edit_reviewers_remove_nonpresent(self):
2658 def test_api_edit_reviewers_remove_nonpresent(self):
2660 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2659 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2661 pullrequest = PullRequest().get(pull_request_id)
2660 pullrequest = db.PullRequest().get(pull_request_id)
2662 assert User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2661 assert db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2663 assert User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) not in pullrequest.get_reviewer_users()
2662 assert db.User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) not in pullrequest.get_reviewer_users()
2664
2663
2665 pullrequest.owner = self.test_user
2664 pullrequest.owner = self.test_user
2666 random_id = random.randrange(1, 9999)
2665 random_id = random.randrange(1, 9999)
@@ -2678,18 +2677,18 b' class _BaseTestApi(object):'
2678 'removed': [base.TEST_USER_REGULAR2_LOGIN],
2677 'removed': [base.TEST_USER_REGULAR2_LOGIN],
2679 }
2678 }
2680 self._compare_ok(random_id, expected, given=response.body)
2679 self._compare_ok(random_id, expected, given=response.body)
2681 assert User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2680 assert db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2682 assert User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) not in pullrequest.get_reviewer_users()
2681 assert db.User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) not in pullrequest.get_reviewer_users()
2683
2682
2684 def test_api_edit_reviewers_remove_multiple(self):
2683 def test_api_edit_reviewers_remove_multiple(self):
2685 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2684 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2686 pullrequest = PullRequest().get(pull_request_id)
2685 pullrequest = db.PullRequest().get(pull_request_id)
2687 prr = PullRequestReviewer(User.get_by_username(base.TEST_USER_REGULAR2_LOGIN), pullrequest)
2686 prr = db.PullRequestReviewer(db.User.get_by_username(base.TEST_USER_REGULAR2_LOGIN), pullrequest)
2688 meta.Session().add(prr)
2687 meta.Session().add(prr)
2689 meta.Session().commit()
2688 meta.Session().commit()
2690
2689
2691 assert User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2690 assert db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2692 assert User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) in pullrequest.get_reviewer_users()
2691 assert db.User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) in pullrequest.get_reviewer_users()
2693
2692
2694 pullrequest.owner = self.test_user
2693 pullrequest.owner = self.test_user
2695 random_id = random.randrange(1, 9999)
2694 random_id = random.randrange(1, 9999)
@@ -2705,13 +2704,13 b' class _BaseTestApi(object):'
2705 assert set(ext_json.loads(response.body)['result']['added']) == set()
2704 assert set(ext_json.loads(response.body)['result']['added']) == set()
2706 assert set(ext_json.loads(response.body)['result']['already_present']) == set()
2705 assert set(ext_json.loads(response.body)['result']['already_present']) == set()
2707 assert set(ext_json.loads(response.body)['result']['removed']) == set([base.TEST_USER_REGULAR_LOGIN, base.TEST_USER_REGULAR2_LOGIN])
2706 assert set(ext_json.loads(response.body)['result']['removed']) == set([base.TEST_USER_REGULAR_LOGIN, base.TEST_USER_REGULAR2_LOGIN])
2708 assert User.get_by_username(base.TEST_USER_REGULAR_LOGIN) not in pullrequest.get_reviewer_users()
2707 assert db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN) not in pullrequest.get_reviewer_users()
2709 assert User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) not in pullrequest.get_reviewer_users()
2708 assert db.User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) not in pullrequest.get_reviewer_users()
2710
2709
2711 def test_api_edit_reviewers_remove_closed(self):
2710 def test_api_edit_reviewers_remove_closed(self):
2712 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2711 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2713 pullrequest = PullRequest().get(pull_request_id)
2712 pullrequest = db.PullRequest().get(pull_request_id)
2714 assert User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2713 assert db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2715 PullRequestModel().close_pull_request(pull_request_id)
2714 PullRequestModel().close_pull_request(pull_request_id)
2716
2715
2717 pullrequest.owner = self.test_user
2716 pullrequest.owner = self.test_user
@@ -2725,14 +2724,14 b' class _BaseTestApi(object):'
2725 response = api_call(self, params)
2724 response = api_call(self, params)
2726
2725
2727 self._compare_error(random_id, "Cannot edit reviewers of a closed pull request.", given=response.body)
2726 self._compare_error(random_id, "Cannot edit reviewers of a closed pull request.", given=response.body)
2728 assert User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2727 assert db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2729
2728
2730 def test_api_edit_reviewers_remove_not_owner(self):
2729 def test_api_edit_reviewers_remove_not_owner(self):
2731 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2730 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2732 pullrequest = PullRequest().get(pull_request_id)
2731 pullrequest = db.PullRequest().get(pull_request_id)
2733 assert User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2732 assert db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2734
2733
2735 pullrequest.owner = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
2734 pullrequest.owner = db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
2736 random_id = random.randrange(1, 9999)
2735 random_id = random.randrange(1, 9999)
2737 params = ascii_bytes(ext_json.dumps({
2736 params = ascii_bytes(ext_json.dumps({
2738 "id": random_id,
2737 "id": random_id,
@@ -2743,13 +2742,13 b' class _BaseTestApi(object):'
2743 response = api_call(self, params)
2742 response = api_call(self, params)
2744
2743
2745 self._compare_error(random_id, "No permission to edit reviewers of this pull request. User needs to be admin or pull request owner.", given=response.body)
2744 self._compare_error(random_id, "No permission to edit reviewers of this pull request. User needs to be admin or pull request owner.", given=response.body)
2746 assert User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2745 assert db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2747
2746
2748 def test_api_edit_reviewers_add_remove_single(self):
2747 def test_api_edit_reviewers_add_remove_single(self):
2749 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2748 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2750 pullrequest = PullRequest().get(pull_request_id)
2749 pullrequest = db.PullRequest().get(pull_request_id)
2751 assert User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2750 assert db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2752 assert User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) not in pullrequest.get_reviewer_users()
2751 assert db.User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) not in pullrequest.get_reviewer_users()
2753
2752
2754 pullrequest.owner = self.test_user
2753 pullrequest.owner = self.test_user
2755 random_id = random.randrange(1, 9999)
2754 random_id = random.randrange(1, 9999)
@@ -2769,18 +2768,18 b' class _BaseTestApi(object):'
2769 'removed': [base.TEST_USER_REGULAR_LOGIN],
2768 'removed': [base.TEST_USER_REGULAR_LOGIN],
2770 }
2769 }
2771 self._compare_ok(random_id, expected, given=response.body)
2770 self._compare_ok(random_id, expected, given=response.body)
2772 assert User.get_by_username(base.TEST_USER_REGULAR_LOGIN) not in pullrequest.get_reviewer_users()
2771 assert db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN) not in pullrequest.get_reviewer_users()
2773 assert User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) in pullrequest.get_reviewer_users()
2772 assert db.User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) in pullrequest.get_reviewer_users()
2774
2773
2775 def test_api_edit_reviewers_add_remove_multiple(self):
2774 def test_api_edit_reviewers_add_remove_multiple(self):
2776 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2775 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2777 pullrequest = PullRequest().get(pull_request_id)
2776 pullrequest = db.PullRequest().get(pull_request_id)
2778 prr = PullRequestReviewer(User.get_by_username(base.TEST_USER_ADMIN_LOGIN), pullrequest)
2777 prr = db.PullRequestReviewer(db.User.get_by_username(base.TEST_USER_ADMIN_LOGIN), pullrequest)
2779 meta.Session().add(prr)
2778 meta.Session().add(prr)
2780 meta.Session().commit()
2779 meta.Session().commit()
2781 assert User.get_by_username(base.TEST_USER_ADMIN_LOGIN) in pullrequest.get_reviewer_users()
2780 assert db.User.get_by_username(base.TEST_USER_ADMIN_LOGIN) in pullrequest.get_reviewer_users()
2782 assert User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2781 assert db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2783 assert User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) not in pullrequest.get_reviewer_users()
2782 assert db.User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) not in pullrequest.get_reviewer_users()
2784
2783
2785 pullrequest.owner = self.test_user
2784 pullrequest.owner = self.test_user
2786 random_id = random.randrange(1, 9999)
2785 random_id = random.randrange(1, 9999)
@@ -2799,16 +2798,16 b' class _BaseTestApi(object):'
2799 assert set(ext_json.loads(response.body)['result']['added']) == set([base.TEST_USER_REGULAR2_LOGIN])
2798 assert set(ext_json.loads(response.body)['result']['added']) == set([base.TEST_USER_REGULAR2_LOGIN])
2800 assert set(ext_json.loads(response.body)['result']['already_present']) == set()
2799 assert set(ext_json.loads(response.body)['result']['already_present']) == set()
2801 assert set(ext_json.loads(response.body)['result']['removed']) == set([base.TEST_USER_REGULAR_LOGIN, base.TEST_USER_ADMIN_LOGIN])
2800 assert set(ext_json.loads(response.body)['result']['removed']) == set([base.TEST_USER_REGULAR_LOGIN, base.TEST_USER_ADMIN_LOGIN])
2802 assert User.get_by_username(base.TEST_USER_ADMIN_LOGIN) not in pullrequest.get_reviewer_users()
2801 assert db.User.get_by_username(base.TEST_USER_ADMIN_LOGIN) not in pullrequest.get_reviewer_users()
2803 assert User.get_by_username(base.TEST_USER_REGULAR_LOGIN) not in pullrequest.get_reviewer_users()
2802 assert db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN) not in pullrequest.get_reviewer_users()
2804 assert User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) in pullrequest.get_reviewer_users()
2803 assert db.User.get_by_username(base.TEST_USER_REGULAR2_LOGIN) in pullrequest.get_reviewer_users()
2805
2804
2806 def test_api_edit_reviewers_invalid_params(self):
2805 def test_api_edit_reviewers_invalid_params(self):
2807 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2806 pull_request_id = fixture.create_pullrequest(self, self.REPO, self.TEST_PR_SRC, self.TEST_PR_DST, 'edit reviewer test')
2808 pullrequest = PullRequest().get(pull_request_id)
2807 pullrequest = db.PullRequest().get(pull_request_id)
2809 assert User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2808 assert db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN) in pullrequest.get_reviewer_users()
2810
2809
2811 pullrequest.owner = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
2810 pullrequest.owner = db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
2812 random_id = random.randrange(1, 9999)
2811 random_id = random.randrange(1, 9999)
2813 params = ascii_bytes(ext_json.dumps({
2812 params = ascii_bytes(ext_json.dumps({
2814 "id": random_id,
2813 "id": random_id,
@@ -23,7 +23,7 b' import pytest'
23 from webtest import TestApp
23 from webtest import TestApp
24
24
25 from kallithea.lib.utils2 import ascii_str
25 from kallithea.lib.utils2 import ascii_str
26 from kallithea.model.db import User
26 from kallithea.model import db
27
27
28
28
29 log = logging.getLogger(__name__)
29 log = logging.getLogger(__name__)
@@ -166,12 +166,12 b' class TestController(object):'
166 return response.session['authuser']
166 return response.session['authuser']
167
167
168 def _get_logged_user(self):
168 def _get_logged_user(self):
169 return User.get_by_username(self._logged_username)
169 return db.User.get_by_username(self._logged_username)
170
170
171 def assert_authenticated_user(self, response, expected_username):
171 def assert_authenticated_user(self, response, expected_username):
172 cookie = response.session.get('authuser')
172 cookie = response.session.get('authuser')
173 user = cookie and cookie.get('user_id')
173 user = cookie and cookie.get('user_id')
174 user = user and User.get(user)
174 user = user and db.User.get(user)
175 user = user and user.username
175 user = user and user.username
176 assert user == expected_username
176 assert user == expected_username
177
177
@@ -15,8 +15,7 b' import kallithea.tests.base # FIXME: ne'
15 from kallithea.controllers.root import RootController
15 from kallithea.controllers.root import RootController
16 from kallithea.lib import inifile
16 from kallithea.lib import inifile
17 from kallithea.lib.utils import repo2db_mapper
17 from kallithea.lib.utils import repo2db_mapper
18 from kallithea.model import meta
18 from kallithea.model import db, meta
19 from kallithea.model.db import Setting, User, UserIpMap
20 from kallithea.model.scm import ScmModel
19 from kallithea.model.scm import ScmModel
21 from kallithea.model.user import UserModel
20 from kallithea.model.user import UserModel
22 from kallithea.tests.base import TEST_USER_ADMIN_LOGIN, TEST_USER_ADMIN_PASS, TEST_USER_REGULAR_LOGIN, TESTS_TMP_PATH, invalidate_all_caches
21 from kallithea.tests.base import TEST_USER_ADMIN_LOGIN, TEST_USER_ADMIN_PASS, TEST_USER_REGULAR_LOGIN, TESTS_TMP_PATH, invalidate_all_caches
@@ -114,7 +113,7 b' def _set_settings(*kvtseq):'
114 k = kvt[0]
113 k = kvt[0]
115 v = kvt[1]
114 v = kvt[1]
116 t = kvt[2] if len(kvt) == 3 else 'unicode'
115 t = kvt[2] if len(kvt) == 3 else 'unicode'
117 Setting.create_or_update(k, v, t)
116 db.Setting.create_or_update(k, v, t)
118 session.commit()
117 session.commit()
119
118
120
119
@@ -124,18 +123,18 b' def set_test_settings():'
124 # Save settings.
123 # Save settings.
125 settings_snapshot = [
124 settings_snapshot = [
126 (s.app_settings_name, s.app_settings_value, s.app_settings_type)
125 (s.app_settings_name, s.app_settings_value, s.app_settings_type)
127 for s in Setting.query().all()]
126 for s in db.Setting.query().all()]
128 yield _set_settings
127 yield _set_settings
129 # Restore settings.
128 # Restore settings.
130 session = meta.Session()
129 session = meta.Session()
131 keys = frozenset(k for (k, v, t) in settings_snapshot)
130 keys = frozenset(k for (k, v, t) in settings_snapshot)
132 for s in Setting.query().all():
131 for s in db.Setting.query().all():
133 if s.app_settings_name not in keys:
132 if s.app_settings_name not in keys:
134 session.delete(s)
133 session.delete(s)
135 for k, v, t in settings_snapshot:
134 for k, v, t in settings_snapshot:
136 if t == 'list' and hasattr(v, '__iter__'):
135 if t == 'list' and hasattr(v, '__iter__'):
137 v = ','.join(v) # Quirk: must format list value manually.
136 v = ','.join(v) # Quirk: must format list value manually.
138 Setting.create_or_update(k, v, t)
137 db.Setting.create_or_update(k, v, t)
139 session.commit()
138 session.commit()
140
139
141
140
@@ -150,10 +149,10 b' def auto_clear_ip_permissions():'
150
149
151 user_ids = []
150 user_ids = []
152 user_ids.append(kallithea.DEFAULT_USER_ID)
151 user_ids.append(kallithea.DEFAULT_USER_ID)
153 user_ids.append(User.get_by_username(TEST_USER_REGULAR_LOGIN).user_id)
152 user_ids.append(db.User.get_by_username(TEST_USER_REGULAR_LOGIN).user_id)
154
153
155 for user_id in user_ids:
154 for user_id in user_ids:
156 for ip in UserIpMap.query().filter(UserIpMap.user_id == user_id):
155 for ip in db.UserIpMap.query().filter(db.UserIpMap.user_id == user_id):
157 user_model.delete_extra_ip(user_id, ip.ip_id)
156 user_model.delete_extra_ip(user_id, ip.ip_id)
158
157
159 # IP permissions are cached, need to invalidate this cache explicitly
158 # IP permissions are cached, need to invalidate this cache explicitly
@@ -30,10 +30,9 b' from kallithea.lib import helpers'
30 from kallithea.lib.auth import AuthUser
30 from kallithea.lib.auth import AuthUser
31 from kallithea.lib.db_manage import DbManage
31 from kallithea.lib.db_manage import DbManage
32 from kallithea.lib.vcs.backends.base import EmptyChangeset
32 from kallithea.lib.vcs.backends.base import EmptyChangeset
33 from kallithea.model import meta
33 from kallithea.model import db, meta
34 from kallithea.model.changeset_status import ChangesetStatusModel
34 from kallithea.model.changeset_status import ChangesetStatusModel
35 from kallithea.model.comment import ChangesetCommentsModel
35 from kallithea.model.comment import ChangesetCommentsModel
36 from kallithea.model.db import ChangesetStatus, Gist, RepoGroup, Repository, User, UserGroup
37 from kallithea.model.gist import GistModel
36 from kallithea.model.gist import GistModel
38 from kallithea.model.pull_request import CreatePullRequestAction # , CreatePullRequestIterationAction, PullRequestModel
37 from kallithea.model.pull_request import CreatePullRequestAction # , CreatePullRequestIterationAction, PullRequestModel
39 from kallithea.model.repo import RepoModel
38 from kallithea.model.repo import RepoModel
@@ -74,14 +73,14 b' class Fixture(object):'
74
73
75 class context(object):
74 class context(object):
76 def __enter__(self):
75 def __enter__(self):
77 anon = User.get_default_user()
76 anon = db.User.get_default_user()
78 self._before = anon.active
77 self._before = anon.active
79 anon.active = status
78 anon.active = status
80 meta.Session().commit()
79 meta.Session().commit()
81 invalidate_all_caches()
80 invalidate_all_caches()
82
81
83 def __exit__(self, exc_type, exc_val, exc_tb):
82 def __exit__(self, exc_type, exc_val, exc_tb):
84 anon = User.get_default_user()
83 anon = db.User.get_default_user()
85 anon.active = self._before
84 anon.active = self._before
86 meta.Session().commit()
85 meta.Session().commit()
87
86
@@ -98,7 +97,7 b' class Fixture(object):'
98 repo_private=False,
97 repo_private=False,
99 repo_landing_rev='rev:tip',
98 repo_landing_rev='rev:tip',
100 repo_copy_permissions=False,
99 repo_copy_permissions=False,
101 repo_state=Repository.STATE_CREATED,
100 repo_state=db.Repository.STATE_CREATED,
102 )
101 )
103 defs.update(custom)
102 defs.update(custom)
104 if 'repo_name_full' not in custom:
103 if 'repo_name_full' not in custom:
@@ -154,11 +153,11 b' class Fixture(object):'
154 def create_repo(self, name, repo_group=None, **kwargs):
153 def create_repo(self, name, repo_group=None, **kwargs):
155 if 'skip_if_exists' in kwargs:
154 if 'skip_if_exists' in kwargs:
156 del kwargs['skip_if_exists']
155 del kwargs['skip_if_exists']
157 r = Repository.get_by_repo_name(name)
156 r = db.Repository.get_by_repo_name(name)
158 if r:
157 if r:
159 return r
158 return r
160
159
161 if isinstance(repo_group, RepoGroup):
160 if isinstance(repo_group, db.RepoGroup):
162 repo_group = repo_group.group_id
161 repo_group = repo_group.group_id
163
162
164 form_data = self._get_repo_create_params(repo_name=name, **kwargs)
163 form_data = self._get_repo_create_params(repo_name=name, **kwargs)
@@ -167,10 +166,10 b' class Fixture(object):'
167 RepoModel().create(form_data, cur_user)
166 RepoModel().create(form_data, cur_user)
168 meta.Session().commit()
167 meta.Session().commit()
169 ScmModel().mark_for_invalidation(name)
168 ScmModel().mark_for_invalidation(name)
170 return Repository.get_by_repo_name(name)
169 return db.Repository.get_by_repo_name(name)
171
170
172 def create_fork(self, repo_to_fork, fork_name, **kwargs):
171 def create_fork(self, repo_to_fork, fork_name, **kwargs):
173 repo_to_fork = Repository.get_by_repo_name(repo_to_fork)
172 repo_to_fork = db.Repository.get_by_repo_name(repo_to_fork)
174
173
175 form_data = self._get_repo_create_params(repo_name=fork_name,
174 form_data = self._get_repo_create_params(repo_name=fork_name,
176 fork_parent_id=repo_to_fork,
175 fork_parent_id=repo_to_fork,
@@ -185,7 +184,7 b' class Fixture(object):'
185 RepoModel().create_fork(form_data, cur_user=owner)
184 RepoModel().create_fork(form_data, cur_user=owner)
186 meta.Session().commit()
185 meta.Session().commit()
187 ScmModel().mark_for_invalidation(fork_name)
186 ScmModel().mark_for_invalidation(fork_name)
188 r = Repository.get_by_repo_name(fork_name)
187 r = db.Repository.get_by_repo_name(fork_name)
189 assert r
188 assert r
190 return r
189 return r
191
190
@@ -197,7 +196,7 b' class Fixture(object):'
197 assert '/' not in name, (name, kwargs) # use group_parent_id to make nested groups
196 assert '/' not in name, (name, kwargs) # use group_parent_id to make nested groups
198 if 'skip_if_exists' in kwargs:
197 if 'skip_if_exists' in kwargs:
199 del kwargs['skip_if_exists']
198 del kwargs['skip_if_exists']
200 gr = RepoGroup.get_by_group_name(group_name=name)
199 gr = db.RepoGroup.get_by_group_name(group_name=name)
201 if gr:
200 if gr:
202 return gr
201 return gr
203 form_data = self._get_repo_group_create_params(group_name=name, **kwargs)
202 form_data = self._get_repo_group_create_params(group_name=name, **kwargs)
@@ -208,7 +207,7 b' class Fixture(object):'
208 owner=kwargs.get('cur_user', TEST_USER_ADMIN_LOGIN),
207 owner=kwargs.get('cur_user', TEST_USER_ADMIN_LOGIN),
209 )
208 )
210 meta.Session().commit()
209 meta.Session().commit()
211 gr = RepoGroup.get_by_group_name(gr.group_name)
210 gr = db.RepoGroup.get_by_group_name(gr.group_name)
212 return gr
211 return gr
213
212
214 def destroy_repo_group(self, repogroupid):
213 def destroy_repo_group(self, repogroupid):
@@ -218,13 +217,13 b' class Fixture(object):'
218 def create_user(self, name, **kwargs):
217 def create_user(self, name, **kwargs):
219 if 'skip_if_exists' in kwargs:
218 if 'skip_if_exists' in kwargs:
220 del kwargs['skip_if_exists']
219 del kwargs['skip_if_exists']
221 user = User.get_by_username(name)
220 user = db.User.get_by_username(name)
222 if user:
221 if user:
223 return user
222 return user
224 form_data = self._get_user_create_params(name, **kwargs)
223 form_data = self._get_user_create_params(name, **kwargs)
225 user = UserModel().create(form_data)
224 user = UserModel().create(form_data)
226 meta.Session().commit()
225 meta.Session().commit()
227 user = User.get_by_username(user.username)
226 user = db.User.get_by_username(user.username)
228 return user
227 return user
229
228
230 def destroy_user(self, userid):
229 def destroy_user(self, userid):
@@ -234,7 +233,7 b' class Fixture(object):'
234 def create_user_group(self, name, **kwargs):
233 def create_user_group(self, name, **kwargs):
235 if 'skip_if_exists' in kwargs:
234 if 'skip_if_exists' in kwargs:
236 del kwargs['skip_if_exists']
235 del kwargs['skip_if_exists']
237 gr = UserGroup.get_by_group_name(group_name=name)
236 gr = db.UserGroup.get_by_group_name(group_name=name)
238 if gr:
237 if gr:
239 return gr
238 return gr
240 form_data = self._get_user_group_create_params(name, **kwargs)
239 form_data = self._get_user_group_create_params(name, **kwargs)
@@ -245,7 +244,7 b' class Fixture(object):'
245 owner=owner, active=form_data['users_group_active'],
244 owner=owner, active=form_data['users_group_active'],
246 group_data=form_data['user_group_data'])
245 group_data=form_data['user_group_data'])
247 meta.Session().commit()
246 meta.Session().commit()
248 user_group = UserGroup.get_by_group_name(user_group.users_group_name)
247 user_group = db.UserGroup.get_by_group_name(user_group.users_group_name)
249 return user_group
248 return user_group
250
249
251 def destroy_user_group(self, usergroupid):
250 def destroy_user_group(self, usergroupid):
@@ -256,7 +255,7 b' class Fixture(object):'
256 form_data = {
255 form_data = {
257 'description': 'new-gist',
256 'description': 'new-gist',
258 'owner': TEST_USER_ADMIN_LOGIN,
257 'owner': TEST_USER_ADMIN_LOGIN,
259 'gist_type': Gist.GIST_PUBLIC,
258 'gist_type': db.Gist.GIST_PUBLIC,
260 'lifetime': -1,
259 'lifetime': -1,
261 'gist_mapping': {'filename1.txt': {'content': 'hello world'}}
260 'gist_mapping': {'filename1.txt': {'content': 'hello world'}}
262 }
261 }
@@ -271,7 +270,7 b' class Fixture(object):'
271 return gist
270 return gist
272
271
273 def destroy_gists(self, gistid=None):
272 def destroy_gists(self, gistid=None):
274 for g in Gist.query():
273 for g in db.Gist.query():
275 if gistid:
274 if gistid:
276 if gistid == g.gist_access_id:
275 if gistid == g.gist_access_id:
277 GistModel().delete(g)
276 GistModel().delete(g)
@@ -289,7 +288,7 b' class Fixture(object):'
289
288
290 def commit_change(self, repo, filename, content, message, vcs_type,
289 def commit_change(self, repo, filename, content, message, vcs_type,
291 parent=None, newfile=False, author=None):
290 parent=None, newfile=False, author=None):
292 repo = Repository.get_by_repo_name(repo)
291 repo = db.Repository.get_by_repo_name(repo)
293 _cs = parent
292 _cs = parent
294 if parent is None:
293 if parent is None:
295 _cs = EmptyChangeset(alias=vcs_type)
294 _cs = EmptyChangeset(alias=vcs_type)
@@ -326,7 +325,7 b' class Fixture(object):'
326
325
327 def review_changeset(self, repo, revision, status, author=TEST_USER_ADMIN_LOGIN):
326 def review_changeset(self, repo, revision, status, author=TEST_USER_ADMIN_LOGIN):
328 comment = ChangesetCommentsModel().create("review comment", repo, author, revision=revision, send_email=False)
327 comment = ChangesetCommentsModel().create("review comment", repo, author, revision=revision, send_email=False)
329 csm = ChangesetStatusModel().set_status(repo, ChangesetStatus.STATUS_APPROVED, author, comment, revision=revision)
328 csm = ChangesetStatusModel().set_status(repo, db.ChangesetStatus.STATUS_APPROVED, author, comment, revision=revision)
330 meta.Session().commit()
329 meta.Session().commit()
331 return csm
330 return csm
332
331
@@ -334,9 +333,9 b' class Fixture(object):'
334 org_ref = 'branch:stable:%s' % pr_src_rev
333 org_ref = 'branch:stable:%s' % pr_src_rev
335 other_ref = 'branch:default:%s' % pr_dst_rev
334 other_ref = 'branch:default:%s' % pr_dst_rev
336 with test_context(testcontroller.app): # needed to be able to mock request user
335 with test_context(testcontroller.app): # needed to be able to mock request user
337 org_repo = other_repo = Repository.get_by_repo_name(repo_name)
336 org_repo = other_repo = db.Repository.get_by_repo_name(repo_name)
338 owner_user = User.get_by_username(TEST_USER_ADMIN_LOGIN)
337 owner_user = db.User.get_by_username(TEST_USER_ADMIN_LOGIN)
339 reviewers = [User.get_by_username(TEST_USER_REGULAR_LOGIN)]
338 reviewers = [db.User.get_by_username(TEST_USER_REGULAR_LOGIN)]
340 request.authuser = AuthUser(dbuser=owner_user)
339 request.authuser = AuthUser(dbuser=owner_user)
341 # creating a PR sends a message with an absolute URL - without routing that requires mocking
340 # creating a PR sends a message with an absolute URL - without routing that requires mocking
342 with mock.patch.object(helpers, 'url', (lambda arg, qualified=False, **kwargs: ('https://localhost' if qualified else '') + '/fake/' + arg)):
341 with mock.patch.object(helpers, 'url', (lambda arg, qualified=False, **kwargs: ('https://localhost' if qualified else '') + '/fake/' + arg)):
@@ -3,8 +3,7 b' import datetime'
3 import os
3 import os
4 from os.path import dirname
4 from os.path import dirname
5
5
6 from kallithea.model import meta
6 from kallithea.model import db, meta
7 from kallithea.model.db import UserLog
8 from kallithea.tests import base
7 from kallithea.tests import base
9
8
10
9
@@ -15,7 +14,7 b' class TestAdminController(base.TestContr'
15
14
16 @classmethod
15 @classmethod
17 def setup_class(cls):
16 def setup_class(cls):
18 UserLog.query().delete()
17 db.UserLog.query().delete()
19 meta.Session().commit()
18 meta.Session().commit()
20
19
21 def strptime(val):
20 def strptime(val):
@@ -32,7 +31,7 b' class TestAdminController(base.TestContr'
32
31
33 with open(os.path.join(FIXTURES, 'journal_dump.csv')) as f:
32 with open(os.path.join(FIXTURES, 'journal_dump.csv')) as f:
34 for row in csv.DictReader(f):
33 for row in csv.DictReader(f):
35 ul = UserLog()
34 ul = db.UserLog()
36 for k, v in row.items():
35 for k, v in row.items():
37 if k == 'action_date':
36 if k == 'action_date':
38 v = strptime(v)
37 v = strptime(v)
@@ -45,7 +44,7 b' class TestAdminController(base.TestContr'
45
44
46 @classmethod
45 @classmethod
47 def teardown_class(cls):
46 def teardown_class(cls):
48 UserLog.query().delete()
47 db.UserLog.query().delete()
49 meta.Session().commit()
48 meta.Session().commit()
50
49
51 def test_index(self):
50 def test_index(self):
@@ -1,4 +1,4 b''
1 from kallithea.model.db import Setting
1 from kallithea.model import db
2 from kallithea.tests import base
2 from kallithea.tests import base
3
3
4
4
@@ -47,7 +47,7 b' class TestAuthSettingsController(base.Te'
47 response = self.app.post(url=test_url, params=params)
47 response = self.app.post(url=test_url, params=params)
48 self.checkSessionFlash(response, 'Auth settings updated successfully')
48 self.checkSessionFlash(response, 'Auth settings updated successfully')
49
49
50 new_settings = Setting.get_auth_settings()
50 new_settings = db.Setting.get_auth_settings()
51 assert new_settings['auth_ldap_host'] == 'dc.example.com', 'fail db write compare'
51 assert new_settings['auth_ldap_host'] == 'dc.example.com', 'fail db write compare'
52
52
53 @base.skipif(not base.ldap_lib_installed, reason='skipping due to missing ldap lib')
53 @base.skipif(not base.ldap_lib_installed, reason='skipping due to missing ldap lib')
@@ -238,7 +238,7 b' class TestAuthSettingsController(base.Te'
238 response = self.app.post(url=test_url, params=params)
238 response = self.app.post(url=test_url, params=params)
239 self.checkSessionFlash(response, 'Auth settings updated successfully')
239 self.checkSessionFlash(response, 'Auth settings updated successfully')
240
240
241 new_settings = Setting.get_auth_settings()
241 new_settings = db.Setting.get_auth_settings()
242 assert new_settings['auth_crowd_host'] == 'hostname', 'fail db write compare'
242 assert new_settings['auth_crowd_host'] == 'hostname', 'fail db write compare'
243
243
244 @base.skipif(not base.pam_lib_installed, reason='skipping due to missing pam lib')
244 @base.skipif(not base.pam_lib_installed, reason='skipping due to missing pam lib')
@@ -255,5 +255,5 b' class TestAuthSettingsController(base.Te'
255 response = self.app.post(url=test_url, params=params)
255 response = self.app.post(url=test_url, params=params)
256 self.checkSessionFlash(response, 'Auth settings updated successfully')
256 self.checkSessionFlash(response, 'Auth settings updated successfully')
257
257
258 new_settings = Setting.get_auth_settings()
258 new_settings = db.Setting.get_auth_settings()
259 assert new_settings['auth_pam_service'] == 'kallithea', 'fail db write compare'
259 assert new_settings['auth_pam_service'] == 'kallithea', 'fail db write compare'
@@ -1,4 +1,4 b''
1 from kallithea.model.db import Setting
1 from kallithea.model import db
2 from kallithea.tests import base
2 from kallithea.tests import base
3
3
4
4
@@ -24,7 +24,7 b' class TestDefaultsController(base.TestCo'
24 self.checkSessionFlash(response, 'Default settings updated successfully')
24 self.checkSessionFlash(response, 'Default settings updated successfully')
25
25
26 params.pop('_session_csrf_secret_token')
26 params.pop('_session_csrf_secret_token')
27 defs = Setting.get_default_repo_settings()
27 defs = db.Setting.get_default_repo_settings()
28 assert params == defs
28 assert params == defs
29
29
30 def test_update_params_false_git(self):
30 def test_update_params_false_git(self):
@@ -40,5 +40,5 b' class TestDefaultsController(base.TestCo'
40 self.checkSessionFlash(response, 'Default settings updated successfully')
40 self.checkSessionFlash(response, 'Default settings updated successfully')
41
41
42 params.pop('_session_csrf_secret_token')
42 params.pop('_session_csrf_secret_token')
43 defs = Setting.get_default_repo_settings()
43 defs = db.Setting.get_default_repo_settings()
44 assert params == defs
44 assert params == defs
@@ -1,5 +1,4 b''
1 from kallithea.model import meta
1 from kallithea.model import db, meta
2 from kallithea.model.db import Gist, User
3 from kallithea.model.gist import GistModel
2 from kallithea.model.gist import GistModel
4 from kallithea.tests import base
3 from kallithea.tests import base
5
4
@@ -10,7 +9,7 b" def _create_gist(f_name, content='some g"
10 gist_mapping = {
9 gist_mapping = {
11 f_name: {'content': content}
10 f_name: {'content': content}
12 }
11 }
13 owner = User.get_by_username(owner)
12 owner = db.User.get_by_username(owner)
14 gist = GistModel().create(description, owner=owner, ip_addr=base.IP_ADDR,
13 gist = GistModel().create(description, owner=owner, ip_addr=base.IP_ADDR,
15 gist_mapping=gist_mapping, gist_type=gist_type,
14 gist_mapping=gist_mapping, gist_type=gist_type,
16 lifetime=lifetime)
15 lifetime=lifetime)
@@ -21,7 +20,7 b" def _create_gist(f_name, content='some g"
21 class TestGistsController(base.TestController):
20 class TestGistsController(base.TestController):
22
21
23 def teardown_method(self, method):
22 def teardown_method(self, method):
24 for g in Gist.query():
23 for g in db.Gist.query():
25 GistModel().delete(g)
24 GistModel().delete(g)
26 meta.Session().commit()
25 meta.Session().commit()
27
26
@@ -1,5 +1,5 b''
1 import kallithea
1 import kallithea
2 from kallithea.model.db import User, UserIpMap
2 from kallithea.model import db
3 from kallithea.tests import base
3 from kallithea.tests import base
4
4
5
5
@@ -46,7 +46,7 b' class TestAdminPermissionsController(bas'
46
46
47 # Delete latest IP and verify same IP is rejected again
47 # Delete latest IP and verify same IP is rejected again
48
48
49 x = UserIpMap.query().filter_by(ip_addr='0.0.1.0/24').first()
49 x = db.UserIpMap.query().filter_by(ip_addr='0.0.1.0/24').first()
50 response = self.app.post(base.url('edit_user_ips_delete', id=default_user_id),
50 response = self.app.post(base.url('edit_user_ips_delete', id=default_user_id),
51 params=dict(del_ip_id=x.ip_id,
51 params=dict(del_ip_id=x.ip_id,
52 _session_csrf_secret_token=self.session_csrf_secret_token()))
52 _session_csrf_secret_token=self.session_csrf_secret_token()))
@@ -57,7 +57,7 b' class TestAdminPermissionsController(bas'
57
57
58 # Delete first IP and verify unlimited access again
58 # Delete first IP and verify unlimited access again
59
59
60 x = UserIpMap.query().filter_by(ip_addr='0.0.0.0/24').first()
60 x = db.UserIpMap.query().filter_by(ip_addr='0.0.0.0/24').first()
61 response = self.app.post(base.url('edit_user_ips_delete', id=default_user_id),
61 response = self.app.post(base.url('edit_user_ips_delete', id=default_user_id),
62 params=dict(del_ip_id=x.ip_id,
62 params=dict(del_ip_id=x.ip_id,
63 _session_csrf_secret_token=self.session_csrf_secret_token()))
63 _session_csrf_secret_token=self.session_csrf_secret_token()))
@@ -72,7 +72,7 b' class TestAdminPermissionsController(bas'
72 # Test response...
72 # Test response...
73
73
74 def test_edit_permissions_permissions(self):
74 def test_edit_permissions_permissions(self):
75 user = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
75 user = db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
76
76
77 # Test unauthenticated access - it will redirect to login page
77 # Test unauthenticated access - it will redirect to login page
78 response = self.app.post(
78 response = self.app.post(
@@ -8,8 +8,7 b' import pytest'
8
8
9 import kallithea
9 import kallithea
10 from kallithea.lib import vcs
10 from kallithea.lib import vcs
11 from kallithea.model import meta
11 from kallithea.model import db, meta
12 from kallithea.model.db import Permission, Repository, Ui, User, UserRepoToPerm
13 from kallithea.model.repo import RepoModel
12 from kallithea.model.repo import RepoModel
14 from kallithea.model.repo_group import RepoGroupModel
13 from kallithea.model.repo_group import RepoGroupModel
15 from kallithea.model.user import UserModel
14 from kallithea.model.user import UserModel
@@ -21,10 +20,10 b' fixture = Fixture()'
21
20
22
21
23 def _get_permission_for_user(user, repo):
22 def _get_permission_for_user(user, repo):
24 perm = UserRepoToPerm.query() \
23 perm = db.UserRepoToPerm.query() \
25 .filter(UserRepoToPerm.repository ==
24 .filter(db.UserRepoToPerm.repository ==
26 Repository.get_by_repo_name(repo)) \
25 db.Repository.get_by_repo_name(repo)) \
27 .filter(UserRepoToPerm.user == User.get_by_username(user)) \
26 .filter(db.UserRepoToPerm.user == db.User.get_by_username(user)) \
28 .all()
27 .all()
29 return perm
28 return perm
30
29
@@ -61,8 +60,8 b' class _BaseTestCase(base.TestController)'
61 % (repo_name, repo_name))
60 % (repo_name, repo_name))
62
61
63 # test if the repo was created in the database
62 # test if the repo was created in the database
64 new_repo = meta.Session().query(Repository) \
63 new_repo = meta.Session().query(db.Repository) \
65 .filter(Repository.repo_name == repo_name).one()
64 .filter(db.Repository.repo_name == repo_name).one()
66
65
67 assert new_repo.repo_name == repo_name
66 assert new_repo.repo_name == repo_name
68 assert new_repo.description == description
67 assert new_repo.description == description
@@ -74,7 +73,7 b' class _BaseTestCase(base.TestController)'
74
73
75 # test if the repository was created on filesystem
74 # test if the repository was created on filesystem
76 try:
75 try:
77 vcs.get_repo(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name))
76 vcs.get_repo(os.path.join(db.Ui.get_by_key('paths', '/').ui_value, repo_name))
78 except vcs.exceptions.VCSError:
77 except vcs.exceptions.VCSError:
79 pytest.fail('no repo %s in filesystem' % repo_name)
78 pytest.fail('no repo %s in filesystem' % repo_name)
80
79
@@ -131,8 +130,8 b' class _BaseTestCase(base.TestController)'
131 'Created repository <a href="/%s">%s</a>'
130 'Created repository <a href="/%s">%s</a>'
132 % (repo_name_full, repo_name_full))
131 % (repo_name_full, repo_name_full))
133 # test if the repo was created in the database
132 # test if the repo was created in the database
134 new_repo = meta.Session().query(Repository) \
133 new_repo = meta.Session().query(db.Repository) \
135 .filter(Repository.repo_name == repo_name_full).one()
134 .filter(db.Repository.repo_name == repo_name_full).one()
136 new_repo_id = new_repo.repo_id
135 new_repo_id = new_repo.repo_id
137
136
138 assert new_repo.repo_name == repo_name_full
137 assert new_repo.repo_name == repo_name_full
@@ -143,13 +142,13 b' class _BaseTestCase(base.TestController)'
143 response.mustcontain(repo_name_full)
142 response.mustcontain(repo_name_full)
144 response.mustcontain(self.REPO_TYPE)
143 response.mustcontain(self.REPO_TYPE)
145
144
146 inherited_perms = UserRepoToPerm.query() \
145 inherited_perms = db.UserRepoToPerm.query() \
147 .filter(UserRepoToPerm.repository_id == new_repo_id).all()
146 .filter(db.UserRepoToPerm.repository_id == new_repo_id).all()
148 assert len(inherited_perms) == 1
147 assert len(inherited_perms) == 1
149
148
150 # test if the repository was created on filesystem
149 # test if the repository was created on filesystem
151 try:
150 try:
152 vcs.get_repo(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name_full))
151 vcs.get_repo(os.path.join(db.Ui.get_by_key('paths', '/').ui_value, repo_name_full))
153 except vcs.exceptions.VCSError:
152 except vcs.exceptions.VCSError:
154 RepoGroupModel().delete(group_name)
153 RepoGroupModel().delete(group_name)
155 meta.Session().commit()
154 meta.Session().commit()
@@ -166,10 +165,10 b' class _BaseTestCase(base.TestController)'
166 # revoke
165 # revoke
167 user_model = UserModel()
166 user_model = UserModel()
168 # disable fork and create on default user
167 # disable fork and create on default user
169 user_model.revoke_perm(User.DEFAULT_USER_NAME, 'hg.create.repository')
168 user_model.revoke_perm(db.User.DEFAULT_USER_NAME, 'hg.create.repository')
170 user_model.grant_perm(User.DEFAULT_USER_NAME, 'hg.create.none')
169 user_model.grant_perm(db.User.DEFAULT_USER_NAME, 'hg.create.none')
171 user_model.revoke_perm(User.DEFAULT_USER_NAME, 'hg.fork.repository')
170 user_model.revoke_perm(db.User.DEFAULT_USER_NAME, 'hg.fork.repository')
172 user_model.grant_perm(User.DEFAULT_USER_NAME, 'hg.fork.none')
171 user_model.grant_perm(db.User.DEFAULT_USER_NAME, 'hg.fork.none')
173
172
174 # disable on regular user
173 # disable on regular user
175 user_model.revoke_perm(base.TEST_USER_REGULAR_LOGIN, 'hg.create.repository')
174 user_model.revoke_perm(base.TEST_USER_REGULAR_LOGIN, 'hg.create.repository')
@@ -223,8 +222,8 b' class _BaseTestCase(base.TestController)'
223 'Created repository <a href="/%s">%s</a>'
222 'Created repository <a href="/%s">%s</a>'
224 % (repo_name_full, repo_name_full))
223 % (repo_name_full, repo_name_full))
225 # test if the repo was created in the database
224 # test if the repo was created in the database
226 new_repo = meta.Session().query(Repository) \
225 new_repo = meta.Session().query(db.Repository) \
227 .filter(Repository.repo_name == repo_name_full).one()
226 .filter(db.Repository.repo_name == repo_name_full).one()
228 new_repo_id = new_repo.repo_id
227 new_repo_id = new_repo.repo_id
229
228
230 assert new_repo.repo_name == repo_name_full
229 assert new_repo.repo_name == repo_name_full
@@ -235,13 +234,13 b' class _BaseTestCase(base.TestController)'
235 response.mustcontain(repo_name_full)
234 response.mustcontain(repo_name_full)
236 response.mustcontain(self.REPO_TYPE)
235 response.mustcontain(self.REPO_TYPE)
237
236
238 inherited_perms = UserRepoToPerm.query() \
237 inherited_perms = db.UserRepoToPerm.query() \
239 .filter(UserRepoToPerm.repository_id == new_repo_id).all()
238 .filter(db.UserRepoToPerm.repository_id == new_repo_id).all()
240 assert len(inherited_perms) == 1
239 assert len(inherited_perms) == 1
241
240
242 # test if the repository was created on filesystem
241 # test if the repository was created on filesystem
243 try:
242 try:
244 vcs.get_repo(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name_full))
243 vcs.get_repo(os.path.join(db.Ui.get_by_key('paths', '/').ui_value, repo_name_full))
245 except vcs.exceptions.VCSError:
244 except vcs.exceptions.VCSError:
246 RepoGroupModel().delete(group_name)
245 RepoGroupModel().delete(group_name)
247 meta.Session().commit()
246 meta.Session().commit()
@@ -260,7 +259,7 b' class _BaseTestCase(base.TestController)'
260 gr = RepoGroupModel().create(group_name=group_name,
259 gr = RepoGroupModel().create(group_name=group_name,
261 group_description='test',
260 group_description='test',
262 owner=base.TEST_USER_ADMIN_LOGIN)
261 owner=base.TEST_USER_ADMIN_LOGIN)
263 perm = Permission.get_by_key('repository.write')
262 perm = db.Permission.get_by_key('repository.write')
264 RepoGroupModel().grant_user_permission(gr, base.TEST_USER_REGULAR_LOGIN, perm)
263 RepoGroupModel().grant_user_permission(gr, base.TEST_USER_REGULAR_LOGIN, perm)
265
264
266 ## add repo permissions
265 ## add repo permissions
@@ -284,8 +283,8 b' class _BaseTestCase(base.TestController)'
284 'Created repository <a href="/%s">%s</a>'
283 'Created repository <a href="/%s">%s</a>'
285 % (repo_name_full, repo_name_full))
284 % (repo_name_full, repo_name_full))
286 # test if the repo was created in the database
285 # test if the repo was created in the database
287 new_repo = meta.Session().query(Repository) \
286 new_repo = meta.Session().query(db.Repository) \
288 .filter(Repository.repo_name == repo_name_full).one()
287 .filter(db.Repository.repo_name == repo_name_full).one()
289 new_repo_id = new_repo.repo_id
288 new_repo_id = new_repo.repo_id
290
289
291 assert new_repo.repo_name == repo_name_full
290 assert new_repo.repo_name == repo_name_full
@@ -298,15 +297,15 b' class _BaseTestCase(base.TestController)'
298
297
299 # test if the repository was created on filesystem
298 # test if the repository was created on filesystem
300 try:
299 try:
301 vcs.get_repo(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name_full))
300 vcs.get_repo(os.path.join(db.Ui.get_by_key('paths', '/').ui_value, repo_name_full))
302 except vcs.exceptions.VCSError:
301 except vcs.exceptions.VCSError:
303 RepoGroupModel().delete(group_name)
302 RepoGroupModel().delete(group_name)
304 meta.Session().commit()
303 meta.Session().commit()
305 pytest.fail('no repo %s in filesystem' % repo_name)
304 pytest.fail('no repo %s in filesystem' % repo_name)
306
305
307 # check if inherited permissiona are applied
306 # check if inherited permissiona are applied
308 inherited_perms = UserRepoToPerm.query() \
307 inherited_perms = db.UserRepoToPerm.query() \
309 .filter(UserRepoToPerm.repository_id == new_repo_id).all()
308 .filter(db.UserRepoToPerm.repository_id == new_repo_id).all()
310 assert len(inherited_perms) == 2
309 assert len(inherited_perms) == 2
311
310
312 assert base.TEST_USER_REGULAR_LOGIN in [x.user.username
311 assert base.TEST_USER_REGULAR_LOGIN in [x.user.username
@@ -373,8 +372,8 b' class _BaseTestCase(base.TestController)'
373 'Created repository <a href="/%s">%s</a>'
372 'Created repository <a href="/%s">%s</a>'
374 % (repo_name, repo_name))
373 % (repo_name, repo_name))
375 # test if the repo was created in the database
374 # test if the repo was created in the database
376 new_repo = meta.Session().query(Repository) \
375 new_repo = meta.Session().query(db.Repository) \
377 .filter(Repository.repo_name == repo_name).one()
376 .filter(db.Repository.repo_name == repo_name).one()
378
377
379 assert new_repo.repo_name == repo_name
378 assert new_repo.repo_name == repo_name
380 assert new_repo.description == description
379 assert new_repo.description == description
@@ -386,7 +385,7 b' class _BaseTestCase(base.TestController)'
386
385
387 # test if the repository was created on filesystem
386 # test if the repository was created on filesystem
388 try:
387 try:
389 vcs.get_repo(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name))
388 vcs.get_repo(os.path.join(db.Ui.get_by_key('paths', '/').ui_value, repo_name))
390 except vcs.exceptions.VCSError:
389 except vcs.exceptions.VCSError:
391 pytest.fail('no repo %s in filesystem' % repo_name)
390 pytest.fail('no repo %s in filesystem' % repo_name)
392
391
@@ -398,12 +397,12 b' class _BaseTestCase(base.TestController)'
398 response.follow()
397 response.follow()
399
398
400 # check if repo was deleted from db
399 # check if repo was deleted from db
401 deleted_repo = meta.Session().query(Repository) \
400 deleted_repo = meta.Session().query(db.Repository) \
402 .filter(Repository.repo_name == repo_name).scalar()
401 .filter(db.Repository.repo_name == repo_name).scalar()
403
402
404 assert deleted_repo is None
403 assert deleted_repo is None
405
404
406 assert os.path.isdir(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name)) == False
405 assert os.path.isdir(os.path.join(db.Ui.get_by_key('paths', '/').ui_value, repo_name)) == False
407
406
408 def test_delete_non_ascii(self):
407 def test_delete_non_ascii(self):
409 self.log_user()
408 self.log_user()
@@ -423,8 +422,8 b' class _BaseTestCase(base.TestController)'
423 'Created repository <a href="/%s">%s</a>'
422 'Created repository <a href="/%s">%s</a>'
424 % (urllib.parse.quote(repo_name), repo_name))
423 % (urllib.parse.quote(repo_name), repo_name))
425 # test if the repo was created in the database
424 # test if the repo was created in the database
426 new_repo = meta.Session().query(Repository) \
425 new_repo = meta.Session().query(db.Repository) \
427 .filter(Repository.repo_name == repo_name).one()
426 .filter(db.Repository.repo_name == repo_name).one()
428
427
429 assert new_repo.repo_name == repo_name
428 assert new_repo.repo_name == repo_name
430 assert new_repo.description == description
429 assert new_repo.description == description
@@ -436,7 +435,7 b' class _BaseTestCase(base.TestController)'
436
435
437 # test if the repository was created on filesystem
436 # test if the repository was created on filesystem
438 try:
437 try:
439 vcs.get_repo(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name))
438 vcs.get_repo(os.path.join(db.Ui.get_by_key('paths', '/').ui_value, repo_name))
440 except vcs.exceptions.VCSError:
439 except vcs.exceptions.VCSError:
441 pytest.fail('no repo %s in filesystem' % repo_name)
440 pytest.fail('no repo %s in filesystem' % repo_name)
442
441
@@ -446,12 +445,12 b' class _BaseTestCase(base.TestController)'
446 response.follow()
445 response.follow()
447
446
448 # check if repo was deleted from db
447 # check if repo was deleted from db
449 deleted_repo = meta.Session().query(Repository) \
448 deleted_repo = meta.Session().query(db.Repository) \
450 .filter(Repository.repo_name == repo_name).scalar()
449 .filter(db.Repository.repo_name == repo_name).scalar()
451
450
452 assert deleted_repo is None
451 assert deleted_repo is None
453
452
454 assert os.path.isdir(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name)) == False
453 assert os.path.isdir(os.path.join(db.Ui.get_by_key('paths', '/').ui_value, repo_name)) == False
455
454
456 def test_delete_repo_with_group(self):
455 def test_delete_repo_with_group(self):
457 # TODO:
456 # TODO:
@@ -474,7 +473,7 b' class _BaseTestCase(base.TestController)'
474 perm = _get_permission_for_user(user='default', repo=self.REPO)
473 perm = _get_permission_for_user(user='default', repo=self.REPO)
475 assert len(perm), 1
474 assert len(perm), 1
476 assert perm[0].permission.permission_name == 'repository.read'
475 assert perm[0].permission.permission_name == 'repository.read'
477 assert Repository.get_by_repo_name(self.REPO).private == False
476 assert db.Repository.get_by_repo_name(self.REPO).private == False
478
477
479 response = self.app.post(base.url('update_repo', repo_name=self.REPO),
478 response = self.app.post(base.url('update_repo', repo_name=self.REPO),
480 fixture._get_repo_create_params(repo_private=1,
479 fixture._get_repo_create_params(repo_private=1,
@@ -484,7 +483,7 b' class _BaseTestCase(base.TestController)'
484 _session_csrf_secret_token=self.session_csrf_secret_token()))
483 _session_csrf_secret_token=self.session_csrf_secret_token()))
485 self.checkSessionFlash(response,
484 self.checkSessionFlash(response,
486 msg='Repository %s updated successfully' % (self.REPO))
485 msg='Repository %s updated successfully' % (self.REPO))
487 assert Repository.get_by_repo_name(self.REPO).private == True
486 assert db.Repository.get_by_repo_name(self.REPO).private == True
488
487
489 # now the repo default permission should be None
488 # now the repo default permission should be None
490 perm = _get_permission_for_user(user='default', repo=self.REPO)
489 perm = _get_permission_for_user(user='default', repo=self.REPO)
@@ -499,7 +498,7 b' class _BaseTestCase(base.TestController)'
499 _session_csrf_secret_token=self.session_csrf_secret_token()))
498 _session_csrf_secret_token=self.session_csrf_secret_token()))
500 self.checkSessionFlash(response,
499 self.checkSessionFlash(response,
501 msg='Repository %s updated successfully' % (self.REPO))
500 msg='Repository %s updated successfully' % (self.REPO))
502 assert Repository.get_by_repo_name(self.REPO).private == False
501 assert db.Repository.get_by_repo_name(self.REPO).private == False
503
502
504 # we turn off private now the repo default permission should stay None
503 # we turn off private now the repo default permission should stay None
505 perm = _get_permission_for_user(user='default', repo=self.REPO)
504 perm = _get_permission_for_user(user='default', repo=self.REPO)
@@ -507,12 +506,12 b' class _BaseTestCase(base.TestController)'
507 assert perm[0].permission.permission_name == 'repository.none'
506 assert perm[0].permission.permission_name == 'repository.none'
508
507
509 # update this permission back
508 # update this permission back
510 perm[0].permission = Permission.get_by_key('repository.read')
509 perm[0].permission = db.Permission.get_by_key('repository.read')
511 meta.Session().commit()
510 meta.Session().commit()
512
511
513 def test_set_repo_fork_has_no_self_id(self):
512 def test_set_repo_fork_has_no_self_id(self):
514 self.log_user()
513 self.log_user()
515 repo = Repository.get_by_repo_name(self.REPO)
514 repo = db.Repository.get_by_repo_name(self.REPO)
516 response = self.app.get(base.url('edit_repo_advanced', repo_name=self.REPO))
515 response = self.app.get(base.url('edit_repo_advanced', repo_name=self.REPO))
517 opt = """<option value="%s">%s</option>""" % (repo.repo_id, self.REPO)
516 opt = """<option value="%s">%s</option>""" % (repo.repo_id, self.REPO)
518 response.mustcontain(no=[opt])
517 response.mustcontain(no=[opt])
@@ -521,12 +520,12 b' class _BaseTestCase(base.TestController)'
521 self.log_user()
520 self.log_user()
522 other_repo = 'other_%s' % self.REPO_TYPE
521 other_repo = 'other_%s' % self.REPO_TYPE
523 fixture.create_repo(other_repo, repo_type=self.REPO_TYPE)
522 fixture.create_repo(other_repo, repo_type=self.REPO_TYPE)
524 repo = Repository.get_by_repo_name(self.REPO)
523 repo = db.Repository.get_by_repo_name(self.REPO)
525 repo2 = Repository.get_by_repo_name(other_repo)
524 repo2 = db.Repository.get_by_repo_name(other_repo)
526 response = self.app.post(base.url('edit_repo_advanced_fork', repo_name=self.REPO),
525 response = self.app.post(base.url('edit_repo_advanced_fork', repo_name=self.REPO),
527 params=dict(id_fork_of=repo2.repo_id, _session_csrf_secret_token=self.session_csrf_secret_token()))
526 params=dict(id_fork_of=repo2.repo_id, _session_csrf_secret_token=self.session_csrf_secret_token()))
528 repo = Repository.get_by_repo_name(self.REPO)
527 repo = db.Repository.get_by_repo_name(self.REPO)
529 repo2 = Repository.get_by_repo_name(other_repo)
528 repo2 = db.Repository.get_by_repo_name(other_repo)
530 self.checkSessionFlash(response,
529 self.checkSessionFlash(response,
531 'Marked repository %s as fork of %s' % (repo.repo_name, repo2.repo_name))
530 'Marked repository %s as fork of %s' % (repo.repo_name, repo2.repo_name))
532
531
@@ -542,12 +541,12 b' class _BaseTestCase(base.TestController)'
542
541
543 def test_set_fork_of_other_type_repo(self):
542 def test_set_fork_of_other_type_repo(self):
544 self.log_user()
543 self.log_user()
545 repo = Repository.get_by_repo_name(self.REPO)
544 repo = db.Repository.get_by_repo_name(self.REPO)
546 repo2 = Repository.get_by_repo_name(self.OTHER_TYPE_REPO)
545 repo2 = db.Repository.get_by_repo_name(self.OTHER_TYPE_REPO)
547 response = self.app.post(base.url('edit_repo_advanced_fork', repo_name=self.REPO),
546 response = self.app.post(base.url('edit_repo_advanced_fork', repo_name=self.REPO),
548 params=dict(id_fork_of=repo2.repo_id, _session_csrf_secret_token=self.session_csrf_secret_token()))
547 params=dict(id_fork_of=repo2.repo_id, _session_csrf_secret_token=self.session_csrf_secret_token()))
549 repo = Repository.get_by_repo_name(self.REPO)
548 repo = db.Repository.get_by_repo_name(self.REPO)
550 repo2 = Repository.get_by_repo_name(self.OTHER_TYPE_REPO)
549 repo2 = db.Repository.get_by_repo_name(self.OTHER_TYPE_REPO)
551 self.checkSessionFlash(response,
550 self.checkSessionFlash(response,
552 'Cannot set repository as fork of repository with other type')
551 'Cannot set repository as fork of repository with other type')
553
552
@@ -556,8 +555,8 b' class _BaseTestCase(base.TestController)'
556 ## mark it as None
555 ## mark it as None
557 response = self.app.post(base.url('edit_repo_advanced_fork', repo_name=self.REPO),
556 response = self.app.post(base.url('edit_repo_advanced_fork', repo_name=self.REPO),
558 params=dict(id_fork_of=None, _session_csrf_secret_token=self.session_csrf_secret_token()))
557 params=dict(id_fork_of=None, _session_csrf_secret_token=self.session_csrf_secret_token()))
559 repo = Repository.get_by_repo_name(self.REPO)
558 repo = db.Repository.get_by_repo_name(self.REPO)
560 repo2 = Repository.get_by_repo_name(self.OTHER_TYPE_REPO)
559 repo2 = db.Repository.get_by_repo_name(self.OTHER_TYPE_REPO)
561 self.checkSessionFlash(response,
560 self.checkSessionFlash(response,
562 'Marked repository %s as fork of %s'
561 'Marked repository %s as fork of %s'
563 % (repo.repo_name, "Nothing"))
562 % (repo.repo_name, "Nothing"))
@@ -565,7 +564,7 b' class _BaseTestCase(base.TestController)'
565
564
566 def test_set_fork_of_same_repo(self):
565 def test_set_fork_of_same_repo(self):
567 self.log_user()
566 self.log_user()
568 repo = Repository.get_by_repo_name(self.REPO)
567 repo = db.Repository.get_by_repo_name(self.REPO)
569 response = self.app.post(base.url('edit_repo_advanced_fork', repo_name=self.REPO),
568 response = self.app.post(base.url('edit_repo_advanced_fork', repo_name=self.REPO),
570 params=dict(id_fork_of=repo.repo_id, _session_csrf_secret_token=self.session_csrf_secret_token()))
569 params=dict(id_fork_of=repo.repo_id, _session_csrf_secret_token=self.session_csrf_secret_token()))
571 self.checkSessionFlash(response,
570 self.checkSessionFlash(response,
@@ -576,10 +575,10 b' class _BaseTestCase(base.TestController)'
576 # revoke
575 # revoke
577 user_model = UserModel()
576 user_model = UserModel()
578 # disable fork and create on default user
577 # disable fork and create on default user
579 user_model.revoke_perm(User.DEFAULT_USER_NAME, 'hg.create.repository')
578 user_model.revoke_perm(db.User.DEFAULT_USER_NAME, 'hg.create.repository')
580 user_model.grant_perm(User.DEFAULT_USER_NAME, 'hg.create.none')
579 user_model.grant_perm(db.User.DEFAULT_USER_NAME, 'hg.create.none')
581 user_model.revoke_perm(User.DEFAULT_USER_NAME, 'hg.fork.repository')
580 user_model.revoke_perm(db.User.DEFAULT_USER_NAME, 'hg.fork.repository')
582 user_model.grant_perm(User.DEFAULT_USER_NAME, 'hg.fork.none')
581 user_model.grant_perm(db.User.DEFAULT_USER_NAME, 'hg.fork.none')
583
582
584 # disable on regular user
583 # disable on regular user
585 user_model.revoke_perm(base.TEST_USER_REGULAR_LOGIN, 'hg.create.repository')
584 user_model.revoke_perm(base.TEST_USER_REGULAR_LOGIN, 'hg.create.repository')
@@ -589,7 +588,7 b' class _BaseTestCase(base.TestController)'
589 meta.Session().commit()
588 meta.Session().commit()
590
589
591
590
592 user = User.get(usr['user_id'])
591 user = db.User.get(usr['user_id'])
593
592
594 repo_name = self.NEW_REPO + 'no_perms'
593 repo_name = self.NEW_REPO + 'no_perms'
595 description = 'description for newly created repo'
594 description = 'description for newly created repo'
@@ -621,11 +620,11 b' class _BaseTestCase(base.TestController)'
621 self.checkSessionFlash(response,
620 self.checkSessionFlash(response,
622 'Error creating repository %s' % repo_name)
621 'Error creating repository %s' % repo_name)
623 # repo must not be in db
622 # repo must not be in db
624 repo = Repository.get_by_repo_name(repo_name)
623 repo = db.Repository.get_by_repo_name(repo_name)
625 assert repo is None
624 assert repo is None
626
625
627 # repo must not be in filesystem !
626 # repo must not be in filesystem !
628 assert not os.path.isdir(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name))
627 assert not os.path.isdir(os.path.join(db.Ui.get_by_key('paths', '/').ui_value, repo_name))
629
628
630
629
631 class TestAdminReposControllerGIT(_BaseTestCase):
630 class TestAdminReposControllerGIT(_BaseTestCase):
@@ -644,7 +643,7 b' class TestAdminReposControllerHG(_BaseTe'
644 OTHER_TYPE = 'git'
643 OTHER_TYPE = 'git'
645
644
646 def test_permanent_url_protocol_access(self):
645 def test_permanent_url_protocol_access(self):
647 repo = Repository.get_by_repo_name(self.REPO)
646 repo = db.Repository.get_by_repo_name(self.REPO)
648 permanent_name = '_%d' % repo.repo_id
647 permanent_name = '_%d' % repo.repo_id
649
648
650 # 400 Bad Request - Unable to detect pull/push action
649 # 400 Bad Request - Unable to detect pull/push action
@@ -1,6 +1,6 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 from kallithea.model.db import Setting, Ui
3 from kallithea.model import db
4 from kallithea.tests import base
4 from kallithea.tests import base
5 from kallithea.tests.fixture import Fixture
5 from kallithea.tests.fixture import Fixture
6
6
@@ -80,7 +80,7 b' class TestAdminSettingsController(base.T'
80 response.mustcontain('test_hooks_2')
80 response.mustcontain('test_hooks_2')
81 response.mustcontain('cd %s2' % base.TESTS_TMP_PATH)
81 response.mustcontain('cd %s2' % base.TESTS_TMP_PATH)
82
82
83 hook_id = Ui.get_by_key('hooks', 'test_hooks_2').ui_id
83 hook_id = db.Ui.get_by_key('hooks', 'test_hooks_2').ui_id
84 ## delete
84 ## delete
85 self.app.post(base.url('admin_settings_hooks'),
85 self.app.post(base.url('admin_settings_hooks'),
86 params=dict(hook_id=hook_id, _session_csrf_secret_token=self.session_csrf_secret_token()))
86 params=dict(hook_id=hook_id, _session_csrf_secret_token=self.session_csrf_secret_token()))
@@ -124,7 +124,7 b' class TestAdminSettingsController(base.T'
124
124
125 self.checkSessionFlash(response, 'Updated application settings')
125 self.checkSessionFlash(response, 'Updated application settings')
126
126
127 assert Setting.get_app_settings()['ga_code'] == new_ga_code
127 assert db.Setting.get_app_settings()['ga_code'] == new_ga_code
128
128
129 response = response.follow()
129 response = response.follow()
130 response.mustcontain("""_gaq.push(['_setAccount', '%s']);""" % new_ga_code)
130 response.mustcontain("""_gaq.push(['_setAccount', '%s']);""" % new_ga_code)
@@ -144,7 +144,7 b' class TestAdminSettingsController(base.T'
144 ))
144 ))
145
145
146 self.checkSessionFlash(response, 'Updated application settings')
146 self.checkSessionFlash(response, 'Updated application settings')
147 assert Setting.get_app_settings()['ga_code'] == new_ga_code
147 assert db.Setting.get_app_settings()['ga_code'] == new_ga_code
148
148
149 response = response.follow()
149 response = response.follow()
150 response.mustcontain(no=["_gaq.push(['_setAccount', '%s']);" % new_ga_code])
150 response.mustcontain(no=["_gaq.push(['_setAccount', '%s']);" % new_ga_code])
@@ -164,7 +164,7 b' class TestAdminSettingsController(base.T'
164 ))
164 ))
165
165
166 self.checkSessionFlash(response, 'Updated application settings')
166 self.checkSessionFlash(response, 'Updated application settings')
167 assert Setting.get_app_settings()['captcha_private_key'] == '1234567890'
167 assert db.Setting.get_app_settings()['captcha_private_key'] == '1234567890'
168
168
169 response = self.app.get(base.url('register'))
169 response = self.app.get(base.url('register'))
170 response.mustcontain('captcha')
170 response.mustcontain('captcha')
@@ -184,7 +184,7 b' class TestAdminSettingsController(base.T'
184 ))
184 ))
185
185
186 self.checkSessionFlash(response, 'Updated application settings')
186 self.checkSessionFlash(response, 'Updated application settings')
187 assert Setting.get_app_settings()['captcha_private_key'] == ''
187 assert db.Setting.get_app_settings()['captcha_private_key'] == ''
188
188
189 response = self.app.get(base.url('register'))
189 response = self.app.get(base.url('register'))
190 response.mustcontain(no=['captcha'])
190 response.mustcontain(no=['captcha'])
@@ -206,7 +206,7 b' class TestAdminSettingsController(base.T'
206 ))
206 ))
207
207
208 self.checkSessionFlash(response, 'Updated application settings')
208 self.checkSessionFlash(response, 'Updated application settings')
209 assert Setting.get_app_settings()['title'] == new_title
209 assert db.Setting.get_app_settings()['title'] == new_title
210
210
211 response = response.follow()
211 response = response.follow()
212 response.mustcontain("""<span class="branding">%s</span>""" % new_title)
212 response.mustcontain("""<span class="branding">%s</span>""" % new_title)
@@ -1,6 +1,5 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 from kallithea.model import meta
2 from kallithea.model import db, meta
3 from kallithea.model.db import Permission, UserGroup, UserGroupToPerm
4 from kallithea.tests import base
3 from kallithea.tests import base
5
4
6
5
@@ -52,14 +51,14 b' class TestAdminUsersGroupsController(bas'
52 self.checkSessionFlash(response,
51 self.checkSessionFlash(response,
53 'Created user group ')
52 'Created user group ')
54
53
55 gr = meta.Session().query(UserGroup) \
54 gr = meta.Session().query(db.UserGroup) \
56 .filter(UserGroup.users_group_name == users_group_name).one()
55 .filter(db.UserGroup.users_group_name == users_group_name).one()
57
56
58 response = self.app.post(base.url('delete_users_group', id=gr.users_group_id),
57 response = self.app.post(base.url('delete_users_group', id=gr.users_group_id),
59 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
58 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
60
59
61 gr = meta.Session().query(UserGroup) \
60 gr = meta.Session().query(db.UserGroup) \
62 .filter(UserGroup.users_group_name == users_group_name).scalar()
61 .filter(db.UserGroup.users_group_name == users_group_name).scalar()
63
62
64 assert gr is None
63 assert gr is None
65
64
@@ -73,7 +72,7 b' class TestAdminUsersGroupsController(bas'
73 '_session_csrf_secret_token': self.session_csrf_secret_token()})
72 '_session_csrf_secret_token': self.session_csrf_secret_token()})
74 response.follow()
73 response.follow()
75
74
76 ug = UserGroup.get_by_group_name(users_group_name)
75 ug = db.UserGroup.get_by_group_name(users_group_name)
77 self.checkSessionFlash(response,
76 self.checkSessionFlash(response,
78 'Created user group ')
77 'Created user group ')
79 ## ENABLE REPO CREATE ON A GROUP
78 ## ENABLE REPO CREATE ON A GROUP
@@ -82,14 +81,14 b' class TestAdminUsersGroupsController(bas'
82 {'create_repo_perm': True,
81 {'create_repo_perm': True,
83 '_session_csrf_secret_token': self.session_csrf_secret_token()})
82 '_session_csrf_secret_token': self.session_csrf_secret_token()})
84 response.follow()
83 response.follow()
85 ug = UserGroup.get_by_group_name(users_group_name)
84 ug = db.UserGroup.get_by_group_name(users_group_name)
86 p = Permission.get_by_key('hg.create.repository')
85 p = db.Permission.get_by_key('hg.create.repository')
87 p2 = Permission.get_by_key('hg.usergroup.create.false')
86 p2 = db.Permission.get_by_key('hg.usergroup.create.false')
88 p3 = Permission.get_by_key('hg.fork.none')
87 p3 = db.Permission.get_by_key('hg.fork.none')
89 # check if user has this perms, they should be here since
88 # check if user has this perms, they should be here since
90 # defaults are on
89 # defaults are on
91 perms = UserGroupToPerm.query() \
90 perms = db.UserGroupToPerm.query() \
92 .filter(UserGroupToPerm.users_group == ug).all()
91 .filter(db.UserGroupToPerm.users_group == ug).all()
93
92
94 assert sorted([[x.users_group_id, x.permission_id, ] for x in perms]) == sorted([[ug.users_group_id, p.permission_id],
93 assert sorted([[x.users_group_id, x.permission_id, ] for x in perms]) == sorted([[ug.users_group_id, p.permission_id],
95 [ug.users_group_id, p2.permission_id],
94 [ug.users_group_id, p2.permission_id],
@@ -101,33 +100,33 b' class TestAdminUsersGroupsController(bas'
101 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
100 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
102
101
103 response.follow()
102 response.follow()
104 ug = UserGroup.get_by_group_name(users_group_name)
103 ug = db.UserGroup.get_by_group_name(users_group_name)
105 p = Permission.get_by_key('hg.create.none')
104 p = db.Permission.get_by_key('hg.create.none')
106 p2 = Permission.get_by_key('hg.usergroup.create.false')
105 p2 = db.Permission.get_by_key('hg.usergroup.create.false')
107 p3 = Permission.get_by_key('hg.fork.none')
106 p3 = db.Permission.get_by_key('hg.fork.none')
108
107
109 # check if user has this perms, they should be here since
108 # check if user has this perms, they should be here since
110 # defaults are on
109 # defaults are on
111 perms = UserGroupToPerm.query() \
110 perms = db.UserGroupToPerm.query() \
112 .filter(UserGroupToPerm.users_group == ug).all()
111 .filter(db.UserGroupToPerm.users_group == ug).all()
113
112
114 assert sorted([[x.users_group_id, x.permission_id, ] for x in perms]) == sorted([[ug.users_group_id, p.permission_id],
113 assert sorted([[x.users_group_id, x.permission_id, ] for x in perms]) == sorted([[ug.users_group_id, p.permission_id],
115 [ug.users_group_id, p2.permission_id],
114 [ug.users_group_id, p2.permission_id],
116 [ug.users_group_id, p3.permission_id]])
115 [ug.users_group_id, p3.permission_id]])
117
116
118 # DELETE !
117 # DELETE !
119 ug = UserGroup.get_by_group_name(users_group_name)
118 ug = db.UserGroup.get_by_group_name(users_group_name)
120 ugid = ug.users_group_id
119 ugid = ug.users_group_id
121 response = self.app.post(base.url('delete_users_group', id=ug.users_group_id),
120 response = self.app.post(base.url('delete_users_group', id=ug.users_group_id),
122 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
121 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
123 response = response.follow()
122 response = response.follow()
124 gr = meta.Session().query(UserGroup) \
123 gr = meta.Session().query(db.UserGroup) \
125 .filter(UserGroup.users_group_name == users_group_name).scalar()
124 .filter(db.UserGroup.users_group_name == users_group_name).scalar()
126
125
127 assert gr is None
126 assert gr is None
128 p = Permission.get_by_key('hg.create.repository')
127 p = db.Permission.get_by_key('hg.create.repository')
129 perms = UserGroupToPerm.query() \
128 perms = db.UserGroupToPerm.query() \
130 .filter(UserGroupToPerm.users_group_id == ugid).all()
129 .filter(db.UserGroupToPerm.users_group_id == ugid).all()
131 perms = [[x.users_group_id,
130 perms = [[x.users_group_id,
132 x.permission_id, ] for x in perms]
131 x.permission_id, ] for x in perms]
133 assert perms == []
132 assert perms == []
@@ -142,7 +141,7 b' class TestAdminUsersGroupsController(bas'
142 '_session_csrf_secret_token': self.session_csrf_secret_token()})
141 '_session_csrf_secret_token': self.session_csrf_secret_token()})
143 response.follow()
142 response.follow()
144
143
145 ug = UserGroup.get_by_group_name(users_group_name)
144 ug = db.UserGroup.get_by_group_name(users_group_name)
146 self.checkSessionFlash(response,
145 self.checkSessionFlash(response,
147 'Created user group ')
146 'Created user group ')
148 ## ENABLE REPO CREATE ON A GROUP
147 ## ENABLE REPO CREATE ON A GROUP
@@ -151,14 +150,14 b' class TestAdminUsersGroupsController(bas'
151 {'fork_repo_perm': True, '_session_csrf_secret_token': self.session_csrf_secret_token()})
150 {'fork_repo_perm': True, '_session_csrf_secret_token': self.session_csrf_secret_token()})
152
151
153 response.follow()
152 response.follow()
154 ug = UserGroup.get_by_group_name(users_group_name)
153 ug = db.UserGroup.get_by_group_name(users_group_name)
155 p = Permission.get_by_key('hg.create.none')
154 p = db.Permission.get_by_key('hg.create.none')
156 p2 = Permission.get_by_key('hg.usergroup.create.false')
155 p2 = db.Permission.get_by_key('hg.usergroup.create.false')
157 p3 = Permission.get_by_key('hg.fork.repository')
156 p3 = db.Permission.get_by_key('hg.fork.repository')
158 # check if user has this perms, they should be here since
157 # check if user has this perms, they should be here since
159 # defaults are on
158 # defaults are on
160 perms = UserGroupToPerm.query() \
159 perms = db.UserGroupToPerm.query() \
161 .filter(UserGroupToPerm.users_group == ug).all()
160 .filter(db.UserGroupToPerm.users_group == ug).all()
162
161
163 assert sorted([[x.users_group_id, x.permission_id, ] for x in perms]) == sorted([[ug.users_group_id, p.permission_id],
162 assert sorted([[x.users_group_id, x.permission_id, ] for x in perms]) == sorted([[ug.users_group_id, p.permission_id],
164 [ug.users_group_id, p2.permission_id],
163 [ug.users_group_id, p2.permission_id],
@@ -169,33 +168,33 b' class TestAdminUsersGroupsController(bas'
169 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
168 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
170
169
171 response.follow()
170 response.follow()
172 ug = UserGroup.get_by_group_name(users_group_name)
171 ug = db.UserGroup.get_by_group_name(users_group_name)
173 p = Permission.get_by_key('hg.create.none')
172 p = db.Permission.get_by_key('hg.create.none')
174 p2 = Permission.get_by_key('hg.usergroup.create.false')
173 p2 = db.Permission.get_by_key('hg.usergroup.create.false')
175 p3 = Permission.get_by_key('hg.fork.none')
174 p3 = db.Permission.get_by_key('hg.fork.none')
176 # check if user has this perms, they should be here since
175 # check if user has this perms, they should be here since
177 # defaults are on
176 # defaults are on
178 perms = UserGroupToPerm.query() \
177 perms = db.UserGroupToPerm.query() \
179 .filter(UserGroupToPerm.users_group == ug).all()
178 .filter(db.UserGroupToPerm.users_group == ug).all()
180
179
181 assert sorted([[x.users_group_id, x.permission_id, ] for x in perms]) == sorted([[ug.users_group_id, p.permission_id],
180 assert sorted([[x.users_group_id, x.permission_id, ] for x in perms]) == sorted([[ug.users_group_id, p.permission_id],
182 [ug.users_group_id, p2.permission_id],
181 [ug.users_group_id, p2.permission_id],
183 [ug.users_group_id, p3.permission_id]])
182 [ug.users_group_id, p3.permission_id]])
184
183
185 # DELETE !
184 # DELETE !
186 ug = UserGroup.get_by_group_name(users_group_name)
185 ug = db.UserGroup.get_by_group_name(users_group_name)
187 ugid = ug.users_group_id
186 ugid = ug.users_group_id
188 response = self.app.post(base.url('delete_users_group', id=ug.users_group_id),
187 response = self.app.post(base.url('delete_users_group', id=ug.users_group_id),
189 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
188 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
190 response = response.follow()
189 response = response.follow()
191 gr = meta.Session().query(UserGroup) \
190 gr = meta.Session().query(db.UserGroup) \
192 .filter(UserGroup.users_group_name ==
191 .filter(db.UserGroup.users_group_name ==
193 users_group_name).scalar()
192 users_group_name).scalar()
194
193
195 assert gr is None
194 assert gr is None
196 p = Permission.get_by_key('hg.fork.repository')
195 p = db.Permission.get_by_key('hg.fork.repository')
197 perms = UserGroupToPerm.query() \
196 perms = db.UserGroupToPerm.query() \
198 .filter(UserGroupToPerm.users_group_id == ugid).all()
197 .filter(db.UserGroupToPerm.users_group_id == ugid).all()
199 perms = [[x.users_group_id,
198 perms = [[x.users_group_id,
200 x.permission_id, ] for x in perms]
199 x.permission_id, ] for x in perms]
201 assert perms == []
200 assert perms == []
@@ -21,8 +21,7 b' import kallithea'
21 from kallithea.controllers.admin.users import UsersController
21 from kallithea.controllers.admin.users import UsersController
22 from kallithea.lib import helpers as h
22 from kallithea.lib import helpers as h
23 from kallithea.lib.auth import check_password
23 from kallithea.lib.auth import check_password
24 from kallithea.model import meta, validators
24 from kallithea.model import db, meta, validators
25 from kallithea.model.db import Permission, RepoGroup, User, UserApiKeys, UserSshKeys
26 from kallithea.model.user import UserModel
25 from kallithea.model.user import UserModel
27 from kallithea.tests import base
26 from kallithea.tests import base
28 from kallithea.tests.fixture import Fixture
27 from kallithea.tests.fixture import Fixture
@@ -39,7 +38,7 b' def user_and_repo_group_fail():'
39 repo_group = fixture.create_repo_group(name=groupname, cur_user=username)
38 repo_group = fixture.create_repo_group(name=groupname, cur_user=username)
40 yield user, repo_group
39 yield user, repo_group
41 # cleanup
40 # cleanup
42 if RepoGroup.get_by_group_name(groupname):
41 if db.RepoGroup.get_by_group_name(groupname):
43 fixture.destroy_repo_group(repo_group)
42 fixture.destroy_repo_group(repo_group)
44
43
45
44
@@ -48,7 +47,7 b' class TestAdminUsersController(base.Test'
48
47
49 @classmethod
48 @classmethod
50 def teardown_class(cls):
49 def teardown_class(cls):
51 if User.get_by_username(cls.test_user_1):
50 if db.User.get_by_username(cls.test_user_1):
52 UserModel().delete(cls.test_user_1)
51 UserModel().delete(cls.test_user_1)
53 meta.Session().commit()
52 meta.Session().commit()
54
53
@@ -85,8 +84,8 b' class TestAdminUsersController(base.Test'
85 response = response.follow()
84 response = response.follow()
86 response.mustcontain("""%s user settings""" % username) # in <title>
85 response.mustcontain("""%s user settings""" % username) # in <title>
87
86
88 new_user = meta.Session().query(User). \
87 new_user = meta.Session().query(db.User). \
89 filter(User.username == username).one()
88 filter(db.User.username == username).one()
90
89
91 assert new_user.username == username
90 assert new_user.username == username
92 assert check_password(password, new_user.password) == True
91 assert check_password(password, new_user.password) == True
@@ -119,7 +118,7 b' class TestAdminUsersController(base.Test'
119 response.mustcontain("""<span class="error-message">An email address must contain a single @</span>""")
118 response.mustcontain("""<span class="error-message">An email address must contain a single @</span>""")
120
119
121 def get_user():
120 def get_user():
122 meta.Session().query(User).filter(User.username == username).one()
121 meta.Session().query(db.User).filter(db.User.username == username).one()
123
122
124 with pytest.raises(NoResultFound):
123 with pytest.raises(NoResultFound):
125 get_user(), 'found user in database'
124 get_user(), 'found user in database'
@@ -171,7 +170,7 b' class TestAdminUsersController(base.Test'
171 self.checkSessionFlash(response, 'User updated successfully')
170 self.checkSessionFlash(response, 'User updated successfully')
172 params.pop('_session_csrf_secret_token')
171 params.pop('_session_csrf_secret_token')
173
172
174 updated_user = User.get_by_username(self.test_user_1)
173 updated_user = db.User.get_by_username(self.test_user_1)
175 updated_params = updated_user.get_api_data(True)
174 updated_params = updated_user.get_api_data(True)
176 updated_params.update({'password_confirmation': ''})
175 updated_params.update({'password_confirmation': ''})
177 updated_params.update({'new_password': ''})
176 updated_params.update({'new_password': ''})
@@ -184,8 +183,8 b' class TestAdminUsersController(base.Test'
184
183
185 fixture.create_user(name=username)
184 fixture.create_user(name=username)
186
185
187 new_user = meta.Session().query(User) \
186 new_user = meta.Session().query(db.User) \
188 .filter(User.username == username).one()
187 .filter(db.User.username == username).one()
189 response = self.app.post(base.url('delete_user', id=new_user.user_id),
188 response = self.app.post(base.url('delete_user', id=new_user.user_id),
190 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
189 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
191
190
@@ -199,8 +198,8 b' class TestAdminUsersController(base.Test'
199 fixture.create_user(name=username)
198 fixture.create_user(name=username)
200 fixture.create_repo(name=reponame, cur_user=username)
199 fixture.create_repo(name=reponame, cur_user=username)
201
200
202 new_user = meta.Session().query(User) \
201 new_user = meta.Session().query(db.User) \
203 .filter(User.username == username).one()
202 .filter(db.User.username == username).one()
204 response = self.app.post(base.url('delete_user', id=new_user.user_id),
203 response = self.app.post(base.url('delete_user', id=new_user.user_id),
205 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
204 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
206 self.checkSessionFlash(response, 'User &quot;%s&quot; still '
205 self.checkSessionFlash(response, 'User &quot;%s&quot; still '
@@ -231,7 +230,7 b' class TestAdminUsersController(base.Test'
231 '%s' % (username, groupname))
230 '%s' % (username, groupname))
232
231
233 # Relevant _if_ the user deletion succeeded to make sure we can render groups without owner
232 # Relevant _if_ the user deletion succeeded to make sure we can render groups without owner
234 # rg = RepoGroup.get_by_group_name(group_name=groupname)
233 # rg = db.RepoGroup.get_by_group_name(group_name=groupname)
235 # response = self.app.get(base.url('repos_groups', id=rg.group_id))
234 # response = self.app.get(base.url('repos_groups', id=rg.group_id))
236
235
237 response = self.app.post(base.url('delete_repo_group', group_name=groupname),
236 response = self.app.post(base.url('delete_repo_group', group_name=groupname),
@@ -250,8 +249,8 b' class TestAdminUsersController(base.Test'
250 fixture.create_user(name=username)
249 fixture.create_user(name=username)
251 ug = fixture.create_user_group(name=groupname, cur_user=username)
250 ug = fixture.create_user_group(name=groupname, cur_user=username)
252
251
253 new_user = meta.Session().query(User) \
252 new_user = meta.Session().query(db.User) \
254 .filter(User.username == username).one()
253 .filter(db.User.username == username).one()
255 response = self.app.post(base.url('delete_user', id=new_user.user_id),
254 response = self.app.post(base.url('delete_user', id=new_user.user_id),
256 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
255 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
257 self.checkSessionFlash(response, 'User &quot;%s&quot; still '
256 self.checkSessionFlash(response, 'User &quot;%s&quot; still '
@@ -271,13 +270,13 b' class TestAdminUsersController(base.Test'
271
270
272 def test_edit(self):
271 def test_edit(self):
273 self.log_user()
272 self.log_user()
274 user = User.get_by_username(base.TEST_USER_ADMIN_LOGIN)
273 user = db.User.get_by_username(base.TEST_USER_ADMIN_LOGIN)
275 response = self.app.get(base.url('edit_user', id=user.user_id))
274 response = self.app.get(base.url('edit_user', id=user.user_id))
276
275
277 def test_add_perm_create_repo(self):
276 def test_add_perm_create_repo(self):
278 self.log_user()
277 self.log_user()
279 perm_none = Permission.get_by_key('hg.create.none')
278 perm_none = db.Permission.get_by_key('hg.create.none')
280 perm_create = Permission.get_by_key('hg.create.repository')
279 perm_create = db.Permission.get_by_key('hg.create.repository')
281
280
282 user = UserModel().create_or_update(username='dummy', password='qwe',
281 user = UserModel().create_or_update(username='dummy', password='qwe',
283 email='dummy', firstname='a',
282 email='dummy', firstname='a',
@@ -294,8 +293,8 b' class TestAdminUsersController(base.Test'
294 params=dict(create_repo_perm=True,
293 params=dict(create_repo_perm=True,
295 _session_csrf_secret_token=self.session_csrf_secret_token()))
294 _session_csrf_secret_token=self.session_csrf_secret_token()))
296
295
297 perm_none = Permission.get_by_key('hg.create.none')
296 perm_none = db.Permission.get_by_key('hg.create.none')
298 perm_create = Permission.get_by_key('hg.create.repository')
297 perm_create = db.Permission.get_by_key('hg.create.repository')
299
298
300 # User should have None permission on creation repository
299 # User should have None permission on creation repository
301 assert UserModel().has_perm(uid, perm_none) == False
300 assert UserModel().has_perm(uid, perm_none) == False
@@ -306,8 +305,8 b' class TestAdminUsersController(base.Test'
306
305
307 def test_revoke_perm_create_repo(self):
306 def test_revoke_perm_create_repo(self):
308 self.log_user()
307 self.log_user()
309 perm_none = Permission.get_by_key('hg.create.none')
308 perm_none = db.Permission.get_by_key('hg.create.none')
310 perm_create = Permission.get_by_key('hg.create.repository')
309 perm_create = db.Permission.get_by_key('hg.create.repository')
311
310
312 user = UserModel().create_or_update(username='dummy', password='qwe',
311 user = UserModel().create_or_update(username='dummy', password='qwe',
313 email='dummy', firstname='a',
312 email='dummy', firstname='a',
@@ -323,8 +322,8 b' class TestAdminUsersController(base.Test'
323 response = self.app.post(base.url('edit_user_perms_update', id=uid),
322 response = self.app.post(base.url('edit_user_perms_update', id=uid),
324 params=dict(_session_csrf_secret_token=self.session_csrf_secret_token()))
323 params=dict(_session_csrf_secret_token=self.session_csrf_secret_token()))
325
324
326 perm_none = Permission.get_by_key('hg.create.none')
325 perm_none = db.Permission.get_by_key('hg.create.none')
327 perm_create = Permission.get_by_key('hg.create.repository')
326 perm_create = db.Permission.get_by_key('hg.create.repository')
328
327
329 # User should have None permission on creation repository
328 # User should have None permission on creation repository
330 assert UserModel().has_perm(uid, perm_none) == True
329 assert UserModel().has_perm(uid, perm_none) == True
@@ -335,8 +334,8 b' class TestAdminUsersController(base.Test'
335
334
336 def test_add_perm_fork_repo(self):
335 def test_add_perm_fork_repo(self):
337 self.log_user()
336 self.log_user()
338 perm_none = Permission.get_by_key('hg.fork.none')
337 perm_none = db.Permission.get_by_key('hg.fork.none')
339 perm_fork = Permission.get_by_key('hg.fork.repository')
338 perm_fork = db.Permission.get_by_key('hg.fork.repository')
340
339
341 user = UserModel().create_or_update(username='dummy', password='qwe',
340 user = UserModel().create_or_update(username='dummy', password='qwe',
342 email='dummy', firstname='a',
341 email='dummy', firstname='a',
@@ -353,8 +352,8 b' class TestAdminUsersController(base.Test'
353 params=dict(create_repo_perm=True,
352 params=dict(create_repo_perm=True,
354 _session_csrf_secret_token=self.session_csrf_secret_token()))
353 _session_csrf_secret_token=self.session_csrf_secret_token()))
355
354
356 perm_none = Permission.get_by_key('hg.create.none')
355 perm_none = db.Permission.get_by_key('hg.create.none')
357 perm_create = Permission.get_by_key('hg.create.repository')
356 perm_create = db.Permission.get_by_key('hg.create.repository')
358
357
359 # User should have None permission on creation repository
358 # User should have None permission on creation repository
360 assert UserModel().has_perm(uid, perm_none) == False
359 assert UserModel().has_perm(uid, perm_none) == False
@@ -365,8 +364,8 b' class TestAdminUsersController(base.Test'
365
364
366 def test_revoke_perm_fork_repo(self):
365 def test_revoke_perm_fork_repo(self):
367 self.log_user()
366 self.log_user()
368 perm_none = Permission.get_by_key('hg.fork.none')
367 perm_none = db.Permission.get_by_key('hg.fork.none')
369 perm_fork = Permission.get_by_key('hg.fork.repository')
368 perm_fork = db.Permission.get_by_key('hg.fork.repository')
370
369
371 user = UserModel().create_or_update(username='dummy', password='qwe',
370 user = UserModel().create_or_update(username='dummy', password='qwe',
372 email='dummy', firstname='a',
371 email='dummy', firstname='a',
@@ -382,8 +381,8 b' class TestAdminUsersController(base.Test'
382 response = self.app.post(base.url('edit_user_perms_update', id=uid),
381 response = self.app.post(base.url('edit_user_perms_update', id=uid),
383 params=dict(_session_csrf_secret_token=self.session_csrf_secret_token()))
382 params=dict(_session_csrf_secret_token=self.session_csrf_secret_token()))
384
383
385 perm_none = Permission.get_by_key('hg.create.none')
384 perm_none = db.Permission.get_by_key('hg.create.none')
386 perm_create = Permission.get_by_key('hg.create.repository')
385 perm_create = db.Permission.get_by_key('hg.create.repository')
387
386
388 # User should have None permission on creation repository
387 # User should have None permission on creation repository
389 assert UserModel().has_perm(uid, perm_none) == True
388 assert UserModel().has_perm(uid, perm_none) == True
@@ -394,7 +393,7 b' class TestAdminUsersController(base.Test'
394
393
395 def test_ips(self):
394 def test_ips(self):
396 self.log_user()
395 self.log_user()
397 user = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
396 user = db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
398 response = self.app.get(base.url('edit_user_ips', id=user.user_id))
397 response = self.app.get(base.url('edit_user_ips', id=user.user_id))
399 response.mustcontain('All IP addresses are allowed')
398 response.mustcontain('All IP addresses are allowed')
400
399
@@ -408,7 +407,7 b' class TestAdminUsersController(base.Test'
408 ])
407 ])
409 def test_add_ip(self, test_name, ip, ip_range, failure, auto_clear_ip_permissions):
408 def test_add_ip(self, test_name, ip, ip_range, failure, auto_clear_ip_permissions):
410 self.log_user()
409 self.log_user()
411 user = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
410 user = db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
412 user_id = user.user_id
411 user_id = user.user_id
413
412
414 response = self.app.post(base.url('edit_user_ips_update', id=user_id),
413 response = self.app.post(base.url('edit_user_ips_update', id=user_id),
@@ -427,7 +426,7 b' class TestAdminUsersController(base.Test'
427
426
428 def test_delete_ip(self, auto_clear_ip_permissions):
427 def test_delete_ip(self, auto_clear_ip_permissions):
429 self.log_user()
428 self.log_user()
430 user = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
429 user = db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
431 user_id = user.user_id
430 user_id = user.user_id
432 ip = '127.0.0.1/32'
431 ip = '127.0.0.1/32'
433 ip_range = '127.0.0.1 - 127.0.0.1'
432 ip_range = '127.0.0.1 - 127.0.0.1'
@@ -451,7 +450,7 b' class TestAdminUsersController(base.Test'
451 def test_api_keys(self):
450 def test_api_keys(self):
452 self.log_user()
451 self.log_user()
453
452
454 user = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
453 user = db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
455 response = self.app.get(base.url('edit_user_api_keys', id=user.user_id))
454 response = self.app.get(base.url('edit_user_api_keys', id=user.user_id))
456 response.mustcontain(user.api_key)
455 response.mustcontain(user.api_key)
457 response.mustcontain('Expires: Never')
456 response.mustcontain('Expires: Never')
@@ -463,7 +462,7 b' class TestAdminUsersController(base.Test'
463 ])
462 ])
464 def test_add_api_keys(self, desc, lifetime):
463 def test_add_api_keys(self, desc, lifetime):
465 self.log_user()
464 self.log_user()
466 user = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
465 user = db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
467 user_id = user.user_id
466 user_id = user.user_id
468
467
469 response = self.app.post(base.url('edit_user_api_keys_update', id=user_id),
468 response = self.app.post(base.url('edit_user_api_keys_update', id=user_id),
@@ -471,17 +470,17 b' class TestAdminUsersController(base.Test'
471 self.checkSessionFlash(response, 'API key successfully created')
470 self.checkSessionFlash(response, 'API key successfully created')
472 try:
471 try:
473 response = response.follow()
472 response = response.follow()
474 user = User.get(user_id)
473 user = db.User.get(user_id)
475 for api_key in user.api_keys:
474 for api_key in user.api_keys:
476 response.mustcontain(api_key)
475 response.mustcontain(api_key)
477 finally:
476 finally:
478 for api_key in UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all():
477 for api_key in db.UserApiKeys.query().filter(db.UserApiKeys.user_id == user_id).all():
479 meta.Session().delete(api_key)
478 meta.Session().delete(api_key)
480 meta.Session().commit()
479 meta.Session().commit()
481
480
482 def test_remove_api_key(self):
481 def test_remove_api_key(self):
483 self.log_user()
482 self.log_user()
484 user = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
483 user = db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
485 user_id = user.user_id
484 user_id = user.user_id
486
485
487 response = self.app.post(base.url('edit_user_api_keys_update', id=user_id),
486 response = self.app.post(base.url('edit_user_api_keys_update', id=user_id),
@@ -490,18 +489,18 b' class TestAdminUsersController(base.Test'
490 response = response.follow()
489 response = response.follow()
491
490
492 # now delete our key
491 # now delete our key
493 keys = UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all()
492 keys = db.UserApiKeys.query().filter(db.UserApiKeys.user_id == user_id).all()
494 assert 1 == len(keys)
493 assert 1 == len(keys)
495
494
496 response = self.app.post(base.url('edit_user_api_keys_delete', id=user_id),
495 response = self.app.post(base.url('edit_user_api_keys_delete', id=user_id),
497 {'del_api_key': keys[0].api_key, '_session_csrf_secret_token': self.session_csrf_secret_token()})
496 {'del_api_key': keys[0].api_key, '_session_csrf_secret_token': self.session_csrf_secret_token()})
498 self.checkSessionFlash(response, 'API key successfully deleted')
497 self.checkSessionFlash(response, 'API key successfully deleted')
499 keys = UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all()
498 keys = db.UserApiKeys.query().filter(db.UserApiKeys.user_id == user_id).all()
500 assert 0 == len(keys)
499 assert 0 == len(keys)
501
500
502 def test_reset_main_api_key(self):
501 def test_reset_main_api_key(self):
503 self.log_user()
502 self.log_user()
504 user = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
503 user = db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
505 user_id = user.user_id
504 user_id = user.user_id
506 api_key = user.api_key
505 api_key = user.api_key
507 response = self.app.get(base.url('edit_user_api_keys', id=user_id))
506 response = self.app.get(base.url('edit_user_api_keys', id=user_id))
@@ -520,7 +519,7 b' class TestAdminUsersController(base.Test'
520 fingerprint = 'Ke3oUCNJM87P0jJTb3D+e3shjceP2CqMpQKVd75E9I8'
519 fingerprint = 'Ke3oUCNJM87P0jJTb3D+e3shjceP2CqMpQKVd75E9I8'
521
520
522 self.log_user()
521 self.log_user()
523 user = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
522 user = db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
524 user_id = user.user_id
523 user_id = user.user_id
525
524
526 response = self.app.post(base.url('edit_user_ssh_keys', id=user_id),
525 response = self.app.post(base.url('edit_user_ssh_keys', id=user_id),
@@ -531,7 +530,7 b' class TestAdminUsersController(base.Test'
531
530
532 response = response.follow()
531 response = response.follow()
533 response.mustcontain(fingerprint)
532 response.mustcontain(fingerprint)
534 ssh_key = UserSshKeys.query().filter(UserSshKeys.user_id == user_id).one()
533 ssh_key = db.UserSshKeys.query().filter(db.UserSshKeys.user_id == user_id).one()
535 assert ssh_key.fingerprint == fingerprint
534 assert ssh_key.fingerprint == fingerprint
536 assert ssh_key.description == description
535 assert ssh_key.description == description
537 meta.Session().delete(ssh_key)
536 meta.Session().delete(ssh_key)
@@ -543,7 +542,7 b' class TestAdminUsersController(base.Test'
543 fingerprint = 'Ke3oUCNJM87P0jJTb3D+e3shjceP2CqMpQKVd75E9I8'
542 fingerprint = 'Ke3oUCNJM87P0jJTb3D+e3shjceP2CqMpQKVd75E9I8'
544
543
545 self.log_user()
544 self.log_user()
546 user = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
545 user = db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
547 user_id = user.user_id
546 user_id = user.user_id
548
547
549 response = self.app.post(base.url('edit_user_ssh_keys', id=user_id),
548 response = self.app.post(base.url('edit_user_ssh_keys', id=user_id),
@@ -552,14 +551,14 b' class TestAdminUsersController(base.Test'
552 '_session_csrf_secret_token': self.session_csrf_secret_token()})
551 '_session_csrf_secret_token': self.session_csrf_secret_token()})
553 self.checkSessionFlash(response, 'SSH key %s successfully added' % fingerprint)
552 self.checkSessionFlash(response, 'SSH key %s successfully added' % fingerprint)
554 response.follow()
553 response.follow()
555 ssh_key = UserSshKeys.query().filter(UserSshKeys.user_id == user_id).one()
554 ssh_key = db.UserSshKeys.query().filter(db.UserSshKeys.user_id == user_id).one()
556 assert ssh_key.description == 'me@localhost'
555 assert ssh_key.description == 'me@localhost'
557
556
558 response = self.app.post(base.url('edit_user_ssh_keys_delete', id=user_id),
557 response = self.app.post(base.url('edit_user_ssh_keys_delete', id=user_id),
559 {'del_public_key_fingerprint': ssh_key.fingerprint,
558 {'del_public_key_fingerprint': ssh_key.fingerprint,
560 '_session_csrf_secret_token': self.session_csrf_secret_token()})
559 '_session_csrf_secret_token': self.session_csrf_secret_token()})
561 self.checkSessionFlash(response, 'SSH key successfully deleted')
560 self.checkSessionFlash(response, 'SSH key successfully deleted')
562 keys = UserSshKeys.query().all()
561 keys = db.UserSshKeys.query().all()
563 assert 0 == len(keys)
562 assert 0 == len(keys)
564
563
565
564
@@ -574,7 +573,7 b' class TestAdminUsersController_unittest('
574
573
575 u = UsersController()
574 u = UsersController()
576 # a regular user should work correctly
575 # a regular user should work correctly
577 user = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
576 user = db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
578 assert u._get_user_or_raise_if_default(user.user_id) == user
577 assert u._get_user_or_raise_if_default(user.user_id) == user
579 # the default user should raise
578 # the default user should raise
580 with pytest.raises(HTTPNotFound):
579 with pytest.raises(HTTPNotFound):
@@ -588,59 +587,59 b' class TestAdminUsersControllerForDefault'
588 """
587 """
589 def test_edit_default_user(self):
588 def test_edit_default_user(self):
590 self.log_user()
589 self.log_user()
591 user = User.get_default_user()
590 user = db.User.get_default_user()
592 response = self.app.get(base.url('edit_user', id=user.user_id), status=404)
591 response = self.app.get(base.url('edit_user', id=user.user_id), status=404)
593
592
594 def test_edit_advanced_default_user(self):
593 def test_edit_advanced_default_user(self):
595 self.log_user()
594 self.log_user()
596 user = User.get_default_user()
595 user = db.User.get_default_user()
597 response = self.app.get(base.url('edit_user_advanced', id=user.user_id), status=404)
596 response = self.app.get(base.url('edit_user_advanced', id=user.user_id), status=404)
598
597
599 # API keys
598 # API keys
600 def test_edit_api_keys_default_user(self):
599 def test_edit_api_keys_default_user(self):
601 self.log_user()
600 self.log_user()
602 user = User.get_default_user()
601 user = db.User.get_default_user()
603 response = self.app.get(base.url('edit_user_api_keys', id=user.user_id), status=404)
602 response = self.app.get(base.url('edit_user_api_keys', id=user.user_id), status=404)
604
603
605 def test_add_api_keys_default_user(self):
604 def test_add_api_keys_default_user(self):
606 self.log_user()
605 self.log_user()
607 user = User.get_default_user()
606 user = db.User.get_default_user()
608 response = self.app.post(base.url('edit_user_api_keys_update', id=user.user_id),
607 response = self.app.post(base.url('edit_user_api_keys_update', id=user.user_id),
609 {'_session_csrf_secret_token': self.session_csrf_secret_token()}, status=404)
608 {'_session_csrf_secret_token': self.session_csrf_secret_token()}, status=404)
610
609
611 def test_delete_api_keys_default_user(self):
610 def test_delete_api_keys_default_user(self):
612 self.log_user()
611 self.log_user()
613 user = User.get_default_user()
612 user = db.User.get_default_user()
614 response = self.app.post(base.url('edit_user_api_keys_delete', id=user.user_id),
613 response = self.app.post(base.url('edit_user_api_keys_delete', id=user.user_id),
615 {'_session_csrf_secret_token': self.session_csrf_secret_token()}, status=404)
614 {'_session_csrf_secret_token': self.session_csrf_secret_token()}, status=404)
616
615
617 # Permissions
616 # Permissions
618 def test_edit_perms_default_user(self):
617 def test_edit_perms_default_user(self):
619 self.log_user()
618 self.log_user()
620 user = User.get_default_user()
619 user = db.User.get_default_user()
621 response = self.app.get(base.url('edit_user_perms', id=user.user_id), status=404)
620 response = self.app.get(base.url('edit_user_perms', id=user.user_id), status=404)
622
621
623 def test_update_perms_default_user(self):
622 def test_update_perms_default_user(self):
624 self.log_user()
623 self.log_user()
625 user = User.get_default_user()
624 user = db.User.get_default_user()
626 response = self.app.post(base.url('edit_user_perms_update', id=user.user_id),
625 response = self.app.post(base.url('edit_user_perms_update', id=user.user_id),
627 {'_session_csrf_secret_token': self.session_csrf_secret_token()}, status=404)
626 {'_session_csrf_secret_token': self.session_csrf_secret_token()}, status=404)
628
627
629 # Emails
628 # Emails
630 def test_edit_emails_default_user(self):
629 def test_edit_emails_default_user(self):
631 self.log_user()
630 self.log_user()
632 user = User.get_default_user()
631 user = db.User.get_default_user()
633 response = self.app.get(base.url('edit_user_emails', id=user.user_id), status=404)
632 response = self.app.get(base.url('edit_user_emails', id=user.user_id), status=404)
634
633
635 def test_add_emails_default_user(self):
634 def test_add_emails_default_user(self):
636 self.log_user()
635 self.log_user()
637 user = User.get_default_user()
636 user = db.User.get_default_user()
638 response = self.app.post(base.url('edit_user_emails_update', id=user.user_id),
637 response = self.app.post(base.url('edit_user_emails_update', id=user.user_id),
639 {'_session_csrf_secret_token': self.session_csrf_secret_token()}, status=404)
638 {'_session_csrf_secret_token': self.session_csrf_secret_token()}, status=404)
640
639
641 def test_delete_emails_default_user(self):
640 def test_delete_emails_default_user(self):
642 self.log_user()
641 self.log_user()
643 user = User.get_default_user()
642 user = db.User.get_default_user()
644 response = self.app.post(base.url('edit_user_emails_delete', id=user.user_id),
643 response = self.app.post(base.url('edit_user_emails_delete', id=user.user_id),
645 {'_session_csrf_secret_token': self.session_csrf_secret_token()}, status=404)
644 {'_session_csrf_secret_token': self.session_csrf_secret_token()}, status=404)
646
645
@@ -649,5 +648,5 b' class TestAdminUsersControllerForDefault'
649 # the global IP whitelist and thus allowed. Only 'edit' is forbidden.
648 # the global IP whitelist and thus allowed. Only 'edit' is forbidden.
650 def test_edit_ip_default_user(self):
649 def test_edit_ip_default_user(self):
651 self.log_user()
650 self.log_user()
652 user = User.get_default_user()
651 user = db.User.get_default_user()
653 response = self.app.get(base.url('edit_user_ips', id=user.user_id), status=404)
652 response = self.app.get(base.url('edit_user_ips', id=user.user_id), status=404)
@@ -1,15 +1,14 b''
1 import re
1 import re
2
2
3 from kallithea.model import meta
3 from kallithea.model import db, meta
4 from kallithea.model.changeset_status import ChangesetStatusModel
4 from kallithea.model.changeset_status import ChangesetStatusModel
5 from kallithea.model.db import ChangesetComment, PullRequest
6 from kallithea.tests import base
5 from kallithea.tests import base
7
6
8
7
9 class TestChangeSetCommentsController(base.TestController):
8 class TestChangeSetCommentsController(base.TestController):
10
9
11 def setup_method(self, method):
10 def setup_method(self, method):
12 for x in ChangesetComment.query().all():
11 for x in db.ChangesetComment.query().all():
13 meta.Session().delete(x)
12 meta.Session().delete(x)
14 meta.Session().commit()
13 meta.Session().commit()
15
14
@@ -34,7 +33,7 b' class TestChangeSetCommentsController(ba'
34 response.mustcontain(text)
33 response.mustcontain(text)
35
34
36 # test DB
35 # test DB
37 assert ChangesetComment.query().count() == 1
36 assert db.ChangesetComment.query().count() == 1
38
37
39 def test_create_inline(self):
38 def test_create_inline(self):
40 self.log_user()
39 self.log_user()
@@ -64,7 +63,7 b' class TestChangeSetCommentsController(ba'
64 response.mustcontain(text)
63 response.mustcontain(text)
65
64
66 # test DB
65 # test DB
67 assert ChangesetComment.query().count() == 1
66 assert db.ChangesetComment.query().count() == 1
68
67
69 def test_create_with_mention(self):
68 def test_create_with_mention(self):
70 self.log_user()
69 self.log_user()
@@ -88,7 +87,7 b' class TestChangeSetCommentsController(ba'
88 response.mustcontain('<b>@%s</b> check CommentOnRevision' % base.TEST_USER_REGULAR_LOGIN)
87 response.mustcontain('<b>@%s</b> check CommentOnRevision' % base.TEST_USER_REGULAR_LOGIN)
89
88
90 # test DB
89 # test DB
91 assert ChangesetComment.query().count() == 1
90 assert db.ChangesetComment.query().count() == 1
92
91
93 def test_create_status_change(self):
92 def test_create_status_change(self):
94 self.log_user()
93 self.log_user()
@@ -112,7 +111,7 b' class TestChangeSetCommentsController(ba'
112 response.mustcontain(text)
111 response.mustcontain(text)
113
112
114 # test DB
113 # test DB
115 assert ChangesetComment.query().count() == 1
114 assert db.ChangesetComment.query().count() == 1
116
115
117 # check status
116 # check status
118 status = ChangesetStatusModel().get_status(repo=base.HG_REPO, revision=rev)
117 status = ChangesetStatusModel().get_status(repo=base.HG_REPO, revision=rev)
@@ -128,7 +127,7 b' class TestChangeSetCommentsController(ba'
128 repo_name=base.HG_REPO, revision=rev),
127 repo_name=base.HG_REPO, revision=rev),
129 params=params, extra_environ={'HTTP_X_PARTIAL_XHR': '1'})
128 params=params, extra_environ={'HTTP_X_PARTIAL_XHR': '1'})
130
129
131 comments = ChangesetComment.query().all()
130 comments = db.ChangesetComment.query().all()
132 assert len(comments) == 1
131 assert len(comments) == 1
133 comment_id = comments[0].comment_id
132 comment_id = comments[0].comment_id
134
133
@@ -137,7 +136,7 b' class TestChangeSetCommentsController(ba'
137 comment_id=comment_id),
136 comment_id=comment_id),
138 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
137 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
139
138
140 comments = ChangesetComment.query().all()
139 comments = db.ChangesetComment.query().all()
141 assert len(comments) == 0
140 assert len(comments) == 0
142
141
143 response = self.app.get(base.url(controller='changeset', action='index',
142 response = self.app.get(base.url(controller='changeset', action='index',
@@ -152,7 +151,7 b' class TestChangeSetCommentsController(ba'
152 class TestPullrequestsCommentsController(base.TestController):
151 class TestPullrequestsCommentsController(base.TestController):
153
152
154 def setup_method(self, method):
153 def setup_method(self, method):
155 for x in ChangesetComment.query().all():
154 for x in db.ChangesetComment.query().all():
156 meta.Session().delete(x)
155 meta.Session().delete(x)
157 meta.Session().commit()
156 meta.Session().commit()
158
157
@@ -195,7 +194,7 b' class TestPullrequestsCommentsController'
195 response.mustcontain(text)
194 response.mustcontain(text)
196
195
197 # test DB
196 # test DB
198 assert ChangesetComment.query().count() == 2
197 assert db.ChangesetComment.query().count() == 2
199
198
200 def test_create_inline(self):
199 def test_create_inline(self):
201 self.log_user()
200 self.log_user()
@@ -225,7 +224,7 b' class TestPullrequestsCommentsController'
225 response.mustcontain(text)
224 response.mustcontain(text)
226
225
227 # test DB
226 # test DB
228 assert ChangesetComment.query().count() == 2
227 assert db.ChangesetComment.query().count() == 2
229
228
230 def test_create_with_mention(self):
229 def test_create_with_mention(self):
231 self.log_user()
230 self.log_user()
@@ -248,7 +247,7 b' class TestPullrequestsCommentsController'
248 response.mustcontain('<b>@%s</b> check CommentOnRevision' % base.TEST_USER_REGULAR_LOGIN)
247 response.mustcontain('<b>@%s</b> check CommentOnRevision' % base.TEST_USER_REGULAR_LOGIN)
249
248
250 # test DB
249 # test DB
251 assert ChangesetComment.query().count() == 2
250 assert db.ChangesetComment.query().count() == 2
252
251
253 def test_create_status_change(self):
252 def test_create_status_change(self):
254 self.log_user()
253 self.log_user()
@@ -275,7 +274,7 b' class TestPullrequestsCommentsController'
275 response.mustcontain(text)
274 response.mustcontain(text)
276
275
277 # test DB
276 # test DB
278 assert ChangesetComment.query().count() == 2
277 assert db.ChangesetComment.query().count() == 2
279
278
280 # check status
279 # check status
281 status = ChangesetStatusModel().get_status(repo=base.HG_REPO, pull_request=pr_id)
280 status = ChangesetStatusModel().get_status(repo=base.HG_REPO, pull_request=pr_id)
@@ -291,7 +290,7 b' class TestPullrequestsCommentsController'
291 repo_name=base.HG_REPO, pull_request_id=pr_id),
290 repo_name=base.HG_REPO, pull_request_id=pr_id),
292 params=params, extra_environ={'HTTP_X_PARTIAL_XHR': '1'})
291 params=params, extra_environ={'HTTP_X_PARTIAL_XHR': '1'})
293
292
294 comments = ChangesetComment.query().all()
293 comments = db.ChangesetComment.query().all()
295 assert len(comments) == 2
294 assert len(comments) == 2
296 comment_id = comments[-1].comment_id
295 comment_id = comments[-1].comment_id
297
296
@@ -300,7 +299,7 b' class TestPullrequestsCommentsController'
300 comment_id=comment_id),
299 comment_id=comment_id),
301 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
300 params={'_session_csrf_secret_token': self.session_csrf_secret_token()})
302
301
303 comments = ChangesetComment.query().all()
302 comments = db.ChangesetComment.query().all()
304 assert len(comments) == 1
303 assert len(comments) == 1
305
304
306 response = self.app.get(base.url(controller='pullrequests', action='show',
305 response = self.app.get(base.url(controller='pullrequests', action='show',
@@ -332,7 +331,7 b' class TestPullrequestsCommentsController'
332 response.mustcontain(text)
331 response.mustcontain(text)
333
332
334 # test DB
333 # test DB
335 assert PullRequest.get(pr_id).status == PullRequest.STATUS_CLOSED
334 assert db.PullRequest.get(pr_id).status == db.PullRequest.STATUS_CLOSED
336
335
337 def test_delete_pr(self):
336 def test_delete_pr(self):
338 self.log_user()
337 self.log_user()
@@ -351,7 +350,7 b' class TestPullrequestsCommentsController'
351 repo_name=base.HG_REPO, pull_request_id=pr_id, extra=''), status=404)
350 repo_name=base.HG_REPO, pull_request_id=pr_id, extra=''), status=404)
352
351
353 # test DB
352 # test DB
354 assert PullRequest.get(pr_id) is None
353 assert db.PullRequest.get(pr_id) is None
355
354
356 def test_delete_closed_pr(self):
355 def test_delete_closed_pr(self):
357 self.log_user()
356 self.log_user()
@@ -374,4 +373,4 b' class TestPullrequestsCommentsController'
374 params=params, extra_environ={'HTTP_X_PARTIAL_XHR': '1'}, status=403)
373 params=params, extra_environ={'HTTP_X_PARTIAL_XHR': '1'}, status=403)
375
374
376 # verify that PR still exists, in closed state
375 # verify that PR still exists, in closed state
377 assert PullRequest.get(pr_id).status == PullRequest.STATUS_CLOSED
376 assert db.PullRequest.get(pr_id).status == db.PullRequest.STATUS_CLOSED
@@ -3,8 +3,7 b' import json'
3 import mimetypes
3 import mimetypes
4 import posixpath
4 import posixpath
5
5
6 from kallithea.model import meta
6 from kallithea.model import db, meta
7 from kallithea.model.db import Repository
8 from kallithea.tests import base
7 from kallithea.tests import base
9 from kallithea.tests.fixture import Fixture
8 from kallithea.tests.fixture import Fixture
10
9
@@ -22,7 +21,7 b' GIT_NODE_HISTORY = fixture.load_resource'
22
21
23
22
24 def _set_downloads(repo_name, set_to):
23 def _set_downloads(repo_name, set_to):
25 repo = Repository.get_by_repo_name(repo_name)
24 repo = db.Repository.get_by_repo_name(repo_name)
26 repo.enable_downloads = set_to
25 repo.enable_downloads = set_to
27 meta.Session().commit()
26 meta.Session().commit()
28
27
@@ -2,8 +2,7 b''
2
2
3 import urllib.parse
3 import urllib.parse
4
4
5 from kallithea.model import meta
5 from kallithea.model import db, meta
6 from kallithea.model.db import Repository, User
7 from kallithea.model.repo import RepoModel
6 from kallithea.model.repo import RepoModel
8 from kallithea.model.user import UserModel
7 from kallithea.model.user import UserModel
9 from kallithea.tests import base
8 from kallithea.tests import base
@@ -45,7 +44,7 b' class _BaseTestCase(base.TestController)'
45 self.log_user(base.TEST_USER_REGULAR_LOGIN, base.TEST_USER_REGULAR_PASS)['user_id']
44 self.log_user(base.TEST_USER_REGULAR_LOGIN, base.TEST_USER_REGULAR_PASS)['user_id']
46 try:
45 try:
47 user_model = UserModel()
46 user_model = UserModel()
48 usr = User.get_default_user()
47 usr = db.User.get_default_user()
49 user_model.revoke_perm(usr, 'hg.fork.repository')
48 user_model.revoke_perm(usr, 'hg.fork.repository')
50 user_model.grant_perm(usr, 'hg.fork.none')
49 user_model.grant_perm(usr, 'hg.fork.none')
51 meta.Session().commit()
50 meta.Session().commit()
@@ -54,7 +53,7 b' class _BaseTestCase(base.TestController)'
54 self.app.post(base.url(controller='forks', action='fork_create',
53 self.app.post(base.url(controller='forks', action='fork_create',
55 repo_name=repo_name), {'_session_csrf_secret_token': self.session_csrf_secret_token()}, status=403)
54 repo_name=repo_name), {'_session_csrf_secret_token': self.session_csrf_secret_token()}, status=403)
56 finally:
55 finally:
57 usr = User.get_default_user()
56 usr = db.User.get_default_user()
58 user_model.revoke_perm(usr, 'hg.fork.none')
57 user_model.revoke_perm(usr, 'hg.fork.none')
59 user_model.grant_perm(usr, 'hg.fork.repository')
58 user_model.grant_perm(usr, 'hg.fork.repository')
60 meta.Session().commit()
59 meta.Session().commit()
@@ -66,7 +65,7 b' class _BaseTestCase(base.TestController)'
66 fork_name = self.REPO_FORK
65 fork_name = self.REPO_FORK
67 description = 'fork of vcs test'
66 description = 'fork of vcs test'
68 repo_name = self.REPO
67 repo_name = self.REPO
69 org_repo = Repository.get_by_repo_name(repo_name)
68 org_repo = db.Repository.get_by_repo_name(repo_name)
70 creation_args = {
69 creation_args = {
71 'repo_name': fork_name,
70 'repo_name': fork_name,
72 'repo_group': '-1',
71 'repo_group': '-1',
@@ -99,7 +98,7 b' class _BaseTestCase(base.TestController)'
99 fork_name_full = 'vc/%s' % fork_name
98 fork_name_full = 'vc/%s' % fork_name
100 description = 'fork of vcs test'
99 description = 'fork of vcs test'
101 repo_name = self.REPO
100 repo_name = self.REPO
102 org_repo = Repository.get_by_repo_name(repo_name)
101 org_repo = db.Repository.get_by_repo_name(repo_name)
103 creation_args = {
102 creation_args = {
104 'repo_name': fork_name,
103 'repo_name': fork_name,
105 'repo_group': group_id,
104 'repo_group': group_id,
@@ -111,7 +110,7 b' class _BaseTestCase(base.TestController)'
111 '_session_csrf_secret_token': self.session_csrf_secret_token()}
110 '_session_csrf_secret_token': self.session_csrf_secret_token()}
112 self.app.post(base.url(controller='forks', action='fork_create',
111 self.app.post(base.url(controller='forks', action='fork_create',
113 repo_name=repo_name), creation_args)
112 repo_name=repo_name), creation_args)
114 repo = Repository.get_by_repo_name(fork_name_full)
113 repo = db.Repository.get_by_repo_name(fork_name_full)
115 assert repo.fork.repo_name == self.REPO
114 assert repo.fork.repo_name == self.REPO
116
115
117 ## run the check page that triggers the flash message
116 ## run the check page that triggers the flash message
@@ -122,8 +121,8 b' class _BaseTestCase(base.TestController)'
122 % (repo_name, fork_name_full, fork_name_full))
121 % (repo_name, fork_name_full, fork_name_full))
123
122
124 # test if the fork was created in the database
123 # test if the fork was created in the database
125 fork_repo = meta.Session().query(Repository) \
124 fork_repo = meta.Session().query(db.Repository) \
126 .filter(Repository.repo_name == fork_name_full).one()
125 .filter(db.Repository.repo_name == fork_name_full).one()
127
126
128 assert fork_repo.repo_name == fork_name_full
127 assert fork_repo.repo_name == fork_name_full
129 assert fork_repo.fork.repo_name == repo_name
128 assert fork_repo.fork.repo_name == repo_name
@@ -142,7 +141,7 b' class _BaseTestCase(base.TestController)'
142
141
143 # create a fork
142 # create a fork
144 repo_name = self.REPO
143 repo_name = self.REPO
145 org_repo = Repository.get_by_repo_name(repo_name)
144 org_repo = db.Repository.get_by_repo_name(repo_name)
146 fork_name = self.REPO_FORK + '-rødgrød'
145 fork_name = self.REPO_FORK + '-rødgrød'
147 creation_args = {
146 creation_args = {
148 'repo_name': fork_name,
147 'repo_name': fork_name,
@@ -160,7 +159,7 b' class _BaseTestCase(base.TestController)'
160 response.mustcontain(
159 response.mustcontain(
161 """<a href="/%s">%s</a>""" % (urllib.parse.quote(fork_name), fork_name)
160 """<a href="/%s">%s</a>""" % (urllib.parse.quote(fork_name), fork_name)
162 )
161 )
163 fork_repo = Repository.get_by_repo_name(fork_name)
162 fork_repo = db.Repository.get_by_repo_name(fork_name)
164 assert fork_repo
163 assert fork_repo
165
164
166 # fork the fork
165 # fork the fork
@@ -193,7 +192,7 b' class _BaseTestCase(base.TestController)'
193 fork_name = self.REPO_FORK
192 fork_name = self.REPO_FORK
194 description = 'fork of vcs test'
193 description = 'fork of vcs test'
195 repo_name = self.REPO
194 repo_name = self.REPO
196 org_repo = Repository.get_by_repo_name(repo_name)
195 org_repo = db.Repository.get_by_repo_name(repo_name)
197 creation_args = {
196 creation_args = {
198 'repo_name': fork_name,
197 'repo_name': fork_name,
199 'repo_group': '-1',
198 'repo_group': '-1',
@@ -205,7 +204,7 b' class _BaseTestCase(base.TestController)'
205 '_session_csrf_secret_token': self.session_csrf_secret_token()}
204 '_session_csrf_secret_token': self.session_csrf_secret_token()}
206 self.app.post(base.url(controller='forks', action='fork_create',
205 self.app.post(base.url(controller='forks', action='fork_create',
207 repo_name=repo_name), creation_args)
206 repo_name=repo_name), creation_args)
208 repo = Repository.get_by_repo_name(self.REPO_FORK)
207 repo = db.Repository.get_by_repo_name(self.REPO_FORK)
209 assert repo.fork.repo_name == self.REPO
208 assert repo.fork.repo_name == self.REPO
210
209
211 ## run the check page that triggers the flash message
210 ## run the check page that triggers the flash message
@@ -216,8 +215,8 b' class _BaseTestCase(base.TestController)'
216 % (repo_name, fork_name, fork_name))
215 % (repo_name, fork_name, fork_name))
217
216
218 # test if the fork was created in the database
217 # test if the fork was created in the database
219 fork_repo = meta.Session().query(Repository) \
218 fork_repo = meta.Session().query(db.Repository) \
220 .filter(Repository.repo_name == fork_name).one()
219 .filter(db.Repository.repo_name == fork_name).one()
221
220
222 assert fork_repo.repo_name == fork_name
221 assert fork_repo.repo_name == fork_name
223 assert fork_repo.fork.repo_name == repo_name
222 assert fork_repo.fork.repo_name == repo_name
@@ -230,9 +229,9 b' class _BaseTestCase(base.TestController)'
230
229
231 usr = self.log_user(self.username, self.password)['user_id']
230 usr = self.log_user(self.username, self.password)['user_id']
232
231
233 forks = Repository.query() \
232 forks = db.Repository.query() \
234 .filter(Repository.repo_type == self.REPO_TYPE) \
233 .filter(db.Repository.repo_type == self.REPO_TYPE) \
235 .filter(Repository.fork_id != None).all()
234 .filter(db.Repository.fork_id != None).all()
236 assert 1 == len(forks)
235 assert 1 == len(forks)
237
236
238 # set read permissions for this
237 # set read permissions for this
@@ -247,7 +246,7 b' class _BaseTestCase(base.TestController)'
247 response.mustcontain('<div>fork of vcs test</div>')
246 response.mustcontain('<div>fork of vcs test</div>')
248
247
249 # remove permissions
248 # remove permissions
250 default_user = User.get_default_user()
249 default_user = db.User.get_default_user()
251 try:
250 try:
252 RepoModel().grant_user_permission(repo=forks[0],
251 RepoModel().grant_user_permission(repo=forks[0],
253 user=usr, perm='repository.none')
252 user=usr, perm='repository.none')
@@ -13,12 +13,12 b' class TestJournalController(base.TestCon'
13
13
14 def test_stop_following_repository(self):
14 def test_stop_following_repository(self):
15 session = self.log_user()
15 session = self.log_user()
16 # usr = Session().query(User).filter(User.username == TEST_USER_ADMIN_LOGIN).one()
16 # usr = Session().query(User).filter(db.User.username == TEST_USER_ADMIN_LOGIN).one()
17 # repo = Session().query(Repository).filter(Repository.repo_name == HG_REPO).one()
17 # repo = Session().query(db.Repository).filter(db.Repository.repo_name == HG_REPO).one()
18 #
18 #
19 # followings = Session().query(UserFollowing) \
19 # followings = Session().query(db.UserFollowing) \
20 # .filter(UserFollowing.user == usr) \
20 # .filter(db.UserFollowing.user == usr) \
21 # .filter(UserFollowing.follows_repository == repo).all()
21 # .filter(db.UserFollowing.follows_repository == repo).all()
22 #
22 #
23 # assert len(followings) == 1, 'Not following any repository'
23 # assert len(followings) == 1, 'Not following any repository'
24 #
24 #
@@ -10,9 +10,8 b' import kallithea.lib.celerylib.tasks'
10 from kallithea.lib import helpers as h
10 from kallithea.lib import helpers as h
11 from kallithea.lib.auth import check_password
11 from kallithea.lib.auth import check_password
12 from kallithea.lib.utils2 import generate_api_key
12 from kallithea.lib.utils2 import generate_api_key
13 from kallithea.model import meta, validators
13 from kallithea.model import db, meta, validators
14 from kallithea.model.api_key import ApiKeyModel
14 from kallithea.model.api_key import ApiKeyModel
15 from kallithea.model.db import User
16 from kallithea.model.user import UserModel
15 from kallithea.model.user import UserModel
17 from kallithea.tests import base
16 from kallithea.tests import base
18 from kallithea.tests.fixture import Fixture
17 from kallithea.tests.fixture import Fixture
@@ -361,7 +360,7 b' class TestLoginController(base.TestContr'
361 assert response.status == '302 Found'
360 assert response.status == '302 Found'
362 self.checkSessionFlash(response, 'You have successfully registered with Kallithea')
361 self.checkSessionFlash(response, 'You have successfully registered with Kallithea')
363
362
364 ret = meta.Session().query(User).filter(User.username == 'test_regular4').one()
363 ret = meta.Session().query(db.User).filter(db.User.username == 'test_regular4').one()
365 assert ret.username == username
364 assert ret.username == username
366 assert check_password(password, ret.password) == True
365 assert check_password(password, ret.password) == True
367 assert ret.email == email
366 assert ret.email == email
@@ -395,7 +394,7 b' class TestLoginController(base.TestContr'
395 lastname = 'reset'
394 lastname = 'reset'
396 timestamp = int(time.time())
395 timestamp = int(time.time())
397
396
398 new = User()
397 new = db.User()
399 new.username = username
398 new.username = username
400 new.password = password
399 new.password = password
401 new.email = email
400 new.email = email
@@ -406,7 +405,7 b' class TestLoginController(base.TestContr'
406 meta.Session().commit()
405 meta.Session().commit()
407
406
408 token = UserModel().get_reset_password_token(
407 token = UserModel().get_reset_password_token(
409 User.get_by_username(username), timestamp, self.session_csrf_secret_token())
408 db.User.get_by_username(username), timestamp, self.session_csrf_secret_token())
410
409
411 collected = []
410 collected = []
412 def mock_send_email(recipients, subject, body='', html_body='', headers=None, from_name=None):
411 def mock_send_email(recipients, subject, body='', html_body='', headers=None, from_name=None):
@@ -495,7 +494,7 b' class TestLoginController(base.TestContr'
495 headers = {}
494 headers = {}
496 else:
495 else:
497 if api_key is True:
496 if api_key is True:
498 api_key = User.get_first_admin().api_key
497 api_key = db.User.get_first_admin().api_key
499 params = {'api_key': api_key}
498 params = {'api_key': api_key}
500 headers = {'Authorization': 'Bearer ' + str(api_key)}
499 headers = {'Authorization': 'Bearer ' + str(api_key)}
501
500
@@ -3,8 +3,7 b''
3 from tg.util.webtest import test_context
3 from tg.util.webtest import test_context
4
4
5 from kallithea.lib import helpers as h
5 from kallithea.lib import helpers as h
6 from kallithea.model import meta
6 from kallithea.model import db, meta
7 from kallithea.model.db import Repository, User, UserApiKeys, UserFollowing, UserSshKeys
8 from kallithea.model.user import UserModel
7 from kallithea.model.user import UserModel
9 from kallithea.tests import base
8 from kallithea.tests import base
10 from kallithea.tests.fixture import Fixture
9 from kallithea.tests.fixture import Fixture
@@ -18,7 +17,7 b' class TestMyAccountController(base.TestC'
18
17
19 @classmethod
18 @classmethod
20 def teardown_class(cls):
19 def teardown_class(cls):
21 if User.get_by_username(cls.test_user_1):
20 if db.User.get_by_username(cls.test_user_1):
22 UserModel().delete(cls.test_user_1)
21 UserModel().delete(cls.test_user_1)
23 meta.Session().commit()
22 meta.Session().commit()
24
23
@@ -31,8 +30,8 b' class TestMyAccountController(base.TestC'
31 def test_my_account_my_repos(self):
30 def test_my_account_my_repos(self):
32 self.log_user()
31 self.log_user()
33 response = self.app.get(base.url('my_account_repos'))
32 response = self.app.get(base.url('my_account_repos'))
34 cnt = Repository.query().filter(Repository.owner ==
33 cnt = db.Repository.query().filter(db.Repository.owner ==
35 User.get_by_username(base.TEST_USER_ADMIN_LOGIN)).count()
34 db.User.get_by_username(base.TEST_USER_ADMIN_LOGIN)).count()
36 response.mustcontain('"raw_name": "%s"' % base.HG_REPO)
35 response.mustcontain('"raw_name": "%s"' % base.HG_REPO)
37 response.mustcontain('"just_name": "%s"' % base.GIT_REPO)
36 response.mustcontain('"just_name": "%s"' % base.GIT_REPO)
38
37
@@ -40,8 +39,8 b' class TestMyAccountController(base.TestC'
40 self.log_user()
39 self.log_user()
41 response = self.app.get(base.url('my_account_watched'))
40 response = self.app.get(base.url('my_account_watched'))
42
41
43 cnt = UserFollowing.query().filter(UserFollowing.user ==
42 cnt = db.UserFollowing.query().filter(db.UserFollowing.user ==
44 User.get_by_username(base.TEST_USER_ADMIN_LOGIN)).count()
43 db.User.get_by_username(base.TEST_USER_ADMIN_LOGIN)).count()
45 response.mustcontain('"raw_name": "%s"' % base.HG_REPO)
44 response.mustcontain('"raw_name": "%s"' % base.HG_REPO)
46 response.mustcontain('"just_name": "%s"' % base.GIT_REPO)
45 response.mustcontain('"just_name": "%s"' % base.GIT_REPO)
47
46
@@ -76,10 +75,9 b' class TestMyAccountController(base.TestC'
76
75
77 response = self.app.get(base.url('my_account_emails'))
76 response = self.app.get(base.url('my_account_emails'))
78
77
79 from kallithea.model.db import UserEmailMap
78 email_id = db.UserEmailMap.query() \
80 email_id = UserEmailMap.query() \
79 .filter(db.UserEmailMap.user == db.User.get_by_username(base.TEST_USER_ADMIN_LOGIN)) \
81 .filter(UserEmailMap.user == User.get_by_username(base.TEST_USER_ADMIN_LOGIN)) \
80 .filter(db.UserEmailMap.email == 'barz@example.com').one().email_id
82 .filter(UserEmailMap.email == 'barz@example.com').one().email_id
83
81
84 response.mustcontain('barz@example.com')
82 response.mustcontain('barz@example.com')
85 response.mustcontain('<input id="del_email_id" name="del_email_id" type="hidden" value="%s" />' % email_id)
83 response.mustcontain('<input id="del_email_id" name="del_email_id" type="hidden" value="%s" />' % email_id)
@@ -128,7 +126,7 b' class TestMyAccountController(base.TestC'
128 self.checkSessionFlash(response,
126 self.checkSessionFlash(response,
129 'Your account was updated successfully')
127 'Your account was updated successfully')
130
128
131 updated_user = User.get_by_username(self.test_user_1)
129 updated_user = db.User.get_by_username(self.test_user_1)
132 updated_params = updated_user.get_api_data(True)
130 updated_params = updated_user.get_api_data(True)
133 updated_params.update({'password_confirmation': ''})
131 updated_params.update({'password_confirmation': ''})
134 updated_params.update({'new_password': ''})
132 updated_params.update({'new_password': ''})
@@ -193,7 +191,7 b' class TestMyAccountController(base.TestC'
193
191
194 def test_my_account_api_keys(self):
192 def test_my_account_api_keys(self):
195 usr = self.log_user(base.TEST_USER_REGULAR2_LOGIN, base.TEST_USER_REGULAR2_PASS)
193 usr = self.log_user(base.TEST_USER_REGULAR2_LOGIN, base.TEST_USER_REGULAR2_PASS)
196 user = User.get(usr['user_id'])
194 user = db.User.get(usr['user_id'])
197 response = self.app.get(base.url('my_account_api_keys'))
195 response = self.app.get(base.url('my_account_api_keys'))
198 response.mustcontain(user.api_key)
196 response.mustcontain(user.api_key)
199 response.mustcontain('Expires: Never')
197 response.mustcontain('Expires: Never')
@@ -205,41 +203,41 b' class TestMyAccountController(base.TestC'
205 ])
203 ])
206 def test_my_account_add_api_keys(self, desc, lifetime):
204 def test_my_account_add_api_keys(self, desc, lifetime):
207 usr = self.log_user(base.TEST_USER_REGULAR2_LOGIN, base.TEST_USER_REGULAR2_PASS)
205 usr = self.log_user(base.TEST_USER_REGULAR2_LOGIN, base.TEST_USER_REGULAR2_PASS)
208 user = User.get(usr['user_id'])
206 user = db.User.get(usr['user_id'])
209 response = self.app.post(base.url('my_account_api_keys'),
207 response = self.app.post(base.url('my_account_api_keys'),
210 {'description': desc, 'lifetime': lifetime, '_session_csrf_secret_token': self.session_csrf_secret_token()})
208 {'description': desc, 'lifetime': lifetime, '_session_csrf_secret_token': self.session_csrf_secret_token()})
211 self.checkSessionFlash(response, 'API key successfully created')
209 self.checkSessionFlash(response, 'API key successfully created')
212 try:
210 try:
213 response = response.follow()
211 response = response.follow()
214 user = User.get(usr['user_id'])
212 user = db.User.get(usr['user_id'])
215 for api_key in user.api_keys:
213 for api_key in user.api_keys:
216 response.mustcontain(api_key)
214 response.mustcontain(api_key)
217 finally:
215 finally:
218 for api_key in UserApiKeys.query().all():
216 for api_key in db.UserApiKeys.query().all():
219 meta.Session().delete(api_key)
217 meta.Session().delete(api_key)
220 meta.Session().commit()
218 meta.Session().commit()
221
219
222 def test_my_account_remove_api_key(self):
220 def test_my_account_remove_api_key(self):
223 usr = self.log_user(base.TEST_USER_REGULAR2_LOGIN, base.TEST_USER_REGULAR2_PASS)
221 usr = self.log_user(base.TEST_USER_REGULAR2_LOGIN, base.TEST_USER_REGULAR2_PASS)
224 user = User.get(usr['user_id'])
222 user = db.User.get(usr['user_id'])
225 response = self.app.post(base.url('my_account_api_keys'),
223 response = self.app.post(base.url('my_account_api_keys'),
226 {'description': 'desc', 'lifetime': -1, '_session_csrf_secret_token': self.session_csrf_secret_token()})
224 {'description': 'desc', 'lifetime': -1, '_session_csrf_secret_token': self.session_csrf_secret_token()})
227 self.checkSessionFlash(response, 'API key successfully created')
225 self.checkSessionFlash(response, 'API key successfully created')
228 response = response.follow()
226 response = response.follow()
229
227
230 # now delete our key
228 # now delete our key
231 keys = UserApiKeys.query().all()
229 keys = db.UserApiKeys.query().all()
232 assert 1 == len(keys)
230 assert 1 == len(keys)
233
231
234 response = self.app.post(base.url('my_account_api_keys_delete'),
232 response = self.app.post(base.url('my_account_api_keys_delete'),
235 {'del_api_key': keys[0].api_key, '_session_csrf_secret_token': self.session_csrf_secret_token()})
233 {'del_api_key': keys[0].api_key, '_session_csrf_secret_token': self.session_csrf_secret_token()})
236 self.checkSessionFlash(response, 'API key successfully deleted')
234 self.checkSessionFlash(response, 'API key successfully deleted')
237 keys = UserApiKeys.query().all()
235 keys = db.UserApiKeys.query().all()
238 assert 0 == len(keys)
236 assert 0 == len(keys)
239
237
240 def test_my_account_reset_main_api_key(self):
238 def test_my_account_reset_main_api_key(self):
241 usr = self.log_user(base.TEST_USER_REGULAR2_LOGIN, base.TEST_USER_REGULAR2_PASS)
239 usr = self.log_user(base.TEST_USER_REGULAR2_LOGIN, base.TEST_USER_REGULAR2_PASS)
242 user = User.get(usr['user_id'])
240 user = db.User.get(usr['user_id'])
243 api_key = user.api_key
241 api_key = user.api_key
244 response = self.app.get(base.url('my_account_api_keys'))
242 response = self.app.get(base.url('my_account_api_keys'))
245 response.mustcontain(api_key)
243 response.mustcontain(api_key)
@@ -266,7 +264,7 b' class TestMyAccountController(base.TestC'
266 response = response.follow()
264 response = response.follow()
267 response.mustcontain(fingerprint)
265 response.mustcontain(fingerprint)
268 user_id = response.session['authuser']['user_id']
266 user_id = response.session['authuser']['user_id']
269 ssh_key = UserSshKeys.query().filter(UserSshKeys.user_id == user_id).one()
267 ssh_key = db.UserSshKeys.query().filter(db.UserSshKeys.user_id == user_id).one()
270 assert ssh_key.fingerprint == fingerprint
268 assert ssh_key.fingerprint == fingerprint
271 assert ssh_key.description == description
269 assert ssh_key.description == description
272 meta.Session().delete(ssh_key)
270 meta.Session().delete(ssh_key)
@@ -285,12 +283,12 b' class TestMyAccountController(base.TestC'
285 self.checkSessionFlash(response, 'SSH key %s successfully added' % fingerprint)
283 self.checkSessionFlash(response, 'SSH key %s successfully added' % fingerprint)
286 response.follow()
284 response.follow()
287 user_id = response.session['authuser']['user_id']
285 user_id = response.session['authuser']['user_id']
288 ssh_key = UserSshKeys.query().filter(UserSshKeys.user_id == user_id).one()
286 ssh_key = db.UserSshKeys.query().filter(db.UserSshKeys.user_id == user_id).one()
289 assert ssh_key.description == 'me@localhost'
287 assert ssh_key.description == 'me@localhost'
290
288
291 response = self.app.post(base.url('my_account_ssh_keys_delete'),
289 response = self.app.post(base.url('my_account_ssh_keys_delete'),
292 {'del_public_key_fingerprint': ssh_key.fingerprint,
290 {'del_public_key_fingerprint': ssh_key.fingerprint,
293 '_session_csrf_secret_token': self.session_csrf_secret_token()})
291 '_session_csrf_secret_token': self.session_csrf_secret_token()})
294 self.checkSessionFlash(response, 'SSH key successfully deleted')
292 self.checkSessionFlash(response, 'SSH key successfully deleted')
295 keys = UserSshKeys.query().all()
293 keys = db.UserSshKeys.query().all()
296 assert 0 == len(keys)
294 assert 0 == len(keys)
@@ -3,8 +3,7 b' import re'
3 import pytest
3 import pytest
4
4
5 from kallithea.controllers.pullrequests import PullrequestsController
5 from kallithea.controllers.pullrequests import PullrequestsController
6 from kallithea.model import meta
6 from kallithea.model import db, meta
7 from kallithea.model.db import PullRequest, User
8 from kallithea.tests import base
7 from kallithea.tests import base
9 from kallithea.tests.fixture import Fixture
8 from kallithea.tests.fixture import Fixture
10
9
@@ -91,9 +90,9 b' class TestPullrequestsController(base.Te'
91
90
92 def test_update_reviewers(self):
91 def test_update_reviewers(self):
93 self.log_user()
92 self.log_user()
94 regular_user = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
93 regular_user = db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
95 regular_user2 = User.get_by_username(base.TEST_USER_REGULAR2_LOGIN)
94 regular_user2 = db.User.get_by_username(base.TEST_USER_REGULAR2_LOGIN)
96 admin_user = User.get_by_username(base.TEST_USER_ADMIN_LOGIN)
95 admin_user = db.User.get_by_username(base.TEST_USER_ADMIN_LOGIN)
97
96
98 # create initial PR
97 # create initial PR
99 response = self.app.post(base.url(controller='pullrequests', action='create',
98 response = self.app.post(base.url(controller='pullrequests', action='create',
@@ -251,7 +250,7 b' class TestPullrequestsController(base.Te'
251 },
250 },
252 status=302)
251 status=302)
253 pr1_id = int(re.search(r'/pull-request/(\d+)/', response.location).group(1))
252 pr1_id = int(re.search(r'/pull-request/(\d+)/', response.location).group(1))
254 pr1 = PullRequest.get(pr1_id)
253 pr1 = db.PullRequest.get(pr1_id)
255
254
256 assert pr1.org_ref == 'branch:webvcs:9e6119747791ff886a5abe1193a730b6bf874e1c'
255 assert pr1.org_ref == 'branch:webvcs:9e6119747791ff886a5abe1193a730b6bf874e1c'
257 assert pr1.other_ref == 'branch:default:948da46b29c125838a717f6a8496eb409717078d'
256 assert pr1.other_ref == 'branch:default:948da46b29c125838a717f6a8496eb409717078d'
@@ -270,11 +269,11 b' class TestPullrequestsController(base.Te'
270 },
269 },
271 status=302)
270 status=302)
272 pr2_id = int(re.search(r'/pull-request/(\d+)/', response.location).group(1))
271 pr2_id = int(re.search(r'/pull-request/(\d+)/', response.location).group(1))
273 pr1 = PullRequest.get(pr1_id)
272 pr1 = db.PullRequest.get(pr1_id)
274 pr2 = PullRequest.get(pr2_id)
273 pr2 = db.PullRequest.get(pr2_id)
275
274
276 assert pr2_id != pr1_id
275 assert pr2_id != pr1_id
277 assert pr1.status == PullRequest.STATUS_CLOSED
276 assert pr1.status == db.PullRequest.STATUS_CLOSED
278 assert pr2.org_ref == 'branch:webvcs:5ec21f21aafe95220f1fc4843a4a57c378498b71'
277 assert pr2.org_ref == 'branch:webvcs:5ec21f21aafe95220f1fc4843a4a57c378498b71'
279 assert pr2.other_ref == pr1.other_ref
278 assert pr2.other_ref == pr1.other_ref
280
279
@@ -292,11 +291,11 b' class TestPullrequestsController(base.Te'
292 },
291 },
293 status=302)
292 status=302)
294 pr3_id = int(re.search(r'/pull-request/(\d+)/', response.location).group(1))
293 pr3_id = int(re.search(r'/pull-request/(\d+)/', response.location).group(1))
295 pr2 = PullRequest.get(pr2_id)
294 pr2 = db.PullRequest.get(pr2_id)
296 pr3 = PullRequest.get(pr3_id)
295 pr3 = db.PullRequest.get(pr3_id)
297
296
298 assert pr3_id != pr2_id
297 assert pr3_id != pr2_id
299 assert pr2.status == PullRequest.STATUS_CLOSED
298 assert pr2.status == db.PullRequest.STATUS_CLOSED
300 assert pr3.org_ref == 'branch:webvcs:fb95b340e0d03fa51f33c56c991c08077c99303e'
299 assert pr3.org_ref == 'branch:webvcs:fb95b340e0d03fa51f33c56c991c08077c99303e'
301 assert pr3.other_ref == 'branch:default:41d2568309a05f422cffb8008e599d385f8af439'
300 assert pr3.other_ref == 'branch:default:41d2568309a05f422cffb8008e599d385f8af439'
302
301
@@ -14,8 +14,7 b''
14
14
15 import pytest
15 import pytest
16
16
17 from kallithea.model import meta
17 from kallithea.model import db, meta
18 from kallithea.model.db import Repository
19 from kallithea.model.repo import RepoModel
18 from kallithea.model.repo import RepoModel
20 from kallithea.model.scm import ScmModel
19 from kallithea.model.scm import ScmModel
21 from kallithea.tests import base
20 from kallithea.tests import base
@@ -36,7 +35,7 b' class TestSummaryController(base.TestCon'
36
35
37 def test_index_hg(self, custom_settings):
36 def test_index_hg(self, custom_settings):
38 self.log_user()
37 self.log_user()
39 ID = Repository.get_by_repo_name(base.HG_REPO).repo_id
38 ID = db.Repository.get_by_repo_name(base.HG_REPO).repo_id
40 response = self.app.get(base.url(controller='summary',
39 response = self.app.get(base.url(controller='summary',
41 action='index',
40 action='index',
42 repo_name=base.HG_REPO))
41 repo_name=base.HG_REPO))
@@ -66,7 +65,7 b' class TestSummaryController(base.TestCon'
66
65
67 def test_index_git(self, custom_settings):
66 def test_index_git(self, custom_settings):
68 self.log_user()
67 self.log_user()
69 ID = Repository.get_by_repo_name(base.GIT_REPO).repo_id
68 ID = db.Repository.get_by_repo_name(base.GIT_REPO).repo_id
70 response = self.app.get(base.url(controller='summary',
69 response = self.app.get(base.url(controller='summary',
71 action='index',
70 action='index',
72 repo_name=base.GIT_REPO))
71 repo_name=base.GIT_REPO))
@@ -95,7 +94,7 b' class TestSummaryController(base.TestCon'
95
94
96 def test_index_by_id_hg(self):
95 def test_index_by_id_hg(self):
97 self.log_user()
96 self.log_user()
98 ID = Repository.get_by_repo_name(base.HG_REPO).repo_id
97 ID = db.Repository.get_by_repo_name(base.HG_REPO).repo_id
99 response = self.app.get(base.url(controller='summary',
98 response = self.app.get(base.url(controller='summary',
100 action='index',
99 action='index',
101 repo_name='_%s' % ID))
100 repo_name='_%s' % ID))
@@ -119,12 +118,12 b' class TestSummaryController(base.TestCon'
119 try:
118 try:
120 response.mustcontain("repo_1")
119 response.mustcontain("repo_1")
121 finally:
120 finally:
122 RepoModel().delete(Repository.get_by_repo_name('repo_1'))
121 RepoModel().delete(db.Repository.get_by_repo_name('repo_1'))
123 meta.Session().commit()
122 meta.Session().commit()
124
123
125 def test_index_by_id_git(self):
124 def test_index_by_id_git(self):
126 self.log_user()
125 self.log_user()
127 ID = Repository.get_by_repo_name(base.GIT_REPO).repo_id
126 ID = db.Repository.get_by_repo_name(base.GIT_REPO).repo_id
128 response = self.app.get(base.url(controller='summary',
127 response = self.app.get(base.url(controller='summary',
129 action='index',
128 action='index',
130 repo_name='_%s' % ID))
129 repo_name='_%s' % ID))
@@ -139,7 +138,7 b' class TestSummaryController(base.TestCon'
139 )
138 )
140
139
141 def _enable_stats(self, repo):
140 def _enable_stats(self, repo):
142 r = Repository.get_by_repo_name(repo)
141 r = db.Repository.get_by_repo_name(repo)
143 r.enable_statistics = True
142 r.enable_statistics = True
144 meta.Session().commit()
143 meta.Session().commit()
145
144
@@ -1,6 +1,5 b''
1 from kallithea.lib.auth import AuthUser
1 from kallithea.lib.auth import AuthUser
2 from kallithea.model import meta
2 from kallithea.model import db, meta
3 from kallithea.model.db import RepoGroup, Repository, User
4 from kallithea.model.repo import RepoModel
3 from kallithea.model.repo import RepoModel
5 from kallithea.model.repo_group import RepoGroupModel
4 from kallithea.model.repo_group import RepoGroupModel
6 from kallithea.model.user import UserModel
5 from kallithea.model.user import UserModel
@@ -12,14 +11,14 b' fixture = Fixture()'
12
11
13 def _destroy_project_tree(test_u1_id):
12 def _destroy_project_tree(test_u1_id):
14 meta.Session.remove()
13 meta.Session.remove()
15 repo_group = RepoGroup.get_by_group_name(group_name='g0')
14 repo_group = db.RepoGroup.get_by_group_name(group_name='g0')
16 for el in reversed(repo_group.recursive_groups_and_repos()):
15 for el in reversed(repo_group.recursive_groups_and_repos()):
17 if isinstance(el, Repository):
16 if isinstance(el, db.Repository):
18 RepoModel().delete(el)
17 RepoModel().delete(el)
19 elif isinstance(el, RepoGroup):
18 elif isinstance(el, db.RepoGroup):
20 RepoGroupModel().delete(el, force_delete=True)
19 RepoGroupModel().delete(el, force_delete=True)
21
20
22 u = User.get(test_u1_id)
21 u = db.User.get(test_u1_id)
23 meta.Session().delete(u)
22 meta.Session().delete(u)
24 meta.Session().commit()
23 meta.Session().commit()
25
24
@@ -70,7 +69,7 b' def _create_project_tree():'
70
69
71
70
72 def expected_count(group_name, objects=False):
71 def expected_count(group_name, objects=False):
73 repo_group = RepoGroup.get_by_group_name(group_name=group_name)
72 repo_group = db.RepoGroup.get_by_group_name(group_name=group_name)
74 objs = repo_group.recursive_groups_and_repos()
73 objs = repo_group.recursive_groups_and_repos()
75 if objects:
74 if objects:
76 return objs
75 return objs
@@ -1,8 +1,14 b''
1 from kallithea.model import db
1 from kallithea.model.changeset_status import ChangesetStatusModel
2 from kallithea.model.changeset_status import ChangesetStatusModel
2 from kallithea.model.db import ChangesetStatus as CS
3 from kallithea.tests import base
3 from kallithea.tests import base
4
4
5
5
6 STATUS_UNDER_REVIEW = db.ChangesetStatus.STATUS_UNDER_REVIEW
7 STATUS_APPROVED = db.ChangesetStatus.STATUS_APPROVED
8 STATUS_REJECTED = db.ChangesetStatus.STATUS_REJECTED
9 STATUS_NOT_REVIEWED = db.ChangesetStatus.STATUS_NOT_REVIEWED
10
11
6 class CSM(object): # ChangesetStatusMock
12 class CSM(object): # ChangesetStatusMock
7
13
8 def __init__(self, status):
14 def __init__(self, status):
@@ -15,27 +21,27 b' class TestChangesetStatusCalculation(bas'
15 self.m = ChangesetStatusModel()
21 self.m = ChangesetStatusModel()
16
22
17 @base.parametrize('name,expected_result,statuses', [
23 @base.parametrize('name,expected_result,statuses', [
18 ('empty list', CS.STATUS_UNDER_REVIEW, []),
24 ('empty list', STATUS_UNDER_REVIEW, []),
19 ('approve', CS.STATUS_APPROVED, [CSM(CS.STATUS_APPROVED)]),
25 ('approve', STATUS_APPROVED, [CSM(STATUS_APPROVED)]),
20 ('approve2', CS.STATUS_APPROVED, [CSM(CS.STATUS_APPROVED), CSM(CS.STATUS_APPROVED)]),
26 ('approve2', STATUS_APPROVED, [CSM(STATUS_APPROVED), CSM(STATUS_APPROVED)]),
21 ('approve_reject', CS.STATUS_REJECTED, [CSM(CS.STATUS_APPROVED), CSM(CS.STATUS_REJECTED)]),
27 ('approve_reject', STATUS_REJECTED, [CSM(STATUS_APPROVED), CSM(STATUS_REJECTED)]),
22 ('approve_underreview', CS.STATUS_UNDER_REVIEW, [CSM(CS.STATUS_APPROVED), CSM(CS.STATUS_UNDER_REVIEW)]),
28 ('approve_underreview', STATUS_UNDER_REVIEW, [CSM(STATUS_APPROVED), CSM(STATUS_UNDER_REVIEW)]),
23 ('approve_notreviewed', CS.STATUS_UNDER_REVIEW, [CSM(CS.STATUS_APPROVED), CSM(CS.STATUS_NOT_REVIEWED)]),
29 ('approve_notreviewed', STATUS_UNDER_REVIEW, [CSM(STATUS_APPROVED), CSM(STATUS_NOT_REVIEWED)]),
24 ('underreview', CS.STATUS_UNDER_REVIEW, [CSM(CS.STATUS_UNDER_REVIEW), CSM(CS.STATUS_UNDER_REVIEW)]),
30 ('underreview', STATUS_UNDER_REVIEW, [CSM(STATUS_UNDER_REVIEW), CSM(STATUS_UNDER_REVIEW)]),
25 ('reject', CS.STATUS_REJECTED, [CSM(CS.STATUS_REJECTED)]),
31 ('reject', STATUS_REJECTED, [CSM(STATUS_REJECTED)]),
26 ('reject_underreview', CS.STATUS_REJECTED, [CSM(CS.STATUS_REJECTED), CSM(CS.STATUS_UNDER_REVIEW)]),
32 ('reject_underreview', STATUS_REJECTED, [CSM(STATUS_REJECTED), CSM(STATUS_UNDER_REVIEW)]),
27 ('reject_notreviewed', CS.STATUS_REJECTED, [CSM(CS.STATUS_REJECTED), CSM(CS.STATUS_NOT_REVIEWED)]),
33 ('reject_notreviewed', STATUS_REJECTED, [CSM(STATUS_REJECTED), CSM(STATUS_NOT_REVIEWED)]),
28 ('notreviewed', CS.STATUS_UNDER_REVIEW, [CSM(CS.STATUS_NOT_REVIEWED)]),
34 ('notreviewed', STATUS_UNDER_REVIEW, [CSM(STATUS_NOT_REVIEWED)]),
29 ('approve_none', CS.STATUS_UNDER_REVIEW, [CSM(CS.STATUS_APPROVED), None]),
35 ('approve_none', STATUS_UNDER_REVIEW, [CSM(STATUS_APPROVED), None]),
30 ('approve2_none', CS.STATUS_UNDER_REVIEW, [CSM(CS.STATUS_APPROVED), CSM(CS.STATUS_APPROVED), None]),
36 ('approve2_none', STATUS_UNDER_REVIEW, [CSM(STATUS_APPROVED), CSM(STATUS_APPROVED), None]),
31 ('approve_reject_none', CS.STATUS_REJECTED, [CSM(CS.STATUS_APPROVED), CSM(CS.STATUS_REJECTED), None]),
37 ('approve_reject_none', STATUS_REJECTED, [CSM(STATUS_APPROVED), CSM(STATUS_REJECTED), None]),
32 ('approve_underreview_none', CS.STATUS_UNDER_REVIEW, [CSM(CS.STATUS_APPROVED), CSM(CS.STATUS_UNDER_REVIEW), None]),
38 ('approve_underreview_none', STATUS_UNDER_REVIEW, [CSM(STATUS_APPROVED), CSM(STATUS_UNDER_REVIEW), None]),
33 ('approve_notreviewed_none', CS.STATUS_UNDER_REVIEW, [CSM(CS.STATUS_APPROVED), CSM(CS.STATUS_NOT_REVIEWED), None]),
39 ('approve_notreviewed_none', STATUS_UNDER_REVIEW, [CSM(STATUS_APPROVED), CSM(STATUS_NOT_REVIEWED), None]),
34 ('underreview_none', CS.STATUS_UNDER_REVIEW, [CSM(CS.STATUS_UNDER_REVIEW), CSM(CS.STATUS_UNDER_REVIEW), None]),
40 ('underreview_none', STATUS_UNDER_REVIEW, [CSM(STATUS_UNDER_REVIEW), CSM(STATUS_UNDER_REVIEW), None]),
35 ('reject_none', CS.STATUS_REJECTED, [CSM(CS.STATUS_REJECTED), None]),
41 ('reject_none', STATUS_REJECTED, [CSM(STATUS_REJECTED), None]),
36 ('reject_underreview_none', CS.STATUS_REJECTED, [CSM(CS.STATUS_REJECTED), CSM(CS.STATUS_UNDER_REVIEW), None]),
42 ('reject_underreview_none', STATUS_REJECTED, [CSM(STATUS_REJECTED), CSM(STATUS_UNDER_REVIEW), None]),
37 ('reject_notreviewed_none', CS.STATUS_REJECTED, [CSM(CS.STATUS_REJECTED), CSM(CS.STATUS_NOT_REVIEWED), None]),
43 ('reject_notreviewed_none', STATUS_REJECTED, [CSM(STATUS_REJECTED), CSM(STATUS_NOT_REVIEWED), None]),
38 ('notreviewed_none', CS.STATUS_UNDER_REVIEW, [CSM(CS.STATUS_NOT_REVIEWED), None]),
44 ('notreviewed_none', STATUS_UNDER_REVIEW, [CSM(STATUS_NOT_REVIEWED), None]),
39 ])
45 ])
40 def test_result(self, name, expected_result, statuses):
46 def test_result(self, name, expected_result, statuses):
41 result = self.m._calculate_status(statuses)
47 result = self.m._calculate_status(statuses)
@@ -1,8 +1,8 b''
1 import pytest
1 import pytest
2 from tg.util.webtest import test_context
2 from tg.util.webtest import test_context
3
3
4 from kallithea.model import db
4 from kallithea.model.comment import ChangesetCommentsModel
5 from kallithea.model.comment import ChangesetCommentsModel
5 from kallithea.model.db import Repository
6 from kallithea.tests import base
6 from kallithea.tests import base
7
7
8
8
@@ -23,7 +23,7 b' class TestComments(base.TestController):'
23
23
24 def test_create_delete_general_comment(self):
24 def test_create_delete_general_comment(self):
25 with test_context(self.app):
25 with test_context(self.app):
26 repo_id = Repository.get_by_repo_name(base.HG_REPO).repo_id
26 repo_id = db.Repository.get_by_repo_name(base.HG_REPO).repo_id
27 revision = '9a7b4ff9e8b40bbda72fc75f162325b9baa45cda'
27 revision = '9a7b4ff9e8b40bbda72fc75f162325b9baa45cda'
28
28
29 self._check_comment_count(repo_id, revision,
29 self._check_comment_count(repo_id, revision,
@@ -47,7 +47,7 b' class TestComments(base.TestController):'
47
47
48 def test_create_delete_inline_comment(self):
48 def test_create_delete_inline_comment(self):
49 with test_context(self.app):
49 with test_context(self.app):
50 repo_id = Repository.get_by_repo_name(base.HG_REPO).repo_id
50 repo_id = db.Repository.get_by_repo_name(base.HG_REPO).repo_id
51 revision = '9a7b4ff9e8b40bbda72fc75f162325b9baa45cda'
51 revision = '9a7b4ff9e8b40bbda72fc75f162325b9baa45cda'
52
52
53 self._check_comment_count(repo_id, revision,
53 self._check_comment_count(repo_id, revision,
@@ -81,7 +81,7 b' class TestComments(base.TestController):'
81
81
82 def test_create_delete_multiple_inline_comments(self):
82 def test_create_delete_multiple_inline_comments(self):
83 with test_context(self.app):
83 with test_context(self.app):
84 repo_id = Repository.get_by_repo_name(base.HG_REPO).repo_id
84 repo_id = db.Repository.get_by_repo_name(base.HG_REPO).repo_id
85 revision = '9a7b4ff9e8b40bbda72fc75f162325b9baa45cda'
85 revision = '9a7b4ff9e8b40bbda72fc75f162325b9baa45cda'
86
86
87 self._check_comment_count(repo_id, revision,
87 self._check_comment_count(repo_id, revision,
@@ -161,7 +161,7 b' class TestComments(base.TestController):'
161
161
162 def test_selective_retrieval_of_inline_comments(self):
162 def test_selective_retrieval_of_inline_comments(self):
163 with test_context(self.app):
163 with test_context(self.app):
164 repo_id = Repository.get_by_repo_name(base.HG_REPO).repo_id
164 repo_id = db.Repository.get_by_repo_name(base.HG_REPO).repo_id
165 revision = '9a7b4ff9e8b40bbda72fc75f162325b9baa45cda'
165 revision = '9a7b4ff9e8b40bbda72fc75f162325b9baa45cda'
166
166
167 self._check_comment_count(repo_id, revision,
167 self._check_comment_count(repo_id, revision,
@@ -7,8 +7,7 b' from tg.util.webtest import test_context'
7 import kallithea.lib.celerylib
7 import kallithea.lib.celerylib
8 import kallithea.lib.celerylib.tasks
8 import kallithea.lib.celerylib.tasks
9 from kallithea.lib import helpers as h
9 from kallithea.lib import helpers as h
10 from kallithea.model import meta
10 from kallithea.model import db, meta
11 from kallithea.model.db import User
12 from kallithea.model.notification import EmailNotificationModel, NotificationModel
11 from kallithea.model.notification import EmailNotificationModel, NotificationModel
13 from kallithea.model.user import UserModel
12 from kallithea.model.user import UserModel
14 from kallithea.tests import base
13 from kallithea.tests import base
@@ -84,7 +83,7 b' class TestNotifications(base.TestControl'
84 pr_target_branch='trunk',
83 pr_target_branch='trunk',
85 pr_source_repo='https://dev.org/repo',
84 pr_source_repo='https://dev.org/repo',
86 pr_source_branch='devbranch',
85 pr_source_branch='devbranch',
87 pr_owner=User.get(self.u2),
86 pr_owner=db.User.get(self.u2),
88 pr_owner_username='u2'
87 pr_owner_username='u2'
89 )
88 )
90
89
@@ -103,8 +102,8 b' class TestNotifications(base.TestControl'
103 status_change=[None, 'Approved'],
102 status_change=[None, 'Approved'],
104 cs_target_repo='http://example.com/repo_target',
103 cs_target_repo='http://example.com/repo_target',
105 cs_url='http://changeset.com',
104 cs_url='http://changeset.com',
106 cs_author_username=User.get(self.u2).username,
105 cs_author_username=db.User.get(self.u2).username,
107 cs_author=User.get(self.u2))),
106 cs_author=db.User.get(self.u2))),
108 (NotificationModel.TYPE_MESSAGE,
107 (NotificationModel.TYPE_MESSAGE,
109 'This is the \'body\' of the "test" message\n - nothing interesting here except indentation.',
108 'This is the \'body\' of the "test" message\n - nothing interesting here except indentation.',
110 dict()),
109 dict()),
@@ -160,7 +159,7 b' class TestNotifications(base.TestControl'
160 "Password reset link",
159 "Password reset link",
161 EmailNotificationModel().get_email_tmpl(EmailNotificationModel.TYPE_PASSWORD_RESET, 'txt', **kwargs),
160 EmailNotificationModel().get_email_tmpl(EmailNotificationModel.TYPE_PASSWORD_RESET, 'txt', **kwargs),
162 EmailNotificationModel().get_email_tmpl(EmailNotificationModel.TYPE_PASSWORD_RESET, 'html', **kwargs),
161 EmailNotificationModel().get_email_tmpl(EmailNotificationModel.TYPE_PASSWORD_RESET, 'html', **kwargs),
163 from_name=User.get(self.u1).full_name_or_username)
162 from_name=db.User.get(self.u1).full_name_or_username)
164
163
165 out = '<!doctype html>\n<html lang="en">\n<head><title>Notifications</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>\n<body>\n%s\n</body>\n</html>\n' % \
164 out = '<!doctype html>\n<html lang="en">\n<head><title>Notifications</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>\n<body>\n%s\n</body>\n</html>\n' % \
166 re.sub(r'<(/?(?:!doctype|html|head|title|meta|body)\b[^>]*)>', r'<!--\1-->', ''.join(l))
165 re.sub(r'<(/?(?:!doctype|html|head|title|meta|body)\b[^>]*)>', r'<!--\1-->', ''.join(l))
@@ -1,7 +1,6 b''
1 import kallithea
1 import kallithea
2 from kallithea.lib.auth import AuthUser
2 from kallithea.lib.auth import AuthUser
3 from kallithea.model import meta
3 from kallithea.model import db, meta
4 from kallithea.model.db import Permission, User, UserGroupRepoGroupToPerm, UserToPerm
5 from kallithea.model.permission import PermissionModel
4 from kallithea.model.permission import PermissionModel
6 from kallithea.model.repo import RepoModel
5 from kallithea.model.repo import RepoModel
7 from kallithea.model.repo_group import RepoGroupModel
6 from kallithea.model.repo_group import RepoGroupModel
@@ -19,7 +18,7 b' class TestPermissions(base.TestControlle'
19 @classmethod
18 @classmethod
20 def setup_class(cls):
19 def setup_class(cls):
21 # recreate default user to get a clean start
20 # recreate default user to get a clean start
22 PermissionModel().create_default_permissions(user=User.DEFAULT_USER_NAME,
21 PermissionModel().create_default_permissions(user=db.User.DEFAULT_USER_NAME,
23 force=True)
22 force=True)
24 meta.Session().commit()
23 meta.Session().commit()
25
24
@@ -36,7 +35,7 b' class TestPermissions(base.TestControlle'
36 username='u3', password='qweqwe',
35 username='u3', password='qweqwe',
37 email='u3@example.com', firstname='u3', lastname='u3'
36 email='u3@example.com', firstname='u3', lastname='u3'
38 )
37 )
39 self.anon = User.get_default_user()
38 self.anon = db.User.get_default_user()
40 self.a1 = UserModel().create_or_update(
39 self.a1 = UserModel().create_or_update(
41 username='a1', password='qweqwe',
40 username='a1', password='qweqwe',
42 email='a1@example.com', firstname='a1', lastname='a1', admin=True
41 email='a1@example.com', firstname='a1', lastname='a1', admin=True
@@ -96,7 +95,7 b' class TestPermissions(base.TestControlle'
96 assert u1_auth.repository_permissions[base.HG_REPO] == 'repository.read'
95 assert u1_auth.repository_permissions[base.HG_REPO] == 'repository.read'
97 assert u1_auth.repository_group_permissions.get('test1') == 'group.read'
96 assert u1_auth.repository_group_permissions.get('test1') == 'group.read'
98 assert u1_auth.repository_group_permissions.get('test2') == 'group.read'
97 assert u1_auth.repository_group_permissions.get('test2') == 'group.read'
99 assert u1_auth.global_permissions == set(Permission.DEFAULT_USER_PERMISSIONS)
98 assert u1_auth.global_permissions == set(db.Permission.DEFAULT_USER_PERMISSIONS)
100
99
101 def test_default_admin_group_perms(self):
100 def test_default_admin_group_perms(self):
102 self.g1 = fixture.create_repo_group('test1', skip_if_exists=True)
101 self.g1 = fixture.create_repo_group('test1', skip_if_exists=True)
@@ -262,9 +261,9 b' class TestPermissions(base.TestControlle'
262 perm='group.read')
261 perm='group.read')
263 meta.Session().commit()
262 meta.Session().commit()
264 # check if the
263 # check if the
265 obj = meta.Session().query(UserGroupRepoGroupToPerm) \
264 obj = meta.Session().query(db.UserGroupRepoGroupToPerm) \
266 .filter(UserGroupRepoGroupToPerm.group == self.g1) \
265 .filter(db.UserGroupRepoGroupToPerm.group == self.g1) \
267 .filter(UserGroupRepoGroupToPerm.users_group == self.ug1) \
266 .filter(db.UserGroupRepoGroupToPerm.users_group == self.ug1) \
268 .scalar()
267 .scalar()
269 assert obj.permission.permission_name == 'group.read'
268 assert obj.permission.permission_name == 'group.read'
270
269
@@ -592,10 +591,10 b' class TestPermissions(base.TestControlle'
592 assert u1_auth.repository_permissions['myownrepo'] == 'repository.admin'
591 assert u1_auth.repository_permissions['myownrepo'] == 'repository.admin'
593
592
594 def _test_def_perm_equal(self, user, change_factor=0):
593 def _test_def_perm_equal(self, user, change_factor=0):
595 perms = UserToPerm.query() \
594 perms = db.UserToPerm.query() \
596 .filter(UserToPerm.user == user) \
595 .filter(db.UserToPerm.user == user) \
597 .all()
596 .all()
598 assert len(perms) == len(Permission.DEFAULT_USER_PERMISSIONS,)+change_factor, perms
597 assert len(perms) == len(db.Permission.DEFAULT_USER_PERMISSIONS,)+change_factor, perms
599
598
600 def test_set_default_permissions(self):
599 def test_set_default_permissions(self):
601 PermissionModel().create_default_permissions(user=self.u1)
600 PermissionModel().create_default_permissions(user=self.u1)
@@ -605,8 +604,8 b' class TestPermissions(base.TestControlle'
605 PermissionModel().create_default_permissions(user=self.u1)
604 PermissionModel().create_default_permissions(user=self.u1)
606 self._test_def_perm_equal(user=self.u1)
605 self._test_def_perm_equal(user=self.u1)
607 # now we delete one, it should be re-created after another call
606 # now we delete one, it should be re-created after another call
608 perms = UserToPerm.query() \
607 perms = db.UserToPerm.query() \
609 .filter(UserToPerm.user == self.u1) \
608 .filter(db.UserToPerm.user == self.u1) \
610 .all()
609 .all()
611 meta.Session().delete(perms[0])
610 meta.Session().delete(perms[0])
612 meta.Session().commit()
611 meta.Session().commit()
@@ -629,15 +628,15 b' class TestPermissions(base.TestControlle'
629 PermissionModel().create_default_permissions(user=self.u1)
628 PermissionModel().create_default_permissions(user=self.u1)
630 self._test_def_perm_equal(user=self.u1)
629 self._test_def_perm_equal(user=self.u1)
631
630
632 old = Permission.get_by_key(perm)
631 old = db.Permission.get_by_key(perm)
633 new = Permission.get_by_key(modify_to)
632 new = db.Permission.get_by_key(modify_to)
634 assert old is not None
633 assert old is not None
635 assert new is not None
634 assert new is not None
636
635
637 # now modify permissions
636 # now modify permissions
638 p = UserToPerm.query() \
637 p = db.UserToPerm.query() \
639 .filter(UserToPerm.user == self.u1) \
638 .filter(db.UserToPerm.user == self.u1) \
640 .filter(UserToPerm.permission == old) \
639 .filter(db.UserToPerm.permission == old) \
641 .one()
640 .one()
642 p.permission = new
641 p.permission = new
643 meta.Session().commit()
642 meta.Session().commit()
@@ -4,8 +4,7 b' import pytest'
4 from sqlalchemy.exc import IntegrityError
4 from sqlalchemy.exc import IntegrityError
5
5
6 import kallithea
6 import kallithea
7 from kallithea.model import meta
7 from kallithea.model import db, meta
8 from kallithea.model.db import RepoGroup
9 from kallithea.model.repo import RepoModel
8 from kallithea.model.repo import RepoModel
10 from kallithea.model.repo_group import RepoGroupModel
9 from kallithea.model.repo_group import RepoGroupModel
11 from kallithea.tests import base
10 from kallithea.tests import base
@@ -83,13 +82,13 b' class TestRepoGroups(base.TestController'
83 sg1 = fixture.create_repo_group('deleteme')
82 sg1 = fixture.create_repo_group('deleteme')
84 self.__delete_group(sg1.group_id)
83 self.__delete_group(sg1.group_id)
85
84
86 assert RepoGroup.get(sg1.group_id) is None
85 assert db.RepoGroup.get(sg1.group_id) is None
87 assert not self.__check_path('deteteme')
86 assert not self.__check_path('deteteme')
88
87
89 sg1 = fixture.create_repo_group('deleteme', parent_group_id=self.g1.group_id)
88 sg1 = fixture.create_repo_group('deleteme', parent_group_id=self.g1.group_id)
90 self.__delete_group(sg1.group_id)
89 self.__delete_group(sg1.group_id)
91
90
92 assert RepoGroup.get(sg1.group_id) is None
91 assert db.RepoGroup.get(sg1.group_id) is None
93 assert not self.__check_path('test1', 'deteteme')
92 assert not self.__check_path('test1', 'deteteme')
94
93
95 def test_rename_single_group(self):
94 def test_rename_single_group(self):
@@ -97,7 +96,7 b' class TestRepoGroups(base.TestController'
97
96
98 new_sg1 = _update_repo_group(sg1.group_id, 'after')
97 new_sg1 = _update_repo_group(sg1.group_id, 'after')
99 assert self.__check_path('after')
98 assert self.__check_path('after')
100 assert RepoGroup.get_by_group_name('initial') is None
99 assert db.RepoGroup.get_by_group_name('initial') is None
101
100
102 def test_update_group_parent(self):
101 def test_update_group_parent(self):
103
102
@@ -105,16 +104,16 b' class TestRepoGroups(base.TestController'
105
104
106 new_sg1 = _update_repo_group(sg1.group_id, 'after', parent_id=self.g1.group_id)
105 new_sg1 = _update_repo_group(sg1.group_id, 'after', parent_id=self.g1.group_id)
107 assert self.__check_path('test1', 'after')
106 assert self.__check_path('test1', 'after')
108 assert RepoGroup.get_by_group_name('test1/initial') is None
107 assert db.RepoGroup.get_by_group_name('test1/initial') is None
109
108
110 new_sg1 = _update_repo_group(sg1.group_id, 'after', parent_id=self.g3.group_id)
109 new_sg1 = _update_repo_group(sg1.group_id, 'after', parent_id=self.g3.group_id)
111 assert self.__check_path('test3', 'after')
110 assert self.__check_path('test3', 'after')
112 assert RepoGroup.get_by_group_name('test3/initial') == None
111 assert db.RepoGroup.get_by_group_name('test3/initial') == None
113
112
114 new_sg1 = _update_repo_group(sg1.group_id, 'hello')
113 new_sg1 = _update_repo_group(sg1.group_id, 'hello')
115 assert self.__check_path('hello')
114 assert self.__check_path('hello')
116
115
117 assert RepoGroup.get_by_group_name('hello') == new_sg1
116 assert db.RepoGroup.get_by_group_name('hello') == new_sg1
118
117
119 def test_subgrouping_with_repo(self):
118 def test_subgrouping_with_repo(self):
120
119
@@ -1,8 +1,7 b''
1 import pytest
1 import pytest
2
2
3 from kallithea.lib.exceptions import AttachedForksError
3 from kallithea.lib.exceptions import AttachedForksError
4 from kallithea.model import meta
4 from kallithea.model import db, meta
5 from kallithea.model.db import Repository
6 from kallithea.model.repo import RepoModel
5 from kallithea.model.repo import RepoModel
7 from kallithea.tests import base
6 from kallithea.tests import base
8 from kallithea.tests.fixture import Fixture
7 from kallithea.tests.fixture import Fixture
@@ -23,7 +22,7 b' class TestRepos(base.TestController):'
23 RepoModel().delete(repo=repo)
22 RepoModel().delete(repo=repo)
24 meta.Session().commit()
23 meta.Session().commit()
25
24
26 assert Repository.get_by_repo_name(repo_name='test-repo-1') is None
25 assert db.Repository.get_by_repo_name(repo_name='test-repo-1') is None
27
26
28 def test_remove_repo_repo_raises_exc_when_attached_forks(self):
27 def test_remove_repo_repo_raises_exc_when_attached_forks(self):
29 repo = fixture.create_repo(name='test-repo-1')
28 repo = fixture.create_repo(name='test-repo-1')
@@ -53,9 +52,9 b' class TestRepos(base.TestController):'
53 RepoModel().delete(repo=repo, forks='delete')
52 RepoModel().delete(repo=repo, forks='delete')
54 meta.Session().commit()
53 meta.Session().commit()
55
54
56 assert Repository.get_by_repo_name(repo_name='test-repo-1') is None
55 assert db.Repository.get_by_repo_name(repo_name='test-repo-1') is None
57 assert Repository.get_by_repo_name(repo_name='test-repo-fork-1') is None
56 assert db.Repository.get_by_repo_name(repo_name='test-repo-fork-1') is None
58 assert Repository.get_by_repo_name(repo_name='test-repo-fork-fork-1') is None
57 assert db.Repository.get_by_repo_name(repo_name='test-repo-fork-fork-1') is None
59
58
60 def test_remove_repo_detach_forks(self):
59 def test_remove_repo_detach_forks(self):
61 repo = fixture.create_repo(name='test-repo-1')
60 repo = fixture.create_repo(name='test-repo-1')
@@ -72,9 +71,9 b' class TestRepos(base.TestController):'
72 meta.Session().commit()
71 meta.Session().commit()
73
72
74 try:
73 try:
75 assert Repository.get_by_repo_name(repo_name='test-repo-1') is None
74 assert db.Repository.get_by_repo_name(repo_name='test-repo-1') is None
76 assert Repository.get_by_repo_name(repo_name='test-repo-fork-1') is not None
75 assert db.Repository.get_by_repo_name(repo_name='test-repo-fork-1') is not None
77 assert Repository.get_by_repo_name(repo_name='test-repo-fork-fork-1') is not None
76 assert db.Repository.get_by_repo_name(repo_name='test-repo-fork-fork-1') is not None
78 finally:
77 finally:
79 RepoModel().delete(repo='test-repo-fork-fork-1')
78 RepoModel().delete(repo='test-repo-fork-fork-1')
80 RepoModel().delete(repo='test-repo-fork-1')
79 RepoModel().delete(repo='test-repo-fork-1')
@@ -1,28 +1,27 b''
1 from kallithea.model import meta
1 from kallithea.model import db, meta
2 from kallithea.model.db import Setting
3
2
4
3
5 name = 'spam-setting-name'
4 name = 'spam-setting-name'
6
5
7
6
8 def test_passing_list_setting_value_results_in_string_valued_setting():
7 def test_passing_list_setting_value_results_in_string_valued_setting():
9 assert Setting.get_by_name(name) is None
8 assert db.Setting.get_by_name(name) is None
10 setting = Setting.create_or_update(name, ['spam', 'eggs'])
9 setting = db.Setting.create_or_update(name, ['spam', 'eggs'])
11 meta.Session().flush() # must flush so we can delete it below
10 meta.Session().flush() # must flush so we can delete it below
12 try:
11 try:
13 assert Setting.get_by_name(name) is not None
12 assert db.Setting.get_by_name(name) is not None
14 # Quirk: list value is stringified.
13 # Quirk: list value is stringified.
15 assert Setting.get_by_name(name).app_settings_value \
14 assert db.Setting.get_by_name(name).app_settings_value \
16 == "['spam', 'eggs']"
15 == "['spam', 'eggs']"
17 assert Setting.get_by_name(name).app_settings_type == 'unicode'
16 assert db.Setting.get_by_name(name).app_settings_type == 'unicode'
18 finally:
17 finally:
19 meta.Session().delete(setting)
18 meta.Session().delete(setting)
20
19
21
20
22 def test_list_valued_setting_creation_requires_manual_value_formatting():
21 def test_list_valued_setting_creation_requires_manual_value_formatting():
23 assert Setting.get_by_name(name) is None
22 assert db.Setting.get_by_name(name) is None
24 # Quirk: need manual formatting of list setting value.
23 # Quirk: need manual formatting of list setting value.
25 setting = Setting.create_or_update(name, 'spam,eggs', type='list')
24 setting = db.Setting.create_or_update(name, 'spam,eggs', type='list')
26 meta.Session().flush() # must flush so we can delete it below
25 meta.Session().flush() # must flush so we can delete it below
27 try:
26 try:
28 assert setting.app_settings_value == ['spam', 'eggs']
27 assert setting.app_settings_value == ['spam', 'eggs']
@@ -31,8 +30,8 b' def test_list_valued_setting_creation_re'
31
30
32
31
33 def test_list_valued_setting_update():
32 def test_list_valued_setting_update():
34 assert Setting.get_by_name(name) is None
33 assert db.Setting.get_by_name(name) is None
35 setting = Setting.create_or_update(name, 'spam', type='list')
34 setting = db.Setting.create_or_update(name, 'spam', type='list')
36 meta.Session().flush() # must flush so we can delete it below
35 meta.Session().flush() # must flush so we can delete it below
37 try:
36 try:
38 assert setting.app_settings_value == ['spam']
37 assert setting.app_settings_value == ['spam']
@@ -1,7 +1,6 b''
1 import functools
1 import functools
2
2
3 from kallithea.model import meta
3 from kallithea.model import db, meta
4 from kallithea.model.db import RepoGroup
5 from kallithea.model.repo_group import RepoGroupModel
4 from kallithea.model.repo_group import RepoGroupModel
6 from kallithea.model.user_group import UserGroupModel
5 from kallithea.model.user_group import UserGroupModel
7 from kallithea.tests.fixture import Fixture
6 from kallithea.tests.fixture import Fixture
@@ -20,7 +19,7 b" def permissions_setup_func(group_name='g"
20 """
19 """
21 Resets all permissions to perm attribute
20 Resets all permissions to perm attribute
22 """
21 """
23 repo_group = RepoGroup.get_by_group_name(group_name=group_name)
22 repo_group = db.RepoGroup.get_by_group_name(group_name=group_name)
24 if not repo_group:
23 if not repo_group:
25 raise Exception('Cannot get group %s' % group_name)
24 raise Exception('Cannot get group %s' % group_name)
26
25
@@ -1,5 +1,4 b''
1 from kallithea.model import meta
1 from kallithea.model import db, meta
2 from kallithea.model.db import User, UserGroup
3 from kallithea.model.user_group import UserGroupModel
2 from kallithea.model.user_group import UserGroupModel
4 from kallithea.tests import base
3 from kallithea.tests import base
5 from kallithea.tests.fixture import Fixture
4 from kallithea.tests.fixture import Fixture
@@ -12,7 +11,7 b' class TestUserGroups(base.TestController'
12
11
13 def teardown_method(self, method):
12 def teardown_method(self, method):
14 # delete all groups
13 # delete all groups
15 for gr in UserGroup.query():
14 for gr in db.UserGroup.query():
16 fixture.destroy_user_group(gr)
15 fixture.destroy_user_group(gr)
17 meta.Session().commit()
16 meta.Session().commit()
18
17
@@ -28,11 +27,11 b' class TestUserGroups(base.TestController'
28 def test_enforce_groups(self, pre_existing, regular_should_be,
27 def test_enforce_groups(self, pre_existing, regular_should_be,
29 external_should_be, groups, expected):
28 external_should_be, groups, expected):
30 # delete all groups
29 # delete all groups
31 for gr in UserGroup.query():
30 for gr in db.UserGroup.query():
32 fixture.destroy_user_group(gr)
31 fixture.destroy_user_group(gr)
33 meta.Session().commit()
32 meta.Session().commit()
34
33
35 user = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
34 user = db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
36 for gr in pre_existing:
35 for gr in pre_existing:
37 gr = fixture.create_user_group(gr)
36 gr = fixture.create_user_group(gr)
38 meta.Session().commit()
37 meta.Session().commit()
@@ -54,6 +53,6 b' class TestUserGroups(base.TestController'
54 UserGroupModel().enforce_groups(user, groups, 'container')
53 UserGroupModel().enforce_groups(user, groups, 'container')
55 meta.Session().commit()
54 meta.Session().commit()
56
55
57 user = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
56 user = db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
58 in_groups = user.group_member
57 in_groups = user.group_member
59 assert sorted(expected) == sorted(x.users_group.users_group_name for x in in_groups)
58 assert sorted(expected) == sorted(x.users_group.users_group_name for x in in_groups)
@@ -1,8 +1,7 b''
1 import functools
1 import functools
2
2
3 import kallithea
3 import kallithea
4 from kallithea.model import meta
4 from kallithea.model import db, meta
5 from kallithea.model.db import RepoGroup, Repository
6 from kallithea.model.repo_group import RepoGroupModel
5 from kallithea.model.repo_group import RepoGroupModel
7 from kallithea.tests.models.common import _check_expected_count, _create_project_tree, _destroy_project_tree, _get_perms, check_tree_perms, expected_count
6 from kallithea.tests.models.common import _check_expected_count, _create_project_tree, _destroy_project_tree, _get_perms, check_tree_perms, expected_count
8
7
@@ -22,7 +21,7 b" def permissions_setup_func(group_name='g"
22 permissions_setup_func(group_name, perm, recursive,
21 permissions_setup_func(group_name, perm, recursive,
23 user_id=kallithea.DEFAULT_USER_ID)
22 user_id=kallithea.DEFAULT_USER_ID)
24
23
25 repo_group = RepoGroup.get_by_group_name(group_name=group_name)
24 repo_group = db.RepoGroup.get_by_group_name(group_name=group_name)
26 if not repo_group:
25 if not repo_group:
27 raise Exception('Cannot get group %s' % group_name)
26 raise Exception('Cannot get group %s' % group_name)
28
27
@@ -133,7 +132,7 b' def test_user_permissions_on_group_with_'
133
132
134 for name, perm in repo_items:
133 for name, perm in repo_items:
135 # default user permissions do not "recurse into" private repos
134 # default user permissions do not "recurse into" private repos
136 is_private = Repository.get_by_repo_name(name).private
135 is_private = db.Repository.get_by_repo_name(name).private
137 check_tree_perms(name, perm, group, 'repository.none' if is_private else 'repository.write')
136 check_tree_perms(name, perm, group, 'repository.none' if is_private else 'repository.write')
138
137
139 for name, perm in items:
138 for name, perm in items:
@@ -1,4 +1,4 b''
1 from kallithea.model.db import UserSshKeys
1 from kallithea.model import db
2 from kallithea.tests.base import TestController
2 from kallithea.tests.base import TestController
3 from kallithea.tests.fixture import Fixture
3 from kallithea.tests.fixture import Fixture
4
4
@@ -11,7 +11,7 b" public_key = 'ssh-rsa AAAAB3NzaC1yc2EAAA"
11 class TestUserSshKeys(TestController):
11 class TestUserSshKeys(TestController):
12
12
13 def test_fingerprint_generation(self):
13 def test_fingerprint_generation(self):
14 key_model = UserSshKeys()
14 key_model = db.UserSshKeys()
15 key_model.public_key = public_key
15 key_model.public_key = public_key
16 expected = 'Ke3oUCNJM87P0jJTb3D+e3shjceP2CqMpQKVd75E9I8'
16 expected = 'Ke3oUCNJM87P0jJTb3D+e3shjceP2CqMpQKVd75E9I8'
17 assert expected == key_model.fingerprint
17 assert expected == key_model.fingerprint
@@ -1,7 +1,6 b''
1 import pytest
1 import pytest
2
2
3 from kallithea.model import meta
3 from kallithea.model import db, meta
4 from kallithea.model.db import Permission, User, UserEmailMap, UserGroup, UserGroupMember
5 from kallithea.model.user import UserModel
4 from kallithea.model.user import UserModel
6 from kallithea.model.user_group import UserGroupModel
5 from kallithea.model.user_group import UserGroupModel
7 from kallithea.tests import base
6 from kallithea.tests import base
@@ -26,13 +25,13 b' class TestUser(base.TestController):'
26 email='u232@example.com',
25 email='u232@example.com',
27 firstname='u1', lastname='u1')
26 firstname='u1', lastname='u1')
28 meta.Session().commit()
27 meta.Session().commit()
29 assert User.get_by_username('test_user') == usr
28 assert db.User.get_by_username('test_user') == usr
30 assert User.get_by_username('test_USER', case_insensitive=True) == usr
29 assert db.User.get_by_username('test_USER', case_insensitive=True) == usr
31 # User.get_by_username without explicit request for case insensitivty
30 # User.get_by_username without explicit request for case insensitivty
32 # will use database case sensitivity. The following will thus return
31 # will use database case sensitivity. The following will thus return
33 # None on for example PostgreSQL but find test_user on MySQL - we are
32 # None on for example PostgreSQL but find test_user on MySQL - we are
34 # fine with leaving that as undefined as long as it doesn't crash.
33 # fine with leaving that as undefined as long as it doesn't crash.
35 User.get_by_username('test_USER', case_insensitive=False)
34 db.User.get_by_username('test_USER', case_insensitive=False)
36
35
37 # make user group
36 # make user group
38 user_group = fixture.create_user_group('some_example_group')
37 user_group = fixture.create_user_group('some_example_group')
@@ -41,12 +40,12 b' class TestUser(base.TestController):'
41 UserGroupModel().add_user_to_group(user_group, usr)
40 UserGroupModel().add_user_to_group(user_group, usr)
42 meta.Session().commit()
41 meta.Session().commit()
43
42
44 assert UserGroup.get(user_group.users_group_id) == user_group
43 assert db.UserGroup.get(user_group.users_group_id) == user_group
45 assert UserGroupMember.query().count() == 1
44 assert db.UserGroupMember.query().count() == 1
46 UserModel().delete(usr.user_id)
45 UserModel().delete(usr.user_id)
47 meta.Session().commit()
46 meta.Session().commit()
48
47
49 assert UserGroupMember.query().all() == []
48 assert db.UserGroupMember.query().all() == []
50
49
51 def test_additional_email_as_main(self):
50 def test_additional_email_as_main(self):
52 usr = UserModel().create_or_update(username='test_user',
51 usr = UserModel().create_or_update(username='test_user',
@@ -56,7 +55,7 b' class TestUser(base.TestController):'
56 meta.Session().commit()
55 meta.Session().commit()
57
56
58 with pytest.raises(AttributeError):
57 with pytest.raises(AttributeError):
59 m = UserEmailMap()
58 m = db.UserEmailMap()
60 m.email = 'main_email@example.com'
59 m.email = 'main_email@example.com'
61 m.user = usr
60 m.user = usr
62 meta.Session().add(m)
61 meta.Session().add(m)
@@ -72,29 +71,29 b' class TestUser(base.TestController):'
72 firstname='u1', lastname='u1')
71 firstname='u1', lastname='u1')
73 meta.Session().commit()
72 meta.Session().commit()
74
73
75 m = UserEmailMap()
74 m = db.UserEmailMap()
76 m.email = 'main_email2@example.com'
75 m.email = 'main_email2@example.com'
77 m.user = usr
76 m.user = usr
78 meta.Session().add(m)
77 meta.Session().add(m)
79 meta.Session().commit()
78 meta.Session().commit()
80
79
81 u = User.get_by_email(email='MAIN_email@example.com')
80 u = db.User.get_by_email(email='MAIN_email@example.com')
82 assert usr.user_id == u.user_id
81 assert usr.user_id == u.user_id
83 assert usr.username == u.username
82 assert usr.username == u.username
84
83
85 u = User.get_by_email(email='main_email@example.com')
84 u = db.User.get_by_email(email='main_email@example.com')
86 assert usr.user_id == u.user_id
85 assert usr.user_id == u.user_id
87 assert usr.username == u.username
86 assert usr.username == u.username
88
87
89 u = User.get_by_email(email='main_email2@example.com')
88 u = db.User.get_by_email(email='main_email2@example.com')
90 assert usr.user_id == u.user_id
89 assert usr.user_id == u.user_id
91 assert usr.username == u.username
90 assert usr.username == u.username
92 u = User.get_by_email(email='main_email3@example.com')
91 u = db.User.get_by_email(email='main_email3@example.com')
93 assert u is None
92 assert u is None
94
93
95 u = User.get_by_email(email='main_e%ail@example.com')
94 u = db.User.get_by_email(email='main_e%ail@example.com')
96 assert u is None
95 assert u is None
97 u = User.get_by_email(email='main_emai_@example.com')
96 u = db.User.get_by_email(email='main_emai_@example.com')
98 assert u is None
97 assert u is None
99
98
100 UserModel().delete(usr.user_id)
99 UserModel().delete(usr.user_id)
@@ -110,7 +109,7 b' class TestUsers(base.TestController):'
110 firstname='u1', lastname='u1')
109 firstname='u1', lastname='u1')
111
110
112 def teardown_method(self, method):
111 def teardown_method(self, method):
113 perm = Permission.query().all()
112 perm = db.Permission.query().all()
114 for p in perm:
113 for p in perm:
115 UserModel().revoke_perm(self.u1, p)
114 UserModel().revoke_perm(self.u1, p)
116
115
@@ -119,19 +118,19 b' class TestUsers(base.TestController):'
119 meta.Session.remove()
118 meta.Session.remove()
120
119
121 def test_add_perm(self):
120 def test_add_perm(self):
122 perm = Permission.query().all()[0]
121 perm = db.Permission.query().all()[0]
123 UserModel().grant_perm(self.u1, perm)
122 UserModel().grant_perm(self.u1, perm)
124 meta.Session().commit()
123 meta.Session().commit()
125 assert UserModel().has_perm(self.u1, perm) == True
124 assert UserModel().has_perm(self.u1, perm) == True
126
125
127 def test_has_perm(self):
126 def test_has_perm(self):
128 perm = Permission.query().all()
127 perm = db.Permission.query().all()
129 for p in perm:
128 for p in perm:
130 has_p = UserModel().has_perm(self.u1, p)
129 has_p = UserModel().has_perm(self.u1, p)
131 assert False == has_p
130 assert False == has_p
132
131
133 def test_revoke_perm(self):
132 def test_revoke_perm(self):
134 perm = Permission.query().all()[0]
133 perm = db.Permission.query().all()[0]
135 UserModel().grant_perm(self.u1, perm)
134 UserModel().grant_perm(self.u1, perm)
136 meta.Session().commit()
135 meta.Session().commit()
137 assert UserModel().has_perm(self.u1, perm) == True
136 assert UserModel().has_perm(self.u1, perm) == True
@@ -3,7 +3,7 b' import uuid'
3 import pytest
3 import pytest
4
4
5 from kallithea.lib.auth_modules import auth_ldap, authenticate
5 from kallithea.lib.auth_modules import auth_ldap, authenticate
6 from kallithea.model.db import User
6 from kallithea.model import db
7
7
8
8
9 @pytest.fixture
9 @pytest.fixture
@@ -35,7 +35,7 b' def test_update_user_attributes_from_lda'
35 # Arrange test user.
35 # Arrange test user.
36 uniqifier = uuid.uuid4()
36 uniqifier = uuid.uuid4()
37 username = 'test-user-{0}'.format(uniqifier)
37 username = 'test-user-{0}'.format(uniqifier)
38 assert User.get_by_username(username) is None
38 assert db.User.get_by_username(username) is None
39 user_input = dict(username='test-user-{0}'.format(uniqifier),
39 user_input = dict(username='test-user-{0}'.format(uniqifier),
40 password='spam password',
40 password='spam password',
41 email='spam-email-{0}'.format(uniqifier),
41 email='spam-email-{0}'.format(uniqifier),
@@ -72,7 +72,7 b' def test_init_user_attributes_from_ldap('
72 # Arrange test user.
72 # Arrange test user.
73 uniqifier = uuid.uuid4()
73 uniqifier = uuid.uuid4()
74 username = 'test-user-{0}'.format(uniqifier)
74 username = 'test-user-{0}'.format(uniqifier)
75 assert User.get_by_username(username) is None
75 assert db.User.get_by_username(username) is None
76
76
77 # Arrange LDAP auth.
77 # Arrange LDAP auth.
78 monkeypatch.setattr(auth_ldap, 'AuthLdap', _AuthLdapMock)
78 monkeypatch.setattr(auth_ldap, 'AuthLdap', _AuthLdapMock)
@@ -89,7 +89,7 b' def test_init_user_attributes_from_ldap('
89
89
90 # Verify that authentication created new user with attributes
90 # Verify that authentication created new user with attributes
91 # retrieved from LDAP.
91 # retrieved from LDAP.
92 new_user = User.get_by_username(username)
92 new_user = db.User.get_by_username(username)
93 assert new_user is not None
93 assert new_user is not None
94 assert new_user.firstname == 'spam ldap first name'
94 assert new_user.firstname == 'spam ldap first name'
95 assert new_user.lastname == 'spam ldap last name'
95 assert new_user.lastname == 'spam ldap last name'
@@ -115,7 +115,7 b' def test_init_user_attributes_from_ldap_'
115 # Arrange test user.
115 # Arrange test user.
116 uniqifier = uuid.uuid4()
116 uniqifier = uuid.uuid4()
117 username = 'test-user-{0}'.format(uniqifier)
117 username = 'test-user-{0}'.format(uniqifier)
118 assert User.get_by_username(username) is None
118 assert db.User.get_by_username(username) is None
119
119
120 # Arrange LDAP auth.
120 # Arrange LDAP auth.
121 monkeypatch.setattr(auth_ldap, 'AuthLdap', _AuthLdapNoEmailMock)
121 monkeypatch.setattr(auth_ldap, 'AuthLdap', _AuthLdapNoEmailMock)
@@ -132,7 +132,7 b' def test_init_user_attributes_from_ldap_'
132
132
133 # Verify that authentication created new user with attributes
133 # Verify that authentication created new user with attributes
134 # retrieved from LDAP, with email == None.
134 # retrieved from LDAP, with email == None.
135 new_user = User.get_by_username(username)
135 new_user = db.User.get_by_username(username)
136 assert new_user is not None
136 assert new_user is not None
137 assert new_user.firstname == 'spam ldap first name'
137 assert new_user.firstname == 'spam ldap first name'
138 assert new_user.lastname == 'spam ldap last name'
138 assert new_user.lastname == 'spam ldap last name'
@@ -32,7 +32,7 b' import mock'
32 from tg.util.webtest import test_context
32 from tg.util.webtest import test_context
33
33
34 from kallithea.lib.utils2 import AttributeDict, safe_bytes
34 from kallithea.lib.utils2 import AttributeDict, safe_bytes
35 from kallithea.model.db import Repository
35 from kallithea.model import db
36 from kallithea.tests import base
36 from kallithea.tests import base
37
37
38
38
@@ -251,13 +251,13 b' class TestLibs(base.TestController):'
251 assert grav == 'https://example.com/%s/%s' % (_md5(em), 24)
251 assert grav == 'https://example.com/%s/%s' % (_md5(em), 24)
252
252
253 @base.parametrize('clone_uri_tmpl,repo_name,username,prefix,expected', [
253 @base.parametrize('clone_uri_tmpl,repo_name,username,prefix,expected', [
254 (Repository.DEFAULT_CLONE_URI, 'group/repo1', None, '', 'http://vps1:8000/group/repo1'),
254 (db.Repository.DEFAULT_CLONE_URI, 'group/repo1', None, '', 'http://vps1:8000/group/repo1'),
255 (Repository.DEFAULT_CLONE_URI, 'group/repo1', 'username', '', 'http://username@vps1:8000/group/repo1'),
255 (db.Repository.DEFAULT_CLONE_URI, 'group/repo1', 'username', '', 'http://username@vps1:8000/group/repo1'),
256 (Repository.DEFAULT_CLONE_URI, 'group/repo1', None, '/prefix', 'http://vps1:8000/prefix/group/repo1'),
256 (db.Repository.DEFAULT_CLONE_URI, 'group/repo1', None, '/prefix', 'http://vps1:8000/prefix/group/repo1'),
257 (Repository.DEFAULT_CLONE_URI, 'group/repo1', 'user', '/prefix', 'http://user@vps1:8000/prefix/group/repo1'),
257 (db.Repository.DEFAULT_CLONE_URI, 'group/repo1', 'user', '/prefix', 'http://user@vps1:8000/prefix/group/repo1'),
258 (Repository.DEFAULT_CLONE_URI, 'group/repo1', 'username', '/prefix', 'http://username@vps1:8000/prefix/group/repo1'),
258 (db.Repository.DEFAULT_CLONE_URI, 'group/repo1', 'username', '/prefix', 'http://username@vps1:8000/prefix/group/repo1'),
259 (Repository.DEFAULT_CLONE_URI, 'group/repo1', 'user', '/prefix/', 'http://user@vps1:8000/prefix/group/repo1'),
259 (db.Repository.DEFAULT_CLONE_URI, 'group/repo1', 'user', '/prefix/', 'http://user@vps1:8000/prefix/group/repo1'),
260 (Repository.DEFAULT_CLONE_URI, 'group/repo1', 'username', '/prefix/', 'http://username@vps1:8000/prefix/group/repo1'),
260 (db.Repository.DEFAULT_CLONE_URI, 'group/repo1', 'username', '/prefix/', 'http://username@vps1:8000/prefix/group/repo1'),
261 ('{scheme}://{user}@{netloc}/_{repoid}', 'group/repo1', None, '', 'http://vps1:8000/_23'),
261 ('{scheme}://{user}@{netloc}/_{repoid}', 'group/repo1', None, '', 'http://vps1:8000/_23'),
262 ('{scheme}://{user}@{netloc}/_{repoid}', 'group/repo1', 'username', '', 'http://username@vps1:8000/_23'),
262 ('{scheme}://{user}@{netloc}/_{repoid}', 'group/repo1', 'username', '', 'http://username@vps1:8000/_23'),
263 ('http://{user}@{netloc}/_{repoid}', 'group/repo1', 'username', '', 'http://username@vps1:8000/_23'),
263 ('http://{user}@{netloc}/_{repoid}', 'group/repo1', 'username', '', 'http://username@vps1:8000/_23'),
@@ -540,7 +540,7 b' class TestLibs(base.TestController):'
540 ("_IDa", '_IDa'),
540 ("_IDa", '_IDa'),
541 ])
541 ])
542 def test_fix_repo_id_name(self, test, expected):
542 def test_fix_repo_id_name(self, test, expected):
543 repo = Repository.get_by_repo_name(base.HG_REPO)
543 repo = db.Repository.get_by_repo_name(base.HG_REPO)
544 test = test.replace('ID', str(repo.repo_id))
544 test = test.replace('ID', str(repo.repo_id))
545 expected = expected.replace('NAME', repo.repo_name).replace('ID', str(repo.repo_id))
545 expected = expected.replace('NAME', repo.repo_name).replace('ID', str(repo.repo_id))
546 from kallithea.lib.utils import fix_repo_id_name
546 from kallithea.lib.utils import fix_repo_id_name
@@ -3,7 +3,7 b''
3 import mock
3 import mock
4
4
5 import kallithea
5 import kallithea
6 from kallithea.model.db import User
6 from kallithea.model import db
7 from kallithea.tests import base
7 from kallithea.tests import base
8
8
9
9
@@ -127,7 +127,7 b' class TestMail(base.TestController):'
127 subject = 'subject'
127 subject = 'subject'
128 body = 'body'
128 body = 'body'
129 html_body = 'html_body'
129 html_body = 'html_body'
130 author = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
130 author = db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
131
131
132 config_mock = {
132 config_mock = {
133 'smtp_server': mailserver,
133 'smtp_server': mailserver,
@@ -151,7 +151,7 b' class TestMail(base.TestController):'
151 subject = 'subject'
151 subject = 'subject'
152 body = 'body'
152 body = 'body'
153 html_body = 'html_body'
153 html_body = 'html_body'
154 author = User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
154 author = db.User.get_by_username(base.TEST_USER_REGULAR_LOGIN)
155
155
156 config_mock = {
156 config_mock = {
157 'smtp_server': mailserver,
157 'smtp_server': mailserver,
@@ -174,7 +174,7 b' class TestMail(base.TestController):'
174 subject = 'subject'
174 subject = 'subject'
175 body = 'body'
175 body = 'body'
176 html_body = 'html_body'
176 html_body = 'html_body'
177 author = User(name='foo', lastname='(fubar) "baz"')
177 author = db.User(name='foo', lastname='(fubar) "baz"')
178 headers = {'extra': 'yes'}
178 headers = {'extra': 'yes'}
179
179
180 config_mock = {
180 config_mock = {
@@ -38,8 +38,7 b' import pytest'
38
38
39 import kallithea
39 import kallithea
40 from kallithea.lib.utils2 import ascii_bytes, safe_str
40 from kallithea.lib.utils2 import ascii_bytes, safe_str
41 from kallithea.model import meta
41 from kallithea.model import db, meta
42 from kallithea.model.db import Repository, Ui, User, UserIpMap, UserLog
43 from kallithea.model.ssh_key import SshKeyModel
42 from kallithea.model.ssh_key import SshKeyModel
44 from kallithea.model.user import UserModel
43 from kallithea.model.user import UserModel
45 from kallithea.tests import base
44 from kallithea.tests import base
@@ -69,7 +68,7 b' class SshVcsTest(object):'
69
68
70 @classmethod
69 @classmethod
71 def repo_url_param(cls, webserver, repo_name, username=base.TEST_USER_ADMIN_LOGIN, password=base.TEST_USER_ADMIN_PASS, client_ip=base.IP_ADDR):
70 def repo_url_param(cls, webserver, repo_name, username=base.TEST_USER_ADMIN_LOGIN, password=base.TEST_USER_ADMIN_PASS, client_ip=base.IP_ADDR):
72 user = User.get_by_username(username)
71 user = db.User.get_by_username(username)
73 if user.ssh_keys:
72 if user.ssh_keys:
74 ssh_key = user.ssh_keys[0]
73 ssh_key = user.ssh_keys[0]
75 else:
74 else:
@@ -221,10 +220,10 b' def _check_outgoing(vcs, cwd, clone_url)'
221
220
222
221
223 def set_anonymous_access(enable=True):
222 def set_anonymous_access(enable=True):
224 user = User.get_default_user()
223 user = db.User.get_default_user()
225 user.active = enable
224 user.active = enable
226 meta.Session().commit()
225 meta.Session().commit()
227 if enable != User.get_default_user().active:
226 if enable != db.User.get_default_user().active:
228 raise Exception('Cannot set anonymous access')
227 raise Exception('Cannot set anonymous access')
229
228
230
229
@@ -253,7 +252,7 b' class TestVCSOperations(base.TestControl'
253 yield
252 yield
254 # remove hook
253 # remove hook
255 for hook in ['prechangegroup', 'pretxnchangegroup', 'preoutgoing', 'changegroup', 'outgoing', 'incoming']:
254 for hook in ['prechangegroup', 'pretxnchangegroup', 'preoutgoing', 'changegroup', 'outgoing', 'incoming']:
256 entry = Ui.get_by_key('hooks', '%s.testhook' % hook)
255 entry = db.Ui.get_by_key('hooks', '%s.testhook' % hook)
257 if entry:
256 if entry:
258 meta.Session().delete(entry)
257 meta.Session().delete(entry)
259 meta.Session().commit()
258 meta.Session().commit()
@@ -313,12 +312,12 b' class TestVCSOperations(base.TestControl'
313 @parametrize_vcs_test
312 @parametrize_vcs_test
314 def test_push_new_repo(self, webserver, vt):
313 def test_push_new_repo(self, webserver, vt):
315 # Clear the log so we know what is added
314 # Clear the log so we know what is added
316 UserLog.query().delete()
315 db.UserLog.query().delete()
317 meta.Session().commit()
316 meta.Session().commit()
318
317
319 # Create an empty server repo using the API
318 # Create an empty server repo using the API
320 repo_name = 'new_%s_%s' % (vt.repo_type, next(_RandomNameSequence()))
319 repo_name = 'new_%s_%s' % (vt.repo_type, next(_RandomNameSequence()))
321 usr = User.get_by_username(base.TEST_USER_ADMIN_LOGIN)
320 usr = db.User.get_by_username(base.TEST_USER_ADMIN_LOGIN)
322 params = {
321 params = {
323 "id": 7,
322 "id": 7,
324 "api_key": usr.api_key,
323 "api_key": usr.api_key,
@@ -359,7 +358,7 b' class TestVCSOperations(base.TestControl'
359 # <UserLog('id:new_git_XXX:pull')>
358 # <UserLog('id:new_git_XXX:pull')>
360 # <UserLog('id:new_git_XXX:push:aed9d4c1732a1927da3be42c47eb9afdc200d427,d38b083a07af10a9f44193486959a96a23db78da,4841ff9a2b385bec995f4679ef649adb3f437622')>
359 # <UserLog('id:new_git_XXX:push:aed9d4c1732a1927da3be42c47eb9afdc200d427,d38b083a07af10a9f44193486959a96a23db78da,4841ff9a2b385bec995f4679ef649adb3f437622')>
361 meta.Session.close() # make sure SA fetches all new log entries (apparently only needed for MariaDB/MySQL ...)
360 meta.Session.close() # make sure SA fetches all new log entries (apparently only needed for MariaDB/MySQL ...)
362 action_parts = [ul.action.split(':', 1) for ul in UserLog.query().order_by(UserLog.user_log_id)]
361 action_parts = [ul.action.split(':', 1) for ul in db.UserLog.query().order_by(db.UserLog.user_log_id)]
363 assert [(t[0], (t[1].count(',') + 1) if len(t) == 2 else 0) for t in action_parts] == ([
362 assert [(t[0], (t[1].count(',') + 1) if len(t) == 2 else 0) for t in action_parts] == ([
364 ('started_following_repo', 0),
363 ('started_following_repo', 0),
365 ('user_created_repo', 0),
364 ('user_created_repo', 0),
@@ -373,7 +372,7 b' class TestVCSOperations(base.TestControl'
373
372
374 @parametrize_vcs_test
373 @parametrize_vcs_test
375 def test_push_new_file(self, webserver, testfork, vt):
374 def test_push_new_file(self, webserver, testfork, vt):
376 UserLog.query().delete()
375 db.UserLog.query().delete()
377 meta.Session().commit()
376 meta.Session().commit()
378
377
379 dest_dir = _get_tmp_dir()
378 dest_dir = _get_tmp_dir()
@@ -391,13 +390,13 b' class TestVCSOperations(base.TestControl'
391 assert 'Last revision is now' in stdout
390 assert 'Last revision is now' in stdout
392
391
393 meta.Session.close() # make sure SA fetches all new log entries (apparently only needed for MariaDB/MySQL ...)
392 meta.Session.close() # make sure SA fetches all new log entries (apparently only needed for MariaDB/MySQL ...)
394 action_parts = [ul.action.split(':', 1) for ul in UserLog.query().order_by(UserLog.user_log_id)]
393 action_parts = [ul.action.split(':', 1) for ul in db.UserLog.query().order_by(db.UserLog.user_log_id)]
395 assert [(t[0], (t[1].count(',') + 1) if len(t) == 2 else 0) for t in action_parts] == \
394 assert [(t[0], (t[1].count(',') + 1) if len(t) == 2 else 0) for t in action_parts] == \
396 [('pull', 0), ('push', 3)]
395 [('pull', 0), ('push', 3)]
397
396
398 @parametrize_vcs_test
397 @parametrize_vcs_test
399 def test_pull(self, webserver, testfork, vt):
398 def test_pull(self, webserver, testfork, vt):
400 UserLog.query().delete()
399 db.UserLog.query().delete()
401 meta.Session().commit()
400 meta.Session().commit()
402
401
403 dest_dir = _get_tmp_dir()
402 dest_dir = _get_tmp_dir()
@@ -412,7 +411,7 b' class TestVCSOperations(base.TestControl'
412 elif vt.repo_type == 'hg':
411 elif vt.repo_type == 'hg':
413 assert 'new changesets' in stdout
412 assert 'new changesets' in stdout
414
413
415 action_parts = [ul.action for ul in UserLog.query().order_by(UserLog.user_log_id)]
414 action_parts = [ul.action for ul in db.UserLog.query().order_by(db.UserLog.user_log_id)]
416 assert action_parts == ['pull']
415 assert action_parts == ['pull']
417
416
418 # Test handling of URLs with extra '/' around repo_name
417 # Test handling of URLs with extra '/' around repo_name
@@ -443,7 +442,7 b' class TestVCSOperations(base.TestControl'
443
442
444 @parametrize_vcs_test
443 @parametrize_vcs_test
445 def test_push_invalidates_cache(self, webserver, testfork, vt):
444 def test_push_invalidates_cache(self, webserver, testfork, vt):
446 pre_cached_tip = [repo.get_api_data()['last_changeset']['short_id'] for repo in Repository.query().filter(Repository.repo_name == testfork[vt.repo_type])]
445 pre_cached_tip = [repo.get_api_data()['last_changeset']['short_id'] for repo in db.Repository.query().filter(db.Repository.repo_name == testfork[vt.repo_type])]
447
446
448 dest_dir = _get_tmp_dir()
447 dest_dir = _get_tmp_dir()
449 clone_url = vt.repo_url_param(webserver, testfork[vt.repo_type])
448 clone_url = vt.repo_url_param(webserver, testfork[vt.repo_type])
@@ -455,7 +454,7 b' class TestVCSOperations(base.TestControl'
455 _check_proper_git_push(stdout, stderr)
454 _check_proper_git_push(stdout, stderr)
456
455
457 meta.Session.close() # expire session to make sure SA fetches new Repository instances after last_changeset has been updated by server side hook in another process
456 meta.Session.close() # expire session to make sure SA fetches new Repository instances after last_changeset has been updated by server side hook in another process
458 post_cached_tip = [repo.get_api_data()['last_changeset']['short_id'] for repo in Repository.query().filter(Repository.repo_name == testfork[vt.repo_type])]
457 post_cached_tip = [repo.get_api_data()['last_changeset']['short_id'] for repo in db.Repository.query().filter(db.Repository.repo_name == testfork[vt.repo_type])]
459 assert pre_cached_tip != post_cached_tip
458 assert pre_cached_tip != post_cached_tip
460
459
461 @parametrize_vcs_test_http
460 @parametrize_vcs_test_http
@@ -475,7 +474,7 b' class TestVCSOperations(base.TestControl'
475
474
476 @parametrize_vcs_test
475 @parametrize_vcs_test
477 def test_push_with_readonly_credentials(self, webserver, vt):
476 def test_push_with_readonly_credentials(self, webserver, vt):
478 UserLog.query().delete()
477 db.UserLog.query().delete()
479 meta.Session().commit()
478 meta.Session().commit()
480
479
481 dest_dir = _get_tmp_dir()
480 dest_dir = _get_tmp_dir()
@@ -490,7 +489,7 b' class TestVCSOperations(base.TestControl'
490 assert 'abort: HTTP Error 403: Forbidden' in stderr or 'abort: push failed on remote' in stderr and 'remote: Push access to %r denied' % str(vt.repo_name) in stdout
489 assert 'abort: HTTP Error 403: Forbidden' in stderr or 'abort: push failed on remote' in stderr and 'remote: Push access to %r denied' % str(vt.repo_name) in stdout
491
490
492 meta.Session.close() # make sure SA fetches all new log entries (apparently only needed for MariaDB/MySQL ...)
491 meta.Session.close() # make sure SA fetches all new log entries (apparently only needed for MariaDB/MySQL ...)
493 action_parts = [ul.action.split(':', 1) for ul in UserLog.query().order_by(UserLog.user_log_id)]
492 action_parts = [ul.action.split(':', 1) for ul in db.UserLog.query().order_by(db.UserLog.user_log_id)]
494 assert [(t[0], (t[1].count(',') + 1) if len(t) == 2 else 0) for t in action_parts] == \
493 assert [(t[0], (t[1].count(',') + 1) if len(t) == 2 else 0) for t in action_parts] == \
495 [('pull', 0)]
494 [('pull', 0)]
496
495
@@ -528,8 +527,8 b' class TestVCSOperations(base.TestControl'
528 assert 'abort: HTTP Error 403: Forbidden' in stderr or 'remote: abort: User test_admin from 127.0.0.127 cannot be authorized' in stdout + stderr
527 assert 'abort: HTTP Error 403: Forbidden' in stderr or 'remote: abort: User test_admin from 127.0.0.127 cannot be authorized' in stdout + stderr
529 finally:
528 finally:
530 # release IP restrictions
529 # release IP restrictions
531 for ip in UserIpMap.query():
530 for ip in db.UserIpMap.query():
532 UserIpMap.delete(ip.ip_id)
531 db.UserIpMap.delete(ip.ip_id)
533 meta.Session().commit()
532 meta.Session().commit()
534 # IP permissions are cached, need to wait for the cache in the server process to expire
533 # IP permissions are cached, need to wait for the cache in the server process to expire
535 time.sleep(1.5)
534 time.sleep(1.5)
@@ -551,7 +550,7 b' class TestVCSOperations(base.TestControl'
551 @parametrize_vcs_test_hg # git hooks doesn't work like hg hooks
550 @parametrize_vcs_test_hg # git hooks doesn't work like hg hooks
552 def test_custom_hooks_preoutgoing(self, testhook_cleanup, webserver, testfork, vt):
551 def test_custom_hooks_preoutgoing(self, testhook_cleanup, webserver, testfork, vt):
553 # set prechangegroup to failing hook (returns True)
552 # set prechangegroup to failing hook (returns True)
554 Ui.create_or_update_hook('preoutgoing.testhook', 'python:kallithea.tests.fixture.failing_test_hook')
553 db.Ui.create_or_update_hook('preoutgoing.testhook', 'python:kallithea.tests.fixture.failing_test_hook')
555 meta.Session().commit()
554 meta.Session().commit()
556 # clone repo
555 # clone repo
557 clone_url = vt.repo_url_param(webserver, testfork[vt.repo_type], username=base.TEST_USER_ADMIN_LOGIN, password=base.TEST_USER_ADMIN_PASS)
556 clone_url = vt.repo_url_param(webserver, testfork[vt.repo_type], username=base.TEST_USER_ADMIN_LOGIN, password=base.TEST_USER_ADMIN_PASS)
@@ -566,7 +565,7 b' class TestVCSOperations(base.TestControl'
566 @parametrize_vcs_test_hg # git hooks doesn't work like hg hooks
565 @parametrize_vcs_test_hg # git hooks doesn't work like hg hooks
567 def test_custom_hooks_prechangegroup(self, testhook_cleanup, webserver, testfork, vt):
566 def test_custom_hooks_prechangegroup(self, testhook_cleanup, webserver, testfork, vt):
568 # set prechangegroup to failing hook (returns exit code 1)
567 # set prechangegroup to failing hook (returns exit code 1)
569 Ui.create_or_update_hook('prechangegroup.testhook', 'python:kallithea.tests.fixture.failing_test_hook')
568 db.Ui.create_or_update_hook('prechangegroup.testhook', 'python:kallithea.tests.fixture.failing_test_hook')
570 meta.Session().commit()
569 meta.Session().commit()
571 # clone repo
570 # clone repo
572 clone_url = vt.repo_url_param(webserver, testfork[vt.repo_type], username=base.TEST_USER_ADMIN_LOGIN, password=base.TEST_USER_ADMIN_PASS)
571 clone_url = vt.repo_url_param(webserver, testfork[vt.repo_type], username=base.TEST_USER_ADMIN_LOGIN, password=base.TEST_USER_ADMIN_PASS)
@@ -583,7 +582,7 b' class TestVCSOperations(base.TestControl'
583 assert stdout != ''
582 assert stdout != ''
584
583
585 # set prechangegroup hook to exception throwing method
584 # set prechangegroup hook to exception throwing method
586 Ui.create_or_update_hook('prechangegroup.testhook', 'python:kallithea.tests.fixture.exception_test_hook')
585 db.Ui.create_or_update_hook('prechangegroup.testhook', 'python:kallithea.tests.fixture.exception_test_hook')
587 meta.Session().commit()
586 meta.Session().commit()
588 # re-try to push
587 # re-try to push
589 stdout, stderr = Command(dest_dir).execute('%s push' % vt.repo_type, clone_url, ignoreReturnCode=True)
588 stdout, stderr = Command(dest_dir).execute('%s push' % vt.repo_type, clone_url, ignoreReturnCode=True)
@@ -598,7 +597,7 b' class TestVCSOperations(base.TestControl'
598 assert stdout != ''
597 assert stdout != ''
599
598
600 # set prechangegroup hook to method that returns False
599 # set prechangegroup hook to method that returns False
601 Ui.create_or_update_hook('prechangegroup.testhook', 'python:kallithea.tests.fixture.passing_test_hook')
600 db.Ui.create_or_update_hook('prechangegroup.testhook', 'python:kallithea.tests.fixture.passing_test_hook')
602 meta.Session().commit()
601 meta.Session().commit()
603 # re-try to push
602 # re-try to push
604 stdout, stderr = Command(dest_dir).execute('%s push' % vt.repo_type, clone_url, ignoreReturnCode=True)
603 stdout, stderr = Command(dest_dir).execute('%s push' % vt.repo_type, clone_url, ignoreReturnCode=True)
@@ -14,7 +14,7 b''
14
14
15 import pytest
15 import pytest
16
16
17 from kallithea.model.db import Repository
17 from kallithea.model import db
18 from kallithea.tests import base
18 from kallithea.tests import base
19
19
20
20
@@ -24,7 +24,7 b' class TestVCSPerformance(base.TestContro'
24 def graphmod(self, repo):
24 def graphmod(self, repo):
25 """ Simple test for running the graph_data function for profiling/testing performance. """
25 """ Simple test for running the graph_data function for profiling/testing performance. """
26 from kallithea.lib.graphmod import graph_data
26 from kallithea.lib.graphmod import graph_data
27 dbr = Repository.get_by_repo_name(repo)
27 dbr = db.Repository.get_by_repo_name(repo)
28 scm_inst = dbr.scm_instance
28 scm_inst = dbr.scm_instance
29 collection = scm_inst.get_changesets(start=0, end=None, branch_name=None)
29 collection = scm_inst.get_changesets(start=0, end=None, branch_name=None)
30 revs = [x.revision for x in collection]
30 revs = [x.revision for x in collection]
@@ -39,9 +39,8 b' from sqlalchemy import engine_from_confi'
39
39
40 import kallithea.config.application
40 import kallithea.config.application
41 from kallithea.lib.auth import get_crypt_password
41 from kallithea.lib.auth import get_crypt_password
42 from kallithea.model import meta
42 from kallithea.model import db, meta
43 from kallithea.model.base import init_model
43 from kallithea.model.base import init_model
44 from kallithea.model.db import Repository, Ui, User
45 from kallithea.tests.base import HG_REPO, TEST_USER_ADMIN_LOGIN, TEST_USER_ADMIN_PASS
44 from kallithea.tests.base import HG_REPO, TEST_USER_ADMIN_LOGIN, TEST_USER_ADMIN_PASS
46
45
47
46
@@ -88,18 +87,18 b' def create_test_user(force=True):'
88 print('creating test user')
87 print('creating test user')
89 sa = get_session()
88 sa = get_session()
90
89
91 user = sa.query(User).filter(User.username == USER).scalar()
90 user = sa.query(db.User).filter(db.User.username == USER).scalar()
92
91
93 if force and user is not None:
92 if force and user is not None:
94 print('removing current user')
93 print('removing current user')
95 for repo in sa.query(Repository).filter(Repository.user == user).all():
94 for repo in sa.query(db.Repository).filter(db.Repository.user == user).all():
96 sa.delete(repo)
95 sa.delete(repo)
97 sa.delete(user)
96 sa.delete(user)
98 sa.commit()
97 sa.commit()
99
98
100 if user is None or force:
99 if user is None or force:
101 print('creating new one')
100 print('creating new one')
102 new_usr = User()
101 new_usr = db.User()
103 new_usr.username = USER
102 new_usr.username = USER
104 new_usr.password = get_crypt_password(PASS)
103 new_usr.password = get_crypt_password(PASS)
105 new_usr.email = 'mail@example.com'
104 new_usr.email = 'mail@example.com'
@@ -118,11 +117,11 b' def create_test_repo(force=True):'
118 from kallithea.model.repo import RepoModel
117 from kallithea.model.repo import RepoModel
119 sa = get_session()
118 sa = get_session()
120
119
121 user = sa.query(User).filter(User.username == USER).scalar()
120 user = sa.query(db.User).filter(db.User.username == USER).scalar()
122 if user is None:
121 if user is None:
123 raise Exception('user not found')
122 raise Exception('user not found')
124
123
125 repo = sa.query(Repository).filter(Repository.repo_name == HG_REPO).scalar()
124 repo = sa.query(db.Repository).filter(db.Repository.repo_name == HG_REPO).scalar()
126
125
127 if repo is None:
126 if repo is None:
128 print('repo not found creating')
127 print('repo not found creating')
@@ -140,7 +139,7 b' def create_test_repo(force=True):'
140
139
141 def set_anonymous_access(enable=True):
140 def set_anonymous_access(enable=True):
142 sa = get_session()
141 sa = get_session()
143 user = sa.query(User).filter(User.username == 'default').one()
142 user = sa.query(db.User).filter(db.User.username == 'default').one()
144 user.active = enable
143 user.active = enable
145 sa.add(user)
144 sa.add(user)
146 sa.commit()
145 sa.commit()
@@ -148,7 +147,7 b' def set_anonymous_access(enable=True):'
148
147
149 def get_anonymous_access():
148 def get_anonymous_access():
150 sa = get_session()
149 sa = get_session()
151 return sa.query(User).filter(User.username == 'default').one().active
150 return sa.query(db.User).filter(db.User.username == 'default').one().active
152
151
153
152
154 #==============================================================================
153 #==============================================================================
@@ -156,7 +155,7 b' def get_anonymous_access():'
156 #==============================================================================
155 #==============================================================================
157 def test_clone_with_credentials(no_errors=False, repo=HG_REPO, method=METHOD,
156 def test_clone_with_credentials(no_errors=False, repo=HG_REPO, method=METHOD,
158 backend='hg'):
157 backend='hg'):
159 cwd = path = os.path.join(Ui.get_by_key('paths', '/').ui_value, repo)
158 cwd = path = os.path.join(db.Ui.get_by_key('paths', '/').ui_value, repo)
160
159
161 try:
160 try:
162 shutil.rmtree(path, ignore_errors=True)
161 shutil.rmtree(path, ignore_errors=True)
General Comments 0
You need to be logged in to leave comments. Login now