def user_login(): username = request.forms('username') password = request.forms('password') user_repository = UserRepository() user = user_repository.check_user_login(username, password) if user is None: return make_response("Not Authorized"), 401 else: session['session_token'] = md5(username + password).digest() return make_response("Logged in"), 200
class UserResource(Resource): repository = UserRepository() @jwt_required() def get(self): users_json = [] users = self.repository.find_all() for user in users: user_json = { 'name': user.name, 'surname': user.surname, 'username': user.username, 'email': user.email, 'roles': user.roles } users_json.append(user_json) return {'users': users_json} @jwt_required() def post(self): data = request.get_json() user_data = data['user'] user = { "id": int(uuid.uuid1()), "name": user_data['name'], "surname": user_data['surname'] } return {'user': user}
class UserManager: def __init__(self): self._user_repository = UserRepository() def flask_login_get_user(self, user_id: str) -> Optional[User]: try: return self.get_user(user_id) except UserNotFoundError: return None def get_user(self, user_id: str) -> User: try: return self._user_repository.get_user(user_id) except UserNotFoundError as e: raise e def check_user(self, user_id: str) -> bool: return self._user_repository.has_user(user_id) def get_all_usernames(self) -> List[str]: return self._user_repository.get_all_usernames() def create_new_user(self, user_id: str, first_name: str, last_name: str, email: str, password: str) -> User: if self._user_repository.has_user(user_id): raise UserAlreadyExistsError(user_id) user = User(user_id, first_name, last_name, email, None) user.password = password self._user_repository.add_user(user) return user def get_users_list(self, usernames: List[str]) -> List[User]: return self._user_repository.get_users_list(usernames)
def create_account_with_ether(self, amount_of_ether: int) -> EthKeyPair: account = self.create_account() provider = UserRepository.get_test_users()[0] self.send_ether(source=provider.eth_key_pair, destination_public_key=account.public_key, amount_in_ether=amount_of_ether, gas=Constants.DEFAULT_GAS, gas_price_in_gwei=Constants.DEFAULT_GAS_PRICE_IN_GWEI) return account
def acord(): if verify_role(1) == 0: return render_template("home.html") repoUser = UserRepository() serviceUser = UserService(repoUser) idOfCurrentUser = serviceUser.getOneByUsername( session["username"]).get_id() repoComp = CompanyInfoRepository() serviceComp = CompanyInfoService(repoComp) if request.method == "POST": company = serviceComp.getOne(idOfCurrentUser) accordYear = request.form["AccordYear"] noHours = request.form["InternshipLenghtDays"] accordSignDate = request.form["AccordSignDate"] companyName = company.get_name() companyCity = company.get_city() companyStreet = company.get_street() companyStreetNo = company.get_streetNo() companyPhone = company.get_phone() fax = company.get_fax() companyFiscalCode = company.get_fiscalCode() companyBank = company.get_bank() companyIBAN = company.get_iban() companyLegalRepresentative = company.get_legalRepresentative() nrOfStudents = request.form["TotalNoStudents"] noStudents1 = request.form["NoStudents1"] noStudents2 = request.form["NoStudents2"] specialization1 = request.form["Specialization1"] specialization2 = request.form["Specialization2"] faculty2 = request.form["Faculty2"] faculty1 = request.form["Faculty1"] signature = request.form["signature"] create_acord(accordYear, noHours, accordSignDate, companyName, companyCity, companyStreet, companyStreetNo, companyPhone, fax, companyFiscalCode, companyBank, companyIBAN, companyLegalRepresentative, nrOfStudents, noStudents1, noStudents2, specialization1, specialization2, faculty1, faculty2, signature) flash("Ati completat cu succes acordul!") return render_template("firmaResponsabil/homeResponsabilFirma.html") else: try: company = serviceComp.getOne(idOfCurrentUser) except: flash("Trebuie sa introduceti mai intai datele firmei.") return redirect(url_for("responsabil_firma.home")) return render_template("firmaResponsabil/acordResponsabilFirma.html")
class SignInResource(Resource): repository = UserRepository() def post(self): data = request.get_json() u = data['user'] user = User(u['name'], u['surname'], u['email'], u['username'], u['password']) new_user = self.repository.save(user) if new_user != None: return {'result': 'user created'}, 201 return {'result': 'error'}, 500
def request_loader(request): user_token = request.headers.get('X-Auth-Token') if user_token is None: return try: # https://firebase.google.com/docs/auth/admin/verify-id-tokens?hl=ja#verify_id_tokens_using_the_firebase_admin_sdk firebase_auth_info = auth.verify_id_token(user_token) except InvalidIdTokenError: return user_id = firebase_auth_info['uid'] repository = UserRepository() stored_user = repository.get_by_id(user_id) if stored_user is not None: return stored_user # Register DB a new user. new_user = User( user_id=user_id ) repository.insert(new_user) return new_user
class UserGroupService: user_repository = UserRepository() group_repository = GroupRepository() def add_user(self, cmdargs): cmdlist = cmdargs.split() if len(cmdlist) != 3: print('Invalid User command') return id, name = cmdlist[1:] if self.user_repository.get_user_by_id(id) is not None: print('User already present') return new_user = User(id, name) self.user_repository.add_user(new_user) print('User {} added'.format(id)) def add_group(self, cmdargs): cmdlist = cmdargs.split() if len(cmdlist) < 4: print('Invalid Group command') return group_id, group_name, member_list = cmdlist[1], cmdlist[2], cmdlist[3:] if self.group_repository.get_group_by_id(id) is not None: print('Group already present') return for member_id in member_list: if self.user_repository.get_user_by_id(member_id) is None: print('Member {} not present'.format(member_id)) return try: new_group = Group(group_id, group_name, member_list) except Exception as e: print(str(e)) return self.group_repository.add_group(new_group) print('Group {} Added'.format(group_id))
def test_building_and_parsing_plain_message(self): test_users = UserRepository.get_test_users() sender = test_users[0] message = 'Message' message_type = MessageType.PUBLIC_POST message_block = MessageBlockBuilder.build_message_block( message=message, message_type=message_type, sender=sender) blockchain_message_block = BlockchainMessageBlock( timestamp=0, block_hash=None, data=message_block.to_bytes()) parsed_block = MessageBlockParser.parse_message_block( blockchain_message_block=blockchain_message_block) self.assertEqual(message, parsed_block.message) self.assertEqual(message_type, parsed_block.message_type) self.assertEqual(sender.encryption_key_pair.public_key, parsed_block.sender)
class CurrentUserResource(Resource): repository = UserRepository() @jwt_required() def get(self): user = self.repository.find_one(int(current_identity)) authenticated_user = { 'id': user.id, 'name': user.name, 'surname': user.surname, 'email': user.email, 'username': user.username, 'roles': user.roles } if user: return {'user': authenticated_user} return {'user': '******'}
def date_firma(): if verify_role(1) == 0: return render_template("home.html") if request.method == "POST": repoUser = UserRepository() serviceUser = UserService(repoUser) idOfCurrentUser = serviceUser.getOneByUsername( session["username"]).get_id() companyName = request.form["CompanyName"] companyCity = request.form["CompanyCity"] companyStreet = request.form["CompanyStreet"] companyStreetNo = request.form["CompanyStreetNo"] companyPhone = request.form["CompanyPhone"] companyFax = request.form["CompanyFax"] companyFiscalCode = request.form["CompanyFiscalCode"] companyBank = request.form["CompanyBank"] companyIBAN = request.form["CompanyIBAN"] companyLegalRepresentative = request.form["CompanyLegalRepresentative"] companyLRFunction = request.form["CompanyLegalRepresentativeFunction"] companyEmail = request.form["CompanyEmail"] adresaPractica = request.form["AdresaPractica"] from domain.company_info import CompanyInfo companyInfo = CompanyInfo(idOfCurrentUser, companyLegalRepresentative, companyName, companyCity, companyStreet, companyStreetNo, companyPhone, companyFax, companyFiscalCode, companyBank, companyIBAN, companyLRFunction, companyEmail, adresaPractica) repoComp = CompanyInfoRepository() serviceComp = CompanyInfoService(repoComp) try: serviceComp.add(companyInfo) except: # nu s-a putut adauga, deci deja exista, caz in care il updatam. serviceComp.update(companyInfo) flash("Ati completat cu succes datele firmei!") return redirect(url_for("responsabil_firma.home")) else: return render_template("firmaResponsabil/dateGeneraleFirma.html")
def test_building_and_parsing_encrypted_message(self): test_users = UserRepository.get_test_users() sender = test_users[0] recipients_public_keys = [test_users[1].encryption_key_pair.public_key] recipients_private_key = test_users[1].encryption_key_pair.private_key message = 'Random Message' message_type = MessageType.PRIVATE_POST message_block = MessageBlockBuilder.build_message_block( message=message, message_type=message_type, sender=sender, recipients_public_keys=recipients_public_keys) blockchain_message_block = BlockchainMessageBlock( timestamp=0, block_hash=None, data=message_block.to_bytes()) parsed_block = MessageBlockParser.parse_message_block( blockchain_message_block=blockchain_message_block, private_key=recipients_private_key) self.assertEqual(message, parsed_block.message) self.assertEqual(message_type, parsed_block.message_type) self.assertEqual(sender.encryption_key_pair.public_key, parsed_block.sender)
def __init__(self): self._user_repository = UserRepository()
import config import cv2 import pymongo from flask import Flask, jsonify from flask import request from flask import send_file from photo_processor import PhotoProcessor from repository.statistics_repository import StatisticsRepository from repository.user_repository import UserRepository from stats_recommendation import StatsRecommendation app = Flask("E-AT") mongo_client = pymongo.MongoClient( 'mongodb://%s:%s@%s:27017' % (config.database_user, config.database_password, config.database_host)) user_repository = UserRepository(mongo_client['e_at_db']) stats_repository = StatisticsRepository(mongo_client['e_at_db']) photo_processor = PhotoProcessor(stats_repository) @app.route('/register', methods=['POST']) def register_user(): try: json_request = request.get_json() user_repository.register(json_request['username'], json_request['password']) return {"result": "user created"} except ValueError as error: return {"result": str(error)}, 400 except Exception as err: return {"result": str(err)}, 500
def __init__(self): self._db_path = 'resources/TradiE.db' self._user_repository = UserRepository() self._portfolio_repository = PortfolioRepository()
class GameRepository(BaseRepository): def __init__(self): self._db_path = 'resources/TradiE.db' self._user_repository = UserRepository() self._portfolio_repository = PortfolioRepository() def get_games_for_user(self, user_id: str) -> List[Game]: games = [] with sqlite3.connect(self._db_path) as connection: cursor = connection.cursor() query = self.build_select_all_query( table=MembershipsTable.TABLE_NAME, identifiers=(MembershipsTable.Columns.USERNAME, )) output = cursor.execute(query, (user_id, )) for row in output: game_id = row[0] games.append(self.get_game_by_id(game_id)) return games def get_game_by_id(self, game_id: int) -> Game: with sqlite3.connect(self._db_path) as connection: cursor = connection.cursor() query = self.build_select_all_query( table=GamesTable.TABLE_NAME, identifiers=(GamesTable.Columns.ID, )) output = cursor.execute(query, (game_id, )) result = output.fetchone() if not result: raise GameNotFoundError(game_id) name = result[1] start_date = result[2] end_date = result[3] users = self._build_users_for_game(game_id) portfolios = self._build_portfolios_for_game(game_id) return Game(game_id, name, start_date, end_date, users, portfolios) def _build_users_for_game(self, game_id: int) -> List[User]: usernames = [] with sqlite3.connect(self._db_path) as connection: cursor = connection.cursor() query = self.build_select_all_query( table=MembershipsTable.TABLE_NAME, identifiers=(MembershipsTable.Columns.GAME_ID, )) output = cursor.execute(query, (game_id, )) for row in output: usernames.append(row[1]) return self._user_repository.get_users_list(usernames) def _build_portfolios_for_game(self, game_id: int) -> List[Portfolio]: portfolio_ids = [] with sqlite3.connect(self._db_path) as connection: cursor = connection.cursor() query = self.build_select_all_query( table=PortfoliosTable.TABLE_NAME, identifiers=(PortfoliosTable.Columns.GAME_ID, )) output = cursor.execute(query, (game_id, )) for row in output: portfolio_ids.append(row[1]) return self._portfolio_repository.get_portfolios_list(portfolio_ids) def add_game(self, game: Game): with sqlite3.connect(self._db_path) as connection: cursor = connection.cursor() game_query = self.build_insert_query( table=GamesTable.TABLE_NAME, columns=(GamesTable.Columns.NAME, GamesTable.Columns.START_DATE, GamesTable.Columns.END_DATE)) cursor.execute(game_query, _unpack_game(game)) game.update_with_generated_id(cursor.lastrowid) for user in game.users: user_query = self.build_insert_query( table=MembershipsTable.TABLE_NAME, columns=(MembershipsTable.Columns.GAME_ID, MembershipsTable.Columns.USERNAME)) cursor.execute(user_query, (game.game_id, user.user_id)) connection.commit() for portfolio in game.portfolios: portfolio_query = self.build_insert_query( table=PortfoliosTable.TABLE_NAME, columns=(PortfoliosTable.Columns.GAME_ID, PortfoliosTable.Columns.PORTFOLIO_ID)) cursor.execute(portfolio_query, (game.game_id, portfolio.portfolio_id))
import json from flask import Blueprint, Response from flask import jsonify, request from controller.helpers.authorize import auth_required_with_role from controller.helpers.mapper import Mapper from domain.enums.role import Role from repository.department_repository import DepartmentRepository from repository.user_repository import UserRepository from service.department_service import DepartmentService from service.user_service import UserService from werkzeug.security import generate_password_hash user_repo = UserRepository() user_service = UserService(user_repo) users = Blueprint('users', __name__) auth = Blueprint('auth', __name__) userRepo = UserRepository() userService = UserService(userRepo) department_repo = DepartmentRepository() department_service = DepartmentService(department_repo) @auth.route('/login', methods=['POST']) def login_post(): user = userService.matchUserPassword(request.json['email'], request.json['password']) if user is None: return json.dumps(user)
class BillService: user_repository = UserRepository() group_repository = GroupRepository() bill_repository = BillRepository() def validate_bill_structure(self, input_dict): if 'desc' not in input_dict or 'totalAmount' not in input_dict: return False if 'groupId' not in input_dict: return False if 'contribution' not in input_dict or 'paidBy' not in input_dict: return False return True def calculate_share(self, group, contributors: List[Tuple[User, int]], paidBy: List[Tuple[User, int]]): for cont_user in contributors: user = cont_user[0] share = cont_user[1] group.group_balance[user.id] -= share user.total_amount_owed -= share for paid_user in paidBy: user = paid_user[0] share = paid_user[1] group.group_balance[user.id] += share user.total_amount_owed += share def add_bill(self, input_dict): if not self.validate_bill_structure(input_dict): print('Invalid Bill Structure') return if self.bill_repository.get_bill_by_desc( input_dict['desc']) is not None: print('Bill already present') return # Interger if input_dict['totalAmount'] <= 0: print('Invalid Total Amount') return group = self.group_repository.get_group_by_id(input_dict['groupId']) if group is None: print('Group not present') return contributor_list = input_dict['contribution'] paid_by_list = input_dict['paidBy'] cont_user_obj_list = [] share_value = 0 for contributor in contributor_list: try: user = self.user_repository.get_user_by_id( contributor['person']) share = contributor['share'] if share < 0: raise ('Negative Share not allowed') except Exception as e: print(str(e)) return if user is None: print('User not present') return share_value += share cont_user_obj_list.append((user, share)) if share_value != input_dict['totalAmount']: print('Contributor total amount does not match!') return paid_user_obj_list = [] share_value = 0 for paidBy_user in paid_by_list: try: user = self.user_repository.get_user_by_id( paidBy_user['person']) share = paidBy_user['share'] if share < 0: raise ('Negative Share not allowed') except Exception as e: print(str(e)) return if user is None: print('User not present') return share_value += share paid_user_obj_list.append((user, share)) if share_value != input_dict['totalAmount']: print('PaidBy amount does not match!') return self.calculate_share(group, cont_user_obj_list, paid_user_obj_list) desc = input_dict['desc'] total_amount = input_dict['totalAmount'] group_id = input_dict['groupId'] contribution = input_dict['contribution'] paidBy = input_dict['paidBy'] new_bill = Bill(desc, total_amount, group_id, contribution, paidBy) self.bill_repository.add_bill(new_bill) print('Bill added') def show_group_balance(self): all_groups = self.group_repository.get_all_groups() for group in all_groups: print(group.group_balance) print('======') def show_all_person_balance(self): all_users = self.user_repository.get_all_users() for user in all_users: print('User {}: total balance {}'.format(user.name, user.total_amount_owed))
def get_user_service(): from repository.user_repository import UserRepository from service.user_service import UserService repo = UserRepository() return UserService(repo)
import os from flask import Flask, render_template, jsonify, request from flask_api import FlaskAPI from flask_cors import CORS from repository.suggestion_repository import SuggestionRepository from repository.user_repository import UserRepository from repository.messages_repository import MessageRepository from repository.database_helper import DatabaseHelper app = Flask(__name__) cors = CORS(app, resource={r"/*":{"origins": "*"}}) suggestionsRepository = SuggestionRepository() userRepository = UserRepository() messageRepository = MessageRepository() @app.route("/suggestions", methods=["GET"]) def hello(): database = DatabaseHelper() response = suggestionsRepository.findAll(database) return jsonify(response) @app.route("/user/login", methods=["POST"]) def login_user(): user = request.get_json() print(user) database = DatabaseHelper() response = userRepository.login(database, user) return jsonify([response])