ElijahPaul

Experience

480

0 Best Reply Awards

  • Member Since 2 Years Ago
  • 0 Lessons Completed
  • 0 Favorites

11th July, 2018

ElijahPaul left a reply on Validate Form Served Via AJAX Call Using JQuery Validation • 1 week ago

I had to also re-initialise my jQuery validation plugin, but this worked great.

Thank you.

9th July, 2018

ElijahPaul left a reply on Laravel 5.5 - Redis Queue Logs • 1 week ago

No answer. :( Have since moved queues for this app to amazon SQS.

8th July, 2018

ElijahPaul started a new conversation Validate Form Served Via AJAX Call Using JQuery Validation • 2 weeks ago

can't seem to figure this one out.

I've configured my login form to submit via AJAX. My LoginController.php checks to see if the user has 2FA enabled, and if so pulls the form from the @section('content) section of the 2FA blade template and loads it (via AJAX) into the @section('content') section of the existing layout:

layouts/auth.blade.php

<html>
    <head>
        ...
    </head>
    <body>
        <div id="content">
            @yield('content')
        </div>
        <script src="{{ secure_asset('js/jquery.min.js') }}"></script>
        <script src="{{ secure_asset('js/jquery.validate.min.js') }}"></script>
        <script src="{{ secure_asset('js/login.js') }}"></script>
    </body>
</html>

login.blade.php

@extends('layouts.auth')

@section('content')
    <form id="loginForm" class="js-validation">
        <div class="form-group">
            <input id="email" name="email" type="email">
        </div>
        <div class="form-group">
            <input id="password" name="password" type="password">
        </div>
        <button id="login-submit-btn" class="btn"></button>
    </form>
@endsection

2fa.blade.php

@extends('layouts.auth')

@section('content')
    <form id="2faLoginForm" class="js-validation">
        <div class="form-group">
            <input id="passcode" type="tel" name="passcode">
        </div>
        <button id="submit-btn" class="btn"></button>
    </form>
@endsection

login.js

....
// login form jQuery
$(document).on('click', '#login-submit-btn', function (e) {
    e.preventDefault();
    if ($('.js-validation').valid()) {
        var formData;
        formData = $('#loginForm').serialize();
        var validator = $(".js-validation").validate();
        $.ajax({
            url: '/login',
            type: 'POST',
            data: formData,
            dataType: 'JSON',
            success: function(data) {
                console.log(data);
                if (data.intended) {
                    window.location.href = data.intended;
                } else {
                    $("#content").html(data.content);
                }
            },
            error: function(data){
                var errors = $.parseJSON(data.responseText).errors;
                if (errors.email) {
                    validator.showErrors({
                        "email": errors.email[0]
                    });
                }
                if (errors.password) {
                    validator.showErrors({
                        "password": errors.password[0]
                    });
                };
            }
        });
    }
})

// 2fa form jQuery
$(document).on('click', '#submit-btn', function (e) {
    e.preventDefault();
    if ($('.js-validation').valid()) {
        var validator = $(".js-validation").validate();
            $.ajax({
                url: "/login/2fa",
                type: 'POST',
                data: {
                    "_token": $('input[name="_token"]').val(),
                    "passcode": $('#passcode').val(),
                },
                error: function (data) {
                    var error;
                    var message;
                    if (data.responseJSON.errors) {
                        error = data.responseJSON.errors.passcode[0];
                        validator.showErrors({
                            "passcode": error
                        });
                    }
                },
                success: function (data) {
                    window.location.href = data.intended;
                }
            });
    }
});

LoginController.php

private function authenticated(Request $request, Authenticatable $user)
    {
        if ($request->ajax()) {
            if (!empty($user->google2faSecurity->google2fa_enable)) {
                Auth::logout();
                $request->session()->put('2fa:user:id', $user->id);
                $twoFactorLogin = view('login.2fa')->renderSections();
                return response()->json([
                    'content' => $twoFactorLogin['content'],
                ]);
            }
            return response()->json([
                'intended' => $this->redirectPath(),
            ]);
        }
    }

While jQuery Validate works with the initial loaded login.blade.php form, it doesn't with the AJAX served 2fa.blade.php form added to the DOM that replaces it. So no client side validation is performed on the newly displayed 2fa form.

How can I get jQuery validation to work on the AJAX served 2fa form?

After a fair bit of Googling (and tinkering) I've come up with nothing that works. :(

Thanks.

P.S. If I'm going about this all wrong or there are mistakes please do let me know.

16th June, 2018

ElijahPaul left a reply on Reload DIV • 1 month ago

Thanks.

I ended up having to change a bunch of other additional DIV's, so this method is a lot more efficient.

11th June, 2018

ElijahPaul started a new conversation Reload DIV • 1 month ago

I'm using the following button to launch a modal which allows the user to enable or disable 2FA in my app:

<div id="2fa-modal-btn">
@if(!empty(Auth::user()->google2fa_enabled))
    <button class="btn btn-danger" data-target=".2fa-modal" data-toggle="modal" type="button">Disable 2FA</button>
@else
    <button class="btn btn-primary" data-target=".2fa-modal" data-toggle="modal" type="button">Enable 2FA</button>
@endif
</div>

Once 2FA is enabled/disabled I reload the DIV using AJAX via its id like so:

$.ajax(
    {
        url: "/2fa/enable",
        type: 'GET',
        dataType: "JSON",
        data: {
            "verify-code": $('#verify-code').val(),
        },
        success: function (data)
        {
            console.log(data.success);            
            $("#2fa-modal-btn").load(location.href+" #2fa-modal-btn>*","");                                   
        }
    });

Is there a better/more efficient way of achieving this? I'm wondering if it may be better to change the class and text of the button rather than reload the DIV?

16th April, 2018

ElijahPaul left a reply on PostgreSQL Connection Via Environment Variables For Local And Production Environments. • 3 months ago

@Cronix I feel stupid for not thinking of that. So simple! Thank you.

ElijahPaul started a new conversation PostgreSQL Connection Via Environment Variables For Local And Production Environments. • 3 months ago

How would i configure the config/database.php file to account for an unsecured local PostgreSQL connection and a secure production one?

My current config:

'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'schema' => 'public',
            'sslmode' => 'prefer',
        ],

If I add the following to the database.php config file...

.....
'sslcert' => env('DB_SSLCERT', ''),
'sslkey' => env('DB_SSLKEY', ''),
'sslrootcert' => env('DB_SSLROOTCERT', ''),
.....

And set the environment variables (only in production)...

DB_SSLMODE=verify-full
DB_SSLCERT=/path/to/mycert.pem
DB_SSLKEY=/path/to/mykey.pem
DB_SSLROOTCERT=/path/to/myrootcert.pem

The local connection (without adding the corresponding environment variables) fails, but the production environment (with the variables set) connects successfully.

So how should i configure config/database.php to accommodate both local (unsecured) and production (secure) database connection requirements?

12th March, 2018

ElijahPaul started a new conversation Laravel 5.5 - Redis Queue Logs • 4 months ago

Are the Redis (4.0.8) logs below normal behaviour/expected? (My queues are processing normally)

1520861326.143064 [0 lua] "lpop" "queues:default"
1520861329.143602 [0 10.42.197.60:54104] "GET" "app_cache:illuminate:queue:restart"
1520861329.144294 [0 10.42.197.60:54104] "EVAL" "-- Get all of the jobs with an expired \"score\"...\nlocal val = redis.call('zrangebyscore', KEYS[1], '-inf', ARGV[1])\n\n-- If we have values in the array, we will remove them from the first queue\n-- and add them onto the destination queue in chunks of 100, which moves\n-- all of the appropriate jobs onto the destination queue very safely.\nif(next(val) ~= nil) then\n    redis.call('zremrangebyrank', KEYS[1], 0, #val - 1)\n\n    for i = 1, #val, 100 do\n        redis.call('rpush', KEYS[2], unpack(val, i, math.min(i+99, #val)))\n    end\nend\n\nreturn val" "2" "queues:default:delayed" "queues:default" "1520861329"
1520861329.144615 [0 lua] "zrangebyscore" "queues:default:delayed" "-inf" "1520861329"
1520861329.145030 [0 10.42.197.60:54104] "EVAL" "-- Get all of the jobs with an expired \"score\"...\nlocal val = redis.call('zrangebyscore', KEYS[1], '-inf', ARGV[1])\n\n-- If we have values in the array, we will remove them from the first queue\n-- and add them onto the destination queue in chunks of 100, which moves\n-- all of the appropriate jobs onto the destination queue very safely.\nif(next(val) ~= nil) then\n    redis.call('zremrangebyrank', KEYS[1], 0, #val - 1)\n\n    for i = 1, #val, 100 do\n        redis.call('rpush', KEYS[2], unpack(val, i, math.min(i+99, #val)))\n    end\nend\n\nreturn val" "2" "queues:default:reserved" "queues:default" "1520861329"
1520861329.145370 [0 lua] "zrangebyscore" "queues:default:reserved" "-inf" "1520861329"
1520861329.145913 [0 10.42.197.60:54104] "EVAL" "-- Pop the first job off of the queue...\nlocal job = redis.call('lpop', KEYS[1])\nlocal reserved = false\n\nif(job ~= false) then\n    -- Increment the attempt count and place job on the reserved queue...\n    reserved = cjson.decode(job)\n    reserved['attempts'] = reserved['attempts'] + 1\n    reserved = cjson.encode(reserved)\n    redis.call('zadd', KEYS[2], ARGV[1], reserved)\nend\n\nreturn {job, reserved}" "2" "queues:default" "queues:default:reserved" "1520861419"

23rd February, 2018

ElijahPaul left a reply on 'Method WhereBetween Does Not Exist' When Using Cached Query. • 4 months ago

@m-rk yeah, I'm slowly figuring that out.

The DB (postgres) has ≈ 20,000 records at the moment, and all the 'fiddling' I've done so far regarding caching + filtering has negatively impacted performance.

Overall query and filtering performance is actually pretty good as it is. So I may just leave this one alone for now.

Still learning, so I appreciate the input.

ElijahPaul left a reply on 'Method WhereBetween Does Not Exist' When Using Cached Query. • 4 months ago

@m-rk I believe you're right.

I don't think I will end up using this, but still wanted to understand why it wasn't working.

Looking at various ways of reducing DB queries and caching whatever possible (if it improves overall performance and scales of course).

ElijahPaul left a reply on 'Method WhereBetween Does Not Exist' When Using Cached Query. • 4 months ago

@tykus Awesome, thank you.

I need to read up on Collections again, the error seems so obvious now!

ElijahPaul started a new conversation 'Method WhereBetween Does Not Exist' When Using Cached Query. • 4 months ago

Still relatively new to Laravel (5.5) so I think I'm not understanding this correctly.

I'm caching a database query in Redis using the following:

$log = Cache::remember('log'.auth()->id(), 10, function () {
                return log::select(['id', 'clientip', 'token', 'timestamp'])->get();
            });

I want to perform a whereBetween on the cached result and have tried:

$logquery = Cache::get('log'.auth()->id());
$now = Carbon::now();
$to = Carbon::parse($request->get('daterange'));
$logrange = $logquery->whereBetween('timestamp', [$to,$now]);

But this fails with Method whereBetween does not exist in my json response.

What am I doing wrong/not understanding?

Any help appreciated.

31st January, 2018

ElijahPaul left a reply on Duplicate Queries., Different `where` Statements • 5 months ago

@wilburpowery Thanks, will check it out.

ElijahPaul started a new conversation Duplicate Queries., Different `where` Statements • 5 months ago

I'm using clone in the following to perform multiple queries with different where statements.

$query = DB1::whereIn('email',$verified_user_domains);

        $total_clean_count = (clone $query)->where('isspam',false)->count();

        $total_spam_count = (clone $query)->where('isspam',true)->count();

I intend to run a whole bunch of additional where statements and was wondering if there was a more efficient way of achieving this.

Thanks.

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.