Esempio n. 1
0
def login():
    """
    login an existing user
    """
    try:
        username = json.loads(request.data.decode())['username'].replace(
            " ", "")
        password = json.loads(request.data.decode())['password'].replace(
            " ", "")
        user = User(username, "", "")

        user = user.exists()
        if check_password_hash(user.password_hash, password):
            """token if password is correct"""
            token = auth_encode(user.user_id)
            if token:
                response = {
                    'response': 'login successful',
                    'token': token.decode()
                }
                return jsonify(response), 200
        else:
            return jsonify({'response': 'invalid username/password'}), 422
    except (KeyError, ValueError) as ex:
        print('error in login', ex)
        return jsonify(
            {'response': 'json body must contain username and password'}), 400
    except (psycopg2.DatabaseError, psycopg2.IntegrityError, Exception) as ex:
        print('error in login', ex)
        return jsonify({'response': 'user not found'}), 404
Esempio n. 2
0
    def post(self):
        username = request.json.get('username', None)
        password = request.json.get('password', None)
        secret = request.json.get('secret', None)
        role = 'admin'
        if secret != 'iniSECret':
            return {'message': 'Permission denied'}, 500

        if User.find_by_username(username):
            return {'message': 'Admin already exists: {}'.format(username)}

        username = username
        password = User.generate_hash(password)

        try:
            new_user = User(username, password, role)
            db.session.add(new_user)
            db.session.commit()

            access_token = create_access_token(identity=username)
            refresh_token = create_refresh_token(identity=username)
            return {
                'message': 'Admin created: {}'.format(username),
                'access_token': access_token,
                'refresh_token': refresh_token
            }
        except Exception as e:
            return {'message': e}, 500
Esempio n. 3
0
def signup():
    """sign up a new user"""
    try:
        username = json.loads(request.data.decode())['username']
        password = json.loads(request.data.decode())['password'].replace(
            " ", "")
        email = json.loads(request.data.decode())['email'].replace(" ", "")

        if re.match('^[a-zA-Z][-\w.]{0,22}([a-zA-Z\d]|(?<![-.])_)$',
                    username) is None:
            return jsonify({'response': 'invalid username'}), 400
        if not validate_email(email):
            return jsonify({'response': 'invalid email'}), 400
        if re.match('[A-Za-z0-9@#$%^&+=]{8,}', password) is None:
            return jsonify(
                {'response':
                 'password must contain 6 or more characters'}), 400
        """
        search if the user exists in the database
        """
        user = User(username, email, "")
        if user.exists() is None:
            user.create_user(password)
            return jsonify({'response': 'user created successfully'}), 201
        else:
            return jsonify({'response': 'user already exists'}), 409
    except (KeyError, ValueError) as ex:
        print('response', ex)
        return jsonify({
            'response':
            'json body must contain username, password and email'
        }), 400
    except (psycopg2.DatabaseError, psycopg2.IntegrityError, Exception) as ex:
        print('error in signup', ex)
        return jsonify({'response': 'something went wrong'}), 500
Esempio n. 4
0
    def post(self):

        parse = reqparse.RequestParser()
        parse.add_argument('mobile',
                           location='json',
                           required=True,
                           type=check_mobile)
        parse.add_argument('smscode', location='json', required=True)
        parse.add_argument('password', location='json', required=True)

        args = parse.parse_args()

        mobile = args.get('mobile')
        smscode = args.get('smscode')
        password = args.get('password')

        try:
            server_smscode = current_app.redis_store.get('sms_%s' % mobile)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="获取本地验证码失败")

        if not server_smscode:
            # 短信验证码过期
            return jsonify(errno=RET.NODATA, errmsg="短信验证码过期")

        if smscode != server_smscode.decode():
            return jsonify(errno=RET.DATAERR, errmsg="短信验证码错误")

        try:
            current_app.redis_store.delete('sms_%s' % mobile)
        except Exception as e:
            current_app.logger.error(e)

        user = User()
        user.nick_name = mobile
        user.mobile = mobile
        user.password = password

        try:
            db.session.add(user)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=RET.DATAERR, errmsg="数据保存错误")

        # 状态保持
        session["user_id"] = user.id
        session["nick_name"] = user.nick_name
        session["mobile"] = user.mobile

        return jsonify(errno=RET.OK, errmsg="OK")
Esempio n. 5
0
 def _create_user(self, username, password):
     with self.app.test_request_context():
         user = User(username=username, password=password)
         # insert the user
         db.session.add(user)
         db.session.commit()
         return user.id
def user_edit(user_id):
    user = User.find_by_id(user_id)
    if request.method == 'POST':
        try:
            is_admin = request.form.get('is-admin')
            password = request.form.get('password')

            user.username = request.form.get('username')
            # user.password = User.generate_hash(password)
            # if User.verify_hash(password, current_user.password):
            #     user.password = password

            user.address = request.form.get('address')
            if is_admin:
                user.role = 'admin'

            db.session.commit()
            return redirect(url_for('admin.users'))

        except IntegrityError:
            db.session.rollback()
            flash('ERROR! username ({}) already exists.'.format(user.username),
                  'error')

    return render_template('user_edit.html', user=user)
Esempio n. 7
0
def create():
    post_data = request.get_json()
    user = User(username=post_data.get('username'),
                password=post_data.get('password'))
    # insert the user
    db.session.add(user)
    db.session.commit()
    return jsonify({"id": user.id})
Esempio n. 8
0
def user_delete(user_id):
    if current_user.role != 'admin':
        return redirect(url_for('home.home'))

    user = User.find_by_id(user_id)
    db.session.delete(user)
    db.session.commit()
    return redirect(url_for('admin.users'))
Esempio n. 9
0
    def post(self):
        username = request.json.get('username', None)
        password = request.json.get('password', None)
        current_user = User.find_by_username(username)
        if not current_user:
            return {'message': 'User doesn\'t exist: {}'.format(username)}

        if User.verify_hash(password, current_user.password):
            access_token = create_access_token(identity=username)
            refresh_token = create_refresh_token(identity=password)
            return {
                'message': 'Logged in as {}'.format(current_user.username),
                'access_token': access_token,
                'refresh_token': refresh_token
            }
        else:
            return {'message': 'Wrong credentials'}
def generate_user():
    """ POST a new user """

    user = User.create_user()

    if isinstance(user, User):
        return user.serialize()

    return (user, 400)
Esempio n. 11
0
    def get(self):
        username = get_jwt_identity()
        current_user = User.find_by_username(username)
        if not current_user:
            return {'message': 'User doesn\'t exist: {}'.format(username)}

        detail = {}
        for column in current_user.__table__.columns:
            detail[column.name] = str(getattr(current_user, column.name))
        return detail
    def wrapper(*args, **kwargs):
        verify_jwt_in_request()
        username = get_jwt_identity()
        current_user = User.find_by_username(username)

        if current_user.role != 'admin':
            return {
                'message': 'Permission denied. Admin only'
            }, 403
        else:
            return fn(*args, **kwargs)
def user_add():
    if request.method == 'POST':
        try:
            username = request.form.get('username')
            password = User.generate_hash(request.form.get('password'))
            is_admin = request.form.get('is-admin')
            if is_admin:
                new_user = User(username, password, role='admin')
            else:
                new_user = User(username, password)

            db.session.add(new_user)
            db.session.commit()
            return redirect(url_for('admin.users'))

        except IntegrityError:
            db.session.rollback()
            flash('ERROR! username ({}) already exists.'.format(username),
                  'error')

    return render_template('user_add.html')
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        current_user = User.find_by_username(username)
        if not current_user:
            flash('ERROR! user not found.', 'error')
            return redirect(url_for('admin.dashboard'))

        if User.verify_hash(password, current_user.password):
            current_user.authenticated = True
            db.session.add(current_user)
            db.session.commit()
            login_user(current_user)

            return redirect(url_for('admin.dashboard'))
        else:
            db.session.rollback()
            flash('ERROR! Incorrect login credentials.', 'error')

    return render_template('login.html')
Esempio n. 15
0
    def post(self):
        username = request.json.get('username', None)
        password = request.json.get('password', None)

        if User.find_by_username(username):
            return {'message': 'User already exists: {}'.format(username)}

        username = username
        password = User.generate_hash(password)

        try:
            new_user = User(username, password)
            db.session.add(new_user)
            db.session.commit()

            access_token = create_access_token(identity=username)
            refresh_token = create_refresh_token(identity=username)
            return {
                'message': 'User created: {}'.format(username),
                'access_token': access_token,
                'refresh_token': refresh_token
            }
        except Exception as e:
            return {'message': e}, 500
Esempio n. 16
0
    def post(self):
        username = get_jwt_identity()
        current_user = User.find_by_username(username)
        if not current_user:
            return {'message': 'User doesn\'t exist: {}'.format(username)}

        try:
            current_user.phone = request.json.get('phone', None)
            current_user.address = request.json.get('address', None)

            db.session.commit()

            return {
                'message': 'Data updated: {}'.format(current_user.username)
            }

        except Exception as e:
            return {'message': e}, 500
Esempio n. 17
0
def createsuperuser(name, password):
    """创建管理员用户"""
    if not all([name, password]):
        print('参数不足')
        return

    user = User()
    user.mobile = name
    user.nick_name = name
    user.password = password
    user.is_admin = True

    try:
        db.session.add(user)
        db.session.commit()
        print("创建成功")
    except Exception as e:
        print(e)
        db.session.rollback()
Esempio n. 18
0
def add_user(username, password):
    user = User(username=username, password=password)
    db.session.add(user)
    db.session.commit()
    return user
Esempio n. 19
0
def profile(username):
    current_user = User.find_by_username(username)
    return render_template('profiles.html', user=current_user)
def user_delete(user_id):
    user = User.find_by_id(user_id)
    db.session.delete(user)
    db.session.commit()
    return redirect(url_for('admin.users'))
Esempio n. 21
0
from project import db
from project.models.models import Apartment, Rankings, Photo, User

db.drop_all()
db.create_all()

apartment1 = Apartment(apartment_url='craigslist.org/example')
apartment2 = Apartment(apartment_url='ft.com')
r1 = Rankings(r_apartment_url='craigslist.org/example')
r2 = Rankings(r_apartment_url='ft.com')
p1 = Photo(p_apartment_url='craigslist.org/example', photo_url='abc.jpg')
p2 = Photo(p_apartment_url='ft.com', photo_url='abc.jpg')
u1 = User(user_random_id='TESTUSER01')

apartment1.apartment_address = 'Masonic Near Fell'

db.session.add_all([apartment1, apartment2, r1, r2, p1, p2, u1])
db.session.commit()