• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python security.remember函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pyramid.security.remember函数的典型用法代码示例。如果您正苦于以下问题:Python remember函数的具体用法?Python remember怎么用?Python remember使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了remember函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:annndrey,项目名称:simplesite,代码行数:60,代码来源:views.py


示例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)
开发者ID:jkoelker,项目名称:pyramid_oauth2_client,代码行数:26,代码来源:abstract.py


示例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,
        )
开发者ID:CroissanceCommune,项目名称:autonomie,代码行数:25,代码来源:auth.py


示例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,
    }
开发者ID:kratenko,项目名称:gy,代码行数:28,代码来源:login_views.py


示例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)
开发者ID:SzkolaCzytania,项目名称:szcz.app,代码行数:26,代码来源:security.py


示例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)
开发者ID:faddai,项目名称:pyramidCrm,代码行数:30,代码来源:auth.py


示例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)
开发者ID:BairnOwl,项目名称:YHack,代码行数:32,代码来源:views.py


示例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 {}
开发者ID:raxitcholera,项目名称:pyramid,代码行数:33,代码来源:views.py


示例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,
        )
开发者ID:robert118,项目名称:ztq,代码行数:31,代码来源:views.py


示例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),
    }
开发者ID:strazdas,项目名称:task_tracker,代码行数:31,代码来源:views.py


示例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')
开发者ID:System25,项目名称:gecoscc-ui,代码行数:30,代码来源:permissions.py


示例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()
    }
开发者ID:France-ioi,项目名称:alkindi-backend,代码行数:26,代码来源:auth.py


示例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')
    }
开发者ID:France-ioi,项目名称:alkindi-backend,代码行数:33,代码来源:auth.py


示例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()
开发者ID:NaturalSolutions,项目名称:NsPortal,代码行数:28,代码来源:security.py


示例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)
开发者ID:attakei,项目名称:esauth,代码行数:7,代码来源:views.py


示例16: login_ajax

def login_ajax(request):
    if request.POST.get('login'):
        username = request.POST.get('username')
        password = request.POST.get('password')

        user_data = user.find_one({"username":username})
        if user_data and user_data['password'] == password:
            user_id = user_data['_id']
            headers = remember(request, str(user_id))
            return HTTPFound(location=request.route_url('public_room'),
                             headers=headers)
        else:
            return False

    if request.POST.get('signup'):
        username = request.POST.get('username')
        password = request.POST.get('password')

        user_data = user.find_one({"username":username})
        if user_data and user_data['username'] == username:
            return False
        else:
            user_data = {'username':username, 'password':password,\
                    'nickname':username, 'textcolor':'#000000'}
            user_id = user.insert(user_data)
            headers = remember(request, str(user_id))
            return HTTPFound(location=request.route_url('public_room'),
                             headers=headers)
开发者ID:WickyYao,项目名称:chat,代码行数:28,代码来源:views.py


示例17: verify_email

def verify_email(request):
    try:
        user_id = int(request.GET["user_id"].strip())
        email_address = request.GET["email_address"].strip()
        token = request.GET["token"].strip()
    except (KeyError, ValueError):
        raise HTTPNotFound
    stored_token = request.session.redis.get("verify:%s:%s" % (user_id, email_address))
    if not user_id or not email_address or not token or not stored_token:
        raise HTTPNotFound

    stored_token = stored_token.decode("utf-8")

    if not stored_token == token:
        raise HTTPNotFound

    if (
        request.db.query(func.count("*")).select_from(User)
        .filter(func.lower(User.email_address) == email_address.lower()).scalar()
    ):
        request.session.flash("There's already an account with that email address.")
        return HTTPFound(request.route_path("home"))

    try:
        user = request.db.query(User).filter(User.id == user_id).one()
    except NoResultFound:
        raise HTTPNotFound

    user.email_address = email_address
    user.email_verified = True

    remember(request, user.id)
    request.session.flash("Your email address has been verified.")

    return HTTPFound(request.route_path("home"))
开发者ID:MSPARP,项目名称:logcabin,代码行数:35,代码来源:account.py


示例18: authenticate

    def authenticate(self):
        """
        The token endpoint is used by the client to obtain an access token by
        presenting its authorization grant or refresh token. The token
        endpoint is used with every authorization grant except for the
        implicit grant type (since an access token is issued directly).
        """
        user = self.request.params.get('nm_user')
        passwd = self.request.params.get('passwd_user')

        if user is None:
            raise Exception('Required parameter nm_user not found in the request')
        elif passwd is None:
            raise Exception("Required parameter 'passwd_user' not found in the request")

        if user == config.ADMIN_USER and passwd == config.ADMIN_PASSWD:
            headers = remember(self.request, user)
            return Response('OK', headers=headers)

        member = self.context.get_member(user)
        if not member:
            raise Exception('No such User!')

        if member.passwd_user != passwd:
            raise Exception('Invalid Password!')

        headers = remember(self.request, user)
        return Response('OK', headers=headers)
开发者ID:VictorMedeiros,项目名称:LBGenerator,代码行数:28,代码来源:user.py


示例19: login_post

def login_post(request):  # tested
    next = request.params.get('next') or request.route_url('home')
    login = request.POST.get('login', '')
    password = request.POST.get('password', '')
    # print(login)
    log.debug(login)
    user = DBSession.query(User).filter_by(login=login).first()
    if user and user.check_password(password):
        client = Client(user_id=user.id)
        user.clients.append(client)
        DBSession.add(client)
        DBSession.flush()
        headers = remember(request, principal=client.id)
        response = Response()
        response.headers = headers
        locale_id = user.default_locale_id
        if not locale_id:
            locale_id = 1
        response.set_cookie(key='locale_id', value=str(locale_id))
        response.set_cookie(key='client_id', value=str(client.id))
        headers = remember(request, principal=client.id)
        # return HTTPFound(location=next, headers=response.headers)
        return HTTPOk(headers=response.headers, json_body={})
        # return {}
    return HTTPUnauthorized(location=request.route_url('login'))
开发者ID:AlexanderYAPPO,项目名称:lingvodoc,代码行数:25,代码来源:user_and_login.py


示例20: render

    def render(self):

        login_url = resource_url(self.request.context, self.request, 'login')
        referrer = self.request.url
        # never use the login form itself as came_from
        if referrer == login_url:
            referrer = '/'
        came_from = self.request.params.get('came_from', referrer)
        login = self.request.params.get('user.login', '')
        if 'form.submitted' in self.request.params:
            password = self.request.params.get('user.password', u'')
            if password:
                if User.by_ldap_credentials(
                        self.session, login, password,
                        self.request.registry.settings) is not None:
                    log.info('login %r succeed', login)
                    headers = remember(self.request, login)
                    return HTTPFound(location=came_from,
                                     headers=headers)
 
                if User.by_credentials(
                        self.session, login, password) is not None:
                    log.info('login %r succeed', login)
                    headers = remember(self.request, login)
                    return HTTPFound(location=came_from,
                                     headers=headers)

        return {'came_from': came_from,
                'user': User(login=login),
                }
开发者ID:EasyPost,项目名称:pyshop,代码行数:30,代码来源:credentials.py



注:本文中的pyramid.security.remember函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap