def recovery(request):
    global post_top_message
    authD.logout(request)
    if request.method == 'POST':
        recovery_form = forms.RecoveryForm(request.POST)
        if recovery_form.is_valid():
            Email = recovery_form.cleaned_data['Email']
            pyrebase_auth = pyrebase.auth()
            try:
                pyrebase_auth.send_password_reset_email(Email)
                post_top_message = 'If we find your Email in our system, you should receive shorlty an email with password reset instructions. Please check your spam folder!'
                return redirect(login)
            except Exception as e:
                if 'EMAIL_NOT_FOUND' in str(e):
                    print('Email was not found in Firebase')
                    post_top_message = "There is no account associated with this email address"
                    return redirect(login)
                else:
                    return redirect(login)

        else:
            print('Recovery form is not valid')
    else:
        pass
    return render(request, 'plotlyapp/recovery.html')
def login(request):
    global post_register_message, post_top_message, full_name
    authD.logout(request)
    if request.method == 'POST':
        form = forms.LoginForm(request.POST)
        if form.is_valid():
            Email = form.cleaned_data[
                'Email']  #the "Email" string needs to match to the name of the variable in the forms.py file (it gets the data from that file)
            pwd = form.cleaned_data[
                'pwd']  #the "pwd" string needs to match to the name of the variable in the forms.py file (it gets the data from that file)
            try:
                pyrebase_auth = pyrebase.auth()
                user = pyrebase_auth.sign_in_with_email_and_password(
                    Email, pwd)
                usuario = auth.get_user_by_email(Email)
                full_name = usuario.custom_claims.get(
                    'First_name') + ' ' + usuario.custom_claims.get(
                        'Last_name')

            except:
                return_message = 'Invalid login credentials. Try again.'
                return render(request, 'plotlyapp/login.html',
                              {'message': return_message})

            user_for_uid = auth.get_user_by_email(Email)
            account = firebase_admin.auth.get_user(user_for_uid.uid)
            if account.email_verified == True:
                session_id = user['idToken']
                request.session['uid'] = str(
                    session_id
                )  #Request session key for authentication in all pages
                if request.session.has_key(
                        'uid'):  #If it has key, send to main page
                    return redirect(welcome)
                else:
                    return render(request, 'plotlyapp/login.html')
            else:
                return_message = 'Please verify your email account address first'
                return render(request, 'plotlyapp/login.html',
                              {'message': return_message})
        else:
            print('Not a valid form')
    else:
        form = forms.LoginForm()
    if post_register_message == False and post_top_message == False:
        return render(request, 'plotlyapp/login.html')
    elif post_register_message != False and post_top_message == False:
        message = {'post_register_message': post_register_message}
        post_register_message = False
        return render(request, 'plotlyapp/login.html', message)
    elif post_register_message == False and post_top_message != False:
        message = {'post_register_message': post_top_message}
        post_top_message = False
        return render(request, 'plotlyapp/login.html', message)
    else:
        return render(request, 'plotlyapp/login.html')
Beispiel #3
0
def createUser(email, password, name):
    '''
    args:
      email: the email associated with the new account
      password: the password associated with the new account
      name: the name of the new account

    returns:
      res: {}
  '''
    res = {'userId': None, 'error': None, 'current_topping': 'default.png'}
    try:
        pyrebase_auth = pyrebase.auth()
        user = pyrebase_auth.create_user_with_email_and_password(
            email, password)
        user = pyrebase_auth.refresh(user['refreshToken'])
    except requests.exceptions.HTTPError as err:
        # Actual error message for data
        # errorDict = ast.literal_eval(err.strerror)
        # message = errorDict["error"]["message"]
        res['error'] = "An account with that email already exists. Please log in."
        return res

    userId = user['userId']
    res['userId'] = userId

    db = firestore.client()
    doc_ref = db.collection('users').document(userId)

    doc_ref.set({
        'userId':
        userId,
        'todos': [],
        'email':
        email,
        'name':
        name,
        'toppings': [
            'avocado', 'bananas', 'butter', 'strawberry', 'bacon', 'egg',
            'default'
        ],
        'current_topping':
        'default.png'
    })

    return res
Beispiel #4
0
def loginUser(email, password):
    '''
      args:
        email: email to login
        password: password to login

      returns:
        response: {"success": False, "message": None, "userId": None, "idToken": None, "refreshToken": None}}
    '''
    response = {
        "success": False,
        "message": None,
        "userId": None,
        "idToken": None,
        "refreshToken": None,
        "current_topping": None
    }
    pyrebase_auth = pyrebase.auth()

    try:
        user = pyrebase_auth.sign_in_with_email_and_password(email, password)
        user = pyrebase_auth.refresh(user['refreshToken'])
        userId = user['userId']
        idToken = user['idToken']
        refreshToken = user['refreshToken']

        response["success"] = True
        response["message"] = "Successfully authenticated."
        response['userId'] = userId
        response['idToken'] = idToken
        response['refreshToken'] = refreshToken
        response['current_topping'] = user['current_topping']
    except:
        response[
            "message"] = "Failed to authenticate. Either username or password is incorrect."
    return response
Beispiel #5
0
import os
from datetime import datetime


def noquote(s):
    return s


pyrebase.pyrebase.quote = noquote

#set up database
cred = credentials.Certificate("apiKey.json")
firebase_admin.initialize_app(cred)
pyrebase = pyrebase.initialize_app(json.load(open('dbconfig.json')))

auth = pyrebase.auth()
db = pyrebase.database()

DEBUG = True

app = Flask(__name__)
app.secret_key = os.urandom(24)
app.config.from_object(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'

# enable CORS
CORS(app, resources={r"/*": {"origins": "*"}})


#middleware for auth
def isAuthenticated(f):
def register(request):
    global post_register_message
    authD.logout(request)
    if request.method == 'POST':
        register_form = forms.RegisterForm(request.POST)
        if register_form.is_valid():
            first_name = register_form.cleaned_data['first_name']
            last_name = register_form.cleaned_data['last_name']
            display_name = first_name + " " + last_name
            Company = register_form.cleaned_data['Company']
            Email = register_form.cleaned_data['Email']
            pwd = register_form.cleaned_data['pwd']
            verify_pwd = register_form.cleaned_data['verify_pwd']

            if pwd != verify_pwd:
                return_message = "Passwords don't match. Try again."
                return render(request, 'plotlyapp/register.html',
                              {'message': return_message})
            else:
                pass

            if len(authorized_email_domains) == 0:
                try:
                    new_user = auth.create_user(email=Email,
                                                email_verified=False,
                                                password=pwd,
                                                display_name=display_name,
                                                disabled=False)
                    #new_user = auth.create_user(email='*****@*****.**', email_verified=False, phone_number='+15555550100',password='******',display_name='John Doe',photo_url='http://www.example.com/12345678/photo.png',disabled=False)
                    uid = new_user.uid
                    print('New user account has been created. ID: {0}'.format(
                        uid))
                    additional_claims = {
                        'First_name': first_name,
                        'Last_name': last_name,
                        'Company': Company,
                        'PremiumAccount': False
                    }
                    auth.set_custom_user_claims(uid, additional_claims)
                    pyrebase_auth = pyrebase.auth()
                    login_user = pyrebase_auth.sign_in_with_email_and_password(
                        Email, pwd)
                    # before the 1 hour expiry:
                    login_user = pyrebase_auth.refresh(
                        login_user['refreshToken'])
                    # now we have a fresh token
                    pyrebase_auth.send_email_verification(
                        login_user['idToken']
                    )  #We need iDToken to send email verification. I couln't get the ID token from the Firebase official python API, just from pyrebase (which the only reason it's here)
                    post_register_message = 'Account has been succcesfully created. Please verify your email address.'
                    authD.logout(request)
                    return redirect(login)

                except Exception as e:
                    if 'The user with the provided email already exists' in str(
                            e):
                        return_message = 'The user with the provided email already exists in our system.'
                    else:
                        return_message = str(e)
                    return render(request, 'plotlyapp/register.html',
                                  {'message': return_message})
            else:
                for domain in authorized_email_domains:
                    if domain in Email:
                        try:
                            new_user = auth.create_user(
                                email=Email,
                                email_verified=False,
                                password=pwd,
                                display_name=display_name,
                                disabled=False)
                            #new_user = auth.create_user(email='*****@*****.**', email_verified=False, phone_number='+15555550100',password='******',display_name='John Doe',photo_url='http://www.example.com/12345678/photo.png',disabled=False)
                            uid = new_user.uid
                            additional_claims = {
                                'First_name': first_name,
                                'Last_name': last_name,
                                'Company': Company,
                                'PremiumAccount': False
                            }
                            auth.set_custom_user_claims(uid, additional_claims)
                            pyrebase_auth = pyrebase.auth()
                            login_user = pyrebase_auth.sign_in_with_email_and_password(
                                Email, pwd)
                            # before the 1 hour expiry:
                            login_user = pyrebase_auth.refresh(
                                login_user['refreshToken'])
                            # now we have a fresh token
                            pyrebase_auth.send_email_verification(
                                login_user['idToken']
                            )  #We need iDToken to send email verification. I couln't get the ID token from the Firebase official python API, just from pyrebase (which the only reason it's here)
                            post_register_message = 'Account has been succcesfully created. Please verify your email address.'
                            authD.logout(request)
                            return redirect(login)

                        except Exception as e:
                            if 'The user with the provided email already exists' in str(
                                    e):
                                return_message = 'An account associated with this email address already exists.'
                            else:
                                return_message = str(e)
                            return render(request, 'plotlyapp/register.html',
                                          {'message': return_message})

                    else:
                        pass
                return_message = 'This organization has not been approved to create an account. Please contact support.'
                return render(request, 'plotlyapp/register.html',
                              {'message': return_message})

    else:
        return render(request, 'plotlyapp/register.html')