Exemple #1
0
def register():
    try:
        list_role = ["ADMIN", "HOTEL_OWNER", "USER"]
        username = request.get_json()['username']
        password = bcrypt.generate_password_hash(
            request.get_json()['password']).decode('utf-8')
        role = request.get_json()['role']
        if role not in list_role:
            return custom_response({"error": "Invalid role"}, 400)
        newuser = User(username, password, role)
        user = User.get_user_by_username(username)
        if (user != None):
            return custom_response({"error": "Duplicate username"}, 400)
        else:
            db.session.add(newuser)
            db.session.commit()
            result = newuser.dump()
        return custom_response(result, 200)
    except Exception as e:
        return custom_response({"error": str(e)}, 400)
Exemple #2
0
def login():
    try:
        username = request.get_json()['username']
        password = request.get_json()['password']
        result = ''
        if not username or not password:
            return custom_response(
                {'error': 'you need username and password to sign in'}, 400)
        user = User.get_user_by_username(username)
        if user != None:
            if bcrypt.check_password_hash(user.password, password):
                access_token = jwt.encode(
                    {
                        'exp':
                        datetime.datetime.utcnow() +
                        datetime.timedelta(days=1),
                        'iat':
                        datetime.datetime.utcnow(),
                        'sub':
                        user.id,
                        'username':
                        user.username,
                        'role':
                        user.role
                    }, config.SECRET_KEY)
                result = access_token.decode("utf-8")
            else:
                return custom_response(
                    {"error": "Invalid username or password!"}, 400)
        else:
            return custom_response({"error": "Invalid username or password!"},
                                   400)
        return custom_response(
            {
                'token': result,
                'role': user.role,
                'username': user.username
            }, 200)
    except Exception as e:
        return custom_response({"error": str(e)}, 400)