Exemplo n.º 1
0
def test_user_service_new_user():
    clean_env()
    user_service = UserService(user_catalog, user_db)
    user_service.try_reg_user("admin", "admin")
    user = user_service.get_user("admin")
    assert user is not None
    clean_env()
Exemplo n.º 2
0
def register():
    request_data = json.loads((request.get_data()).decode())
    email = request_data.get("email")
    user = UserService.get_instance().find_user(email)
    if user:
        return response_template(409, "User Already Exist")
    else:
        first_name = request_data.get("first_name")
        last_name = request_data.get("last_name")
        password = request_data.get("password")
        UserService.get_instance().add_new_user(email, first_name, last_name,
                                                password)
        return response_template(201, "User added successfully")
Exemplo n.º 3
0
    def __init__(self):
        parser = argparse.ArgumentParser(
            description='Multi text editor server launcher')

        parser.add_argument('-i',
                            '--ip',
                            type=str,
                            help='ip address for server to listen',
                            required=False,
                            default=self.listen_ip)
        parser.add_argument('-p',
                            '--port',
                            type=int,
                            help='port for server to listen',
                            required=False,
                            default=self.listen_port)
        parser.add_argument('-d',
                            '--dir',
                            type=str,
                            help='users files directory (relative path)',
                            required=False,
                            default=self.users_dir)

        args = parser.parse_args()
        self.listen_ip = args.ip
        self.listen_port = args.port
        self.host = (self.listen_ip, self.listen_port)
        self.users_dir = args.dir
        file_service = FileService(Path.cwd() / self.users_dir)
        user_service = UserService(Path.cwd() / self.users_dir)
        self.client_handler = ClientHandler(user_service, file_service)
Exemplo n.º 4
0
 def find_game():
     lobby_id, n_members = LobbyService.get_instance().add_user_to_lobby(UserService.get_instance().get_user(request.sid))
     join_room(str(lobby_id))
     emit("find_game_response", {"lobbyId": lobby_id, "numberOfMembers": n_members}, room=lobby_id)
     if LobbyService.get_instance().lobbies[lobby_id].is_full():
         GameService.get_instance().create_game(lobby_id, LobbyService.get_instance().lobbies[lobby_id].members)
         LobbyService.get_instance().remove_lobby(lobby_id)
         emit("game_started", room=lobby_id)
Exemplo n.º 5
0
 def get_balls_for_user():
     game, game_id = GameService.get_instance().get_game_for_user(
         request.sid)
     emit("get_balls_response",
          game.get_balls_for_user(UserService.get_instance().get_user(
              request.sid).username),
          room=request.sid)
     emit("game_players", game.get_members(), room=game_id)
Exemplo n.º 6
0
 def __init__(self):
     logging.info('=====> README.md services')
     self._user_service = UserService(self)
     self._cart_service = CartService(self)
     self._order_service = OrderService(self)
     self._pay_service = PayService(self)
     self._order_overtime_task_service = OrderOvertimeTaskService(self)
     self._webhooks_service = WebhooksService(self)
     self._credit_card_service = CreditCardService(self)
Exemplo n.º 7
0
    def get(self, action, sub_action, id):
        print self.request

        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
        self.set_header('Access-Control-Max-Age', 1000)
        self.set_header("Access-Control-Allow-Credentials", "true");
        self.set_header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        #self.set_header("Access-Control-Allow-Headers", "accept, authorization");
        self.set_header('Content-type', 'application/json')
        print action
        log.debug("UserHandler: action: %s and sub-action: %s and id: %s" % (action, sub_action, id))
        if not action: 
            self.redirect('/')
                
        #initialize response JSON
        response_message = {}
        
        # init user class
        user = UserService()
        
        # what action to take
        if action == "register":
            # Get email        
            user_email = self.get_argument('email', None)
            if not user_email: raise tornado.web.HTTPError(404)        
            log.debug("UserHandler: Registering user %s" % user_email)
            resend_email = self.get_argument('resend', None)
            response_message = user.register_user(user_email, resend_email)
        
        elif action == "signin":
            # Get email        
            user_email = self.get_argument('email', None)
            print user_email
            if not user_email: raise tornado.web.HTTPError(404)        
            log.debug("UserHandler: Signing in user %s" % user_email)
            
            # Get password        
            user_password = self.get_argument('password', "awesome")
            if not user_password: raise tornado.web.HTTPError(404)

            response_message = user.login_user(user_email, user_password)
        
        elif action == "segment":
            user_token = util.decode_jwt_token(self.request.headers.get('Authorization', None))
            
            if sub_action is not None and sub_action == "add" and segment_or_funnel is not None:
                response_message = user.add_segment(user_token["email"], segment_or_funnel)
            elif sub_action is not None and sub_action == "delete" and segment_or_funnel is not None:
                response_message = user.remove_segment(user_token["email"], segment_or_funnel)
            else:
                response_message = user.get_segments(user_token["email"])

        elif action == "funnels":
            user_token = util.decode_jwt_token(self.request.headers.get('Authorization', None))
            response_message = user.get_funnelsget_funnels(user_token["email"])

        # Write Response   
        self.write(json_encode(response_message))
Exemplo n.º 8
0
def test_user_service_auth_add_file():
    clean_env()
    user_service = UserService(user_catalog, user_db)
    user_service.try_reg_user("admin", "admin1234")
    user_service.try_add_file("admin", "new_file")

    assert user_service.check_is_author("admin", "new_file") is True
    clean_env()
Exemplo n.º 9
0
def profile():
    user = UserService.get_user(user_id=current_user.id)
    missing = UserService.get_missing_evaluations(user.id)
    if 'GET' == request.method:
        return render_template("profile.html",
                               user=user,
                               missing_evaluations=missing)
    data = dict(request.form)
    if data['password'][0] != user.password:
        return render_template("profile.html",
                               user=user,
                               error_message="Wrong password!")
    elif data['newPassword'][0] != data['confirmPassword'][0]:
        return render_template("profile.html",
                               user=user,
                               error_message="Non-matching password!")
    else:
        user.password = data['newPassword'][0]
        user = UserService.update_user(user)
        return render_template("profile.html",
                               user=user,
                               info_message="Information updated!")
Exemplo n.º 10
0
 def get_conn(self):
     if self.transport == None:
         self.socket = TSocket.TSocket("localhost", 9091)
         #            self.socket = TSocket.TSocket("192.168.199.8", 9091)       # 测试环境
         #            self.socket = TSocket.TSocket("192.168.99.212", 9091)      # 预生产
         #           self.socket = TSocket.TSocket("192.168.99.164", 9094)       # 生产
         #           self.socket = TSocket.TSocket("192.168.99.234", 9095)
         self.socket.setTimeout(5000)  #time out 10 sec
         self.transport = TTransport.TBufferedTransport(self.socket)
         protocol = TBinaryProtocol.TBinaryProtocol(self.transport)
         #           protocol = TJSONProtocol.TSimpleJSONProtocol(self.transport)
         self.client = UserService.Client(protocol)
         self.transport.open()
Exemplo n.º 11
0
def login():
    request_data = json.loads((request.get_data()).decode())
    email = request_data.get("email")
    password = request_data.get("password")
    if email is None or password is None:
        return response_template(401, "Missing Email or Password")
    check_user = UserService.get_instance().check_user(email, password)
    if check_user:
        expires = timedelta(
            minutes=int(os.environ.get("JWT_ACCESS_TOKEN_EXPIRES", 240)))
        access_token = create_access_token(identity=email,
                                           expires_delta=expires)
        return jsonify(access_token=access_token), 201
    else:
        return response_template(401, "Wrong Email or Password")
Exemplo n.º 12
0
from trip_service import TripBooker
from user_service import UserService


def cleanup(actor_list):
    print("global cleanup called")
    for actor in actor_list:
        actor.cleanup.remote()
        # del actor


if __name__ == "__main__":
    print("started app service")
    ray.init()
    userService = UserService.remote()
    tripService = TripBooker.remote()
    atexit.register(cleanup, [userService, tripService])

    date = "20200430"
    source = "BOS"
    destination = "DEL"
    user_id = "3000"
    car_results, flight_results = ray.get(
        tripService.get_trip_options.remote(date, source, destination))
    print(f"car results: {car_results}")

    flight_id = flight_results[0]['id']
    print(f"flightId: {flight_id}")
    car_id = car_results[0]['id']
    print(f"car_id: {car_id}")
Exemplo n.º 13
0
sys.path.append(os.path.relpath('../mykafka'))
sys.path.append(os.path.relpath('../rest_common'))
import rest_common
import mykafka

import getopt
from Exceptions import *
from flask import Flask, request
from user_service import UserService

app = Flask(__name__)
app.secret_key = "hallo blub foo bar"
app.config['SESSION_TYPE'] = 'filesystem'

user_service = UserService(
    mykafka.create_producer(
        'ec2-35-159-21-220.eu-central-1.compute.amazonaws.com', 9092))


@app.route('/add_user', methods=['POST'])
def restAddUser():
    try:
        data = rest_common.get_rest_data(request)
        user_service.add_user(data)
        return rest_common.create_response(200)
    except InvalidActionException as e:
        return rest_common.create_response(400, e.toDict())
    except UserExistsException as e:
        return rest_common.create_error_response(409, e)
    except CommandFailedException as e:
        return rest_common.create_error_response(504, e)
Exemplo n.º 14
0
def create():
    body = request.get_json()
    new_user = UserService().create(body)
    return jsonify(new_user)
Exemplo n.º 15
0
def list_users():
    list = UserService().list()
    return jsonify(list)
Exemplo n.º 16
0
def test_user_service_auth_user_success():
    clean_env()
    user_service = UserService(user_catalog, user_db)
    user_service.try_reg_user("admin", "admin1234")
    assert user_service.auth_user("admin", "admin1234") is True
    clean_env()
Exemplo n.º 17
0
from flask import Flask, abort, request
from settings import Settings
from models import database, Feedback, User
from user_service import UserService
from feedback_service import FeedbackService
from text_rank import TextRank

debug = os.environ.get("DEBUG", "false").lower() == "true"

log = logging.getLogger("summarizer_server")

app = Flask(__name__)
app.config.from_object(Settings)
database.init_app(app)

userservice = UserService()
feedbackservice = FeedbackService()
textrank = TextRank()


@app.before_first_request
def before_first_request():
    textrank.setup()


@app.route("/api/")
def index():
    return "Summarizer API"


@app.route("/api/extract", methods=["POST"])
Exemplo n.º 18
0
def delete():
    user = UserService().delete()
    return jsonify(user)
Exemplo n.º 19
0
import cherrypy
from user_service import UserService, NazgulListService, AuthService
from process_service import ProcessService
from whitelist_service import WhitelistService
from screenshot_service import ScreenshotService, ScreenshotListService
from config import WITH_AUTHENTICATION, WITHOUT_AUTHENTICATION, CHERRYPY_CONFIG_DEFAULT

if __name__ == '__main__':
    cherrypy.config.update(CHERRYPY_CONFIG_DEFAULT)
    cherrypy.tree.mount(UserService(), '/api/user', WITH_AUTHENTICATION)
    cherrypy.tree.mount(NazgulListService(), '/api/nazgul',
                        WITH_AUTHENTICATION)
    cherrypy.tree.mount(ProcessService(), '/api/process', WITH_AUTHENTICATION)
    cherrypy.tree.mount(WhitelistService(), '/api/whitelist',
                        WITH_AUTHENTICATION)
    cherrypy.tree.mount(ScreenshotService(), '/api/screenshot',
                        WITH_AUTHENTICATION)
    cherrypy.tree.mount(ScreenshotListService(), '/api/screenshotlist',
                        WITH_AUTHENTICATION)
    cherrypy.tree.mount(AuthService(), '/api/auth', WITH_AUTHENTICATION)

    cherrypy.engine.start()
    cherrypy.engine.block()
Exemplo n.º 20
0
import instana
import logging
from os import path
import sys
import time
import user_service_pb2
import user_service_pb2_grpc
from user_service import UserService
sys.path.append(
    path.join(path.dirname(path.dirname(path.abspath(__file__))),
              'common_service'))
from common_service import create_grpc_server  # noqa: E402

GRPC_PORT = 50051

user_svc = UserService()


class UserServicer(user_service_pb2_grpc.TwitterUserServicer):
    def GetUser(self, request, context):
        user_id = request.user_id
        name = user_svc.get_name(user_id)
        return user_service_pb2.GetUserResponse(user_id=user_id, name=name)

    def GetUsers(self, request, context):
        names = user_svc.get_names(list(request.user_ids))
        res = user_service_pb2.GetUsersResponse()
        res.names[:] = names
        return res

    def CheckPassword(self, request, context):
Exemplo n.º 21
0
 def connect_user(connection_data):
     user_connected = UserService.get_instance().connect_user(request.sid, connection_data["username"])
     emit("connect_user_response", user_connected, room=request.sid)
Exemplo n.º 22
0
from flask_cors import CORS
CORS(current_app)
routes = Blueprint("routes", __name__)

from .agent import *
from .training_data import *
from .response import *
from .user import *
from .context import *

from agents_service import AgentsService
AgentsService.get_instance().starting_load_agents()

from user_service import UserService
exist_user = UserService.get_instance().exist_user()
if not exist_user:
    UserService.get_instance().add_new_user(os.environ.get("ADMIN_LOGIN"),
                                            "Admin", "Admin",
                                            os.environ.get("ADMIN_PWD"))


@current_app.route("/", methods=["GET"])
def index():
    return "Boticot API !"


@current_app.route("/healthcheck", methods=["GET"])
def healthcheck():
    return "Boticot API Run OK"
Exemplo n.º 23
0
 def disconnect():
     lobby_id, n_members = LobbyService.get_instance().remove_user(UserService.get_instance().get_user(request.sid))
     if lobby_id != "":
         leave_room(lobby_id)
         emit("find_game_response", {"lobbyId": lobby_id, "numberOfMembers": n_members}, room=lobby_id)
     UserService.get_instance().disconnect_user(request.sid)
Exemplo n.º 24
0
def test_user_service_auth_user_fail():
    clean_env()
    user_service = UserService(user_catalog, user_db)
    user_service.try_reg_user("admin", "admin")
    assert user_service.auth_user("admin", "bad_pass") is False
    clean_env()
Exemplo n.º 25
0
 def get_game_for_user(self, sid):
     user = UserService.get_instance().get_user(sid)
     for game_id in self.games:
         game = self.games[game_id]
         if game.has_member(user.username):
             return game, game_id
Exemplo n.º 26
0
def simulate_user_behaviour():
    def sigint_handler(signum, frame):
        print("Interrupted")
        time.sleep(3)
        user_service.close()

    signal.signal(signal.SIGINT, sigint_handler)

    user_service = UserService()

    user_service.print_databases()

    for i in range(3):
        user_data = create_test_user()
        try:
            user_service.add_user(user_data)
        except UserExistsException:
            continue
        print('User {} added'.format(user_data['email']))
        #time.sleep(randint(1,2))

        for i in range(randint(7, 10)):

            session_id = user_service.authenticate_user(user_data)
            print('User {} authenticated '.format(user_data['email']))
            #time.sleep(randint(1,2))
            for j in range(randint(0, 10)):
                if randint(0, 1):
                    user_service.add_packet_to_user(
                        create_add_packet_data(session_id))
                    print('User {} added packet'.format(user_data['email']))
                else:
                    packets = user_service.get_packets_from_user(session_id)
                    print('User {} has packets'.format(user_data['email'],
                                                       packets))
                #time.sleep(randint(1,2))
            user_service.logout_user(session_id)
            print('User {} logged out'.format(user_data['email']))
            #time.sleep(randint(1,2))

    user_service.print_databases()