<s> import datetime <EOL> import six <EOL> import string <EOL> from girder . constants import AccessType , TerminalColor , TokenScope <EOL> from . model_base import AccessControlledModel <EOL> try : <EOL> from random import SystemRandom <EOL> random = SystemRandom ( ) <EOL> random . random ( ) <EOL> except NotImplementedError : <EOL> print ( TerminalColor . warning ( <EOL> '<STR_LIT>' ) ) <EOL> import random <EOL> def genToken ( length = <NUM_LIT:64> ) : <EOL> """<STR_LIT>""" <EOL> return '<STR_LIT>' . join ( random . choice ( string . ascii_letters + string . digits ) <EOL> for x in range ( length ) ) <EOL> class Token ( AccessControlledModel ) : <EOL> """<STR_LIT>""" <EOL> def initialize ( self ) : <EOL> self . name = '<STR_LIT>' <EOL> self . ensureIndex ( ( '<STR_LIT>' , { '<STR_LIT>' : <NUM_LIT:0> } ) ) <EOL> def validate ( self , doc ) : <EOL> return doc <EOL> def createToken ( self , user = None , days = <NUM_LIT> , scope = None ) : <EOL> """<STR_LIT>""" <EOL> now = datetime . datetime . utcnow ( ) <EOL> if scope is None : <EOL> scope = ( TokenScope . USER_AUTH , ) <EOL> elif isinstance ( scope , six . string_types ) : <EOL> scope = ( scope , ) <EOL> token = { <EOL> '<STR_LIT>' : genToken ( ) , <EOL> '<STR_LIT>' : now , <EOL> '<STR_LIT>' : now + datetime . timedelta ( days = days ) , <EOL> '<STR_LIT>' : list ( set ( scope ) ) <EOL> } <EOL> if user is None : <EOL> self . setPublic ( token , True , save = False ) <EOL> else : <EOL> token [ '<STR_LIT>' ] = user [ '<STR_LIT>' ] <EOL> self . setUserAccess ( token , user = user , level = AccessType . ADMIN , <EOL> save = False ) <EOL> return self . save ( token ) <EOL> def addScope ( self , token , scope ) : <EOL> """<STR_LIT>""" <EOL> if '<STR_LIT>' not in token : <EOL> token [ '<STR_LIT>' ] = [ ] <EOL> if scope not in token [ '<STR_LIT>' ] : <EOL> token [ '<STR_LIT>' ] . append ( scope ) <EOL> token = self . save ( token ) <EOL> return token <EOL> def getAllowedScopes ( self , token ) : <EOL> """<STR_LIT>""" <EOL> return token . get ( '<STR_LIT>' , ( TokenScope . USER_AUTH , ) ) <EOL> def hasScope ( self , token , scope ) : <EOL> """<STR_LIT>""" <EOL> if token is None : <EOL> return False <EOL> if scope is None : <EOL> return True <EOL> if isinstance ( scope , six . string_types ) : <EOL> scope = ( scope , ) <EOL> return set ( scope ) . issubset ( set ( self . getAllowedScopes ( token ) ) ) </s>
