How to run a script when a user authenticates Laravel? - javascript

I would like to know how to run a function when a user authenticates,
This is my function for log
public function redirectPath()
{
if (Auth::user()->hasRole('admin')){
$bitacora = TblBitacora::create([
'accion' => 'Inicio de SesiĆ³n Admin Exitoso',
'user_id' => Auth::id(),
'ip' => \Request::ip(),
]);
return '/';
}
}
I would like to run this script
#if(Auth::user()->??????????????????????????????????????????
<script>
$(function() {
$('#mostrarmodal').modal('show');
});
</script>
#endif

Laravel has Authentication Directives
The #auth and #guest directives may be used to quickly determine if
the current user is authenticated or is a guest:
#auth
// The user is authenticated...
#endauth
#guest
// The user is not authenticated...
#endguest
More information available at https://laravel.com/docs/5.8/blade
Also I wouldn't recommend to log in redirectPath method in your controller. You can use events, an similar to what you want to achieve is provided as an example on Laravel docs. https://laravel.com/docs/5.7/events#event-subscribers

First Question Answer :
You can check is user login in your blade file and add javascript or something like this in your view file :
#if(\Auth::check())
<script>
$(function() {
$('#mostrarmodal').modal('show');
});
</script>
#endif
If Authenticate user is an Admin
#if (auth()->check())
#if (auth()->user()->Admin())
// Put your js files here
#else
// this is for others role
#endif
#endif
Second Question Answer :
If you want to run a function if user is authenticate then you can do it like that :
public function check() {
if(Auth::check()){
$this->secondFunc(); // This will run if user is authenticate.
}
else{
return redirect('auth/login');
}
}
public function secondFunc() {
echo "This is second function";
}

You can use JS localStorage to help you to do it:
#if(\Auth::check())
<script>
if (localStorage.getItem('already_connected') !== '1') {
$('#mostrarmodal').modal('show');
localStorage.setItem('already_connected', 1);
}
</script>
#endif
Now, if you refresh the page, unless you clear localStorage data, it will not show
run this function again.
Hope it helps.

Related

Store username in array from login to server

I have a small Go web-server that displays data to users as they login. The problem I'm trying to achieve is to have the web-page only show certain information when a specific user logs in. For example, when admin logs in there would be a list of admin-only items that they can see on the web-page.
The problem I'm having is for some reason my Go code isn't storing the username in the array that I'm calling, so when I pass it over to the JavaScript it is blank.
Here are the 3 main parts of the code that I'm struggling with:
main.go
package main
import "fmt"
func authHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
usernameArray, hasUsername := r.PostForm["j_username"]
//This line added for debugging purposes
log.Println("username:", usernameArray[0])
if hasUsername {
fmt.Fprintf(w, "%s", usernameArray[0])
}
}
func main() {
http.HandleFunc("/getAuth", authHandler)
}
javascript.js
Note that this is AngularJS
$scope.init = function() {
checkAuthentication();
};
checkAuthentication = function() {
$http.get("/getAuth").then(
function(response) {
var username = response.data;
console.log(username): //Added for debugging purposes
if (username === "admin") {
$scope.showAdminOnlyItems = true;
}
});
}
main.html
<div id="admin-only-items" ng-show="showAdminOnlyItems">
<hr style="border:1px solid">
<p style="text-align: center">admin only: </p>
<div id="adminOnlyButtom">
<button class="button" data-ng-click="doSomething()">Do something</button>
</div>
</div>
Again, I only want that div to show up when admin logs in, and Go needs to send the username over to the javascript to verify that. By adding the debugging line in Go and starting the server up, I get this:
2018/11/19 16:28:42 http: panic serving 10.240.49.238:59621: runtime error:
index out of range
goroutine 26 [running]:
net/http.(*conn).serve.func1(0xc42009f720)
C:/Go/src/net/http/server.go:1726 +0xd0
panic(0x79f820, 0xe17940)
C:/Go/src/runtime/panic.go:502 +0x229
main.authHandler(0xc56220, 0xc420135180, 0xc4207a3500)
D:/src/main.go:346 +0x1d8
So it's clear that the usernameArray is empty, not sure what I did wrong. Can anyone help tell me why the usernameArray is empty in authHandler?
The first, I can see that you send GET request to server without j_username query param therefore you can not read j_username on server side.
The second, usernameArray is empty slice which is failing while parse j_username. Error index out of range occur when you try to call usernameArray[0].
You should send GET request with j_username like that /getAuth?j_username=admin and modify code from server.
usernameArray, hasUsername := r.URL.Query()["j_username"]
//This line added for debugging purposes
log.Println("debug here :", usernameArray)
if hasUsername {
fmt.Fprintf(w, "%s", usernameArray[0])
return
}
// Send an error message to client
http.Error(w, `missing username`, 500)

how to create an alert prompt in the controller before redirecting to a new view?

is it possible to create an alert prompt in the controller before redirecting to a new view? i want to make the users acknowledge a message in the current view before directing them to the next view
using System.Web.Mvc;
using System.Web.Security;
using MvcApplication.Models;
[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (!this.ModelState.IsValid)
{
return this.View(model);
}
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
***// Here! create an alert with a close button using javascript and make the user acknowledge it by clicking a button and closing the alert before redirecting the user***
if (this.Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return this.Redirect(returnUrl);
}
return this.RedirectToAction("Index", "Home");
}
this.ModelState.AddModelError(string.Empty, "The user name or password provided is incorrect.");
return this.View(model);
}
Return from that method some View with the message, with a link and/or an auto-redirect.
It's not possible to "pause" the processing of the controllers to send messages back to the user!!
Make a custom ActionFilter and put this action filter on Controller's Action
public class CustomActionFilter : System.Web.Mvc.ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.Controller.ViewBag.StartupScript = "Your Message Goes here";
base.OnActionExecuted(filterContext);
}
}
Your javascript code on _Layout page as below
<script type="text/javascript" defer="defer">
alert('#Html.Raw(ViewBag.StartupScript)');
</script>
You controller Action
[CustomActionFilter]
public ActionResult Helo(
{
//Some Stuff here
}
Yes it possible to show (javascript)alert box from controller.
Just add below line to your controller.
Try with this it may help you.
return JavaScript(alert("Hello this is an alert"));
You can add it by using ViewBag in MVC. You could put your javascript code in a ViewBag like:
ViewBag.Javascript = "<script language='javascript' type='text/javascript'>alert('Your message');</script>";
and then navigate to your page.

Binding data into localStorage with ngStorage - what's wrong here?

I started this journey trying to get some settings to persist with localStorage, has some problems and posted about it here (without a solution): Why won't this data bind? An odd case in Angularjs
I've abandoned that method as I learnt about ngStorage. In theory ngStorage lets you 2-way bind into and out of Angular models. It's a great, great theory.
I'm having problems with it though. It half works.
The ideas is this:
Test for permission selection (true or false).
If no selection (first time use) pop-up a choice.
Store the choice.
On restart use the stored choice to set the permission true or false.
Allow user to change the permission from within the app.
It works up to number 4.
Testing shows that although on first use I can set $storage.analytics to true or false subsequent changes are not being stored and retrieved from local storage.
Here is the code:
permissionCallback = function(permission){
if(permission===1){
console.log("analytics allowed");
analytics.startTrackerWithId('UA-45544004-1');
$scope.$storage.analytics=true;
navigator.notification.alert('You can turn analytics off in the Data Tracking section at any time.', null, 'Analytics On', 'OK');
}else{
console.log("analytics denied");
$scope.$storage.analytics=false;
navigator.notification.alert('You can turn analytics on in the Data Tracking section at any time.',null , 'Analytics Off', 'OK');
}
}
if(typeof $scope.$storage.analytics === 'undefined'){
navigator.notification.confirm('This app would like your permission to collect data on how you use the app. No personal or user identifiable data will be collected.', permissionCallback, 'Attention', ['Allow','Deny']);
}
else{
console.log('start analytics are', $scope.$storage.analytics);
if(typeof analytics !== 'undefined'){
console.log("analytics functioning");
analytics.startTrackerWithId('UA-45544004-1');
$scope.trackClick = function(category, action){
analytics.trackEvent(category, action);
console.log('Tracking category: ' + category + ', Section: ' + action + '.');
}
}
}
$scope.counter = 0;
$scope.change = function(){
$scope.counter++;
console.log('analytics are ' + $scope.$storage.analytics);
}
And here is the html.
<li class="item item-toggle">
<i class="icon ion-cloud"></i> Data Tracking is {{$storage.analytics}} {{counter}}
<label class="toggle toggle-balanced">
<input type="checkbox" ng-model="$storage.analytics" ng-change="change()">
<div class="track">
<div class="handle"></div>
</div>
</label>
</li>
It's either a fault with my logic or, and I think this more likely, a misunderstanding about the scope of the data.
The odd thing is the console log in the change() function (which is purely for tracking these things) is always correct. So using $storage.analytics in the html is the correct way to do it (using $scope.storage.analytics causes all sorts of errors) and it is indeed binding from the html into $scope.storage.analytics.
So why isn't it saving it to local storage when using the toggle?
I ran into a similar problem with ng-storage. When the page was loaded/reloaded anything bound to a value in $sessionStorage was updated correctly. However any changes to $sessionStorage afterwards were not reflected in my view. What I ended up doing was creating a service for storing changes and using $sessionStorage as a temporary data store.
app.controller('TestController', funciton($scope, $sessionStorage, Service) {
// if we have session data set our service
if($sessionStorage.data) {
Service.data = $sessionStorage.data;
} else {
$sessionStorage.data = {};
}
// now bind scope to service
scope.data = Service.data;
// on update we set both Service and $sessionStorage
// scope.data will be automatically updated
scope.update = function(val) {
Service.data.value = val;
$sessionStorage.data.value = val;
}
});
app.service('TestService', function() {
var service = {
data: {
value: 'Hello World'
}
};
return service;
});
<div ng-controller="TestController">{{data.value}}</div>
<button ng-click-"update('Hello Universe')">Update</button>
This is a very rudimentary example of how my solution works but hopefully it gets anyone else stuck in the same situation on the right track.

How to remove the item in session using javascript for codeigniter?

I am working on a shopping cart php(codeigniter) project. So I have add the item in the session like the code following. The problem is, I would like to remove the item in session in the checkout page.
But of course I can not call the php function to remove the session in javascript , that means , when the remove button is click , how can I do (not restrict to use ajax, simple is the best), I can remove the item in session ? Thanks
if ($this->form_validation->run()) {
if ($this->session->userdata('purchase') !== false)
$purchase_list = $this->session->userdata('purchase');
else
$purchase_list = array();
$purchase = array(
'id' => $product[0]['id'],
'quantity' => $this->input->post('quantity')
);
if ($this->input->post('opt1') !== false)
$purchase['opt1'] = $this->input->post('opt1');
if ($this->input->post('opt2') !== false)
$purchase['opt2'] = $this->input->post('opt2');
array_push($purchase_list, $purchase);
$this->session->set_userdata('purchase', $purchase_list);
redirect('cart');
}
You can define a function in your controller to unset the session e.g.
class Controllername extends CI_Controller {
function index(){}
function reset_session(){
$sesion_variable = 'name_of_session';
$this->session->unset_userdata($session_variable);
}
}
And you can call that via CURL or ajax. On checkout page
from CodeIgniter's session class documentation
This assumes you understand your cart and will know where to actually unset session data in your checkout scenery.
you can set the value of desired item in your session using this syntax:
$this->session->set_userdata('purchase', null); // will set the purchase session data to null
you only know which key to set to null though

give two function in one button in Yii framework

I have a question about Yii framework, i have problem with submit button, i want to given two fungsi save and update in one submit button, can anyone tell me how to set that function on form ?
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
i change 'Save' with 'Update' it's still have error Primary key added, how i can create two function update and save in one push button ?
public function actionCreate()
{
$model=new TblUasUts;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['TblUasUts']))
{
$model->attributes=$_POST['TblUasUts'];
if($model->save())
$this->redirect(array('view','id'=>$model->nim_mhs));
}
if(isset($_POST['TblUasUts'])
{
$model->attributes=$_POST['TblUasUts'];
if($model->update())
$this->redirect(array('view','id'=>$model->nim_mhs));
}
$this->render('update',array(
'model'=>$model,
));
}
In your form, you can use something like :
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Update'); ?>
</div>
As far as processing different actions on the backend code, there are a few options, for example, you could :-
Direct your form to different URLs
Set a (hidden) field (for example ID) and parse for that.
Use the default action from the activeForm, which directs back to the invoking action, for example actionCreate(), or actionUpdate()
In light of your updates, please extend your controller as per my initial suggestion to have another action actionUpdate()
The main difference between the actionCreate(), or actionUpdate() actions is that the Create action create a new (empty) TblUasUts object, while the Update action populates the TblUasUts object from the database.
public function actionCreate()
{
$model=new TblUasUts;
...
... Do things with $model ...
...
$model->save();
}
public function actionUpdate
{
// The id of the existing entry is passed in the url. for example
// ...http:// .... /update/id/10
//
$model = TblUasUts::model()->findByPK($_GET['id']);
...
... Do things with $model ...
...
$model->save();
}

Categories