Exemplo n.º 1
0
def login():
    form = LoginForm(request.form)

    if form.validate_on_submit():
        db_session = DB_Session()
        loginUser = db_session.query(User).filter_by(
            username=form.username.data).first()
        db_session.close()

        if loginUser is not None:
            if pbkdf2_sha256.verify(form.password.data, loginUser.password):
                session['username'] = loginUser.username
                userJson = json.loads(jsonpickle.encode(loginUser))
                # app.logger.info('%s logged in and created session' % loginUser.username)
                # TODO Add logging
                if loginUser.twoFactorAuthEnabled:
                    totp.SetAuthenticator(loginUser.twoFactorAuthKey)
                    return redirect(url_for("twoFactorAuth"))

                return render_template("profile.html", user=userJson)
        return render_template("login.html",
                               form=form,
                               loginError="Wrong username or password")

    return render_template('login.html', form=form)
Exemplo n.º 2
0
def forgotPassword():
    form = ForgotPasswordForm(request.form)

    if form.validate_on_submit():

        if form.code.data != "" and form.email.data != "":
            dbsess = DB_Session()
            user = dbsess.query(User).filter_by(email=form.email.data).first()
            dbsess.close()
            print(user.username)
            if user is not None:
                code = dbsess.query(ResetPwdCode).filter_by(
                    owner=user.username).first()
                if code == form.code.data:
                    return "Succes"
                else:
                    return "Wrong code"
            else:
                render_template

        if form.code.data == "" and validate_email(form.email.data):
            print("sending code to email: %s" % (form.email.data))
            SendAndSaveForgotPasswordCode(form.email.data)

    return render_template('forgotPassword.html', form=form)
Exemplo n.º 3
0
def save_item(item, update_desc=False):
    baidu_id = item.get('id')
    if baidu_id is None:
        return
    session = DB_Session()
    photo = session.query(Photo).filter(Photo.baidu_id==baidu_id).first()
    if not photo:
        photo = Photo(baidu_id=baidu_id,
                      photo_id=item['photo_id'],
                      image_url = item['image_url'],
                      image_width = item['image_width'],
                      image_height = item['image_height'],
                      thumbnail_url = item['thumbnail_url'],
                      thumbnail_width = item['thumbnail_width'],
                      thumbnail_height = item['thumbnail_height'],
                      thumb_large_url = item['thumb_large_url'],
                      thumb_large_width = item['thumb_large_width'],
                      thumb_large_height = item['thumb_large_height'],
                      from_url = item['from_url'],
                      obj_url = item['obj_url'],
                      desc = item['desc'],
                      image_date = item['date'],
                      insert_date = datetime.datetime.now()
                )
        session.add(photo)
        session.commit()
        logging.warn("add one item-%s" % photo.id)
    elif update_desc:
        photo.desc = item['desc']
        session.commit()
        logging.warn("update one item-%s" % photo.id)
    session.close()
Exemplo n.º 4
0
def validate_name(form, field):
    if field.data is not None:
        if len(field.data) > 50:
            raise ValidationError("name must be less en 50 characters")
        if not re.match("^[A-Za-z0-9_-]*$", field.data):
            raise ValidationError("Name can only contain numbers, letters, '-' and '_'")
        db_session = DB_Session()
        usernameCheck = db_session.query(User).filter_by(username = field.data).first()
        db_session.close()
        if usernameCheck is not None:
            if usernameCheck.username != field.data:
                raise ValidationError("Username is already taken")
Exemplo n.º 5
0
def index():
    if 'username' in session:
        db_session = DB_Session()
        loginUser = db_session.query(User).filter_by(
            username=session['username']).first()
        db_session.close()
        if loginUser is not None:
            userJson = json.loads(jsonpickle.encode(loginUser))
            # app.logger.info('%s logged into existing session' % loginUser.username)
            return render_template('profile.html', user=userJson)

    return render_template("index.html")
Exemplo n.º 6
0
def editProfileFunc(loggedInUser, form):
    changedUsername = False
    if form.username.data is not None:
        if form.username.data != loggedInUser.username:
            dbsess = DB_Session()
            dbsess.query(User).filter(username=loggedInUser.username).update(
                {'username': form.username.data})
            dbsess.commit()
            dbsess.close()
            changedUsername = True

    if form.password.data is not None:
        if loggedInUser.username != pbkdf2_sha256.hash(form.password.data):
            dbsess = DB_Session()
            dbsess.query(User).filter(username=loggedInUser.username).update(
                {'password': pbkdf2_sha256.hash(form.password.data)})
            dbsess.commit()
            dbsess.close()

    if form.email.data is not None:
        if loggedInUser.email != form.email.data:
            dbsess = DB_Session()
            dbsess.query(User).filter(username=loggedInUser.username).update(
                {'email': form.email.data})
            dbsess.commit()
            dbsess.close()

    if changedUsername:
        dbsess = DB_Session()
        changedUser = dbsess.query(User).filter_by(
            username=form.username.data).first()
        dbsess.close()
        session['username'] = changedUser.username
Exemplo n.º 7
0
    def __init__(self):
        sess = DB_Session()
        roles = sess.query(Role).all()
        if (len(roles) == 0):
            normal = Role("normal")
            admin = Role("admin")
            helpdesk = Role("helpdesk")

            sess.add(normal)
            sess.add(admin)
            sess.add(helpdesk)

            sess.commit()
        sess.close()
Exemplo n.º 8
0
def twoFactorAuth():
    form = TwoFactorAuthForm(request.form)
    if form.validate_on_submit():
        if (totp.Verify(form.verify.data)):
            db_session = DB_Session()
            loginUser = db_session.query(User).filter_by(
                username=session['username']).first()
            db_session.close()
            userJson = json.loads(jsonpickle.encode(loginUser))
            return render_template("profile.html", user=userJson)
        else:
            return render_template("twoFactorAuth.html",
                                   form=form,
                                   error="Wrong code")

    return render_template('twoFactorAuth.html', form=form)
Exemplo n.º 9
0
def register():
    form = RegistrationForm(request.form)
    if form.validate_on_submit():
        db_session = DB_Session()

        hashedPWD = pbkdf2_sha256.hash(form.password.data)

        newUser = User(form.username.data, hashedPWD, form.email.data,
                       form.twoFactorAuthEnabled.data,
                       form.twoFactorAuthKey.data)
        db_session.add(newUser)

        db_session.commit()
        db_session.close()
        # app.logger.info('Account created with username: %s' % form.username.data)

        return render_template('index.html')

    return render_template('register.html', form=form)
Exemplo n.º 10
0
    def __init__(self):
        sess = DB_Session()
        users = sess.query(User).all()
        if len(users) == 0:

            sess.add(
                User('Piet', '*****@*****.**',
                     pbkdf2_sha256.hash('Asdf1234'), True,
                     'averylonglonglongkey', 1))
            sess.add(
                User('Klaas', '*****@*****.**',
                     pbkdf2_sha256.hash('Asdf1234'), True,
                     'averytalltalltallkey', 2))
            sess.add(
                User('Freek', '*****@*****.**',
                     pbkdf2_sha256.hash('Asdf1234'), True,
                     'averyhandsomelongkey', 3))

            sess.commit()
        sess.close()
Exemplo n.º 11
0
def SendAndSaveForgotPasswordCode(email):
    code = os.urandom(8)

    content = "Yo dog here's your code to reset your password: \n <b>%s</b>" % (
        code)

    print(email)
    try:
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.ehlo()
        server.starttls()
        server.login('*****@*****.**', 'Geheimlol!1')
        server.sendmail('*****@*****.**', email, content)
        server.close()

        dbsess = DB_Session()
        user = dbsess.query(User).filter_by(email=email).first()
        newCode = ResetPwdCode(owner=user.username, code=code)
        dbsess.add(newCode)
        dbsess.commit()
        dbsess.close()
    except:
        pass
Exemplo n.º 12
0
def getUser():
    db_session = DB_Session()
    user = db_session.query(User).filter_by(
        username=session['username']).first()
    db_session.close()
    return user
Exemplo n.º 13
0
def allUsers():
    db_session = DB_Session()
    allUsers = db_session.query(User).all()
    db_session.close()
    return render_template('allUsers.html', allUsers=allUsers)
Exemplo n.º 14
0
    def validate(self):
        validated = True

        if self.loggedInUser is None:
            validated = False

        # means the user has changed his password, so we have to add the usual validators manually here since this is a special case form
        if self.password.data is not None:
            if not pbkdf2_sha256.verify(self.password.data,
                                        self.loggedInUser.password):
                errorList = []
                pwd = self.password.data
                if not (any(x.isupper() for x in pwd) and any(x.islower()
                                                              for x in pwd)
                        and any(x.isdigit() for x in pwd)):
                    errorList.append(
                        "Password must contain at least 1 capital, 1 lower case letter and at least 1 number"
                    )
                if len(pwd) <= 7:
                    errorList.append("Must be at least 8 characters long")
                self.password.errors = tuple(errorList)
                validated = False

        ## to check if the user changed his username and if so, if the new username already exists in database
        dbsess = DB_Session()
        userCheck = dbsess.query(User).filter_by(
            username=self.username.data).first()
        dbsess.close()
        if self.username.data != self.loggedInUser.username:
            if self.username.data is not None:
                errorList = []
                if userCheck is not None:
                    errorList.append('username already taken')
                    validated = False

                if len(self.username.data) > 50:
                    errorList.append(
                        'username must be less than 50 characters long')
                    validated = False

                if not re.match("^[A-Za-z0-9_-]*$", self.username.data):
                    errorList.append(
                        "Name can only contain numbers, letters, '-' and '_'")
                    validated = False

                self.username.errors = tuple(errorList)

        if self.email.data != self.loggedInUser.email:
            if self.email.data is not None:
                errorList = []
                if not validate_email:
                    errorList.append('Should be a valid email')
                    self.email.errors = tuple(errorList)
                    validated = False

        if not pbkdf2_sha256.verify(self.old_password.data,
                                    self.loggedInUser.password):
            errorList = []
            if self.old_password is None:
                errorList.append(
                    "Current password is required, when trying to change your profile."
                )
            else:
                errorList.append("Wrong current password.")
            self.old_password.errors = tuple(errorList)
            validated = False

        return validated