Exemplo n.º 1
0
def handle_exception(e):
    text = ''
    dbUser = DBUser.LoadFromSession('dbUser')
    if (dbUser != None):
        text += f'Uzivatel:<br>{dbUser.__dict__}<br>'
    else:
        dbUserReg = DBUser.LoadFromSession('dbUserRegistration')
        if (dbUserReg != None):
            text += f'Uzivatel registrace:<br>{dbUserReg.__dict__}<br>'

    etype, value, tb = sys.exc_info()
    exceptionString = '<br>'.join(traceback.format_exception(etype, value, tb))
    text += f'Error message:<br> {exceptionString}'
    SendMail(GetEmail('noreplyMail'), GetEmail('errorMail'),
             'Internal error on app.seniore.org', text)
    return render_template('error_500.html')
Exemplo n.º 2
0
def comment():
    form = TextFormular()
    if form.validate_on_submit():
        dbUser = DBUser.LoadFromSession('dbUserRegistration')
        dbUser.info = form.comment.data
        dbUser.id = DBAccess.GetSequencerNextVal('users_id_seq')
        dbUser.telephone2 = form.telephone.data
        dbUser.InsertDB()
        response = RenameImageToPrivate(session['cloudinaryId'],
                                        (str(dbUser.id) + 'OP'))
        imageUrl = response['url']

        ts = URLSafeTimedSerializer(app.config["SECRET_KEY"])
        token = ts.dumps(dbUser.id, salt='email-confirm-key')
        confirm_url = url_for('login_bp.user_confirmation',
                              token=token,
                              _external=True)

        SendMail(
            GetEmail('noreplyMail'), GetEmail('adminMail'),
            'Zaregistrován nový uživatel',
            f'''<html>Nový uživatel zaregistrovan, čeká na schválení. <br>
         <img src={GetImageUrl(dbUser.id)}>foto</img> 
         <br> <img src={imageUrl}>OP</img> 
         <br> jméno a příjmení: {dbUser.first_name} {dbUser.surname}
         <br> email: {dbUser.email}
         <br> telefon: {dbUser.telephone}
         <br> adresa: {dbUser.street}, {dbUser.town}
         <br> info: {dbUser.info} 
         <br> telefon na kontaktní osobu (seniora registruje někdo jiný): {dbUser.telephone2}
         <br> Pro schválení uživatele klikněte na následující link {confirm_url} </html>'''
        )
        SendMail(
            GetEmail('noreplyMail'), '*****@*****.**',
            'Zaregistrován nový uživatel',
            f'''<html>Nový uživatel zaregistrovan, čeká na schválení. <br>
         <img src={GetImageUrl(dbUser.id)}>foto</img> 
         <br> <img src={imageUrl}>OP</img> 
         <br> jméno a příjmení: {dbUser.first_name} {dbUser.surname}
         <br> email: {dbUser.email}
         <br> telefon: {dbUser.telephone}
         <br> adresa: {dbUser.street}, {dbUser.town}
         <br> info: {dbUser.info},
          <br> telefon na kontaktní osobu (seniora registruje někdo jiný): {dbUser.telephone2},
         <br> Pro schválení uživatele klikněte na následující link {confirm_url} </html>'''
        )
        SendMail(
            GetEmail('noreplyMail'), '*****@*****.**',
            'Zaregistrován nový uživatel',
            f'<html>Nový uživatel zaregistrovan, čeká na schválení. <br> <img src={GetImageUrl(dbUser.id)}>foto</img> <br> <img src={imageUrl}>OP</img> <br> údaje: {dbUser.__dict__} <br> Pro schválení uživatele klikněte na následující link {confirm_url}'
        )
        flash(
            f'Registrace uživatele {dbUser.first_name} {dbUser.surname} úspěšně dokončena. Váš profil nyní musíme zkontrolovat. Zabere nám to maximálně 48 hodin. Prosíme, mějte strpení. Ruční ověřování považujeme za nezbytnost kvůli bezpečnosti. O schválení vás budeme informovat emailem.',
            FlashStyle.Success)
        SendMail(
            GetEmail('noreplyMail'), dbUser.email, 'Registrace na Seniore.org',
            'Děkujeme za vaši registraci na Seniore.org. Váš profil nyní musíme zkontrolovat. Zabere nám to maximálně 48 hodin. Prosíme, mějte strpení. Ruční ověřování považujeme za nezbytnost kvůli bezpečnosti. O schválení vás budeme informovat emailem. Děkujeme, tým Seniore.org'
        )
        return redirect(url_for("login_bp.login"))
    return render_template("/registraceComment.html", form=form)
Exemplo n.º 3
0
 def decorated_function(*args, **kwargs):
     dbUser = DBUser.LoadFromSession('dbUser')
     if dbUser is None:
         flash(
             'Nejste přihlášeni, pro přístup je nutné se přihlásit.',
             FlashStyle.Danger)
         return redirect(url_for("login_bp.login"))
     elif dbUser.level < level:
         abort(403)
     return function(*args, **kwargs)
Exemplo n.º 4
0
def registrace_address():

    form = RegistrationFormAddress()

    if form.validate_on_submit():
        dbUser = DBUser.LoadFromSession('dbUserRegistration')
        dbUser.town = form.town.data
        dbUser.street = form.street.data
        # dbUser.street_number = form.street_number.data
        dbUser.post_code = form.post_code.data

        kwargs = dbUser.__dict__
        address = "{} {} {}".format(kwargs["street"], kwargs["town"],
                                    kwargs["post_code"])
        # address = "{} {} {} {}".format(kwargs["street"], kwargs["street_number"], kwargs["town"], kwargs["post_code"])
        coordinates = GetCoordinates(address)
        if (coordinates is not None):
            # dbUser.latitude = coordinates[0]
            # dbUser.longitude = coordinates[1]
            dbUser.latitude = round(coordinates[0], 5)
            dbUser.longitude = round(coordinates[1], 5)

            x = 1
            y = 1
            difference = 0.00001
            originalLatitude = dbUser.latitude
            originalLongitue = dbUser.longitude
            #check if same coordinates already exists
            while DBAccess.ExecuteScalar(
                    'select id from users where latitude=%s and longitude=%s',
                (
                    dbUser.latitude,
                    dbUser.longitude,
                )) is not None:
                #if exists add difference and try again and again..
                dbUser.latitude = originalLatitude + x * difference
                dbUser.longitude = originalLongitue + y * difference
                if x != -1:
                    x -= 1
                elif y != -1:
                    y -= 1
                else:
                    x = 1
                    y = 1
                    difference += 0.00001

        else:
            flash('Nenalezeny souřadnice pro vaši adresu', FlashStyle.Danger)
            return render_template("registrace_address.html", form=form)

        dbUser.SaveToSession('dbUserRegistration')
        #return redirect(url_for("login_bp.photo"))
        return redirect(url_for("login_bp.registrace_idCard"))

    return render_template("registrace_address.html", form=form)
Exemplo n.º 5
0
def registrace_name():

    form = RegistrationFormName()

    if form.validate_on_submit():
        dbUser = DBUser.LoadFromSession('dbUserRegistration')
        dbUser.first_name = form.first_name.data
        dbUser.surname = form.surname.data
        dbUser.telephone = form.telephone.data

        dbUser.SaveToSession('dbUserRegistration')
        return redirect(url_for("login_bp.registrace_address"))

    return render_template("registrace_name.html", form=form)
Exemplo n.º 6
0
def registrace():

    form = RegistrationForm()

    if form.validate_on_submit():
        if (form.password.data != form.passwordAgain.data):
            flash('Hesla nejsou stejná.', FlashStyle.Danger)
            email = session['confirmed_email']
            form.email.data = email
            return render_template("registrace.html", form=form)
        email = session['confirmed_email']
        form.email.data = email
        dbUser = DBUser()
        dbUser.email = form.email.data
        dbUser.password = form.password.data
        dbUser.level = 0

        if DBAccess.ExecuteScalar('select id from users where email=%s',
                                  (dbUser.email, )) is not None:
            flash(
                f'Uživatel {dbUser.email} je již zaregistrován, zvolte jiný email.',
                FlashStyle.Danger)
            dbUser.email = None
            form.email.data = None
            return render_template("registrace.html", form=form)

        dbUser.salt = salt = DBAccess.ExecuteScalar("select salt()")

        #md% tranform password use md5 function on password + salt
        # md5Pass = hashlib.md5((dbUser.password+dbUser.salt).encode()).hexdigest()
        # dbUser.password = md5Pass
        bcrypt = Bcrypt()
        dbUser.password = bcrypt.generate_password_hash(
            dbUser.password).decode('UTF-8')

        dbUser.SaveToSession('dbUserRegistration')
        return redirect(url_for("login_bp.registrace_name"))

    #email = session.pop('confirmed_email',None)
    email = session.get('confirmed_email')

    if (email is None):
        abort(403)

    form.email.data = email

    return render_template("registrace.html", form=form)
Exemplo n.º 7
0
def remove_service():
    id = request.args.get("id", type=int)
    #check if there was argument
    if (id is None):
        abort(403)
    #check if service belongs to logged user..
    dbUser = DBUser.LoadFromSession('dbUser')
    user_service = DBAccess.ExecuteScalar(
        "select id from users_services where id = %s and id_users=%s",
        (id, dbUser.id))
    if (user_service is None):
        abort(403)

    #delete service
    DBAccess.ExecuteUpdate("delete from users_services where id=%s", (id, ))
    return redirect(url_for("profile_bp.profil"))
Exemplo n.º 8
0
def requests_detail():
    rid = request.args.get("id", type=int)

    if request.method == "POST":
        # status = request.form["submit_button"]
        status = RequestStatus[request.form["submit_button"]]
        DBAccess.ExecuteUpdate(
            "UPDATE requests SET id_requests_status= %s where id= %s",
            (status, rid))

    requests = DBAccess.ExecuteSQL(
        """select
          ud.first_name,
          ud.surname,
          ud.email,
          ud.telephone,
          ud.town,
          uo.first_name,
          uo.surname,
          uo.email,
          uo.telephone,
          uo.town,
          s.category,
          r.date_time,
          r.add_information,
          to_char(r.timestamp, 'YYYY-mm-DD HH12:MI'),
          rs.status,
          r.id,
          ud.id,
          uo.id
        from requests r
        inner join services s on r.id_services = s.id
        inner join users ud on r.id_users_demand = ud.id
        inner join users uo on r.id_users_offer = uo.id
        inner join requests_status rs on r.id_requests_status = rs.id
        where r.id =%s""", (rid, ))

    if (requests is None):
        abort(403)
    requests = requests[0]
    dbUser = DBUser.LoadFromSession('dbUser')
    if dbUser.level < 2 and dbUser.id != int(
            requests[16]) and dbUser.id != int(requests[17]):
        abort(403)

    return render_template("requests_detail.html", entries=requests)
Exemplo n.º 9
0
def feedback():
    range_evaluation = range(1, 6)
    form = FeedbackFormular()
    rid = request.args.get("id", type=int)
    dbUser = DBUser.LoadFromSession('dbUser')
    id_user_review = dbUser.id

    id_users = DBAccess.ExecuteSQL(
        """select
        id_users_demand, id_users_offer
        from requests 
        where id =%s""", (rid, ))

    if id_users[0][0] == id_user_review:
        id_user_evaluated = id_users[0][1]
    else:
        id_user_evaluated = id_users[0][0]

    if form.validate_on_submit():
        comment = form.comment.data
        number_evaluation = request.form["number_evaluation"]
        DBAccess.ExecuteInsert(
            """insert into feedback
         (id_requests, id_user, id_user_review, comment, evaluation)
         values (%s, %s, %s, %s, %s)""",
            (rid, id_user_evaluated, id_user_review, comment,
             number_evaluation))
        DBAccess.ExecuteUpdate(
            """update requests
      set id_requests_status = 5 
      where id =%s""", (rid, ))

        return render_template("feedback_thanks.html")

    return render_template("feedback.html",
                           form=form,
                           range_evaluation=range_evaluation)
Exemplo n.º 10
0
def senior_registration():
    form = SeniorRegistrationForm()

    if (form.validate_on_submit()):
        if form.password.data != form.passwordAgain.data:
            flash('Hesla nejsou totožná!', FlashStyle.Danger)
            return render_template('senior_registration.html', form=form)
        if DBAccess.ExecuteScalar(
                'select id from users where trim(email) ilike %s',
            (form.email.data.strip(), )) is not None:
            flash(
                f'Uživatel {form.email.data} je již zaregistrován, zvolte jiný email.',
                FlashStyle.Danger)
            form.email.data = None
            return render_template('senior_registration.html', form=form)

        dbUser = DBUser()
        dbUser.first_name = form.first_name.data
        dbUser.surname = form.surname.data
        dbUser.email = form.email.data
        dbUser.telephone = form.telephone.data
        dbUser.telephone2 = form.telephone2.data
        dbUser.comment = form.comment.data
        dbUser.street = form.street.data
        dbUser.street_number = form.street_number.data
        if (form.street_number.data == ''):
            dbUser.street_number = 1
        dbUser.town = form.town.data
        dbUser.post_code = form.post_code.data
        dbUser.password = form.password.data
        bcrypt = Bcrypt()
        dbUser.password = bcrypt.generate_password_hash(
            dbUser.password).decode('UTF-8')
        dbUser.level = 1

        address = '{} {} {}'.format(dbUser.street, dbUser.town,
                                    dbUser.post_code)

        coordinates = GetCoordinates(address)
        if (coordinates is not None):
            dbUser.latitude = round(coordinates[0], 5)
            dbUser.longitude = round(coordinates[1], 5)
            x = 1
            y = 1
            difference = 0.00001
            originalLatitude = dbUser.latitude
            originalLongitue = dbUser.longitude
            #check if same coordinates already exists
            while DBAccess.ExecuteScalar(
                    'select id from users where latitude=%s and longitude=%s',
                (
                    dbUser.latitude,
                    dbUser.longitude,
                )) is not None:
                #if exists add difference and try again and again..
                dbUser.latitude = originalLatitude + x * difference
                dbUser.longitude = originalLongitue + y * difference
                if x != -1:
                    x -= 1
                elif y != -1:
                    y -= 1
                else:
                    x = 1
                    y = 1
                    difference += 0.00001
        else:
            flash('Nenalezeny souřadnice pro vaši adresu', FlashStyle.Danger)
            return render_template('senior_registration.html', form=form)

        dbUser.salt = salt = DBAccess.ExecuteScalar("select salt()")
        dbUser.id = DBAccess.GetSequencerNextVal('users_id_seq')
        dbUser.InsertDB()
        flash(
            f'Senior {dbUser.first_name} {dbUser.surname} email: {dbUser.email} vložen do databáze a nastaven jako ověřený.',
            FlashStyle.Success)
        return redirect(url_for("login_bp.login"))

    return render_template('senior_registration.html', form=form)
Exemplo n.º 11
0
def requests_detail_user():
    rid = request.args.get("id", type=int)
    dbUser = DBUser.LoadFromSession('dbUser')
    userId = dbUser.id

    requests = DBAccess.ExecuteSQL(
        """select s.category, 
            
            case when 	ud.id = %s
            then	uo.first_name 
            else	ud.first_name
            end,
            
            case when 	ud.id = %s
            then	uo.surname 
            else	ud.surname
            end,
			
		      	case when 	ud.id = %s
            then	uo.email 
            else	ud.email
            end,
          
          r.date_time,
          r.id,
          ud.id,
          uo.id,
          r.id_users_creator
        from requests r
        inner join services s on r.id_services = s.id
        inner join users ud on r.id_users_demand = ud.id
        inner join users uo on r.id_users_offer = uo.id
        inner join requests_status rs on r.id_requests_status = rs.id
        where r.id =%s""", (userId, userId, userId, rid))

    if (requests is None):
        abort(403)
    requests = requests[0]
    dbUser = DBUser.LoadFromSession('dbUser')
    if dbUser.level < 2 and dbUser.id != int(requests[6]) and dbUser.id != int(
            requests[7]):
        abort(403)

    acceptButtonVisible = (int(requests[8]) != userId)

    if request.method == "POST":
        # status = request.form["submit_button"]
        status = RequestStatusUser[request.form["submit_button"]]
        DBAccess.ExecuteUpdate(
            "UPDATE requests SET id_requests_status= %s where id= %s",
            (status, rid))
        text = 'potvrzena' if status == '2' else 'zamítnuta'
        SendMail(
            GetEmail('noreplyMail'), requests[3],
            'Seniore.org - změna stavu vaší žádosti',
            f'Vaše žádost / nabídka na činnost {requests[0]} dne {requests[4]} byla {text}.'
        )
        return redirect(url_for("profile_bp.user_request_overview"))

    return render_template("request_detail_user.html",
                           entries=requests,
                           acceptButtonVisible=acceptButtonVisible)
Exemplo n.º 12
0
def email_sent():

    # kdo oslovuje
    user = session["user"]
    id_users_services = request.form.get("id", type=int)
    dbUser = DBUser.LoadFromSession('dbUser')
    email_oslovujici = dbUser.email
    name_oslovujici = dbUser.first_name
    surname_oslovujici = dbUser.surname
    # date = request.form.get("date", type=str)
    # time = request.form.get("time", type=str)
    # strDateTime = f"{date} {time}"
    # dt = datetime.strptime(strDateTime, "%Y-%m-%d %H:%M")

    info = request.form.get("info", type=str)

    email_user_long = DBAccess.ExecuteSQL(
        """
    SELECT u.email, u.id, s.id, d.id
    FROM users u
    LEFT JOIN users_services us on us.id_users = u.id
    LEFT JOIN services s on s.id = us.id_services
    LEFT JOIN demand_offer d on d.id = us.id_demand_offer
    WHERE us.id = %s
    """, (id_users_services, ))

    email_user = email_user_long[0][0]  # for testing emails are sent to admin
    services_id = email_user_long[0][2]
    id_demand_offer = email_user_long[0][3]

    offeringUserId = email_user_long[0][
        1] if id_demand_offer == 2 else session["id_user"]
    demandingUserId = email_user_long[0][
        1] if id_demand_offer == 1 else session["id_user"]

    id_request = DBAccess.GetSequencerNextVal("requests_id_seq")
    DBAccess.ExecuteInsert(
        "INSERT INTO requests (id, id_users_demand, id_users_offer, id_services, "
        "timestamp, date_time, add_information, id_requests_status, id_users_creator)"
        " values (%s, %s,%s,%s,now(),now(),%s,%s, %s)",
        (id_request, demandingUserId, offeringUserId, services_id, info, 1,
         session["id_user"]))

    # protistrana, kdo je osloven - email_user
    dbUser_protistrana = DBAccess.GetDBUserByEmail(email_user)
    name_protistrana = dbUser_protistrana.first_name
    surname_protistrana = dbUser_protistrana.surname

    text1 = 'Vaši nabídku' if id_demand_offer == 1 else 'Váš požadavek'

    text2 = 'Vaši nabídky' if id_demand_offer == 1 else 'vašeho požadavku'

    # mail to person who click on "contact"
    SendMail(
        GetEmail('noreplyMail'), f'{email_oslovujici}',
        'Zaregistrována žádost o spolupráci',
        f'''<html>Úspěšně jsme zaregistrovali Vaší žádost o spolupráci. <br> 
    Váš kontakt je {name_protistrana},  email: {email_user} <br>
    Prosíme, spojte se, abyste se mohli domluvit na podrobnostech. Nezapomeňte dodržovat pravidla: <a href="https://app.seniore.org/podminky_dobrovolnici"> dobrovolníci</a> / <a href="https://app.seniore.org/podminky_seniori"> senioři</a><br>
    V případě potíží, nebo nejasností nám neváhejte napsat na [email protected]. <br>
    Děkujeme, Váš tým Seniore</html>''')
    # mail to person who is being contacted
    SendMail(
        GetEmail('noreplyMail'), f'{email_user}',
        'Zaregistrována žádost o spolupráci', f'''
    <html> Pan / paní {name_oslovujici} by se s Vámi rád/a spojil/a ohledně možné pomoci. 
    Kontaktní email je: {email_oslovujici} <br> 
    Prosíme, spojte se, abyste se mohli domluvit na podrobnostech. Nezapomeňte dodržovat pravidla: <a href="https://app.seniore.org/podminky_dobrovolnici"> dobrovolníci</a> / <a href="https://app.seniore.org/podminky_seniori"> senioři</a><br>
    V případě potíží, nebo nejasností nám neváhejte napsat na [email protected]. <br>
    Děkujeme, Váš tým Seniore < / html > ''')
    # mail to admins
    SendMail(
        GetEmail('noreplyMail'), GetEmail('adminMail'),
        'Seniore - zažádáno o spolupráci',
        f'''Uživatel {user} se s chce setkat s {email_user}! :-D <br>
    Doplňující informace: {info}. <br>
    Prosím, zkontrolujte žádost v http://seniore.herokuapp.com/requests_detail?id={id_request}.'''
    )
    # print(response.status_code)
    # print(response.body)
    # print(response.headers)
    return render_template("email_sent.html", text1=text1, text2=text2)
Exemplo n.º 13
0
def profil_editace():

    regForm = ProfilUpdateForm()
    dbUser = DBUser.LoadFromSession('dbUser')
    if (regForm.validate_on_submit()):
        dbUser.first_name = regForm.first_name.data
        dbUser.surname = regForm.surname.data
        dbUser.telephone = regForm.telephone.data
        dbUser.street = regForm.street.data
        # dbUser.street_number = regForm.street_number.data
        dbUser.post_code = regForm.post_code.data
        dbUser.town = regForm.town.data
        dbUser.info = regForm.info.data

        address = "{} {} {}".format(dbUser.street, dbUser.town,
                                    dbUser.post_code)
        coordinates = GetCoordinates(address)
        if (coordinates is not None):
            dbUser.latitude = coordinates[0]
            dbUser.longitude = coordinates[1]
        else:
            flash('Nenalezeny souřadnice pro vaši adresu', FlashStyle.Danger)
            return render_template("profil_editace.html", form=regForm)

        dbUser.UpdateDB()
        dbUser.SaveToSession('dbUser')

        if (regForm.soubor.data is not None
                and regForm.soubor.data.filename != ''):
            file_name = secure_filename(regForm.soubor.data.filename)
            path = os.path.join(app.config["UPLOAD_FOLDER"], file_name)
            regForm.soubor.data.save(path)
            json = UploadImage(path, str(dbUser.id) + 'new')
            version = json['version']

            newImageUrl = GetImageUrl(str(dbUser.id) + 'new', version=version)
            RenameImage(str(dbUser.id) + 'new', str(dbUser.id))
            DeleteImage(str(dbUser.id) + 'new')

            SendMail(
                GetEmail('noreplyMail'), dbUser.email,
                "Seniore.org - schválení profilové fotografie",
                "Vaše nové profilové foto na app.seniore.org bude nahráno na váš profil. Může to chvilku zabrat, mějte, prosím, strpení."
            )

            # ts = URLSafeTimedSerializer(app.config["SECRET_KEY"])
            # token = ts.dumps(dbUser.email, salt='change-photo-key')
            # confirm_url = url_for(
            #     'profile_bp.change_photo_confirm',
            #     token=token,
            #     _external=True)

            # denied_url = url_for(
            #     'profile_bp.change_photo_denied',
            #     token=token,
            #     _external=True)
            # noCacheSufix = '?nocache=<?php echo time(); ?'

            # email_text = f'''Uživatel { dbUser.first_name } {dbUser.surname} {dbUser.email} si změnil profilovou fotografii.  <br>\
            #      <img src={GetImageUrl(dbUser.id)+noCacheSufix}>původní foto</img> <br>\
            #      <img src={newImageUrl+noCacheSufix}>nové foto</img> <br>\
            #     Link pro schválení fotografie {confirm_url} <br>\
            #     Link pro odmítnutí fotografie {denied_url}'''

            # SendMail("*****@*****.**",to_emails,'Seniore.cz - schválení profilové fotografie',email_text)
            # flash("Nová profilová fotografie byla odeslána administrátorovi ke schválení, o výsledku budete informováni emailem.",FlashStyle.Success)
        return redirect(url_for('profile_bp.profil'))

    regForm.first_name.data = dbUser.first_name
    regForm.surname.data = dbUser.surname
    regForm.telephone.data = dbUser.telephone
    regForm.street.data = dbUser.street
    # regForm.street_number.data = dbUser.street_number
    regForm.post_code.data = dbUser.post_code
    regForm.town.data = dbUser.town
    regForm.info.data = dbUser.info
    return render_template("profil_editace.html", form=regForm)