##// END OF EJS Templates
Use HttpFound response in login....
marcink -
r2623:44678a64 beta
parent child Browse files
Show More
@@ -1,169 +1,183
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 rhodecode.controllers.login
3 rhodecode.controllers.login
4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
5
5
6 Login controller for rhodeocode
6 Login controller for rhodeocode
7
7
8 :created_on: Apr 22, 2010
8 :created_on: Apr 22, 2010
9 :author: marcink
9 :author: marcink
10 :copyright: (C) 2010-2012 Marcin Kuzminski <marcin@python-works.com>
10 :copyright: (C) 2010-2012 Marcin Kuzminski <marcin@python-works.com>
11 :license: GPLv3, see COPYING for more details.
11 :license: GPLv3, see COPYING for more details.
12 """
12 """
13 # This program is free software: you can redistribute it and/or modify
13 # This program is free software: you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation, either version 3 of the License, or
15 # the Free Software Foundation, either version 3 of the License, or
16 # (at your option) any later version.
16 # (at your option) any later version.
17 #
17 #
18 # This program is distributed in the hope that it will be useful,
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
21 # GNU General Public License for more details.
22 #
22 #
23 # You should have received a copy of the GNU General Public License
23 # You should have received a copy of the GNU General Public License
24 # along with this program. If not, see <http://www.gnu.org/licenses/>.
24 # along with this program. If not, see <http://www.gnu.org/licenses/>.
25
25
26 import logging
26 import logging
27 import formencode
27 import formencode
28 import datetime
28
29
29 from formencode import htmlfill
30 from formencode import htmlfill
30
31 from webob.exc import HTTPFound
31 from pylons.i18n.translation import _
32 from pylons.i18n.translation import _
32 from pylons.controllers.util import abort, redirect
33 from pylons.controllers.util import abort, redirect
33 from pylons import request, response, session, tmpl_context as c, url
34 from pylons import request, response, session, tmpl_context as c, url
34
35
35 import rhodecode.lib.helpers as h
36 import rhodecode.lib.helpers as h
36 from rhodecode.lib.auth import AuthUser, HasPermissionAnyDecorator
37 from rhodecode.lib.auth import AuthUser, HasPermissionAnyDecorator
37 from rhodecode.lib.base import BaseController, render
38 from rhodecode.lib.base import BaseController, render
38 from rhodecode.model.db import User
39 from rhodecode.model.db import User
39 from rhodecode.model.forms import LoginForm, RegisterForm, PasswordResetForm
40 from rhodecode.model.forms import LoginForm, RegisterForm, PasswordResetForm
40 from rhodecode.model.user import UserModel
41 from rhodecode.model.user import UserModel
41 from rhodecode.model.meta import Session
42 from rhodecode.model.meta import Session
42
43
43
44
45
44 log = logging.getLogger(__name__)
46 log = logging.getLogger(__name__)
45
47
46
48
47 class LoginController(BaseController):
49 class LoginController(BaseController):
48
50
49 def __before__(self):
51 def __before__(self):
50 super(LoginController, self).__before__()
52 super(LoginController, self).__before__()
51
53
52 def index(self):
54 def index(self):
53 # redirect if already logged in
55 # redirect if already logged in
54 c.came_from = request.GET.get('came_from', None)
56 c.came_from = request.GET.get('came_from', None)
55
57
56 if self.rhodecode_user.is_authenticated \
58 if self.rhodecode_user.is_authenticated \
57 and self.rhodecode_user.username != 'default':
59 and self.rhodecode_user.username != 'default':
58
60
59 return redirect(url('home'))
61 return redirect(url('home'))
60
62
61 if request.POST:
63 if request.POST:
62 # import Login Form validator class
64 # import Login Form validator class
63 login_form = LoginForm()
65 login_form = LoginForm()
64 try:
66 try:
67 session.invalidate()
65 c.form_result = login_form.to_python(dict(request.POST))
68 c.form_result = login_form.to_python(dict(request.POST))
66 # form checks for username/password, now we're authenticated
69 # form checks for username/password, now we're authenticated
67 username = c.form_result['username']
70 username = c.form_result['username']
68 user = User.get_by_username(username, case_insensitive=True)
71 user = User.get_by_username(username, case_insensitive=True)
69 auth_user = AuthUser(user.user_id)
72 auth_user = AuthUser(user.user_id)
70 auth_user.set_authenticated()
73 auth_user.set_authenticated()
71 cs = auth_user.get_cookie_store()
74 cs = auth_user.get_cookie_store()
72 session['rhodecode_user'] = cs
75 session['rhodecode_user'] = cs
76 user.update_lastlogin()
77 Session().commit()
78
73 # If they want to be remembered, update the cookie
79 # If they want to be remembered, update the cookie
74 if c.form_result['remember'] is not False:
80 if c.form_result['remember'] is not False:
75 session.cookie_expires = False
81 _year = (datetime.datetime.now() +
76 session._set_cookie_values()
82 datetime.timedelta(seconds=60 * 60 * 24 * 365))
77 session._update_cookie_out()
83 session._set_cookie_expires(_year)
84
78 session.save()
85 session.save()
79
86
80 log.info('user %s is now authenticated and stored in '
87 log.info('user %s is now authenticated and stored in '
81 'session, session attrs %s' % (username, cs))
88 'session, session attrs %s' % (username, cs))
82 user.update_lastlogin()
89
83 Session.commit()
90 # dumps session attrs back to cookie
91 session._update_cookie_out()
92
93 # we set new cookie
94 headers = None
95 if session.request['set_cookie']:
96 # send set-cookie headers back to response to update cookie
97 headers = [('Set-Cookie', session.request['cookie_out'])]
84
98
85 if c.came_from:
99 if c.came_from:
86 return redirect(c.came_from)
100 raise HTTPFound(location=c.came_from, headers=headers)
87 else:
101 else:
88 return redirect(url('home'))
102 raise HTTPFound(location=url('home'), headers=headers)
89
103
90 except formencode.Invalid, errors:
104 except formencode.Invalid, errors:
91 return htmlfill.render(
105 return htmlfill.render(
92 render('/login.html'),
106 render('/login.html'),
93 defaults=errors.value,
107 defaults=errors.value,
94 errors=errors.error_dict or {},
108 errors=errors.error_dict or {},
95 prefix_error=False,
109 prefix_error=False,
96 encoding="UTF-8")
110 encoding="UTF-8")
97
111
98 return render('/login.html')
112 return render('/login.html')
99
113
100 @HasPermissionAnyDecorator('hg.admin', 'hg.register.auto_activate',
114 @HasPermissionAnyDecorator('hg.admin', 'hg.register.auto_activate',
101 'hg.register.manual_activate')
115 'hg.register.manual_activate')
102 def register(self):
116 def register(self):
103 c.auto_active = False
117 c.auto_active = False
104 for perm in User.get_by_username('default').user_perms:
118 for perm in User.get_by_username('default').user_perms:
105 if perm.permission.permission_name == 'hg.register.auto_activate':
119 if perm.permission.permission_name == 'hg.register.auto_activate':
106 c.auto_active = True
120 c.auto_active = True
107 break
121 break
108
122
109 if request.POST:
123 if request.POST:
110
124
111 register_form = RegisterForm()()
125 register_form = RegisterForm()()
112 try:
126 try:
113 form_result = register_form.to_python(dict(request.POST))
127 form_result = register_form.to_python(dict(request.POST))
114 form_result['active'] = c.auto_active
128 form_result['active'] = c.auto_active
115 UserModel().create_registration(form_result)
129 UserModel().create_registration(form_result)
116 h.flash(_('You have successfully registered into rhodecode'),
130 h.flash(_('You have successfully registered into rhodecode'),
117 category='success')
131 category='success')
118 Session.commit()
132 Session().commit()
119 return redirect(url('login_home'))
133 return redirect(url('login_home'))
120
134
121 except formencode.Invalid, errors:
135 except formencode.Invalid, errors:
122 return htmlfill.render(
136 return htmlfill.render(
123 render('/register.html'),
137 render('/register.html'),
124 defaults=errors.value,
138 defaults=errors.value,
125 errors=errors.error_dict or {},
139 errors=errors.error_dict or {},
126 prefix_error=False,
140 prefix_error=False,
127 encoding="UTF-8")
141 encoding="UTF-8")
128
142
129 return render('/register.html')
143 return render('/register.html')
130
144
131 def password_reset(self):
145 def password_reset(self):
132 if request.POST:
146 if request.POST:
133 password_reset_form = PasswordResetForm()()
147 password_reset_form = PasswordResetForm()()
134 try:
148 try:
135 form_result = password_reset_form.to_python(dict(request.POST))
149 form_result = password_reset_form.to_python(dict(request.POST))
136 UserModel().reset_password_link(form_result)
150 UserModel().reset_password_link(form_result)
137 h.flash(_('Your password reset link was sent'),
151 h.flash(_('Your password reset link was sent'),
138 category='success')
152 category='success')
139 return redirect(url('login_home'))
153 return redirect(url('login_home'))
140
154
141 except formencode.Invalid, errors:
155 except formencode.Invalid, errors:
142 return htmlfill.render(
156 return htmlfill.render(
143 render('/password_reset.html'),
157 render('/password_reset.html'),
144 defaults=errors.value,
158 defaults=errors.value,
145 errors=errors.error_dict or {},
159 errors=errors.error_dict or {},
146 prefix_error=False,
160 prefix_error=False,
147 encoding="UTF-8")
161 encoding="UTF-8")
148
162
149 return render('/password_reset.html')
163 return render('/password_reset.html')
150
164
151 def password_reset_confirmation(self):
165 def password_reset_confirmation(self):
152 if request.GET and request.GET.get('key'):
166 if request.GET and request.GET.get('key'):
153 try:
167 try:
154 user = User.get_by_api_key(request.GET.get('key'))
168 user = User.get_by_api_key(request.GET.get('key'))
155 data = dict(email=user.email)
169 data = dict(email=user.email)
156 UserModel().reset_password(data)
170 UserModel().reset_password(data)
157 h.flash(_('Your password reset was successful, '
171 h.flash(_('Your password reset was successful, '
158 'new password has been sent to your email'),
172 'new password has been sent to your email'),
159 category='success')
173 category='success')
160 except Exception, e:
174 except Exception, e:
161 log.error(e)
175 log.error(e)
162 return redirect(url('reset_password'))
176 return redirect(url('reset_password'))
163
177
164 return redirect(url('login_home'))
178 return redirect(url('login_home'))
165
179
166 def logout(self):
180 def logout(self):
167 session.delete()
181 session.delete()
168 log.info('Logging out and deleting session for user')
182 log.info('Logging out and deleting session for user')
169 redirect(url('home'))
183 redirect(url('home'))
General Comments 0
You need to be logged in to leave comments. Login now