def net_cmd_mc(self, args): """ Play music. MC#<song_name:int>#<???:int>#% """ try: area = self.server.area_manager.get_area_by_name(args[0]) self.client.change_area(area) except AreaError: if self.client.is_muted: # Checks to see if the client has been muted by a mod self.client.send_host_message("You have been muted by a moderator") return if not self.client.is_dj: self.client.send_host_message('You were blockdj\'d by a moderator.') return if not self.validate_net_cmd(args, self.ArgType.STR, self.ArgType.INT): return if args[1] != self.client.char_id: return if self.client.change_music_cd(): self.client.send_host_message('You changed song too much times. Please try again after {} seconds.'.format(int(self.client.change_music_cd()))) return try: name, length = self.server.get_song_data(args[0]) self.client.area.play_music(name, self.client.char_id, length) self.client.area.add_music_playing(self.client, name) logger.log_server('[{}][{}]Changed music to {}.' .format(self.client.area.id, self.client.get_char_name(), name), self.client) except ServerError: return except ClientError as ex: self.client.send_host_message(ex)
def net_cmd_hp(self, args): """ Sets the penalty bar. HP#<type:int>#<new_value:int>#% """ if self.client.is_muted: # Checks to see if the client has been muted by a mod self.client.send_host_message("You have been muted by a moderator") return if self.client.area.cannot_ic_interact(self.client): self.client.send_host_message( "You are not on the area's invite list, and thus, you cannot change the Confidence bars!" ) return if not self.validate_net_cmd(args, self.ArgType.INT, self.ArgType.INT): return try: self.client.area.change_hp(args[0], args[1]) self.client.area.add_to_judgelog(self.client, 'changed the penalties') logger.log_server( '[{}]{} changed HP ({}) to {}'.format( self.client.area.abbreviation, self.client.get_char_name(), args[0], args[1]), self.client) except AreaError: return
def ooc_cmd_cleardoc(client, arg): if len(arg) != 0: raise ArgumentError('This command has no arguments.') client.send_host_message('Document cleared.') logger.log_server('[{}][{}]Cleared document. Old link: {}'.format( client.area.id, client.get_char_name(), client.area.doc)) client.area.change_doc()
def net_cmd_rt(self, args: List[str]): """ Plays the Testimony/CE animation. RT#<type:string>#% """ pargs = self.process_arguments('RT', args) if self.client.is_muted: # Checks to see if the client has been muted by a mod self.client.send_ooc('You have been muted by a moderator.') return if not self.client.is_staff() and self.client.area.lobby_area: self.client.send_ooc('Judge buttons are disabled in this area.') return self.client.publish_inbound_command('RT', pargs) name = pargs['name'] for client in self.client.area.clients: client.send_splash(name=name) self.client.area.add_to_judgelog(self.client, 'used judge button {}.'.format(name)) logger.log_server('[{}]{} used judge button {}.' .format(self.client.area.id, self.client.get_char_name(), name), self.client) self.client.last_active = Constants.get_time()
def net_cmd_zz(self, args: List[str]): """ Sent on mod call. """ pargs = self.process_arguments('ZZ', args) if self.client.is_muted: # Checks to see if the client has been muted by a mod self.client.send_ooc('You have been muted by a moderator.') return if not self.client.can_call_mod(): self.client.send_ooc('You must wait 30 seconds between mod calls.') return self.client.publish_inbound_command('ZZ', pargs) self.client.send_ooc('You have called for a moderator.') current_time = strftime("%H:%M", localtime()) message = ('[{}] {} ({}) called for a moderator in {} ({}).' .format(current_time, self.client.get_char_name(), self.client.get_ip(), self.client.area.name, self.client.area.id)) for c in self.server.get_clients(): if c.is_officer(): c.send_command_dict('ZZ', { 'message': message }) self.client.set_mod_call_delay() logger.log_server('[{}][{}]{} called a moderator.' .format(self.client.get_ip(), self.client.area.id, self.client.get_char_name()))
def net_cmd_hp(self, args: List[str]): """ Sets the penalty bar. HP#<type:int>#<new_value:int>#% """ pargs = self.process_arguments('HP', args) if self.client.is_muted: # Checks to see if the client has been muted by a mod self.client.send_ooc("You have been muted by a moderator") return self.client.publish_inbound_command('HP', pargs) try: side, health = pargs['side'], pargs['health'] self.client.area.change_hp(side, health) info = 'changed penalty bar {} to {}.'.format(side, health) self.client.area.add_to_judgelog(self.client, info) logger.log_server('[{}]{} changed HP ({}) to {}' .format(self.client.area.id, self.client.get_char_name(), side, health), self.client) except AreaError: pass self.client.last_active = Constants.get_time()
def notify_me(self, area, old_dname, ignore_bleeding=False): client = self.client # Code here assumes successful area change, so it will be sending client notifications old_area = client.area ########### # Check if exiting a zone if old_area.in_zone and area.in_zone != old_area.in_zone: zone_id = old_area.in_zone.get_id() if client.is_staff() and client.zone_watched == old_area.in_zone: client.send_ooc( '(X) You have left zone `{}`. To stop receiving its notifications, ' 'stop watching it with /zone_unwatch'.format(zone_id)) else: client.send_ooc('You have left zone `{}`.'.format(zone_id)) # Check if entering a zone if area.in_zone and area.in_zone != old_area.in_zone: zone_id = area.in_zone.get_id() if client.is_staff() and client.zone_watched != area.in_zone: client.send_ooc( '(X) You have entered zone `{}`. To be able to receive its ' 'notifications, start watching it with /zone_watch {}'. format(zone_id, zone_id)) else: client.send_ooc('You have entered zone `{}`.'.format(zone_id)) # Check if someone in the new area has the same showname try: # Verify that showname is still valid client.change_showname(client.showname, target_area=area) except ValueError: client.send_ooc( 'Your showname `{}` was already used in this area, so it has been ' 'removed.'.format(client.showname)) client.send_ooc_others( '(X) Client {} had their showname `{}` removed in your zone ' 'due to it conflicting with the showname of another player in ' 'the same area ({}).'.format(client.id, client.showname, area.id), is_zstaff=area) client.change_showname('', target_area=area) logger.log_server( '{} had their showname removed due it being used in the new area.' .format(client.ipid), client) ########### # Check if the lights were turned off, and if so, let you know, if you are not blind if not area.lights: client.send_ooc('You enter a pitch dark room.', to_blind=False) if not ignore_bleeding and client.is_bleeding: # As these are sets, repetitions are automatically filtered out old_area.bleeds_to.add(area.name) area.bleeds_to.add(old_area.name) client.send_ooc('You are bleeding.') ########### # Check bleeding status self.notify_me_blood(area)
def ooc_cmd_ban(client, arg): if not client.is_mod: raise ClientError('You must be authorized to do that.') try: ipid = int(arg.strip()) if len(str(ipid)) != 10: raise ClientError( 'Argument must be an IP address or 10-digit number.') integer = True except ValueError: ipid = arg.strip() integer = False try: client.server.ban_manager.add_ban(ipid) except ServerError: raise if ipid is not None: if integer: targets = client.server.client_manager.get_targets( client, TargetType.IPID, ipid, False) else: targets = client.server.client_manager.get_targets( client, TargetType.IP, ipid, False) if targets: for c in targets: c.disconnect() client.send_host_message('{} clients were kicked.'.format( len(targets))) client.area.send_host_message('{} was banned.'.format(c.get_char_name)) logger.log_server('Banned {}.'.format(ipid), client)
def net_cmd_hi(self, args): """ Handshake. HI#<hdid:string>#% :param args: a list containing all the arguments """ if not self.validate_net_cmd(args, self.ArgType.STR, needs_auth=False): return self.client.hdid = args[0] if self.client.hdid not in self.client.server.hdid_list: self.client.server.hdid_list[self.client.hdid] = [] if self.client.ipid not in self.client.server.hdid_list[ self.client.hdid]: self.client.server.hdid_list[self.client.hdid].append( self.client.ipid) self.client.server.dump_hdids() for ipid in self.client.server.hdid_list[self.client.hdid]: if self.server.ban_manager.is_banned(ipid): self.client.send_command('BD') self.client.disconnect() return logger.log_server('Connected. HDID: {}.'.format(self.client.hdid), self.client) self.client.send_command('ID', self.client.id, self.server.software, self.server.get_version_string()) self.client.send_command('PN', self.server.get_player_count() - 1, self.server.config['playerlimit'])
def ooc_cmd_roll(client, arg): roll_max = 11037 if len(arg) != 0: try: val = list(map(int, arg.split(' '))) if not 1 <= val[0] <= roll_max: raise ArgumentError( 'Roll value must be between 1 and {}.'.format(roll_max)) except ValueError: raise ArgumentError( 'Wrong argument. Use /roll [<max>] [<num of rolls>]') else: val = [6] if len(val) == 1: val.append(1) if len(val) > 2: raise ArgumentError( 'Too much arguments. Use /roll [<max>] [<num of rolls>]') if val[1] > 20 or val[1] < 1: raise ArgumentError('Num of rolls must be between 1 and 20') roll = '' for i in range(val[1]): roll += str(random.randint(1, val[0])) + ', ' roll = roll[:-2] if val[1] > 1: roll = '(' + roll + ')' client.area.send_host_message('{} rolled {} out of {}.'.format( client.get_char_name(), roll, val[0])) logger.log_server('[{}][{}]Used /roll and got {} out of {}.'.format( client.area.id, client.get_char_name(), roll, val[0]))
def net_cmd_zz(self, _): """ Sent on mod call. """ if self.client.is_muted: # Checks to see if the client has been muted by a mod self.client.send_host_message("You have been muted by a moderator") return if not self.client.can_call_mod(): self.client.send_host_message( "You must wait 30 seconds between mod calls.") return current_time = strftime("%H:%M", localtime()) self.server.send_all_cmd_pred('ZZ', '[{}] {} ({}) in {} ({})'.format( current_time, self.client.get_char_name(), self.client.get_ip(), self.client.area.name, self.client.area.id), pred=lambda c: c.is_mod) self.client.set_mod_call_delay() logger.log_server('[{}][{}]{} called a moderator.'.format( self.client.get_ip(), self.client.area.id, self.client.get_char_name()))
def change_area(self, area): if self.area == area: raise ClientError('You are already in this area.') if area.is_locked and not self.is_mod and not self.ipid in self.area.invite_list: self.send_host_message("That area is locked!") return old_area = self.area if not area.is_char_available(self.char_id): try: new_char_id = area.get_rand_avail_char_id() except AreaError: raise ClientError('No available characters in that area.') self.change_character(new_char_id) self.send_host_message('Character taken, switched to {}.'.format(self.get_char_name())) self.area.remove_client(self) self.area = area area.new_client(self) self.send_host_message('Changed area to {}.[{}]'.format(area.name, self.area.status)) logger.log_server( '[{}]Changed area from {} ({}) to {} ({}).'.format(self.get_char_name(), old_area.name, old_area.id, self.area.name, self.area.id), self) self.send_command('HP', 1, self.area.hp_def) self.send_command('HP', 2, self.area.hp_pro) self.send_command('BN', self.area.background) self.send_command('LE', *self.area.get_evidence_list(self))
async def _abnormal_shutdown(exception, server=None): # Print complete traceback to console etype, evalue, etraceback = (type(exception), exception, exception.__traceback__) info = 'TSUSERVERDR HAS ENCOUNTERED A FATAL PYTHON ERROR.' info += "\r\n" + "".join( traceback.format_exception(etype, evalue, etraceback)) logger.log_print(info) logger.log_error(info, server=server, errortype='P') logger.log_server('Server is shutting down due to an unhandled exception.') logger.log_print('Attempting a graceful shutdown.') if not server: logger.log_pserver('Server has successfully shut down.') return try: await server.normal_shutdown() except Exception as exception2: logger.log_print('Unable to gracefully shut down: Forcing a shutdown.') etype, evalue, etraceback = (type(exception2), exception2, exception2.__traceback__) info = "\r\n" + "".join( traceback.format_exception(etype, evalue, etraceback)) logger.log_print(info) logger.log_error(info, server=server, errortype='P')
def change_area(self, area): if self.area == area: raise ClientError('You are already in this area.') old_area = self.area if not area.is_char_available(self.char_id): try: new_char_id = area.get_rand_avail_char_id() except AreaError: raise ClientError('No available characters in that area.') self.area.remove_client(self) self.area = area area.new_client(self) self.change_character(new_char_id) self.send_host_message( 'Character taken, switched to {}.'.format( self.get_char_name())) else: self.area.remove_client(self) self.area = area area.new_client(self) self.send_host_message('Changed area to {}.'.format(area.name)) logger.log_server( '[{}]Changed area from {} ({}) to {} ({}).'.format( self.get_char_name(), old_area.name, old_area.id, self.area.name, self.area.id), self) self.send_command('HP', 1, self.area.hp_def) self.send_command('HP', 2, self.area.hp_pro) self.send_command('BN', self.area.background)
def __add_post(self, post_type, boardname, topic_id, title, content, attach): ''' Helper for adding post ''' if attach: attach = StringIO.StringIO(attach) if post_type == 'reply': r = requests.post(add_post_site, cookies=self.cookie, data={'type': post_type, 'boardname': boardname, 'articleid': topic_id, 'title': title, 'content': content}, files=({'attach': attach} if attach else None)) elif post_type == 'new': r = requests.post(add_post_site, cookies=self.cookie, data={'type': post_type, 'boardname': boardname, 'title': title, 'content': content}, files=({'attach': attach} if attach else None)) elif post_type == 'update': r = requests.post(add_post_site, cookies=self.cookie, data={'type': post_type, 'boardname': boardname, 'articleid': topic_id, 'title': title, 'content': content}, files=({'attach': attach} if attach else None)) else: raise ValueError('Invalid post_type %s' % post_type) log_server('add_post %s: %s' % (post_type, r.text)) # FIXME: Send a post with attachment will response 502 error # Don't know why. ISSUE #10 resp = r.json() if resp['success']: return {'id': resp['data']} return resp['code']
def net_cmd_ms(self, args): """ IC message. Refer to the implementation for details. """ if self.client.is_muted: # Checks to see if the client has been muted by a mod self.client.send_host_message("You have been muted by a moderator") return if not self.client.area.can_send_message(): return if not self.validate_net_cmd( args, self.ArgType.STR, self.ArgType.STR_OR_EMPTY, self.ArgType.STR, self.ArgType.STR, self.ArgType.STR, self.ArgType.STR, self.ArgType.STR, self.ArgType.INT, self.ArgType.INT, self.ArgType.INT, self.ArgType.INT, self.ArgType.INT, self.ArgType.INT, self.ArgType.INT, self.ArgType.INT): return msg_type, pre, folder, anim, text, pos, sfx, anim_type, cid, sfx_delay, button, unk, flip, ding, color = args if msg_type not in ('chat', '0', '1'): return if anim_type not in (0, 1, 2, 5, 6): return if cid != self.client.char_id: return if sfx_delay < 0: return if button not in (0, 1, 2, 3, 4): return if ding not in (0, 1): return if color not in (0, 1, 2, 3, 4, 5, 6): return if color == 2 and not self.client.is_mod: color = 0 if color == 6: text = re.sub(r'[^\x00-\x7F]+', ' ', text) #remove all unicode to prevent redtext abuse if len(text.strip(' ')) == 1: color = 0 else: if text.strip(' ') in ('<num>', '<percent>', '<dollar>', '<and>'): color = 0 if self.client.pos: pos = self.client.pos else: if pos not in ('def', 'pro', 'hld', 'hlp', 'jud', 'wit'): return msg = text[:256] self.client.area.send_command('MS', msg_type, pre, folder, anim, msg, pos, sfx, anim_type, cid, sfx_delay, button, unk, flip, ding, color) self.client.area.set_next_msg_delay(len(msg)) logger.log_server( '[IC][{}][{}]{}'.format(self.client.area.id, self.client.get_char_name(), msg), self.client)
def follow_area(self, area): self.send_host_message('Followed user moved area at {}'.format( time.asctime(time.localtime(time.time())))) if self.area == area: self.send_host_message( 'Unable to follow to {}: Already in target area.'.format( area.name)) return if area.is_locked and not self.is_mod and not self.is_gm and not ( self.ipid in area.invite_list): self.send_host_message( 'Unable to follow to {}: Area is locked.'.format( area.name)) return if area.is_gmlocked and not self.is_mod and not self.is_gm and not ( self.ipid in area.invite_list): self.send_host_message( 'Unable to follow to {}: Area is GM-locked.'.format( area.name)) return if area.is_modlocked and not self.is_mod and not ( self.ipid in area.invite_list): self.send_host_message( 'Unable to follow to {}: Area is Mod-Locked.'.format( area.name)) return old_area = self.area if not area.is_char_available(self.char_id): try: new_char_id = area.get_rand_avail_char_id() except AreaError: self.send_host_message( 'Unable to follow to {}: No available characters.'. format(area.name)) return self.change_character(new_char_id) self.send_host_message( 'Character taken, switched to {}.'.format( self.get_char_name())) self.area.remove_client(self) self.area = area area.new_client(self) self.send_host_message('Changed area to {}.[{}]'.format( area.name, self.area.status)) logger.log_server( '[{}]Changed area from {} ({}) to {} ({}).'.format( self.get_char_name(), old_area.name, old_area.id, self.area.name, self.area.id), self) #logger.log_rp( # '[{}]Changed area from {} ({}) to {} ({}).'.format(self.get_char_name(), old_area.name, old_area.id, # self.area.name, self.area.id), self) self.send_command('HP', 1, self.area.hp_def) self.send_command('HP', 2, self.area.hp_pro) self.send_command('BN', self.area.background) self.send_command('LE', *self.area.get_evidence_list(self))
def ooc_cmd_unban(client, arg): if not client.is_mod: raise ClientError('You must be authorized to do that.') try: client.server.ban_manager.remove_ban(int(arg.strip())) except: raise ClientError('You must specify \'hdid\'') logger.log_server('Unbanned {}.'.format(arg), client) client.send_host_message('Unbanned {}'.format(arg))
def ooc_cmd_need(client, arg): if client.muted_adverts: raise ClientError('You have advertisements muted.') if len(arg) == 0: raise ArgumentError("You must specify what you need.") client.server.broadcast_need(client, arg) logger.log_server( '[{}][{}][NEED]{}.'.format(client.area.id, client.get_char_name(), arg), client)
def ooc_cmd_coinflip(client, arg): if len(arg) != 0: raise ArgumentError('This command has no arguments.') coin = ['heads', 'tails'] flip = random.choice(coin) client.area.send_host_message('{} flipped a coin and got {}.'.format( client.get_char_name(), flip)) logger.log_server('[{}][{}]Used /coinflip and got {}.'.format( client.area.id, client.get_char_name(), flip))
def ooc_cmd_g(client, arg): if client.muted_global: raise ClientError('Global chat toggled off.') if len(arg) == 0: raise ArgumentError("You can't send an empty message.") client.server.broadcast_global(client, arg) logger.log_server( '[{}][{}][GLOBAL]{}.'.format(client.area.id, client.get_char_name(), arg), client)
def set_cookie(self): """ set the cookie value for processor before request """ if not is_in_exclude_url(): cookie = get_cookie_from_authorization() log_server(api_addr=request.url, msg="in set_cookie, cookie: %s" % str(cookie)) if cookie and hasattr(self.__processor__, 'set_cookie'): self.cookie = cookie self.__processor__.set_cookie(cookie)
def get_user_avatar(self, username): """ get user avatar """ ret = self.__processor__.get_user_avatar(username) log_server(api_addr="get_user_avatar", msg="username is %s, avatar is None[%s]" % (username, ret is None)) if ret: return make_response(ret) else: return make_response(fill_fail_format(err_code=get_user_avatar_fail))
def ooc_cmd_login(client, arg): if len(arg) == 0: raise ArgumentError('You must specify the password.') try: client.auth_mod(arg) except ClientError: raise client.send_host_message('Logged in as a moderator.') logger.log_server('Logged in as moderator.', client) client.in_rp = False
def ooc_cmd_ToD(client, arg): if len(arg) != 0: raise ArgumentError('This command has no arguments.') coin = ['truth', 'dare'] flip = random.choice(coin) client.area.send_host_message('{} has to do a {}.'.format( client.get_char_name(), flip)) logger.log_server('[{}][{}]has to do a {}.'.format(client.area.id, client.get_char_name(), flip))
def ooc_cmd_8ball(client, arg): if len(arg) != 0: raise ArgumentError('This command has no arguments.') coin = [ 'yes', 'no', 'maybe', 'I dont know', 'perhaps', 'Please do not', 'try again', 'you shouldn\'t ask that' ] flip = random.choice(coin) client.area.send_host_message('The magic 8 ball says {}.'.format(flip)) logger.log_server('The magic 8 ball said {}.'.format(flip))
def get_newest_topics(self, offset): """ get newest topics """ log_server(api_addr='get_newest_topics', msg='in get newest topics, offset=%s' % offset) ret = self.__processor__.get_new_topic(offset) log_request(api_addr='get_newest_topics', response=ret) if is_process_success(ret): return make_response(fill_success_format(ret)) else: return make_response(fill_fail_format(err_code=unknown_error))
def ooc_cmd_doc(client, arg): if len(arg) == 0: client.send_host_message('Document: {}'.format(client.area.doc)) logger.log_server('[{}][{}]Requested document. Link: {}'.format( client.area.id, client.get_char_name(), client.area.doc)) else: client.area.change_doc(arg) client.area.send_host_message('{} changed the doc link.'.format( client.get_char_name())) logger.log_server('[{}][{}]Changed document to: {}'.format( client.area.id, client.get_char_name(), arg))
def ooc_cmd_lm(client, arg): if not client.is_mod: raise ClientError('You must be authorized to do that.') if len(arg) == 0: raise ArgumentError("Can't send an empty message.") client.area.send_command( 'CT', '{}[MOD][{}]'.format(client.server.config['hostname'], client.get_char_name()), arg) logger.log_server( '[{}][{}][LOCAL-MOD]{}.'.format(client.area.id, client.get_char_name(), arg), client)
def ooc_cmd_ghm(client, arg): if not client.is_mod: raise ClientError('You must be authorized to do that.') if client.muted_global: raise ClientError('You have the global chat muted.') if len(arg) == 0: raise ArgumentError("Can't send an empty message.") client.server.broadcast_globalmod(client, arg, True) logger.log_server( '[{}][{}][GLOBAL-MOD]{}.'.format(client.area.id, client.get_char_name(), arg), client)
def ooc_cmd_gooc(client, arg): if not client.is_mod and not client.is_gm and not client.is_cm: raise ClientError('You must be authorized to do that.') if client.muted_global: raise ClientError('Global chat toggled off.') if len(arg) == 0: raise ArgumentError("You can't send an empty message.") client.server.broadcast_globalooc(client, arg) logger.log_server( '[{}][{}][GLOBAL]{}.'.format(client.area.id, client.get_char_name(), arg), client)
def ooc_cmd_logincm(client, arg): if len(arg) == 0: raise ArgumentError('You must specify the password.') try: client.auth_cm(arg) except ClientError: raise if client.area.evidence_mod == 'HiddenCM': client.area.broadcast_evidence_list() client.send_host_message('Logged in as a community manager.') logger.log_server('Logged in as community manager.', client)
def ooc_cmd_play(client, arg): if not client.is_mod and not client.is_gm and not client.is_cm: raise ClientError('You must be authorized to do that.') if len(arg) == 0: raise ArgumentError('You must specify a song.') client.area.play_music(arg, client.char_id, -1) client.area.add_music_playing(client, arg) logger.log_server( '[{}][{}]Changed music to {}.'.format(client.area.id, client.get_char_name(), arg), client)
def change_character(self, char_id, force=False): if not self.server.is_valid_char_id(char_id): raise ClientError('Invalid Character ID.') if not force and not self.area.is_char_available(char_id): raise ClientError('Character not available.') old_char = self.get_char_name() self.char_id = char_id self.send_command('PV', self.id, 'CID', self.char_id) logger.log_server( '[{}]Changed character from {} to {}.'.format( self.area.id, old_char, self.get_char_name()), self)
def update_user_avatar(self): """ update user avatar post data: the new avatar binary data """ log_server(api_addr="update_user_avatar", msg="cookie: %s" % str(self.cookie)) data = request.data ret = self.__processor__.update_user_avatar(data) log_request(api_addr="update_user_avatar", response=ret) if is_process_success(ret): return make_response(fill_success_format()) else: return make_response(fill_fail_format(err_code=ret))
def logout(self): """ logout user methods: GET url: '/logout/' post data format (in Authorization header): { "access_token": "..." "nounce": "nounce" } and encrypt with server's public key """ # get the cookie and access_token access_token = self.get_logout_info_from_authorization() log_server(api_addr="logout", msg="logout, cookie: %s" % self.cookie) if self.cookie: try: logout_ret = self.__processor__.logout() if logout_ret is True: del_access_token(access_token) log_server(api_addr="logout", msg="logout success, del access_token: %s" % access_token) return make_response(fill_success_format()) else: log_server(api_addr="logout", msg="logout fail, err_code: %s" % logout_ret) return make_response(fill_fail_format(err_code=logout_ret)) except KeyError, e: del_access_token(access_token) log_server(api_addr="logout", msg="logout throw exception: %s, del access_token: %s" % (str(e), access_token)) return make_response(fill_success_format())
access_token = self.get_logout_info_from_authorization() log_server(api_addr="logout", msg="logout, cookie: %s" % self.cookie) if self.cookie: try: logout_ret = self.__processor__.logout() if logout_ret is True: del_access_token(access_token) log_server(api_addr="logout", msg="logout success, del access_token: %s" % access_token) return make_response(fill_success_format()) else: log_server(api_addr="logout", msg="logout fail, err_code: %s" % logout_ret) return make_response(fill_fail_format(err_code=logout_ret)) except KeyError, e: del_access_token(access_token) log_server(api_addr="logout", msg="logout throw exception: %s, del access_token: %s" % (str(e), access_token)) return make_response(fill_success_format()) else: del_access_token(access_token) log_server(api_addr="logout", msg="logout success, del access_token: %s" % access_token) return make_response(fill_success_format()) def get_logout_info_from_authorization(self): user_info = decrypt_client_data(request.headers.get('Authorization', None)) user_info = json.loads(user_info) access_token = user_info.get('access_token') #cookie = get_cookie_from_access_token(access_token) return access_token
def request_access_token(self): """ request access token, and the server login this user methods: GET url: '/request_access_token/' post data format (in Authorization header): { "username": username, "password": password, "login_token": "", "nounce": "..." } and encrypt with server's public key """ client_data = decrypt_client_data(request.headers.get('Authorization', None)) # check the data if valid if not client_data: return make_response(fill_fail_format(err_code=request_data_format_error)) client_data = json.loads(client_data) if not ('username' in client_data and 'password' in client_data and 'login_token' in client_data and 'nounce' in client_data): log_server(api_addr="request_access_token", msg="client data not provide enough info") return make_response(fill_fail_format(err_code=request_data_format_error)) # first check the login_token if still exist now login_token = client_data['login_token'] login_token_value = get_login_token_value(login_token) if not login_token_value: return fail_login_token_expired() login_token_value = json.loads(login_token_value) del_login_token(login_token) # login user username = client_data['username'] password = client_data['password'] ret = self.__processor__.login(username, password) cookie = None if type(ret) is dict: cookie = ret.get('cookie') log_server(api_addr="request_access_token", msg="user: %s login success" % username) else: # login fail log_server(api_addr="request_access_token", msg="user: %s login fail, err_code: %s" % (username, ret)) return make_response(fill_fail_format(err_code=ret)) nounce = client_data['nounce'] # get the client public key client_publickey = login_token_value.get('client_publickey') # generate a new access_token access_token = gen_access_token() # store the new access_token expireat = int(time.time()) + 2592000 store_access_token(access_token, {'client_publickey': client_publickey, 'username': username, 'nounce': nounce, 'cookie': cookie, 'expire': expireat}, expireat=expireat) ret_val = json.dumps(dict(access_token=access_token, expire=expireat)) log_request(api_addr="request_access_token", response=ret_val, request=client_data) # encrypt ret_val with client_publickey ret_val = encrypt_data_by_client_publickey(ret_val, client_publickey) response = make_response(fill_success_format()) response.headers['Authorization'] = ret_val return response