##// END OF EJS Templates
cleared prints leftoovers, and changed current user fetching in login controller
marcink -
r195:7109d15c default
parent child Browse files
Show More
@@ -1,37 +1,38 b''
1 1 import logging
2 2 from formencode import htmlfill
3 3 from pylons import request, response, session, tmpl_context as c, url
4 4 from pylons.controllers.util import abort, redirect
5 5 from pylons_app.lib.base import BaseController, render
6 6 import formencode
7 7 from pylons_app.model.forms import LoginForm
8 8 from pylons_app.lib.auth import AuthUser
9 9
10 10 log = logging.getLogger(__name__)
11 11
12 12 class LoginController(BaseController):
13 13
14 14 def index(self):
15 if session.get('hg_app_user', AuthUser()).is_authenticated:
15 #redirect if already logged in
16 if c.hg_app_user.is_authenticated:
16 17 return redirect(url('hg_home'))
17 18
18 19 if request.POST:
19 20 #import Login Form validator class
20 21 login_form = LoginForm()
21 22 try:
22 23 c.form_result = login_form.to_python(dict(request.POST))
23 24 return redirect(url('hg_home'))
24 25
25 26 except formencode.Invalid as errors:
26 27 c.form_errors = errors.error_dict
27 28 return htmlfill.render(
28 29 render('/login.html'),
29 30 defaults=errors.value,
30 31 encoding="UTF-8")
31 32
32 33 return render('/login.html')
33 34
34 35 def logout(self):
35 36 session['hg_app_user'] = AuthUser()
36 37 session.save()
37 38 redirect(url('hg_home'))
@@ -1,126 +1,125 b''
1 1 """ this is forms validation classes
2 2 http://formencode.org/module-formencode.validators.html
3 3 for list off all availible validators
4 4
5 5 we can create our own validators
6 6
7 7 The table below outlines the options which can be used in a schema in addition to the validators themselves
8 8 pre_validators [] These validators will be applied before the schema
9 9 chained_validators [] These validators will be applied after the schema
10 10 allow_extra_fields False If True, then it is not an error when keys that aren't associated with a validator are present
11 11 filter_extra_fields False If True, then keys that aren't associated with a validator are removed
12 12 if_key_missing NoDefault If this is given, then any keys that aren't available but are expected will be replaced with this value (and then validated). This does not override a present .if_missing attribute on validators. NoDefault is a special FormEncode class to mean that no default values has been specified and therefore missing keys shouldn't take a default value.
13 13 ignore_key_missing False If True, then missing keys will be missing in the result, if the validator doesn't have .if_missing on it already
14 14
15 15
16 16 <name> = formencode.validators.<name of validator>
17 17 <name> must equal form name
18 18 list=[1,2,3,4,5]
19 19 for SELECT use formencode.All(OneOf(list), Int())
20 20
21 21 """
22 22 from formencode.validators import UnicodeString, OneOf, Int, Number, Regex
23 23 from pylons import session
24 24 from pylons.i18n.translation import _
25 25 from pylons_app.lib.auth import get_crypt_password
26 26 from pylons_app.model import meta
27 27 from pylons_app.model.db import Users
28 28 from sqlalchemy.exc import OperationalError
29 29 from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
30 30 from webhelpers.pylonslib.secure_form import authentication_token
31 31 import formencode
32 32 import logging
33 33 log = logging.getLogger(__name__)
34 34
35 35
36 36 #this is needed to translate the messages using _() in validators
37 37 class State_obj(object):
38 38 _ = staticmethod(_)
39 39
40 40 #===============================================================================
41 41 # VALIDATORS
42 42 #===============================================================================
43 43 class ValidAuthToken(formencode.validators.FancyValidator):
44 44 messages = {'invalid_token':_('Token mismatch')}
45 45
46 46 def validate_python(self, value, state):
47 47
48 48 if value != authentication_token():
49 49 raise formencode.Invalid(self.message('invalid_token', state,
50 50 search_number=value), value, state)
51 51
52 52 class ValidAuth(formencode.validators.FancyValidator):
53 53 messages = {
54 54 'invalid_password':_('invalid password'),
55 55 'invalid_login':_('invalid user name'),
56 56 'disabled_account':_('Your acccount is disabled')
57 57
58 58 }
59 59 #error mapping
60 60 e_dict = {'username':messages['invalid_login'],
61 61 'password':messages['invalid_password']}
62 62
63 63 def validate_python(self, value, state):
64 64 sa = meta.Session
65 65 crypted_passwd = get_crypt_password(value['password'])
66 66 username = value['username']
67 67 try:
68 68 user = sa.query(Users).filter(Users.username == username).one()
69 69 except (NoResultFound, MultipleResultsFound, OperationalError) as e:
70 70 log.error(e)
71 71 user = None
72 print value
73 72 if user:
74 73 if user.active:
75 74 if user.username == username and user.password == crypted_passwd:
76 75 log.info('user %s authenticated correctly', username)
77 76 from pylons_app.lib.auth import AuthUser
78 77 auth_user = AuthUser()
79 78 auth_user.username = username
80 79 auth_user.is_authenticated = True
81 80 auth_user.is_admin = user.admin
82 81 session['hg_app_user'] = auth_user
83 82 session.save()
84 83 return value
85 84 else:
86 85 log.warning('user %s not authenticated', username)
87 86 raise formencode.Invalid(self.message('invalid_password',
88 87 state=State_obj), value, state,
89 88 error_dict=self.e_dict)
90 89 else:
91 90 log.warning('user %s is disabled', username)
92 91 raise formencode.Invalid(self.message('disabled_account',
93 92 state=State_obj),
94 93 value, state, error_dict=self.e_dict)
95 94
96 95
97 96
98 97 #===============================================================================
99 98 # FORMS
100 99 #===============================================================================
101 100 class LoginForm(formencode.Schema):
102 101 allow_extra_fields = True
103 102 filter_extra_fields = True
104 103 username = UnicodeString(
105 104 strip=True,
106 105 min=3,
107 106 not_empty=True,
108 107 messages={
109 108 'empty':_('Please enter a login'),
110 109 'tooShort':_('Enter a value %(min)i characters long or more')}
111 110 )
112 111
113 112 password = UnicodeString(
114 113 strip=True,
115 114 min=3,
116 115 not_empty=True,
117 116 messages={
118 117 'empty':_('Please enter a password'),
119 118 'tooShort':_('Enter a value %(min)i characters long or more')}
120 119 )
121 120
122 121
123 122 #chained validators have access to all data
124 123 chained_validators = [ValidAuth]
125 124
126 125
@@ -1,66 +1,67 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 #
4 4 # Copyright (c) 2010 marcink. All rights reserved.
5 5 #
6 6 from vcs.exceptions import RepositoryError
7 7 '''
8 8 Created on Apr 9, 2010
9 9
10 10 @author: marcink
11 11 '''
12 12 import os
13 13 from pylons import tmpl_context as c, app_globals as g, session, request, config
14 14 from pylons.controllers.util import abort
15 import sys
15 16 try:
16 17 from vcs.backends.hg import get_repositories, MercurialRepository
17 18 except ImportError:
18 print 'You have to import vcs module'
19 sys.stderr.write('You have to import vcs module')
19 20 raise Exception('Unable to import vcs')
20 21
21 22 class HgModel(object):
22 23 """
23 24 Mercurial Model
24 25 """
25 26
26 27
27 28 def __init__(self):
28 29 """
29 30 Constructor
30 31 """
31 32 pass
32 33
33 34 def get_repos(self):
34 35 for mercurial_repo in get_repositories(g.paths[0][0], g.paths[0][1], g.baseui):
35 36
36 37 if mercurial_repo._get_hidden():
37 38 #skip hidden web repository
38 39 continue
39 40
40 41 last_change = mercurial_repo.last_change
41 42 try:
42 43 tip = mercurial_repo.get_changeset('tip')
43 44 except RepositoryError:
44 45 from pylons_app.lib.utils import EmptyChangeset
45 46 tip = EmptyChangeset()
46 47
47 48 tmp_d = {}
48 49 tmp_d['name'] = mercurial_repo.name
49 50 tmp_d['name_sort'] = tmp_d['name']
50 51 tmp_d['description'] = mercurial_repo.description
51 52 tmp_d['description_sort'] = tmp_d['description']
52 53 tmp_d['last_change'] = last_change
53 54 tmp_d['last_change_sort'] = last_change[1] - last_change[0]
54 55 tmp_d['tip'] = tip.raw_id
55 56 tmp_d['tip_sort'] = tip.revision
56 57 tmp_d['rev'] = tip.revision
57 58 tmp_d['contact'] = mercurial_repo.contact
58 59 tmp_d['contact_sort'] = tmp_d['contact']
59 60 tmp_d['repo_archives'] = list(mercurial_repo._get_archives())
60 61
61 62 yield tmp_d
62 63
63 64 def get_repo(self, repo_name):
64 65 path = g.paths[0][1].replace('*', '')
65 66 repo = MercurialRepository(os.path.join(path, repo_name), baseui=g.baseui)
66 67 return repo
General Comments 0
You need to be logged in to leave comments. Login now