'Overrides Web2Py\'s login() to use custom flash styles & utcnow
@return: a login form'

def login(self, next=DEFAULT, onvalidation=DEFAULT, onaccept=DEFAULT, log=DEFAULT, inline=False, lost_pw_link=None, register_link=True):

    T = current.T
    db = current.db
    messages = self.messages
    request = current.request
    response = current.response
    session = current.session
    settings = self.settings
    deployment_settings = current.deployment_settings
    utable = settings.table_user
    userfield = settings.login_userfield
    old_requires = utable[userfield].requires
    utable[userfield].requires = [IS_NOT_EMPTY(), IS_LOWER()]
    passfield = settings.password_field
    try:
        utable[passfield].requires[(-1)].min_length = 0
    except:
        pass
    if (next is DEFAULT):
        next = (request.vars._next or settings.login_next)
    if (onvalidation is DEFAULT):
        onvalidation = settings.login_onvalidation
    if (onaccept is DEFAULT):
        onaccept = settings.login_onaccept
    if (log is DEFAULT):
        log = messages.login_log
    user = None
    response.title = T('Login')
    if (settings.login_form == self):
        if inline:
            formstyle = deployment_settings.get_ui_inline_formstyle()
        else:
            formstyle = deployment_settings.get_ui_formstyle()
        buttons = []
        self_registration = deployment_settings.get_security_registration_visible()
        if (self_registration and register_link):
            if (self_registration == 'index'):
                controller = 'index'
            else:
                controller = 'user'
            register_link = A(T('Register    for    Account'), _href=URL(f=controller, args='register'), _id='register-btn', _class='action-lnk')
            buttons.append(register_link)
        if (lost_pw_link is None):
            lost_pw_link = deployment_settings.get_auth_password_changes()
        if lost_pw_link:
            lost_pw_link = A(T('Lost    Password'), _href=URL(f='user', args='retrieve_password'), _class='action-lnk')
            buttons.append(lost_pw_link)
        submit_button = INPUT(_type='submit', _value=T('Login'))
        buttons.insert(0, submit_button)
        form = SQLFORM(utable, fields=[userfield, passfield], hidden=dict(_next=request.vars._next), showid=settings.showid, submit_button=T('Login'), delete_label=messages.delete_label, formstyle=formstyle, separator=settings.label_separator, buttons=buttons)
        form.add_class('auth_login')
        if settings.remember_me_form:
            s3_addrow(form, '', DIV(INPUT(_type='checkbox', _class='checkbox', _id='auth_user_remember', _name='remember'), LABEL(messages.label_remember_me, _for='auth_user_remember')), '', formstyle, 'auth_user_remember__row')
        if deployment_settings.get_auth_set_presence_on_login():
            s3_addrow(form, '', INPUT(_id='auth_user_clientlocation', _name='auth_user_clientlocation', _style='display:none'), '', formstyle, 'auth_user_client_location')
            response.s3.jquery_ready.append("S3.getClientLocation($('#auth_user_clientlocation'))")
        captcha = (settings.login_captcha or ((settings.login_captcha != False) and settings.captcha))
        if captcha:
            s3_addrow(form, captcha.label, captcha, captcha.comment, formstyle, 'captcha__row')
        accepted_form = False
        if form.accepts(request.post_vars, session, formname='login', dbio=False, onvalidation=onvalidation):
            accepted_form = True
            if (userfield == 'email'):
                gmail_domains = deployment_settings.get_auth_gmail_domains()
                office365_domains = deployment_settings.get_auth_office365_domains()
                if (gmail_domains or office365_domains):
                    from gluon.contrib.login_methods.email_auth import email_auth
                    domain = form.vars[userfield].split('@')[1]
                    if (domain in gmail_domains):
                        settings.login_methods.append(email_auth('smtp.gmail.com:587', ('@%s' % domain)))
                    elif (domain in office365_domains):
                        settings.login_methods.append(email_auth('smtp.office365.com:587', ('@%s' % domain)))
            query = (utable[userfield] == form.vars[userfield])
            user = db(query).select(limitby=(0, 1)).first()
            if user:
                temp_user = user
                if (temp_user.registration_key == 'pending'):
                    response.warning = deployment_settings.get_auth_registration_pending()
                    return form
                elif (temp_user.registration_key in ('disabled', 'blocked')):
                    response.error = messages.login_disabled
                    return form
                elif ((not (temp_user.registration_key is None)) and temp_user.registration_key.strip()):
                    response.warning = messages.registration_verifying
                    return form
                user = None
                for login_method in settings.login_methods:
                    if ((login_method != self) and login_method(request.vars[userfield], request.vars[passfield])):
                        if (not (self in settings.login_methods)):
                            form.vars[passfield] = None
                        user = self.get_or_create_user(form.vars)
                        break
                if (not user):
                    if (settings.login_methods[0] == self):
                        if (temp_user[passfield] == form.vars.get(passfield, '')):
                            user = temp_user
            elif (not settings.alternate_requires_registration):
                for login_method in settings.login_methods:
                    if ((login_method != self) and login_method(request.vars[userfield], request.vars[passfield])):
                        if (not (self in settings.login_methods)):
                            form.vars[passfield] = None
                        register_onaccept = settings.register_onaccept
                        if register_onaccept:
                            settings.register_onaccept = [self.s3_register_onaccept, register_onaccept]
                        else:
                            settings.register_onaccept = self.s3_register_onaccept
                        user = self.get_or_create_user(form.vars)
                        break
            if (not user):
                self.log_event(settings.login_failed_log, request.post_vars)
                session.error = messages.invalid_login
                if inline:
                    next_url = URL(args=request.args, vars=request.get_vars)
                else:
                    next_url = self.url(args=request.args, vars=request.get_vars)
                redirect(next_url)
    else:
        cas = settings.login_form
        cas_user = cas.get_user()
        if cas_user:
            cas_user[passfield] = None
            register_onaccept = settings.register_onaccept
            if register_onaccept:
                settings.register_onaccept = [self.s3_register_onaccept, register_onaccept]
            else:
                settings.register_onaccept = self.s3_register_onaccept
            user = self.get_or_create_user(utable._filter_fields(cas_user))
        elif hasattr(cas, 'login_form'):
            return cas.login_form()
        else:
            next = ('%s?_next=%s' % (URL(r=request), next))
            redirect(cas.login_url(next))
    if user:
        user = Storage(utable._filter_fields(user, id=True))
        self.login_user(user)
    if (log and self.user):
        self.log_event(log, self.user)
    if (settings.login_form == self):
        if accepted_form:
            if onaccept:
                onaccept(form)
            if isinstance(next, (list, tuple)):
                next = next[0]
            if (next and (not (next[0] == '/')) and (next[:4] != 'http')):
                next = self.url(next.replace('[id]', str(form.vars.id)))
            redirect(next)
        utable[userfield].requires = old_requires
        return form
    else:
        redirect(next)
