def facebook_authorized(): resp = facebook.authorized_response() if resp is None: return 'Access denied: reason=%s error=%s' % ( request.args['error_reason'], request.args['error_description'] ) if isinstance(resp, OAuthException): return 'Access denied: %s' % resp.message session['facebook_token'] = (resp['access_token'], '') me = facebook.get('me?fields=id,name,picture{is_silhouette,url},email') user_exists = UserController.email_exists(me.data['email']) if user_exists is True: user = UserController(email=me.data['email']) user.update(idp_tokens={'facebook': resp}) else: if type(me.data['name']) is str: first_name = me.data['name'].split()[0] last_name = me.data['name'].split()[1] UserController().create( type='landlord', first_name=first_name, last_name=last_name, email=me.data['email'], idp_tokens={'facebook': resp} ) return redirect(url_for('index'))
def google_authorized(): resp = google.authorized_response() if resp is None: return 'Access denied: reason=%s error=%s' % ( request.args['error_reason'], request.args['error_description'] ) if isinstance(resp, OAuthException): return 'Access denied: %s' % resp.message session['google_token'] = (resp['access_token'], '') me = google.get('userinfo') user_exists = UserController.email_exists(me.data['email']) if user_exists is True: user_controller = UserController(email=me.data['email']) user_controller.update(idp_tokens={'google': resp}) else: UserController().create( type='landlord', first_name=me.data['given_name'], last_name=me.data['family_name'], email=me.data['email'], idp_tokens={'google': resp} ) return redirect(url_for('index'))
def favorite_keyword(keyword): if not g.user.is_anonymous(): try: UserController.update_favorite_keyword(g.user, keyword, request.method) except NoResultFound as e: abort(404) return ''
def update_address(): region_id = request.form.get('region_id') if not region_id: abort(404) UserController.update_address(g.user, region_id) return ''
def delete_member(self, member_id): UserController.delete_user({'_id': member_id}) borrowers = BorrowerController.search_borrower({'user_id': member_id}) for borrower in borrowers: print(borrower['_id']) print('--------') BorrowerController.delete_borrower({'_id': borrower['_id']}) self.refresh_borrower() self.refresh_members() self.book_refresh()
def list_all(): if not LoginController.athenticate_user(): return redirect(url_for('logout')) resp = google.get("/oauth2/v2/userinfo") email = resp.json()["email"] # all_agents = UserModel.find_all() user = UserController() all_agents = user.get_all() return render_template('list_all.html', all_agents=all_agents, email=email)
def mypage(): if g.user.is_anonymous(): abort(401) legislator = RegionController.legislator_of(g.user.address_id) district_feeds = UserController.district_feeds(legislator) district_feeds = district_more.query(district_feeds) keyword_feeds = UserController.keyword_feeds(g.user) keyword_feeds = keyword_more.query(keyword_feeds) return render_template('mypage.html', legislator=legislator, district_feeds=district_feeds, keyword_feeds=keyword_feeds)
def post(self): auth_header = request.headers.get('Authorization') if auth_header: access_token = auth_header.split(" ")[1] else: return { "message": "This method requires an authorization header." }, 400 error, client_id = auth_by_token(access_token) if error: return {"message": error}, 401 if UserController.not_admin(client_id): return { "message": "Only the priveleged can come here. Get out peasant." }, 400 data = ThemeAdmin.parser.parse_args() error_message = ThemeController.create_theme(data["release_time"], data["theme"], data["theme_inspire"], data["theme_author"]) if error_message: return {"message": error_message}, 400 else: return {"message": "Success!"}, 201
def api_user(id): if request.method == 'PUT': data = request.get_json() try: UserController().update_user(id=data['id'], name=data['name'], fruit=data['fruit']) return "Success", 200 except: return "Bad request", 400 elif request.method == 'GET': return UserController().get_user(id).toJson() elif request.method == 'DELETE': pass else: return "Bad request", 400
def get(self): try: session = Session() uuid = request.headers["GreenList-User-Id"] user = UserController().get_user_by_id(uuid, session) if not user: abort(401) products = ( SuggestionController().get_suboptimal_products(session)) result = [] for product in products: product_json = self.product_to_json(product) suggestions = SuggestionController().get_suggestions( user, product, session) alternatives = [ self.suggestion_to_json(suggestion) for suggestion in suggestions ] product_json.update({'alternatives': alternatives}) result.append(product_json) return result finally: session.close()
def login(self, username, password): (success, user) = UserController.auth_user({ 'username': username, 'password': password }) # tidak bisa mengirim dict langsung ke qml, harus dimasukin list dulu baru mau self.loginCompleted.emit(success, [user])
def api_users(): if request.method == 'POST': return "Not implemented", 500 elif request.method == 'GET': users = UserController().get_all_users() return jsonify([user.toJson() for user in users]) else: return "Bad request", 400
def keyword_feeds(): if g.user.is_anonymous(): abort(401) keyword_feeds = UserController.keyword_feeds(g.user) keyword_feeds = keyword_more.query(keyword_feeds, _from=request.args.get('before', None)) keyword_feeds['html'] = render_template('keyword-feeds.html', keyword_feeds=keyword_feeds) del keyword_feeds['feeds'] return jsonify(keyword_feeds)
def create_member(self, fullname, username, password, profile_picture, phone, address, role='guest'): new_member = { 'fullname': fullname, 'username': username, 'password': password, 'address': address, 'profile_picture': profile_picture, 'phone': phone, 'role': role } UserController.register_user(new_member) self.refresh_members()
def put(self): try: user_controller = UserController(id=self.id) except Exception: abort(404, message="User not loaded") return None try: # Processing input arguments parser.add_argument('first_name', type=str, trim=True, store_missing=False) parser.add_argument('last_name', type=str, trim=True, store_missing=False) parser.add_argument('email', type=str, trim=True, store_missing=False) parser.add_argument('username', type=str, trim=True, store_missing=False) parser.add_argument('password', type=str, store_missing=False) parsed_args = parser.parse_args() # Updating user instance user_controller.update(**parsed_args) return user_controller.user, 202 except Exception as e: abort(400, message=str(e))
def add_borrower(self, context): # print(context) if UserController.is_exist(context['user_id']) and BookController.is_exist(context['book_id']): context['borrowed_at'] = str(date.today()) context['return_at'] = str(date.today() + timedelta(days=7)) book = BookController.search_book({'_id': context['book_id']})[0] book['stock'] = int(book['stock']) - 1 BookController.update_book(book) self._model.insert(context) else: print('user_id or book_id doesnt exist, failed to create...')
def post(self): data = UserRegister.parser.parse_args() error_message, status = UserController.create_user( data['username'], data['password'], data['question'], data['answer'], data['intro']) if error_message: return {"message": error_message}, status return {"message": "Success!"}, 201
class UserResource(Resource): def __init__(self): self.controller = UserController() @token_required(roles=['Administrator']) @swag_from('/resources/users/description/users_get.yml') @marshal_with(get_registered_user_details()) def get(self, public_id: str, current_user: User) -> List[User]: return self.controller.get_by_id(public_id, current_user) @token_required(roles=['Administrator']) @swag_from('/resources/users/description/users_put.yml') @marshal_with(get_registered_user_details()) def put(self, public_id: str, current_user: User) -> User: return self.controller.edit(public_id, current_user) @token_required(roles=['Administrator']) @swag_from('/resources/users/description/users_delete.yml') def delete(self, public_id: str, current_user: User): self.controller.delete(public_id, current_user) return get_delete_response()
def district_feeds(): if g.user.is_anonymous(): abort(401) legislator = RegionController.legislator_of(g.user.address_id) district_feeds = UserController.district_feeds(legislator) district_feeds = district_more.query(district_feeds, _from=request.args.get('before', None)) district_feeds['html'] = render_template('district-feeds.html', legislator=legislator, district_feeds=district_feeds) del district_feeds['feeds'] return jsonify(district_feeds)
async def register(request): body = json.loads(await request.body()) name_user = body.get('name_user') or None email = body.get('email') pwd = body.get('pwd') user_controller = UserController(email=email, pwd=pwd) ok, message = await user_controller.create_user(username=name_user) if ok: return JSONResponse({'message': f'user created successfully {email}'}, status_code=200) else: return JSONResponse({'message': message}, status_code=400)
def make_user(cls): data = json.loads(request.data.decode('utf-8')) req_params = ['username'] if 'username' not in data: return json.dumps({"response": "ill-formed request"}), 400 error_message, status, response = UserController.make_user( data['username']) if error_message: return json.dumps({"response": error_message}), status return json.dumps({"response": response}), 201
class UserListResource(Resource): def __init__(self): self.controller = UserController() @token_required(roles=['Administrator']) @swag_from('/resources/users/description/users_list_get.yml') @marshal_with(get_registered_user_details()) def get(self, current_user: User) -> List[User]: return self.controller.get_list(current_user) @token_required(roles=['Administrator']) @swag_from('/resources/users/description/users_list_post.yml') def post(self, current_user: User) -> User: user = self.controller.create(current_user) serialized_user = serialize(user, get_registered_user_details()) json_user = json.dumps(serialized_user) response = get_post_response(obj=user, body=json_user, content_type='application/json', api='/{rsc}'.format(rsc=API_PREFIX)) return response
def search_late_borrower(self): borrowers = BorrowerController.search_late() for borrower in borrowers: book = BookController.get_book(borrower['book_id']) user = UserController.get_user(borrower['user_id']) d1 = datetime.strptime(borrower['return_at'], '%Y-%m-%d').date() d2 = date.today() delta = (d2 - d1).days borrower['penalty'] = (delta / 7) * OVERDUE_FINES borrower['title'] = book['title'] borrower['profile_picture'] = user['profile_picture'] borrower['fullname'] = user['fullname'] self.searchLateBorrowersCompleted.emit(borrowers)
def put(self, username): data = User.parser.parse_args() caller_username = current_identity.username error_message, myfault = UserController.user_update( caller_username, username, data["mode"], data["payload"]) if error_message and myfault: return {"message": error_message}, 500 elif error_message and not myfault: return {"message": error_message}, 400 elif not error_message and not myfault: return {"message": "Success!"}, 200 elif not error_message and type(myfault) is list: return myfault, 200
async def login(request): body = json.loads(await request.body()) user_controller = UserController(email=body.get('email'), pwd=body.get('pwd')) user = await user_controller.get_user() if user: if verify_password(user.password, body.get('pwd')): return JSONResponse({'status': 'logged in'}, status_code=200) else: return JSONResponse({'status': 'password is wrong'}, status_code=401) else: return JSONResponse({'status': 'not logged'}, status_code=400)
def post(self): name = self.get_argument("name") password = self.get_argument("password") args = {} if name and password: args["name"] = name args["password"] = password args["gender"] = int(self.get_argument("gender", 1)) args["email"] = self.get_argument("email", "") args["phone"] = self.get_argument("phone", "") args["image"] = self.get_argument("image", "") args["country"] = self.get_argument("country", "CN") args["city"] = self.get_argument("city", "") info = UserController.create_user(args) self.render(dict(info=info))
def put(self): if UserController.not_admin(): return { "message": "Only the priveleged can come here. Get out peasant." }, 400 data = ThemeAdmin.parser.parse_args() error_message = ThemeController.update_theme(data["release_time"], data["theme"], data["theme_inspire"], data["theme_author"]) if error_message: return {"message": error_message}, 400 else: return {"message": "Success!"}
def post(self): try: req = request.get_json() user_id = req['userId'] product_id = req['productId'] quantity = req['quantity'] session = Session() user = UserController().get_user_by_id(user_id, session) product = ProductController().get_product(product_id, session) PurchasesController().add_purchase(user, product, quantity, session) finally: session.commit() session.close()
def search_borrower(self, search_by='title', argument=''): _borrowers = BorrowerController.search_borrower({}) self.borrower_query = {'search_by': search_by, 'argument': argument} borrowers = [] for borrower in _borrowers: book = BookController.get_book(borrower['book_id']) user = UserController.get_user(borrower['user_id']) if (search_by == 'title' and argument.lower() not in book['title'].lower()) or ( search_by == 'fullname' and argument.lower() not in user['fullname'].lower()): continue borrower['title'] = book['title'] borrower['profile_picture'] = user['profile_picture'] borrower['fullname'] = user['fullname'] borrowers.append(borrower) self.searchBorrowersCompleted.emit(borrowers) self.search_late_borrower()
def co2_difference_to_trees(self, user, original, alternative, session=None): own_session = False if not session: session = Session() own_session = True challenge_months = ( UserController().get_challenge_duration_in_months(user)) tree_co2_equivalent = TREE_CO2_GRAMS_PER_MONTH * challenge_months saved_trees = (original - alternative) / tree_co2_equivalent if own_session: session.close() return saved_trees
def get(self, username): """ checks if the request is authorized. Then uses username to give the usermodel in json form. """ auth_header = request.headers.get('Authorization') if auth_header: access_token = auth_header.split(" ")[1] else: return { "message": "This method requires an authorization header." }, 400 error, client_id = auth_by_token(access_token) if error: return {"message": error}, 401 error_message, response = UserController.find_by_username(username) if error_message: return {"message": error_message}, 400 else: return {"user": response.json()}
def get(self, year, month, day): if UserController.not_admin(current_identity): return { "message": "Only the priveleged can come here. Get out peasant." }, 400 if safe_str_cmp(day, "all"): error_message, response = ThemeController.get_for_month( year, month) elif day.isdigit(): error_message, response = ThemeController.get_for_day( year, month, int(day)) else: return {"message": "Unsupported mode of get"}, 400 if error_message: return {"message": error_message}, 500 else: return { "response": list(map(lambda x: x.json() if x else "", response)) }
def get(self, year, month, day): auth_header = request.headers.get('Authorization') if auth_header: access_token = auth_header.split(" ")[1] else: return {"message": "This method requires an authorization header."}, 400 error, client_id = auth_by_token(access_token) if error: return {"message": error}, 401 if UserController.not_admin(client_id): return {"message": "Only the priveleged can come here. Get out peasant."}, 401 if safe_str_cmp(day, "all"): error_message, response = ThemeController.get_for_month(year, month) elif day.isdigit(): error_message, response = ThemeController.get_for_day(year, month, int(day)) else: return {"message": "Unsupported mode of get"}, 400 if error_message: return {"message": error_message}, 500 else: return {"response": list(map(lambda x: x.json() if x else "", response))}
from pydantic import UUID4 import requests import uuid from uuid import UUID from tortoise.contrib.pydantic import pydantic_model_creator from fastapi import FastAPI, HTTPException from tortoise.exceptions import DoesNotExist from utils import get_current_user, demand_current_user from controllers.user import UserController router = APIRouter(tags=["User"]) user_router = router controller = UserController() @router.get("/", response_model=List[controller.pydantic_model]) async def get_users(): return await controller.retrieveAll() from models.user import User, User_Pydantic UserPydantic = pydantic_model_creator(User, name="user") @router.get("/me", response_model=UserPydantic) async def get_me(current_user: dict = Depends(demand_current_user)):
def post(self): UserController.user_save() self.render(dict(code=1, message="success"))
def login_guest(self, username, password): (success, user) = UserController.auth_user({ 'username': username, 'password': password }) self.loginGuestCompleted.emit(success, [user])
def user_seed(): UserController.register_user({'phone': '082102080', 'address':'Jl.Pisang', 'profile_picture': '../assets/pasfoto-1.jpg', 'fullname': 'Hadi Yahya', 'username':'******', 'password': '******', 'role': 'admin'}) UserController.register_user({'phone': '0821013123', 'address':'Jl.Manggis', 'profile_picture': '../assets/pasfoto-2.jpg', 'fullname': 'Aditya Hagi','username':'******', 'password': '******', 'role': 'guest'}) UserController.register_user({'phone': '21312302080', 'address':'Jl.Kedondong', 'profile_picture': '../assets/pasfoto-3.jpg', 'fullname': 'Dinda A.','username':'******', 'password': '******', 'role': 'guest'}) UserController.register_user({'phone': '0821123080', 'address':'Jl.Tomat', 'profile_picture': '../assets/pasfoto-4.jpg', 'fullname': 'Budi Baskoro','username':'******', 'password': '******', 'role': 'guest'}) UserController.register_user({'phone': '0821123080', 'address':'Jl.Tomat', 'profile_picture': '../assets/pasfoto-5.jpg', 'fullname': 'Rania Putri','username':'******', 'password': '******', 'role': 'guest'}) UserController.register_user({'phone': '0821123080', 'address':'Jl.Tomat', 'profile_picture': '../assets/pasfoto-6.png', 'fullname': 'Deva Alviana','username':'******', 'password': '******', 'role': 'guest'}) UserController.register_user({'phone': '23213123', 'address':'Jl.Nangka', 'profile_picture': '../assets/pasfoto-7.jpg', 'fullname': 'Putri A.','username':'******', 'password': '******', 'role': 'guest'}) print('user seed done')
from controllers.user import UserController from controllers.student import StudentController user = UserController() student = StudentController() user_data = ["dian romadlonal", "adzim"] if __name__ == "__main__": user.update(2, user_data)