Esempio n. 1
0
def create_user_profile(user):
    try:
        Profile(username=user.username,email=user.email,password='').save()
    except:
        Profile(username=user.username,email='*****@*****.**',password='').save()

    this_profile = Profile.objects.get(username=user.username)
    this_profile.save()
    return this_profile
Esempio n. 2
0
def upload_user_image(id):
    if request.method == 'POST' and request.files['file']:
        img = request.files['file']
        img_name = secure_filename(img.filename)

        #Renaming File and save
        discard, ext = os.path.splitext(img_name)
        basename = uuid.uuid4().hex
        new_name = ''.join('{}{}'.format(basename, ext))
        saved_path = os.path.join(app.config['UPLOAD_FOLDER'], new_name)
        img.save(saved_path)

        schema = ProfileSchema(only=('u_id', 'image'))

        # #save to db
        if session.query(User).filter(User.id == id).scalar() is not None:
            if (img_obj :=
                    session.query(Profile).filter(Profile.u_id == id).first()):
                # img_obj = session.query(Profile).filter(Profile.u_id == id).first()
                img_obj.image = new_name
                result = schema.dump(img_obj)
            else:
                user_img = Profile(u_id=id, image=new_name)
                session.add(user_img)
                result = schema.dump(user_img)
        else:
            result = {"ERROR": "USER DOES NOT EXISTS"}

        session.commit()
        return jsonify(result)
Esempio n. 3
0
    def _getProfileFromUser(self):
        """Return user Profile from datastore, creating new one if non-existent."""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # TODO 1
        # step 1. copy utils.py from additions folder to this folder
        #         and import getUserId from it
        # step 2. get user id by calling getUserId(user)
        # step 3. create a new key of kind Profile from the id
        user_id = getUserId(user)
        p_key = ndb.Key(Profile, user_id)

        # TODO 3
        # get the entity from datastore by using get() on the key
        profile = p_key.get()
        if not profile:
            profile = Profile(
                key=p_key,  # TODO 1 step 4. replace with the key from step 3
                displayName=user.nickname(),
                mainEmail=user.email(),
                teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED),
            )
            # TODO 2
            # save the profile to datastore
            profile.put()

        return profile  # return Profile
Esempio n. 4
0
def register():
    if current_user.is_authenticated:
        return redirect('/blogs')

    if request.method == 'POST':
        email = request.form['email']
        username = request.form['username']
        password = request.form['password']
        gender = request.form['gender']
        website = request.form['website']

        if UserModel.query.filter_by(email=email).first():
            return ('Email already Present')

        user = UserModel(email=email, username=username)
        add_profile = Profile(
            username=username, gender=gender, website=website,
            owner=user)  #, image=open('static/default.jpeg','wb'))

        user.set_password(password)
        db.session.add(user)
        db.session.add(add_profile)
        db.session.commit()
        return redirect('/login')
    return render_template('register.html')
Esempio n. 5
0
    def _get_profile_from_user(self):
        """Return user Profile from datastore, creating new one if 
        non-existent."""
        # Make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # Try to retrieve an existing profile...
        user_id = get_user_id(user)
        key = ndb.Key(Profile, user_id)
        profile = key.get()
        # ... and if not exists, create a new Profile from logged in user data
        if not profile:
            profile = Profile(
                userId=user_id,
                key=key,
                displayName=user.nickname(),
                mainEmail=user.email(),
                teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED),
            )
            # Create the profile in datastore
            profile.put()

        return profile
Esempio n. 6
0
    def get(self):
        oauth_token = self.request.get('oauth_token', default_value=None)
        oauth_verifier = self.request.get('oauth_verifier', default_value=None)
        user = users.get_current_user()
        authr = AuthRequest.all().filter('owner = ', user).get()

        if oauth_token and oauth_verifier and user and authr:

            host = self.request.headers.get('host', 'nohost')
            access_token_url = 'https://%s/_ah/OAuthGetAccessToken' % host

            consumer_key = 'anonymous'
            consumer_secret = 'anonymous'

            consumer = oauth.Consumer(consumer_key, consumer_secret)

            token = oauth.Token(oauth_token, authr.request_secret)
            token.set_verifier(oauth_verifier)
            client = oauth.Client(consumer, token)

            if "localhost" not in host:

                resp, content = client.request(access_token_url, "POST")

                if resp['status'] == '200':

                    access_token = dict(cgi.parse_qsl(content))

                    profile = Profile(owner=user,
                                      token=access_token['oauth_token'],
                                      secret=access_token['oauth_token_secret'])
                    profile.put()

        self.redirect("/documentation/credentials")
def create_profile(identity_id=None, name=None, email=None):
    profile = Profile(identity_id=identity_id,
                      name=name,
                      email=email,
                      institution=None)
    db.session.add(profile)
    db.session.commit()
Esempio n. 8
0
    def register(self):
        while True:
            username = self.user_text_input(
                'Enter your username (# to cancel): ')
            if username != '#':
                if self.user_controller.read_user(
                        username=username) is not None:
                    print(
                        f'User with username \'{username}\' already exists; try a different username.'
                    )
                else:
                    break
            else:
                return None

        password = self.user_text_input('Enter your password: '******'Enter your first name: ')
        second_name = self.user_text_input('Enter your second name: ')
        last_name = self.user_text_input('Enter your last name: ')
        age = self.user_num_input('Enter your age: ')

        if self.user_text_input(
                'Press any key to confirm (# to cancel): ') != '#':
            profile = Profile(first_name, second_name, last_name, age)
            self.profile_controller.create_profile(profile)
            profile_id = self.profile_controller.read_profile(
                profile=profile).id

            user = BlogUser(username, password, profile_id)
            self.user_controller.create_user(user)
        else:
            return None

        return user
Esempio n. 9
0
def register(request):
    next = request.GET.get('next', '/')
    if request.method == "POST":
        form = RegisterForm(request.POST, request.FILES)
        if form.is_valid():
            username = form.cleaned_data["username"]
            email = form.cleaned_data["email"]
            password = form.cleaned_data["password"]
            try:
                file_obj = request.FILES['avatar']
                url = make_avatar(file_obj)
            except:
                url = ''
            next = request.POST["next"]
            if next == 'None':
                next = '/'
            user = User.objects.create_user(username, email, password)
            profile = Profile(user=user, avatar=url, today=today)
            profile.save()
            user.save()
            return HttpResponseRedirect("/account/login/?f=register&next=%s" %
                                        next)
    else:
        form = RegisterForm()
    return render_to_response("account/register.html",{'form': form, 'next': next},\
                        context_instance=RequestContext(request))
Esempio n. 10
0
def _add_profile(data, user, id=0):
    if id:
        obj = get_profile(id)
        update_ref_count(obj.construct_list, -1)
        obj.name = data[NAME]

        if not data[CONSTRUCT_LIST]:
            raise IgniteException(ERR_PROF_IS_EMPTY)
        else:
            obj.construct_list = data[CONSTRUCT_LIST]

        obj.submit = data[SUBMIT]
        obj.updated_by = user
        update_ref_count(data[CONSTRUCT_LIST], +1)
        obj.save()
        return obj
    else:
        fp_object = Profile()
        fp_object.name = data[NAME]

        if not data[CONSTRUCT_LIST]:
            raise IgniteException(ERR_PROF_IS_EMPTY)
        else:
            fp_object.construct_list = data[CONSTRUCT_LIST]

        fp_object.submit = data[SUBMIT]
        fp_object.updated_by = user
        update_ref_count(data[CONSTRUCT_LIST], +1)
        fp_object.save()
        return fp_object
Esempio n. 11
0
    def get_profile(self):
        profile = self._get_profile()
        followers = self._get_followers()
        companies = self.get_companies_id()
        companies_names = {
            company: self.get_company_name(company)
            for company in companies
        }

        post_id = profile['id']
        followers = followers['firstDegreeSize']
        name = f"{list(profile['firstName']['localized'].values())[0]} {list(profile['lastName']['localized'].values())[0]}"

        profile_picture = None
        if 'profilePicture' in profile:
            profile_picture = profile['profilePicture']['displayImage~'][
                'elements'][-1]['identifiers'][0]['identifier']

        bio = profile.get('headline', None)

        profile.update({'followers': followers})

        return Profile(profile,
                       post_id,
                       followers,
                       name=name,
                       bio=bio,
                       profile_picture=profile_picture,
                       pages=companies,
                       pages_names=companies_names).as_dict()
Esempio n. 12
0
    def _getProfileFromUser(self):
        """Return user Profile from datastore, creating new one if non-existent."""  # noqa
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # Get user id by calling getUserId(user)
        user_id = getUserId(user)

        # Create a new key of kind Profile from the id.
        p_key = ndb.Key(Profile, user_id)

        # Get the entity from datastore by using get() on the key
        profile = p_key.get()

        # If profile doesn't exist, we create a new one
        if not profile:
            profile = Profile(
                key=p_key,
                displayName=user.nickname(),
                mainEmail=user.email(),
                teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED),
            )
            # Save the profile to datastore
            profile.put()

        return profile  # return Profile
    def _getProfileFromUser(self):
        """Return user Profile from datastore, creating new one if
        non-existent."""
        # TODO 2
        # step 1: make sure user is authed
        # uncomment the following lines:
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        p_key = ndb.Key(Profile, getUserId(user))
        profile = None
        # step 2: create a new Profile from logged in user data
        # you can use user.nickname() to get displayName
        # and user.email() to get mainEmail
        profile = p_key.get()
        if not profile:
            profile = Profile(
                key=p_key,
                displayName=user.nickname(),
                mainEmail=user.email(),
                teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED),
            )
            profile.put()

        return profile  # return Profile
def profile():
    """
    Add new profile answers 

    """

    # POST request
    if request.method == 'POST':
        body = request.get_json()
        if body is None:
            raise APIException(
                "You need to specify the request body as a json object",
                status_code=400)
        newprofile = Profile(question1=body['question1'],
                             question2=body['question2'],
                             question3=body['question3'])
        db.session.add(newprofile)
        db.session.commit()
        return "ok", 200

    #GET request
    if request.method == 'GET':
        newprofile = Profile.query.all()
        newprofile = list(map(lambda x: x.serialize(), newprofile))
        return jsonify(newprofile), 200
    return "Invalid Method", 404
Esempio n. 15
0
def add_profile():
    form = UpForm()
    if (form.validate_on_submit()
        ):  # validate and insert form data into database
        flash("Is valid")
        fname = form.fname.data
        lname = form.lname.data
        uname = form.uname.data
        uage = form.age.data
        gen = form.gender.data
        bio = form.biography.data

        photo = form.photo.data

        photo_name = secure_filename(photo.filename)

        photo.save(os.path.join(app.config['UPLOAD_FOLDER'], photo_name))

        profile = Profile(first_name=fname,
                          last_name=lname,
                          username=uname,
                          age=uage,
                          gender=gen,
                          photo=photo_name,
                          biography=bio,
                          date=datetime.datetime.now().date())

        db.session.add(profile)
        db.session.commit()

        return redirect(url_for('home'))
    elif (request.method == "POST" and not form.validate_on_submit()):
        flash("Error in submission")

    return render_template("add_profile.html", form=form)
Esempio n. 16
0
    def _getProfileFromUser(self):
        """Return user Profile from datastore, 
        creating new one if non-existent.
        """

        # make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException(
                'Authorization required')

        user_id = getUserId(user)
        p_key = ndb.Key(Profile, user_id)
        profile = p_key.get()

        # create new Profile if not there
        if not profile:
            profile = Profile(
                key = p_key,
                displayName = user.nickname(), 
                mainEmail= user.email(),
                teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED))
            profile.put()

        # return Profile
        return profile      
Esempio n. 17
0
 def create_object(self, data: dict, current_user: User) -> Profile:
     profile = Profile()
     profile.name = data['name']
     profile.user = current_user
     profile.coffee_strength_in_percent = data['coffee_strength_in_percent']
     profile.water_in_percent = data['water_in_percent']
     return profile
Esempio n. 18
0
def newPuppy():

    if request.method == 'POST':
        newProfile = Profile(name=request.form['pupname'],
                             weight=request.form['weight'],
                             gender=request.form['gender'],
                             picture=random.choice(puppy_images),
                             dateOfBirth=datetime.strptime(
                                 request.form['birthday'], "%Y-%m-%d"),
                             description=request.form['description'],
                             specialNeeds=request.form['needs'])

        session.add(newProfile)

        new_puppy = Puppy(shelter_id=randint(1, 5), profile=newProfile)

        session.add(new_puppy)
        session.commit()

        flash("New puppy created!")
        return redirect(url_for('viewPuppy', key=newPuppy.id))

    else:
        return render_template('new.html',
                               viewType="puppy",
                               traits=Puppy.defaultTraits())
Esempio n. 19
0
    def _getProfileFromUser(self):
        """Return user Profile from datastore, creating new one if non-existent."""

        ## step 1: make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        user_id = getUserId(user)
        # Create an instance of a Key for an id(user email) of a kind(Profile) 
        p_key = ndb.Key(Profile, user_id)
        # Get the entity(user profile) associated with the key
        profile = p_key.get()

        # If the entity does not exist, create a new entity and put in datastore
        if not profile:
            profile = Profile(
                key = p_key,
                displayName = user.nickname(), 
                mainEmail= user.email(),
                teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED),
            )
            # put will store profile as a persistent entity in the Datastore
            profile.put()

        return profile
Esempio n. 20
0
    def create(self, data):

        pk_base_user = General().generate_id(BaseUser)
        token = General().generate_token()
        base_user = BaseUser(pk_base_user,
                             token=token,
                             password=data["password"],
                             email=data["email"])

        SESSION.add(base_user)
        SESSION.flush()

        pk_instance = General().generate_id(Profile)
        instance = Profile(pk_instance, pk_base_user, data["first_name"],
                           datetime.date.today(), data["phone"],
                           data["date_birthday"], data["gender"])

        SESSION.add(instance)
        SESSION.flush()

        return {
            "id": pk_instance,
            "email": data["email"],
            "first_name": data["first_name"],
            "phone": data["phone"],
            "date_birthday": data["date_birthday"],
            "gender": data["gender"],
            "token": token
        }
Esempio n. 21
0
def register(request):
    uform = UserForm(request.POST or None)
    form = PlayerForm(request.POST or None)
    if uform.is_valid() and form.is_valid():
        dj_user = uform.save()
        player = form.save(commit=False)
        player.user = dj_user
        prof = Profile()
        prof.save()
        player.profile = prof
        player.save()
        #authenticate user
        #dj_user = authenticate(username=uform.cleaned_data['username'],
        #                       password=uform.cleaned_data['password'],
        #                      )
        #login(request, dj_user)
        #success sends to map and the questions..
        return redirect(reverse('login'))
    #register invalid.. go back to register (test registration errors!! probably fix css for errors)
    return render(request,
                  'registration/register.html',
                  context={
                      'form': form,
                      'uform': uform
                  })
Esempio n. 22
0
    def handle_post(self, email, account_info):
        if self.request.get("profile_entity_key"):
            profile_key = ndb.Key(
                urlsafe=self.request.get("profile_entity_key"))
            profile = profile_key.get()
        else:
            profile = Profile(parent=account_info.key, id=email)
            profile_key = profile.key.urlsafe()

        if self.get_uploads() and len(self.get_uploads()) == 1:
            logging.info("Received an image blob with this profile update.")
            media_blob = self.get_uploads()[0]
            profile.picture = media_blob.key()
        else:
            # There is a chance this is an edit in which case we should check for an existing blob key.
            original_blob_key = self.request.get("original_blob_key")
            if original_blob_key:
                logging.info(
                    "Attaching original blob key (this must have been an edit or duplicate)"
                )
                profile.picture = BlobKey(original_blob_key)

        profile.name = self.request.get("name")
        profile.location = self.request.get("location")
        profile.description = self.request.get("description")
        profile.dob = datetime.strptime(self.request.get("dob"), "%m/%d/%Y")
        profile.put()
        url_redir_str = "./user-profile?profile_entity_key=" + profile_key
        logging.info(url_redir_str)
        self.redirect(url_redir_str)
Esempio n. 23
0
    def _getProfileFromUser(self):
        """Return user Profile from datastore, creating new one if non-existent."""
        ## TODO 2
        ## step 1: make sure user is authed
        ## uncomment the following lines:
        # Use endpoints AUTH to get the current user.
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        user_id = getUserId(user)

        # create a new key of kind Profile from the id
        p_key = ndb.Key(Profile, user_id)

        # get the entity from datastore by using get() on the key
        profile = p_key.get()

        # profile = None
        ## step 2: create a new Profile from logged in user data
        ## you can use user.nickname() to get displayName
        ## and user.email() to get mainEmail
        if not profile:
            profile = Profile(
                key=p_key,
                displayName=user.nickname(),
                mainEmail=user.email(),
                teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED),
            )
            # save the profile to the datastore
            profile.put()

        return profile  # return Profile
Esempio n. 24
0
    def post_new_user(jwt):
        try:
            # Get request data
            req_data = request.get_json()
            first_name = req_data.get('first_name')
            last_name = req_data.get('last_name')
            location = req_data.get('location', None)
            description = req_data.get('description', None)
            contact = req_data.get('contact', None)
            
            # Create new Profile instance
            new_user = Profile(
                first_name = first_name,
                last_name = last_name,
                location = location,
                description = description,
                contact = contact
            )

            # Create new entry in database
            new_user.insert()

            return jsonify({
                'success':True,
                'user': new_user.format()
            })
        except:
            db.session.rollback()
            abort(422)
Esempio n. 25
0
    def addUser():
        json_data = request.get_json(force=True)
        if not json_data:
            return jsonify({'message': 'No input data provided'}), 400

        user = User.query.filter_by(email=json_data['email'].lower()).first()
        if user:
            return jsonify({'message': 'Email address already exists'}), 400
        """response = requests.get("https://isitarealemail.com/api/email/validate", params = {'email': email})
        status = response.json()['status']
        if status != "valid":
            return jsonify({'message': 'Email address does not exist/cannot be found'}), 400"""

        user = User.query.filter_by(username=json_data['username']).first()
        if user:
            return jsonify({'message': 'Username not available'}), 400

        user = User(username=json_data['username'],
                    email=json_data['email'],
                    password=generate_password_hash(json_data['password']))
        db.session.add(user)
        db.session.commit()

        result = User.serialize(user)

        profile = Profile(username=result['username'])
        db.session.add(profile)
        db.session.commit()

        acs = ACS(username=result['username'])
        db.session.add(acs)
        db.session.commit()

        return jsonify({"status": 'success', 'data': result}), 201
Esempio n. 26
0
 def form_valid(self, form):
     login           = form.cleaned_data['login']
     password1       = form.cleaned_data['password1']
     first_name      = form.cleaned_data['first_name']
     image           = form.cleaned_data['image']
     new_user = User(
         username=login,
         first_name=first_name,
     )
     new_user.set_password(password1)
     try:
         new_user.full_clean()
     except ValidationError:
         self.set_message(u'Не правильно заполненна форма', True)
         return super(CreateCompanyView, self).form_invalid(form)
     new_user.save()
     new_profile = Profile(
         user=new_user,
         is_company=True,
         is_report=False,
         is_super_user=False,
         image=image,
     )
     new_profile.save()
     new_company = Company(com_user=new_user)
     new_company.save()
     self.set_message(u'Компания успешно добавлена.')
     return super(CreateCompanyView,self).form_valid(form)
Esempio n. 27
0
 def testPriceForBuyTrade(self):
     prediction_key = Prediction(contract_one=0.00,
                                 contract_two=0.00,
                                 liquidity=100,
                                 statement="Test",
                                 end_time=datetime.datetime.now()).put()
     user_key = Profile().put()
     trade = Trade(prediction_id=prediction_key,
                   user_id=user_key,
                   direction='BUY',
                   contract='CONTRACT_ONE',
                   quantity=10.00)
     priceBuy = get_price_for_trade(prediction_key.get(), trade)
     self.assertEqual(5.124947951362557, priceBuy)
     prediction_key = Prediction(contract_one=10.00,
                                 contract_two=0.00,
                                 liquidity=100,
                                 statement="Test",
                                 end_time=datetime.datetime.now()).put()
     trade = Trade(prediction_id=prediction_key,
                   user_id=user_key,
                   direction='SELL',
                   contract='CONTRACT_ONE',
                   quantity=10.00)
     priceSale = get_price_for_trade(prediction_key.get(), trade)
     self.assertEqual(-5.124947951362557, priceSale)
Esempio n. 28
0
def register(request):
    """Try to register new user"""

    if request.user.is_authenticated():
        return redirect('grunts')

    if request.method == 'POST':
        form = CustomRegisterForm(data=request.POST)
        if not form.is_valid():
            return render(request, 'auth/register.html', {'form': form})
        else:
            # If valid form -> create user
            user = User.objects.create_user(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password1'])

            # And associate profile
            profile = Profile()
            profile.user = user
            profile.save()

            # Login registered user
            user.backend = 'django.contrib.auth.backends.ModelBackend'
            login_user(request, user)

            # Go to device list
            return redirect('grunts')
    else:
        form = CustomRegisterForm()

    return render(request, 'auth/register.html', {'form': form})
    def _getProfileFromUser(self):
        """Return user Profile from DataStore or create add new one if
        non-existent."""

        # Getting and Verifying current user
        user = getUser()
        
        # get the user_id (email) 
        user_id = getUserId(user)

        # Creating a profile key. 
        p_key = ndb.Key(Profile, user_id)
        
        # Using the profile key to get a profile Object
        profile = p_key.get()

        # create new Profile if not there
        if not profile:
            
            profile=Profile(
                key=p_key,
                displayName=user.nickname(),
                mainEmail=user.email(),
                teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED),)
            
            profile.put()
        
        return profile 
Esempio n. 30
0
def handle_join(request):
    # Handle request here
    vkuser = request.session.get('vk_user')
    errors = {}
    phone = request.REQUEST.get('phone')
    email = request.REQUEST.get('email')
    if phone:
        if not phone_validate(phone):
            errors["phone_error"] = u'Введите правильный телефон'
    else:
        errors['phone_error'] = u'Это поле не должно быть пустым'

    if email:
        if not email_validate(email):
            errors['email_error'] = u'Введите корректный e-mail'
    else:
        errors['email_error'] = u'Это поле не должно быть пустым'

    if errors:
        ec = {'vkuser': vkuser, 'email': email, 'phone': phone}
        ec.update(errors)
        return render_to_response('joinus.html',
                                  ec,
                                  context_instance=RequestContext(request))
    else:
        p = Profile(name=' '.join([vkuser.first_name, vkuser.last_name]),
                    vkontakte_id=vkuser.uid,
                    email=email,
                    phone=phone,
                    photo=vkuser.photo,
                    photo_medium=vkuser.photo_medium,
                    status=u'Игрок')
        p.save()
        return redirect('/thankyou/')