<s> from datetime import datetime <EOL> import hashlib <EOL> import hmac <EOL> import os <EOL> from grouper . models . base . model_base import Model <EOL> from sqlalchemy import Column , Integer , String , UniqueConstraint , ForeignKey , DateTime <EOL> from sqlalchemy . orm import relationship <EOL> def _make_secret ( ) : <EOL> return os . urandom ( <NUM_LIT:20> ) . encode ( "<STR_LIT>" ) <EOL> class UserToken ( Model ) : <EOL> """<STR_LIT>""" <EOL> __tablename__ = "<STR_LIT>" <EOL> id = Column ( Integer , primary_key = True ) <EOL> user_id = Column ( Integer , ForeignKey ( "<STR_LIT>" ) ) <EOL> name = Column ( String ( length = <NUM_LIT:16> ) , nullable = False ) <EOL> created_at = Column ( DateTime , default = datetime . utcnow , nullable = False ) <EOL> disabled_at = Column ( DateTime , default = None , nullable = True ) <EOL> hashed_secret = Column ( String ( length = <NUM_LIT:64> ) , unique = True , nullable = False ) <EOL> user = relationship ( "<STR_LIT>" , back_populates = "<STR_LIT>" ) <EOL> __table_args__ = ( <EOL> UniqueConstraint ( "<STR_LIT>" , "<STR_LIT:name>" ) , <EOL> ) <EOL> @ staticmethod <EOL> def get ( session , user , name = None , id = None ) : <EOL> """<STR_LIT>""" <EOL> assert name is None or id is None <EOL> if name is not None : <EOL> return session . query ( UserToken ) . filter_by ( name = name , user = user ) . scalar ( ) <EOL> return session . query ( UserToken ) . filter_by ( id = id , user = user ) . scalar ( ) <EOL> def _set_secret ( self ) : <EOL> secret = _make_secret ( ) <EOL> self . hashed_secret = hashlib . sha256 ( secret ) . hexdigest ( ) <EOL> return secret <EOL> def check_secret ( self , secret ) : <EOL> return self . enabled and hmac . compare_digest ( <EOL> hashlib . sha256 ( secret ) . hexdigest ( ) , <EOL> self . hashed_secret . encode ( '<STR_LIT:utf-8>' ) , <EOL> ) <EOL> @ property <EOL> def enabled ( self ) : <EOL> return self . disabled_at is None and self . user . enabled <EOL> def __str__ ( self ) : <EOL> return "<STR_LIT:/>" . join ( ( <EOL> self . user . username if self . user is not None else "<STR_LIT>" , <EOL> self . name if self . name is not None else "<STR_LIT>" , <EOL> ) ) </s>
