本文整理汇总了Python中pyramid.security.remember函数的典型用法代码示例。如果您正苦于以下问题:Python remember函数的具体用法?Python remember怎么用?Python remember使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了remember函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: client_oauth_register
def client_oauth_register(request, regdict):
nxt = request.route_url('main')
loc = get_localizer(request)
headers = None
cfg = request.registry.settings
mailer = get_mailer(request)
errors = {}
sess = DBSession()
login = regdict.get('username', None)
passwd = regdict.get('password', None)
email = regdict.get('email', None)
name_family = regdict.get('familyname', '')
name_given = regdict.get('givenname', '')
if login is not None and passwd is not None:
q = sess.query(User).filter(User.name == login)
logincount = q.count()
if logincount == 1:
if q is not None:
for user in q:
if user.password == passwd and user.name == login:
headers = remember(request, login)
return headers
else:
request.session.flash({
'class' : 'warning',
'text' : request.translate(_('Пользователь с таким именем уже есть. Мы не знаем что вам делать'))
})
return False
else:
if headers is None:
try:
usr = User(login, passwd)
usr.email = email
usr.admin = 0
sess.add(usr)
#email user credentials to a given email
sess.flush()
headers = remember(request, login)
message = Message(subject=request.translate(_("Новая учетная запись на lietlahti-park.ru")),
sender="[email protected]",
recipients=[email,],
body="{0}: login - {1}, password - {2}".format(request.translate(_("Добро пожаловать на наш сайт, надеемся, что вам тут понравится. Ваши учетные данные")), login, passwd))
mailer.send(message)
transaction.commit()
return headers
except IntegrityError:
sess.rollback()
request.session.flash({
'class' : 'warning',
'text' : request.translate(_('Пользователь с таким именем уже есть. Мы работаем над этой проблемой :('))
})
return False
else:
return False
示例2: callback
def callback(self):
"""Receive an authorization code and log in the user.
"""
request = self.request
code = request.params.get('code')
state = request.params.get('state')
if not code or not state:
return HTTPBadRequest("Missing code or state parameters")
session = request.session
session_state = session.get(self.session_prefix + 'state')
if session_state != state:
# CSRF protection
return HTTPBadRequest(body="Incorrect state value")
self.prepare_access_token(code)
userid = self.get_userid()
if userid:
remember(request, userid)
location = session.get(self.session_prefix + 'came_from')
if not location:
location = request.application_url
headers = [('Cache-Control', 'no-cache')]
return HTTPFound(location=location, headers=headers)
示例3: connect_user
def connect_user(request, form_datas):
"""
Effectively connect the user
:param obj request: The pyramid Request object
:pram dict form_datas: Validated form_datas
"""
login = form_datas['login']
login_id = Login.id_from_login(login)
log.info(
u" + '{0}' id : {1} has been authenticated".format(
login, login_id
)
)
# Storing the form_datas in the request object
remember(request, login)
remember_me = form_datas.get('remember_me', False)
if remember_me:
log.info(" * The user wants to be remembered")
longtimeout = get_longtimeout()
request.response.set_cookie(
'remember_me',
"ok",
max_age=longtimeout,
)
示例4: view_login
def view_login(request):
"""
View for login form and logging in.
"""
failed = False
reason = None
if request.POST:
# login request submitted:
name = request.POST.getone('name')
password = request.POST.getone('password')
try:
user = DBSession.query(User).filter_by(name=name).one()
except NoResultFound:
failed = True
reason = u'That password is not correct for that user.'
else:
if user.check_password(password):
# password correct, log in user for this session:
security.remember(request, user)
raise HTTPFound('/')
else:
failed = True
reason = u'That password is not correct for that user.'
return {
'Title': 'Login',
'failed': failed,
'reason': reason,
}
示例5: velruse_complete
def velruse_complete(context, request):
email = context.profile.get('verifiedEmail')
user = DBSession.query(User).get(email)
if not user:
session = DBSession()
try:
given_name, family_name = context.profile['displayName'].split(' ')
except ValueError:
given_name = context.profile['displayName']
family_name = context.profile['displayName']
user = User(given_name=given_name,
family_name=family_name,
email=context.profile.get('verifiedEmail'))
session.add(user)
headers = remember(request, user.email)
request.session.flash({'title': u'Zarejestrowany',
'body': u'Witamy w Szkole Czytania. Twoje konto zostało utworzone.'},
queue='success')
return HTTPFound(location='/profile', headers=headers)
request.session.flash({'title': u'Zalogowany',
'body': u'Witamy w Szkole Czytania!'},
queue='success')
headers = remember(request, user.email)
return HTTPFound(location='/', headers=headers)
示例6: login_view
def login_view(request):
"""
Login view
"""
log.debug("# Login page")
form = Form(authSchema,
buttons=(Button(name="submit",
title="Valider",
type='submit'),))
nextpage = request.params.get('nextpage') or request.route_url('index')
app_struct = {'nextpage':nextpage}
myform = form.render(app_struct)
fail_message = None
if 'submit' in request.params:
log.debug(" + Validating authentication")
controls = request.params.items()
try:
datas = form.validate(controls)
except ValidationFailure, err:
log.debug("Erreur d'authentification")
myform = err.render()
request.session.flash(_(request, u"Authentication error"), "error")
return {'title':"Login page",
'form':myform,}
log.debug(" + Validation ok, redirecting")
log.debug(" -> {0}".format(nextpage))
login = datas['login']
# Storing the datas in the session
remember(request, login)
return HTTPFound(location=nextpage)
示例7: login
def login(request):
login_url = request.route_url('login')
referrer = request.url
if referrer == login_url:
referrer = '/'
came_from = request.params.get('came_from', referrer)
message = ''
login = ''
if 'form.submitted' in request.params:
login = request.params['login']
user = request.db.get_user(login)
if user is None: # new account
if 'facebook_id' in request.params: # TODO: check if existing user w/ same facebook_id
user = User(dict(
facebook_id = int(request.params['facebook_id']),
username = login,
name = request.params['name'],
interests = []
))
request.db.insert_user(user)
headers = remember(request, login)
request.session['user'] = user
return HTTPFound(location = came_from, headers = headers)
else:
if 'facebook_id' in request.params and user.facebook_id == int(request.params['facebook_id']):
headers = remember(request, login)
request.session['user'] = user
return HTTPFound(location = came_from, headers = headers)
else:
message = 'Mismatch with Facebook'
return dict(message = message, url = request.application_url + '/login', came_from = came_from, login = login)
示例8: login_view
def login_view(request):
if request.method == 'POST' or 'logged_session_id' in request.session:
if request.POST.get('UserName') and request.POST.get('Password'):
passw=set_password(request.POST.get('Password'))
usr=DBSession.query(Users).filter_by(name=request.POST['UserName'],password=passw).first()
if usr:
request.session.flash('Welcome!')
request.session['logged_in']='yes'
#request.session['logged_in_id']=usr.id
#request.session['logged_in_group']=usr.group
Sessiontimeoutime=datetime.now() + timedelta(minutes = 10)
newSessionObj = Login_Session(userid=usr.id,group=usr.group,timeout=Sessiontimeoutime)
DBSession.add(newSessionObj)
log=DBSession.query(Login_Session).filter_by(userid=usr.id).order_by(Login_Session.id.desc()).first()
request.session['logged_session_id']=log.id
headers = remember(request,usr.group)
return HTTPFound(location=request.route_url('list'),headers=headers)
else:
request.session.flash('Please enter a valid User Name or Password!')
return HTTPFound(location=request.route_url('login'))
elif 'logged_session_id' in request.session and check_session(request.session['logged_session_id']):
session_login =DBSession.query(Login_Session).filter_by(id=request.session['logged_session_id'])
headers = remember(request,session_login.group)
request.session.flash('Welcome Back !')
return HTTPFound(location=request.route_url('list'),headers=headers)
else:
request.session.flash('Please enter a User Name or Password!')
return HTTPFound(location=request.route_url('login'))
return {}
示例9: login
def login(request):
login_url = request.route_url('login')
referrer = request.url
if referrer == login_url:
referrer = '/' # never use the login form itself as came_from
came_from = request.params.get('came_from', referrer)
message = ''
login = 'admin'
password = ''
from utils.password import get_password
if 'form.submitted' in request.params:
login = request.params['login']
password = request.params['password']
try:
if get_password() == password:
headers = remember(request, login)
return HTTPFound(location = came_from, headers = headers)
except:
if USERS.get(login) == password:
headers = remember(request, login)
return HTTPFound(location = came_from, headers = headers)
message = 'Failed login'
return dict(
message = message,
url = request.application_url + '/login',
came_from = came_from,
login = login,
password = password,
)
示例10: login
def login(request):
message = None
form = Form(request, schema=UserSchema())
if request.method == 'POST' and form.validate():
username = request.params['username']
password = request.params['password']
password_again = request.params['password_again']
if bool(password_again):
if password == password_again:
user = form.bind(User())
DBSession.add(user)
DBSession.flush()
user_id = user.id
headers = remember(request, user.id)
return HTTPFound(location='/', headers=headers)
else:
message = 'Passwords do not match.'
else:
user = DBSession.query(User).filter(User.username==username).first()
if user and user.password == password:
headers = remember(request, user.id)
return HTTPFound(location='/', headers=headers)
else:
message = 'Username or password is incorrect.'
return {
'message': message,
'form': form,
'renderer': FormRenderer(form),
'user': get_user(request),
}
示例11: __acl__
def __acl__(self):
# Get the remote address
remote_addr = self.request.remote_addr
header = 'remote_addr'
if 'X-Real-IP' in self.request.headers:
remote_addr = self.request.headers['X-Real-IP']
header = 'X-Real-IP'
if 'X-Forwarded-For' in self.request.headers:
remote_addr = self.request.headers['X-Forwarded-For']
header = 'X-Forwarded-For'
logger.debug('InternalAccessFactory: remote_addr=%s header=%s (%s)'%(remote_addr, header, str(self.request.headers.items())))
# Check if the remote IP address is localhost
if remote_addr == '127.0.0.1' or remote_addr == '::1':
logger.debug('InternalAccessFactory: access allowed for localhost: %s'%(remote_addr))
remember(self.request, 'localhost_access')
return [(Allow, Everyone, 'view')]
server_list = self.request.db.servers.find()
# Check if the remote IP address belongs to a GECOSCC server
for server in server_list:
if server['address'] == remote_addr:
logger.debug('InternalAccessFactory: access allowed for GECOS CC server: %s'%(server['name']))
remember(self.request, server['name'])
return [(Allow, Everyone, 'view')]
logger.debug('InternalAccessFactory: forbidden access for %s'%(remote_addr))
raise HTTPForbidden('Internal access only')
示例12: login_with_participation_code
def login_with_participation_code(request):
# This view handles the outcome of authentication performed by the
# identity provider.
now = datetime.utcnow()
json_request = request.json_body
code = json_request.get('code')
if code is None:
return {'error': 'missing code'}
participation_id = find_participation_by_code(request.db, code)
if participation_id is None:
return {'error': 'no such participation'}
participation = load_participation(request.db, participation_id)
team_id = participation['team_id']
user_id = get_team_creator(request.db, team_id)
mark_participation_code_entered(request.db, participation_id, now)
request.db.commit()
# Clear the user's cached principals to force them to be refreshed.
reset_user_principals(request)
remember(request, str(user_id))
# The view template posts the result (encoded as JSON) to the parent
# window, causing the frontend to update its state.
return {
'success': True,
'user_id': user_id,
'csrf_token': request.session.get_csrf_token()
}
示例13: oauth_callback_view
def oauth_callback_view(request):
# This view handles the outcome of authentication performed by the
# identity provider.
error = request.params.get('error')
if error is not None:
message = format_error_value(request.params)
return {'error': message}
try:
accept_oauth2_code(request)
except AuthenticationError as ex:
return {'error': str(ex)}
# Get the user identity (refreshing the token should not be needed).
profile = get_user_profile(request, refresh=False)
# Make pyramid remember the user's id.
user_id = find_user_by_foreign_id(request.db, profile['idUser'])
if user_id is None:
user_id = import_user(request.db, profile, now=datetime.utcnow())
else:
update_user(request.db, user_id, profile)
request.db.commit()
# Clear the user's cached principals to force them to be refreshed.
reset_user_principals(request)
remember(request, str(user_id))
# The view template posts the result (encoded as JSON) to the parent
# window, causing the frontend to update its state.
# The Origin header is passed to the template to limit recipients.
# Pass the CSRF token to the login window so that it can send it to
# the front.
return {
'user_id': user_id,
'csrf_token': request.session.get_csrf_token(),
'origin': request.headers.get('Origin')
}
示例14: login
def login(request):
user_id = request.POST.get('userId', '')
pwd = request.POST.get('password', '')
user = DBSession.query(User).filter(User.id==user_id).one()
if user is not None and user.check_password(pwd):
table = Base.metadata.tables['VAllUsersApplications']
query = select([
table
]).where((table.c['TSit_Name'] == dbConfig['siteName']) & (table.c['TUse_PK_ID'] == user_id) & (table.c['TRol_Label'] != 'Interdit')).order_by(table.c['TIns_Order'])
result = DBSession.execute(query).fetchall()
claims = {
"iss": user_id,
"sub": user_id,
"username": user.Login,
"userlanguage": user.Language,
"roles" : {
row.TIns_Label : row.TRol_Label for row in result
}
}
jwt = make_jwt(request, claims)
response = Response(body='login success', content_type='text/plain')
remember(response, jwt)
transaction.commit()
return response
else:
transaction.commit()
return HTTPUnauthorized()
示例15: post
def post(self):
form = self.get_form()
if not form.validate():
return self.response
security.remember(self.request, 'admin_user')
redirect_url = self.request.params.get('next') or '/'
return HTTPFound(redirect_url)