def login():
    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password']

        user = db.get_user_by_email(email)

        error = None

        if user is None:
            error = 'Incorrect email'
        elif not check_password_hash(user.password, password):
            error = 'Incorrect password'

        # redirect if credentials are correct
        if error is None:
            session.clear()
            session['user_id'] = user.id

            return redirect(url_for('index'))

        # flash error on incorrect credentials
        flash(error)

    return render_template('auth/login.html')
示例#2
0
 def post(self, *args, **kwargs):
     email = self.get_argument('email')
     password = self.get_argument('password')
     next = self.get_argument('next', None)
     user = db.get_user_by_email(email)
     if user:
         if password == user['password']:
             self.set_secure_cookie("user_id", user['user_id'])
             return self.redirect(next if next else '/admin')
         else:
             error = 'password invalid'
     else:
         error = 'no such email in db'
     return self.render("admin/login.html", error=error, next=next, email=email)
示例#3
0
def get_user_by_email(email):
    """This function gets user's data by it's email.
    It takes user's email and retrieves user's data from db. After that this
    function creates User object and returns it.
    :Parameters:
        - `email`: email of the user to retrieve.
    :Returns:
        User object, if the row with such email exists in database or None, if
        no row with such email has been found.
    """
    user = None
    if email:
        user = db.get_user_by_email(email)
    if user:
        return User(uid=user[0], first_name=user[1], last_name=user[2],
                    email=user[3], password=user[4], age=user[5],
                    state=user[6], native_lang=user[7])
    return None
示例#4
0
def signup():
    """Signs a new user to the service. On success returns the user object,
       on error returns 400 and json with err-field."""

    input = request.json or {}
    email = input.get('email')
    password = input.get('password')
    fname = input.get('fname')
    lname = input.get('lname')
    company = input.get('company')

    if not email or not password or not fname or not lname:
        return webutil.warn_reply("Invalid signup input")

    u = db.get_user_by_email(email)
    if u:
        msg = "Signup email taken: {}".format(email)
        return webutil.warn_reply(msg)

    err = account.check_password_validity(password)
    if err:
        return jsonify({"err": err}), 400

    # create new user
    u = db.User()
    u.email = email
    u.company = company
    u.first_name = fname
    u.last_name = lname
    u.password = account.hash_password(password)
    u.tags = []
    u.role = 'editor'  # set default to what makes sense to your app
    u.save(force_insert=True)

    account.new_signup_steps(u)
    account.build_session(u, is_permanent=input.get('remember', True))

    log.info("SIGNUP OK agent={}".format(webutil.get_agent()))

    return jsonify(u), 201
示例#5
0
def login():
    """Logs the user in with email+password.
       On success returns the user object,
       on error returns 400 and json with err-field."""

    input = request.json or {}
    email = input.get('email')
    password = input.get('password')

    if not email or not password:
        return webutil.warn_reply("Missing input")

    u = db.get_user_by_email(email)
    if not u or not account.check_password(u.password, password):
        # error
        return webutil.warn_reply("Invalid login credentials")
    else:
        # success
        account.build_session(u, is_permanent=input.get('remember', True))

        log.info("LOGIN OK agent={}".format(webutil.get_agent()))
        return jsonify(u), 200
示例#6
0
if os.environ["REQUEST_METHOD"].upper() == "POST":
    username = params.getvalue("username")
    password = params.getvalue("password")
    password_repeat = params.getvalue("password_repeat")
    email = params.getvalue("email")
    secret_question = params.getvalue("secret_question")
    secret_answer = params.getvalue("secret_answer")

    validation_error = False
    success = False

    if password != password_repeat:
        registration_error += "<br>Passwords must match!"
        validation_error = True

    if db.get_user_by_email(email) != None:
        registration_error += "<br>Email " + email + "already exists!"
        validation_error = True

    if validation_error == False:
        success = authentication.register(username, password, email,
                                          secret_question, secret_answer)
        if success:
            print('Location: login.py')
print("")
base.start_html()
print('''
        <form method="POST">
            username <input type="text" name="username" required /><br>
            password <input type="password" name="password" required/><br>
            repeat password <input type="password" name="password_repeat" required/><br>
示例#7
0
        x = '<button name="%s"%s>%s</button>' % (safename, self.addatts(), label)
        return x

_ = i18n.strings.get_namespace('/account/login')

login = Form(
    Hidden('redirect'),
    Textbox('username', notnull, description=_.username),
    Password('password', notnull, description=_.password),
    Checkbox('remember', description=_.remember_me)
)

vlogin = regexp(r"^[A-Za-z0-9-_]{3,20}$", 'must be between 3 and 20 letters and numbers') 
vpass = regexp(r".{3,20}", 'must be between 3 and 20 characters')
vemail = regexp(r".*@.*", "must be a valid email address")
not_already_used = Validator('This email is already used', lambda email: db.get_user_by_email(context.site, email) is None)

_ = i18n.strings.get_namespace('/account/register')

register = Form(
    Textbox('username', 
            vlogin,
            description=_.username),
    Textbox('displayname', notnull, description=_.display_name),
    Textbox('email', notnull, vemail, description=_.email),
    Password('password', notnull, vpass, description=_.password),
    Password('password2', notnull, description=_.confirm_password),
    validators = [
        Validator(_.passwords_did_not_match, lambda i: i.password == i.password2)]    
)
示例#8
0
def postform():
    """Form POST endpoint for all form variations."""

    input = request.form
    mode = input["mode"]
    email = input["email"]
    passwd = input.get("passwd")
    token = input.get("token")

    u = db.get_user_by_email(email)

    errmsg = ""
    if not email:
        errmsg = "Email is missing"

    elif mode == "login":
        if not u or not account.check_password(u.password, passwd):
            errmsg = "Invalid login credentials"
        else:
            account.build_session(u, is_permanent=True)

            log.info(f"LOGIN OK {email}")

            # you should redirect to real ui...
            return redirect("/api/me")

    elif mode == "signup":
        if u:
            errmsg = f"Account exists already {email}"
        elif passwd != input.get("passwd2"):
            errmsg = f"Passwords differ"
        else:
            errmsg = account.check_password_validity(passwd)
            if not errmsg:
                # create new user
                u = db.User()
                u.email = email
                u.first_name = input["firstname"]
                u.last_name = input["lastname"]
                u.password = account.hash_password(passwd)
                u.role = 'editor'  # set default to what makes sense to your app
                u.save(force_insert=True)

                account.new_signup_steps(u)
                account.build_session(u, is_permanent=True)

                log.info(f"SIGNUP OK {email}")

                # you should redirect to real ui...
                return redirect("/api/me")

    elif mode == "forgot":
        # request a new password
        if u:
            # generate an expiring token and store in redis
            token = str(util.generate_token())
            data = {"uid": f"{u.id}", "ip": get_ip()}
            expire_secs = 60 * 60  # 1h
            red.set_keyval(token, data, expire_secs)

            # email the link to the user
            link = f"DOMAIN/auth/reset?token={token}"
            errmsg = f"Server should now send a reset email to {email}..."
            log.info(f"password reset link = {link}")

        else:
            errmsg = f"Unknown account {email}"

    elif mode == "reset":
        # reset a password
        data = red.get_keyval(token)
        if data:
            try:
                u = db.get_user(data["uid"])

                # extra security: make sure ip addresses match, only the
                # requester can use the link
                if get_ip() != data["ip"]:
                    errmsg = "Invalid IP"

                elif passwd != input.get("passwd2"):
                    errmsg = "Passwords differ"

                else:
                    # ok, reset the password
                    u.password = account.hash_password(passwd)
                    u.save()
                    account.build_session(u, is_permanent=True)

                    # security: disable link from further use
                    red.delete_key(token)

                    log.info(f"PASSWD RESET OK {email}")
                    return redirect("/api/me")

            except:
                log.error(f"no user {value}")
                errmsg = "Invalid token"
        else:
            errmsg = "Invalid token"

    if errmsg:
        log.warn(errmsg)

    return render_template('auth.html',
                           mode=mode,
                           email=email,
                           err=errmsg,
                           token=token)
示例#9
0

_ = i18n.strings.get_namespace('/account/login')

login = Form(Hidden('redirect'),
             Textbox('username', notnull, description=_.username),
             Password('password', notnull, description=_.password),
             Checkbox('remember', description=_.remember_me))

vlogin = regexp(r"^[A-Za-z0-9-_]{3,20}$",
                'must be between 3 and 20 letters and numbers')
vpass = regexp(r".{3,20}", 'must be between 3 and 20 characters')
vemail = regexp(r".*@.*", "must be a valid email address")
not_already_used = Validator(
    'This email is already used',
    lambda email: db.get_user_by_email(context.site, email) is None)

_ = i18n.strings.get_namespace('/account/register')

register = Form(Textbox('username', vlogin, description=_.username),
                Textbox('displayname', notnull, description=_.display_name),
                Textbox('email', notnull, vemail, description=_.email),
                Password('password', notnull, vpass, description=_.password),
                Password('password2', notnull, description=_.confirm_password),
                validators=[
                    Validator(_.passwords_did_not_match,
                              lambda i: i.password == i.password2)
                ])

_ = i18n.strings.get_namespace('/account/preferences')