def add_super_company_user(): first_company = CompanyModel.find_by_name("OneSteward") if not first_company: first_company = CompanyModel("OneSteward", "*****@*****.**", "555-555-5555") first_company.save_to_db() first_staff = StaffModel.find_by_name("admin") if not first_staff: first_staff = StaffModel("admin", "admin", generate_password_hash("admin_password"), first_company.id) first_staff.save_to_db() first_user = UserModel.find_by_name("NA") if not first_user: first_user = UserModel(generate_password_hash("admin_password"), name="NA", email="NA", phone="") first_user.save_to_db()
def post(self): data = UserRegister.parser.parse_args() username = data['username'] if UserModel.find_by_username(username): return { "message": f"A user with name '{username}' already exists" }, 400 user = UserModel(**data) user.save_to_db() return {"message": f"User '{username}' created successfully"}, 201
def user_register(): form = UserCreateForm() if form.validate_on_submit(): user = UserModel( hashed_password = generate_password_hash(form.password.data), name = form.username.data, email = form.email.data, phone = form.phone.data ) user.save_to_db() return redirect(url_for("web.index")) return render_template("user_register.html", form=form)
def login(): form = AuthLogin() if form.validate_on_submit(): user = UserModel.find_by_name(form.username.data) staff = StaffModel.find_by_name(form.username.data) if staff and check_password_hash(staff.password_hash, form.password.data): login_user(staff) elif user and check_password_hash(user.password_hash, form.password.data): login_user(user) else: return render_error_page_wrong_password() next = request.args.get("next") if not next: next = url_for("web.index") # solve admin login redirect to account bug if staff and staff.role == 'admin': next = url_for("web.index") return redirect(next) return render_template("login.html", form=form)
def put(self): data = self.user_parser.parse_args() user = UserModel.find_by_name(data["username"]) if not user: return { "message": "user:{} not found".format(data["username"]) }, 404 # auth group: user account owner, admin # all staffs are user with wrong id are unauthorized identity = get_jwt_identity() if identity["auth_level"] == "staff" or ( identity["auth_level"] == "user" and identity["id"] != user.id): return {"message": "unauthorized access"}, 500 # authorized: admin, user account owner user.email = data["email"] try: user.save_to_db() return {"message": "user info updated succesfully."}, 200 except: return {"message": "something went wrong."}
def post(self): data = self.parser.parse_args() if data['email'] not in email_confirm_table.keys(): return { "message": "no reset code associates with email {}".format(data['email']) }, 404 if data['reset_code'] == email_confirm_table[data['email']]: # del email_confirm_table[data['email']] user = UserModel.find_by_email(data['email']) if user: user.password_hash = generate_password_hash( data['new_password']) user.save_to_db() return { "message": "password updated successfully for {}".format( user.username) }, 200 else: return { "message": "user with email {} not found.".format(data['email']) }, 404 else: return {"message": "Incorrect reset code."}, 401
def post(self): data = self.user_parser.parse_args() user = UserModel.find_by_username(data['username']) if not user: return {"message": "username does not exist."}, 404 if check_password_hash(user.password_hash, data['password']): identity = {"role": user.role, "id": user.id} access_token = create_access_token(identity=identity, fresh=True, expires_delta=self.expires) refresh_token = create_refresh_token(identity=identity) return { "message": "Succesfully logged in", "role": user.role, "id": user.id, "username": user.username, "email": user.email, "profile_img": user.profile_img, "reg_date": str(user.date), "access_token": access_token, "refresh_token": refresh_token } else: return {"message": "wrong credentials."}, 401
def load_user(user_id): role = user_id.split("_")[0] _id = user_id.split("_")[1] if role == "staff": return StaffModel.find_by_id(int(_id)) if role == "user": return UserModel.find_by_id(int(_id))
def user_close_account(): user_id = request.args.get("user_id") user= UserModel.find_by_id(user_id) if user: user.delete_from_db() return redirect(url_for("web.index"))
def delete(cls, user_id): user = UserModel.find_by_id(user_id) if user: user.delete_from_db() return { 'message': f"User with id '{user_id}' deleted successfully" }, 200 return {'message': f"User with id '{user_id}' not found"}, 404
def user_account(): if is_user(current_user): user_id = current_user.id else: user_id = request.args.get("user_id", type=int) user = UserModel.find_by_id(user_id) return render_template("user_account.html", user=user)
def post(self): data = self.user_parser.parse_args() user = UserModel.find_by_name(data["username"]) if user: return {"message": "username:already exists"}, 400 user = UserModel(generate_password_hash(data["password"]), data["username"], data["email"]) try: user.save_to_db() identity = {"auth_level": "user", "id": user.id} access_token = create_access_token(identity=identity) refresh_token = create_refresh_token(identity=identity) return { "message": "User created successfully.", "access_token": access_token, "refresh_token": refresh_token }, 201 except: return {"message": "something went wrong."}, 500
def post(self): email = self.parser.parse_args()['email'] user = UserModel.find_by_email(email=email) if user: confirm_email_owner(username=user.username, recipient=email) return { "message": "password reset code emailed to {}".format(email) }, 200 else: return { "message": "no user with email {} can be found.".format(email) }, 404
def user_list (): # no access to users(customers) if is_user(current_user): return render_error_page_unauthorized_access() # admin sees all users if is_admin(current_user): users = UserModel.find_all() # company_admin and staff sees all users of their company if is_company_admin or is_staff: pass page = request.args.get("page", 1, type=int) users = users.paginate(page=page, per_page=5) return render_template("user_list.html", users=users)
def post(self): data = self.user_parser.parse_args() user = UserModel.find_by_name(data["username"]) if not user: return {"message": "username does not exist."}, 404 if check_password_hash(user.password_hash, data["password"]): identity = {"auth_level": "user", "id": user.id} access_token = create_access_token(identity=identity, fresh=True) refresh_token = create_refresh_token(identity=identity) return { "message": "Logged in as {}".format(user.name), "access_token": access_token, "refresh_token": refresh_token } else: return {"message": "wrong credentials."}
def post(self): data = self.user_parser.parse_args() user = UserModel.find_by_name(data["username"]) if not user: return { "message": "user:{} not found".format(data["username"]) }, 404 # auth group: user account owner, admin identity = get_jwt_identity() if identity["auth_level"] == "user" and identity["id"] != user.id: return { "message": "unauthorized access, user is only allowed to view his/her own account info" }, 500 if identity["auth_level"] == "staff": return {"message": "unauthorized access for staff."}, 500 return user.json(), 200
def post(self): data = self.parser.parse_args() role = "USER" profile_img = "0" # str type, 0~99 preset images password_hash = generate_password_hash(data["password"]) user = UserModel.find_by_username(data["username"]) if user: return {"message": "username already exists."}, 400 user = UserModel.find_by_email(data["email"]) if user: return {"message": "email already exists."}, 400 user = UserModel(role=role, username=data["username"], password_hash=password_hash, email=data["email"], profile_img=profile_img) try: user.save_to_db() identity = {"role": user.role, "id": user.id} registration_confirmation(username=user.username, recipient=user.email) access_token = create_access_token(identity=identity, fresh=True, expires_delta=self.expires) refresh_token = create_refresh_token(identity=identity) except: return { "message": "something went wrong during user registration." }, 500 return { "message": "user registered!", "role": user.role, "id": user.id, "username": user.username, "email": user.email, "profile_img": user.profile_img, "reg_date": str(user.date), "access_token": access_token, "refresh_token": refresh_token }, 201
def post(self): user_id = int(get_jwt_identity()['id']) user = UserModel.find_by_id(id=user_id) data = self.parser.parse_args() if data['new_email']: user.email = data['new_email'] if data["new_profile_img"]: user.profile_img = data['new_profile_img'] if data["old_password"] and data["new_password"]: if check_password_hash(user.password_hash, data['old_password']): user.password_hash = generate_password_hash( data['new_password']) else: return {"message": "old password doesn't match record."}, 401 try: user.save_to_db() except: return { "message": "something wrong happened updating database." }, 500 return {"message": "profile updated successfully."}
def user_update(): if is_staff(current_user) or is_company_admin(current_user): return render_error_page_unauthorized_access() if is_user(current_user): user_id = current_user.id elif is_admin(current_user): user_id = request.args.get("user_id") user = UserModel.find_by_id(user_id) form = UserUpdateForm() if form.validate_on_submit(): user.email=form.email.data user.phone = form.phone.data user.password_hash = generate_password_hash(form.password.data) user.save_to_db() return render_template("user_account.html", user=user) form.email.data = user.email form.phone.data = user.phone return render_template("user_update.html", form=form)
def delete(self): data = self.user_parser.parse_args() user = UserModel.find_by_name(data["username"]) if not user: return { "message": "user:{} not found".format(data["username"]) }, 404 # auth group: user account owner, admin # all staffs and user with wrong id are unauthorized identity = get_jwt_identity() if identity["auth_level"] == "staff" or ( identity["auth_level"] == "user" and identity["id"] != user.id): return {"message": "unauthorized access"}, 500 # authorized: admin, user account owner try: user.delete_from_db() return {"message": "user:{} deleted".format(data["username"])}, 200 except: return {"message": "something went wrong"}
def validate_username(self, username): if UserModel.find_by_name(username.data): raise ValidationError("your username has been registered.")
return compiler.visit_drop_table(element) + " CASCADE" db.drop_all() from rest_api.models.video import VideoModel # noqa from rest_api.models.user import UserModel # noqa from rest_api.models.comment import CommentModel # noqa from rest_api.models.jwt import RevokedTokenModel # noqa from rest_api.models.rating import RatingModel # noqa db.create_all() #### init db with essential data #### # create first user as admin admin = UserModel(role='admin', username='******', password_hash= generate_password_hash('admin_password'), email='*****@*****.**', profile_img='0') admin.save_to_db() print('...admin created') # create second user as guest guest = UserModel(role='guest', username='******', password_hash= generate_password_hash('guest_password'), email='*****@*****.**', profile_img='0') guest.save_to_db() print ('...guest created')
def get(cls, user_id): user = UserModel.find_by_id(user_id) if user: return user.json() return {'message': f"User with id '{user_id}' not found"}, 404
def authenticate(username, password): user = UserModel.find_by_username(username) if user and safe_str_cmp(user.password, password): return user
def identity(payload): user_id = payload['identity'] return UserModel.find_by_id(user_id)
def validate_email(self, email): if UserModel.find_by_email(email.data): raise ValidationError("your email has been registered.")
def validate_username(self, username): if (not UserModel.find_by_name(username.data)) and ( not StaffModel.find_by_name(username.data)): raise ValidationError("username doesn't exist.")