301 lines
11 KiB
Python
301 lines
11 KiB
Python
from flask import session, jsonify
|
|
from app.utils.logger import logger
|
|
from app.api.services.base_service import BaseService
|
|
from marshmallow import ValidationError
|
|
from app.extensions import db
|
|
from app.models import Offer, MembersPending, Members
|
|
from app.api.helpers.response_helper import ResponseHelper
|
|
from werkzeug.security import generate_password_hash, check_password_hash
|
|
|
|
from app.api.schemas.register import RegisterSchema
|
|
from app.api.schemas.register_verify import RegisterVerifySchema
|
|
from app.api.schemas.register_complete import RegisterCompleteSchema
|
|
|
|
from app.api.services.login import LoginService
|
|
|
|
from flask_mail import Mail, Message
|
|
import smtplib
|
|
from email.mime.text import MIMEText
|
|
from email.mime.multipart import MIMEMultipart
|
|
|
|
|
|
import datetime
|
|
import jwt
|
|
import random
|
|
from app.config import Config
|
|
|
|
|
|
class RegisterService(BaseService):
|
|
JWT_SECRET_KEY = Config.JWT_SECRET_KEY
|
|
|
|
SEND_EMAIL_FROM = Config.SEND_EMAIL_FROM
|
|
SEND_EMAIL_PASS = Config.SEND_EMAIL_PASS
|
|
THIS_SITE_URL = Config.THIS_SITE_URL
|
|
|
|
@staticmethod
|
|
def encrypt_password(self, password):
|
|
"""Encrypt password"""
|
|
return generate_password_hash(password)
|
|
|
|
@staticmethod
|
|
def process_complete(data):
|
|
try:
|
|
with db.session.begin():
|
|
|
|
validated_data = RegisterService.validate_data(data, RegisterCompleteSchema())
|
|
# Simulate processing
|
|
verify_link = validated_data.get('verify_link')
|
|
username = validated_data.get('username')
|
|
password = validated_data.get('password')
|
|
country = validated_data.get('country')
|
|
|
|
data ={}
|
|
if not verify_link:
|
|
return jsonify({'message': 'Error - missing verify link'}), 403
|
|
try:
|
|
data = jwt.decode(verify_link, RegisterService.JWT_SECRET_KEY, algorithms=["HS256"])
|
|
except:
|
|
return jsonify({'status': 'INVALID', 'message': 'Link is invalid'}), 403
|
|
|
|
previousAcc = Members.get_member_by_username(username)
|
|
if previousAcc:
|
|
response_data = {
|
|
"error_message": "try another username ",
|
|
"error_message_key": "use_another_username",
|
|
}
|
|
return ResponseHelper.error(data=response_data)
|
|
user= data["user"]
|
|
firstname = user['first_name']
|
|
lastname = user['last_name']
|
|
email = user['email']
|
|
|
|
encrypted_pass = generate_password_hash(password)
|
|
newAccount = Members.add_member(firstname, lastname, email, username,encrypted_pass, country)
|
|
|
|
return LoginService.login_user(username,password)
|
|
|
|
# country = {
|
|
# "last_update": datetime.datetime.utcnow(),
|
|
# "list": [
|
|
# {"code": "US", "description": "United States"},
|
|
# {"code": "CA", "description": "Canada"},
|
|
# ]
|
|
# }
|
|
#
|
|
# response_data = {
|
|
# "user": data["user"],
|
|
# "country": country,
|
|
# }
|
|
#
|
|
# return ResponseHelper.success(data=response_data)
|
|
|
|
except ValidationError as err:
|
|
|
|
logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}")
|
|
db.session.rollback()
|
|
return ResponseHelper.unprocessable_entity(result_description="Validation exception")
|
|
|
|
except ValueError as err:
|
|
logger.error(f"{getattr(err, 'messages', str(err))}")
|
|
db.session.rollback()
|
|
return ResponseHelper.error(result_description=str(err))
|
|
|
|
except Exception as e:
|
|
logger.error(f"An error occurred: {str(e)}", exc_info=True)
|
|
db.session.rollback()
|
|
return ResponseHelper.internal_server_error()
|
|
|
|
|
|
@staticmethod
|
|
def process_verify(data):
|
|
#"verify_link": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiMThmYzg0YTQtYjQzMC00ZWFkLWE4ZjEtMTk2MTJmNzA5ZDE0IiwiZXhwIjoxNzUyMjc2NjQzfQ.UEsSpCkMq8xNTLiqzyCB572tK-9WkeYaSBF4gfvX7vk"
|
|
try:
|
|
with db.session.begin():
|
|
|
|
validated_data = RegisterService.validate_data(data, RegisterVerifySchema())
|
|
# Simulate processing
|
|
verify_link = validated_data.get('verify_link')
|
|
data ={}
|
|
if not verify_link:
|
|
return jsonify({'message': 'Error - missing verify link'}), 403
|
|
try:
|
|
data = jwt.decode(verify_link, RegisterService.JWT_SECRET_KEY, algorithms=["HS256"])
|
|
except:
|
|
return jsonify({'status': 'INVALID', 'message': 'Link is invalid'}), 403
|
|
|
|
country = {
|
|
"last_update": datetime.datetime.utcnow(),
|
|
"list": [
|
|
{"code": "US", "description": "United States"},
|
|
{"code": "CA", "description": "Canada"},
|
|
]
|
|
}
|
|
|
|
response_data = {
|
|
"user": data["user"],
|
|
"country": country,
|
|
}
|
|
|
|
return ResponseHelper.success(data=response_data)
|
|
|
|
except ValidationError as err:
|
|
|
|
logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}")
|
|
db.session.rollback()
|
|
return ResponseHelper.unprocessable_entity(result_description="Validation exception")
|
|
|
|
except ValueError as err:
|
|
logger.error(f"{getattr(err, 'messages', str(err))}")
|
|
db.session.rollback()
|
|
return ResponseHelper.error(result_description=str(err))
|
|
|
|
except Exception as e:
|
|
logger.error(f"An error occurred: {str(e)}", exc_info=True)
|
|
db.session.rollback()
|
|
return ResponseHelper.internal_server_error()
|
|
|
|
|
|
@staticmethod
|
|
def process_request(data):
|
|
try:
|
|
with db.session.begin():
|
|
|
|
validated_data = RegisterService.validate_data(data, RegisterSchema())
|
|
# Simulate processing
|
|
firstname = validated_data.get('firstname')
|
|
lastname = validated_data.get('lastname')
|
|
email = validated_data.get('email')
|
|
|
|
regData = MembersPending.add_members_pending( firstname, lastname, email)
|
|
send_register_mail(regData.email, regData.uid, regData.id, firstname, lastname)
|
|
|
|
response_data = {
|
|
"pending_id": regData.id,
|
|
"pending_uid": regData.uid,
|
|
}
|
|
|
|
return ResponseHelper.success(data=response_data)
|
|
|
|
except ValidationError as err:
|
|
|
|
logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}")
|
|
db.session.rollback()
|
|
return ResponseHelper.unprocessable_entity(result_description="Validation exception")
|
|
|
|
except ValueError as err:
|
|
logger.error(f"{getattr(err, 'messages', str(err))}")
|
|
db.session.rollback()
|
|
return ResponseHelper.error(result_description=str(err))
|
|
|
|
except Exception as e:
|
|
logger.error(f"An error occurred: {str(e)}", exc_info=True)
|
|
db.session.rollback()
|
|
return ResponseHelper.internal_server_error()
|
|
|
|
|
|
def send_register_mail(signup_email, pending_uid,pending_id,firstname, lastname):
|
|
|
|
pending_member = {
|
|
"email": signup_email,
|
|
"pending_uid": pending_uid,
|
|
"first_name": firstname,
|
|
"last_name": lastname,
|
|
"pending_id":pending_id,
|
|
}
|
|
jwt_part = jwt.encode(
|
|
{"user": pending_member, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=3330)},
|
|
RegisterService.JWT_SECRET_KEY, algorithm='HS256'
|
|
)
|
|
panel_url = panel_url = RegisterService.THIS_SITE_URL # "https://qa-panel.mermsemr.com"
|
|
link_url= str(panel_url) + '/csignup/' + jwt_part
|
|
|
|
msg_body = f"""
|
|
Hello {firstname},
|
|
|
|
You received this message for account verification
|
|
|
|
Follow the link:{link_url}
|
|
|
|
For any Support
|
|
Reach Out
|
|
support@mermsemr.com
|
|
"""
|
|
|
|
sender_email = RegisterService.SEND_EMAIL_FROM
|
|
sender_password = RegisterService.SEND_EMAIL_PASS
|
|
receiver_email = signup_email
|
|
subject = "Verify your MERMS(AI) Account Setup"
|
|
body = msg_body
|
|
|
|
|
|
msg = MIMEMultipart()
|
|
msg['Subject'] = subject
|
|
msg['From'] = sender_email
|
|
msg['To'] = receiver_email
|
|
msg.attach(MIMEText(body, 'plain')) # or 'html' for HTML content
|
|
|
|
try:
|
|
# For Gmail, use 'smtp.gmail.com' and port 587 (TLS) or 465 (SSL)
|
|
# For other providers, consult their documentation for SMTP server and port
|
|
server = smtplib.SMTP('smtp.gmail.com', 587)
|
|
# server.starttls() # Enable TLS encryption
|
|
server.login(sender_email, sender_password)
|
|
server.sendmail(sender_email, receiver_email, msg.as_string())
|
|
print("Email sent successfully!")
|
|
except Exception as e:
|
|
print(f"Error sending email: {e}")
|
|
logger.error(f"Error sending email: {e}")
|
|
finally:
|
|
server.quit() # Close the connection
|
|
|
|
#
|
|
# signup_data = {}
|
|
# signup_data["id"] = last_row_id
|
|
# signup_data["uid"] = email_uid
|
|
# #'d8651e10-3279-4858-87da-b52936faa6f0'
|
|
#
|
|
# jwt_part = jwt.encode(
|
|
# {"user": signup_data, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=3330)},
|
|
# RegisterService.JWT_SECRET_KEY, algorithm='HS256'
|
|
# )
|
|
# panel_url = "www.me.com"
|
|
# link_url= str(panel_url) + '/csignup/' + jwt_part
|
|
# print(link_url)
|
|
# #firstname ='Name001'
|
|
# msg = Message(
|
|
# 'verify your MERMS Account',
|
|
# sender ='message@chiefsoft.com',
|
|
# recipients = [signup_email,'ameye+merscopy@chiefsoft.com']
|
|
# )
|
|
# msg.body = f"""
|
|
# Hello {firstname},
|
|
# You received this message for account verification
|
|
#
|
|
# Follow the link:{link_url}
|
|
#
|
|
# For any Support
|
|
# Reach Out
|
|
# """
|
|
#
|
|
# mail.send(msg)
|
|
|
|
# mail = Mail(app) # instantiate the mail class
|
|
#
|
|
# # configuration of mail
|
|
# app.config['MAIL_SERVER'] = 'smtp.gmail.com'
|
|
# app.config['MAIL_PORT'] = 465
|
|
# # app.config['MAIL_PORT'] = 587
|
|
# app.config['MAIL_USERNAME'] = 'message@chiefsoft.com'
|
|
# app.config['MAIL_PASSWORD'] = 'may12002!'
|
|
# app.config['MAIL_USE_TLS'] = False
|
|
# app.config['MAIL_USE_SSL'] = True
|
|
# mail = Mail(app)
|
|
|
|
|
|
|
|
# {
|
|
# "email": "ameye@chiefsoft.com",
|
|
# "firstname": "Olusesan",
|
|
# "lastname": "Ameye",
|
|
# "isChecked": true
|
|
# } |