def editprofile(): user_id = current_user.get_id() if not user_id: abort(403) user = User.query.filter_by(id=user_id).first() if not user: abort(404) user_data = request.form['user'] user_data = json.loads(user_data) if 'id' in user_data or 'username' in user_data or 'email' in user_data: abort(400) if 'file' not in request.files: picture_path = user.image_file else: file = request.files['file'] picture_path = save_picture(file) hashed_password = bcrypt.generate_password_hash( user_data['password']).decode('utf-8') user.first_name = user_data['firstname'] user.last_name = user_data['lastname'] user.password = hashed_password user.bio = user_data['bio'] user.image_file = picture_path db.session.commit() return make_response((jsonify({'ok': 'profile edited'})), 200)
def register(): if current_user.is_authenticated: abort(400) data = request.get_json() if not data or not 'password' in data or not 'username' in data or not 'first_name' in data \ or not 'last_name' in data or not 'gender' in data or not 'birth_date' in data or not 'email' in data: abort(400) check_user = User.query.filter_by(email=data['email']).first() if check_user: return 'Email Taken' check_user = User.query.filter_by(username=data['username']).first() if check_user: return 'Username Taken' hashed_password = bcrypt.generate_password_hash( data['password']).decode('utf-8') user = User(username=data['username'], first_name=data['first_name'], last_name=data['last_name'], gender=data['gender'], birth_date=datetime.datetime.now(), email=data['email'], password=hashed_password) db.session.add(user) db.session.commit() return 'Created'
def register(): if current_user.is_authenticated: abort(403) data = request.form['user'] data = json.loads(data) if not data or not 'password' in data or not 'username' in data or not 'firstname' in data \ or not 'lastname' in data or not 'email' in data or not 'bio' in data: abort(400) check_user = User.query.filter_by(email=data['email']).first() if check_user: return make_response((jsonify({'error': 'email taken'})), 400) check_user = User.query.filter_by(username=data['username']).first() if check_user: return make_response((jsonify({'error': 'username taken'})), 400) if 'file' in request.files: file = request.files['file'] picture_saved_name = save_picture(file) else: picture_saved_name = "" hashed_password = bcrypt.generate_password_hash( data['password']).decode('utf-8') user = User(username=data['username'], first_name=data['firstname'], last_name=data['lastname'], email=data['email'], password=hashed_password, bio=data['bio'], image_file=picture_saved_name) db.session.add(user) db.session.commit() return make_response((jsonify({'ok': 'account created'})), 200)
def normal_register(): request_json = request.get_json() print(request_json) if request_json.get('isSnap'): user = User(email="*****@*****.**", password="******", name=request_json['name'], isSnap=True, snapPic=request_json['snapPic']) db.session.add(user) db.session.commit() return json.dumps({'id': user.id, 'status': 0}) if User.query.filter_by(email=request_json['email']).first(): return json.dumps({ 'status': 1, 'output': User.query.filter_by(email=request_json['email']).first().email, 'error': "User Already Exists" }) email = request_json['email'] hashed_pwd = bcrypt.generate_password_hash( request_json['password']).decode('utf-8') name = request_json['name'] # noinspection PyArgumentList user = User(email=email, password=hashed_pwd, name=name) db.session.add(user) db.session.commit() return json.dumps({'id': user.id, 'status': 0})
def normal_register(): request_json = request.get_json() if User.query.filter_by(email=request_json['email']).first(): return json.dumps({ 'status': 0, 'output': User.query.filter_by(email=request_json['email']).first().email, 'error': "User Already Exists" }) elif User.query.filter_by(gt_id=request_json['gt_id']).first(): return json.dumps({ 'status': 0, 'error': "The provided GeorgiaTech ID is already registered." }) email = request_json['email'] hashed_pwd = bcrypt.generate_password_hash( request_json['password']).decode('utf-8') name = request_json['name'] gt_id = request_json['gt_id'] # noinspection PyArgumentList user = User(email=email, password=hashed_pwd, name=name, gt_id=gt_id, isAdmin=False) db.session.add(user) db.session.commit() return json.dumps({'id': user.id, 'status': 1})
def resetPassword(): body = request.get_json(force=True) # Grab the verification token from the query parameter resetToken = body['reset_token'] password = body['password'] if resetToken == None: return {"error": "No reset_token present in query parameter"}, 400 # Check that the reset_token belongs to the email user = User.query.filter_by(reset_token=resetToken).first() if user == None: return {"error": "Invalid reset_token or email"}, 404 # If it does, then we set the password field to the new password, and remove the reset_token user.reset_token = '' # Encrypt the password encodedPassword = bcrypt.generate_password_hash(password).decode( encoding="utf-8") user.password = encodedPassword db.session.commit() db.session.close() # Redirect to the frontend homepage return {"success": True}
def post(self): url = "http://optical.cs.ucdavis.edu/" # url = "http://*****:*****@gmail.com', recipients=[email]) msg.body = ( "Hey Fort Nitta user,\n\n" + " To verify your account, please visit the following link:\n " + url + "#home/verifyemail?" + "user="******"&tok=" + hash_token + "\n\nAll the best,\n" + "Fort Nitta Team,\n" + url) mail.send(msg) return jsonify(**{'success': True}) return jsonify(**{'success': False}), 401 return jsonify(**{'success': False}), 401
def __init__(self, email, username, password): """ This function initializes this model. This function is necessary since we are hashing the user's password before storing it into the database. """ self.email = email self.username = username # Protecting the user's password using a hash function self.password = bcrypt.generate_password_hash(password.encode('utf-8'))
def reset_password(): request_json = request.get_json() user = User.verify_reset_token(request_json['token']) if user is None: return json.dumps({'status': 0, 'error': "Sorry, the link is invalid or has expired. Please submit password reset request again."}) else: hashed_pwd = bcrypt.generate_password_hash(form.password.data).decode('utf-8') user.password = hashed_pwd db.session.commit() return json.dumps({'status': 1})
def create_user(cls, email: str, password: str) -> 'User': encrypted_pass = bcrypt.generate_password_hash(password).decode( 'utf-8') user = cls(email=email, password=encrypted_pass) try: db.session.add(user) db.session.commit() except sqlalchemy.exc.IntegrityError: flask.abort(409, "User with this email aleady exists.") return user
def add_company_user(): request_json = request.get_json() auth_token = request_json['auth_token'] user = User.verify_auth_token(auth_token) if user is None: return json.dumps({ 'status': 0, 'error': "Session expired. Please login again." }) elif not user.isMaster: return json.dumps({'status': 0, 'error': "Access Denied"}) company_id = request_json['company_id'] company = Company.query.filter_by(id=company_id).first() name = request_json['name'] designation = request_json['designation'] email = request_json['email'] random_password = ''.join( random.choices(string.ascii_uppercase + string.digits + string.ascii_lowercase + string.punctuation, k=8)) msg = Message("Welcome to Helpify Corporate", sender="*****@*****.**", recipients=[email], body=f""" Hi {name}, Thanks for your interest in working with us over the upcoming event! We have created a user account for you under the company {company.name}. You may log in by going to {current_app.config['CURRENT_URL']}. Your username is the email address on which you received this email, and your password is: {random_password} Please feel free to contact us in case of any queries. We look forward towards meeting you at the event! Regards, Helpify Corporate Team (on behalf of the event organizers) """) mail.send(msg) hashed_pwd = bcrypt.generate_password_hash(random_password).decode('utf-8') new_user = User(name=name, email=email, password=hashed_pwd, isAdmin=True, company_id=company.id, designation=designation) db.session.add(new_user) db.session.commit() return json.dumps({'status': 1})
def signup(): try: username = request.form.get('username') email = request.form.get('email') password = request.form.get('password') if not username or not password or not email: return jsonify({ "status": 401, "field": "common", "msg": "All fields are required!" }) hashed_pwd = bcrypt.generate_password_hash(password).decode('utf-8') if User.query.filter_by(username=username).first(): # user with username exists return jsonify({ "status": 409, "field": "username", "msg": "Username already exists..." }), 409 elif User.query.filter_by(email=email).first(): # user with that email exists return jsonify({ "status": 409, "field": "email", "msg": "Email already exists..." }), 409 else: # New user user = User(username=username, email=email, password=hashed_pwd) db.session.add(user) db.session.commit() return jsonify({ "status": 200, "field": "success", "msg": "Your account has been succesfully created! Please Login to Continue..." }) except: return jsonify({ "status": 500, "field": "common", "msg": "Oops, Some error happened!" }), 500
def __init__(self, firstname, lastname, usertype, email, education, major, gender, about, password): """ This function initializes this model. This function is necessary since we are hashing the user's password before storing it into the database. """ self.firstname = firstname self.lastname = lastname self.usertype = usertype self.email = email self.education = education self.major = major self.gender = gender self.about = about # Protecting the user's password using a hash function self.password = bcrypt.generate_password_hash(password)
def register(): if current_user.is_authenticated: return redirect(url_for('home')) form = RegisterForm() if form.validate_on_submit(): try: if contract.function.insertUser(form.eth_address.data ,form.username, "owner" ).call(): hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8') user = User(username=form.username.data, eth_address=form.eth_address.data, password=hashed_password) db.session.add(user) db.session.commit() flash('Your account has been created! You are now able to log in', 'success') return redirect(url_for('login')) except: flash("Error occured while processing please try again " ,'danger') return render_template('main.html' , form=form) return render_template('main.html', title='Register', form=form)
def register(token): if current_user.is_authenticated: return redirect(url_for('home')) req_id = RequestID.verify_request_token(token) if req_id is None: flash('That is an invalid or expired token', 'warning') return redirect(url_for('request_account')) form = RegistrationForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8') user = User(username=form.username.data, email=req_id.email, password=hashed_password) db.session.add(user) db.session.commit() send_database() send_credential(user,form) flash('Account has been created! Credentials are sent to user by email! User is now able to log in', 'success') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
def normal_register(): """ Enables user registration by adding the user to the database. Method Type ----------- POST JSON Parameters --------------- name : str name of the user email : str email of the user password : str (un-hashed) password of the user Restrictions ------------ User must not already be registered JSON Returns ------------ status : int Status code representing success status of the request message : str Message explaining the response status """ request_json = request.get_json() print("Yo!") name = request_json['name'] email = request_json['email'] password = request_json['password'] hashed_password = bcrypt.generate_password_hash(password).decode('utf-8') existing_user = User.query.filter_by(email=email).first() if existing_user is not None: return json.dumps({'status': 2, 'message': "User Already Exists"}) user = User(name=name, email=email, password=hashed_password) db.session.add(user) db.session.commit() return json.dumps({ 'status': 0, 'message': "User account created successfully" })
def normal_register(): if current_user.is_authenticated: return redirect(url_for('events.generate')) form = RegistrationForm() if User.query.filter_by(email=form.email.data).first(): flash("User Already Exists", 'danger') else: if form.validate_on_submit(): email = form.email.data hashed_pwd = bcrypt.generate_password_hash(form.password.data).decode('utf-8') name = form.name.data user = User(email=email, password=hashed_pwd, name=name, isAdmin=False) db.session.add(user) db.session.commit() flash(f'Account created for {user.name}.', 'success') return redirect(url_for('users.login')) return render_template('register.html', title='Register', form=form)
def reset_password(): """ Resets password of the user Method Type ----------- POST JSON Parameters --------------- token : str Verification token to authenticate the user password : str New password of the user Restrictions ------------ Verification token must not be expired Tokens expire 30 minutes after they are issued. JSON Returns ------------ status : int Status code representing success status of the request message : str Message explaining the response status """ request_json = request.get_json() user = User.verify_reset_token(request_json['token']) if user is None: return json.dumps({ 'status': 1, 'error': "Sorry, the link is invalid or has expired." + " Please submit password reset request again." }) else: hashed_pwd = bcrypt.generate_password_hash( request_json['password']).decode('utf-8') user.password = hashed_pwd db.session.commit() return json.dumps({ 'status': 0, 'message': "Password Reset Successfully" })
def register(): if current_user.is_authenticated: return redirect(url_for("home")) form = RegistrationForm() # if the data is valid then flash a success prompt if form.validate_on_submit(): # Hash the registration password with bcrypt hashed_pw = bcrypt.generate_password_hash( form.password.data).decode("utf-8") user = User(username=form.username.data, email=form.email.data, password=hashed_pw) db.session.add(user) db.session.commit() flash(f"Your account has been created! You are now able to login", "success") return redirect(url_for("login")) return render_template("register.html", title="Register", form=form)
def reset_token(token): if current_user.is_authenticated: return redirect(url_for("home")) user = User.verify_reset_token(token) if user is None: flash("That is an invalid or expired token", "warning") return redirect(url_for("reset_request")) form = ResetPasswordForm() if form.validate_on_submit(): # Hash the registration password with bcrypt hashed_pw = bcrypt.generate_password_hash( form.password.data).decode("utf-8") user.password = hashed_pw db.session.commit() flash(f"Your password has been updated! You are now able to login", "success") return redirect(url_for("login")) return render_template("reset_token.html", title="Reset Password", form=form)
def add_company_recruiter(): request_json = request.get_json() auth_token = request_json['auth_token'] user = User.verify_auth_token(auth_token) if user is None: return json.dumps({ 'status': 0, 'error': "Session expired. Please login again." }) elif not user.isAdmin: return json.dumps({'status': 0, 'error': "Access Denied"}) elif User.query.filter_by( company_id=user.company_id).count() >= Company.query.filter_by( id=user.company_id).first().num_reps: return json.dumps({ 'status': 0, 'error': "Max Representatives Reached. Please contact event organizer for help." }) company_id = user.company_id company = Company.query.filter_by(id=company_id).first() name = request_json['name'] email = f"{name}@{company.name}.com" random_password = ''.join( random.choices(string.ascii_uppercase + string.digits + string.ascii_lowercase + string.punctuation, k=8)) hashed_pwd = bcrypt.generate_password_hash(random_password).decode('utf-8') new_user = User(name=name, email=email, password=hashed_pwd, isAdmin=True, company_id=company.id, designation="Recruiter") db.session.add(new_user) db.session.commit() return json.dumps({'status': 1})
def set_password(self, password): self.password = bcrypt.generate_password_hash(password)
def normal_register(): request_json = request.get_json() if User.query.filter_by(email=request_json['email']).first(): return json.dumps({ 'status': 0, 'output': User.query.filter_by(email=request_json['email']).first().email, 'error': "User Already Exists" }) email = request_json['email'] hashed_pwd = bcrypt.generate_password_hash( request_json['password']).decode('utf-8') fname = request_json['fname'] lname = request_json['lname'] address_line_1 = request_json['address_line_1'] city = request_json['city'] state = request_json['state'] zip_code = request_json['zip_code'] phone_num = request_json['phone_num'] acc_num = request_json['acc_num'] # noinspection PyArgumentList user = User(email=email, password=hashed_pwd, fname=fname, lname=lname, address_line_1=address_line_1, city=city, state=state, zip_code=zip_code, phone_num=phone_num, acc_num=acc_num, isAdmin=False) db.session.add(user) db.session.commit() cust_data = { "address": { "city": user.city, "line1": user.address_line_1, "state": user.state, "zip": user.zip_code }, "fundingAccount": { "ddaAccount": { "accountNumber": user.acc_num, "accountType": "Checking", "rtn": "044000037" }, "nickName": f"{user.fname} {user.lname}" }, "email": user.email, "externalCustomerIdentifier": user.id, "mode": "initiate", "personName": { "firstName": user.fname, "lastName": user.lname }, "phone1": user.phone_num, "requestID": user.id } endpoint_url = 'Payments/Customers' headers = { "apiKey": os.environ['FISERV_API_KEY'], "businessID": os.environ['BUSINESS_ID'] } request_data = requests.post( f"https://certwebservices.ft.cashedge.com/sdk/{endpoint_url}", headers=headers, json=cust_data) try: user.cust_id = request_data.json()['customerID'] except Exception: raise Exception(f"{request_data.json()}") user.acc_id = request_data.json()['fundingAccount']['accountID'] db.session.commit() return json.dumps({'id': user.id, 'status': 1})
def signUp(): body = request.get_json(force=True) # trim the email to remove unnecessary spaces email = body['email'].strip() # convert input email to lowercase email = email.lower() # Validate that the email is the correct format try: v = validate_email(email) # validate and get info email = v["email"] # replace with normalized form except EmailNotValidError as e: # email is not valid, return error code return { "error": "Invalid Email Format" }, 406 # Encrypt the password encodedPassword = bcrypt.generate_password_hash(body['password']).decode(encoding="utf-8") # Check that they've passed a valid role try: role = body['role'] if role != Role.CLIENT.name and role != Role.COACH.name: return { "error": "Expected role of COACH or CLIENT" }, 400 except: return { "error": "Expected role of COACH or CLIENT" }, 400 # Create the user with the encoded password user = User( first_name=body['first_name'], last_name=body['last_name'], email=email, password=encodedPassword, approved=False, role=body['role'], verified=False ) # Create an album in imgur if we aren't being run by a test create_album = True if 'test' in body: if body['test'] == True: create_album = False if create_album: album_id, album_deletehash, code = createAlbum() if code != 200: print("Failed to create imgur album for user with code: " + str(code)) return { "error": "Internal Server Error" }, 500 user.album_id = album_id user.album_deletehash = album_deletehash try: db.session.add(user) db.session.commit() except IntegrityError: return { "error": "Duplicate Email" }, 409 except Exception as e: print(e) return { "error": "Internal Server Error" }, 500 raise # Refresh the user to grab the id db.session.refresh(user) # Grab the user from the database and dump the result into a user schema user = User.query.get(user.id) # Generate a new access token # encode own token and put it in session before calling the endpoint token = user.encode_auth_token({ 'id': user.id, 'role': user.role }) if isinstance(token, Exception): print(token) # This is printed as an error db.session.rollback() return { "error": "Internal Server Error" }, 500 # Generate a new verification token verificationToken = str(uuid.uuid1()) # Update the users access_token and verification_token and commit the result user.access_token = token user.verification_token = verificationToken db.session.commit() # Send a verification email err = sendVerificationEmail(mail, [user.email], user.first_name, user.last_name, str(verificationToken)) if err != None: print(err) db.session.rollback() return { "error": "Internal Server Error" }, 500 # Set the session access_token session['access_token'] = token result = user_schema.dump(user) # Delete the password from the response, we don't want to transfer this over the wire del result['password'] # Delete the access token and verification token as we don't want this to be in the resopnse del result['access_token'] del result['verification_token'] db.session.close() # Return the user return { "user": result }
def updateProfile(token_claims): body = request.get_json(force=True) # retrieve user with id passed in user = User() user = User.query.get(token_claims['id']) # check which parameters were passed into this function if 'email' in body: newEmail = True try: v = validate_email(body["email"]) # validate and get info email = v["email"] # replace with normalized form except EmailNotValidError as e: # email is not valid, return error code return { "error": "Invalid Email Format" }, 406 else: newEmail = False if 'first_name' in body: newFirstName = True else: newFirstName = False if 'last_name' in body: newLastName = True else: newLastName = False if 'newPassword' in body: # check that the current password field was entered if 'oldPassword' not in body: return{ "error": "User must enter old password" } # check that oldPassword matches the password in the database if not bcrypt.check_password_hash(user.password, body['oldPassword'].encode(encoding='utf-8')): return { "error": "The old password doesn't match the password in the database" }, 400 newPassword = True encodedPassword = bcrypt.generate_password_hash(body['newPassword']).decode(encoding="utf-8") else: newPassword = False # update the requested fields for this user try: if newEmail == True: user.email = email if newFirstName == True: user.first_name = body['first_name'] if newLastName == True: user.last_name = body['last_name'] if newPassword == True: user.password = encodedPassword db.session.commit() except Exception as e: return { "error": "Internal Server Error" }, 500 raise # Refresh the user to grab the id db.session.refresh(user) # Grab the user from the database and dump the result into a user schema user = User.query.get(user.id) result = user_schema.dump(user) # remove the sensitive data fields del result['password'] del result['access_token'] del result['verification_token'] # Return the user db.session.close() return { "user": result }
def add_new_kid(): """Adds a new kid account, links it to the database, and sends them their login credentials Method Type: POST Special Restrictions -------------------- User must be logged in User must be parent JSON Parameters --------------- auth_token : str Token to authorize the request - released when logging in kid_name : str Name of the kid being added kid_email : str Email of the kid being added init_amount : int Amount that needs to be transferred to the kid Returns ------- JSON status : int Tells whether or not did the function work - 1 for success, 0 for failure """ request_json = request.get_json() auth_token = request_json['auth_token'] user = User.verify_auth_token(auth_token) if user is None: return json.dumps({'status': 0, 'error': "User Not Authenticated"}) if not user.isParent: return json.dumps({'status': 0, 'error': "Access Denied"}) kid_name = request_json['kid_name'] kid_email = request_json['kid_email'] init_amount = request_json['init_amount'] # Create a Kid account using Nessie new_account_number = ''.join(random.choices(string.digits, k=16)) new_account_id = add_account(user.customerId, f"Kid Card - {kid_name}", 0, new_account_number) # Initiate a transfer between the parent account and the kid account using Nessie init_money_transfer_status = transfer_money(user.accountId, new_account_id, init_amount) if not init_money_transfer_status: return json.dumps({ 'status': 0, 'error': "The parent account does not have enough money." }) random_password = ''.join( random.choices(string.digits + string.ascii_uppercase, k=8)) hashed_pwd = bcrypt.generate_password_hash(random_password).decode('utf-8') kid_user = User(name=kid_name, email=kid_email, password=hashed_pwd, isParent=False, accountId=new_account_id, parent_id=user.id) db.session.add(kid_user) db.session.commit() # msg = Message('KidFin Login Credentials', sender='*****@*****.**', recipients=[kid_user.email]) # msg.body = f'''Hi {kid_name}, #You have been added by your parent to their account. You may now log in using the credentials listed below: #Username: {kid_email} #Password: {random_password} #Please be sure to keep this email secure. #Cheers, #KidFin Team''' # mail.send(msg) return json.dumps({ 'status': 1, 'message': "Account Created Successfully!", 'email': kid_email, 'password': random_password })
def hash_password(pw): return bcrypt.generate_password_hash(pw)
def hash_password(password): print(password) return bcrypt.generate_password_hash(password=password)