Exemplo n.º 1
0
 def __init__(self, port=9999, maximumClient=10):
     print("Initializing Server...")
     start = time.time()
     self.host = socket.gethostbyname(socket.gethostname())
     self.port = port
     self.maximumClient = maximumClient
     self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.logFileName = 'serverLog'
     self.constant = 'constant'
     self.password = None
     try:
         self.socket.bind((self.host, self.port))
         self.socket.listen(self.maximumClient)
         self.userManager = UserManager()
         #self.projectManager = ProjectManager(self.socket)
         #self.eventManager = EventManager(self.socket)
         self.chatManager = ChatManager(self.userManager)
         self.departmentManager = DepartmentManager(self.userManager)
         self.projectManager = ProjectManager(self.userManager,
                                              self.departmentManager)
         self.eventManager = EventManager(self.userManager,
                                          self.departmentManager)
         print("\n--- Server is Online ---")
         print("IP:", self.host, "Port:", self.port)
         print("Initial Runtime:",
               format((time.time() - start) / 1000, '.10f'), "sec")
         self.thread = threading.Thread(target=self.listen, args=[])
         self.thread.setDaemon(True)
         self.thread.start()
         self.getInformation()
         self.command()
     except OSError as err:
         print(err)
         print("\n!!! Server is already working !!!")
Exemplo n.º 2
0
def register():
	if request.method == 'POST':
		user_data = request.values
		um = UserManager(name=user_data['nickname'], mail=user_data['email'], password=user_data['password'])
		um.create_new_user()
		return render_template('main.html', nickname=user_data['nickname'])
	return render_template("register.html")
Exemplo n.º 3
0
    def test_create_user_raises_value_error_if_normalized_email_is_empty_string(self):
        manager = UserManager()
        manager.normalize_email.return_value = ""
        email = "*****@*****.**"
        password = "******"

        with pytest.raises(ValueError):
            manager._create_user(email, password)
Exemplo n.º 4
0
    def test_create_superuser_raises_an_error_if_is_staff_or_is_superuser_is_not_true(
        self, is_staff, is_superuser
    ):
        manager = UserManager()
        email = "*****@*****.**"
        password = "******"
        kwargs = {"is_staff": is_staff, "is_superuser": is_superuser}

        with pytest.raises(ValueError):
            manager.create_superuser(email, password, **kwargs)
Exemplo n.º 5
0
def logout():

    token = request.cookies.get('auth-token')

    if token is None:
        return json.dumps({"code": 200}), 200

    UserManager.logout(token)

    resp = Response(json.dumps({'code': 200}))

    return resp
Exemplo n.º 6
0
    def test_create_superuser_sets_is_staff_and_is_superuser_to_true_if_not_defined(
        self,
    ):
        manager = UserManager()
        email = "*****@*****.**"
        password = "******"

        manager.create_superuser(email, password)

        manager._create_user.assert_called_with(
            email, password, is_staff=True, is_superuser=True
        )
Exemplo n.º 7
0
def test_signup_cg_user():
    from django.conf import settings
    settings.configure()
    userManager = UserManager()

    token = userManager.create_new_user(CG_USER,{
        "userName" : "*****@*****.**",
        "password" : "123456"
    })
    if token:
        assert True
    else:
        assert False
    pass
Exemplo n.º 8
0
def signup():

    fn = request.json.get('fn')
    if not fn:
        return json.dumps({"error": "Please Enter your First Name"}), 500

    ln = request.json.get('ln')
    if not ln:
        return json.dumps({"error": "Please Enter your Last Name"}), 500

    email = request.json.get('email')
    if email is None:
        return json.dumps({"error": "Email is not valid"}), 500

    EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+")

    if not EMAIL_REGEX.match(email):
        return json.dumps({"error": "Email is not valid"}), 500

    password = request.json.get('password')
    if password is None:
        return json.dumps({"error": "Password is not valid"}), 500

    token = UserManager.signup(email, password, fn, ln)

    if token is None:
        return json.dumps({"error": "Please try another email"}), 500

    resp = Response(json.dumps({'code': 200}))

    resp.set_cookie('auth-token', token)

    return resp
Exemplo n.º 9
0
def on_trigger(submit_id, submit_author, comment):
    """
    On Trigger of bot
    :param submit_id:
    :param submit_author:
    :param comment:
    """
    cid = comment.id
    try:
        cauthor = comment.author.name
    except AttributeError:
        return

    cbody = comment.body.lower()
    message = cbody.split(OfferBot.TRIGGER)[1].split("\n")[0]

    if "accept" in message:
        # UserManager.plus_job(cauthor)
        reply = get_response_accept(cauthor, submit_author)
    elif "plusrep" in message:
        # UserManager.plus_rep(cauthor)
        reply = get_response_plus_rep(cauthor, submit_author)
    elif "minusrep" in message:
        reason = message.split("minusrep")[1]
        reply = get_response_minus_rep(cauthor, submit_author, reason)
    elif "done" in message:
        reply = get_response_done(cauthor, submit_author)
    else:
        reply = get_response_user(cauthor)

    if UserManager.get_rep_level(DBManager.get_user(cauthor)['reputation']) == "Scammer":
        OfferBot.bot_reply(comment, get_response_scammer(cauthor))

    OfferBot.bot_reply(comment, reply)
Exemplo n.º 10
0
def visitable(request, user_email, place_id):
    response_data = {}
    response_data["success"] = False
    response_data["canVisit"] = False

    #use usermanager method to get user we want
    user = UserManager.getActualUser(user_email)
    if user:
        location = Visited.objects.filter(user=user).filter(placeid=place_id)

        if (location):
            response_data["success"] = True
            response_data["date"] = str(location[0].visit_date)
            since_last = (datetime.today().date() -
                          location[0].visit_date).days
            response_data["since_last"] = since_last

            if (since_last >= 30):
                response_data["canVisit"] = True

        else:  #user hasnt visited this place before
            response_data["success"] = True
            response_data["canVisit"] = True

    else:
        errorMessage = "Error! This user has no visits."
        response_data = {'success': False, "error": errorMessage}

    return HttpResponse(json.dumps(response_data),
                        content_type="application/json")
class Migration(migrations.Migration):

    dependencies = [
        ('auth', '0006_require_contenttypes_0002'),
    ]

    operations = [
        migrations.CreateModel(
            name='User',
            fields=[
                ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),
                ('password', models.CharField(verbose_name='password', max_length=128)),
                ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
                ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
                ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='created', editable=False)),
                ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False)),
                ('email', models.EmailField(unique=True, verbose_name='email address', error_messages={'unique': 'A user with that email address already exists.'}, max_length=254)),
                ('first_name', models.CharField(max_length=30, blank=True, verbose_name='first name')),
                ('last_name', models.CharField(max_length=30, blank=True, verbose_name='last name')),
                ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
                ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
                ('groups', models.ManyToManyField(related_query_name='user', related_name='user_set', blank=True, verbose_name='groups', help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', to='auth.Group')),
                ('user_permissions', models.ManyToManyField(related_query_name='user', related_name='user_set', blank=True, verbose_name='user permissions', help_text='Specific permissions for this user.', to='auth.Permission')),
            ],
            options={
                'verbose_name': 'user',
                'verbose_name_plural': 'users',
            },
            managers=[
                ('objects', UserManager()),
            ],
        ),
    ]
Exemplo n.º 12
0
def connectGithub(channels, managerid):
    documents = db.get_collection("project")
    paths = "../Projects/rep"
    if UserManager.checkUserRole(managerid):
        try:
            gitlink = documents.find({
                "managerid": managerid
            }).distinct("githublink")[0]
            if gitlink != None:
                if gitlink.split("//")[0] == "https:":
                    if os.path.exists(paths):
                        repo = Repo(paths)
                        repo.remotes.origin.pull()
                    else:
                        Repo.clone_from(gitlink, paths)
                    repo = Repo(paths)
                    if not repo.bare:
                        commits = list(repo.iter_commits('master'))[:10000]
                        for commit in commits:
                            checkcommit(channels, commit, repo)
                            pass
                    else:
                        text = 'Repo description: Server problem'
                        SlackCommunication.postMessege(channels, text)
            else:
                text = 'Link Github repository.'
                SlackCommunication.postMessege(channels, text)
        except:
            text = 'Complete github link registration first'
            SlackCommunication.postMessege(channels, text)
Exemplo n.º 13
0
def checkAlltaskdetails(dicts):
    taskids, taskname, strtdate, enddate, totalslack, type, status, enddepends, strtsdepends = None, None, None, None, None, None, None, None, None
    documents = db.get_collection("task")
    channels = dicts.get("channel")
    manager = dicts.get("user")
    msg = dicts.get("text")
    if UserManager.checkUserRole(manager):
        count = 0
        array = msg.split(" ")
        for split in array:
            if split != None:
                if split[0] == "-":
                    if split == "-projectid":
                        projectid = array[count + 1]
                        taskids = documents.find({
                            "projectid": projectid
                        }).distinct("taskid")

            count = count + 1
        for taskid in taskids:
            taskname = documents.find({
                "taskid": taskid
            }).distinct("taskname")[0]
            strtdate = documents.find({
                "taskid": taskid
            }).distinct("starttime")[0]
            enddate = documents.find({"taskid": taskid}).distinct("endtime")[0]
            totalslack = documents.find({
                "taskid": taskid
            }).distinct("freeslack")[0]
            progress = documents.find({
                "taskid": taskid
            }).distinct("taskprogress")[0]
            type = documents.find({"taskid": taskid}).distinct("type")[0]
            status = documents.find({"taskid": taskid}).distinct("status")[0]
            enddepends = documents.find({
                "taskid": taskid
            }).distinct("enddepends")
            strtsdepends = documents.find({
                "taskid": taskid
            }).distinct("startdepends")
            if enddepends != None and enddepends != [] and enddepends != [
                    None
            ]:
                enddepends = enddepends[0]
            else:
                enddepends = "no depends"
            if strtsdepends != None and strtsdepends != [] and strtsdepends != [
                    None
            ]:
                strtsdepends = strtsdepends[0]
            else:
                strtsdepends = "no depends"
            text="\n Task name : "+taskname+" Task ID : "+taskid+"\n Start date : "+strtdate+\
                 " End date : "+enddate+" \n Task progress "+progress+" \n"+" Total Slack : "+totalslack+"\n Type : "+type+\
                 " Status : "+status+"\n  Depends : "+enddepends+" Start depends :" + strtsdepends
            SlackCommunication.postMessege(channels, text)
    else:
        text = "Only manager can perform this command"
        SlackCommunication.postMessege(channels, text)
Exemplo n.º 14
0
def login():
    if request.method == 'POST':
        user_data = request.values
        print request.args.get('remember_me')
        user = UserManager(mail=user_data['email'], password=user_data['password'])
        print request.args
        session['remember_me'] = request.args.get('remember_me', 1)
        if user.is_validate():
            login_user(user, remember=True)
            for key in session.iterkeys():
                print key
                print session[key]
            #print session['user_id']
            flash("Log in successfully")
            #nickname = user.get_nickname()
            return render_template('main.html', nickname=current_user._mail)
Exemplo n.º 15
0
def taskContent(dict):
    msg = dict.get("text")
    records = db.get_collection("task")
    manager = dict.get("user")
    channel = dict.get("channel")
    arraycontent = []
    array = msg.split(" ")
    if UserManager.checkUserRole(manager):
        taskid, content = None, None
        if array[0] == "-taskcontent" and array[1] == "-taskid" and array[
                3] == "-projectid":
            for x in range(5, len(array)):
                arraycontent.append(array[x])
                objectives = " ".join(arraycontent)
            if records.find_one_and_update(
                {
                    "taskid": array[2],
                    "projectid": array[4]
                }, {'$set': {
                    "taskcontent": objectives
                }}):
                text = "Data updated"
                SlackCommunication.postMessege(channel, text)
    else:
        text = "Only project manager can perform this command"
        SlackCommunication.postMessege(channel, text)
Exemplo n.º 16
0
 def register(self, inStream):
     username = inStream.readQString()
     password = inStream.readQString()
     email = inStream.readQString()
     status = UserManager.register(username, password, email)
     reply, outStream = self.newReply()
     outStream.writeInt16(status)
     self.sendReply(reply, outStream)
 def __init__(self, _ip, _p):
     self.__db_manager = DbManager.DbManager()
     self.__user_manager = UserManager.UserManager(self.__db_manager)
     self.__game_manager = None
     self.__service_manager = ServiceManager.ServiceManager(
         self.__user_manager, self.__game_manager)
     self.__server_socket = ServerNetwork.ServerSocket(
         _ip, _p, self.__service_manager)
Exemplo n.º 18
0
def library_members(libcon):

    idnumb = NumbID()
    usermanager = UserManager.UserManager()
    usermanager.set_library_controller(libcon)
    usermanager.create_user(idnumb.new_id())
    print 'User ID created: ',idnumb.idnumber
    usermanager.create_user(idnumb.new_id())
    print 'User ID created: ',idnumb.idnumber
Exemplo n.º 19
0
 def login(self, inStream):
     username = inStream.readQString()
     password = inStream.readQString()
     email = inStream.readQString()
     status, user = UserManager.authenticate(username, password)
     if status == AUTHENTICATE_SUCCESS:
         self.user = user
     reply, outStream = self.newReply()
     outStream.writeInt16(status)
     self.sendReply(reply, outStream)
    def __init__(self):
        if not (InstanceManager.make_first_instance):
            #自身のstaticメンバを1度だけ初期化
            InstanceManager.gp = GUIProcessor.GUIProcessor(self)
            InstanceManager.mp = MessageProcessor.MessageProcessor(self)
            InstanceManager.um = UserManager.UserManager(self)
            InstanceManager.cp = ClientProcessor.ClientProcessor(self)
            InstanceManager.sv = Server.Server(self)

            #static menberを再度生成しないようにする
            InstanceManager.make_first_instance = True
Exemplo n.º 21
0
    def test_create_user_uses_user_values_or_sets_defaults_for_is_staff_and_is_superuser_if_not_defined(
        self, is_staff, is_superuser, expected_is_staff, expected_is_superuser
    ):
        manager = UserManager()
        email = "*****@*****.**"
        password = "******"
        kwargs = {}
        if is_staff is not None:
            kwargs["is_staff"] = is_staff
        if is_superuser is not None:
            kwargs["is_superuser"] = is_superuser

        manager.create_user(email, password, **kwargs)

        manager._create_user.assert_called_with(
            email,
            password,
            is_staff=expected_is_staff,
            is_superuser=expected_is_superuser,
        )
Exemplo n.º 22
0
def login():
    if current_user is not None and current_user.is_authenticated():
        return redirect(url_for('chatChannels'))

    form = LoginForm()
    if form.validate_on_submit():
        validUser = UserManager.validateUser(session, User(form.username.data, form.password.data))
        if (validUser != None):
            login_user(validUser)
            return redirect(request.args.get("next") or url_for("chatChannels"))
        else:
            flash('Incorrect username or password')
    return render_template("login.html", form=form)
Exemplo n.º 23
0
def get_response_plus_rep(user, op):
    """
    OfferBot Tests
    :param user:
    """
    user_info = DBManager.get_user(user)
    rep = user_info['reputation']
    rep_string = UserManager.get_rep_level(rep)

    response = Template(config.get("offer", "plus_rep_reply"))
    response = response.substitute(username=user, username2=op, rep=rep_string, repno=rep)

    return response
Exemplo n.º 24
0
def update_github(dict):
    count = 0
    msg = dict.get("text")
    manager = dict.get("user")
    channel = dict.get("channel")
    ts = dict.get("ts")
    githublink = None
    array = msg.split(" ")
    if UserManager.checkUserRole(manager):
        for split in array:
            try:
                if split != None and split != "":
                    if split[0] == "-":
                        if split == "-githublink":
                            githublink = array[count + 1]
            except:
                break
            count = count + 1
        SlackCommunication.deleteMessege(channel, ts)
        records = db.get_collection("project")
        if githublink == "" or githublink == None:
            text = "User command is incomplete. Please input right command to proceed"
            SlackCommunication.postMessege(channel, text)
        else:
            if UserManager.checkUserRole(manager) and githublink != None:
                githublink = githublink[1:]
                githublink = githublink[:-1]
                githublink = githublink.split("|")[0]
                if records.find_one_and_update(
                    {"managerid": manager},
                    {'$set': {
                        "githublink": githublink
                    }}):
                    text = "Github linked"
                    SlackCommunication.postMessege(channel, text)
    else:
        text = "Only manager can performe this command and need to configure at the beginning of project"
        SlackCommunication.postMessege(channel, text)
Exemplo n.º 25
0
 def __init__(self, port=9999, maximumClient=10):
     print("Initializing Server...")
     self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.host = socket.gethostname()
     self.port = port
     self.maximumClient = maximumClient
     try:
         self.socket.bind((self.host, self.port))
         self.socket.listen(self.maximumClient)
         self.userManager = UserManager(self.socket)
         print("The server is ready!")
         self.listen()
     except OSError:
         print("Server is already working!")
Exemplo n.º 26
0
def usermanager():
    global window
    window = QDialog()
    userMgr = UserManager.Ui_Dialog()
    userMgr.setupUi(window)
    view = userMgr.tableUser
    model = QSqlTableModel()
    view.setModel(model)
    model.setTable('USER')
    model.select()
    model.setHeaderData(0, Qt.Horizontal, '用户名')
    model.setHeaderData(1, Qt.Horizontal, '密码')
    model.setHeaderData(2, Qt.Horizontal, '用户权限')
    window.show()
Exemplo n.º 27
0
def enter_Name():
    global name
    global user_points
    offline_update(name)
    name = ""
    enter_name = True
    name_entered = False
    name = ""
    login_image = pygame.image.load("images/login.jpg").convert()

    while enter_name:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                offline_update(name)
                pygame.quit()
        if name != "":
            name_entered = True
        gameDisplay.fill(white)
        gameDisplay.blit(login_image, (0, 0))
        #message_to_screen("Waiting For Username", red, [200, 100], 35)
        #message_to_screen("Enter The Username You Previously Used", black, [120, 200], 30)
        #message_to_screen("OR", black, [380, 250], 35)
        #message_to_screen("Choose any username to create a new account", black, [90, 300], 30)
        pygame.display.update()
        clock.tick(10)
        if name_entered:
            name = name.lower()
            name = name.replace(' ', '')
            if name == "global" or name == "blank":
                name_entered = False
                name = ""
            try:
                user_details = User.Get_Details(name)
                user_ex = user_details.get_points()
                if user_ex == "false":
                    user_details.register_user()
                    print(
                        "Account Created! Always use this name to access your score"
                    )
                user_points = user_details.get_points()
            except:
                user_points = "Can't Connect To Server"
            print(user_points)
            print("Continue to game...")
            if name_entered:
                enter_name = False
                game_Menu()

        box = DialogBox()
        box.box()
Exemplo n.º 28
0
def dealAfterPack(sock, name):
    while True:
        src = sock.recv(1024)
        if not src:
            break
        dst = src.decode('utf-8')
        if dst.startswith('ls'):
            os.chdir(name)
            for eachFile in os.listdir():
                sock.send((eachFile + '\r\n').encode('utf-8'))
            os.chdir('..')
        elif dst.startswith('download'):
            preList = dst.split(' ')
            download.startDownload(name, preList[1], preList[2])
            sock.send(b'download start')
        elif dst.startswith('check'):
            preList = dst.split(' ')
            result = download.check(name, preList[1])
            if result == 1:
                sock.send(b'no download dir')
            elif result == 2:
                sock.send(b'read fail')
            else:
                sock.send(result.encode('utf8'))
        elif dst.startswith('get'):
            preList = dst.split(' ')
            result = download.check(name, preList[1])
            if not result in [1, 2]:
                obj = UserManager.readServerSetting()
                if obj != False:
                    ip = obj['IP']
                    port = obj['downloadPort']
                    sock.send(('http://' + ip + (':%d' % port) + '/' + name +
                               '/' + preList[1]).encode('utf-8'))
                else:
                    sock.send(b'server data error')
            else:
                sock.send(b'connot download this file')
        elif dst.startswith('del'):
            try:
                preList = dst.split(' ')
                os.remove(name + '/' + preList[1])
                sock.send(b'remove success')
            except:
                sock.send(b'remove fail')
        elif dst == 'exit':
            sock.send(b'Bye~')
            break
        else:
            sock.send(b'Unknow order')
Exemplo n.º 29
0
 def __init__(self, conn):
     # Create an INET, STREAMing socket
     self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     # Bind the socket to an addres, and a port
     self.serversocket.bind(conn)
     # Become a server socket
     self.serversocket.listen(5)
     
     control = stackless.channel()
     
     stackless.tasklet(self.acceptConnection)(control)
     
     UserManager.UserManager(control)
Exemplo n.º 30
0
def register():
    if current_user is not None and current_user.is_authenticated():
        return redirect(url_for('chatChannels'))

    form = RegistrationForm()
    if form.validate_on_submit():
        if form.password.data == form.passwordConfirmation.data:
            user = User(form.username.data, form.password.data)
            if UserManager.registerNewUser(session, user):
                return redirect(request.args.get("next") or url_for("login"))
            else:
                flash('This username is already in use')
        else:
            flash('Passwords do not match')
    return render_template("register.html", form=form)    
Exemplo n.º 31
0
def mainServer():
    obj = UserManager.readServerSetting()
    if obj == False:
        return
    ip = obj['IP']
    port = obj['port']
    key = obj['key']

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((ip, port))
    s.listen(5)
    while (True):
        sock, addr = s.accept()
        clientThread = threading.Thread(target=dealClient, args=(sock, addr))
        clientThread.start()
Exemplo n.º 32
0
class User(AbstractBaseUser, PermissionsMixin, models.Model):
    class Meta:
        swappable = 'AUTH_USER_MODEL'
        verbose_name = 'user'
        verbose_name_plural = 'users'
        abstract = False

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    email = models.EmailField(unique=True, null=False, blank=False)
    first_name = models.CharField('first name', max_length=30, blank=True, null=True)
    last_name = models.CharField('last name', max_length=30, blank=True, null=True)
    date_joined = models.DateTimeField('date joined', auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    is_staff = models.BooleanField(
        'staff_status',
        default=False,
        help_text='Designates whether the user can log into this admin site.',
    )

    is_active = models.BooleanField(
        'active',
        default=True,
        help_text=
        'Unselect this instead of deleting accounts.',
    )

    objects = UserManager()
    USERNAME_FIELD = 'email'

    def get_full_name(self):
        """
        Returns the first_name plus the last_name, with a space in between.
        """
        full_name = '{first_name} {last_name}'.format(first_name=self.first_name,
                                                      last_name=self.last_name)
        return full_name.strip()

    def get_short_name(self):
        "Returns the short name for the user."
        return self.first_name

    def email_user(self, subject, message, from_email=None, **kwargs):
        """
        Sends an email to this User.
        """
        from django.core.mail import send_mail
        send_mail(subject, message, from_email, [self.email], **kwargs)
Exemplo n.º 33
0
def register_Project(dict):
    count = 0
    user = dict.get("user")
    msg = dict.get("text")
    channels = dict.get("channel")
    if UserManager.checkUserRole(user):
        projectid, projectname, startdate, enddate, totalslack = None, None, None, None, None
        array = msg.split(" ")
        for split in array:
            if split[0] != None and split[0] != " ":
                if split[0] == "-":
                    if split == "-projectid":
                        projectid = array[count + 1]
                    if split == "-projectname":
                        projectname = array[count + 1]
                    if split == "-startdate":
                        startdate = array[count + 1]
                    if split == "-enddate":
                        enddate = array[count + 1]
                    if split == "-totalslack":
                        totalslack = array[count + 1]
            count = count + 1
        records = db.get_collection("project")
        if periodValidation(
                startdate, enddate, channels
        ) and projectid != None and projectname != None and startdate != None and enddate != None and totalslack != None and Task.duplicateChecker(
                "projectid", projectid, "project"):
            mydict = {
                "projectid": projectid,
                "projectname": projectname,
                "startdate": startdate,
                "enddate": enddate,
                "totalslack": totalslack,
                "managerid": user
            }
            ischecked = records.insert_one(mydict).acknowledged
            if ischecked:
                text = "Project  " + projectname + " is connected"
                SlackCommunication.postMessege(channels, text)
            else:
                text = "Process terminated. Try again"
                SlackCommunication.postMessege(channels, text)
        else:
            text = "Check input again"
            SlackCommunication.postMessege(channels, text)
    else:
        text = "Only project manager can perform this project"
        SlackCommunication.postMessege(channels, text)
Exemplo n.º 34
0
def dealFirstPack(data):
    try:
        nameLen = data[0]
        name = data[1:nameLen + 1].decode('utf-8')
        pswLen = data[nameLen + 1]
        psw = data[nameLen + 2:].decode('utf-8')
    except Exception as e:
        return 3

    realPsw = UserManager.readUserData(name)
    if realPsw == None:
        return 1
    elif realPsw != psw:
        return 2
    else:
        return name
Exemplo n.º 35
0
def check_session():

    token = request.cookies.get('auth-token')

    if token is None:
        return json.dumps({"error": "Invalid Login"}), 500

    user = UserManager.check_login(token)

    if user is None:
        return json.dumps({"error": "Invalid Login"}), 500

    name = user.get('fn') + " " + user.get('ln')
    resp = Response(json.dumps({'code': 200, 'name': name}))

    return resp
Exemplo n.º 36
0
def enter_Name():
    global name
    global user_points
    offline_update(name)
    name = ""
    enter_name = True
    name_entered = False
    name = ""
    login_image = pygame.image.load("images/login.jpg").convert()

    while enter_name:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                offline_update(name)
                pygame.quit()
        if name != "":
            name_entered = True
        gameDisplay.fill(white)
        gameDisplay.blit(login_image, (0, 0))
        pygame.display.update()
        clock.tick(10)
        if name_entered:
            name = name.lower()
            name = name.replace(' ', '')
            if name == "global" or name == "blank":
                name_entered = False
                name = ""
            try:
                user_details = User.Get_Details(name)
                user_ex = user_details.get_points()
                if user_ex == "false":
                    user_details.register_user()
                    print(
                        "Account Created! Always use this name to access your score"
                    )
                user_points = user_details.get_points()
            except:
                user_points = "Can't Connect To Server"
            print(user_points)
            print("Continue to game...")
            if name_entered:
                enter_name = False
                game_Menu()
        box = DialogBox()
        box.box()
Exemplo n.º 37
0
class Authentification:

    userManager = UserManager.getInstance()

    # Session id
    session_id = 0

    def getSessionID(self, login, password):
        """
			Return a session ID if the user is valid
			@type  login : String
			@param login : Login  for the user
			@type  password : String
			@param password : Password for the user
			@rtype: Int
			@return: The new Session ID
		"""

        # only if this user is valid
        valid, user = self.isValid(login, password)
        print valid
        if valid:
            # return a new session_id
            self.session_id += 1
            return user, self.session_id
        else:
            return False, None

    # Authentification method
    def isValid(self, login, password):
        """
			Test is the user is valid
			@type  login : String
			@param login : Login  for the user
			@type  password : String
			@param password : Password for the user
			@rtype: int
			@return: The result if the test
		"""
        user = self.userManager.findUserByLogin(login)

        if user != None:
            if user.getPassword() == password:
                return True, user
        return False, None
Exemplo n.º 38
0
def updateproject(dicts):
    channels = dicts.get("channel")
    msg = dicts.get("text")
    count = 0
    if UserManager.checkUserRole(dicts.get("user")):
        array = msg.split(" ")
        for split in array:
            if split != None:
                if split[0] == "-":
                    if split == "-projectid":
                        projectid = array[count + 1]
                    if split == "-projectname":
                        projectname = array[count + 1]
                        projectmongoupdate(channels, projectid, "projectname",
                                           projectname, dicts)
                    if split == "-totalslack":
                        totalslack = array[count + 1]
                        projectmongoupdate(channels, projectid, "totalslack",
                                           totalslack, dicts)
                    if split == "-startdate":
                        startdate = array[count + 1]
                        projectmongoupdate(channels, projectid, "startdate",
                                           startdate, dicts)
                    if split == "-enddate":
                        enddate = array[count + 1]
                        projectmongoupdate(channels, projectid, "enddate",
                                           enddate, dicts)
                    if split == "-managerid":
                        managerid = array[count + 1]
                        projectmongoupdate(channels, projectid, "managerid",
                                           managerid, dicts)
                    if split == "-githublink":
                        githublink = array[count + 1]
                        projectmongoupdate(channels, projectid, "githublink",
                                           githublink, dicts)

            count = count + 1
        text = "System updated!"
        SlackCommunication.postMessege(channels, text)

    else:
        text = "Only managers can perform this"
        SlackCommunication.postMessege(channels, text)
Exemplo n.º 39
0
 def __init__(self):
     cursor.execute("TRUNCATE TABLE leagues")
     cursor.execute("TRUNCATE TABLE users")
     cursor.execute("TRUNCATE TABLE middle")
     self.userManager = UserManager.User_Manager()
     self.leagueManager = LeagueManager.League_Manager()
     print("initialized server")
     self.userManager.create_user("default", "password")
     self.userManager.create_user("default1", "password1")
     self.leagueManager.create_league(
         json.dumps({
             "league_name": "butt",
             "owner_id": 1,
             "team_count": 8,
             "team_name": "dragons"
         }))
     self.leagueManager.add_team(2, 1, "tigers")
     connection.commit()
     self.run_server()
Exemplo n.º 40
0
def load_user(userid):
    return UserManager.findUserById(session, userid)
Exemplo n.º 41
0
def logout():
    UserManager.removeChatChannelIdForUser(session, current_user.id)
    logout_user()
    return redirect('home')    
Exemplo n.º 42
0
def chatChannel(channel_id):
    UserManager.enterChatChannel(session, current_user, channel_id)
    return render_template("chat_channel.html", channel_id = channel_id)    
Exemplo n.º 43
0
def leaveChatChannel(channel_id):
    UserManager.removeChatChannelIdForUser(session, current_user.id)
    return redirect(url_for('chatChannels'))