コード例 #1
0
ファイル: html.py プロジェクト: optimumtact/sr.ht
def disown():
    if request.method == 'GET':
        filename = request.args.get('filename')
        Upload.query.filter_by(path=filename).first().hidden = True
        db.commit()
        return redirect("%s://%s/uploads" % (_cfg('protocol'), _cfg('domain')))
    return render_template("not_found.html")
コード例 #2
0
ファイル: oauth.py プロジェクト: TheReverend403/u.pste.pw
def exchange():
    client_id = request.form.get("client_id")
    client_secret = request.form.get("client_secret")
    code = request.form.get("code")
    if not client_id:
        return { "error": "Missing client_id" }, 400

    client = OAuthClient.query.filter(OAuthClient.client_id == client_id).first()
    if not client:
        return { "error": "Unknown client" }, 404

    if client.client_secret != client_secret:
        return { "error": "Incorrect client secret" }, 401

    r = redis.Redis(unix_socket_path=_cfg("socket"), db=_cfg("database"))
    _client_id = r.get("oauth.exchange.client." + code)
    user_id = r.get("oauth.exchange.user." + code)
    if not client_id or not user_id:
        return { "error": "Unknown or expired exchange code" }, 404

    _client_id = _client_id.decode("utf-8")
    user_id = int(user_id.decode("utf-8"))
    user = User.query.filter(User.id == user_id).first()
    if not user or _client_id != client.client_id:
        return { "error": "Unknown or expired exchange code" }, 404

    token = OAuthToken.query.filter(OAuthToken.client == client, OAuthToken.user == user).first()
    if not token:
        token = OAuthToken(user, client)
        db.add(token)
        db.commit()

    r.delete("oauth.exchange.client." + code)
    r.delete("oauth.exchange.user." + code)
    return { "token": token.token }
コード例 #3
0
ファイル: html.py プロジェクト: lzimann/sr.ht
def disown():
    if request.method == 'GET':
        filename = request.args.get('filename')
        Upload.query.filter_by(path=filename).first().hidden = True
        db.commit()
        return redirect("%s://%s/uploads" % (_cfg('protocol'), _cfg('domain')))
    return render_template("not_found.html")
コード例 #4
0
ファイル: email.py プロジェクト: optimumtact/sr.ht
def send_reset(user):
    if _cfg("smtp-host") == "":
        return
    smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port"))
    smtp.starttls()
    smtp.ehlo()
    smtp.login(_cfg("smtp-user"), _cfg("smtp-password"))
    with open("emails/reset") as f:
        message = MIMEText(
            html.parser.HTMLParser().unescape(
                pystache.render(
                    f.read(),
                    {
                        "user": user,
                        "domain": _cfg("domain"),
                        "protocol": _cfg("protocol"),
                        "confirmation": user.passwordReset,
                    },
                )
            )
        )
    message["X-MC-Important"] = "true"
    message["X-MC-PreserveRecipients"] = "false"
    message["Subject"] = "Reset your %s password" % _cfg("domain")
    message["From"] = _cfg("smtp-from")
    message["To"] = user.email
    smtp.sendmail(_cfg("smtp-from"), [user.email], message.as_string())
    smtp.quit()
コード例 #5
0
ファイル: email.py プロジェクト: Ninja3047/sr.ht
def send_rejection(user):
    if _cfg("smtp-host") == "":
        return
    smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port"))
    smtp.login(_cfg("smtp-user"), _cfg("smtp-password"))
    with open("emails/reject") as f:
        message = MIMEText(f.read())
    message['X-MC-Important'] = "true"
    message['X-MC-PreserveRecipients'] = "false"
    message['Subject'] = "Your sr.ht account has been rejected"
    message['From'] = "*****@*****.**"
    message['To'] = user.email
    smtp.sendmail("*****@*****.**", [ user.email ], message.as_string())
    smtp.quit()
コード例 #6
0
def send_rejection(user):
    if _cfg("smtp-host") == "":
        return
    smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port"))
    smtp.login(_cfg("smtp-user"), _cfg("smtp-password"))
    with open("emails/reject") as f:
        message = MIMEText(f.read())
    message['X-MC-Important'] = "true"
    message['X-MC-PreserveRecipients'] = "false"
    message['Subject'] = "Your sr.ht account has been rejected"
    message['From'] = "*****@*****.**"
    message['To'] = user.email
    smtp.sendmail("*****@*****.**", [user.email], message.as_string())
    smtp.quit()
コード例 #7
0
ファイル: api.py プロジェクト: optimumtact/sr.ht
def upload():
    key = request.form.get('key')
    f = request.files.get('file')
    if not key:
        return { "error": "API key is required" }, 401
    if not f:
        return { "error": "File is required" }, 400
    user = User.query.filter(User.apiKey == key).first()
    if not user:
        return { "error": "API key not recognized" }, 403
    filename = ''.join(c for c in f.filename if c.isalnum() or c == '.')
    upload = Upload()
    upload.user = user
    upload.hash = get_hash(f)
    existing = Upload.query.filter(Upload.hash == upload.hash).first()
    if existing:
        db.rollback()#file already exists, end this session
        return {
            "success": True,
            "hash": existing.hash,
            "shorthash": existing.shorthash,
            "url": file_link(existing.path)
        }
    len = 4
    shorthash = upload.hash[:len]
    while any(Upload.query.filter(Upload.shorthash == shorthash)):
        len += 1
        shorthash = upload.hash[:len]
    upload.shorthash = shorthash
    upload.path = os.path.join(upload.shorthash + "." + extension(filename))
    upload.original_name = f.filename

    f.seek(0)
    f.save(os.path.join(_cfg("storage"), upload.path))

    if upload.shorthash is None:
        return {
            "success": False,
            "error": "Upload interrupted"
        }

    db.add(upload)
    db.commit()
    return {
        "success": True,
        "hash": upload.hash,
        "shorthash": upload.shorthash,
        "url": _cfg("protocol") + "://" + _cfg("domain") + "/" + upload.path
    }
コード例 #8
0
ファイル: html.py プロジェクト: optimumtact/sr.ht
def delete():
    if request.method == 'GET':
        filename = request.args.get('filename')
        returnto = request.args.get('return_to')
        if returnto:
            returnto = urllib.parse.unquote_plus(returnto)
        else:
            returnto = "{0}://{1}/uploads".format(_cfg('protocol'), _cfg('domain'))

        file = Upload.query.filter_by(path=filename).first()
        if file and (current_user.admin or current_user == file.user):
            db.delete(file)
            db.commit()
            os.remove(os.path.join(_cfg("storage"), file.path))
            return redirect(returnto)
    return render_template("not_found.html")
コード例 #9
0
def index():
    if current_user and current_user.approved:
        new = datetime.now() - timedelta(hours=24) < current_user.approvalDate
        total = Upload.query.count()
        st = os.statvfs("/")
        free_space = st.f_bavail * st.f_frsize
        total_space = st.f_blocks * st.f_frsize
        used_space = (st.f_blocks - st.f_bfree) * st.f_frsize
        approvals = User.query.filter(User.approved == False).filter(
            User.rejected == False).count()
        return render_template("index-member.html", new=new, total=total, \
                used_space=used_space, free_space=free_space, total_space=total_space, approvals=approvals)
    registration = False
    if _cfg("registration") and _cfg("registration") == "True":
        registration = True
    return render_template("index.html", registration=registration)
コード例 #10
0
def register():
    errors = list()
    registration = True
    if _cfg("registration") and _cfg("registration") != "True":
        registration = False
        errors.append('Registration is currently disabled')

    email = request.form.get('email')
    username = request.form.get('username')
    password = request.form.get('password')
    comments = request.form.get('comments')
    if not email:
        errors.append('Email is required.')
    else:
        if not re.match(r"^[^@]+@[^@]+\.[^@]+$", email):
            errors.append('Please use a valid email address.')
        if User.query.filter(User.username.ilike(username)).first():
            errors.append('This username is already in use.')
    if not username:
        errors.append('Username is required.')
    else:
        if not re.match(r"^[A-Za-z0-9_]+$", username):
            errors.append('Usernames are letters, numbers, underscores only.')
        if len(username) < 3 or len(username) > 24:
            errors.append('Username must be between 3 and 24 characters.')
        if User.query.filter(User.username.ilike(username)).first():
            errors.append('This username is already in use.')
    if not password:
        errors.append('Password is required.')
    else:
        if len(password) < 5 or len(password) > 256:
            errors.append('Password must be between 5 and 256 characters.')
    if len(errors) != 0:
        return render_template("index.html",
                               username=username,
                               email=email,
                               errors=errors,
                               registration=registration)
    # All good, create an account for them
    user = User(username, email, password)
    user.comments = comments
    db.add(user)
    db.commit()
    send_request_notification(user)
    return render_template("index.html",
                           registered=True,
                           registration=registration)
コード例 #11
0
def upload():
    key = request.form.get('key')
    f = request.files.get('file')
    if not key:
        return {"error": "API key is required"}, 401
    if not f:
        return {"error": "File is required"}, 400
    user = User.query.filter(User.apiKey == key).first()
    if not user:
        return {"error": "API key not recognized"}, 403
    filename = ''.join(c for c in f.filename if c.isalnum() or c == '.')
    upload = Upload()
    upload.user = user
    upload.hash = get_hash(f)
    existing = Upload.query.filter(Upload.hash == upload.hash).first()
    if existing:
        db.rollback()  #file already exists, end this session
        return {
            "success": True,
            "hash": existing.hash,
            "shorthash": existing.shorthash,
            "url": file_link(existing.path)
        }
    len = 4
    shorthash = upload.hash[:len]
    while any(Upload.query.filter(Upload.shorthash == shorthash)):
        len += 1
        shorthash = upload.hash[:len]
    upload.shorthash = shorthash
    upload.path = os.path.join(upload.shorthash + "." + extension(filename))
    upload.original_name = f.filename

    f.seek(0)
    f.save(os.path.join(_cfg("storage"), upload.path))

    if upload.shorthash is None:
        return {"success": False, "error": "Upload interrupted"}

    db.add(upload)
    db.commit()
    return {
        "success": True,
        "hash": upload.hash,
        "shorthash": upload.shorthash,
        "url": _cfg("protocol") + "://" + _cfg("domain") + "/" + upload.path
    }
コード例 #12
0
ファイル: html.py プロジェクト: lzimann/sr.ht
def delete():
    if request.method == 'GET':
        filename = request.args.get('filename')
        returnto = request.args.get('return_to')
        if returnto:
            returnto = urllib.parse.unquote_plus(returnto)
        else:
            returnto = "{0}://{1}/uploads".format(_cfg('protocol'),
                                                  _cfg('domain'))

        file = Upload.query.filter_by(path=filename).first()
        if file and (current_user.admin or current_user == file.user):
            db.delete(file)
            db.commit()
            os.remove(os.path.join(_cfg("storage"), file.path))
            return redirect(returnto)
    return render_template("not_found.html")
コード例 #13
0
ファイル: oauth.py プロジェクト: TheReverend403/u.pste.pw
def authorize_POST():
    client_id = request.form.get("client_id")
    if not client_id:
        return render_template("oauth-authorize.html", errors="Missing client_id")
    client = OAuthClient.query.filter(OAuthClient.client_id == client_id).first()
    if not client:
        abort(404)
    salt = os.urandom(40)
    code = hashlib.sha256(salt).hexdigest()[:10]
    r = redis.Redis(unix_socket_path=_cfg("socket"), db=_cfg("database"))
    r.setex("oauth.exchange.client." + code, client_id, 600) # expires in 10 minutes
    r.setex("oauth.exchange.user." + code, current_user.id, 600)
    params = {
        "code": code
    }
    parts = list(urllib.parse.urlparse(client.redirect_uri))
    parsed = urllib.parse.parse_qs(parts[4])
    parsed.update(params)
    parts[4] = urllib.parse.urlencode(parsed)
    return redirect(urllib.parse.urlunparse(parts))
コード例 #14
0
ファイル: email.py プロジェクト: optimumtact/sr.ht
def send_request_notification(user):
    if _cfg("smtp-host") == "":
        return
    smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port"))
    smtp.ehlo()
    smtp.starttls()
    smtp.login(_cfg("smtp-user"), _cfg("smtp-password"))
    with open("emails/new_request") as f:
        message = MIMEText(
            html.parser.HTMLParser().unescape(
                pystache.render(f.read(), {"user": user, "domain": _cfg("domain"), "protocol": _cfg("protocol")})
            )
        )
    message["X-MC-Important"] = "true"
    message["X-MC-PreserveRecipients"] = "false"
    message["Subject"] = "New %s account request" % _cfg("domain")
    message["From"] = _cfg("smtp-from")
    message["To"] = _cfg("owner_email")
    smtp.sendmail(_cfg("smtp-from"), [_cfg("owner_email")], message.as_string())
    smtp.quit()
コード例 #15
0
ファイル: oauth.py プロジェクト: lzimann/sr.ht
def authorize_POST():
    client_id = request.form.get("client_id")
    if not client_id:
        return render_template("oauth-authorize.html",
                               errors="Missing client_id")
    client = OAuthClient.query.filter(
        OAuthClient.client_id == client_id).first()
    if not client:
        abort(404)
    salt = os.urandom(40)
    code = hashlib.sha256(salt).hexdigest()[:10]
    r = redis.Redis(unix_socket_path=_cfg("socket"), db=_cfg("database"))
    r.setex("oauth.exchange.client." + code, client_id,
            600)  # expires in 10 minutes
    r.setex("oauth.exchange.user." + code, current_user.id, 600)
    params = {"code": code}
    parts = list(urllib.parse.urlparse(client.redirect_uri))
    parsed = urllib.parse.parse_qs(parts[4])
    parsed.update(params)
    parts[4] = urllib.parse.urlencode(parsed)
    return redirect(urllib.parse.urlunparse(parts))
コード例 #16
0
ファイル: html.py プロジェクト: optimumtact/sr.ht
def login():
    if request.method == 'GET':
        if current_user:
            return redirect("%s://%s/" % (_cfg('protocol'), _cfg('domain')))
        reset = request.args.get('reset') == '1'
        return render_template("login.html", **{ 'return_to': request.args.get('return_to'), 'reset': reset })
    else:
        username = request.form['username']
        password = request.form['password']
        remember = request.form.get('remember-me')
        if remember == "on":
            remember = True
        else:
            remember = False
        user = User.query.filter(User.username.ilike(username)).first()
        if not user:
            return render_template("login.html", **{ "username": username, "errors": 'Your username or password is incorrect.' })
        if not bcrypt.hashpw(password.encode('UTF-8'), user.password.encode('UTF-8')) == user.password.encode('UTF-8'):
            return render_template("login.html", **{ "username": username, "errors": 'Your username or password is incorrect.' })
        if not user.approved:
            return redirect("%s://%s/pending" % (_cfg('protocol'), _cfg('domain')))
        login_user(user, remember=remember)
        if 'return_to' in request.form and request.form['return_to']:
            return redirect(urllib.parse.unquote(request.form.get('return_to')))
        return redirect("%s://%s/" % (_cfg('protocol'), _cfg('domain')))
コード例 #17
0
ファイル: html.py プロジェクト: optimumtact/sr.ht
def reset_password(username, confirmation):
    user = User.query.filter(User.username == username).first()
    if not user:
        redirect("%s://%s/" % (_cfg('protocol'), _cfg('domain')))
    if request.method == 'GET':
        if user.passwordResetExpiry == None or user.passwordResetExpiry < datetime.now():
            return render_template("reset.html", expired=True)
        if user.passwordReset != confirmation:
            redirect("%s://%s/" % (_cfg('protocol'), _cfg('domain')))
        return render_template("reset.html", username=username, confirmation=confirmation)
    else:
        if user.passwordResetExpiry == None or user.passwordResetExpiry < datetime.now():
            abort(401)
        if user.passwordReset != confirmation:
            abort(401)
        password = request.form.get('password')
        password2 = request.form.get('password2')
        if not password or not password2:
            return render_template("reset.html", username=username, confirmation=confirmation, errors="Please fill out both fields.")
        if password != password2:
            return render_template("reset.html", username=username, confirmation=confirmation, errors="You seem to have mistyped one of these, please try again.")
        user.set_password(password)
        user.passwordReset = None
        user.passwordResetExpiry = None
        db.commit()
        return redirect("%s://%s/login?reset=1" % (_cfg('protocol'), _cfg('domain')))
コード例 #18
0
ファイル: oauth.py プロジェクト: lzimann/sr.ht
def exchange():
    client_id = request.form.get("client_id")
    client_secret = request.form.get("client_secret")
    code = request.form.get("code")
    if not client_id:
        return {"error": "Missing client_id"}, 400

    client = OAuthClient.query.filter(
        OAuthClient.client_id == client_id).first()
    if not client:
        return {"error": "Unknown client"}, 404

    if client.client_secret != client_secret:
        return {"error": "Incorrect client secret"}, 401

    r = redis.Redis(unix_socket_path=_cfg("socket"), db=_cfg("database"))
    _client_id = r.get("oauth.exchange.client." + code)
    user_id = r.get("oauth.exchange.user." + code)
    if not client_id or not user_id:
        return {"error": "Unknown or expired exchange code"}, 404

    _client_id = _client_id.decode("utf-8")
    user_id = int(user_id.decode("utf-8"))
    user = User.query.filter(User.id == user_id).first()
    if not user or _client_id != client.client_id:
        return {"error": "Unknown or expired exchange code"}, 404

    token = OAuthToken.query.filter(OAuthToken.client == client,
                                    OAuthToken.user == user).first()
    if not token:
        token = OAuthToken(user, client)
        db.add(token)
        db.commit()

    r.delete("oauth.exchange.client." + code)
    r.delete("oauth.exchange.user." + code)
    return {"token": token.token}
コード例 #19
0
ファイル: email.py プロジェクト: p440/sr.ht
def send_rejection(user):
    if _cfg("smtp-host") == "":
        return
    smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port"))
    smtp.starttls()
    smtp.ehlo()
    smtp.login(_cfg("smtp-user"), _cfg("smtp-password"))
    with open("emails/reject") as f:
        message = MIMEText(html.parser.HTMLParser().unescape(
            pystache.render(f.read(), {
                'user': user,
                "domain": _cfg("domain"),
                "protocol": _cfg("protocol")
            })))
    message['X-MC-Important'] = "true"
    message['X-MC-PreserveRecipients'] = "false"
    message['Subject'] = "Your %s account has been rejected" % _cfg("domain")
    message['From'] = _cfg("smtp-from")
    message['To'] = user.email
    smtp.sendmail(_cfg("smtp-from"), [ user.email ], message.as_string())
    smtp.quit()
コード例 #20
0
ファイル: email.py プロジェクト: CarpyCar/cpcr.io
def send_invite(user):
    if _cfg("smtp-host") == "":
        return
    smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port"))
    smtp.ehlo()
    smtp.starttls()
    smtp.login(_cfg("smtp-user"), _cfg("smtp-password"))
    with open("emails/invite") as f:
        message = MIMEText(html.parser.HTMLParser().unescape(\
            pystache.render(f.read(), {
                'user': user,
                "domain": _cfg("domain"),
                "protocol": _cfg("protocol")
            })))
    message['Subject'] = "Your sr.ht account is approved"
    message['From'] = _cfg("smtp-user")
    message['To'] = user.email
    smtp.sendmail(_cfg("smtp-user"), [user.email], message.as_string())
    smtp.quit()
コード例 #21
0
def delete():
    key = request.form.get('key')
    filename = request.form.get('filename')
    if not key:
        return {"error": "API key is required"}, 401
    if not filename:
        return {"error": "File is required"}, 400
    user = User.query.filter(User.apiKey == key).first()
    if not user:
        return {"error": "API key not recognized"}, 403
    file = Upload.query.filter_by(path=filename).first()
    if file and (user.admin or user == file.user):
        db.delete(file)
        os.remove(os.path.join(_cfg("storage"), file.path))
        db.commit()
        return {"success": True, "filename": filename}

    else:
        return {"error": "File doesn't exist or is not belonging to you"}, 400
コード例 #22
0
ファイル: email.py プロジェクト: CarpyCar/cpcr.io
def send_rejection(user):
    if _cfg("smtp-host") == "":
        return
    smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port"))
    smtp.ehlo()
    smtp.starttls()
    smtp.login(_cfg("smtp-user"), _cfg("smtp-password"))
    with open("emails/reject") as f:
        message = MIMEText(f.read())
    message['Subject'] = "Your sr.ht account has been rejected"
    message['From'] = _cfg("smtp-user")
    message['To'] = user.email
    smtp.sendmail(_cfg("smtp-user"), [user.email], message.as_string())
    smtp.quit()
コード例 #23
0
ファイル: app.py プロジェクト: minus7/sr.ht
def inject():
    return {
        'root': _cfg("protocol") + "://" + _cfg("domain"),
        'domain': _cfg("domain"),
        'protocol': _cfg("protocol"),
        'len': len,
        'any': any,
        'request': request,
        'locale': locale,
        'url_for': url_for,
        'user': current_user,
        'random': random,
        'owner': _cfg("owner"),
        'owner_email': _cfg("owner_email"),
    }
コード例 #24
0
ファイル: api.py プロジェクト: optimumtact/sr.ht
def delete():
    key = request.form.get('key')
    filename = request.form.get('filename')
    if not key:
        return { "error": "API key is required" }, 401
    if not filename:
        return { "error": "File is required" }, 400
    user = User.query.filter(User.apiKey == key).first()
    if not user:
        return { "error": "API key not recognized" }, 403
    file = Upload.query.filter_by(path=filename).first()
    if file and (user.admin or user == file.user):
        db.delete(file)
        os.remove(os.path.join(_cfg("storage"), file.path))
        db.commit()
        return {
                "success": True,
                "filename": filename
        }

    else:
    	return { "error": "File doesn't exist or is not belonging to you" }, 400
コード例 #25
0
def inject():
    return {
        'root': _cfg("protocol") + "://" + _cfg("domain"),
        'domain': _cfg("domain"),
        'protocol': _cfg("protocol"),
        'len': len,
        'any': any,
        'request': request,
        'locale': locale,
        'url_for': url_for,
        'file_link': file_link,
        'disown_link': disown_link,
        'user': current_user,
        'random': random,
        'owner': _cfg("owner"),
        'owner_email': _cfg("owner_email"),
        '_cfg': _cfg
    }
コード例 #26
0
ファイル: email.py プロジェクト: Ninja3047/sr.ht
def send_invite(user):
    if _cfg("smtp-host") == "":
        return
    smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port"))
    smtp.login(_cfg("smtp-user"), _cfg("smtp-password"))
    with open("emails/invite") as f:
        message = MIMEText(html.parser.HTMLParser().unescape(\
            pystache.render(f.read(), {
                'user': user,
                "domain": _cfg("domain"),
                "protocol": _cfg("protocol")
            })))
    message['X-MC-Important'] = "true"
    message['X-MC-PreserveRecipients'] = "false"
    message['Subject'] = "Your sr.ht account is approved"
    message['From'] = "*****@*****.**"
    message['To'] = user.email
    smtp.sendmail("*****@*****.**", [ user.email ], message.as_string())
    smtp.quit()
コード例 #27
0
def send_reset(user):
    if _cfg("smtp-host") == "":
        return
    smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port"))
    smtp.login(_cfg("smtp-user"), _cfg("smtp-password"))
    with open("emails/reset") as f:
        message = MIMEText(html.parser.HTMLParser().unescape(\
            pystache.render(f.read(), {
                'user': user,
                "domain": _cfg("domain"),
                "protocol": _cfg("protocol"),
                'confirmation': user.passwordReset
            })))
    message['X-MC-Important'] = "true"
    message['X-MC-PreserveRecipients'] = "false"
    message['Subject'] = "Reset your sr.ht password"
    message['From'] = "*****@*****.**"
    message['To'] = user.email
    smtp.sendmail("*****@*****.**", [user.email], message.as_string())
    smtp.quit()
コード例 #28
0
def login():
    if request.method == 'GET':
        if current_user:
            return redirect("%s://%s/" % (_cfg('protocol'), _cfg('domain')))
        reset = request.args.get('reset') == '1'
        return render_template(
            "login.html", **{
                'return_to': request.args.get('return_to'),
                'reset': reset
            })
    else:
        username = request.form['username']
        password = request.form['password']
        remember = request.form.get('remember-me')
        if remember == "on":
            remember = True
        else:
            remember = False
        user = User.query.filter(User.username.ilike(username)).first()
        if not user:
            return render_template(
                "login.html", **{
                    "username": username,
                    "errors": 'Your username or password is incorrect.'
                })
        if not bcrypt.hashpw(password.encode('UTF-8'),
                             user.password.encode(
                                 'UTF-8')) == user.password.encode('UTF-8'):
            return render_template(
                "login.html", **{
                    "username": username,
                    "errors": 'Your username or password is incorrect.'
                })
        if not user.approved:
            return redirect("%s://%s/pending" %
                            (_cfg('protocol'), _cfg('domain')))
        login_user(user, remember=remember)
        if 'return_to' in request.form and request.form['return_to']:
            return redirect(urllib.parse.unquote(
                request.form.get('return_to')))
        return redirect("%s://%s/" % (_cfg('protocol'), _cfg('domain')))
コード例 #29
0
def reset_password(username, confirmation):
    user = User.query.filter(User.username == username).first()
    if not user:
        redirect("%s://%s/" % (_cfg('protocol'), _cfg('domain')))
    if request.method == 'GET':
        if user.passwordResetExpiry == None or user.passwordResetExpiry < datetime.now(
        ):
            return render_template("reset.html", expired=True)
        if user.passwordReset != confirmation:
            redirect("%s://%s/" % (_cfg('protocol'), _cfg('domain')))
        return render_template("reset.html",
                               username=username,
                               confirmation=confirmation)
    else:
        if user.passwordResetExpiry == None or user.passwordResetExpiry < datetime.now(
        ):
            abort(401)
        if user.passwordReset != confirmation:
            abort(401)
        password = request.form.get('password')
        password2 = request.form.get('password2')
        if not password or not password2:
            return render_template("reset.html",
                                   username=username,
                                   confirmation=confirmation,
                                   errors="Please fill out both fields.")
        if password != password2:
            return render_template(
                "reset.html",
                username=username,
                confirmation=confirmation,
                errors=
                "You seem to have mistyped one of these, please try again.")
        user.set_password(password)
        user.passwordReset = None
        user.passwordResetExpiry = None
        db.commit()
        return redirect("%s://%s/login?reset=1" %
                        (_cfg('protocol'), _cfg('domain')))
コード例 #30
0
ファイル: app.py プロジェクト: lzimann/sr.ht
def inject():
    return {
        'root': _cfg("protocol") + "://" + _cfg("domain"),
        'domain': _cfg("domain"),
        'protocol': _cfg("protocol"),
        'len': len,
        'any': any,
        'request': request,
        'locale': locale,
        'url_for': url_for,
        'file_link': file_link,
        'disown_link': disown_link,
        'delete_link': delete_link,
        'admin_delete_link': admin_delete_link,
        'user': current_user,
        'random': random,
        'owner': _cfg("owner"),
        'owner_email': _cfg("owner_email"),
        'git_repo': _cfg("git_repo"),
        'irc_server': _cfg("irc_server"),
        'irc_channel': _cfg("irc_channel"),
        'donate_link': _cfg("donate_link"),
        'donate_button_image': _cfg("donate_button_image"),
        'site_cost': _cfg("site_cost"),
        'current_financial_status': _cfg("current_financial_status"),
        '_cfg': _cfg
    }
コード例 #31
0
ファイル: app.py プロジェクト: lzimann/sr.ht
import sys
import os
import locale

from srht.config import _cfg, _cfgi
from srht.database import db, init_db
from srht.objects import User
from srht.common import *
from srht.network import *

from srht.blueprints.html import html
from srht.blueprints.api import api
from srht.blueprints.oauth import oauth

app = Flask(__name__)
app.secret_key = _cfg("secret-key")
app.jinja_env.cache = None
init_db()
login_manager = LoginManager()
login_manager.init_app(app)

app.jinja_loader = ChoiceLoader([
    FileSystemLoader("overrides"),
    FileSystemLoader("templates"),
])


@login_manager.user_loader
def load_user(username):
    return User.query.filter(User.username == username).first()
コード例 #32
0
from srht.app import app
from srht.config import _cfg, _cfgi

import os

app.static_folder = os.path.join(os.getcwd(), "static")

import os
if __name__ == '__main__':
    app.run(host=_cfg("debug-host"), port=_cfgi('debug-port'), debug=True)
コード例 #33
0
def logout():
    logout_user()
    return redirect("%s://%s/" % (_cfg('protocol'), _cfg('domain')))
コード例 #34
0
ファイル: html.py プロジェクト: optimumtact/sr.ht
def script_plain():
    with open("templates/pstepw", "r") as f:
        resp = f.read().replace('{{ protocol }}', _cfg('protocol'))
        resp = resp.replace('{{ domain }}', _cfg('domain'))
    return Response(resp, mimetype="text/plain")
コード例 #35
0
ファイル: common.py プロジェクト: optimumtact/sr.ht
def file_link(path):
    return _cfg("protocol") + "://" + _cfg("domain") + "/" + path
コード例 #36
0
ファイル: app.py プロジェクト: CarpyCar/cpcr.io
import sys
import os
import locale

from srht.config import _cfg, _cfgi
from srht.database import db, init_db
from srht.objects import User
from srht.common import *
from srht.network import *

from srht.blueprints.html import html
from srht.blueprints.api import api
from srht.blueprints.oauth import oauth

app = Flask(__name__)
app.secret_key = _cfg("secret-key")
app.jinja_env.cache = None
init_db()
login_manager = LoginManager()
login_manager.init_app(app)

app.jinja_loader = ChoiceLoader([
    FileSystemLoader("overrides"),
    FileSystemLoader("templates"),
])

@login_manager.user_loader
def load_user(username):
    return User.query.filter(User.username == username).first()

login_manager.anonymous_user = lambda: None
コード例 #37
0
ファイル: common.py プロジェクト: CarpyCar/cpcr.io
def file_link(path):
    return _cfg("protocol") + "://" + _cfg("domain") + "/" + path
コード例 #38
0
ファイル: html.py プロジェクト: optimumtact/sr.ht
def logout():
    logout_user()
    return redirect("%s://%s/" % (_cfg('protocol'), _cfg('domain')))
コード例 #39
0
ファイル: app.py プロジェクト: TheReverend403/u.pste.pw
import sys
import os
import locale

from srht.config import _cfg, _cfgi
from srht.database import db, init_db
from srht.objects import User
from srht.common import *
from srht.network import *

from srht.blueprints.html import html
from srht.blueprints.api import api
from srht.blueprints.oauth import oauth

app = Flask(__name__)
app.secret_key = _cfg("secret-key")
app.jinja_env.cache = None
init_db()
login_manager = LoginManager()
login_manager.init_app(app)

app.jinja_loader = ChoiceLoader([
    FileSystemLoader("overrides"),
    FileSystemLoader("templates"),
])

@login_manager.user_loader
def load_user(username):
    return User.query.filter(User.username == username).first()

login_manager.anonymous_user = lambda: None
コード例 #40
0
ファイル: common.py プロジェクト: optimumtact/sr.ht
def disown_link(path):
    return _cfg("protocol") + "://" + _cfg("domain") + "/disown?filename=" + path
コード例 #41
0
ファイル: app.py プロジェクト: TheReverend403/u.pste.pw
def inject():
    return {
        'root': _cfg("protocol") + "://" + _cfg("domain"),
        'domain': _cfg("domain"),
        'protocol': _cfg("protocol"),
        'len': len,
        'any': any,
        'request': request,
        'locale': locale,
        'url_for': url_for,
        'file_link': file_link,
        'disown_link': disown_link,
        'user': current_user,
        'random': random,
        'owner': _cfg("owner"),
        'owner_email': _cfg("owner_email"),
        'git_repo': _cfg("git_repo"),
        'irc_server': _cfg("irc_server"),
        'irc_channel': _cfg("irc_channel"),
        'donate_link': _cfg("donate_link"),
        'donate_button_image': _cfg("donate_button_image"),
        'site_cost': _cfg("site_cost"),
        'current_financial_status': _cfg("current_financial_status"),
        '_cfg': _cfg
    }
コード例 #42
0
ファイル: common.py プロジェクト: optimumtact/sr.ht
def admin_delete_link(path):
    returnto = urllib.parse.quote_plus(_cfg("protocol") + "://" + _cfg("domain") + "/admin_uploads")
    return _cfg("protocol") + "://" + _cfg("domain") + "/delete?filename=" + path + "&return_to=" + returnto
コード例 #43
0
def script_plain():
    with open("templates/pstepw", "r") as f:
        resp = f.read().replace('{{ protocol }}', _cfg('protocol'))
        resp = resp.replace('{{ domain }}', _cfg('domain'))
    return Response(resp, mimetype="text/plain")
コード例 #44
0
ファイル: app.py プロジェクト: optimumtact/sr.ht
from srht.app import app
from srht.config import _cfg, _cfgi

import os

app.static_folder = os.path.join(os.getcwd(), "static")

import os

if __name__ == "__main__":
    app.run(host=_cfg("debug-host"), port=_cfgi("debug-port"), debug=True)
コード例 #45
0
ファイル: common.py プロジェクト: CarpyCar/cpcr.io
def disown_link(path):
    return _cfg("protocol") + "://" + _cfg(
        "domain") + "/disown?filename=" + path
コード例 #46
0
def admin_delete_link(path):
    returnto = urllib.parse.quote_plus(_cfg("protocol") + "://" + _cfg("domain") + '/admin_uploads')
    return _cfg("protocol") + "://"  + _cfg("domain") + "/delete?filename=" + path + '&return_to='+returnto