Handle user authentication.

    If requested over GET, present login page.
    If requested over POST, log user in.

    :param str status: Status of previous request/login attempt

def login():
    """Handle user authentication.

    If requested over GET, present login page.
    If requested over POST, log user in.

    :param str status: Status of previous request/login attempt
    """
    alert = None
    alert_status = 'danger'
    code = 200
    captcha = app.config['COIL_LOGIN_CAPTCHA']
    form = LoginForm()
    if request.method == 'POST':
        if form.validate():
            user = find_user_by_name(request.form['username'])
            if not user:
                alert = 'Invalid credentials.'
                code = 401
            if captcha['enabled']:
                r = requests.post('https://www.google.com/recaptcha/api/siteverify',
                                  data={'secret': captcha['secret_key'],
                                        'response': request.form['g-recaptcha-response'],
                                        'remoteip': request.remote_addr})
                if r.status_code != 200:
                    alert = 'Cannot check CAPTCHA response.'
                    code = 500
                else:
                    rj = r.json()
                    if not rj['success']:
                        alert = 'Invalid CAPTCHA response. Please try again.'
                        code = 401
            if code == 200:
                try:
                    pwd_ok = check_password(user.password,
                                            request.form['password'])
                except ValueError:
                    if user.password.startswith('$2a$12'):
                        # old bcrypt hash
                        pwd_ok = check_old_password(user.password,
                                                    request.form['password'])
                        if pwd_ok:
                            user.password = password_hash(
                                request.form['password'])
                            write_user(user)
                    else:
                        pwd_ok = False

                if pwd_ok and user.is_active:
                    login_user(user, remember=('remember' in request.form))
                    return redirect(url_for('index'))
                else:
                    alert = "Invalid credentials."
                    code = 401

        else:
            alert = 'Invalid credentials.'
            code = 401
    else:
        if request.args.get('status') == 'unauthorized':
            alert = 'Please log in to access this page.'
        elif request.args.get('status') == 'logout':
            alert = 'Logged out successfully.'
            alert_status = 'success'
    return render('coil_login.tmpl', {'title': 'Login', 'alert': alert, 'form':
                                      form, 'alert_status': alert_status,
                                      'pwdchange_skip': True,
                                      'captcha': captcha},
                  code)