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)
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))
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"
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)
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)
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)
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 ='******'_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)
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
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))
def get(self): uniqueid = self.request.get('uniqueid') userDetails = self.current_user group_query = GroupData.query(GroupData.uniqueid == uniqueid) groups = group_query.fetch(1) registration_ids = [] for group in groups: bid = group.bid bname = group.bname for friend in group.friends: uid = friend.userid if friend.issmashed == 'true': l_auth = auth.get_auth() userData = l_auth.store.user_model.get_by_id (uid) registration_ids.append(userData.instants.gcm_regid) #querry databse for registration ids logging.info("%s" %registration_ids) if len(registration_ids) == 0: self.response.write("") return Bodyfields = { "data":{"username":userDetails.name,"bname":bname,"instanttype":'request','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 ) self.response.write('%s' %uniqueid)
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')
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>')
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
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:'******'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
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()
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
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))
def get(self): state = self.request.get('state') regid = self.request.get('regid') uniqueid = self.request.get('uniqueid') userid = self.user_id group_query = GroupData.query(GroupData.uniqueid == uniqueid) groups = group_query.fetch(1) bid = '' for group in groups: bid = group.bid self.current_user.instants.gcm_regid = regid exists = False; for sbid in self.current_user.instants.gcm_bids: if sbid == bid: exists = True if exists == False: self.current_user.instants.gcm_bids.append(bid) self.current_user.put() group_query = GroupData.query(GroupData.uniqueid == uniqueid) groups = group_query.fetch(1) finalDict = {} allFriends = [] for group in groups: eachFriend = {} if group.userid != userid: l_auth = auth.get_auth() userData = l_auth.store.user_model.get_by_id (group.userid) if userData: eachFriend['name'] = userData.name eachFriend['avatar'] = userData.avatar_url allFriends.append(eachFriend) for friend in group.friends: if friend.userid == userid: friend.state = state else: l_auth = auth.get_auth() userData = l_auth.store.user_model.get_by_id (friend.userid) if userData: eachFriend['name'] = userData.name eachFriend['avatar'] = userData.avatar_url allFriends.append(eachFriend) group.put() finalDict['friends'] = allFriends finalDict['bid'] = bid self.response.write(json.dumps(finalDict))
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
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()
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()
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)
def _on_signin(self, data, auth_info, provider): # Create the auth ID format used by the User model auth_id = '%s:%s' % (provider, data['id']) user_model = auth.get_auth().store.user_model user = user_model.get_by_auth_id(auth_id) if not user: ok, user = user_model.create_user(auth_id) if not ok: logging.error('Unable to create user for auth_id %s' % auth_id) self.abort(500, 'Unable to create user') return user
def get(self): regid = self.request.get("regid"); bid = self.request.get("bid") userid = self.user_id if self.current_user.instants == None: self.current_user.instants = Instants(gcm_bids = [""],gcm_regid = "") self.current_user.put() self.current_user.instants.gcm_regid = regid exists = False; for sbid in self.current_user.instants.gcm_bids: if sbid == bid: exists = True if exists == False: self.current_user.instants.gcm_bids.append(bid) self.current_user.put() push_query = GcmData.query(GcmData.bid == bid) pushes = push_query.fetch(1) finalDict = {} allmessages = [] bidExists = False; for push in pushes: i = 0 bidExists = True for instant in push.instants: messageDict = {} messageDict['message'] = instant.message l_auth = auth.get_auth() userData = l_auth.store.user_model.get_by_id(push.instants[i].userid) messageDict['username'] = userData.name messageDict['atplace'] = push.instants[i].atplace messageDict['instanttype'] = push.instants[i].instanttype messageDict['ohurl'] = push.instants[i].ohid secs = calendar.timegm(push.instants[i].timestamp.timetuple()) messageDict['timestamp'] = secs if push.instants[i].userid == self.user_id: messageDict['self'] = 'true' else: messageDict['self'] = 'false' i = i + 1 allmessages.append(messageDict) finalDict['messages'] = allmessages if bidExists == False: pushdb = GcmData(parent=push_dbkey("push_db")) pushdb.bid = bid pushdb.put() self.response.write(json.dumps(finalDict))
def __init__(self, request, response): # Initialize the jinja environment self.jinja_environment = jinja2.Environment( autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../views')) ) # Initialize logger utils.initialize_logger() 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']) # webapp2.RequestHandler.__init__(self, request, response)
def auth(self): """Shortcut to access the auth instance as a property. Also check if a facebook session is in place, if yes, set the session""" """ cookie = facebook.get_user_from_cookie(self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET) if cookie: logging.info("COOKIE TROUVE") user = self.user_model.get_by_fb_id(cookie["uid"]) if user: self.auth.set_session(self.auth.store.user_to_dict(user), remember=False) """ return auth.get_auth()
def validate_username(form, field): """Validate the username.""" auth_obj = auth.get_auth() user_dict = auth_obj.get_user_by_session() original_username = None if user_dict: user = auth_obj.store.user_model.get_by_id(user_dict['user_id']) original_username = user.username username = field.data.strip() if not _USERNAME_RE.search(username): raise validators.ValidationError('Invalid username.') # Only throw a name already exists error, if the user is trying to change their username. elif (username != original_username) and models.User.get_by_username(username): raise validators.ValidationError('This username is already taken.')
def login(cls, params): ''' ''' email_address = params[cls.PARAM_USER_EMAIL] password = params[cls.PARAM_USER_PASS] try: user = auth.get_auth().get_user_by_password(email_address, password, remember=True) # Signify invalid login attempt except (auth.InvalidAuthIdError, auth.InvalidPasswordError) as e: utils.log('Login failed for user: {0} with exception: {1}'.format(email_address, e)) result = { 'success': False } return result # Otherwise it succeeded result = { 'success': True, 'user': user } return result
def test_get_user_by_password(self): app = webapp2.WSGIApplication(config={ 'webapp2_extras.sessions': { 'secret_key': 'foo', } }) req = webapp2.Request.blank('/') req.app = app auth.get_store(app=app) a = auth.get_auth(request=req) session_store = sessions.get_store(request=req) m = models.User success, user = m.create_user(auth_id='auth_id', password_raw='password') user_id = user.key.id() # Lets test the cookie max_age when we use remember=True or False. rv = a.get_user_by_password('auth_id', 'password', remember=True) self.assertEqual(rv['user_id'], user_id) self.assertEqual( session_store.sessions['auth'].session_args['max_age'], 86400 * 7 * 3 ) # Now remember=False. rv = a.get_user_by_password('auth_id', 'password') self.assertEqual(rv['user_id'], user_id) self.assertEqual( session_store.sessions['auth'].session_args['max_age'], None ) # User was set so getting it from session will return the same one. rv = a.get_user_by_session() self.assertEqual(rv['user_id'], user_id) # Now try a failed password submission: user will be unset. rv = a.get_user_by_password('auth_id', 'password_2', silent=True) self.assertTrue(rv is None) # And getting by session will no longer work. rv = a.get_user_by_session() self.assertTrue(rv is None)
def get(self): tag = self.request.get('tag',default_value="auto") mode = self.request.get('mode',default_value="gallery") tags = tag.split(',') if mode == "gallery": if tag == "auto": meme_query = UserMemeDb.query(UserMemeDb.mode == 'gallery').order(-UserMemeDb.date) else: meme_query = UserMemeDb.query(UserMemeDb.mode == 'gallery').order(-UserMemeDb.date) meme_query = meme_query.filter(UserMemeDb.tags.IN(tags)); else: if tag == "auto": meme_query = UserMemeDb.query(UserMemeDb.userid == self.user_id).order(-UserMemeDb.date) else: meme_query = UserMemeDb.query(UserMemeDb.userid == self.user_id).order(-UserMemeDb.date) meme_query = meme_query.filter(UserMemeDb.tags.IN(tags)); 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) for meme in memes: meme.tickText = ' Created an Overheard' if self.logged_in == True: if meme.bid != "": meme.tickText = ' Overheard something in %s' %GetBarName(meme.bid) l_auth = auth.get_auth() userData = l_auth.store.user_model.get_by_id (meme.userid) meme.username = userData.name meme.useravatar = userData.avatar_url meme.icon_url = images.get_serving_url (meme.blobid, 500) meme.thumburl = images.get_serving_url (meme.blobid, 200) meme.downloadurl = images.get_serving_url (meme.blobid) path = os.path.join(os.path.dirname(__file__), 'templates/listmeme.tmpl') tclass = Template.compile (file = path) template_values = {"memes" : memes} self.response.headers['Content-Type'] = 'text/xml' self.response.write (tclass (searchList=template_values))
def auth(self): return auth.get_auth(request=self.request)
def auth(self): return webapp2_auth.get_auth(request=self.request)
def add_db_user_meta(controller): controller.db_user = None db_user = get_auth().get_user_by_session() if db_user and db_user['user_id']: auth_key = controller.util.decode_key(db_user['user_id']) controller.db_user = auth_key.get()
def check_login(self, *args, **kwargs): if not auth.get_auth().get_user_by_session(): self.redirect(self.uri_for('index')) else: return handler(self, *args, **kwargs)
def auth(self): """ Helper for accessing the auth instance as a property """ return auth.get_auth()
def auth(self): """Handles user authentication.""" return auth.get_auth(request=self.request)
def post(self): auth.get_auth().unset_session() self.redirect('/')
def __init__(self): self.auth = auth.get_auth()
def auth(self): #pylint: disable=no-self-use """ Simple method to access webapp2's auth predictably""" return auth.get_auth()
def auth(self): return webapp2_auth.get_auth()
def get_auth_user(self): return auth.get_auth().store.user_model.get_by_id(self.auth_user_id)
def auth(self): """Returns auth data associated with currently logged in user""" return auth.get_auth()
def auth(self): return auth.get_auth()
def get_auth(request=None): return auth.get_auth(factory=Authentication,request=request) pass
def auth(self): """Shortcut to access the auth instance as a property.""" return auth.get_auth()
def __init__(self): self.data = auth.get_auth().get_user_by_session()
def auth(self): # Access the auth instance as a property return auth.get_auth()