__init__.py
5.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import logging
from datetime import timedelta
import colander
from deform import (
Form, ValidationFailure, widget, Button, )
from opensipkd.tools.api import JsonRpcInvalidLoginError
from pyramid.httpexceptions import (
HTTPFound, HTTPForbidden, HTTPNotFound, HTTPInternalServerError,
HTTPSeeOther)
from pyramid.i18n import TranslationStringFactory
from pyramid.interfaces import IRoutesMapper
from pyramid.renderers import render_to_response
from pyramid.response import Response
from pyramid.security import remember
from pyramid.view import view_config
from opensipkd.base import get_params, get_urls
from opensipkd.base.tools.api import rpc_auth
from .base_views import BaseView
from opensipkd.models import (
DBSession, UserService, )
from .common import DataTables, ColumnDT
from pyramid.csrf import new_csrf_token
_ = TranslationStringFactory('login')
log = logging.getLogger(__name__)
@view_config(context=HTTPNotFound, renderer='templates/404.pt')
def not_found(request):
path = request.path
registry = request.registry
mapper = registry.queryUtility(IRoutesMapper)
if mapper is not None and path.endswith('/'):
noslash_path = path.rstrip('/')
for route in mapper.get_routes():
if route.match(noslash_path) is not None:
qs = request.query_string
if qs:
noslash_path += '?' + qs
return HTTPFound(location=noslash_path)
request.response.status = 404
return {}
@view_config(context=HTTPInternalServerError, renderer='templates/500.pt')
def internal_server_error(request):
return {}
# response = Response('Terjadi kesahala')
# response.status_int = 500
# return response
########
# Home #
########
class Home(BaseView):
@view_config(route_name='home', renderer='templates/home.pt')
def view_home(self):
request = self.req
# session = request.session
modules = request.menus
modules_default = get_params('modules_default')
submodules_default = get_params('submenus')
# request.session['modules'] = modules
# request.session['modules_default'] = modules_default
log.info(request.session.peek_flash())
if modules_default:
if request.user and request.has_permission(modules_default):
return HTTPFound(location=get_urls(request.route_url(modules_default)))
elif request.user and len(request.session.peek_flash('error')) < 2:
return HTTPFound(location=get_urls(request.route_url(modules_default)))
elif not request.user:
return HTTPFound(location=get_urls(request.route_url(modules_default)))
logo = get_params('logo', "static/img/logo.png")
home_tpl = get_params("home_tpl")
if home_tpl:
return render_to_response(
home_tpl,
dict(modules=modules, logo=logo, submodules=[]),
request=request
)
return dict(modules=modules, logo=logo, submodules=[])
@view_config(context=HTTPForbidden, renderer='templates/403.pt')
def http_forbidden(request):
if not request.is_authenticated:
next_url = get_urls(request.route_url('login', _query={'next': request.url}))
return HTTPSeeOther(location=next_url)
request.response.status = 403
return {"url": request.url}
###################
# Change password #
###################
class Password(colander.Schema):
old_password = colander.SchemaNode(
colander.String(), widget=widget.PasswordWidget())
new_password = colander.SchemaNode(
colander.String(), widget=widget.CheckedPasswordWidget())
# retype_password = colander.SchemaNode(
# colander.String(), widget=widget.PasswordWidget())
def password_validator(form, value):
if not UserService.check_password(form.request.user, value['old_password']):
raise colander.Invalid(form, 'Invalid old password.')
# if value['new_password'] != value['retype_password']:
# raise colander.Invalid(form, 'Retype mismatch.')
@view_config(
route_name='password', renderer='templates/chg_password.pt',
permission='view')
def view_password(request):
schema = Password(validator=password_validator)
btn_save = Button('save', _('Simpan'))
btn_cancel = Button('cancel', _('Batal'))
buttons = (btn_save, btn_cancel)
form = Form(schema, buttons=buttons)
if not request.POST:
return dict(form=form.render())
if 'save' not in request.POST:
return HTTPFound(location=request._host)
schema.request = request
controls = request.POST.items()
try:
c = form.validate(controls)
except ValidationFailure as e:
return dict(form=e.render())
UserService.set_password(request.user, c['new_password'])
DBSession.add(request.user)
request.session.flash('Password baru Anda sudah disimpan.')
return HTTPFound(location=request._host)
######################################
# Change password with security code #
######################################
one_hour = timedelta(1.0 / 24)
two_minutes = timedelta(1.0 / 24 / 60)
@colander.deferred
def deferred_jenis(node, kw):
values = kw.get('daftar_jenis', [])
return widget.RadioChoiceWidget(values=values)