def connect(self): # Syntax: "dbtype://*****:*****@host:port/dbname" # The /dbname syntax doesn't seem to work with SQLite... from gluon.tools import DAL if self.server == self.port == self.db_name == None: self.server = 'sqlite://oauth.sqlite' conn = self.server if not self.port else self.server + self.port self.db = DAL(conn, pool_size=1, check_reserved=['all'])
class web2pyStorage(OAuthStorage): """Adapter for the DAL (Database Abstraction Layer) created for the web2py framework. - Usable with a variety of databases (including GAE, MongoDB and PostgreSQL) - Can be imported into other frameworks (official 'support' for Flask, pyramid &etc.... see: https://github.com/mdipierro/gluino for further info) """ tables_created = False def create_tables(self): if self.tables_created: return from gluon.tools import Field from gluon.validators import IS_URL # Note that (by default): an 'id' primary key is associated with every table. self.db.define_table( 'clients', Field('client_id'), # pid Field('client_secret'), Field('redirect_uri', requires=IS_URL(allowed_schemes=['http', 'https'])), Field('client_name')) self.db.define_table( 'codes', Field('code_id'), # pid Field('client_id', 'reference clients'), Field('user_id'), Field('expires_access', 'datetime'), Field('expires_refresh', 'datetime'), Field('the_scope'), # 'scope' is a reserved SQL keyword Field('access_token')) self.db.define_table( 'tokens', Field('refresh_token'), # pid Field('client_id'), Field('user_id'), Field('expires_access'), Field('expires_refresh'), Field('the_scope'), Field('access_token')) self.tables_created = True def connect(self): # Syntax: "dbtype://*****:*****@host:port/dbname" # The /dbname syntax doesn't seem to work with SQLite... from gluon.tools import DAL if self.server == self.port == self.db_name == None: self.server = 'sqlite://oauth.sqlite' conn = self.server if not self.port else self.server + self.port self.db = DAL(conn, pool_size=1, check_reserved=['all']) def add_client(self, client_name, redirect_uri): """Adds a client application to the database, with its client name and redirect URI. It returns the generated client_id and client_secret """ try: self.db.clients except AttributeError: self.create_tables() client_id = self.generate_hash_sha1() client_secret = self.generate_hash_sha1() self.db.clients.insert( **{ 'client_id': client_id, 'client_secret': client_secret, 'redirect_uri': redirect_uri, 'client_name': client_name }) return client_id, client_secret def get_client_credentials(self, client_id): """Gets the client credentials by the client application ID given.""" try: return self.db.clients(client_id) except AttributeError: self.create_tables() return None def exists_client(self, client_id): """Checks if a client exists, given its client_id""" return self.get_client_credentials(client_id) != None def add_code(self, client_id, user_id, lifetime): """Adds a temporary authorization code to the database. It takes 3 arguments: * The client application ID * The user ID who wants to authenticate * The lifetime of the temporary code It returns the generated code """ expires = add_seconds_to_date(datetime.datetime.now(), lifetime) # do -> while FTW code = self.generate_hash_sha1() while self.get_refresh_token(code): code = self.generate_hash_sha1() self.db.codes(self.db.codes.code_id == code).update(**{ 'client_id': client_id, 'user_id': user_id, 'expires': expires }) return code def valid_code(self, client_id, code): """Validates if a code is (still) a valid one. It takes two arguments: * The client application ID * The temporary code given by the application It returns True if the code is valid. Otherwise, False """ try: data = self.db.codes(self.db.codes.code_id == code).select( self.db.expires_access).first() except AttributeError: self.create_tables() return False if data: return datetime.datetime.now() < data.expires_access return False def exists_code(self, code): """Checks if a given code exists on the database or not""" try: self.db.codes( self.db.codes.code_id == code).select().first() != None except AttributeError: self.create_tables() return False def remove_code(self, code): """Removes a temporary code from the database""" self.db.codes(self.db.codes.code_id == code).select().first().delete() def get_user_id(self, client_id, code): """Gets the user ID, given a client application ID and a temporary authentication code """ try: return self.db.codes(self.db.codes.code_id == code).select( self.db.codes.user_id).first() except AttributeError: self.create_tables() return None def expired_access_token(self, token): """Checks if the access token remains valid or if it has expired""" return token['expires_access'] < datetime.datetime.now() def expired_refresh_token(self, token): """Checks if the refresh token remains valid or if it has expired""" return token['expires_refresh'] < datetime.datetime.now() def add_access_token(self, client_id, user_id, access_lifetime, refresh_token=None, refresh_lifetime=None, expires_refresh=None, the_scope=None): """Generates an access token and adds it to the database. If the refresh token does not exist, it will create one. The method takes 6 arguments: * The client application ID * The user ID * The access token lifetime * [OPTIONAL] The refresh token * [OPTIONAL] The refresh token lifetime * [OPTIONAL] The the_scope of the access """ now = datetime.datetime.now() # do -> while FTW access_token = self.generate_hash_512() while self.get_access_token(access_token): access_token = self.generate_hash_512() expires_access = add_seconds_to_date(now, access_lifetime) # It guarantees uniqueness. Better way? if not refresh_token: # do -> while FTW refresh_token = self.generate_hash_512() while self.get_refresh_token(refresh_token): refresh_token = self.generate_hash_512() expires_refresh = add_seconds_to_date(now, refresh_lifetime) self.db.tokens.update_or_insert( **{ 'refresh_token': referesh_token, 'client_id': client_id, 'user_id': user_id, 'expires_access': expires_access, 'expires_refresh': expires_refresh, 'the_scope': the_scope, 'access_token': access_token }) return access_token, refresh_token, expires_access def refresh_access_token(self, client_id, client_secret, refresh_token): """Updates an access token, given the refresh token. The method takes 3 arguments: * The client application ID * The client application secret ID * The refresh token """ now = datetime.datetime.now() credentials = self.get_client_credentials(client_id) old_token = self.db.tokens.update_or_insert({ 'refresh_token': refresh_token, 'client_id': client_id }) if old_token and expired_refresh_token( old_token, now) and credentials['client_secret'] == client_secret: return self.add_access_token( client_id, old_token['user_id'], self.config[self.CONFIG_ACCESS_LIFETIME], old_token['refresh_token'], self.config[self.CONFIG_REFRESH_LIFETIME], old_token['expires_refresh'], old_token['the_scope']) return (False, ) * 3 def get_access_token(self, access_token): """Returns the token data, if the access token exists""" try: return self.db( self.db.tokens.access_token == access_token).select().first() except AttributeError: self.create_tables() return None def get_refresh_token(self, refresh_token): """Returns the token data, if the refresh token exists""" try: return self.db.tokens( self.db.tokens.refresh_token == refresh_token).select().first( ) # 'code' == 'refresh_token', right? [pid that is] except AttributeError: self.create_tables() return None
# coding: utf8 if False: from gluon import * from gluon.tools import request,response, session, cache, Auth, DAL db = DAL('sqlite://storage.sqlite',pool_size=1,check_reserved=['all']) auth=Auth(db) #from plugin_lazy_options_widget import lazy_options_widget from plugin_suggest_widget import suggest_widget from cascadedrop import CascadingSelect from gluon.contrib.populate import populate db.define_table('school', Field('name', requires=IS_NOT_EMPTY()), auth.signature, format='%(name)s' ) db.define_table('department', Field('school', db.school), #, requires=IS_IN_DB(db, db.school.id, '%(name)s')), Field('name', requires=IS_NOT_EMPTY()), Field('HOD', 'reference auth_user'), auth.signature, format='%(name)s' ) db.define_table('program', Field('department', 'reference department'), Field('classification', requires=IS_IN_SET(['ND', 'HND', 'PRE-ND', 'PGD','NON-ND'])), Field('the_option', label='Option'),
# -*- coding: utf-8 -*- __author__ = 'Naptin' if False: from gluon import * from datetime import date, datetime from gluon.tools import request,response, session, cache, DAL,Auth, Service, PluginManager #from gluon.tools import from gluon.contrib.appconfig import AppConfig myconf = AppConfig(reload=True) db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) auth = Auth(db) service = Service() plugins = PluginManager() from db import * ## create all tables needed by auth if not custom tables #auth.define_tables(username=False, signature=False) from time import ctime db.define_table('rev_wallet', Field('revnumber', requires=IS_LENGTH(16, 16)), Field('month_issued', 'integer', requires=IS_INT_IN_RANGE(1, 12)), Field('year_issued', 'integer', requires=IS_INT_IN_RANGE(2015, 2099)), Field('month_expired', 'integer', requires=IS_INT_IN_RANGE(1, 12)), Field('year_expired', 'integer', requires=IS_INT_IN_RANGE(2015, 2099)), Field('amount', 'float'), ) db.define_table('device',
settings.email_admin = '*****@*****.**' settings.home_dir = '/home/CBSData/' # settings.home_dir = '/home/developers/manhtd/CBSData/' settings.cp_dir = 'CPData/' settings.creator_dir = 'CreatorImages/' settings.product_image_dir = 'ProductImages/' settings.rpc_server = "http://127.0.0.1" settings.discount_value = 30 response.generic_patterns = ['*'] from gluon.custom_import import track_changes track_changes(True) db = DAL(settings.database_uri, pool_size=1, check_reserved=['all'], migrate_enabled=False, decode_credentials=True) ## configure email mail = Mail() mail.settings.server = settings.email_server mail.settings.sender = settings.email_sender mail.settings.login = settings.email_login ## configure auth policy url_index = URL('default', 'index') auth = Auth(db, hmac_key=settings.security_key, controller='users', function='index') ######################################### db.define_table('clsb_country', Field('country_name', type = 'string', notnull = True, default = "Viet Nam", label = T('Country name')),
settings.email_sender = '*****@*****.**' settings.email_login = '******' settings.home_dir = '/home/CBSData/' #settings.home_dir = '/home/developers/manhtd/CBSData/' settings.cp_dir = 'CPData/' settings.creator_dir = 'CreatorImages/' settings.product_image_dir = 'ProductImages/' settings.rpc_server = "http://127.0.0.1:8001" response.generic_patterns = ['*'] from gluon.custom_import import track_changes track_changes(True) db = DAL(settings.database_uri, pool_size=1, check_reserved=['all'], migrate_enabled=False, decode_credentials=True) service = Service() ## configure email mail = Mail() mail.settings.server = settings.email_server mail.settings.sender = settings.email_sender mail.settings.login = settings.email_login ## configure auth policy url_index = URL('default', 'index') auth = Auth(db, hmac_key=settings.security_key) auth.settings.mailer = mail auth.settings.extra_fields['auth_user'] = [ Field('is_root', type='boolean', writable=False, readable=False),
class web2pyStorage(OAuthStorage): """Adapter for the DAL (Database Abstraction Layer) created for the web2py framework. - Usable with a variety of databases (including GAE, MongoDB and PostgreSQL) - Can be imported into other frameworks (official 'support' for Flask, pyramid &etc.... see: https://github.com/mdipierro/gluino for further info) """ tables_created = False def create_tables(self): if self.tables_created: return from gluon.tools import Field from gluon.validators import IS_URL # Note that (by default): an 'id' primary key is associated with every table. self.db.define_table('clients', Field('client_id'), # pid Field('client_secret'), Field('redirect_uri', requires=IS_URL(allowed_schemes=['http', 'https'])), Field('client_name') ) self.db.define_table('codes', Field('code_id'), # pid Field('client_id', 'reference clients'), Field('user_id'), Field('expires_access', 'datetime'), Field('expires_refresh', 'datetime'), Field('the_scope'), # 'scope' is a reserved SQL keyword Field('access_token') ) self.db.define_table('tokens', Field('refresh_token'), # pid Field('client_id'), Field('user_id'), Field('expires_access'), Field('expires_refresh'), Field('the_scope'), Field('access_token') ) self.tables_created = True def connect(self): # Syntax: "dbtype://*****:*****@host:port/dbname" # The /dbname syntax doesn't seem to work with SQLite... from gluon.tools import DAL if self.server == self.port == self.db_name == None: self.server = 'sqlite://oauth.sqlite' conn = self.server if not self.port else self.server + self.port self.db = DAL(conn, pool_size=1, check_reserved=['all']) def add_client(self, client_name, redirect_uri): """Adds a client application to the database, with its client name and redirect URI. It returns the generated client_id and client_secret """ try: self.db.clients except AttributeError: self.create_tables() client_id = self.generate_hash_sha1() client_secret = self.generate_hash_sha1() self.db.clients.insert(**{'client_id': client_id, 'client_secret': client_secret, 'redirect_uri': redirect_uri, 'client_name': client_name}) return client_id, client_secret def get_client_credentials(self, client_id): """Gets the client credentials by the client application ID given.""" try: return self.db.clients(client_id) except AttributeError: self.create_tables() return None def exists_client(self, client_id): """Checks if a client exists, given its client_id""" return self.get_client_credentials(client_id) != None def add_code(self, client_id, user_id, lifetime): """Adds a temporary authorization code to the database. It takes 3 arguments: * The client application ID * The user ID who wants to authenticate * The lifetime of the temporary code It returns the generated code """ expires = add_seconds_to_date(datetime.datetime.now(), lifetime) # do -> while FTW code = self.generate_hash_sha1() while self.get_refresh_token(code): code = self.generate_hash_sha1() self.db.codes(self.db.codes.code_id == code).update(**{'client_id': client_id, 'user_id': user_id, 'expires': expires}) return code def valid_code(self, client_id, code): """Validates if a code is (still) a valid one. It takes two arguments: * The client application ID * The temporary code given by the application It returns True if the code is valid. Otherwise, False """ try: data = self.db.codes(self.db.codes.code_id == code).select(self.db.expires_access).first() except AttributeError: self.create_tables() return False if data: return datetime.datetime.now() < data.expires_access return False def exists_code(self, code): """Checks if a given code exists on the database or not""" try: self.db.codes(self.db.codes.code_id == code).select().first() != None except AttributeError: self.create_tables() return False def remove_code(self, code): """Removes a temporary code from the database""" self.db.codes(self.db.codes.code_id == code).select().first().delete() def get_user_id(self, client_id, code): """Gets the user ID, given a client application ID and a temporary authentication code """ try: return self.db.codes(self.db.codes.code_id == code).select(self.db.codes.user_id).first() except AttributeError: self.create_tables() return None def expired_access_token(self, token): """Checks if the access token remains valid or if it has expired""" return token['expires_access'] < datetime.datetime.now() def expired_refresh_token(self, token): """Checks if the refresh token remains valid or if it has expired""" return token['expires_refresh'] < datetime.datetime.now() def add_access_token(self, client_id, user_id, access_lifetime, refresh_token=None, refresh_lifetime=None, expires_refresh=None, the_scope=None): """Generates an access token and adds it to the database. If the refresh token does not exist, it will create one. The method takes 6 arguments: * The client application ID * The user ID * The access token lifetime * [OPTIONAL] The refresh token * [OPTIONAL] The refresh token lifetime * [OPTIONAL] The the_scope of the access """ now = datetime.datetime.now() # do -> while FTW access_token = self.generate_hash_512() while self.get_access_token(access_token): access_token = self.generate_hash_512() expires_access = add_seconds_to_date(now, access_lifetime) # It guarantees uniqueness. Better way? if not refresh_token: # do -> while FTW refresh_token = self.generate_hash_512() while self.get_refresh_token(refresh_token): refresh_token = self.generate_hash_512() expires_refresh = add_seconds_to_date(now, refresh_lifetime) self.db.tokens.update_or_insert(**{'refresh_token': referesh_token, 'client_id': client_id, 'user_id': user_id, 'expires_access': expires_access, 'expires_refresh': expires_refresh, 'the_scope': the_scope, 'access_token': access_token}) return access_token, refresh_token, expires_access def refresh_access_token(self, client_id, client_secret, refresh_token): """Updates an access token, given the refresh token. The method takes 3 arguments: * The client application ID * The client application secret ID * The refresh token """ now = datetime.datetime.now() credentials = self.get_client_credentials(client_id) old_token = self.db.tokens.update_or_insert({'refresh_token': refresh_token, 'client_id': client_id}) if old_token and expired_refresh_token(old_token, now) and credentials['client_secret'] == client_secret: return self.add_access_token(client_id, old_token['user_id'], self.config[self.CONFIG_ACCESS_LIFETIME], old_token['refresh_token'], self.config[self.CONFIG_REFRESH_LIFETIME], old_token['expires_refresh'], old_token['the_scope']) return (False,) * 3 def get_access_token(self, access_token): """Returns the token data, if the access token exists""" try: return self.db(self.db.tokens.access_token == access_token).select().first() except AttributeError: self.create_tables() return None def get_refresh_token(self, refresh_token): """Returns the token data, if the refresh token exists""" try: return self.db.tokens(self.db.tokens.refresh_token == refresh_token).select().first() # 'code' == 'refresh_token', right? [pid that is] except AttributeError: self.create_tables() return None
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations ######################################################################### ## This is a sample controller ## - index is the default action of any application ## - user is required for authentication and authorization ## - download is for downloading files uploaded in the db (does streaming) ######################################################################### if False: from gluon import * from gluon.tools import request, response, session, cache, Auth, DAL, Service, Crud, PluginManager from gluon.contrib.appconfig import AppConfig myconf = AppConfig(reload=True) db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) #db = DAL('sqlite://storage.sqlite',pool_size=1,check_reserved=['all']) auth = Auth(db) service = Service() plugins = PluginManager() def index(): """ example action using the internationalization operator T and flash rendered by views/default/index.html or views/generic.html if you need a simple wiki simply replace the two lines below with: return auth.wiki() """
## File is released under public domain and you can use without limitations ######################################################################### ## if SSL/HTTPS is properly configured and you want all HTTP requests to ## be redirected to HTTPS, uncomment the line below: # request.requires_https() ## app configuration made easy. Look inside private/appconfig.ini if False: from gluon import * from gluon.tools import request, response, session, cache, DAL from gluon.contrib.appconfig import AppConfig myconf = AppConfig(reload=True) #db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) db = DAL('sqlite://storage.sqlite', pool_size=1, check_reserved=['all']) #from gluon.contrib.appconfig import AppConfig ## once in production, remove reload=True to gain full speed #myconf = AppConfig(reload=True) if not request.env.web2py_runtime_gae: ## if NOT running on Google App Engine use SQLite or other DB db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) #db = DAL('sqlite://storage.sqlite',pool_size=1,check_reserved=['all']) else: ## connect to Google BigTable (optional 'google:datastore://namespace') db = DAL('google:datastore+ndb') ## store sessions and tickets there