# app/auth/views.py
import os
from flask import flash, redirect, render_template, url_for, request
from flask_login import login_required, login_user, logout_user, current_user
from . import auth
from .forms import (LoginForm, RegistrationForm,
                    RequestResetForm, ResetPasswordForm)
from .. import db, mail
from ..models import User
from flask_mail import Message
from werkzeug.security import generate_password_hash


@auth.route('/register/', methods=['GET', 'POST'])
def register():
    """
    Handle requests to the /register route
    Add an user to the database through the registration form
    """
    logout_user()
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(first_name=form.first_name.data,
                    last_name=form.last_name.data,
                    email=form.email.data,
                    username=form.username.data,
                    password=form.password.data,
                    is_freelancer=form.freelancer.data,
                    is_employer=form.employer.data)
        # add user to the database
        db.session.add(user)
        db.session.commit()
        flash(f'You have successfully registered! You may now login', 'success')

        # redirect to the login page

        return redirect(url_for('auth.login'))
    # load registration form
    return render_template('auth/register.html', form=form, title='Register')


@auth.route('/login/', methods=['GET', 'POST'])
def login():
    """
    Handle requests to the /login route
    Log an employee in through the login form
    """
    if current_user.is_authenticated:
        if current_user.is_freelancer == True and current_user.is_employer == False:
            # redirect to the freelancer dashboard page after login
            return redirect(url_for('freelancer.dashboard'))
        elif current_user.is_employer == True and current_user.is_freelancer == False:
            # redirect to the employer dashboard page after login
            return redirect(url_for('employer.dashboard'))
        elif current_user.is_employer and current_user.is_freelancer:
            # redirect to the employer dashboard page after login
            return redirect(url_for('employer.dashboard'))
        else:
            # redirect to the admin dashboard
            return redirect(url_for('admin.admin_dashboard'))

    form = LoginForm()
    if form.validate_on_submit():
        # check whether user exists in the database
        # the password entered matches the password in the database

        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user, remember=form.remember.data)
            #flash(f'Logged In', 'success')
            if user.is_freelancer == True and user.is_employer == False:
                # redirect to the freelancer dashboard page after login
                return redirect(url_for('freelancer.dashboard'))
            elif user.is_employer == True and user.is_freelancer == False:
                # redirect to the employer dashboard page after login
                return redirect(url_for('employer.dashboard'))
            elif user.is_employer and user.is_freelancer:
                # redirect to the employer dashboard page after login
                return redirect(url_for('employer.dashboard'))
            else:
                # redirect to the admin dashboard
                return redirect(url_for('admin.admin_dashboard'))
        flash(f'Invalid Credentials', 'danger')
    # load login template
    return render_template('auth/login.html', form=form, title='Login')


@auth.route('/logout/', methods=['GET', 'POST'])
@login_required
def logout():
    """
    Handle requests to the /logout route
    Log an employee out through the logout link
    """
    logout_user()
    flash(f'You have been logged out', 'success')
    # redirect to the login page
    return redirect(url_for('auth.login'))


def send_reset_email(user):
    
    try:
        token = user.get_reset_token()
        msg = Message('Password Reset Request',
                      sender='activecodar@gmail.com',
                      recipients=[user.email])
        msg.body = f''' To reset your password visit the following link
        {url_for('auth.reset_password', token=token, _external=True)}

        If you did not make this request ignore this email
        '''
        mail.send(msg)
        
    except Exception as e:
        print(e)


@auth.route('/reset-password', methods=['GET', 'POST'])
def request_reset():
    if current_user.is_authenticated:
        next_page = request.args.get('next')
        if current_user.is_freelancer == True and current_user.is_employer == False:
            # redirect to the freelancer dashboard page after login
            return redirect(next_page) if next_page else redirect(url_for('freelancer.dashboard'))
        elif current_user.is_employer == True and current_user.is_freelancer == False:
            # redirect to the employer dashboard page after login
            return redirect(next_page) if next_page else redirect(url_for('employer.dashboard'))
        elif current_user.is_employer and current_user.is_freelancer:
            # redirect to the employer dashboard page after login
            return redirect(next_page) if next_page else redirect(url_for('employer.dashboard'))
        else:
            # redirect to the admin dashboard
            return redirect(next_page) if next_page else redirect(url_for('admin.admin_dashboard'))
    form = RequestResetForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        send_reset_email(user)
        flash(f'Email has been sent with password reset instructions', 'info')
        return redirect(url_for('auth.login'))
    return render_template('auth/reset_request.html', form=form, title='Request Reset Password')


@auth.route('/reset-password/<token>', methods=['GET', 'POST'])
def reset_password(token):
    if current_user.is_authenticated:
        next_page = request.args.get('next')
        if current_user.is_freelancer == True and current_user.is_employer == False:
            # redirect to the freelancer dashboard page after login
            return redirect(next_page) if next_page else redirect(url_for('freelancer.dashboard'))
        elif current_user.is_employer == True and current_user.is_freelancer == False:
            # redirect to the employer dashboard page after login
            return redirect(next_page) if next_page else redirect(url_for('employer.dashboard'))
        elif current_user.is_employer and current_user.is_freelancer:
            # redirect to the employer dashboard page after login
            return redirect(next_page) if next_page else redirect(url_for('employer.dashboard'))
        else:
            # redirect to the admin dashboard
            return redirect(next_page) if next_page else redirect(url_for('admin.admin_dashboard'))

    user = User.verify_reset_token(token)

    if user is None:
        flash(f'Invalid token or expired token', 'warning')
        return redirect(url_for('auth.request_reset'))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        # add user to the database
        hashed_password = generate_password_hash(form.password.data)
        user.password_hash = hashed_password
        db.session.commit()
        flash(
            f'Your password has been reset successfully! You may now login', 'success')
        return redirect(url_for('auth.login'))
    return render_template('auth/reset_password.html', form=form, title='Reset Password')

[((630, 643), 'flask_login.logout_user', 'logout_user', ([], {}), '()\n', (641, 643), False, 'from flask_login import login_required, login_user, logout_user, current_user\n'), ((1360, 1426), 'flask.render_template', 'render_template', (['"""auth/register.html"""'], {'form': 'form', 'title': '"""Register"""'}), "('auth/register.html', form=form, title='Register')\n", (1375, 1426), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((3623, 3683), 'flask.render_template', 'render_template', (['"""auth/login.html"""'], {'form': 'form', 'title': '"""Login"""'}), "('auth/login.html', form=form, title='Login')\n", (3638, 3683), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((3874, 3887), 'flask_login.logout_user', 'logout_user', ([], {}), '()\n', (3885, 3887), False, 'from flask_login import login_required, login_user, logout_user, current_user\n'), ((3892, 3937), 'flask.flash', 'flash', (['f"""You have been logged out"""', '"""success"""'], {}), "(f'You have been logged out', 'success')\n", (3897, 3937), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((5892, 5982), 'flask.render_template', 'render_template', (['"""auth/reset_request.html"""'], {'form': 'form', 'title': '"""Request Reset Password"""'}), "('auth/reset_request.html', form=form, title=\n    'Request Reset Password')\n", (5907, 5982), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((7632, 7710), 'flask.render_template', 'render_template', (['"""auth/reset_password.html"""'], {'form': 'form', 'title': '"""Reset Password"""'}), "('auth/reset_password.html', form=form, title='Reset Password')\n", (7647, 7710), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((1161, 1233), 'flask.flash', 'flash', (['f"""You have successfully registered! You may now login"""', '"""success"""'], {}), "(f'You have successfully registered! You may now login', 'success')\n", (1166, 1233), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((3546, 3585), 'flask.flash', 'flash', (['f"""Invalid Credentials"""', '"""danger"""'], {}), "(f'Invalid Credentials', 'danger')\n", (3551, 3585), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((3991, 4012), 'flask.url_for', 'url_for', (['"""auth.login"""'], {}), "('auth.login')\n", (3998, 4012), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((4111, 4205), 'flask_mail.Message', 'Message', (['"""Password Reset Request"""'], {'sender': '"""activecodar@gmail.com"""', 'recipients': '[user.email]'}), "('Password Reset Request', sender='activecodar@gmail.com',\n    recipients=[user.email])\n", (4118, 4205), False, 'from flask_mail import Message\n'), ((4673, 4697), 'flask.request.args.get', 'request.args.get', (['"""next"""'], {}), "('next')\n", (4689, 4697), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((5763, 5833), 'flask.flash', 'flash', (['f"""Email has been sent with password reset instructions"""', '"""info"""'], {}), "(f'Email has been sent with password reset instructions', 'info')\n", (5768, 5833), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((6129, 6153), 'flask.request.args.get', 'request.args.get', (['"""next"""'], {}), "('next')\n", (6145, 6153), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((7122, 7173), 'flask.flash', 'flash', (['f"""Invalid token or expired token"""', '"""warning"""'], {}), "(f'Invalid token or expired token', 'warning')\n", (7127, 7173), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((7355, 7397), 'werkzeug.security.generate_password_hash', 'generate_password_hash', (['form.password.data'], {}), '(form.password.data)\n', (7377, 7397), False, 'from werkzeug.security import generate_password_hash\n'), ((7479, 7564), 'flask.flash', 'flash', (['f"""Your password has been reset successfully! You may now login"""', '"""success"""'], {}), "(f'Your password has been reset successfully! You may now login',\n    'success')\n", (7484, 7564), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((1297, 1318), 'flask.url_for', 'url_for', (['"""auth.login"""'], {}), "('auth.login')\n", (1304, 1318), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((2705, 2750), 'flask_login.login_user', 'login_user', (['user'], {'remember': 'form.remember.data'}), '(user, remember=form.remember.data)\n', (2715, 2750), False, 'from flask_login import login_required, login_user, logout_user, current_user\n'), ((5858, 5879), 'flask.url_for', 'url_for', (['"""auth.login"""'], {}), "('auth.login')\n", (5865, 5879), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((7198, 7227), 'flask.url_for', 'url_for', (['"""auth.request_reset"""'], {}), "('auth.request_reset')\n", (7205, 7227), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((7598, 7619), 'flask.url_for', 'url_for', (['"""auth.login"""'], {}), "('auth.login')\n", (7605, 7619), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((1811, 1842), 'flask.url_for', 'url_for', (['"""freelancer.dashboard"""'], {}), "('freelancer.dashboard')\n", (1818, 1842), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((4347, 4406), 'flask.url_for', 'url_for', (['"""auth.reset_password"""'], {'token': 'token', '_external': '(True)'}), "('auth.reset_password', token=token, _external=True)\n", (4354, 4406), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((4870, 4889), 'flask.redirect', 'redirect', (['next_page'], {}), '(next_page)\n', (4878, 4889), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((6326, 6345), 'flask.redirect', 'redirect', (['next_page'], {}), '(next_page)\n', (6334, 6345), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((2025, 2054), 'flask.url_for', 'url_for', (['"""employer.dashboard"""'], {}), "('employer.dashboard')\n", (2032, 2054), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((2972, 3003), 'flask.url_for', 'url_for', (['"""freelancer.dashboard"""'], {}), "('freelancer.dashboard')\n", (2979, 3003), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((4917, 4948), 'flask.url_for', 'url_for', (['"""freelancer.dashboard"""'], {}), "('freelancer.dashboard')\n", (4924, 4948), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((5122, 5141), 'flask.redirect', 'redirect', (['next_page'], {}), '(next_page)\n', (5130, 5141), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((6373, 6404), 'flask.url_for', 'url_for', (['"""freelancer.dashboard"""'], {}), "('freelancer.dashboard')\n", (6380, 6404), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((6578, 6597), 'flask.redirect', 'redirect', (['next_page'], {}), '(next_page)\n', (6586, 6597), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((2220, 2249), 'flask.url_for', 'url_for', (['"""employer.dashboard"""'], {}), "('employer.dashboard')\n", (2227, 2249), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((2339, 2371), 'flask.url_for', 'url_for', (['"""admin.admin_dashboard"""'], {}), "('admin.admin_dashboard')\n", (2346, 2371), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((3182, 3211), 'flask.url_for', 'url_for', (['"""employer.dashboard"""'], {}), "('employer.dashboard')\n", (3189, 3211), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((5169, 5198), 'flask.url_for', 'url_for', (['"""employer.dashboard"""'], {}), "('employer.dashboard')\n", (5176, 5198), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((5355, 5374), 'flask.redirect', 'redirect', (['next_page'], {}), '(next_page)\n', (5363, 5374), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((5512, 5531), 'flask.redirect', 'redirect', (['next_page'], {}), '(next_page)\n', (5520, 5531), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((6625, 6654), 'flask.url_for', 'url_for', (['"""employer.dashboard"""'], {}), "('employer.dashboard')\n", (6632, 6654), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((6811, 6830), 'flask.redirect', 'redirect', (['next_page'], {}), '(next_page)\n', (6819, 6830), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((6968, 6987), 'flask.redirect', 'redirect', (['next_page'], {}), '(next_page)\n', (6976, 6987), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((3373, 3402), 'flask.url_for', 'url_for', (['"""employer.dashboard"""'], {}), "('employer.dashboard')\n", (3380, 3402), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((3504, 3536), 'flask.url_for', 'url_for', (['"""admin.admin_dashboard"""'], {}), "('admin.admin_dashboard')\n", (3511, 3536), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((5402, 5431), 'flask.url_for', 'url_for', (['"""employer.dashboard"""'], {}), "('employer.dashboard')\n", (5409, 5431), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((5559, 5591), 'flask.url_for', 'url_for', (['"""admin.admin_dashboard"""'], {}), "('admin.admin_dashboard')\n", (5566, 5591), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((6858, 6887), 'flask.url_for', 'url_for', (['"""employer.dashboard"""'], {}), "('employer.dashboard')\n", (6865, 6887), False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((7015, 7047), 'flask.url_for', 'url_for', (['"""admin.admin_dashboard"""'], {}), "('admin.admin_dashboard')\n", (7022, 7047), False, 'from flask import flash, redirect, render_template, url_for, request\n')]