
    f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y)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  |_        t         d      r j                  |_        |S # t        $ r Y *w xY w)Nc                 2     | j                   | g|i |S N)_callInTransaction)selfargskwargsfuncs      P/var/www/cs2snipe.com/venv/lib/python3.12/site-packages/openid/store/sqlstore.pywrappedz_inTxn.<locals>.wrapped   s"    &t&&tTCDCFCC    __name__   __doc__)hasattrr   	TypeErrorr   )r   r   s   ` r   _inTxnr      s]    D tZ 	#}}QR0G tY,,N  		s   A 	AA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y)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                 p   || _         d| _        i | _        |xs | j                  |xs | j                  d| _        d| _        t        | j                   d      r't        | j                   d      r| j                   | _        t        | j                  d      rt        | j                  d      st        d      y)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$2I2I"7d&7&7
 )
 DII/0		#56"iiDO)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   sX    	((22 	$)C4$$$C.1D!!(+J		s    5A	A	c                     | j                  |      }d }t        t        ||            }| j                  j	                  ||       y )Nc                 <    t        | t              rt        |       S | S r   )
isinstancestr)args    r   unicode_to_strz)SQLStore._execSQL.<locals>.unicode_to_str   s    #s#3x
r   )r8   listmapr!   execute)r
   r6   r   r7   r>   str_argss         r   _execSQLzSQLStore._execSQL   s<    ll8$	 ND12h'r   c                 n     |d d dk(  r|dd  dz    fd}t         ||       |S t        d|d      )N   db__sqlc                  *     j                   g|  S r   )rC   )r   r
   r6   s    r   r   z"SQLStore.__getattr__.<locals>.func   s    $t}}X555r   z
Attribute z
 not found)setattrAttributeError)r
   attrr   r6   s   `  @r   __getattr__zSQLStore.__getattr__   sI     8uABx&(H6 D$%K T!DEEr   c                    | j                   j                          	 | j                   j                         | _        	  ||i |}| j                  j	                          d| _        	 | j                   j                          |S # | j                  j	                          d| _        w xY w#  | j                   j                           xY w)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    
 				yy'')DH D+F+ 
 II
  	II s"   B( B !B( #B%%B( (Cc                 D    | j                          | j                          y)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                  |j
                  |j                         y)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   sB    
 *ahh//!((3QXXqzz,,	(r   c                    || j                  ||       n| j                  |       | j                  j                         }t	        |      dk(  ryg }|D ]u  }t        |      }| j                  |d         |d<   t        | }|j                  dk(  r| j                  ||j                         Y|j                  |j                  |f       w |r|j                          |d   d   S y)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z*xx  "t9>L ?f OOF1I6q	#V,??a'..z5<<H ''u(=>? !!##B'**r   c                 X    | j                  ||       | j                  j                  dkD  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xx  1$$r   c                     t        |t        j                         z
        t        j                  kD  ry	 | j	                  |||       y# | j
                  j                  $ r Y y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  s]    
 y499;&'%**4	j)T:  -- 		s   A A$#A$c                     | j                  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  s4    C		,uzz9:xx   r   c                     | j                  t        t        j                                      | j                  j                  S r   )db_clean_assocr   rw   r!   rt   rV   s    r   txn_cleanupAssociationsz SQLStore.txn_cleanupAssociations  s+    C		,-xx   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@d
( F, *+L( 23> ./N% 45" l#H! ,-M! !!8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        | 
  |i |S # | j                  j                  $ r*}t        j                  dt        |            rY d }~y 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[  sR    	d4dEfEE// 	xx5s3x@		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   "  sc    2MDN	E LO? RO>MCO
 
r   r   c                   \    e Zd ZdZ	 ddlZdZdZdZ	dZ
dZd	Zd
ZdZdZdZy# e$ r dZY w xY w)
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  ss    	$>MGNNO	J C TODMEOY  
s   ! ++r   c                       e Zd ZdZ	 ddl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 Zy# e$ r ddlmZ ej                          Y ?w xY w)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                  ||      }| j                  j                         }t        |      r| j	                  ||||||      S | j                  ||||||      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  sq     "":v6xx  "t9''*(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    #d|r   c                 "    |j                         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
Y  's   . AAr   )r   r   rw   openid.associationr   openid.store.interfacer   openid.storer   r   r   r   r   r   r+   r   r   <module>r      s[    
  * .  }:{ }:@C( CL:F :FzYh Yr   