Ejemplo n.º 1
0
def twoFactorAuthentication(handler, p_action):
    handler.title("Two-Factor Authentication")
    requirePriv(handler, "User")

    if p_action == "enable":
        handler.session["user"].hotpKey = b32encode("".join(chr(randrange(256)) for _ in range(10)))
        handler.session["user"].save()
        Event.tfa(handler, handler.session["user"])

        print SuccessBox("Two-factor authentication is <b>enabled</b>")
        print "Your HOTP key is <b>%s</b>:<br><br>" % handler.session["user"].hotpKey
        print '<div style="text-align: center"><img src="https://chart.googleapis.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/Sprint%%3Fsecret%%3D%s"></div><br>' % handler.session[
            "user"
        ].hotpKey

        print "This key will not be displayed again &mdash; be sure to write it down, or add it to your Google Authenticator list now"
    elif p_action == "disable":
        handler.session["user"].hotpKey = ""
        handler.session["user"].save()
        Event.tfa(handler, handler.session["user"])

        delay(handler, SuccessBox("Two-factor authentication is <b>disabled</b>"))
        redirect("/users/%s" % handler.session["user"].username)
    else:
        ErrorBox.die("Unexpected action: <b>%s</b>" % stripTags(p_action))
Ejemplo n.º 2
0
 def __init__(self):
     self.__progress = QuestsProgress()
     self.__waitForSync = False
     self.__invalidateCbID = None
     self.onSyncStarted = Event()
     self.onSyncCompleted = Event()
     return
Ejemplo n.º 3
0
 def __init__(self):
     Event.__init__(self)
     self.base = 'adventure'
     self.desc = "+1 Buy, Look at the top 5 cards of your deck. Discard 3 of them and put the rest back in any order"
     self.name = "Scouting Party"
     self.buys = 1
     self.cost = 2
Ejemplo n.º 4
0
 def __init__(self):
     self.__waitForSync = False
     self.__fortProvider = ClientFortProvider()
     self.__clanMembersLen = None
     self.onSyncStarted = Event()
     self.onSyncCompleted = Event()
     return
Ejemplo n.º 5
0
def adminReplPost(handler, p_code):
	def makeStr(v):
		if isinstance(v, list):
			return "<ul>%s</ul>" % ''.join("<li>%s</li>" % item for item in v)
		return str(v)

	handler.wrappers = False

	p_code = re.sub('^!([A-Za-z]+)$', 'from \\1 import \\1', p_code)
	match = re.match('!([A-Za-z ]+)$', p_code)
	if match:
		parts = match.group(1).split(' ')
		res = []
		for part in parts:
			w = ResponseWriter()
			adminReplPost(handler, "!%s" % part)
			res.append(fromJS(w.done()))
		print toJS(res)
		done()

	if 'admin-repl' not in handler.session:
		print toJS({'code': highlightCode(p_code), 'stdout': '', 'stderr': ['Session Expired', 'REPL session no longer exists'], 'vars': {}})
		done()

	writer = ResponseWriter()
	try:
		Event.repl(handler, p_code)
		exec compile(p_code, '<admin repl>', 'single') in handler.session['admin-repl']
		stderr = ''
	except:
		stderr = map(str, [sys.exc_info()[0].__name__, sys.exc_info()[1]])
	stdout = writer.done()

	vars = sorted([(k, pformat(v), makeStr(v)) for (k, v) in handler.session['admin-repl'].items() if k != '__builtins__'], lambda (k1, v1, vs1), (k2, v2, vs2): cmp(k1, k2))
	print toJS({'code': highlightCode(p_code), 'stdout': stdout, 'stderr': stderr, 'vars': vars})
Ejemplo n.º 6
0
def prefsPost(handler, p_default_sprint_tab, p_default_tasks_tab, p_backlog_style, p_messages = []):
	def die(msg):
		print msg
		done()

	handler.wrappers = False

	if not handler.session['user']:
		die("You must be logged in to modify preferences")
	if p_default_sprint_tab not in sprintTabs():
		die("Unrecognized default sprint tab <b>%s</b>" % stripTags(p_default_sprint_tab))
	if p_default_tasks_tab not in taskTabs:
		die("Unrecognized default task tab <b>%s</b>" % stripTags(p_default_tasks_tab))
	if set(p_backlog_style.keys()) != set(name for block in statusMenu for name in block):
		die("Backlog style key mismatch")
	if not set(p_messages.keys()) <= set(name for name, desc in messageTypes):
		die("Message type mismatch")

	prefs = handler.session['user'].getPrefs()
	prefs.defaultSprintTab = p_default_sprint_tab
	prefs.defaultTasksTab = p_default_tasks_tab
	prefs.backlogStyles = p_backlog_style
	prefs.messages = dict((name, name in p_messages.keys()) for name, desc in messageTypes)
	prefs.save()

	handler.responseCode = 299
	print "Saved changes"
	Event.prefs(handler)
Ejemplo n.º 7
0
 def __init__(self):
     Event.__init__(self)
     self.base = 'empires'
     self.desc = "Gain a Curse. If you do, trash a card from your hand. +1VP per Coin it cost."
     self.name = "Ritual"
     self.cost = 4
     self.required_cards = ['Curse']
Ejemplo n.º 8
0
 def __init__(self):
     Event.__init__(self)
     self.base = 'empires'
     self.desc = "After this turn, put all cards from your deck and discard pile into your hand, trash any number, shuffle your hand into your deck, then draw 5 cards."
     self.name = "Donate"
     self.cost = 0
     self.debtcost = 8
Ejemplo n.º 9
0
 def __init__(self, fig, subplot, maxt=1, dt=0.01, ylims = (-1, 1)):
     '''
     Constructor
     '''
     
     self.maxt = maxt
     self.dt = dt
     self.subplot = subplot
     self.ylims = list(ylims)
     
     
     self.tdata = [0]
     
     self.ax = fig.add_subplot(*self.subplot)
     self.ylims_ch()
     self.ax.set_xlim(0, self.maxt)
     self.ax.grid()
     
     self.on_data = Event()
     self.__on_line_upd = Event()
     self.__on_line_rst = Event()
     self.need_stop = False
     
     self.anim = animation.FuncAnimation(fig, self.update, itertools.count, blit=True, event_source=self)
     
     
     
     pass
Ejemplo n.º 10
0
class _SettingsCache(object):
    def __init__(self):
        self.__intSettings = IntSettingsRequester()
        self.__waitForSync = False
        self.onSyncStarted = Event()
        self.onSyncCompleted = Event()

    def init(self):
        g_clientUpdateManager.addCallbacks({"intUserSettings": self._onResync})

    def fini(self):
        self.onSyncStarted.clear()
        self.onSyncCompleted.clear()
        g_clientUpdateManager.removeObjectCallbacks(self)

    @property
    def waitForSync(self):
        return self.__waitForSync

    @property
    def settings(self):
        return self.__intSettings

    def _onResync(self, *args):
        self.__invalidateData()

    @async
    def update(self, callback=None):
        self.__invalidateData(callback)

    def getSectionSettings(self, section, defaultValue=0):
        return self.__intSettings.getSetting(section, defaultValue)

    def setSectionSettings(self, section, value):
        self.__intSettings.setSetting(section, value)

    def setSettings(self, settings):
        self.__intSettings.setSettings(settings)

    def getSetting(self, key, defaultValue=0):
        return self.__intSettings.getSetting(key, defaultValue)

    def getVersion(self, defaultValue=0):
        return self.__intSettings.getSetting("VERSION", defaultValue)

    def setVersion(self, value):
        self.__intSettings.setSetting("VERSION", value)

    def __invalidateData(self, callback=lambda *args: None):
        def cbWrapper(*args):
            self.__waitForSync = False
            self.onSyncCompleted()
            callback(*args)

        self.__waitForSync = True
        self.onSyncStarted()
        if BattleReplay.g_replayCtrl.isPlaying:
            cbWrapper(dict())
            return
        self.__intSettings.request()(cbWrapper)
Ejemplo n.º 11
0
class List(list):
    def __init__(self, *args, **kwargs):
        list.__init__(self, *args, **kwargs)
        
        # addEvent(pos, item)
        self._addEvent = Event()
        # removeEvent(pos, item)
        self._removeEvent = Event()
        # setitemEvent(pos, item)
        self._setitemEvent = Event()
    
    def __setitem__(self, key, value):
        self._setitemEvent.trigger(key, value)
        return list.__setitem__(self, key, value)
    
    def __delitem__(self, key):
        self._removeEvent.trigger(key, self[key])
        return list.__delitem__(self, key)
    
    def append(self, item):
        self._addEvent.trigger(len(self), item)
        return list.append(self, item)
    
    def insert(self, pos, item):
        self._addEvent.trigger(pos, item)
        return list.insert(self, pos, item)
    
    def pop(self, pos=-1):
        self._removeEvent.trigger(pos, self[pos])
        return list.pop(self, pos)
    
    def remove(self, item):
        pos = self.index(item)
        del self[pos]
Ejemplo n.º 12
0
	def receiveEvent(self, event, emitter):		
		if event.attributes['signature'] == 'game_tick':
			self.attributes['tick_count'] += 1
		
		filterFunc	= (lambda receiver: receiver.attributes['signature'] == event.attributes['signature'])
	
		for handler in filter(filterFunc, self.attributes['event_handlers']):
			newEvent = Event()
		
			newEvent.attributes = {
				'signature'		: event.attributes['signature'],
				'data'			: event.attributes['data'].copy(),
				'flags'			: event.attributes['flags'][:],
				'receiver'		: self,
				'event_target'	: None
			}
			
			handler.receiveEvent(newEvent)
			
		if self.attributes.has_key('AI'):			
			newEvent = Event()
		
			newEvent.attributes = {
				'signature'		: event.attributes['signature'],
				'data'			: event.attributes['data'].copy(),
				'flags'			: event.attributes['flags'][:],
				'receiver'		: self,
				'event_target'	: None
			}
			
			self.attributes['AI'].receiveEvent(newEvent, emitter)
Ejemplo n.º 13
0
 def __init__(self):
     Event.__init__(self)
     self.base = 'empires'
     self.desc = """Once per turn: Turn your Journey token over; then if it's face up,
     choose up to 3 differently named cards you have in play and gain a copy of each."""
     self.name = "Pilgrimage"
     self.cost = 4
Ejemplo n.º 14
0
def adminPrivilegesPost(handler, p_grant):
	handler.title("Privileges")
	requirePriv(handler, 'Admin')
	p_grant = {name: privs.keys() for name, privs in p_grant.iteritems()}

	privNames = set()
	for privs in p_grant.values():
		privNames |= set(privs)
	if not privNames <= set(privList.keys()):
		ErrorBox.die("Update privileges", "Unrecognized privilege name")

	for user in User.loadAll():
		for priv in privList:
			privs = p_grant.get(user.username, [])
			has = user.hasPrivilege(priv)
			if has and priv not in privs:
				print "Revoking %s from %s<br>" % (priv, user.username)
				user.privileges.remove(priv)
				Event.revokePrivilege(handler, user, priv)
			elif not has and priv in privs:
				print "Granting %s to %s<br>" % (priv, user.username)
				user.privileges.add(priv)
				Event.grantPrivilege(handler, user, priv, False)
		user.save()
	print "Done"
Ejemplo n.º 15
0
class DisposableEntity(object):

    def __init__(self):
        super(DisposableEntity, self).__init__()
        self.onModuleDispose = Event()
        self.__created = False
        self.__disposed = False

    def create(self):
        self.__created = True
        self.__disposed = False
        self._populate()

    def destroy(self):
        if self.__disposed:
            return
        self.onModuleDispose(self)
        self.onModuleDispose.clear()
        self._dispose()
        self.__disposed = True

    def _populate(self):
        pass

    def _dispose(self):
        pass

    def _isCreated(self):
        return self.__created

    def isDisposed(self):
        return self.__disposed
Ejemplo n.º 16
0
 def __init__(self):
     Event.__init__(self)
     self.base = 'empires'
     self.desc = "+1VP, Gain a Gold."
     self.name = "Wedding"
     self.cost = 4
     self.debtcost = 3
Ejemplo n.º 17
0
def newGroupPost(handler, p_group, p_name):
	def die(msg):
		print msg
		done()

	handler.title('New Group')
	requirePriv(handler, 'User')
	handler.wrappers = False

	predid = to_int(p_group, 'group', die)
	pred = Group.load(predid)
	if not pred:
		die("No group with ID <b>%d</b>" % predid)
	elif p_name.strip() == '':
		die("Group must have a non-empty name")

	group = Group(pred.sprint.id, p_name, pred.seq + 1)
	group.save()

	handler.responseCode = 299
	delay(handler, """
<script type=\"text/javascript\">
$(document).ready(function() {
	$('#group%d').effect('highlight', {}, 3000);
});
</script>""" % group.id)
	print "/sprints/%d#group%d" % (group.sprint.id, group.id)
	Event.newGroup(handler, group)
Ejemplo n.º 18
0
 def __init__(self):
     self.__vehInvID = 0
     self.__changeCallbackID = None
     self.__historicalBattle = None
     self.onChanged = Event()
     self.onChangeStarted = Event()
     return
Ejemplo n.º 19
0
 def __init__(self):
     Event.__init__(self)
     self.base = 'empires'
     self.desc = "+1 Buy. Gain a Silver."
     self.name = "Delve"
     self.buys = 1
     self.cost = 2
Ejemplo n.º 20
0
def newSprintPost(handler, p_project, p_name, p_start, p_end, p_members = None, p_private = False, p_hidden = False):
	def die(msg):
		print msg
		done()

	handler.wrappers = False
	p_project = int(p_project)
	if not handler.session['user']:
		die("You must be logged in to create a new sprint")

	project = Project.load(p_project)
	if not project:
		die("Unknown project ID: %d" % p_project)

	if p_name == '':
		die("The sprint name cannot be empty")

	try:
		start = re.match("^(\d{1,2})/(\d{1,2})/(\d{4})$", p_start)
		if not start:
			raise ValueError
		month, day, year = map(int, start.groups())
		start = datetime(year, month, day)
	except ValueError:
		die("Malformed start date: %s" % stripTags(p_start))

	try:
		end = re.match("^(\d{1,2})/(\d{1,2})/(\d{4})$", p_end)
		if not end:
			raise ValueError
		month, day, year = map(int, end.groups())
		end = datetime(year, month, day, 23, 59, 59)
	except ValueError:
		die("Malformed end date: %s" % stripTags(p_end))

	msg = Sprint.validateDates(start, end)
	if msg:
		die(msg)

	members = set(User.load(int(memberid)) for memberid in p_members)
	if None in members:
		die("Unknown username")
	if handler.session['user'] not in members:
		die("The scrummaster (%s) must be a sprint member" % handler.session['user'])

	sprint = Sprint(project.id, p_name, handler.session['user'].id, dateToTs(start), dateToTs(end))
	sprint.members |= members
	if p_private or p_hidden:
		sprint.flags.add('private')
	if p_hidden:
		sprint.flags.add('hidden')
	sprint.save()
	# Make a default 'Miscellaneous' group so there's something to add tasks to
	Group(sprint.id, 'Miscellaneous', 1, False).save()
	# Make the standard set of sprint goals
	Goal.newSet(sprint)

	handler.responseCode = 299
	print "/sprints/%d" % sprint.id
	Event.newSprint(handler, sprint)
Ejemplo n.º 21
0
	def test__addSegment__right_first(self):
		e = Event(1, 1)
		s = ComparableSegment(0, 0, 1, 1)
		e.addSegment(s)
		self.assertEqual(e.right, [s])
		self.assertEqual((e.left, e.inner_inter, e.low, e.high), 
						 ([], [], [], []))
Ejemplo n.º 22
0
def newNoteModify(handler, taskid, id, p_action):
    handler.title("New Note")
    requirePriv(handler, "User")

    if p_action != "delete":
        ErrorBox.die("Invalid Action", "Unrecognized action <b>%s</b>" % p_action)

    taskid = int(taskid)
    task = Task.load(taskid)
    if not task or task.sprint.isHidden(handler.session["user"]):
        ErrorBox.die("Invalid Task", "No task with ID <b>%d</b>" % taskid)

    id = int(id)
    note = Note.load(id)
    if not note:
        ErrorBox.die("Invalid Note", "No note with ID <b>%d</b>" % noteid)
    elif note.task != task:  # Doesn't really matter, but shouldn't happen
        ErrorBox.die("Task mismatch", "Note/task mismatch")
    elif note.user != handler.session["user"]:
        ErrorBox.die("Permission denied", "Notes can only be deleted by their creators")

    note.delete()
    delay(handler, SuccessBox("Deleted note", close=3))
    Event.deleteNote(handler, note)
    redirect("/tasks/%d" % task.id)
Ejemplo n.º 23
0
def taskEditPost(handler, ids, p_hours, p_status, p_goal, p_assigned=[], p_include={}):
    handler.title("Edit tasks")
    requirePriv(handler, "Write")

    allIDs = map(int, uniq(ids.split(",")))
    ids = map(lambda i: to_int(i, "include", ErrorBox.die), p_include.keys())
    if not set(ids) <= set(allIDs):
        ErrorBox.die("Included tasks don't match query arguments")

    tasks = dict((id, Task.load(id)) for id in ids)
    if not all(tasks.values()):
        ids = [str(id) for (id, task) in tasks.iteritems() if not task]
        ErrorBox.die(
            "No %s with %s %s"
            % ("task" if len(ids) == 1 else "tasks", "ID" if len(ids) == 1 else "IDs", ", ".join(ids))
        )
    tasks = [tasks[id] for id in ids]
    if len(set(task.sprint for task in tasks)) > 1:
        ErrorBox.die("All tasks must be in the same sprint")
    sprint = (tasks[0] if len(tasks) > 0 else Task.load(allIDs[0])).sprint
    if sprint.isHidden(handler.session["user"]):
        ErrorBox.die(
            "No %s with %s %s"
            % ("task" if len(ids) == 1 else "tasks", "ID" if len(ids) == 1 else "IDs", ", ".join(ids))
        )
    if not sprint.canEdit(handler.session["user"]):
        ErrorBox.die("You don't have permission to modify this sprint")

    assignedids = set(to_int(i, "assigned", ErrorBox.die) for i in p_assigned)

    changes = {
        "assigned": False if assignedids == set() else {User.load(assignedid) for assignedid in assignedids},
        "hours": False if p_hours == "" else int(p_hours),
        "status": False if p_status == "" else p_status,
        "goal": False if p_goal == "" else Goal.load(int(p_goal)),
    }

    if changes["assigned"] and not all(changes["assigned"]):
        ErrorBox.die("Invalid assignee")
    if changes["assigned"] and not set(changes["assigned"]).issubset(sprint.members):
        ErrorBox.die("Unable to assign tasks to non-sprint members")
    if changes["goal"] and changes["goal"].sprint != sprint:
        ErrorBox.die("Unable to set goal to a goal outside the sprint")

    changed = set()
    for task in tasks:
        for field, value in changes.iteritems():
            if value is not False and getattr(task, field) != value:
                setattr(task, field, value)
                changed.add(task)
                Event.taskUpdate(handler, task, field, value)

    if len(changed) == 0:
        delay(handler, WarningBox("No changes necessary", close=3, fixed=True))
    else:
        for task in changed:
            task.saveRevision(handler.session["user"])
        delay(handler, SuccessBox("Updated %d %s" % (len(changed), "task" if len(changed) == 1 else "tasks")))
    redirect("/sprints/%d" % sprint.id)
Ejemplo n.º 24
0
def main(json_event):
	json_event
	d = json.loads(json_event)
	uid = d['uid']
	lat = d['lat']
	lon = d['lon']
	timestamp = d['timestamp']
	Event.add(uid, lat, lon, timestamp)
Ejemplo n.º 25
0
class _ItemsCache(object):

    def __init__(self):
        self.__items = ItemsRequester()
        self.__waitForSync = False
        self.onSyncStarted = Event()
        self.onSyncCompleted = Event()

    def init(self):
        g_playerEvents.onInventoryResync += self._onResync
        g_playerEvents.onDossiersResync += self._onResync
        g_playerEvents.onStatsResync += self._onResync
        g_playerEvents.onCenterIsLongDisconnected += self._onCenterIsLongDisconnected

    def fini(self):
        self.onSyncStarted.clear()
        self.onSyncCompleted.clear()
        g_playerEvents.onCenterIsLongDisconnected -= self._onCenterIsLongDisconnected
        g_playerEvents.onStatsResync -= self._onResync
        g_playerEvents.onDossiersResync -= self._onResync
        g_playerEvents.onInventoryResync -= self._onResync

    @property
    def waitForSync(self):
        return self.__waitForSync

    @property
    def items(self):
        return self.__items

    @async
    def update(self, diff = None, callback = None):
        self.__invalidateData(diff, callback)

    def clear(self):
        return self.items.clear()

    def _onResync(self, *args):
        if not self.__waitForSync:
            self.__invalidateData()

    def _onCenterIsLongDisconnected(self, isLongDisconnected):
        self.items.dossiers.onCenterIsLongDisconnected(isLongDisconnected)

    def __invalidateData(self, diff = None, callback = lambda *args: None):

        def cbWrapper(*args):
            self.__waitForSync = False
            self.onSyncCompleted()
            callback(*args)

        self.__waitForSync = True
        self.onSyncStarted()
        self.__items.invalidateCache(diff)
        self.__items.request()(cbWrapper)

    def isSynced(self):
        return self.items.isSynced()
Ejemplo n.º 26
0
	def invokeHandler(self, handler, query):
		if self.log:
			filename = handler['fn'].func_code.co_filename
			if filename.startswith(basePath()):
				filename = filename[len(basePath())+1:]
			self.log = LogEntry('rorn.handle', "%s %s" % (self.method.upper(), self.path), userid = self.session['user'].id if self.session['user'] else None, ip = self.client_address[0], location = "%s(%s:%d)" % (handler['fn'].func_code.co_name, filename, handler['fn'].func_code.co_firstlineno))
			Event.pageHandle(self, handler['fn'])

		return super(HTTPHandler, self).invokeHandler(handler, query)
Ejemplo n.º 27
0
 def __init__(self, *args, **kwargs):
     list.__init__(self, *args, **kwargs)
     
     # addEvent(pos, item)
     self._addEvent = Event()
     # removeEvent(pos, item)
     self._removeEvent = Event()
     # setitemEvent(pos, item)
     self._setitemEvent = Event()
Ejemplo n.º 28
0
 def __init__(self):
     self.__waitForSync = False
     self.__fortProvider = None
     self.__clanMembersLen = None
     self.__clanMotto = ''
     self.__clanDescription = ''
     self.onSyncStarted = Event()
     self.onSyncCompleted = Event()
     return
Ejemplo n.º 29
0
	def test__addSegment__inner_inter_before(self):
		e = Event(0.5, 0.5)
		s1 = ComparableSegment(0, 0.5, 1, 0.5)
		s2 = ComparableSegment(0, 1, 1, 0)
		e.addSegment(s1)
		e.addSegment(s2)
		self.assertEqual(e.inner_inter, [s2, s1])
		self.assertEqual((e.left, e.right, e.low, e.high), 
						 ([], [], [], []))
Ejemplo n.º 30
0
	def test__addSegment__left_after(self):
		e = Event(0, 0)
		s1 = ComparableSegment(0, 0, 1, 1)
		s2 = ComparableSegment(0, 0, 1, 2)
		e.addSegment(s1)
		e.addSegment(s2)
		self.assertEqual(e.left, [s1, s2])
		self.assertEqual((e.right, e.inner_inter, e.low, e.high), 
						 ([], [], [], []))