Violation of the security policy in nodeJS - node.js

I'm trying to learn NodeJS and I am at the session part ( see if a user is logged in or not )
I wrote a code stating that IF HE IS logged in, it shows a page and IF HE IS NOT, it shows another one :
app.get('/home', function(request, response) {
// If the user is loggedin
if (request.session.loggedin) {
// show the home page of logged users
response.sendFile(path.join(__dirname+'/views/loggedin/index.html'));
} else {
// Not logged in
response.send('Please login to view this page! login');
}
//response.end();
});
It works properly except ONE LITTLE THING. It doesn't want to load the scripts.
It is the exact same code at the home page but it doesn't allow me to load it.
The console errors
HTML :
<html>
<head>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</head>
<body p-0 m-0>
<div id="header"></div>
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine#v2.x.x/dist/alpine.min.js" defer></script>
<div class="w-full text-gray-700 dark:text-gray-200 dark:bg-gray-900">
<div class="w-full grid place-items-center text-5xl h-screen">GACHA GAME IN NODEJS
</div>
<div class="container" align="center">
</div> <!-- container -->
</body>
</html>
<script>
$("#header").load("navbar");
</script>

The error that you provided says that was not able to load the scripts due the Content Security Policy, So i think you should set the content security policy with any external script:
app.get('/home', function(request, response) {
// If the user is loggedin
if (request.session.loggedin) {
response.sendFile(path.join(__dirname+'/views/loggedin/index.html'));
} else {
// setting the header here
res.set({"Content-Security-Policy": "script-src-elem self https://cdn.jsdelivr.net/gh/alpinejs/alpine#v2.x.x/dist/alpine.min.js https://code.jquery.com/jquery-3.6.0.min.js https://cdn.tailwindcss.com;"})
response.send('Please login to view this page! login');
}
});
or you can add a meta tag in your html file as well, see this question. But be aware with this approach because it can allow XSS attacks.

Related

Node.JS :How to forward to the login page with parameter?

I am building the login function with node.js, express,express-session, ejs.
This is the log-in page (i.e. index.ejs)
<html>
<head>
<meta charset="UTF-8">
<title>Video Chat Room</title>
<link rel="stylesheet" type="text/css" href="/css/style.css">
<style>
#message
{
color:red;
font-weight: bold;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$( document ).ready(function() {
var messageBox=document.getElementById("message");
<%
if (typeof errorField!="undefined") {
switch (errorField) {
case "email":%>
messageBox.innerHTML="Your email address has been used by another user, please use another one.";
document.getElementById("email").focus();
<% break;
case "logoutSuccess":%>
messageBox.innerHTML="<%=alias%> has successfully logged out.";
<% break;
}
}
%>
});
</script>
</head>
<body>
<form method="post" action="/login">
Nick name/Alias:<input type=text required name="alias" value="<%=((typeof user=='undefined')?'':user.alias)%>"><br>
Email Address:<input type=email id="email" required name="email" value="<%=((typeof user=='undefined')?'':user.email)%>"><br>
<input type="submit" value="Login">
</form>
<div id="message">
</div>
</body>
</html>
Here is the server-side code(i.e. server.js)
........
app.get('/',function (req,res) {
res.render('../ejs/index.ejs');
});
app.post('/login', function(req, res) {
var alias = req.body.alias;
var email = req.body.email;
var user=require("./classes/user.js");
user.alias=alias;
user.email=email;
if (user.login) {
req.session.user = user;
res.redirect('/home/');
} else {
res.locals.errorField="email";
res.locals.user=user;
res.render('../ejs/index.ejs');
}
It works fine, however, when the login process failed, although the web output the login page(i.e. index.ejs), the browser address bar still stay in "/login"; is it possible to change the browser address bar to "/" and the index.ejs can read the errorField and user value also?
If you want a user login error to go back to /, then you need to do res.redirect("/"). If you want to add some parameters to that page that can be used either in server-side rendering or client-side rendering, then the simplest way to do that is to add query parameters:
res.redirect("/?error=email")
Then, either your server-side rendering or some client-side Javascript can pick up that query parameter and display something like a message in the page that explains what happened.
There are lots of ways to do something like this. Here's a partial list:
Send data in a query parameter that server-side rendering picks up and adds some explanatory text to the page.
Send data in a query parameter that client-side Javascript picks up and adds some explanatory text to the page.
Set a cookie that contains an error message that your server-side rendering will pick upon the redirect and then clear the cookie.
Set some error data in the user session object on the server that your server-side rendering will pick up when rendering the redirected page and the clean that info from the session.
Use an Express middleware module built for these temporary messages called flash.
Render an error page from the server (without an immediate redirect) and then have a client-driven redirect back to "/" that occurs after a few seconds time. The client-driven redirect can either be from a <meta> tag or can be client-side Javascript on a timer.

SweetAlert2 is not working in node.js

I'm making website for db study.
I wanted to alert to user if user didn't input id and password in register page.
So I installed sweetalert2 by npm. But sweetalert2 doesn't work in route.js which connect user's ask and server.
var swal = require('sweetalert2');
router.post('/register', function(req, res){
if(!req.body.id && !req.body.password){
swal('WARNING','You must input both id and password!','error')
}
else{
swal('COMPLETE','You registered your information!','success');
res.redirect('/');
}
})
How can I fix it?
I used .ejs file to use sweetalert2.
<!DOCTYPE html>
<html>
<head>
<% include ../pages/head %>
</head>
<body>
<% if(fail) { %>
<% include ../partials/alert_login %>
<% } %>
<% include ../pages/login %>
</body>
</html>
in login_connect.ejs includes when user fail login alert_login.ejs file and alert_login.ejs includes script tag of using swal of sweetalert2 module.
But It isn't work. What is the problem?
alert_login.ejs is below.
<script type="text/javascript">
alert("You are not our member!");
</script>

Multiple Layouts in Ember.js?

Coming from a Rails background, you can have multiple Layouts - for say, anonymous user pages and then authenticated pages.
Is this possible with Ember?
I've tried declaring a new templateName in my UsersRouter, with no avail.
I've also checked this guide: http://emberjs.com/guides/views/adding-layouts-to-views/
But it doesn't seem to be working :/
You can use {{render}} inside an if helper to show different layouts.
For instance if you have an ApplicationController that has login and logout action handlers, and a corresponding `loggedIn' property.
App.ApplicationController = Ember.Controller.extend({
loggedIn: false,
login: function() {
this.set('loggedIn', true);
},
logout: function() {
this.set('loggedIn', false);
}
});
The you can bind to the loggedIn property inside the application template like so.
<script type='text/x-handlebars' data-template-name='application'>
<button {{action login }}>Login</button>
<button {{action logout }}>Logout</button>
{{#if loggedIn}}
{{render 'user'}}
{{else}}
{{render 'guest'}}
{{/if}}
</script>
Where user and guest are corresponding templates.
<script type='text/x-handlebars' data-template-name='user'>
<h1>User layout</h1>
<div class='box user'>
{{outlet}}
</div>
</script>
<script type='text/x-handlebars' data-template-name='guest'>
<h1>Guest layout</h1>
<div class='box guest'>
{{outlet}}
</div>
</script>
Here's a working jsbin.
Edit: To not use the application route based on some static criteria or loaded via model hooks, you can override the renderTemplate method of the ApplicationRoute.
App.ApplicationRoute = Ember.Route.extend({
renderTemplate: function() {
var loggedIn = false;
if (loggedIn) {
this.render('user');
} else {
this.render('guest');
}
}
});

Fancy box popup is not working

I created a web application where it needs to popup images and videos from Fancy boxes called rippolls. Here my "Rippolls" are load in popup boxes and users can vote for those rippolls.
My question is, in one page I listed all rippolls and when I click on a rippoll with an image or video it is loaded withour fancy box and fancy box css.
I have referenced
<script src="../../Content/Scripts/jquery.fancybox-1.3.4.pack.js" type="text/javascript"></script>
<link href="../../Content/Styles/jquery.fancybox-1.3.4.css" rel="stylesheet" type="text/css" />
in a _layout.cshtml where is referenced to the _RippollList.chtml page.
Code in the _RippollList.chtml is :
$("a.btnVotePop#(poll.Id)").fancybox({
'onComplete' : function() {
alert('hello');
try {
FB.XFBML.parse();
twttr.widgets.load();
history.pushState({}, "#poll.Name.Trim()", "/polls/#poll.Id");
document.getElementsByTagName("title")[0].innerHTML = "#poll.Name.Trim()";
//history.replaceState({}, "title", "#poll.Name.Trim()");
//$("#rippoll_image_path").attr("content", $("#polltitle").val());
}
catch (ex) {
alert('Error parsing response.');
}
},
'onClosed' : function(){
alert("closed");
try {
history.pushState({}, "Rippoll", "/home/mypage");
document.getElementsByTagName("title")[0].innerHTML = "My Page";
$('#divDetailCont').css('display', 'none');
}
catch (ex) {
}
},
ajax : {
type : "GET"
},
'width': '560px'
});
Html :
<div id="videoDeftImgContainer" class="videoDefultImg">
<a class="btnVotePop#(poll.Id)" href="RippollCardPopup/#(poll.Id)">
<img class="inImgSize" src="#poll.ImagePath" />
</a>
<div id="plyBtnClk" class="playBtn" onclick="">
<a class="btnVotePop#(poll.Id)" href="RippollCardPopup/#(poll.Id)">
<img src="../../Content/images/newImages/hoverPlay.png" />
</a></div></div>
script references:
<script src="../../Content/Scripts/jquery.fancybox-1.3.4.pack.js" type="text/javascript"></script>
<link href="../../Content/Styles/jquery.fancybox-1.3.4.css" rel="stylesheet" type="text/css" />
but still I m getting a page without fancybox and its styles.
I am in a doubt of because I am putting some text values to rippoll( ex: rippoll name, rippoll question etc..) and it may having some special characters(#%$#{}) also, and is it the reason for not open rippolls in the fancy box.
Help me out for this. please post if any code segments where you successed.

google oAuth - how can i get data. C#.net

I am a new to OAuth.
I just doing some work on that.
I have done following code. but the problem is that it opens the new window and then redirect in to the same window, it is not coming on the browser window from which (parent) it calls.
Also, can anyone tell me how can i get UserName and Email of Gmail account in to my application.
My sample code is........
<form id="form1" runat="server">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
google.load("identitytoolkit", "1.0", { packages: ["ac"] }); </script> <script type="text/javascript">
$(function () {
window.google.identitytoolkit.setConfig({
developerKey: "AIzaSyAj99p8A9p5ay9E89jRHKuYZRrN3fSWp90",
companyName: "tatvasoft",
callbackUrl: "http://localhost:51749/Logins/Result.aspx",
realm: "",
userStatusUrl: "http://localhost:51749/Logins/Login.aspx",
loginUrl: "http://localhost:51749/Logins/Login.aspx",
signupUrl: "http://localhost:51749/Logins/Result.aspx",
homeUrl: "http://localhost:51749/Logins/Default.aspx",
logoutUrl: "http://localhost:51749/Logins/Default.aspx",
language: "en",
idps: ["Gmail", "Hotmail"],
tryFederatedFirst: true,
useCachedUserStatus: false
});
$("#navbar").accountChooser();
});
this should get you started
http://havethunk.wordpress.com/2011/08/10/google-identity-toolkit-asp-net-mvc3/
The important part is what's on your page at:
http://localhost:51749/Logins/Result.aspx
You need to have some javascript to reload the parent page, or handle the log in action in the parent window. Something like the following will work:
<html>
<head>
<script type='text/javascript'>
function notify() {
window.opener.location.reload();
// or you could use a redirect:
// window.opener.location = "/"
window.close();
}
</script>
</head>
<body onload='notify();'>
</body>
</html>
If you are looking for a full guide for implementing Google Identity Toolkit in MVC3, I would follow the link Ali suggests: http://havethunk.wordpress.com/2011/08/10/google-identity-toolkit-asp-net-mvc3/
Alternatively, just follow the documentation on the GITKit website: http://code.google.com/apis/identitytoolkit/v1/getting_started.html

Resources