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

Python auth.get_auth函数代码示例

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

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



在下文中一共展示了get_auth函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: get

 def get(self):
     template_values = {
             'title': 'Login page',
             'login': False
         }
     if auth.get_auth().get_user_by_session():
         user_id = auth.get_auth().get_user_by_session()['user_id']
         user = User.get_by_id(user_id)
         userURI = user.name if user.name else user_id
         name = user.name if user.name else user.email_address
         if user:
             template_values = {
                 'title': 'Hi there, {}'.format(name),
                 'login': True,
                 'name': userURI,
                 'messages': ''
             }
         if self.request.path == '/':
             self.redirect('/{}'.format(user_id))
         if self.request.path == '/logout':
             auth.get_auth().unset_session()
             self.redirect('/')
             logging.info('Logout bye bye...')
         if self.request.path == '/profile':
             template_values['page'] = 'profile'
             profile = ProfileHandler()
             profile.drawProfilePage()
     template = JINJA_ENVIRONMENT.get_template('_layout.html')
     self.response.write(template.render(template_values))
开发者ID:MarkoSh,项目名称:NextImage,代码行数:29,代码来源:main.py


示例2: logout

 def logout(self):
     get_auth().unset_session()
     
     next = self.request.params.get('next', None)
     if not next:
         next = settings.get('db_login')['logout_dest_url']
     return self.redirect(next)
开发者ID:ksdtech,项目名称:gae-conferences,代码行数:7,代码来源:sessions.py


示例3: post_logout

			def post_logout(self):
				auth.get_auth().unset_session()

				# User is logged out, let's try redirecting to login page
				try:
					self.redirect(self.logout_result)
				except (AttributeError, KeyError), e:
					return "User is logged out"
开发者ID:Diddit,项目名称:diddit,代码行数:8,代码来源:gaut.py


示例4: post

    def post(self):
        username = self.request.POST.get('username', None)
        password = self.request.POST.get('password', None)

        try:
            auth.get_auth().get_user_by_password(username, password)
        except Exception, e:
            logging.warning(e)
开发者ID:michaelore,项目名称:cdc2012,代码行数:8,代码来源:main.py


示例5: auth

    def auth(self):
        """Extract an Auth object from the request object.

        Returns:
            An Auth object (webapp2_extras.auth.Auth) containing
            the authorization of the current user.
        """
        print auth.get_auth(request=self.request).get_user_by_session()
        return auth.get_auth(request=self.request)
开发者ID:fractal1729,项目名称:emcc-website,代码行数:9,代码来源:BaseHandler.py


示例6: post

 def post(self):
     username = self.request.get('username')
     password = self.request.get('password')
     try:
         auth.get_auth().get_user_by_password(username, password,
                                              remember=True, save_session=True)
         return self.redirect(self.uri_for('home'))
     except auth.AuthError as e:
         logging.info('Login failed for user %s because of %s', username, type(e))
         return self._serve_page(True)
开发者ID:gsakkis,项目名称:webapp2-user-accounts,代码行数:10,代码来源:main.py


示例7: insert_details

def insert_details(context):
    try:
        current_session = auth.get_auth().get_user_by_session()
        new_user_object = auth.get_auth().store.user_model.get_by_auth_token(current_session['user_id'], current_session['token'])[0]
        username = new_user_object.auth_ids[0]
        old_user_object = models.Account.all().filter('username =', username).fetch(1)[0].__dict__['_entity']

        context['username'] = old_user_object['username']
        context['is_admin'] = old_user_object['is_admin']
        context['is_employee'] = old_user_object['is_employee']
    except Exception, e:
        logging.warning(e)
开发者ID:michaelore,项目名称:cdc2012,代码行数:12,代码来源:main.py


示例8: UpdateGcmGroup

def UpdateGcmGroup(self,instanttype,ohurl):
	uniqueid = self.request.get("uniqueid")
	bname = self.request.get("bname")
	message = self.request.get("message")
	atplace = self.request.get("atplace")
        bid = ''        
	timestamp = datetime.datetime.now()
	userid = self.user_id
	userDetails = self.current_user
	group_query = GroupData.query(GroupData.uniqueid == uniqueid)	
	groups = group_query.fetch(1) 
	registration_ids = []
        frienduserids = []
	for group in groups:
            bid = group.bid
            if group.userid != self.user_id:
                l_auth = auth.get_auth()
                userData = l_auth.store.user_model.get_by_id (group.userid)
                registration_ids.append(userData.instants.gcm_regid)                            
	    instants = group.instants            
	    if len(instants) > 20:
		del instants[-1]
	    instant = InstantMesg(message = message,atplace = atplace,userid=self.user_id,timestamp = timestamp,instanttype = instanttype,ohid = ohurl,gcmtype='group',uniqueid=uniqueid)
	    instants.append(instant)
	    group.instants = instants
            friends = group.friends
            for friend in friends:
                if friend.state == 'in':
                    frienduserids.append(friend.userid)
                    if self.user_id != friend.userid:
                        l_auth = auth.get_auth()
                        userData = l_auth.store.user_model.get_by_id (friend.userid)
                        registration_ids.append(userData.instants.gcm_regid)            
	    group.put()

	secs = calendar.timegm(timestamp.timetuple())
	logging.info("%s" %frienduserids)
	logging.info("%s" %registration_ids)
	if len(registration_ids) == 0:
	    self.response.write("")
	    return
	Bodyfields = {
	      "data": {"live":message,"username":userDetails.name,"bid":bid,"bname":bname,"atplace":atplace,"timestamp":secs,"instanttype":instanttype,'ohurl':ohurl,'uniqueid':uniqueid},
	      "registration_ids": registration_ids
	     }
	result = urlfetch.fetch(url="https://android.googleapis.com/gcm/send",
			payload=json.dumps(Bodyfields),
			method=urlfetch.POST,
			headers={'Content-Type': 'application/json','Authorization': 'key=AIzaSyBNnXeISW8-KfETBKE-r0ASytx4WyC6NTk'})
	#self.response.out.write('Server response, status: ' + result.content )
        return result
开发者ID:thejasvibhat,项目名称:smashed,代码行数:51,代码来源:gcm.py


示例9: post

 def post(self):
     if self.request.get('login'):
         template_values = {
             'title': 'Login page',
             'login': False
         }
         login = self.request.get('login')
         password = self.request.get('password')
         if "checkname" in self.request.path:
             logging.info('Checking name {}...'.format(login))
             # TODO проверка доступности логина, вернуть джисоном результат
         if self.request.get('sigbtn'):
             logging.info('Registering user {}...'.format(login))
             if "@" in login and len(password) > 6:
                 unique_properties = ['email_address']
                 user = User.create_user(login, unique_properties,
                                         email_address=login,
                                         password_raw=password,
                                         verified=False)
                 if not user[0]:
                     template_values = {
                         'title': ERRORMSG_TRYLOGIN,
                         'notify': ERRORMSG_TRYLOGIN,
                         'login': False
                     }
                     logging.info('Unable to create user {}, duplicating key {}'.format(login, user[1]))
                 else:
                     logging.info('6sfull creating user {}'.format(login))
                     user_id = user[1].get_id()
                     auth.get_auth().set_session(auth.get_auth().store.user_to_dict(user[1]))
                     self.redirect('/{}'.format(user_id))
         if self.request.get('logbtn'):
             logging.info('Logging as {}...'.format(login))
             try:
                 user_id = auth.get_auth().get_user_by_password(login, password, remember=True, save_session=True,
                                                                silent=False)['user_id']
                 self.session_store.save_sessions(self.response)
                 logging.info('6sfull logged user {} '.format(login))
                 self.redirect('/{}'.format(user_id))
             except (InvalidPasswordError, InvalidAuthIdError) as e:
                 template_values = {
                         'title': ERRORMSG_INVLOGIN,
                         'notify': ERRORMSG_INVLOGIN,
                         'login': False
                     }
                 logging.info("Auth error {}".format(type(e)))
         template = JINJA_ENVIRONMENT.get_template('_layout.html')
         self.response.write(template.render(template_values))
开发者ID:MarkoSh,项目名称:NextImage,代码行数:48,代码来源:main.py


示例10: get

    def get (self):
        fsbid = self.request.get ("fsbid");
        meme_query = UserMemeDb.query(UserMemeDb.fsbid == fsbid)
        oLimit = int(self.request.get("limit", default_value="10"))
        oOffset = int(self.request.get("offset", default_value="0"))
        memes = meme_query.fetch(oLimit,offset=oOffset)
        self.response.write('<memes>')
        for meme in memes:
            l_auth = auth.get_auth()
            userData = l_auth.store.user_model.get_by_id (meme.userid)
            #logging.info(userData)
            self.response.write('<meme>')
            self.response.write('<ts>')
            self.response.write('%s' %meme.date)
            self.response.write('</ts>')			
            self.response.write('<icon>')
            self.response.write('/res/icon/%s' %meme.blobid)
            self.response.write('</icon>')
            self.response.write('<url>')
            self.response.write('/oh/%s' %meme.resid)
            self.response.write('</url>')
            
            self.response.write('<creatorname>')
            self.response.write('%s' %userData.name)
            self.response.write('</creatorname>')

            self.response.write('<creatoravatar>')
            self.response.write('%s' %userData.avatar_url)
            self.response.write('</creatoravatar>')

            self.response.write('</meme>')
        self.response.write('</memes>')         
开发者ID:thejasvibhat,项目名称:smashed,代码行数:32,代码来源:meme.py


示例11: post

    def post(self):
        print self.request.POST

        name = self.request.POST.get('name')
        passw = self.request.POST.get('password')

        if not name or not passw:
            jsonMsg(self.response, 'Missing Required Field')
            self.response.set_status(400, "Missing required field")
            return

        success, user = auth.get_auth().store.user_model.create_user(name, password_raw=passw)

        if not success:
            prefix='Unable to create that user:'

            if 'auth_id' in user:
                jsonMsg(self.response, prefix + " Username Already Taken")
                self.response.set_status(400)
            else:
                jsonMsg(self.response, prefix + " Server Error")
                self.response.set_status(500)
            return

        else:
            print user
            self.response.write(
                json.dumps({"msg": "User Logged In",
                            'userid': user.key.id(),
                            'token': user.create_auth_token(user.key.id())},
                           indent=2
                           ))
            self.response.write("\n")
            self.response.set_status(200)
            return
开发者ID:swanyriver,项目名称:webapp-user-test,代码行数:35,代码来源:main.py


示例12: get

    def get(self, verification_type, user_id, token):
        user, ts = User.get_by_auth_token(int(user_id), token, verification_type)
        if not user:
            logging.info('Could not find any user with id "%s" token "%s"',
                         user_id, token)
            self.abort(404, 'This link has expired')

        # remove token, we don't want users to come back with an old link
        User.delete_auth_token(user.get_id(), token, verification_type)

        # store user data in the session
        auth_obj = auth.get_auth()
        # invalidate current session (if any) and set a new one
        auth_obj.unset_session()
        auth_obj.set_session(auth_obj.store.user_to_dict(user), remember=True)

        if verification_type == 'signup':
            if not user.verified:
                user.verified = True
                user.put()
            return self.display_message('User email address has been verified.')
        elif verification_type == 'reset':
            return self.render_template('resetpassword.html')

        assert False, verification_type
开发者ID:gsakkis,项目名称:webapp2-user-accounts,代码行数:25,代码来源:main.py


示例13: get

    def get(self):
        uniqueid = self.request.get('uniqueid')
        userid = self.user_id
	group_query = GroupData.query(GroupData.uniqueid == uniqueid)	
	groups = group_query.fetch(1) 
        delsuccess = False
        registration_ids = []
	for group in groups:
            if group.userid == userid:
                for friend in group.friends:
                    uid = friend.userid
                    if friend.state == 'in':
                        l_auth = auth.get_auth()
                        userData = l_auth.store.user_model.get_by_id (uid)
                        registration_ids.append(userData.instants.gcm_regid)
                group.key.delete()
                delsuccess = True
	if len(registration_ids) != 0:
	    Bodyfields = {
	      "data":{"instanttype":'delete','uniqueid':uniqueid},
	      "registration_ids": registration_ids
	     }
            result = urlfetch.fetch(url="https://android.googleapis.com/gcm/send",
			payload=json.dumps(Bodyfields),
			method=urlfetch.POST,
			headers={'Content-Type': 'application/json','Authorization': 'key=AIzaSyBNnXeISW8-KfETBKE-r0ASytx4WyC6NTk'})
        if delsuccess == True:
             self.response.write('success')
        else:
             self.response.write('failure')
开发者ID:thejasvibhat,项目名称:smashed,代码行数:30,代码来源:gcm.py


示例14: auth

  def auth(self):
    """
    Shortcut to access the auth instance as a property. Borrowed from:
    http://blog.abahgat.com/2013/01/07/user-authentication-with-webapp2-on-google-app-engine/

    """
    return auth.get_auth()
开发者ID:emma-murray,项目名称:cs496-finalproject,代码行数:7,代码来源:base.py


示例15: get_user

def get_user(a=None):
	if(not a):
		a=auth.get_auth()
	udict=a.get_user_by_session()
	if(udict):
		return User(udict['user_id'])
	return None
开发者ID:Diddit,项目名称:diddit,代码行数:7,代码来源:gaut.py


示例16: test_get_auth

 def test_get_auth(self):
     app = webapp2.WSGIApplication()
     req = webapp2.Request.blank('/')
     req.app = app
     self.assertEqual(len(req.registry), 0)
     a = auth.get_auth(request=req)
     self.assertEqual(len(req.registry), 1)
     self.assertTrue(isinstance(a, auth.Auth))
开发者ID:AlexStott,项目名称:eko_upload,代码行数:8,代码来源:extras_auth_test.py


示例17: getCurrentUser

	def getCurrentUser( cls ):
		logging.error( "現在 getCurrentUser にはバグがあります" )
		if cls.userCache=="notInitialized":
			myAuth = auth.get_auth()
			userInfo = myAuth.get_user_by_session()
			if userInfo:
				cls.userCache = User.get_by_id( userInfo["user_id"] )
			else:
				cls.userCache = None
		return cls.userCache
开发者ID:noughts,项目名称:openfish,代码行数:10,代码来源:models.py


示例18: user_info

    def user_info(self):
        """Shortcut to access a subset of the user attributes that are stored
        in the session.

        The list of attributes to store in the session is specified in
          config['webapp2_extras.auth']['user_attributes'].
        :returns
          A dictionary with most user information
        """
        return auth.get_auth().get_user_by_session()
开发者ID:gsakkis,项目名称:webapp2-user-accounts,代码行数:10,代码来源:main.py


示例19: login

    def login(self):
        """ Login erquested from within game client """
        nm = self.get_post('nm', '!').lower()
        pw = self.get_post('pw', '!')
        self.out = '0'
        self.a_user = None
        try:                
            a = auth.get_auth() 
            self.a_user = a.get_user_by_password("own:" + nm, pw, remember=True, save_session=True)
        except auth.InvalidAuthIdError:
            self.out = '0Invalid E-mail'
        except auth.InvalidPasswordError:
            self.out = '0Invalid Password'
        
        # user found and password checked out
        if self.a_user:
            self.out = '0Server error. Please try again in a few minutes.'
            
            self.user_token = UserToken.get(user=self.a_user['user_id'], subject='auth', token=self.a_user['token'])
            if not self.user_token:
                self.out = '0Server error 1. Please try again in a few minutes.'

            self.user = User.get_by_id(self.a_user['user_id'])
            if not self.user:
                self.out = '0Server error 2. Please try again in a few minutes.'
                
            if self.user and self.user_token:
                uid = int(self.user.get_id())

                # update the token
                now = int(time.time())
                self.user_token.uid = uid
                self.user_token.plrname = self.user.name
                self.user_token.location = 'L' # in lobby
                self.user_token.last_game_refresh = now
                self.user_token.last_chat_refresh = now
                self.user_token.put();
                
                self.out = '1'
                
                # send the auth cookie in the body too just incase i cant read it from header                
                self.out += 'auth='+self.session_store.serializer.serialize('auth', a.session)                
                          
                # output player name      
                self.out += '^' + self.user.name + '^'
                                
                # tell client which parts of game the player own
                #for s in self.user.shop.values():
                #    self.out += s
                self.out += ''.join(self.user.shop) + '^'

                # send settings
                self.out += '1^' if self.user.email_bmchallenge else '0^'                

        self.respond()
开发者ID:mayk93,项目名称:College,代码行数:55,代码来源:gamecommon.py


示例20: __init__

    def __init__(self, request, response):

        self.auth = auth.get_auth()

        # If not logged in, the dispatch() call will redirect to /login if needed
        if self.logged_in():
            # Make sure a handler has a reference to the current user
            user_dict = self.auth.get_user_by_session()
            self.user = self.auth.store.user_model.get_by_id(user_dict['user_id'])

            # Most pages will need the UserData, so for convenience we add it here.
            self.user_data = db.GqlQuery("SELECT * FROM UserData WHERE user_id = :1", self.user.user_id()).get()

            # If the user_data does not exist in the datastore, we instantiate it here
            if self.user_data == None:

                user_data = UserData()
                user_data.user_id = self.user.user_id()

                # Get optional app-instance configurations and add those to user_data
                credentials = {'EC2_SECRET_KEY': "",
                               'EC2_ACCESS_KEY': ""}
                try:
                    env_variables = app.config.get('env_variables')
                    user_data.env_variables = json.dumps(env_variables)
                    if 'AWS_ACCESS_KEY' in env_variables:
                        credentials['EC2_ACCESS_KEY'] = env_variables['AWS_ACCESS_KEY']
                    if 'AWS_SECRET_KEY' in env_variables:
                        credentials['EC2_SECRET_KEY'] = env_variables['AWS_SECRET_KEY']
                except:
                    raise

                user_data.setCredentials(credentials)

                # Check if the credentials are valid
                service = backendservices(user_data)
                params = {}
                params['credentials'] = credentials
                params["infrastructure"] = "ec2"
                if service.validateCredentials(params):
                    user_data.valid_credentials = True
                else:
                    user_data.valid_credentials = False

                # Create an unique bucket name for the user
                import uuid

                user_data.setBucketName('stochss-output-' + str(uuid.uuid4()))

                user_data.put()
                self.user_data = user_data

        webapp2.RequestHandler.__init__(self, request, response)
开发者ID:dnath,项目名称:stochss,代码行数:53,代码来源:stochssapp.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python auth.get_user_by_session函数代码示例发布时间:2022-05-26
下一篇:
Python models.User类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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