
    )JfA                         d Z ddlZddlZddlmZ ddlmZ ddlmZ d Z	 G d de          Z
 G d	 d
e
          Z G d de
          Z G d de
          ZdS )a.  
This module contains C{L{OpenIDStore}} implementations that use
various SQL databases to back them.

Example of how to initialize a store database::

python -c 'from openid.store import sqlstore; import pysqlite2.dbapi2;'
  'sqlstore.SQLiteStore(pysqlite2.dbapi2.connect("cstore.db")).createTables()'
    N)Association)OpenIDStore)noncec                       fd}t           d          r&	  j        dd          |_        n# t          $ r Y nw xY wt           d          r j        |_        |S )Nc                 (     | j         | g|R i |S N)_callInTransaction)selfargskwargsfuncs      X/home/alex/cs2snipeproduction/venv/lib/python3.11/site-packages/openid/store/sqlstore.pywrappedz_inTxn.<locals>.wrapped   s(    &t&tTCDCCCFCCC    __name__   __doc__)hasattrr   	TypeErrorr   )r   r   s   ` r   _inTxnr      s    D D D D D tZ   	#}QRR0G 	 	 	D	 tY ',Ns   - 
::c                      e Zd ZdZdZdZddZd Zd Zd Z	d	 Z
d
 Zd Zd Z ee          Zd Z ee          ZddZ ee          Zd Z ee          Zd Z ee          Zd Z ee          Zd Z ee          ZdS )SQLStorea  
    This is the parent class for the SQL stores, which contains the
    logic common to all of the SQL stores.

    The table names used are determined by the class variables
    C{L{associations_table}} and
    C{L{nonces_table}}.  To change the name of the tables used, pass
    new table names into the constructor.

    To create the tables with the proper schema, see the
    C{L{createTables}} method.

    This class shouldn't be used directly.  Use one of its subclasses
    instead, as those contain the code necessary to use a specific
    database.

    All methods other than C{L{__init__}} and C{L{createTables}}
    should be considered implementation details.


    @cvar associations_table: This is the default name of the table to
        keep associations in

    @cvar nonces_table: This is the default name of the table to keep
        nonces in.


    @sort: __init__, createTables
    oid_associations
oid_noncesNc                 L   || _         d| _        i | _        |p| j        |p| j        d| _        d| _        t          | j         d          r!t          | j         d          r| j         | _        t          | j        d          rt          | j        d          st          d          dS )a  
        This creates a new SQLStore instance.  It requires an
        established database connection be given to it, and it allows
        overriding the default table names.


        @param conn: This must be an established connection to a
            database of the correct type for the SQLStore subclass
            you're using.

        @type conn: A python database API compatible connection
            object.


        @param associations_table: This is an optional parameter to
            specify the name of the table used for storing
            associations.  The default value is specified in
            C{L{SQLStore.associations_table}}.

        @type associations_table: C{str}


        @param nonces_table: This is an optional parameter to specify
            the name of the table used for storing nonces.  The
            default value is specified in C{L{SQLStore.nonces_table}}.

        @type nonces_table: C{str}
        N)associationsnoncesi`T  IntegrityErrorOperationalErrorzDError using database connection module (Maybe it can't be imported?))
conncur_statement_cacheassociations_tablenonces_table_table_namesmax_nonce_ager   
exceptionsRuntimeError)r
   r    r#   r$   s       r   __init__zSQLStore.__init__D   s    : 	 ".I$2I"7d&7
 
 )
 DI/00 	(	#566	("iDO)9:: 	@);<<	@  ? @ @ @	@ 	@r   c                     |S )zSConvert a blob as returned by the SQL engine into a str object.

        str -> str r
   blobs     r   
blobDecodezSQLStore.blobDecodev   s	     r   c                     |S )z]Convert a str object into the necessary object for storing
        in the database as a blob.r+   r
   ss     r   
blobEncodezSQLStore.blobEncode|   s	     r   c                     	 | j         |         S # t          $ r) t          | |          }|| j        z  }|| j         |<   |cY S w xY wr   )r"   KeyErrorgetattrr%   )r
   sql_namesqls      r   _getSQLzSQLStore._getSQL   sb    	(22 	 	 	$))C4$$C.1D!(+JJJ		s    0AAc                     |                      |          }d }t          t          ||                    }| j                            ||           d S )Nc                 N    t          | t                    rt          |           S | S r   )
isinstancestr)args    r   unicode_to_strz)SQLStore._execSQL.<locals>.unicode_to_str   s$    #s## 3xx
r   )r8   listmapr!   execute)r
   r6   r   r7   r>   str_argss         r   _execSQLzSQLStore._execSQL   sY    ll8$$	 	 	 ND1122h'''''r   c                      |d d         dk    r&|dd          dz    fd}t           ||           |S t          d|d          )N   db__sqlc                        j         g| R  S r   )rC   )r   r
   r6   s    r   r   z"SQLStore.__getattr__.<locals>.func   s    $t}X55555r   z
Attribute z
 not found)setattrAttributeError)r
   attrr   r6   s   `  @r   __getattr__zSQLStore.__getattr__   sy     8uABBx&(H6 6 6 6 6 6 D$%%%K .TTT!DEEEr   c                    | j                                          	 | j                                         | _        	  ||i |}| j                                         d| _        n%# | j                                         d| _        w xY w	 | j                                          n#  | j                                           xY w|S )zExecute the given function inside of a transaction, with an
        open cursor. If no exception is raised, the transaction is
        comitted, otherwise it is rolled back.N)r    rollbackcursorr!   closecommit)r
   r   r   r   rets        r   r	   zSQLStore._callInTransaction   s    
 			y''))DH dD+F++       
 I		I    
s"   B# A# !B# #"BB# #B?c                 V    |                                   |                                  dS )z
        This method creates the database tables necessary for this
        store to work.  It should not be called if the tables already
        exist.
        N)db_create_noncedb_create_assocr
   s    r   txn_createTableszSQLStore.txn_createTables   s.     	r   c                     |}|                      ||j        |                     |j                  |j        |j        |j                   dS )zQSet the association for the server URL.

        Association -> NoneType
        N)db_set_assochandler2   secretissuedlifetime
assoc_type)r
   
server_urlassociationas       r   txn_storeAssociationzSQLStore.txn_storeAssociation   sO    
 *ah//!(33QXqz,	( 	( 	( 	( 	(r   c                    ||                      ||           n|                     |           | j                                        }t	          |          dk    rdS g }|D ]{}t          |          }|                     |d                   |d<   t          | }|j        dk    r| 	                    ||j
                   _|                    |j        |f           ||r"|                                 |d         d         S dS )zGet the most recent association that has been set for this
        server URL and handle.

        str -> NoneType or Association
        Nr      )db_get_assocdb_get_assocsr!   fetchalllenr?   r.   r   	expiresIntxn_removeAssociationrZ   appendr\   sort)r
   r_   rZ   rowsr   valuesassocs          r   txn_getAssociationzSQLStore.txn_getAssociation   s    j&1111z***x  ""t99>>4L ? ?f OOF1I66q	#V,?a''..z5<HHHH ''u(=>>>> !!####B'**tr   c                 N    |                      ||           | j        j        dk    S )zRemove the association for the given server URL and handle,
        returning whether the association existed at all.

        (str, str) -> bool
        r   )db_remove_assocr!   rowcount)r
   r_   rZ   s      r   rk   zSQLStore.txn_removeAssociation   s*     	Z000x 1$$r   c                     t          |t          j                    z
            t          j        k    rdS 	 |                     |||           dS # | j        j        $ r Y dS w xY w)zmReturn whether this nonce is present, and if it is, then
        remove it from the set.

        str -> boolFT)abstimer   SKEWdb_add_noncer'   r   )r
   r_   	timestampsalts       r   txn_useNoncezSQLStore.txn_useNonce  sv    
 y49;;&''%*445	j)T::: 4 - 	 	 	55	s   A A! A!c                     |                      t          t          j                              t          j        z
             | j        j        S r   )db_clean_nonceintrw   r   rx   r!   rt   rV   s    r   txn_cleanupNonceszSQLStore.txn_cleanupNonces  s6    C	,,uz9:::x  r   c                     |                      t          t          j                                         | j        j        S r   )db_clean_assocr   rw   r!   rt   rV   s    r   txn_cleanupAssociationsz SQLStore.txn_cleanupAssociations  s/    C	,,---x  r   )NNr   )r   
__module____qualname__r   r#   r$   r)   r.   r2   r8   rC   rL   r	   rW   r   createTablesrb   storeAssociationrq   getAssociationrk   removeAssociationr|   useNoncer   cleanupNoncesr   cleanupAssociationsr+   r   r   r   r   "   s        < ,L0@ 0@ 0@ 0@d    
  ( ( ( F F F  ,   6*++L( ( ( v233   > V.//N% % % 455  " vl##H! ! ! F,--M! ! ! !&!899r   r   c                   P     e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZd Z fdZ xZS )SQLiteStorez
    This is an SQLite-based specialization of C{L{SQLStore}}.

    To create an instance, see C{L{SQLStore.__init__}}.  To create the
    tables it will use, see C{L{SQLStore.createTables}}.

    All other methods are implementation details.
    z
    CREATE TABLE %(nonces)s (
        server_url VARCHAR,
        timestamp INTEGER,
        salt CHAR(40),
        UNIQUE(server_url, timestamp, salt)
    );
    a  
    CREATE TABLE %(associations)s
    (
        server_url VARCHAR(2047),
        handle VARCHAR(255),
        secret BLOB(128),
        issued INTEGER,
        lifetime INTEGER,
        assoc_type VARCHAR(64),
        PRIMARY KEY (server_url, handle)
    );
    z}INSERT OR REPLACE INTO %(associations)s (server_url, handle, secret, issued, lifetime, assoc_type) VALUES (?, ?, ?, ?, ?, ?);z_SELECT handle, secret, issued, lifetime, assoc_type FROM %(associations)s WHERE server_url = ?;znSELECT handle, secret, issued, lifetime, assoc_type FROM %(associations)s WHERE server_url = ? AND handle = ?;zDSELECT server_url FROM %(associations)s WHERE issued + lifetime < ?;zADELETE FROM %(associations)s WHERE server_url = ? AND handle = ?;z9DELETE FROM %(associations)s WHERE issued + lifetime < ?;z(INSERT INTO %(nonces)s VALUES (?, ?, ?);z+DELETE FROM %(nonces)s WHERE timestamp < ?;c                      t          |          S r   )
memoryviewr0   s     r   r2   zSQLiteStore.blobEncodeX  s    !}}r   c                     	  t          t          |           j        |i |S # | j        j        $ r.}t          j        dt          |                    rY d }~dS  d }~ww xY w)Nz^columns .* are not unique$F)superr   r   r'   r   rematchr<   )r
   r   r   why	__class__s       r   r   zSQLiteStore.useNonce[  sy    	45d++4dEfEEE/ 	 	 	x5s3xx@@ uuuuu		s   # A "AAA )r   r   r   r   create_nonce_sqlcreate_assoc_sqlset_assoc_sqlget_assocs_sqlget_assoc_sqlget_expired_sqlremove_assoc_sqlclean_assoc_sqladd_nonce_sqlclean_nonce_sqlr2   r   __classcell__)r   s   @r   r   r   "  s         2MDN	E LO? RO>MCO  
 
 
 
 
 
 
 
 
r   r   c                   `    e Zd ZdZ	 ddlZn# e$ r dZY nw xY wdZdZdZ	dZ
dZd	Zd
ZdZdZdZdS )
MySQLStorea&  
    This is a MySQL-based specialization of C{L{SQLStore}}.

    Uses InnoDB tables for transaction support.

    To create an instance, see C{L{SQLStore.__init__}}.  To create the
    tables it will use, see C{L{SQLStore.createTables}}.

    All other methods are implementation details.
    r   Nz
    CREATE TABLE %(nonces)s (
        server_url BLOB NOT NULL,
        timestamp INTEGER NOT NULL,
        salt CHAR(40) NOT NULL,
        PRIMARY KEY (server_url(255), timestamp, salt)
    )
    ENGINE=InnoDB;
    aG  
    CREATE TABLE %(associations)s
    (
        server_url BLOB NOT NULL,
        handle VARCHAR(255) NOT NULL,
        secret BLOB NOT NULL,
        issued INTEGER NOT NULL,
        lifetime INTEGER NOT NULL,
        assoc_type VARCHAR(64) NOT NULL,
        PRIMARY KEY (server_url(255), handle)
    )
    ENGINE=InnoDB;
    zDREPLACE INTO %(associations)s VALUES (%%s, %%s, %%s, %%s, %%s, %%s);aSELECT handle, secret, issued, lifetime, assoc_type FROM %(associations)s WHERE server_url = %%s;FSELECT server_url FROM %(associations)s WHERE issued + lifetime < %%s;rSELECT handle, secret, issued, lifetime, assoc_type FROM %(associations)s WHERE server_url = %%s AND handle = %%s;EDELETE FROM %(associations)s WHERE server_url = %%s AND handle = %%s;;DELETE FROM %(associations)s WHERE issued + lifetime < %%s;.INSERT INTO %(nonces)s VALUES (%%s, %%s, %%s);-DELETE FROM %(nonces)s WHERE timestamp < %%s;)r   r   r   r   MySQLdbr'   ImportErrorr   r   r   r   r   r   r   r   r   r   r+   r   r   r   r   h  s        	 	$$$$$   


>MGNNO	J C TODMEOOOs    r   c                       e Zd ZdZ	 ddlZn%# e$ r ddlmZ e                                 Y nw xY wdZ	dZ
dZd ZdZd	Zd
ZdZdZdZdZdZdZd Zd ZdS )PostgreSQLStorez
    This is a PostgreSQL-based specialization of C{L{SQLStore}}.

    To create an instance, see C{L{SQLStore.__init__}}.  To create the
    tables it will use, see C{L{SQLStore.createTables}}.

    All other methods are implementation details.
    r   N)compatz
    CREATE TABLE %(nonces)s (
        server_url VARCHAR(2047) NOT NULL,
        timestamp INTEGER NOT NULL,
        salt CHAR(40) NOT NULL,
        PRIMARY KEY (server_url, timestamp, salt)
    );
    a  
    CREATE TABLE %(associations)s
    (
        server_url VARCHAR(2047) NOT NULL,
        handle VARCHAR(255) NOT NULL,
        secret BYTEA NOT NULL,
        issued INTEGER NOT NULL,
        lifetime INTEGER NOT NULL,
        assoc_type VARCHAR(64) NOT NULL,
        PRIMARY KEY (server_url, handle),
        CONSTRAINT secret_length_constraint CHECK (LENGTH(secret) <= 128)
    );
    c                     |                      ||          }| j                                        }t          |          r|                     ||||||          S |                     ||||||          S )z
        Set an association.  This is implemented as a method because
        REPLACE INTO is not supported by PostgreSQL (and is not
        standard SQL).
        )rf   r!   rh   ri   db_update_assocdb_new_assoc)	r
   r_   rZ   r[   r\   r]   r^   resultrn   s	            r   rY   zPostgreSQLStore.db_set_assoc  s     "":v66x  ""t99 	;''*(2F< < <
 $$Z%-z; ; ;r   zCINSERT INTO %(associations)s VALUES (%%s, %%s, %%s, %%s, %%s, %%s);zUPDATE %(associations)s SET secret = %%s, issued = %%s, lifetime = %%s, assoc_type = %%s WHERE server_url = %%s AND handle = %%s;r   r   r   r   r   r   r   c                 $    ddl m}  ||          S )Nr   )Binary)psycopg2r   )r
   r-   r   s      r   r2   zPostgreSQLStore.blobEncode  s"    ######vd||r   c                 *    |                                 S r   )tobytesr,   s     r   r.   zPostgreSQLStore.blobDecode  s    ||~~r   )r   r   r   r   r   r   psycopg2cffir   registerr'   r   r   rY   new_assoc_sqlupdate_assoc_sqlr   r   r   r   r   r   r   r2   r.   r+   r   r   r   r     s            '''''' J; ; ;&>MCGNNO	J C TODMEO  
    s    //r   )r   r   rw   openid.associationr   openid.store.interfacer   openid.storer   r   r   r   r   r   r+   r   r   <module>r      s?    
			  * * * * * * . . . . . .         }: }: }: }: }:{ }: }: }:@C C C C C( C C CL:F :F :F :F :F :F :F :FzY Y Y Y Yh Y Y Y Y Yr   