Beispiel #1
0
    def get(self):
        user = users.get_current_user()
        if not user:  # need to sign in
            self.redirect(users.create_login_url(self.request.uri))
            return

        producer = bene_util.sanitize(self.request.get('producer'))
        consumer = bene_util.sanitize(self.request.get('consumer'))

        u = bene_query.getCurrentUser()
        if not u:  # no user exists
            if producer and not consumer:  # make person a producer only in most restricted case
                u = entities.User(email=bene_util.getEmail(user),
                                  owner=user,
                                  isConsumer=False,
                                  isProducer=True)
                u.put()
                self.redirect('/createproducer')
                return
            else:  # all other cases, make consumer
                u = entities.User(email=bene_util.getEmail(user),
                                  owner=user,
                                  isConsumer=True,
                                  isProducer=False)
                u.put()
                self.redirect('/createconsumer')
                return

        if producer and not consumer:  # signed in producer
            if u.isConsumer:  # if previously signed in as consumer
                u.isConsumer = False
                u.isProducer = True
                u.put()
            if bene_query.getCurrentProducer(
            ) == None:  # no producer page, so create one
                self.redirect('/createproducer')
                return
            else:  # already has producer page, so redirect
                self.redirect('/producerhome')
                return
        else:  # signed in consumer
            if u.isProducer:  # if previously signed in as producer
                u.isConsumer = True
                u.isProducer = False
                u.put()
            if bene_query.getCurrentConsumer(
            ) == None:  # no consumer page, so create on
                self.redirect('/createconsumer')
                return
            else:  # already has consumer page, so redirect
                self.redirect('/consumerhome')
                return
Beispiel #2
0
	def get(self):
		# Check signed request for uid
		uid = self.request.GET['userID']
		signedRequest = self.request.GET['signedRequest']
		if not uid or not signedRequest:
			return self.abort(400)

		parsed_request = facebook.parse_signed_request(self.request.GET['signedRequest'], FACEBOOK_APP_SECRET)
		if not parsed_request or uid != parsed_request['user_id']:
			return self.abort(403)

		try:
			result = facebook.get_access_token_from_code(parsed_request["code"], "", FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
			profile = facebook.GraphAPI(result['access_token']).get_object("me")
		except facebook.GraphAPIError:
			return self.abort(403)

		# Fetch existant user or create new one
		user = entities.User.get_by_key_name(profile['id'])
		if not user:
			api_key = ''. join(random.choice(string.hexdigits) for x in range(64))
			user = entities.User(key_name = str(profile['id']),
								uid = int(profile['id']),
								first_name = profile['first_name'], last_name = profile['last_name'],
								api_key = api_key, access_token = result['access_token'], active = True)
		else:
			user.access_token = result['access_token']
		user.put();

		profile['api_key'] = user.api_key
		profile['access_token'] = user.access_token
		self.response.out.write(json.dumps(profile))
Beispiel #3
0
    def post(self):
        user_username = self.request.get('username')
        user_password = self.request.get('password')
        user_verify = self.request.get('verify')
        user_email = self.request.get('email')

        errors = common.check_signup(user_username, user_password, user_verify,
                                     user_email)
        if errors:
            self.render("Registration.html",
                        error=errors[0],
                        error2=errors[1],
                        error3=errors[2],
                        error4=errors[3],
                        username=user_username)
        else:
            u = entities.User(
                username=user_username,
                password=common.make_pw_hash(user_username, user_password),
                email=user_email
            )  #the password is made up of a combination of username, password and a secret value
            u.put()
            user_id = u.key().id()
            new_cookie_val = common.make_secure_val(
                str(user_id)
            )  #passes the user id into this function to get a hash of the user id
            self.response.headers.add_header(
                'Set-Cookie', 'user_id=%s; Path=/' % new_cookie_val)
            self.redirect("/blog/welcome")
Beispiel #4
0
def userAPI():
    user_res = db['users'].find_one({"login": request.args.get('login')})

    try:
        user = entities.User(user_res['id'], user_res['login'],
                             user_res['password'], user_res['eMail'],
                             user_res['name'])
        if user.password == request.args.get('password'):
            return json.dumps(user.__dict__)
    except:
        pass
Beispiel #5
0
    def get(self):
        os_type = self.request.get(PARAM_OS_TYPE)

        # create a new anonymous user entity, give json response with hashed id
        new_user = entities.User(os_type=os_type)
        new_user.put()
        generated_hash = wutil.createSecret(new_user.key().id())
        dictionary = {PARAM_USER_ID: generated_hash}
        self.response.headers[
            'Content-Type'] = "application/json; charset=utf-8"
        self.write(json.dumps(dictionary))
Beispiel #6
0
 def updateUser(self, username, data):
     """This function takes a username and a list of data as its input, updates the User account matching username and
     returns username. It follows a very similar procedure to updateRecord, however, username will not be None as this
     is user defined not automatically generated."""
     if username in self.__entities["User"].keys():
         self.__entities["User"][username].update(data)
     else:
         tempEntity = entities.User()
         tempEntity.update(data)
         self.__entities["User"][username] = tempEntity
     return username
Beispiel #7
0
    def get(self):
        userHash = self.request.cookies.get(PARAM_USER_ID, None)
        if (userHash is None):
            os_type = self.request.headers["User-Agent"]
            # create a new anonymous user entity, give json response with hashed id
            new_user = entities.User(os_type=os_type)
            new_user.put()
            generated_hash = wutil.createSecret(new_user.key().id())
            expires = datetime.now() + timedelta(days=1500)
            dead_date = expires.strftime('%a, %d-%b-%Y %H:%M:%S')
            self.response.headers.add_header(
                'Set-Cookie', '%s=%s; Path=/; expires=%s;' %
                (PARAM_USER_ID, generated_hash, dead_date))

        # user should have an identifier
        foodType = self.request.get(PARAM_FOOD_TYPE)
        if foodType not in (FOOD_MARKETPLACE, FOOD_SMOKEHOUSE):
            foodType = FOOD_MARKETPLACE
        dataTuple = dd.fetchRatings(foodType)
        entry = dataTuple[0]

        entry_id = entry.key().id()
        # find if the user voted, and change vote arrows
        cookie = self.request.cookies.get(str(entry_id), None)
        up_selected = ""
        down_selected = ""
        if cookie is not None:
            if cookie == '1':
                up_selected = "_selected"
            if cookie == '0':
                down_selected = "_selected"

        if entry.totalVotes == 0:
            percentage = 0
        else:
            percentage = int(
                (((float(entry.upvotes) / entry.totalVotes) * 100)))
        downvotes = entry.totalVotes - entry.upvotes

        voteComments = dataTuple[1]
        commentHTML = dd.generateCommentsHTML(voteComments)

        self.render("index.html",
                    type_name=entry.name,
                    percentage=percentage,
                    upvotes=entry.upvotes,
                    downvotes=downvotes,
                    entry_id=entry_id,
                    up=up_selected,
                    down=down_selected,
                    comments=commentHTML)
Beispiel #8
0
def create_users():
    body = json.loads(request.data)
    user = entities.User(username=body['username'],
                         name=body['name'],
                         fullname=body['fullname'],
                         password=body['password'],
                         contact=body['contact'])
    db_session = db.getSession(engine)
    db_session.add(user)
    db_session.commit()
    message = {'msg': 'User created'}
    json_message = json.dumps(message, cls=connector.AlchemyEncoder)
    db_session.close()
    return Response(json_message, status=201, mimetype='application/json')
Beispiel #9
0
def userAdd():
    try:
        max_id = db['users'].find_one(sort=[("id", -1)])['id']
    except:
        max_id = -1
    data = request.get_json()

    login = data['login']
    password = data['password']
    eMail = data['eMail']
    name = data['name']

    user = entities.User(max_id + 1, login, password, eMail, name)

    db['users'].insert_one(user.__dict__)

    return '{"result": "OK"}'
Beispiel #10
0
 def find_user(self, messenger: str, id_: str) -> 'entities.User':
     users = next(
         self.users.fetch([
             {
                 'id': id_,
                 'messenger': messenger
             },
             {
                 'nick': id_,
                 'messenger': messenger
             },
             {
                 # TODO format phone
                 'phone': id_,
                 'messenger': messenger
             }
         ]))
     return entities.User(**users[0], refine=False) if users else None
Beispiel #11
0
def register():
    username = request.json.get("username")
    password = request.json.get("password")
    number = request.json.get("number")
    identity = request.json.get("identity")

    user = entities.User(username, number, password)

    result = register_process(user, identity)
    response = entities.ResponseClass(True, "", "null")

    response.msg = result[0]
    response.isSuccess = result[1]

    resp_dict = utility.class_2_dict(response)
    result = json.dumps(resp_dict,
                        sort_keys=True,
                        indent=4,
                        separators=(',', ':'),
                        ensure_ascii=False).encode('utf8')

    return result
Beispiel #12
0
 def show_MainWindow(self, userId):
     self.ui = Ui_MainWindow()
     self.ui.user = entities.User(userId)
     self.ui.setupUi(LoginWindow)
     LoginWindow.show()
Beispiel #13
0
    def get_connected(self, key: str):
        users = next(self.users.fetch({'receiver': key}))

        return [entities.User(**user, refine=False) for user in users]
Beispiel #14
0
 def get_user(self, key: str) -> 'entities.User':
     user_db = self.users.get(key)
     return entities.User(**user_db, refine=False)