def login_account(self, data): """Get login credentials.""" ret_obj = {} err = [] req_fields = ['username', 'password'] if any([not data[f] for f in req_fields]): err.append('LOG00001') if not err: uname = data['username'] pwrd = Tools().sha1(app.config['SALT'] + data['password'].lower()) result = self.__session.query(T_account).filter( T_account.username == uname).first() if result: if result.password == pwrd: ret_obj['token'] = result.token ret_obj['id'] = result.id ret_obj['username'] = result.username ret_obj['accounttype'] = result.acc_type else: err.append('LOG00002') else: err.append('LOG00002') Tools.close_all_connection(self.__engine, self.__session) return ret_obj, err
def post(self): """Add new admin.""" if self.errorcodes: return Tools().response400(self.errorcodes, self.timestamp) args_list = [('username', str, 'json', None), ('password', str, 'json', None), ('accounttype', int, 'json', None)] for args in args_list: self.parser.add_argument(args[0], type=args[1], location=args[2], default=args[3]) # parse arguments self.__args = self.parser.parse_args() # add account_id to args to save in database --> created_by self.__args['accnt_id'] = self.accnt_id # Initialize Model # start saving to database , if failed return 400 response model = AccountModel(self.session, self.engine) ret_obj, errorcodes = model.add_new_account(self.__args) if errorcodes: return Tools().response400(errorcodes, self.timestamp) return Tools().response200(ret_obj, self.timestamp, 201)
def __connect_to_database(self): """Connect to database.""" try: self.engine = create_engine(app.config['CONNSTR'], poolclass=NullPool) self.engine.connect() self.session = sessionmaker(bind=self.engine)() except Exception as exc: Tools.log(exc, err=True) self.errorcodes.append('DB0001')
def __private_auth(self): """Private Authentiation. Authentication that requires credentials. """ # check for errors if not self.errorcodes: # get token of the user username = self.__args['username'].lower() token = '' result = self.engine.execute( "SELECT * FROM accounts where username ='******' ".format( username)).first() if result: token = result.token self.accnt_id = result.id # create private authorization priv_authorization = Tools.sha1(self.__client + self.__client_token + username + token + str(self.__args['timestamp'])) # check if match with supplied authorization and created by API if self.__args['authorization'] != priv_authorization: self.errorcodes.append('AU0001') # check if authorization is expired else: if int(self.__args['timestamp']) + 600 < int(time.time()): self.errorcodes.append('AU0002') self.parser = reqparse.RequestParser()
def add_new_account(self, data): """Add new admin to database.""" ret_obj = {} err = [] clean_data, err = self.__validate_new_account(data) if not err: table = T_account() try: for key, value in clean_data.items(): setattr(table, key, value) self.__session.add(table) except Exception as exc: Tools.log(exc, err=True) err.append('ACC00004') else: self.__session.commit() Tools.close_all_connection(self.__engine, self.__session) return ret_obj, err
def post(self): """Account login.""" if self.errorcodes: return Tools().response400(self.errorcodes, self.timestamp) args_list = [('username', str, 'json', None), ('password', str, 'json', None)] for args in args_list: self.parser.add_argument(args[0], type=args[1], location=args[2], default=args[3]) # parse arguments self.__args = self.parser.parse_args() # Initialize Model # start getting credentials to database , if failed return 400 response model = AccountModel(self.session, self.engine) ret_obj, errorcodes = model.login_account(self.__args) if errorcodes: return Tools().response400(errorcodes, self.timestamp) return Tools().response200(ret_obj, self.timestamp, 201)
def get_account(self, data): """Get list of accounts.""" ret_obj = [] err = [] allowed_param = ['username', 'acc_type'] ret_columns = [ 'username', 'created_by', 'datecreated', 'acc_type', 'active' ] search_filter = [] for key in allowed_param: if data.get(key) not in (None, ''): search_filter.append(getattr(T_account, key) == data[key]) offset = Tools.pagination(data['limit'], data['page']) try: if search_filter: result = self.__session.query(T_account).filter( *search_filter).order_by(T_account.id).limit( data['limit']).offset(offset).all() else: result = self.__session.query(T_account).order_by( T_account.id).limit(data['limit']).offset(offset).all() except Exception as exc: Tools.log(exc, err=True) err.append('ACC00005') else: for d in result: r = d.toJSON(*ret_columns) ret_obj.append(r) Tools.close_all_connection(self.__engine, self.__session) return ret_obj, err
def get(self): """Get admin data.""" if self.errorcodes: return Tools().response400(self.errorcodes, self.timestamp) args_list = [('un', str, 'args', None, 'username'), ('at', int, 'args', None, 'acc_type'), ('l', int, 'args', 10, 'limit'), ('p', int, 'args', 1, 'page')] for args in args_list: self.parser.add_argument(args[0], type=args[1], location=args[2], default=args[3], dest=args[4]) # parse arguments self.__args = self.parser.parse_args() # Initialize Model # start get to database , if failed return 400 response model = AccountModel(self.session, self.engine) ret_obj, errorcodes = model.get_account(self.__args) if errorcodes: return Tools().response400(errorcodes, self.timestamp) return Tools().response200(ret_obj, self.timestamp)
def __public_auth(self): """Public Authentiation. Authentication that don't requires a credentials. """ # create public authorization pub_authorization = Tools.sha1(self.__client + self.__client_token + str(self.__args['timestamp'])) # check if match with supplied authorization and created by API if self.__args['authorization'] != pub_authorization: self.errorcodes.append('AU0001') # check if authorization is expired else: if int(self.__args['timestamp']) + 600 < int(time.time()): self.errorcodes.append('AU0002') self.parser = reqparse.RequestParser()
def __validate_new_account(self, data): """NEW ACCOUNT - Validate and sanitize datas before adding to database.""" retval = {} err = [] # ================= Check Required fields ================== req_fields = ['username', 'password', 'accounttype'] if any([not data[f] for f in req_fields]): err.append('ACC00001') # =========================== END ========================== if not err: # ====================== Validations ===================== # make username lowercase for generalization duplicate_test = self.__check_duplicate_username(data['username']) if not duplicate_test: err.append('ACC00002') # check if acc_type suplied is valid if data['accounttype'] not in (1, 2, '1', '2'): err.append('ACC00003') # =========================== END ======================== if not err: # ====================== Sanitations ===================== # make username lowercase for generalization retval['username'] = data['username'].lower() # encrypt password retval['password'] = Tools().sha1(app.config['SALT'] + data['password'].lower()) # generate token retval['token'] = str(uuid.uuid4()) # active is always true for new admin retval['active'] = True # accounttype retval['acc_type'] = data['accounttype'] # created by retval['created_by'] = data['accnt_id'] # =========================== END ======================== return retval, err