Exemplo n.º 1
0
def reset_code():
    username = request.form.get("username")
    user = db.get_user(username)
    if not user:
        flash(messages.INVALID_USERNAME, "error")
        return redirect(url_for("index"))
    code = accounts.create_reset_code(username)
    url = "http://{0}{1}".format(request.headers.get("HOST"), url_for("reset", code=code))
    tmpl = """
Greetings...

Please click the following link to reset your password.

{0}

If you did not request this reset, please ignore this email and the code will
automatically expire.

Thanks!
{1}""".format(
        url, config.APP_NAME
    )
    utils.send_mail("Keymaker Password Reset", tmpl, [user.get("email")])
    flash(messages.RESET_CODE_SENT, "success")
    return redirect(url_for("index"))
Exemplo n.º 2
0
def get_user_from_code(code=None):
    rds = get_redis_connection()
    key = RESET_CODE_KEY.format(code)
    user = None
    if key:
        user = db.get_user(rds.get(key))
    return user
Exemplo n.º 3
0
def loginauth():
    if 'user' in session:
        return redirect('/')

    else:

        try:
            usern = request.form['username']
            passs = request.form['password']
        except:
            return render_template("index.html", log=False)

        #success!
        if db.get_user(usern):

            if db.auth(usern, passs):
                session['username'] = usern
                return redirect(url_for('profile'))

            #can not log in :(
            flash('thats not the right password')
            return render_template("login.html", log=False)

        else:
            flash('that person doesnt exist')
            return render_template("login.html", log=False)
Exemplo n.º 4
0
def get_user_from_code(code=None):
    rds = get_redis_connection()
    key = RESET_CODE_KEY.format(code)
    user = None
    if key:
        user = db.get_user(rds.get(key))
    return user
Exemplo n.º 5
0
def generate_token(username, expire=TOKEN_EXPIRED_TIME):
    key = db.get_user(username)[0]['passhash']
    ts_str = str(time.time() + expire)
    ts_byte = ts_str.encode("utf-8")
    sha1_tshexstr = hmac.new(key.encode("utf-8"), ts_byte, 'sha1').hexdigest()
    token = username + ':' + ts_str + ':' + sha1_tshexstr
    b64_token = base64.urlsafe_b64encode(token.encode("utf-8"))
    return b64_token.decode("utf-8")
Exemplo n.º 6
0
 def get(self):
     if current_cookie_user(self):
         user = current_cookie_user(self)
         admin_screen_name = db.get_user(login_name='admin').screen_name
         if user == admin_screen_name:
             db.init(force=True)
         self.redirect('/')
     else:
         self.redirect('/admin')
Exemplo n.º 7
0
 def get(self):
     if current_cookie_user(self):
         user = current_cookie_user(self)
         admin_screen_name = db.get_user(login_name='admin').screen_name
         if user == admin_screen_name:
             db.init(force=True)
         self.redirect('/')
     else:
         self.redirect('/admin')
Exemplo n.º 8
0
 def get(self):
     if current_cookie_user(self):
         self.render(
             'list.html',
             posts=db.get_posts(30),
             user=current_cookie_user(self),
             admin_screen_name=db.get_user(login_name='admin').screen_name,
             blog_settings=conf.blog_settings,
         )
     else:
         self.redirect('/login')
Exemplo n.º 9
0
 def get(self):
     if current_cookie_user(self):
         self.render(
             'list.html',
             posts = db.get_posts(30),
             user = current_cookie_user(self),
             admin_screen_name = db.get_user(login_name='admin').screen_name,
             blog_settings = conf.blog_settings,
         )
     else:
         self.redirect('/login')
Exemplo n.º 10
0
def delete_user(db: Session, user_id: int) -> bool:
    """Удаление пользователя"""
    user_data = get_user(db, user_id)
    if user_data is None:
        return False
    try:
        db.delete(user_data)
        db.commit()
    except BaseException as e:
        print(f'Error: {e}')
        db.rollback()
    return True
Exemplo n.º 11
0
def ban_user(db: Session, user_id: int) -> models.User:
    """Запретить пользователю добавлять собственные рецепты """
    user_data = get_user(db, user_id)
    user_data.is_active = not user_data.is_active
    try:
        db.add(user_data)
        db.commit()
        db.refresh(user_data)
    except BaseException as e:
        print(f'Error: {e}')
        db.rollback()
    return user_data
Exemplo n.º 12
0
 def decorated(*args, **kwargs):
     api_key = request.headers.get('api-key')
     # validate
     if not api_key:
         data = {'error': messages.NO_API_KEY}
         return generate_api_response(data, 401)
     user = db.get_user({'api_key': api_key})
     if not user:
         data = {'error': messages.INVALID_API_KEY}
         return generate_api_response(data, 401)
     session['user'] = user
     return f(*args, **kwargs)
Exemplo n.º 13
0
 def decorated(*args, **kwargs):
     api_key = request.headers.get('api-key')
     # validate
     if not api_key:
         data = {'error': messages.NO_API_KEY}
         return generate_api_response(data, 401)
     user = db.get_user({'api_key': api_key})
     if not user:
         data = {'error': messages.INVALID_API_KEY}
         return generate_api_response(data, 401)
     session['user'] = user
     return f(*args, **kwargs)
Exemplo n.º 14
0
def login():
    username = ''
    if request.method == 'POST':
        form = request.form
        username = form.get('username')
        u = db.get_user(username)
        if u:
            if hash_text(form.get('password')) == u.get('password'):
                # login
                session['user'] = u
                return redirect(url_for('admin.index'))
        flash(messages.INVALID_USERNAME_PASSWORD, 'error')
    ctx = {'username': username}
    return render_template('accounts/login.html', **ctx)
Exemplo n.º 15
0
def login():
    username = ''
    if request.method == 'POST':
        form = request.form
        username = form.get('username')
        u = db.get_user(username)
        if u:
            if hash_text(form.get('password')) == u.get('password'):
                # login
                session['user'] = u
                return redirect(url_for('admin.index'))
        flash(messages.INVALID_USERNAME_PASSWORD, 'error')
    ctx = {'username': username}
    return render_template('accounts/login.html', **ctx)
Exemplo n.º 16
0
def get_profile(db: Session, user_id: int) -> dict:
    """Получить профиль пользователя"""
    db_user = get_user(db, user_id)
    if db_user:
        profile = {
            'id': db_user.id,
            'nickname': db_user.nickname,
            'is_active': db_user.is_active,
            'favorites': [like.recipe_id for like in db_user.user_likes],
            'number_my_recipe': len(db_user.my_recipe)
        }
        return profile
    else:
        return {'error': 'The user does not exist'}
Exemplo n.º 17
0
def login():
    if request.method == 'POST':
        form = request.form
        u = db.get_user({'username': form.get('username')})
        next_url = utils.get_redirect_target()
        if not next_url:
            next_url = url_for('admin.index')
        if u:
            if hash_text(form.get('password')) == u.get('password'):
                # login
                session['user'] = u
                return redirect(next_url)
            print(u)
        flash(messages.INVALID_USERNAME_PASSWORD, 'error')
        return redirect(url_for('accounts.login'))
    ctx = {}
    return render_template('accounts/login.html', **ctx)
Exemplo n.º 18
0
def login():
    if request.method == 'POST':
        form = request.form
        u = db.get_user({'username': form.get('username')})
        next_url = utils.get_redirect_target()
        if not next_url:
            next_url = url_for('admin.index')
        if u:
            if hash_text(form.get('password')) == u.get('password'):
                # login
                session['user'] = u
                return redirect(next_url)
            print(u)
        flash(messages.INVALID_USERNAME_PASSWORD, 'error')
        return redirect(url_for('accounts.login'))
    ctx = {}
    return render_template('accounts/login.html', **ctx)
Exemplo n.º 19
0
def verify_token(token):
    try:
        token_str = base64.urlsafe_b64decode(token).decode('utf-8')
        token_list = token_str.split(':')
        if len(token_list) != 3:
            return False
        username = token_list[0]
        user = db.get_user(username)
        if not user:
            return False
        key = user[0]['passhash']
        ts_str = token_list[1]
        if float(ts_str) < time.time():
            # token expired
            return False
        known_sha1_tsstr = token_list[2]
        sha1 = hmac.new(key.encode("utf-8"), ts_str.encode('utf-8'), 'sha1')
        calc_sha1_tsstr = sha1.hexdigest()
        return calc_sha1_tsstr == known_sha1_tsstr
    except Exception:
        return False
Exemplo n.º 20
0
def sign_up():
    username = request.form['username']
    password = request.form['password']

    tjupt_id = request.form['id']
    tjupt_passkey = request.form['passkey']
    if not db.check_tjuid_registered(tjupt_id):
        return jsonify({
            'success': False,
            'msg': 'This ID has been used.'
        }), 403
    msg = check_id_passkey(tjupt_id, tjupt_passkey)
    if msg:
        return jsonify({'success': False, 'msg': msg}), 403

    if not db.get_user(username):
        salt = bcrypt.gensalt()
        passhash = bcrypt.hashpw(password.encode('utf-8'), salt)

        db.signup(username, passhash.decode('utf-8'), tjupt_id)
        return jsonify({'success': True, 'msg': 'Registration success!'}), 201
    else:
        return jsonify({'success': False, 'msg': 'Username existed!'}), 403
Exemplo n.º 21
0
def log_in():
    username = request.form['username']
    password = request.form['password']

    user = db.get_user(username)
    if user:
        if bcrypt.checkpw(password.encode('utf-8'),
                          user[0]['passhash'].encode('utf-8')):
            token = generate_token(user[0]['username'])
            return jsonify({
                'success': True,
                'msg': 'Success~',
                'token': token
            })
        else:
            return jsonify({
                'success': False,
                'msg': 'Invalid username or password!'
            }), 401
    else:
        return jsonify({
            'success': False,
            'msg': 'Invalid username or password!'
        }), 401
def reset_code():
    username = request.form.get('username')
    user = db.get_user(username)
    if not user:
        flash(messages.INVALID_USERNAME, 'error')
        return redirect(url_for('index'))
    code = accounts.create_reset_code(username)
    url = 'http://{0}{1}'.format(request.headers.get('HOST'),
                                 url_for('reset', code=code))
    tmpl = """
Greetings...

Please click the following link to reset your password.

{0}

If you did not request this reset, please ignore this email and the code will
automatically expire.

Thanks!
{1}""".format(url, config.APP_NAME)
    utils.send_mail('Keymaker Password Reset', tmpl, [user.get('email')])
    flash(messages.RESET_CODE_SENT, 'success')
    return redirect(url_for('index'))
Exemplo n.º 23
0
 def test_get_user(self):
     self._create_user()
     u = db.get_user(self.test_user_username)
     self.assertNotEqual(u, None)
     self.assertTrue(u.has_key('username'))
Exemplo n.º 24
0
 def _create_user(self):
     db.create_user(self.test_user_username, self.test_user_password,
         self.test_user_email, self.test_user_is_admin)
     user = db.get_user(self.test_user_username)
     return user
Exemplo n.º 25
0
from multiprocessing import Process

app = config.create_app()
app.register_blueprint(accounts_blueprint, url_prefix='/accounts')
app.register_blueprint(admin_blueprint, url_prefix='/admin')
babel = Babel(app)
mail = Mail(app)
redis = redis.init_redis(app)
# add exts for blueprint use
app.config['babel'] = babel
app.config['mail'] = mail
app.config['redis'] = redis
RQDashboard(app)

# check for admin user ; create if missing
if not db.get_user('admin'):
    print('Creating admin user; password: launchpad')
    db.create_user(username='******',
                   password='******',
                   email=config.ADMIN_EMAIL,
                   is_admin=True)


# hack to add auth for rq dashboard
@app.before_request
def rq_auth_check():
    if request.path.find('/rq') > -1 and not session.get('user'):
        return redirect(url_for('accounts.login'))


@app.route('/')
Exemplo n.º 26
0
def current_cookie_user(self):
    try:
        cookie_user = self.current_user
        return db.get_user(login_name=cookie_user).screen_name
    except:
        return None
Exemplo n.º 27
0
def current_cookie_user(self):
    try:
        cookie_user = self.current_user
        return db.get_user(login_name=cookie_user).screen_name
    except:
        return None
Exemplo n.º 28
0
def get_user_by_key(key):
    user = db.get_user({'key': key})
    return user
Exemplo n.º 29
0
app.register_blueprint(admin_blueprint, url_prefix='/admin')
app.register_blueprint(accounts_blueprint, url_prefix='/accounts')
babel = Babel(app)
cache = Cache(app)
mongo = PyMongo(app)
mail = Mail(app)
redis = redis.init_redis(app)
# add exts for blueprint use
app.config['cache'] = cache
app.config['babel'] = babel
app.config['mongo'] = mongo
app.config['redis'] = redis
app.config['mail'] = mail

# check for admin user
if not db.get_user({'username': '******'}):
    db.create_user(username='******', password='******', is_admin=True)
    print('Admin user created: username: admin password: tekken')

# ----- context processors
@app.context_processor
def load_user():
    return {'user': session.get('user', None)}

@app.context_processor
def load_sensu_api_url():
    return {'sensu_api_url': app.config.get('SENSU_API_URL')}
# ----- end context processors

# ----- template filters
@app.template_filter('date_from_timestamp')
Exemplo n.º 30
0
from accounts.views import accounts_blueprint
from admin.views import admin_blueprint

app = config.create_app()
app.register_blueprint(accounts_blueprint, url_prefix="/accounts")
app.register_blueprint(admin_blueprint, url_prefix="/admin")
babel = Babel(app)
mail = Mail(app)
redis = redis.init_redis(app)
# add exts for blueprint use
app.config["babel"] = babel
app.config["mail"] = mail
app.config["redis"] = redis

# check for admin user ; create if missing
if not db.get_user("admin"):
    if not config.ADMIN_EMAIL:
        print("You must set ADMIN_EMAIL in config.py")
    else:
        print("Creating admin user; password: keymaker")
        db.create_user(username="******", password="******", email=config.ADMIN_EMAIL, is_admin=True)


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/resetcode/", methods=["POST"])
def reset_code():
    username = request.form.get("username")
Exemplo n.º 31
0
from multiprocessing import Process

app = config.create_app()
app.register_blueprint(accounts_blueprint, url_prefix='/accounts')
app.register_blueprint(admin_blueprint, url_prefix='/admin')
babel = Babel(app)
mail = Mail(app)
redis = redis.init_redis(app)
# add exts for blueprint use
app.config['babel'] = babel
app.config['mail'] = mail
app.config['redis'] = redis
RQDashboard(app)

# check for admin user ; create if missing
if not db.get_user('admin'):
    print('Creating admin user; password: launchpad')
    db.create_user(username='******', password='******',
        email=config.ADMIN_EMAIL, is_admin=True)

# hack to add auth for rq dashboard
@app.before_request
def rq_auth_check():
    if request.path.find('/rq') > -1 and not session.get('user'):
        return redirect(url_for('accounts.login'))

@app.route('/')
def index():
    return redirect(url_for('admin.index'))

#github post receive hook
Exemplo n.º 32
0
 def test_get_user(self):
     self._create_user()
     u = db.get_user(self.test_user_username)
     self.assertNotEqual(u, None)
     self.assertTrue(u.has_key('username'))
Exemplo n.º 33
0
 def _create_user(self):
     db.create_user(self.test_user_username, self.test_user_password,
         self.test_user_email, self.test_user_is_admin)
     user = db.get_user(self.test_user_username)
     return user